### Import and Globalize three-mesh-bvh Workers Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/test/workers/parallel-worker-test.html Imports necessary Three.js and three-mesh-bvh modules and makes them globally accessible. This setup is typically used for testing environments. ```javascript import * as THREE from 'three'; import { MeshBVH } from 'three-mesh-bvh'; import { ParallelMeshBVHWorker, GenerateMeshBVHWorker } from 'three-mesh-bvh/worker'; window.THREE = THREE; window.MeshBVH = MeshBVH; window.ParallelMeshBVHWorker = ParallelMeshBVHWorker; window.GenerateMeshBVHWorker = GenerateMeshBVHWorker; ``` -------------------------------- ### Get Bounding Box Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Calculates the axis-aligned bounding box for all primitives within the BVH. ```js getBoundingBox( target: Box3 ): Box3 ``` -------------------------------- ### Get BVH JSON structure Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Generates a plain-object representation of the BVH hierarchy for inspection or serialization. ```js getJSONStructure( bvh: BVH ): Object ``` -------------------------------- ### Initialize PointsBVH for Point Clouds Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/README.md Demonstrates configuring a THREE.Points object to use an accelerated BVH and manual construction of the BVH. ```javascript import { PointsBVH } from 'three-mesh-bvh'; // For point clouds THREE.Points.prototype.raycast = acceleratedRaycast; const points = new THREE.Points( geometry, material ); geometry.computeBoundsTree( { type: PointsBVH } ); // Or create directly geometry.boundsTree = new PointsBVH( geometry ); ``` -------------------------------- ### SkinnedMeshBVH constructor Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Initializes a new SkinnedMeshBVH instance for a given SkinnedMesh. ```js constructor( mesh: SkinnedMesh, options: Object ) ``` -------------------------------- ### SkinnedMeshBVH.constructor Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Constructs a new SkinnedMeshBVH for the provided SkinnedMesh object. ```APIDOC ## SkinnedMeshBVH.constructor ### Description Creates a BVH for SkinnedMesh objects. Computes primitive bounds using SkinnedMesh.getVertexPosition so the tree reflects the current posed state of the mesh. ### Signature constructor( mesh: SkinnedMesh, options: Object ) ``` -------------------------------- ### Registering and using pre-made BVH functions Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/README.md Extends THREE.BufferGeometry and THREE.Mesh prototypes to include BVH computation and raycasting capabilities. ```javascript import * as THREE from 'three'; import { computeBoundsTree, disposeBoundsTree, computeBatchedBoundsTree, disposeBatchedBoundsTree, acceleratedRaycast, } from 'three-mesh-bvh'; // Add the extension functions THREE.BufferGeometry.prototype.computeBoundsTree = computeBoundsTree; THREE.BufferGeometry.prototype.disposeBoundsTree = disposeBoundsTree; THREE.Mesh.prototype.raycast = acceleratedRaycast; THREE.BatchedMesh.prototype.computeBoundsTree = computeBatchedBoundsTree; THREE.BatchedMesh.prototype.disposeBoundsTree = disposeBatchedBoundsTree; THREE.BatchedMesh.prototype.raycast = acceleratedRaycast; // Generate geometry and associated BVH const geom = new THREE.TorusKnotGeometry( 10, 3, 400, 100 ); const mesh = new THREE.Mesh( geom, material ); geom.computeBoundsTree(); // Or generate BatchedMesh and associated BVHs const batchedMesh = new THREE.BatchedMesh( ... ); const geomId = batchedMesh.addGeometry( geom ); const instId = batchedMesh.addGeometry( geom ); // Generate bounds tree for sub geometry batchedMesh.computeBoundsTree( geomId ); ``` -------------------------------- ### constructor Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Creates a new ObjectBVH instance from a root object or array of objects. ```APIDOC ## constructor ### Description Initializes a new ObjectBVH instance to accelerate spatial queries for a scene hierarchy. ### Signature `constructor(root: Object3D | Array, options: { precise?: boolean, includeInstances?: boolean })` ### Parameters - **root** (Object3D | Array) - Required - The root object or array of objects to build the BVH from. - **precise** (boolean) - Optional - Use vertex-level bounds instead of cached bounding boxes. - **includeInstances** (boolean) - Optional - Treat each instance of InstancedMesh/BatchedMesh as a separate primitive. ``` -------------------------------- ### Initialize GeometryBVH Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Constructor for creating a new BVH instance with specific build strategies and configuration options. ```js constructor( geometry: BufferGeometry, { // Split strategy: `CENTER`, `AVERAGE`, or `SAH`. strategy = CENTER: number, // Maximum tree depth. Note that this can cause the target leaf // size to not be met if the tree is truncated. maxDepth = 40: number, // The target number of primitives per leaf node. Note that // this is a soft limit and generation strategies like SAH will // terminate early if the heuristic determines. targetLeafSize = 10: number, // Set `geometry.boundingBox` if not already present. setBoundingBox = true: boolean, // Use `SharedArrayBuffer` for BVH root buffers. useSharedArrayBuffer = false: boolean, // Build using an indirect buffer, leaving the original index unmodified. indirect = false: boolean, // Log build progress to the console. verbose = true: boolean, // Called with a progress value in [0, 1] during build. onProgress = null: function | null, // Restrict the BVH to a specific geometry group range. range = null: Object | null, } ) ``` -------------------------------- ### Initialize ObjectBVH Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Constructs a new ObjectBVH instance from a root object or array of objects, with options for precision and instance handling. ```js constructor( root: Object3D | Array, { // Use vertex-level bounds instead of cached bounding boxes. precise = false: boolean, // Treat each instance of InstancedMesh/BatchedMesh as a // separate primitive. includeInstances = true: boolean, } ) ``` -------------------------------- ### Perform First Raycast Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Returns the first raycast hit in the model, which is typically faster than returning all hits. ```js raycastFirst( ray: Ray, materialOrSide = FrontSide: number | Material | Array, near = 0: number, far = Infinity: number ): Intersection | null ``` -------------------------------- ### GeometryBVH Constructor Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Initializes a new GeometryBVH instance with the specified geometry and configuration options. ```APIDOC ## constructor(geometry, options) ### Description Creates a new BVH instance for the provided BufferGeometry. Configures build strategies, tree depth, and memory usage settings. ### Parameters - **geometry** (BufferGeometry) - Required - The geometry to build the BVH from. - **options** (Object) - Optional - Configuration object: - **strategy** (number) - Optional - Split strategy: CENTER, AVERAGE, or SAH. - **maxDepth** (number) - Optional - Maximum tree depth. - **targetLeafSize** (number) - Optional - Target number of primitives per leaf node. - **setBoundingBox** (boolean) - Optional - Set geometry.boundingBox if not already present. - **useSharedArrayBuffer** (boolean) - Optional - Use SharedArrayBuffer for BVH root buffers. - **indirect** (boolean) - Optional - Build using an indirect buffer. - **verbose** (boolean) - Optional - Log build progress to the console. - **onProgress** (function) - Optional - Callback with progress value in [0, 1]. - **range** (Object) - Optional - Restrict the BVH to a specific geometry group range. ``` -------------------------------- ### set Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Sets the parameters for the oriented box. ```APIDOC ## set(min, max, matrix) ### Description Updates the oriented box parameters. Note that `.needsUpdate` must be set to true after modification. ### Parameters - **min** (Vector3) - Required - The minimum bounds. - **max** (Vector3) - Required - The maximum bounds. - **matrix** (Matrix4) - Required - The transformation matrix. ``` -------------------------------- ### Initialize BVHComputeData Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/WEBGPU_API.md Constructor for creating a new BVHComputeData instance with specified attributes and automatic BVH generation settings. ```js constructor( objects: Object3D | BufferGeometry | GeometryBVH | Array, { // WGSL type map for the interleaved per-vertex attribute // buffer. Keys are geometry attribute names; values are WGSL // type strings (e.g. 'vec3f', 'vec4f'). attributes = { position: 'vec4f' }: Record, // When true, a [MeshBVH](MeshBVH) is automatically built for any // object that does not already have `geometry.boundsTree` set. autogenerateBvh = true: boolean, } ) ``` -------------------------------- ### BVHComputeData Constructor Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/WEBGPU_API.md Initializes a new BVHComputeData instance to pack scene objects into GPU-accessible buffers. ```APIDOC ## constructor(objects, options) ### Description Creates a new instance to manage BVH data for GPU compute shaders. ### Parameters - **objects** (Object3D | BufferGeometry | GeometryBVH | Array) - Required - The scene objects to pack. - **options** (Object) - Optional - **attributes** (Record) - Optional - WGSL type map for the interleaved per-vertex attribute buffer. - **autogenerateBvh** (boolean) - Optional - Whether to automatically build a MeshBVH for objects without one. ``` -------------------------------- ### StaticGeometryGenerator.constructor Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Initializes a new StaticGeometryGenerator instance with the provided meshes or object hierarchies. ```APIDOC ## constructor( meshes: Object3D | Array ) ### Description Takes an array of object hierarchies to bake into a single static geometry. ### Parameters - **meshes** (Object3D | Array) - Required - The meshes or object hierarchies to be baked. ``` -------------------------------- ### .raycastFirst Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Returns the first raycast hit in the model. ```APIDOC ## .raycastFirst(ray, materialOrSide, near, far) ### Description Returns the first raycast hit in the model. This is typically much faster than returning all hits. ### Parameters - **ray** (Ray) - Required - The ray to cast. - **materialOrSide** (number | Material | Array) - Optional - The side to check or a material with the side field. - **near** (number) - Optional - Near clipping distance. - **far** (number) - Optional - Far clipping distance. ### Response - **Returns** (Intersection | null) - The first intersection found or null. ``` -------------------------------- ### OrientedBox Constructor and Set Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Methods for initializing or updating the oriented box parameters. ```js constructor( min: Vector3, max: Vector3, matrix: Matrix4 ) ``` ```js set( min: Vector3, max: Vector3, matrix: Matrix4 ): void ``` -------------------------------- ### BVHComputeData#update Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/WEBGPU_API.md Rebuilds all GPU storage buffers. ```APIDOC ## update() ### Description Rebuilds all GPU storage buffers from the current scene state. Must be called before using storage or fns in a shader. ``` -------------------------------- ### Construct LineLoopBVH Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Initializes a BVH for THREE.LineLoop geometries. ```js constructor( geometry: BufferGeometry, options: Object ) ``` -------------------------------- ### Retrieve Root Object Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/WEBGPU_API.md Returns the representative root object for the scene to be constructed. ```js getRootObject(): Object3D ``` -------------------------------- ### BVHComputeData#dispose Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/WEBGPU_API.md Releases GPU resources. ```APIDOC ## dispose() ### Description Releases GPU resources held by this instance. ``` -------------------------------- ### computeBoundsTree Extension Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Builds a new BVH and assigns it to BufferGeometry. ```js computeBoundsTree( options: Object ): GeometryBVH ``` ```js THREE.BufferGeometry.prototype.computeBoundsTree = computeBoundsTree; ``` -------------------------------- ### Query MeshBVH Directly Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/README.md Shows how to perform ray and sphere intersections by transforming inputs into the local space of the geometry. ```javascript import * as THREE from 'three'; import { MeshBVH, acceleratedRaycast } from 'three-mesh-bvh'; let mesh, geometry; const invMat = new THREE.Matrix4(); // instantiate the geometry // ... const bvh = new MeshBVH( geometry ); invMat.copy( mesh.matrixWorld ).invert(); // raycasting // ensure the ray is in the local space of the geometry being cast against raycaster.ray.applyMatrix4( invMat ); const hit = bvh.raycastFirst( raycaster.ray ); // results are returned in local spac, as well, so they must be transformed into // world space if needed. hit.point.applyMatrixWorld( mesh.matrixWorld ); // spherecasting // ensure the sphere is in the local space of the geometry being cast against sphere.applyMatrix4( invMat ); const intersects = bvh.intersectsSphere( sphere ); ``` -------------------------------- ### .raycast Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Returns all raycast triangle hits in unsorted order. ```APIDOC ## .raycast(ray, materialOrSide, near, far) ### Description Returns all raycast triangle hits in unsorted order. It is expected that `ray` is in the frame of the BVH already. ### Parameters - **ray** (Ray) - Required - The ray to cast. - **materialOrSide** (number | Material | Array) - Optional - The side to check or a material with the side field. - **near** (number) - Optional - Near clipping distance. - **far** (number) - Optional - Far clipping distance. ### Response - **Returns** (Array) - An array of intersection results in the local frame of the BVH. ``` -------------------------------- ### OrientedBox Constructor Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Creates a new instance of an OrientedBox. ```APIDOC ## constructor(min, max, matrix) ### Description Creates a new OrientedBox instance with the specified min, max, and transformation matrix. ### Parameters - **min** (Vector3) - Required - The minimum bounds of the box. - **max** (Vector3) - Required - The maximum bounds of the box. - **matrix** (Matrix4) - Required - The transformation matrix applied to the box. ``` -------------------------------- ### Dispose Resources Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/WEBGPU_API.md Releases GPU resources held by the instance. ```js dispose(): void ``` -------------------------------- ### Performing optimized raycasting Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/README.md Configures the Raycaster to use the BVH's accelerated raycast functions by setting firstHitOnly to true. ```javascript // Setting "firstHitOnly" to true means the Mesh.raycast function will use the // bvh "raycastFirst" function to return a result more quickly. const raycaster = new THREE.Raycaster(); raycaster.firstHitOnly = true; raycaster.intersectObjects( [ mesh ] ); ``` -------------------------------- ### Shader and Texture Packing API Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md GLSL shader functions and struct definitions for interacting with packed BVH data. ```js bvh_ray_functions: string ``` ```js common_functions: string ``` ```js bvh_distance_functions: string ``` ```js bvh_struct_definitions: string ``` -------------------------------- ### Manually building a BVH Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/README.md Constructs a MeshBVH instance directly and assigns it to the geometry's boundsTree property. ```javascript import * as THREE from 'three'; import { MeshBVH, acceleratedRaycast } from 'three-mesh-bvh'; // Add the raycast function. Assumes the BVH is available on // the `boundsTree` variable THREE.Mesh.prototype.raycast = acceleratedRaycast; // ... // Generate the BVH and use the newly generated index geom.boundsTree = new MeshBVH( geom ); ``` -------------------------------- ### Configure overrideItemSize property Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Sets a custom item size for buffer attribute packing. Throws an error if the value does not divide evenly into the buffer length. ```js overrideItemSize: number ``` -------------------------------- ### BVH Construction Constants Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Constants defining strategies for splitting BVH nodes during construction. ```js CENTER: number ``` ```js AVERAGE: number ``` ```js SAH: number ``` -------------------------------- ### StaticGeometryGenerator constructor Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Initializes the generator with object hierarchies to bake. ```js constructor( meshes: Object3D | Array ) ``` -------------------------------- ### Refit BVH Bounds Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Updates node bounds based on current primitive positions. Faster than rebuilding but results in a less optimal tree. ```js refit(): void ``` -------------------------------- ### .refit Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Refits the node bounds to the current triangle positions. This is faster than regenerating the BVH but less optimal after significant vertex changes. ```APIDOC ## .refit(nodeIndices) ### Description Refit the node bounds to the current triangle positions. This is quicker than regenerating a new BVH but will not be optimal after significant changes to the vertices. ### Parameters - **nodeIndices** (Set | Array | null) - Optional - A set of node indices (provided by the shapecast function) that need to be refit including all internal nodes. ``` -------------------------------- ### StaticGeometryGenerator .getMaterials method Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Retrieves the materials required for the merged geometry. ```js getMaterials(): Array ``` -------------------------------- ### CSS for Loader Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/example/distancecast.html Basic CSS to style a loader element. This is often used to indicate background processing. ```css #loader { height: 3px; position: absolute; bottom: 0; width: 100%; background: white; } ``` -------------------------------- ### Generate MeshBVH with WebWorker Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/README.md Offload BVH generation to a background thread to prevent main thread blocking. Import the worker class from the 'three-mesh-bvh/worker' subpath. ```javascript import { GenerateMeshBVHWorker } from 'three-mesh-bvh/worker'; // ... const geometry = new KnotGeometry( 1, 0.5, 40, 10 ); const worker = new GenerateMeshBVHWorker(); worker.generate( geometry ).then( bvh => { geometry.boundsTree = bvh; } ); ``` -------------------------------- ### Retrieve Instance Index by ID Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Retrieves the instance index associated with a specific composite ID. ```js getInstanceFromId( compositeId: number ): number ``` -------------------------------- ### BVHComputeData#getShapecastFn Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/WEBGPU_API.md Builds a WGSL shapecast function for custom shape traversal. ```APIDOC ## getShapecastFn(options) ### Description Builds a WGSL shapecast function that traverses the TLAS and per-cluster BLAS in a single merged stack/loop for a custom shape type. ### Parameters - **options** (Object) - Required - **name** (string) - Optional - Function name. - **shapeStruct** (StructTypeNode) - Required - TSL struct describing the query shape. - **resultStruct** (StructTypeNode | null) - Optional - TSL struct for the accumulated result. - **boundsOrderFn** (function | null) - Optional - Function node controlling traversal order. - **intersectsBoundsFn** (function) - Required - Function node testing shape against bounds. - **intersectRangeFn** (function) - Required - Function node testing shape against triangle range. - **transformShapeFn** (function | null) - Optional - Function node to transform shape into local space. - **transformResultFn** (function | null) - Optional - Function node to transform hit result to world space. - **resetShapeFn** (function | null) - Optional - Function node called after BLAS traversal. ``` -------------------------------- ### Build WGSL Shapecast Function Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/WEBGPU_API.md Generates a WGSL function for traversing TLAS and BLAS structures for custom shape queries. ```js getShapecastFn( { // Function name. Defaults to a random identifier. name?: string, // TSL struct or definition describing the query shape. shapeStruct: StructTypeNode, // TSL struct for the accumulated result, or null. resultStruct?: StructTypeNode | null, // function node controlling left/right child traversal order. boundsOrderFn?: function | null, // function node testing the shape against a BVH node's bounds. intersectsBoundsFn: function, // function node testing the shape against a leaf triangle // range. intersectRangeFn: function, // function node that transforms the shape into object local // space. transformShapeFn?: function | null, // function node that transforms a hit result back to world // space. transformResultFn?: function | null, // function node called after each BLAS traversal to reset any // per-object state set by `transformShapeFn`. resetShapeFn?: function | null, } ): function ``` -------------------------------- ### Perform Raycast Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Returns all raycast triangle hits in unsorted order. Results are provided in the local frame of the BVH. ```js raycast( ray: Ray, materialOrSide = FrontSide: number | Material | Array, near = 0: number, far = Infinity: number ): Array ``` -------------------------------- ### Compute triangle hit point info Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Retrieves detailed hit data such as face indices, normals, and UVs for a specific triangle. ```js getTriangleHitPointInfo( point: Vector3, geometry: BufferGeometry, triangleIndex: number, target: HitTriangleInfo ): HitTriangleInfo ``` -------------------------------- ### Refit BVH Node Bounds Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Updates node bounds to match current triangle positions. This is faster than regenerating the BVH but less optimal after significant vertex changes. ```js refit( nodeIndices = null: Set | Array | null ): void ``` -------------------------------- ### ndcToCameraRay Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/WEBGPU_API.md WGSL function node that builds a camera ray from an NDC coordinate and an inverse model-view-projection matrix. ```APIDOC ## ndcToCameraRay ### Description WGSL function node that builds a camera ray (origin + far-plane direction) from an NDC coordinate and an inverse model-view-projection matrix. Works for both perspective and orthographic projections. The returned direction is not normalized and extends to the camera far plane. ``` -------------------------------- ### Raycast Object3D Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Performs a raycast against the mesh and returns results in world space. ```js raycastObject3D( object: Object3D, raycaster: Raycaster, intersects = []: Array ): Array ``` -------------------------------- ### StaticGeometryGenerator.getMaterials Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Returns an array of materials for the meshes to be merged, suitable for use when creating a new Mesh. ```APIDOC ## getMaterials() ### Description Returns an array of materials for the meshes to be merged. These can be used alongside the generated geometry when creating a mesh. ### Returns - **Array** - An array of materials. ``` -------------------------------- ### BVHComputeData#getRootObject Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/WEBGPU_API.md Retrieves the representative root object for the scene. ```APIDOC ## getRootObject() ### Description Returns the representative root object for the scene to be constructed. ``` -------------------------------- ### OrientedBox Distance Methods Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Methods to calculate distances between the box and other points or boxes. ```js closestPointToPoint( point: Vector3, target: Vector3 ): number ``` ```js distanceToPoint( point: Vector3 ): number ``` ```js distanceToBox( box: Box3, threshold = 0: number, target1: Vector3, target2: Vector3 ): number ``` -------------------------------- ### acceleratedRaycast Function Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Accelerated raycast function with the same signature as THREE.Mesh.raycast. ```js acceleratedRaycast( raycaster: Raycaster, intersects: Array ): void ``` -------------------------------- ### traverse Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Traverses all nodes of the BVH, invoking a callback for each node. ```APIDOC ## .traverse(callback: function, rootIndex = 0: number) ### Description Traverses all nodes of the BVH, invoking a callback for each node. For leaf nodes the callback receives (depth, isLeaf, boundingData, offset, count). For internal nodes it receives (depth, isLeaf, boundingData, splitAxis) and may return true to stop descending. ``` -------------------------------- ### Perform Spatial Query with Shapecast Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Executes a generalized depth-first spatial query. Returns true upon the first reported intersection. ```js shapecast( { intersectsBounds: ( box: Box3, isLeaf: boolean, score: number | undefined, depth: number, nodeIndex: number ) => number, intersectsRange?: ( offset: number, count: number, contained: boolean, depth: number, nodeIndex: number, box: Box3 ) => boolean, boundsTraverseOrder?: ( box: Box3 ) => number, } ): boolean ``` -------------------------------- ### Update GPU Buffers Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/WEBGPU_API.md Rebuilds all GPU storage buffers from the current scene state. Must be called before shader usage or when scene topology changes. ```js update(): void ``` -------------------------------- ### getBoundingBox Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Computes the axis-aligned bounding box of all primitives in the BVH. ```APIDOC ## .getBoundingBox(target: Box3) ### Description Computes the axis-aligned bounding box of all primitives in the BVH. ### Parameters - **target** (Box3) - Required - The target Box3 object to store the result. ``` -------------------------------- ### Generate BVH in worker Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Initiates asynchronous BVH generation for a geometry, returning a promise that resolves with the MeshBVH instance. ```js generate( geometry: BufferGeometry, { // Callback invoked with a `[0, 1]` progress value as the BVH // is built. onProgress?: function, } ): Promise ``` -------------------------------- ### estimateMemoryInBytes Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Roughly estimates the amount of memory in bytes used by a BVH by walking its object graph. ```APIDOC ## estimateMemoryInBytes(bvh) ### Description Estimates the memory usage of a BVH by summing typed-array byte lengths and primitive sizes. ### Parameters - **bvh** (BVH) - The BVH instance to estimate. ### Returns - **number** - The estimated memory in bytes. ``` -------------------------------- ### GenerateMeshBVHWorker.dispose Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Terminates the worker instance. ```APIDOC ## GenerateMeshBVHWorker.dispose ### Description Terminates the worker associated with the GenerateMeshBVHWorker instance. ``` -------------------------------- ### distanceToBox Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Calculates the distance to another box. ```APIDOC ## distanceToBox(box, threshold, target1, target2) ### Description Returns the distance to the provided box. Optionally returns early if the distance is within the threshold. ### Parameters - **box** (Box3) - Required - The box to measure distance to. - **threshold** (number) - Optional - Early exit distance. - **target1** (Vector3) - Required - Set to the closest point on this box. - **target2** (Vector3) - Required - Set to the closest point on the argument box. ``` -------------------------------- ### StaticGeometryGenerator .useGroups property Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Determines if groups are used to support multiple materials on the mesh. ```js useGroups: boolean ``` -------------------------------- ### acceleratedRaycast Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md An accelerated raycast function that uses the BVH for raycasting if available, falling back to the built-in approach otherwise. It maintains the same signature as THREE.Mesh.raycast. ```APIDOC ## acceleratedRaycast(raycaster, intersects) ### Description An accelerated raycast function with the same signature as THREE.Mesh.raycast. Uses the BVH for raycasting if it's available otherwise it falls back to the built-in approach. ### Parameters - **raycaster** (Raycaster) - Required - The Three.js Raycaster object. - **intersects** (Array) - Required - The array to store intersection results. ### Returns - **void** ``` -------------------------------- ### refit Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Refits all BVH node bounds to reflect the current primitive positions. ```APIDOC ## .refit() ### Description Refits all BVH node bounds to reflect the current primitive positions. Faster than rebuilding the BVH but produces a less optimal tree after large vertex deformations. ``` -------------------------------- ### getInstanceFromId Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Retrieves the instance index associated with a specific composite ID. ```APIDOC ## getInstanceFromId ### Description Returns the instance index associated with a composite id as provided to intersectsObject. ### Signature `getInstanceFromId(compositeId: number): number` ### Parameters - **compositeId** (number) - Required - The composite ID to look up. ``` -------------------------------- ### getTriangleHitPointInfo Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Computes hit-point information for a point on a triangle within a BufferGeometry, returning face indices, normals, material index, UVs, and barycentric coordinates. ```APIDOC ## getTriangleHitPointInfo(point, geometry, triangleIndex, target) ### Description Computes hit-point information for a point on a triangle within a `BufferGeometry`. Returns the face vertex indices, face normal, material index, UV coordinates, and barycentric coordinates. ### Parameters - **point** (Vector3) - The point to evaluate. - **geometry** (BufferGeometry) - The geometry containing the triangle. - **triangleIndex** (number) - The index of the triangle. - **target** (HitTriangleInfo) - The object to store the result in. ### Returns - **HitTriangleInfo** - The populated hit information object. ``` -------------------------------- ### shapecast Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Performs a spatial query against the BVH using custom callbacks. ```APIDOC ## shapecast ### Description Performs a spatial query against the BVH. Extends the base shapecast with an intersectsObject callback that is called once per object primitive in leaf nodes. ### Signature `shapecast(options: { intersectsBounds: Function, intersectsObject?: Function, intersectsRange?: Function, boundsTraverseOrder?: Function }): boolean` ### Parameters - **intersectsBounds** (Function) - Required - Callback for bounding box intersection. - **intersectsObject** (Function) - Optional - Callback for object intersection. - **intersectsRange** (Function) - Optional - Callback for range intersection. - **boundsTraverseOrder** (Function) - Optional - Callback to determine traversal order. ``` -------------------------------- ### disposeBoundsTree Extension Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Disposes of the BVH attached to BufferGeometry. ```js disposeBoundsTree(): void ``` ```js THREE.BufferGeometry.prototype.disposeBoundsTree = disposeBoundsTree; ``` -------------------------------- ### HitPointInfo Properties Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Data structures representing the closest point on a mesh surface. ```js point: Vector3 ``` ```js distance: number ``` ```js faceIndex: number ``` -------------------------------- ### TSL Structs Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/WEBGPU_API.md Definitions for rayStruct, rayIntersectionResultStruct, and pointQueryResultStruct used in WebGPU shaders. ```APIDOC ## TSL Structs ### rayStruct WGSL struct node representing a ray with an origin and direction. Used as the input to BVH traversal and intersection functions. ### rayIntersectionResultStruct WGSL struct node describing a ray–triangle intersection result, including barycentric coordinates, world-space normal, hit distance, face side, triangle indices, and the object index within the TLAS. ### pointQueryResultStruct WGSL struct node describing a closest-point query result, including the world-space closest point, squared distance, barycentric coordinates, face normal, side, triangle indices, and the object index within the TLAS. ``` -------------------------------- ### Access geometry property Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Retrieves the BufferGeometry instance associated with the BVH. ```js readonly geometry: BufferGeometry ``` -------------------------------- ### OrientedBox Intersection Methods Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Methods to check for intersections with other geometric primitives. ```js intersectsBox( box: Box3 ): boolean ``` ```js intersectsTriangle( triangle: Triangle ): boolean ``` -------------------------------- ### Generate MeshBVH with ParallelWorker Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/README.md Perform parallel BVH generation using SharedArrayBuffer. Requires SharedArrayBuffer support; otherwise, it falls back to the standard worker. ```javascript import { ParallelMeshBVHWorker } from 'three-mesh-bvh/worker'; // ... const geometry = new KnotGeometry( 1, 0.5, 40, 10 ); const worker = new ParallelMeshBVHWorker(); worker.generate( geometry ).then( bvh => { geometry.boundsTree = bvh; } ); ``` -------------------------------- ### SkinnedMeshBVH.shapecast Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Performs a spatial query against the SkinnedMeshBVH, allowing for custom intersection logic for bounds and triangles. ```APIDOC ## SkinnedMeshBVH.shapecast ### Description Performs a spatial query against the BVH. Extends the base shapecast with an intersectsTriangle callback that is called once per triangle primitive in leaf nodes. ### Signature shapecast( { intersectsBounds, intersectsTriangle?, intersectsRange?, boundsTraverseOrder? } ): boolean ### Parameters - **intersectsBounds** (function) - Required - Callback for box intersection. - **intersectsTriangle** (function) - Optional - Callback for triangle intersection. - **intersectsRange** (function) - Optional - Callback for range intersection. - **boundsTraverseOrder** (function) - Optional - Callback for traversal order. ``` -------------------------------- ### MeshBVH.serialize Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Generates a serializable representation of the BVH for off-main-thread processing. ```APIDOC ## static serialize ### Description Generates a representation of the complete bounds tree and the geometry index buffer which can be used to recreate a bounds tree using the deserialize function. ### Parameters - **bvh** (MeshBVH) - Required - The MeshBVH instance to serialize. - **options** (Object) - Required - Configuration object containing cloneBuffers (boolean). ``` -------------------------------- ### GenerateMeshBVHWorker.generate Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Generates a MeshBVH instance for the given geometry in a WebWorker. ```APIDOC ## GenerateMeshBVHWorker.generate ### Description Generates a MeshBVH instance for the given geometry with the given options in a WebWorker. Returns a Promise that resolves with the generated MeshBVH. ### Parameters - **geometry** (BufferGeometry) - Required - The geometry to generate the BVH for. - **onProgress** (function) - Optional - Callback invoked with a [0, 1] progress value as the BVH is built. ### Returns - **Promise** - Resolves with the generated MeshBVH instance. ``` -------------------------------- ### closestPointToPoint Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Calculates the distance to a point and finds the closest point on the surface. ```APIDOC ## closestPointToPoint(point, target) ### Description Returns the distance to the provided point. If a target is provided, it is set to the closest point on the surface of the box. ### Parameters - **point** (Vector3) - Required - The point to measure distance to. - **target** (Vector3) - Optional - The vector to store the closest point result. ``` -------------------------------- ### distanceToPoint Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Calculates the distance to a point. ```APIDOC ## distanceToPoint(point) ### Description Returns the distance from the oriented box to the provided point. ### Parameters - **point** (Vector3) - Required - The point to measure distance to. ``` -------------------------------- ### computeBoundsTree Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md A BufferGeometry extension function that builds a new BVH, assigns it to boundsTree, and applies the new index buffer to the geometry. ```APIDOC ## computeBoundsTree(options) ### Description A pre-made BufferGeometry extension function that builds a new BVH, assigns it to `boundsTree` for BufferGeometry, and applies the new index buffer to the geometry. ### Parameters - **options** (Object) - Required - Configuration options for the BVH construction. ### Returns - **GeometryBVH** ``` -------------------------------- ### shapecast Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md A generalized traversal function for performing spatial queries against the BVH. ```APIDOC ## .shapecast(options: object) ### Description A generalized traversal function for performing spatial queries against the BVH. Returns true as soon as a primitive has been reported as intersected. ``` -------------------------------- ### Shift triangle offsets Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Updates BVH triangle offsets to match compacted or shifted geometry buffers. ```js shiftTriangleOffsets( offset: number ): void ``` -------------------------------- ### StaticGeometryGenerator .attributes property Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Lists the attributes to be copied to the static geometry. ```js attributes: Array ``` -------------------------------- ### Estimate BVH memory usage Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Calculates the approximate memory footprint of a BVH by traversing its object graph. ```js estimateMemoryInBytes( bvh: BVH ): number ``` -------------------------------- ### Validate BVH bounds Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Checks that bounding boxes correctly contain children and primitives, logging failures via console.assert. ```js validateBounds( bvh: MeshBVH ): boolean ``` -------------------------------- ### rayStruct TSL Struct Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/WEBGPU_API.md WGSL struct node representing a ray with an origin and direction, used as input to BVH traversal. ```js rayStruct: StructTypeNode ``` -------------------------------- ### bvhcast Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Simultaneously traverses two BVH structures to find intersecting primitive pairs. ```APIDOC ## .bvhcast(otherBvh: BVH, matrixToLocal: Matrix4, options: object) ### Description Simultaneously traverses two BVH structures to find intersecting primitive pairs. Returns true as soon as any intersection is reported. ``` -------------------------------- ### computeBatchedBoundsTree Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Equivalent of computeBoundsTree for BatchedMesh, allowing generation of BVHs for specific or all geometries within the batch. ```APIDOC ## computeBatchedBoundsTree(index, options) ### Description Equivalent of `computeBoundsTree` for `BatchedMesh`. Creates the `BatchedMesh.boundsTrees` array if it does not exist. ### Parameters - **index** (number) - Optional - The geometry index to process. Defaults to -1 (all). - **options** (Object) - Required - Configuration options for the BVH construction. ### Returns - **GeometryBVH | Array | null** ``` -------------------------------- ### .shapecast Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md A generalized cast function for custom shape intersection logic. ```APIDOC ## .shapecast(callbacks) ### Description A generalized cast function that can be used to implement intersection logic for custom shapes. ### Parameters - **callbacks** (Object) - Required - Contains intersection logic functions: intersectsBounds, intersectsTriangle, intersectsRange, and boundsTraverseOrder. ### Response - **Returns** (boolean) - Returns true if a triangle has been intersected. ``` -------------------------------- ### PointsBVH shapecast method Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Performs a spatial query on PointsBVH, utilizing an intersectsPoint callback for leaf node primitives. ```js shapecast( { intersectsBounds: ( box: Box3, isLeaf: boolean, score: number | undefined, depth: number, nodeIndex: number ) => number, intersectsPoint?: ( point: Vector3, index: number, contained: boolean, depth: number ) => boolean, intersectsRange?: ( offset: number, count: number, contained: boolean, depth: number, nodeIndex: number, box: Box3 ) => boolean, boundsTraverseOrder?: ( box: Box3 ) => number, } ): boolean ``` -------------------------------- ### disposeBatchedBoundsTree Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Equivalent of disposeBoundsTree for BatchedMesh, allowing disposal of BVHs for specific or all geometries within the batch. ```APIDOC ## disposeBatchedBoundsTree(index) ### Description Equivalent of `disposeBoundsTree` for `BatchedMesh`. Sets entries in `BatchedMesh.boundsTrees` to `null`. ### Parameters - **index** (number) - Optional - The geometry index to dispose. Defaults to -1 (all). ### Returns - **void** ``` -------------------------------- ### pointQueryResultStruct TSL Struct Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/WEBGPU_API.md WGSL struct node describing a closest-point query result including world-space point, distance, and triangle indices. ```js pointQueryResultStruct: StructTypeNode ``` -------------------------------- ### Serialize MeshBVH Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Generates a serializable representation of the BVH for storage or worker transfer. ```js static serialize( bvh: MeshBVH, { // If `true`, the index and BVH root buffers are cloned so // the serialized data is independent of the live BVH. cloneBuffers = true: boolean, } ): SerializedBVH ``` -------------------------------- ### MeshBVHUniformStruct.dispose Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Disposes of the associated textures. ```APIDOC ## MeshBVHUniformStruct.dispose ### Description Dispose of the associated textures used by the uniform struct. ``` -------------------------------- ### MeshBVH.deserialize Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Reconstructs a MeshBVH instance from serialized data. ```APIDOC ## static deserialize ### Description Returns a new MeshBVH instance from the serialized data. ### Parameters - **data** (SerializedBVH) - Required - The serialized BVH data. - **geometry** (BufferGeometry) - Required - The geometry used to generate the original BVH. - **options** (Object) - Required - Configuration object containing setIndex (boolean). ``` -------------------------------- ### StaticGeometryGenerator .applyWorldTransforms property Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Specifies whether to apply world transforms to vertices during generation. ```js applyWorldTransforms: boolean ``` -------------------------------- ### StaticGeometryGenerator.generate Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Generates a single, static geometry for the meshes provided to the constructor. ```APIDOC ## generate( targetGeometry: BufferGeometry ) ### Description Generates a single, static geometry for the passed meshes. The same generated geometry can be passed into the function on subsequent calls to update the geometry in place. ### Parameters - **targetGeometry** (BufferGeometry) - Required - The geometry to populate or update. ### Returns - **BufferGeometry** - The generated or updated static geometry. ``` -------------------------------- ### disposeBoundsTree Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md A BufferGeometry extension function that disposes of the BVH associated with the geometry. ```APIDOC ## disposeBoundsTree() ### Description A BufferGeometry extension function that disposes of the BVH. ### Returns - **void** ``` -------------------------------- ### BVH Extremes properties Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Properties representing metrics for the BVH tree structure. ```js nodeCount: number ``` ```js leafNodeCount: number ``` ```js surfaceAreaScore: number ``` ```js depth: Object ``` ```js tris: Object ``` ```js splits: Array ``` -------------------------------- ### BVHHelper Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md A THREE.Group that visualizes a BVH as wireframe bounding boxes or solid face overlays. ```APIDOC ## constructor(mesh, bvh, depth) ### Description Creates a new BVHHelper instance. ### Parameters - **mesh** (Object3D | GeometryBVH | null) - Optional - The mesh to visualize. - **bvh** (GeometryBVH | number | null) - Optional - The BVH to visualize. - **depth** (number) - Optional - The depth of the visualization. ## update() ### Description Rebuilds the helper's display geometry from the current BVH state. Must be called after changes to the BVH, depth, displayParents, or displayEdges. ## dispose() ### Description Disposes of the materials and geometries used by the helper. ``` -------------------------------- ### Perform BVH Intersection with Bvhcast Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Traverses two BVH structures simultaneously to identify intersecting primitive pairs. ```js bvhcast( otherBvh: BVH, matrixToLocal: Matrix4, { intersectsRanges: ( offset1: number, count1: number, offset2: number, count2: number, depth1: number, nodeIndex1: number, depth2: number, nodeIndex2: number ) => boolean, } ): boolean ``` -------------------------------- ### Shift Primitive Offsets Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Adjusts primitive offsets in leaf nodes, useful after geometry buffer compaction. ```js shiftPrimitiveOffsets( offset: number ): void ``` -------------------------------- ### validateBounds Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Validates that every node's bounding box fully contains its children and primitives. ```APIDOC ## validateBounds(bvh) ### Description Validates that every node's bounding box fully contains its children and, for leaf nodes, fully contains all of its primitives. Uses `console.assert` to log failures. ### Parameters - **bvh** (MeshBVH) - The BVH instance to validate. ### Returns - **boolean** - Returns `false` if any check fails. ``` -------------------------------- ### computeBatchedBoundsTree Extension Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Generates BVHs for BatchedMesh geometries. ```js computeBatchedBoundsTree( index = -1: number, options: Object ): GeometryBVH | Array | null ``` ```js THREE.BatchedMesh.prototype.computeBoundsTree = computeBatchedBoundsTree; ``` -------------------------------- ### StaticGeometryGenerator .meshes property Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Defines the array of meshes to be processed. ```js meshes: Array ``` -------------------------------- ### Perform Spatial Query with shapecast Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Executes a spatial query using callbacks for bounds, objects, and ranges. The intersectsObject callback is triggered for each object primitive in leaf nodes. ```js shapecast( { intersectsBounds: ( box: Box3, isLeaf: boolean, score: number | undefined, depth: number, nodeIndex: number ) => number, intersectsObject?: ( object: Object3D, instanceId: number, contained: boolean, depth: number ) => boolean, intersectsRange?: ( offset: number, count: number, contained: boolean, depth: number, nodeIndex: number, box: Box3 ) => boolean, boundsTraverseOrder?: ( box: Box3 ) => number, } ): boolean ``` -------------------------------- ### Measure BVH extremes Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md Calculates structural metrics including depth, primitive counts, and surface area heuristic scores. ```js getBVHExtremes( bvh: MeshBVH ): Array ``` -------------------------------- ### Serialize and Deserialize MeshBVH Source: https://github.com/gkjohnson/three-mesh-bvh/blob/master/README.md Use these methods to convert a BVH structure to a serializable format and reconstruct it later. The original geometry must be provided during deserialization. ```javascript const geometry = new KnotGeometry( 1, 0.5, 40, 10 ); const bvh = new MeshBVH( geometry ); const serialized = MeshBVH.serialize( bvh ); // ... const deserializedBVH = MeshBVH.deserialize( serialized, geometry ); geometry.boundsTree = deserializedBVH; ```