Helper class for generating a MeshBVH for a given geometry in asynchronously in a worker. The
geometry position and index arrays are copied to the Worker so the geometry can still be read
while the BVH is being generated, and the reordered index is written back to the geometry's
original index array when it finishes. If transferBuffers is set the array ArrayBuffers are
transferred instead, meaning the geometry will be unavailable to use while the BVH is being
processed unless SharedArrayBuffers are used. They will be automatically replaced when the
MeshBVH is finished generating.
If the worker module can't be loaded, such as when the library is loaded from a CDN on another origin or the worker can't resolve the "three" import, a pre-bundled copy of the worker script with three.js included is loaded through a blob url instead.
import { AmbientLight, DirectionalLight, Mesh, MeshStandardMaterial, TorusKnotGeometry } from 'three';
import { BVHHelper } from 'three-mesh-bvh';
import { GenerateMeshBVHWorker } from 'three-mesh-bvh/worker';
// scene, camera and renderer are initialized here
const light = new DirectionalLight( 0xffffff, 3 );
light.position.set( 1, 1, 1 );
scene.add( light, new AmbientLight( 0xb0bec5, 1.5 ) );
const geometry = new TorusKnotGeometry( 1, 0.3, 500, 500 );
const worker = new GenerateMeshBVHWorker();
geometry.boundsTree = await worker.generate( geometry );
const mesh = new Mesh( geometry, new MeshStandardMaterial( { color: 0x4db6ac, roughness: 0.75 } ) );
const helper = new BVHHelper( mesh, 10 );
scene.add( mesh, helper );On this page
Properties
running: boolean
Flag indicating whether or not a BVH is already being generated in the worker.
Methods
generate(
geometry: BufferGeometry,
// Same options accepted by the `MeshBVH` constructor.
options?: {
// Callback invoked with a `[0, 1]` progress value as the BVH is built.
onProgress?: function,
// If true the position and index `ArrayBuffers` are transferred to the worker rather than copied, avoiding the copy but leaving the geometry unusable until the build finishes. Any other attribute stored in the same `ArrayBuffer` is detached as well. Ignored with a warning for an interleaved position attribute or a `range`.
transferBuffers: boolean = false
}
): Promise<MeshBVH>Generates a MeshBVH instance for the given geometry with the given options in a WebWorker.
Returns a Promise that resolves with the generated MeshBVH. Throws if already running.
By default the geometry can still be read during the build, but its position and index
arrays must not be modified until the promise resolves.
dispose(): voidTerminates the worker.