Is there a way to initialise BVH boundsTree before doing the first raycast?

I would like to initialise boundstree on my objects before the first raycast is performed is there any way to do so?

Hi Martin, yes—you can force BVH (BoundsTree) initialization ahead of the first raycast. If you’re using the three‐mesh‐bvh integration (which Needle Engine leverages for accelerated raycasting, as hinted by the raycast options in the physics types at engine_physics.d.ts.md), you can explicitly compute the BVH by calling the geometry’s computeBoundsTree() method as soon as your mesh is loaded.

For example, you can create a Needle Engine component that, in its awake() method, calls computeBoundsTree() on your mesh’s geometry:


import { Behaviour, serializable } from “@needle-tools/engine”;
import { Mesh } from “three”;
// Make sure you have installed and imported three-mesh-bvh if necessary
// import { MeshBVH } from “three-mesh-bvh”;

export class BVHInitializer extends Behaviour {
// Reference your mesh (assign in Unity or via your editor)
@serializable(Mesh)
mesh?: Mesh;

awake() {
if (this.mesh && this.mesh.geometry) {
// Precompute the BVH boundsTree so that raycasts later will be faster.
this.mesh.geometry.computeBoundsTree();
console.log(“BVH initialized for”, this.mesh.name);
}
}
}

By calling computeBoundsTree() early (for example in awake()), you ensure that the heavy lifting happens upfront rather than during the first raycast, avoiding any lag later on. This approach is especially useful if your BVH would otherwise be computed lazily when a raycast is first performed.

If you have additional questions about integrating BVH initialization into your project or need help with specific performance aspects, feel free to ask.

1 replies left - Become PRO for more replies.
thread_Ym5ouGPndITW4hTwk2KgSrlf
Reply to this post directly if you need further help (bottom right button)