three-mesh-bvh
Version:
A BVH implementation to speed up raycasting against three.js meshes.
82 lines (61 loc) • 2.05 kB
JavaScript
/** @import { BVHComputeData } from './BVHComputeData.js' */
import { wgslFn, wgsl } from 'three/tsl';
import { rayStruct, bvhNodeBoundsStruct } from './tsl/structs.js';
/** @deprecated Use {@link BVHComputeData} instead. */
export const constants = wgsl( /* wgsl */`
const BVH_STACK_DEPTH = 60u;
const INFINITY = 1e20;
const TRI_INTERSECT_EPSILON = 1e-5;
` );
/** @deprecated Use {@link BVHComputeData} instead. */
export const intersectionResultStruct = wgsl( /* wgsl */`
struct IntersectionResult {
indices: vec4u,
normal: vec3f,
didHit: bool,
barycoord: vec3f,
side: f32,
dist: f32,
};
` );
/** @deprecated Use {@link BVHComputeData} instead. */
export const getVertexAttribute = wgslFn( /* wgsl */`
fn getVertexAttribute(
barycoord: vec3f,
indices: vec3u,
attributeBuffer: ptr<storage, array<vec3f>, read>
) -> vec3f {
let n0 = attributeBuffer[ indices.x ];
let n1 = attributeBuffer[ indices.y ];
let n2 = attributeBuffer[ indices.z ];
return barycoord.x * n0 + barycoord.y * n1 + barycoord.z * n2;
}
` );
/** @deprecated Use {@link BVHComputeData} instead. */
export const intersectsBounds = wgslFn( /* wgsl */`
fn intersectsBounds(
ray: Ray,
bounds: BVHBoundingBox,
dist: ptr<function, f32>
) -> bool {
let boundsMin = vec3( bounds.min[0], bounds.min[1], bounds.min[2] );
let boundsMax = vec3( bounds.max[0], bounds.max[1], bounds.max[2] );
let invDir = 1.0 / ray.direction;
let tMinPlane = ( boundsMin - ray.origin ) * invDir;
let tMaxPlane = ( boundsMax - ray.origin ) * invDir;
let tMinHit = vec3f(
min( tMinPlane.x, tMaxPlane.x ),
min( tMinPlane.y, tMaxPlane.y ),
min( tMinPlane.z, tMaxPlane.z )
);
let tMaxHit = vec3f(
max( tMinPlane.x, tMaxPlane.x ),
max( tMinPlane.y, tMaxPlane.y ),
max( tMinPlane.z, tMaxPlane.z )
);
let t0 = max( max( tMinHit.x, tMinHit.y ), tMinHit.z );
let t1 = min( min( tMaxHit.x, tMaxHit.y ), tMaxHit.z );
( *dist ) = max( t0, 0.0 );
return t1 >= ( *dist );
}
`, [ rayStruct, bvhNodeBoundsStruct ] );