# Bounding box error

**URL:** <https://forum.babylonjs.com/t/bounding-box-error/51631>\
**Category:** Bugs\
**Created:** [June 27, 2024, 8:44am UTC](https://forum.babylonjs.com/t/bounding-box-error/51631 "2024-06-27T08:44:54Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![Rohith\_K](https://sea2.discourse-cdn.com/flex024/user_avatar/forum.babylonjs.com/rohith_k/32/40623_2.png) [@Rohith\_K](https://forum.babylonjs.com/u/Rohith_K)\
**Post date:** [June 27, 2024, 8:44am UTC](https://forum.babylonjs.com/t/bounding-box-error/51631/1 "2024-06-27T08:44:54Z")

</div>

HI I HAVE CREATED A BOUNDING BOX FOR MY BABYLON SCENE AND I GOT THE BOUNDING BOX BIGGER THAN MY SCENE

IN THE SAME WAY I CREATED A BOUNDING BOX USING THREE JS AND IT IS IN THE CORRECT WAY

 ![BABYLON OUTPUT](https://us1.discourse-cdn.com/flex024/uploads/babylonjs/original/3X/b/4/b42ee056c5a774ee581e94dd4b6f32164764d769.png)  
 ![THREE JS OUTPUT](https://us1.discourse-cdn.com/flex024/uploads/babylonjs/original/3X/3/8/38f2fda3cc2c294bc94f9e14065b208a7bbee3f5.png)

CAN ANYONE HELP ME

---

<div class="post-metadata">

**Author:** ![CrashMaster](https://sea2.discourse-cdn.com/flex024/user_avatar/forum.babylonjs.com/crashmaster/32/23662_2.png) [@CrashMaster](https://forum.babylonjs.com/u/CrashMaster)\
**Post date:** [June 27, 2024, 9:24am UTC](https://forum.babylonjs.com/t/bounding-box-error/51631/2 "2024-06-27T09:24:35Z")

</div>

WHY ARE WE SCREAMING?

Anyway did you try calling `computeWorldMatrix` on your object?

---

<div class="post-metadata">

**Author:** ![RaananW](https://sea2.discourse-cdn.com/flex024/user_avatar/forum.babylonjs.com/raananw/32/28955_2.png) [@RaananW](https://forum.babylonjs.com/u/RaananW)\
**Post date:** [June 27, 2024, 9:58am UTC](https://forum.babylonjs.com/t/bounding-box-error/51631/3 "2024-06-27T09:58:20Z")

</div>

Would also be interesting to see the model or see a reproduction, because how would we know why it doesn’t work if we can’t see it not working?

---

<div class="post-metadata">

**Author:** ![Rohith\_K](https://sea2.discourse-cdn.com/flex024/user_avatar/forum.babylonjs.com/rohith_k/32/40623_2.png) [@Rohith\_K](https://forum.babylonjs.com/u/Rohith_K)\
**Post date:** [June 27, 2024, 10:14am UTC](https://forum.babylonjs.com/t/bounding-box-error/51631/4 "2024-06-27T10:14:26Z")

</div>

Should i post my git link or paste my code here

```auto
import React, { useRef, useEffect, useState } from 'react';
import * as BABYLON from '@babylonjs/core';
import '@babylonjs/loaders'; // Ensure loaders are included for external assets
import { openDatabase, addScene, getScene, clearDatabase } from './database';

const BabylonViewer = () => {
  const canvasRef = useRef(null);
  const [scene, setScene] = useState(null);
  const [engine, setEngine] = useState(null);
  const [boundingBoxes, setBoundingBoxes] = useState([]); // State for storing bounding boxes

  useEffect(() => {
    // Clear the database on refresh
    clearDatabase();

    // Open the IndexedDB and initialize Babylon.js engine and scene
    openDatabase().then(() => {
      const engine = new BABYLON.Engine(canvasRef.current, true);
      const scene = new BABYLON.Scene(engine);

      // Set up the camera
      const camera = new BABYLON.ArcRotateCamera("camera", 0, 0, 10, new BABYLON.Vector3(0, 0, 0), scene);
      camera.setPosition(new BABYLON.Vector3(0, 0, -10));
      camera.attachControl(canvasRef.current, true);

      // Set up the light
      new BABYLON.HemisphericLight('light', new BABYLON.Vector3(0, 1, 0), scene);

      // Start the render loop
      engine.runRenderLoop(() => {
        scene.render();
      });

      // Handle window resize
      window.addEventListener('resize', () => {
        engine.resize();
      });

      // Set state
      setScene(scene);
      setEngine(engine);

      // Clean up on unmount
      return () => {
        window.removeEventListener('resize', () => {
          engine.resize();
        });
        scene.dispose();
        engine.dispose();
      };
    });
  }, []);

  const handleFileChange = (event) => {
    const files = event.target.files;

    Array.from(files).forEach(file => {
      const reader = new FileReader();
      reader.onload = async () => {
        const data = reader.result;
        const sceneData = { name: file.name, data: data };

        // Store scene data in IndexedDB and wait for completion
        const sceneId = await addScene(sceneData);
        console.log(`Scene added with ID: ${sceneId}`);

        // Load the scene from DB after storing
        const sceneDataFromDB = await getScene(sceneId);
        if (sceneDataFromDB) {
          BABYLON.SceneLoader.Append('', sceneDataFromDB.data, scene, (loadedScene) => {
            let minVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
            let maxVector = new BABYLON.Vector3(-Number.MIN_VALUE, -Number.MIN_VALUE, -Number.MIN_VALUE);

            // Calculate bounding box for each mesh and update cumulative bounding box
            loadedScene.meshes.forEach(mesh => {
              const boundingInfo = mesh.getBoundingInfo();
              const boundingBox = boundingInfo.boundingBox;
              console.log(`Bounding Box for mesh ${mesh.name}:`, boundingBox);

              minVector = BABYLON.Vector3.Minimize(minVector, boundingBox.minimumWorld);
              maxVector = BABYLON.Vector3.Maximize(maxVector, boundingBox.maximumWorld);
            });

            const cumulativeBoundingBox = new BABYLON.BoundingBox(minVector, maxVector);
            console.log('Cumulative Bounding Box:', cumulativeBoundingBox);

            // Store the cumulative bounding box in state
            setBoundingBoxes(prevBoundingBoxes => [...prevBoundingBoxes, cumulativeBoundingBox]);

            // Create a cube based on the cumulative bounding box
            const boundingBoxSize = maxVector.subtract(minVector);
            const boundingBoxCenter = minVector.add(boundingBoxSize.scale(0.5));

            const box = BABYLON.MeshBuilder.CreateBox("boundingBox", {
              height: boundingBoxSize.y,
              width: boundingBoxSize.x,
              depth: boundingBoxSize.z
            }, scene);

            box.position = boundingBoxCenter;
            box.isVisible = true; // Make sure the box is visible

            // Add material to the box for better visibility
            const boxMaterial = new BABYLON.StandardMaterial("boxMaterial", scene);
            boxMaterial.wireframe = true; // Show as wireframe
            boxMaterial.emissiveColor = new BABYLON.Color3(0, 1, 0); // Green color
            box.material = boxMaterial;

            // Adjust camera to focus on the loaded scene
            if (scene.activeCamera) {
              scene.activeCamera.attachControl(canvasRef.current, true);
            }
          });
        }
      };
      reader.readAsDataURL(file);
    });
  };

  return (
    <div>
      <input
        type="file"
        multiple
        accept=".babylon,.gltf,.glb"
        onChange={handleFileChange}
      />
      <canvas ref={canvasRef} style={{ width: '100%', height: 'calc(100vh - 40px)' }} />
      <div>
        <h3>Cumulative Bounding Boxes</h3>
        <ul>
          {boundingBoxes.map((box, index) => (
            <li key={index}>
              Min: ({box.minimum.x.toFixed(2)}, {box.minimum.y.toFixed(2)}, {box.minimum.z.toFixed(2)}), 
              Max: ({box.maximum.x.toFixed(2)}, {box.maximum.y.toFixed(2)}, {box.maximum.z.toFixed(2)})
            </li>
          ))}
        </ul>
      </div>
    </div>
  );
};

export default BabylonViewer;

```

---

<div class="post-metadata">

**Author:** ![RaananW](https://sea2.discourse-cdn.com/flex024/user_avatar/forum.babylonjs.com/raananw/32/28955_2.png) [@RaananW](https://forum.babylonjs.com/u/RaananW)\
**Post date:** [June 27, 2024, 10:48am UTC](https://forum.babylonjs.com/t/bounding-box-error/51631/5 "2024-06-27T10:48:04Z")

</div>

~~are you using the babylon viewer deliberately? If you are initializing the engine and the scene, there is no need to use the viewer package.~~ sorry, misread the code. Ignore that! 🙂 However:

If you can reproduce this in the playground, it would be the best - [playground.babylonjs.com](http://playground.babylonjs.com)

---

<div class="post-metadata">

**Author:** ![Rohith\_K](https://sea2.discourse-cdn.com/flex024/user_avatar/forum.babylonjs.com/rohith_k/32/40623_2.png) [@Rohith\_K](https://forum.babylonjs.com/u/Rohith_K)\
**Post date:** [June 28, 2024, 9:30am UTC](https://forum.babylonjs.com/t/bounding-box-error/51631/6 "2024-06-28T09:30:25Z")

</div>

**Implementing an octree structure for fast raycasting and occlusion culling in Babylon.js**  
That’s ok,  
The bounding box error has fixed  
Now i need to create octree ,Means i have created a bounding box for my entire scene.Now i need to divide the box into 8 parts(octree implementation) and so on …  
so i can optimize my large scene

---

<div class="post-metadata">

**Author:** ![roland](https://sea2.discourse-cdn.com/flex024/user_avatar/forum.babylonjs.com/roland/32/38940_2.png) [@roland](https://forum.babylonjs.com/u/roland)\
**Post date:** [July 3, 2024, 11:18am UTC](https://forum.babylonjs.com/t/bounding-box-error/51631/7 "2024-07-03T11:18:52Z")

</div>

FYI:

[https://doc.babylonjs.com/features/featuresDeepDive/scene/optimizeOctrees](https://doc.babylonjs.com/features/featuresDeepDive/scene/optimizeOctrees)

To inspire you (Bounding Volume Hierarchy (BVH) with YUKA

> **[Yuka | Examples](https://mugen87.github.io/yuka/examples/)**
>
> A JavaScript library for developing Game AI

[https://mugen87.github.io/yuka/examples/math/bvh/](https://mugen87.github.io/yuka/examples/math/bvh/)
