v0.10.0
three-mesh-bvh
A long-standing & still growing spatial query system for three.js trusted for fast and accurate spatial queries. Used for accelerating raycasting, collision detection, and spatial queries with BVH-based acceleration structures.
performancegame devphysics
import { AmbientLight, BufferAttribute, DirectionalLight, Mesh, MeshStandardMaterial, Raycaster, Sphere, TorusKnotGeometry, Vector2 } from 'three';
import { MeshBVH, acceleratedRaycast, INTERSECTED, NOT_INTERSECTED } from 'three-mesh-bvh';
// scene, camera and renderer are initialized here
const light = new DirectionalLight( 0xffffff, 1.5 );
light.position.set( 1, 1, 1 );
scene.add( light, new AmbientLight( 0xffffff, 1.2 ) );
// a torus knot of over half a million triangles, every vertex white to start
const geometry = new TorusKnotGeometry( 1, 0.4, 800, 400 ).toNonIndexed();
const colors = new BufferAttribute( new Float32Array( geometry.attributes.position.count * 3 ).fill( 1 ), 3 );
geometry.setAttribute( 'color', colors );
geometry.boundsTree = new MeshBVH( geometry );
const mesh = new Mesh( geometry, new MeshStandardMaterial( { vertexColors: true, roughness: 0.3 } ) );
mesh.raycast = acceleratedRaycast;
scene.add( mesh );
// hovering paints every triangle within a sphere around the point under the pointer
const raycaster = new Raycaster();
raycaster.firstHitOnly = true;
const pointer = new Vector2();
const hits = [];
const brush = new Sphere( undefined, 0.2 );
const paint = {
intersectsBounds: box => brush.intersectsBox( box ) ? INTERSECTED : NOT_INTERSECTED,
intersectsTriangle: ( triangle, index ) => {
if ( ! triangle.intersectsSphere( brush ) ) return;
for ( let i = 3 * index; i < 3 * index + 3; i ++ ) {
colors.setXYZ( geometry.index.getX( i ), 0.93, 0.25, 0.48 );
}
},
};
window.addEventListener( 'pointermove', e => {
pointer.set( e.clientX / window.innerWidth * 2 - 1, - e.clientY / window.innerHeight * 2 + 1 );
raycaster.setFromCamera( pointer, camera );
hits.length = 0;
raycaster.intersectObject( mesh, false, hits );
if ( ! hits.length ) return;
brush.center.copy( hits[ 0 ].point );
geometry.boundsTree.shapecast( paint );
colors.needsUpdate = true;
} );Install
npm install three-mesh-bvhChangelog
0.10.0
Added
- GenerateMeshBVHWorker, ParallelMeshBVHWorker: Fall back to a pre-bundled copy of the worker script, loaded through a blob url, when the worker module fails to load, such as when the library is loaded from a CDN. Jobs are sent once the worker has loaded so a failed load no longer leaves the geometry buffers detached.
- "REVISION" export with the package version, with a "-dev" suffix outside of published builds, and a "window.THREE_MESH_BVH" global set to it so pages using the library can be detected, with a warning when multiple copies are loaded.
- BVHHelper: "displayChildBVHs" option to also display the BVHs of the objects in an ObjectBVH.
- BVHComputeData: "oct16", "2x16float" and "4x16float" packed attribute types for octahedral encoded normals and tangents and half float uvs and colors.
- BVH: The "strategy" option can be a function that picks the split for each node, for custom split heuristics.
- BVHComputeData: "attributeLayout" with the packed vertex stride and the offset and size of each attribute.
- BVHComputeData: "getObjectInfo" and "getAllObjectInfo" functions returning an object's mesh, instance, group, index, geometry offsets and triangle range in the packed buffers.
- BVHComputeData: "fns.getVertex" and "fns.getVertexPosition" functions to read a vertex from the packed attributes.
- GenerateMeshBVHWorker, ParallelMeshBVHWorker: Support for interleaved position attributes.
Changed
- GenerateMeshBVHWorker: The position and index are copied to the worker by default so the geometry stays usable during the build. Set the new "transferBuffers" option to transfer them instead, as before.
- ParallelMeshBVHWorker: The geometry's position and index arrays are no longer replaced by a build.
- GenerateMeshBVHWorker, ParallelMeshBVHWorker: With the "range" option only the triangles and vertices in the range are copied, and separate ranges of a geometry can be built at the same time.
- ndcToCameraRay: Takes "( ndc, cameraToWorld, inverseProjection )" instead of "( ndc, inverseModelViewProjection )", keeping the ray precise when the camera is far from the origin.
- MeshBVH: "bvhcast" passes the triangle indices of the geometry to "intersectsTriangles" when using "indirect", so they must no longer be passed to "resolveTriangleIndex".
- BVHComputeData: Automatically generated BVHs are built with the "SAH" strategy, for faster GPU traversal.
- BVHComputeData: "update" is now async and awaits "getBVH" for every object, replacing "updateAsync".
- BVHComputeData: "getShapecastFn" "transformShapeFn" must return a bool, whether to traverse the object, so an object can be skipped.
- BVHComputeData: "writeObjectRecord", "getBVH" and "getDefaultAttributeValue" are now public so subclasses can override them. The class API is still unstable and may change in future releases.
- BVHComputeData: Renamed "storage.transforms" to "storage.objects", "structs.transform" to "structs.objectRecord", "transformStruct" to "objectRecordStruct" and "writeTransformData" to "writeObjectRecord".
- BVHComputeData: Geometry attributes are copied directly from the backing arrays when packing, making "update" several times faster on large scenes.
- BVHComputeData: The index and attributes are packed into one storage buffer, freeing a binding. "storage.index" and "storage.attributes" are removed, read triangle indices with the new "fns.getTriangleIndices" instead.
- BVHComputeData: The index and attributes are packed in one block per geometry, with triangle and vertex indices relative to it. "getTriangleIndices" takes the geometry's index offset and "getVertex", "getVertexPosition" and "sampleTrianglePoint" its attributes offset as a last argument, read from the object's record in "storage.objects". "intersectRangeFn" callbacks receive both offsets after the count.
Removed
- Deprecated "maxLeafTris" and "maxLeafSize" options. Use "targetLeafSize" instead.
- Deprecated "MeshBVHHelper" class and "MeshBVHOptions" type. Use "BVHHelper" and "BVHOptions" instead.
- Deprecated WebGPU WGSL functions from "bvh_ray_functions", "common_functions" and "distance_functions". Use "BVHComputeData" instead.
Fixed
- ParallelMeshBVHWorker: A build that throws now rejects instead of never settling and blocking later builds.
- Workers: A failed build no longer also logs an unhandled promise rejection when the caller handles it.
- Workers: Builds no longer copy the triangle bounds to every parallel worker, or the index and nodes before returning them.
- BVH: "shiftPrimitiveOffsets" no longer wraps the offsets of an indirect BVH when they don't fit in 16 bits.
- BVHComputeData: "update" now throws when the BVH is deeper than the traversal stack.
- BVHComputeData: Passing a MeshBVH no longer throws in "update".
- BVHComputeData: A BatchedMesh with no "boundsTrees" or with deleted instances no longer throws in "update".
- OrientedBox: "distanceToBox" throwing when targets are passed and the boxes intersect.
- BVHHelper: Fixed throwing for a BatchedMesh on recent three.js versions.
- PointsBVH, LineSegmentsBVH: The raycast threshold uses the object's world scale on three.js r188 and up, to match three.js.
- ParallelMeshBVHWorker: Builds now respect the geometry's draw range, as MeshBVH does.
- ParallelMeshBVHWorker: A position attribute that is a view into a larger buffer no longer adds the rest of that buffer as extra vertices.
- BVHComputeData: Attributes other than "vec4f" are no longer read from the wrong offset.
0.9.18
Added
- BVHComputeData: "raycastAnyHit" function that ends traversal at the first hit, for shadow and occlusion rays.
- BVHComputeData: "getShapecastFn" range callbacks can return "STOP_TRAVERSAL" to end the traversal early.
Fixed
- BVHComputeData: "raycastFirstHit" no longer misses bounds for axis-parallel rays that lie on a bounds face.
- BVHHelper: No longer generates infinite positions for a BVH with empty bounds, such as one built from an empty geometry.
0.9.17
Added
- BVHComputeData: "updateAsync" so a "getBVH" override can build BVHs asynchronously.
Changed
- SAH builds are faster: 8 bins per axis and an exact sweep for small nodes.
- BVH builds write nodes directly into the packed buffer instead of an intermediate node tree, using a fraction of the memory.
Fixed
- MeshBVH: Raycasts no longer test triangles when the ray misses a root that is a leaf.
- OrientedBox: Fixed "distanceToBox" using the wrong axis for one set of box edges.
- ExtendedTriangle: Fixed "closestPointToSegment" returning a positive distance for segments that pass through the triangle.