-
-
Notifications
You must be signed in to change notification settings - Fork 163
Expand file tree
/
Copy pathBVHComputeData.js
More file actions
1074 lines (716 loc) · 26.3 KB
/
BVHComputeData.js
File metadata and controls
1074 lines (716 loc) · 26.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Matrix4, Vector4 } from 'three';
import { Mesh, StorageBufferAttribute, StructTypeNode } from 'three/webgpu';
import { storage, wgsl } from 'three/tsl';
import { constants } from './wgsl/common.wgsl.js';
import { rayStruct, bvhNodeStruct, bvhNodeBoundsStruct } from './wgsl/structs.wgsl.js';
import { wgslTagCode, wgslTagFn } from './nodes/WGSLTagFnNode.js';
import { MeshBVH, SkinnedMeshBVH, GeometryBVH, ObjectBVH, SAH } from 'three-mesh-bvh';
// TODO: add ability to easily update a single matrix / scene rearrangement (partial update)
// TODO: add material support w/ function to easily update material
// - add a callback for writing a property for a geometry to a range
// TODO: Add support for other geometry types (tris, lines, custom BVHs etc)
// temporary shim so StructTypeNodes can be passed to storage functions until
// this is fixed in three.js
Object.defineProperty( StructTypeNode.prototype, 'layout', {
get() {
return this;
}
} );
StructTypeNode.prototype.isStruct = true;
//
const isVisible = object => {
let curr = object;
while ( curr ) {
if ( curr.visible === false ) {
return false;
}
curr = curr.parent;
}
return true;
};
const applyBoneTransform = ( () => {
// a vec4-compatible version of SkinnedMesh.applyBoneTransform to support directions, positions
const _base = new Vector4();
const _skinIndex = new Vector4();
const _skinWeight = new Vector4();
const _matrix4 = new Matrix4();
const _vector4 = new Vector4();
return function applyBoneTransform( mesh, index, target ) {
const skeleton = mesh.skeleton;
const geometry = mesh.geometry;
_skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
_skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
if ( target.isVector4 ) {
_base.copy( target );
target.set( 0, 0, 0, 0 );
} else {
_base.set( ...target, 1 );
target.set( 0, 0, 0 );
}
_base.applyMatrix4( mesh.bindMatrix );
for ( let i = 0; i < 4; i ++ ) {
const weight = _skinWeight.getComponent( i );
if ( weight !== 0 ) {
const boneIndex = _skinIndex.getComponent( i );
_matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
target.addScaledVector( _vector4.copy( _base ).applyMatrix4( _matrix4 ), weight );
}
}
if ( target.isVector4 ) {
target.w = _base.w;
}
return target.applyMatrix4( mesh.bindMatrixInverse );
};
} )();
//
// structs
const transformStruct = new StructTypeNode( {
matrixWorld: 'mat4x4f',
inverseMatrixWorld: 'mat4x4f',
nodeOffset: 'uint',
visible: 'uint',
_alignment0: 'uint',
_alignment1: 'uint',
}, 'TransformStruct' );
export const intersectionResultStruct = new StructTypeNode( {
indices: 'vec4u',
normal: 'vec3f',
didHit: 'bool',
barycoord: 'vec3f',
objectIndex: 'uint',
side: 'float',
dist: 'float',
}, 'IntersectionResult' );
//
// node constants
const BYTES_PER_NODE = 6 * 4 + 4 + 4;
const UINT32_PER_NODE = BYTES_PER_NODE / 4;
const IS_LEAFNODE_FLAG = 0xFFFF;
// scratch
const _def = /* @__PURE__ */ new Vector4();
const _vec = /* @__PURE__ */ new Vector4();
const _matrix = /* @__PURE__ */ new Matrix4();
const _inverseMatrix = /* @__PURE__ */ new Matrix4();
// functions
function dereferenceIndex( indexAttr, indirectBuffer ) {
const indexArray = indexAttr ? indexAttr.array : null;
const result = new Uint32Array( indirectBuffer.length * 3 );
for ( let i = 0, l = indirectBuffer.length; i < l; i ++ ) {
const i3 = 3 * i;
const v3 = 3 * indirectBuffer[ i ];
for ( let c = 0; c < 3; c ++ ) {
result[ i3 + c ] = indexArray ? indexArray[ v3 + c ] : v3 + c;
}
}
return result;
}
function getTotalBVHByteLength( bvh ) {
return bvh._roots.reduce( ( v, root ) => v + root.byteLength, 0 );
}
export const intersectsTriangle = wgslTagFn/* wgsl */ `
// fn
fn intersectsTriangle( ray: ${ rayStruct }, a: vec3f, b: vec3f, c: vec3f ) -> ${ intersectionResultStruct } {
// TODO: see if we can remove the "DIST" epsilon and account for it on ray origin bounce positioning
const DET_EPSILON = 1e-15;
const DIST_EPSILON = 1e-5;
var result: ${ intersectionResultStruct };
result.didHit = false;
let edge1 = b - a;
let edge2 = c - a;
let n = cross( edge1, edge2 );
let det = - dot( ray.direction, n );
if ( abs( det ) < DET_EPSILON ) {
return result;
}
let invdet = 1.0 / det;
let AO = ray.origin - a;
let DAO = cross( AO, ray.direction );
let u = dot( edge2, DAO ) * invdet;
if ( u < 0.0 || u > 1.0 ) {
return result;
}
let v = - dot( edge1, DAO ) * invdet;
if ( v < 0.0 || u + v > 1.0 ) {
return result;
}
let t = dot( AO, n ) * invdet;
let w = 1.0 - u - v;
if ( t < DIST_EPSILON ) {
return result;
}
result.didHit = true;
result.barycoord = vec3f( w, u, v );
result.dist = t;
result.side = sign( det );
result.normal = result.side * normalize( n );
return result;
}
`;
export class BVHComputeData {
constructor( bvh, options = {} ) {
// convert the bvh argument to an ObjectBVH. Supports the following as arguments
// - Object3D
// - BufferGeometry
// - GeometryBVH
// - Array of the above
if ( ! ( bvh instanceof ObjectBVH ) ) {
if ( ! Array.isArray( bvh ) ) {
bvh = [ bvh ];
}
const objects = bvh.map( item => {
if ( item.isObject3D ) {
return item;
} else if ( item.isBufferGeometry ) {
return new Mesh( item );
} else if ( item instanceof GeometryBVH ) {
const dummy = new Mesh();
dummy.geometry.boundsTree = item;
return dummy;
}
} );
bvh = new ObjectBVH( objects, { strategy: SAH, maxLeafSize: 1 } );
}
const {
attributes = { position: 'vec4f' },
autogenerateBvh = true,
} = options;
this._bvhCache = new Map();
this.autogenerateBvh = autogenerateBvh;
this.attributes = attributes;
this.bvh = bvh;
this.storage = {
index: null,
attributes: null,
nodes: null,
transforms: null,
};
this.structs = {
transform: transformStruct,
attributes: null,
};
this.fns = {
raycastFirstHit: null,
};
}
getShapecastFn( options ) {
// TODO: test with and verify use with TSL Fn - both passing them as arguments,
// calling the function from a TSL Fn.
// TODO: revisit the semantics and mental model of "transformShapeFn" and "transformResultFn".
// Are they "before" and "after" hooks? Should they include words implying a direction of transform?
// eg "toLocal" / "toWorld"?
const {
name = `bvh_shapecast_fn_${ Math.random().toString( 36 ).substring( 2, 7 ) }`,
shapeStruct,
resultStruct = null,
boundsOrderFn = null,
intersectsBoundsFn,
intersectRangeFn,
transformShapeFn = null,
transformResultFn = null,
} = options;
const { storage } = this;
const { BVH_STACK_DEPTH } = constants;
// handle optional functions
let transformResultSnippet = '';
if ( transformResultFn ) {
transformResultSnippet = wgslTagCode/* wgsl */`${ transformResultFn }( result, i );`;
}
let transformShapeSnippet = '';
if ( transformShapeFn ) {
transformShapeSnippet = wgslTagCode/* wgsl */`${ transformShapeFn }( &localShape, i );`;
}
let leftToRightSnippet = '';
if ( boundsOrderFn ) {
leftToRightSnippet = wgslTagCode/* wgsl */`
let leftToRight = ${ boundsOrderFn }( shape, splitAxis, node );
c1 = select( rightIndex, leftIndex, leftToRight );
c2 = select( leftIndex, rightIndex, leftToRight );
`;
}
const resultPtrSnippet = resultStruct ? wgslTagCode/* wgsl */`result: ptr<function, ${ resultStruct }>` : '';
const resultArg = resultStruct ? 'result' : '';
const getFnBody = leafSnippet => {
// returns a function with a snippet inserted for the leaf intersection test
return wgslTagCode/* wgsl */`
var pointer: i32 = 0;
var stack: array<u32, ${ BVH_STACK_DEPTH }>;
stack[ 0 ] = rootNodeIndex;
loop {
if ( pointer < 0 || pointer >= i32( ${ BVH_STACK_DEPTH } ) ) {
break;
}
let nodeIndex = stack[ pointer ];
let node = ${ storage.nodes }[ nodeIndex ];
pointer = pointer - 1;
if ( ${ intersectsBoundsFn }( shape, node.bounds, ${ resultArg } ) == 0u ) {
continue;
}
let infoX = node.splitAxisOrTriangleCount;
let infoY = node.rightChildOrTriangleOffset;
let isLeaf = ( infoX & 0xffff0000u ) != 0u;
if ( isLeaf ) {
let count = infoX & 0x0000ffffu;
let offset = infoY;
${ leafSnippet }
} else {
let leftIndex = nodeIndex + 1u;
let splitAxis = infoX & 0x0000ffffu;
let rightIndex = nodeIndex + infoY;
var c1 = rightIndex;
var c2 = leftIndex;
${ leftToRightSnippet }
pointer = pointer + 1;
stack[ pointer ] = c2;
pointer = pointer + 1;
stack[ pointer ] = c1;
}
}
`;
};
const blasFn = wgslTagFn/* wgsl */`
// fn
fn ${ name }_blas( shape: ${ shapeStruct }, rootNodeIndex: u32, ${ resultPtrSnippet } ) -> bool {
var didHit = false;
${ getFnBody( wgslTagCode/* wgsl */`
didHit = ${ intersectRangeFn }( shape, offset, count, ${ resultArg } ) || didHit;
` ) }
return didHit;
}
`;
const tlasFn = wgslTagFn/* wgsl */`
// fn
fn ${ name }( shape: ${ shapeStruct }, ${ resultPtrSnippet } ) -> bool {
const rootNodeIndex = 0u;
var didHit = false;
${ getFnBody( wgslTagCode/* wgsl */`
for ( var i = offset; i < offset + count; i ++ ) {
let transform = ${ storage.transforms }[ i ];
if ( transform.visible == 0u ) {
continue;
}
// Transform shape into object local space
var localShape = shape;
${ transformShapeSnippet }
if ( ${ blasFn }( localShape, transform.nodeOffset, ${ resultArg } ) ) {
${ transformResultSnippet }
didHit = true;
}
}
` ) }
return didHit;
}
`;
tlasFn.outputType = resultStruct;
tlasFn.functionName = name;
return tlasFn;
}
update() {
const self = this;
const { attributes, structs, bvh } = this;
// collect the BVHs
const bvhInfo = [];
const transformInfo = [];
// accumulate the sizes of the bvh nodes buffer, number of objects, and geometry buffers
let bvhNodesBufferLength = getTotalBVHByteLength( bvh );
let indexBufferLength = 0;
let attributesBufferLength = 0;
bvh.primitiveBuffer.forEach( compositeId => {
const object = bvh.getObjectFromId( compositeId );
const instanceId = bvh.getInstanceFromId( compositeId );
const range = { start: 0, count: 0, vertexStart: 0, vertexCount: 0 };
const primBvh = this.getBVH( object, instanceId, range );
if ( ! primBvh ) {
throw new Error( 'BVHComputeData: BVH not found.' );
}
// if we haven't added this bvh, yet
if ( ! bvhInfo.find( info => info.bvh === primBvh ) ) {
// save the geometry info to write later and increment the buffer sizes
const info = {
index: bvhInfo.length,
bvh: primBvh,
range: range,
bvhNodeOffsets: null,
indexBufferOffset: null,
};
// increase the buffer sizes for bvh and geometry
bvhNodesBufferLength += getTotalBVHByteLength( primBvh );
indexBufferLength += info.range.count;
attributesBufferLength += info.range.vertexCount;
bvhInfo.push( info );
}
// save the index of the bvh associated with this transform
const data = bvhInfo.find( info => primBvh === info.bvh );
primBvh._roots.forEach( ( root, i ) => {
transformInfo.push( {
data,
root: i,
object,
instanceId,
compositeId,
} );
} );
} );
//
// NOTE: These buffer lengths are increased to a minimum size of 2 to avoid the TSL of converting storage buffers
// with length 1 being converted to a scalar value.
// TODO: remove this when fixed in three
const transformBufferLength = Math.max( transformInfo.length, 2 );
indexBufferLength = Math.max( indexBufferLength, 2 );
attributesBufferLength = Math.max( attributesBufferLength, 2 );
// construct the attribute struct
const attributeStruct = new StructTypeNode( attributes, 'bvh_GeometryStruct' );
// write the geometry buffer attributes & bvh data
let attributesOffset = 0;
let indexOffset = 0;
let nodeWriteOffset = 0;
const indexBuffer = new Uint32Array( indexBufferLength );
const attributesBuffer = new ArrayBuffer( attributesBufferLength * attributeStruct.getLength() * 4 );
const bvhNodesBuffer = new ArrayBuffer( bvhNodesBufferLength );
// append TLAS data
appendBVHData( bvh, 0, transformInfo, 0, bvhNodesBuffer, true );
nodeWriteOffset += getTotalBVHByteLength( bvh ) / BYTES_PER_NODE;
bvhInfo.forEach( info => {
// append bvh data
const bvhNodeOffsets = appendBVHData( info.bvh, indexOffset / 3, transformInfo, nodeWriteOffset, bvhNodesBuffer, false );
info.bvhNodeOffsets = bvhNodeOffsets;
// append geometry data
appendIndexData( info.bvh, info.range, attributesOffset, indexOffset, indexBuffer );
appendGeometryData( info.bvh, info.range, attributesOffset, attributesBuffer );
info.indexBufferOffset = indexOffset;
// step the write offsets forward
indexOffset += info.range.count;
attributesOffset += info.range.vertexCount;
nodeWriteOffset += getTotalBVHByteLength( info.bvh ) / BYTES_PER_NODE;
} );
//
// write the transforms
const transformArrayBuffer = new ArrayBuffer( structs.transform.getLength() * transformBufferLength * 4 );
transformInfo.forEach( ( info, i ) => {
_inverseMatrix.copy( bvh.matrixWorld ).invert();
this.writeTransformData( info, _inverseMatrix, i, transformArrayBuffer );
} );
//
// set up the storage buffers
// if itemSize for StorageBufferAttribute == arraySize,
// then buffer is treated not as array of structs, but as a single struct
// And that breaks code. For now itemSize = 1 does not seem to break anything
const bvhNodesStorage = storage( new StorageBufferAttribute( new Uint32Array( bvhNodesBuffer ), 1 ), bvhNodeStruct ).toReadOnly().setName( 'bvh_nodes' );
const transformsBuffer = new StorageBufferAttribute( new Uint32Array( transformArrayBuffer ), 1 );
const transformsStorage = storage( transformsBuffer, structs.transform ).toReadOnly().setName( 'bvh_transforms' );
const indexStorage = storage( new StorageBufferAttribute( indexBuffer, 1 ), 'uint' ).toReadOnly().setName( 'bvh_index' );
const attributesStorage = storage( new StorageBufferAttribute( new Uint32Array( attributesBuffer ), attributeStruct.getLength() ), attributeStruct ).toReadOnly().setName( 'bvh_attributes' );
this.storage.transforms = transformsStorage;
this.storage.nodes = bvhNodesStorage;
this.storage.index = indexStorage;
this.storage.attributes = attributesStorage;
this.structs.attributes = attributeStruct;
this._initFns();
this._bvhCache.clear();
function appendBVHData( bvh, geometryOffset, transformInfo, nodeWriteOffset, target, tlas = false ) {
const targetU16 = new Uint16Array( target );
const targetU32 = new Uint32Array( target );
const targetF32 = new Float32Array( target );
const result = [];
let tlasOffset = 0;
bvh._roots.forEach( root => {
const rootBuffer16 = new Uint16Array( root );
const rootBuffer32 = new Uint32Array( root );
result.push( nodeWriteOffset );
for ( let i = 0, l = root.byteLength / BYTES_PER_NODE; i < l; i ++ ) {
const r32 = i * UINT32_PER_NODE;
const r16 = r32 * 2;
const n32 = nodeWriteOffset * UINT32_PER_NODE;
const n16 = n32 * 2;
// write bounds
const view = new Float32Array( root, i * BYTES_PER_NODE, 6 );
if ( i === 0 ) {
// if we're copying the root then check for cases where there are no primitives and therefore
// be a bounds of [ Infinity, - Infinity ]. Convert this to [ 1, - 1 ] for reliable GPU behavior.
for ( let i = 0; i < 3; i ++ ) {
const vMin = view[ i + 0 ];
const vMax = view[ i + 3 ];
if ( vMin > vMax ) {
targetF32[ n32 + i + 0 ] = 1;
targetF32[ n32 + i + 3 ] = - 1;
} else {
targetF32[ n32 + i + 0 ] = vMin;
targetF32[ n32 + i + 3 ] = vMax;
}
}
} else {
targetF32.set( view, n32 );
}
const isLeaf = IS_LEAFNODE_FLAG === rootBuffer16[ r16 + 15 ];
if ( isLeaf ) {
if ( tlas ) {
// 0xFFFF == mesh leaf, 0xFF00 == TLAS leaf
targetU32[ n32 + 6 ] = tlasOffset;
targetU16[ n16 + 15 ] = 0xFF00;
const count = rootBuffer16[ r16 + 14 ];
// const offset = rootBuffer32[ r32 + 6 ];
// each root is expanded into a separate transform so we need to expand
// the embedded offsets and counts.
let rootsCount = 0;
for ( let o = 0; o < count; o ++ ) {
const roots = transformInfo[ tlasOffset ].data.bvh._roots.length;
tlasOffset += roots;
rootsCount += roots;
}
targetU16[ n16 + 14 ] = rootsCount;
} else {
targetU32[ n32 + 6 ] = rootBuffer32[ r32 + 6 ] + geometryOffset;
targetU16[ n16 + 14 ] = rootBuffer16[ r16 + 14 ];
targetU16[ n16 + 15 ] = IS_LEAFNODE_FLAG;
}
} else {
targetU32[ n32 + 6 ] = rootBuffer32[ r32 + 6 ];
targetU32[ n32 + 7 ] = rootBuffer32[ r32 + 7 ];
}
nodeWriteOffset ++;
}
} );
return result;
}
function appendIndexData( bvh, range, valueOffset, writeOffset, target ) {
const { geometry } = bvh;
const { start, count, vertexStart } = range;
if ( bvh.indirect ) {
const dereferencedIndex = dereferenceIndex( geometry.index, bvh._indirectBuffer );
for ( let i = 0; i < dereferencedIndex.length; i ++ ) {
target[ i + writeOffset ] = dereferencedIndex[ i ] - vertexStart + valueOffset;
}
} else if ( geometry.index ) {
for ( let i = 0; i < count; i ++ ) {
target[ i + writeOffset ] = geometry.index.getX( i + start ) - vertexStart + valueOffset;
}
} else {
for ( let i = 0; i < count; i ++ ) {
target[ i + writeOffset ] = i + start + valueOffset;
}
}
}
function appendGeometryData( bvh, range, writeOffset, target ) {
// if "mesh" is present then it is assumed to be a SkinnedMeshBVH
const { geometry, mesh = null } = bvh;
const { vertexStart, vertexCount } = range;
const attributesBufferF32 = new Float32Array( target );
const attrStructLength = attributeStruct.getLength();
attributeStruct.membersLayout.forEach( ( { name }, interleavedOffset ) => {
// TODO: we should be able to have access to memory layout offsets here via the struct
// API but it's not currently available.
const attr = geometry.attributes[ name ];
self.getDefaultAttributeValue( name, _def );
for ( let i = 0; i < vertexCount; i ++ ) {
if ( attr ) {
_vec.fromBufferAttribute( attr, i + vertexStart );
switch ( attr.itemSize ) {
case 1:
_vec.y = _def.y;
_vec.z = _def.z;
_vec.w = _def.w;
break;
case 2:
_vec.z = _def.z;
_vec.w = _def.w;
break;
case 3:
_vec.w = _def.w;
break;
}
if ( mesh && ( name === 'position' || name === 'normal' || name === 'tangent' ) ) {
applyBoneTransform( mesh, i + vertexStart, _vec );
}
} else {
_vec.copy( _def );
}
_vec.toArray( attributesBufferF32, ( writeOffset + i ) * attrStructLength + interleavedOffset * 4 );
}
} );
}
}
_initFns() {
const { storage, structs, fns } = this;
// raycast first hit
const scratchRayScalar = wgsl( /* wgsl */`
var<private> bvh_rayScalar = 1.0;
` );
fns.raycastFirstHit = this.getShapecastFn( {
name: 'bvh_RaycastFirstHit',
shapeStruct: rayStruct,
resultStruct: intersectionResultStruct,
boundsOrderFn: wgslTagFn/* wgsl */`
fn getBoundsOrder( ray: ${ rayStruct }, splitAxis: u32, node: ${ bvhNodeStruct } ) -> bool {
return ray.direction[ splitAxis ] >= 0.0;
}
`,
intersectsBoundsFn: wgslTagFn/* wgsl */`
${ [ scratchRayScalar ] }
fn rayIntersectsBounds( ray: ${ rayStruct }, bounds: ${ bvhNodeBoundsStruct }, result: ptr<function, ${ intersectionResultStruct }> ) -> u32 {
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 );
let dist = max( t0, 0.0 );
if ( t1 < dist ) {
return 0u;
} else if ( result.didHit && dist * bvh_rayScalar >= result.dist ) {
return 0u;
} else {
return 1u;
}
}
`,
intersectRangeFn: wgslTagFn/* wgsl */`
${ [ scratchRayScalar ] }
fn intersectRange( ray: ${ rayStruct }, offset: u32, count: u32, result: ptr<function, ${ intersectionResultStruct }> ) -> bool {
var didHit = false;
for ( var ti = offset; ti < offset + count; ti = ti + 1u ) {
let i0 = ${ storage.index }[ ti * 3u ];
let i1 = ${ storage.index }[ ti * 3u + 1u ];
let i2 = ${ storage.index }[ ti * 3u + 2u ];
let a = ${ storage.attributes }[ i0 ].position.xyz;
let b = ${ storage.attributes }[ i1 ].position.xyz;
let c = ${ storage.attributes }[ i2 ].position.xyz;
var triResult = ${ intersectsTriangle }( ray, a, b, c );
triResult.dist *= bvh_rayScalar;
if ( triResult.didHit && ( ! result.didHit || triResult.dist < result.dist ) ) {
result.didHit = true;
result.dist = triResult.dist;
result.normal = triResult.normal;
result.side = triResult.side;
result.barycoord = triResult.barycoord;
result.indices = vec4u( i0, i1, i2, ti );
didHit = true;
}
}
return didHit;
}
`,
transformShapeFn: wgslTagFn/* wgsl */`
${ [ scratchRayScalar ] }
fn transformRay( ray: ptr<function, ${ rayStruct }>, objectIndex: u32 ) -> void {
let toLocal = ${ storage.transforms }[ objectIndex ].inverseMatrixWorld;
ray.origin = ( toLocal * vec4f( ray.origin, 1.0 ) ).xyz;
ray.direction = ( toLocal * vec4f( ray.direction, 0.0 ) ).xyz;
let len = length( ray.direction );
ray.direction /= len;
bvh_rayScalar = 1.0 / len;
}
`,
transformResultFn: wgslTagFn/* wgsl */`
fn transformResult( hit: ptr<function, ${ intersectionResultStruct }>, objectIndex: u32 ) -> void {
let toLocal = ${ storage.transforms }[ objectIndex ].inverseMatrixWorld;
hit.normal = normalize( ( transpose( toLocal ) * vec4f( hit.normal, 0.0 ) ).xyz );
hit.objectIndex = objectIndex;
}
`,
} );
const interpolateBody = structs
.attributes
.membersLayout
.map( ( { name } ) => {
return `result.${ name } = a0.${ name } * barycoord.x + a1.${ name } * barycoord.y + a2.${ name } * barycoord.z;`;
} ).join( '\n' );
fns.sampleTrianglePoint = wgslTagFn/* wgsl */`
// fn
fn bvh_sampleTrianglePoint( barycoord: vec3f, indices: vec3u ) -> ${ structs.attributes } {
var result: ${ structs.attributes };
var a0 = ${ storage.attributes }[ indices.x ];
var a1 = ${ storage.attributes }[ indices.y ];
var a2 = ${ storage.attributes }[ indices.z ];
${ interpolateBody }
return result;
}
`;
}
writeTransformData( info, premultiplyMatrix, writeOffset, targetBuffer ) {
const { structs } = this;
const transformBufferF32 = new Float32Array( targetBuffer );
const transformBufferU32 = new Uint32Array( targetBuffer );
const { object, instanceId, root, data } = info;
const { bvhNodeOffsets } = data;
if ( object.isInstancedMesh || object.isBatchedMesh ) {
object.getMatrixAt( instanceId, _matrix );
_matrix.premultiply( object.matrixWorld );
} else {
_matrix.copy( object.matrixWorld );
}
// write transform
_matrix.premultiply( premultiplyMatrix );
_matrix.toArray( transformBufferF32, writeOffset * structs.transform.getLength() );
// write inverse transform
_matrix.invert();
_matrix.toArray( transformBufferF32, writeOffset * structs.transform.getLength() + 16 );
// write node offset
transformBufferU32[ writeOffset * structs.transform.getLength() + 32 ] = bvhNodeOffsets[ root ];
let visible = isVisible( object );
if ( object.isBatchedMesh ) {
visible = visible && object.getVisibleAt( instanceId );
}
transformBufferU32[ writeOffset * structs.transform.getLength() + 33 ] = visible ? 1 : 0;
}
getBVH( object, instanceId, rangeTarget ) {
const { autogenerateBvh, _bvhCache } = this;
let bvh = null;
if ( object.boundsTree || object.isSkinnedMesh ) {
// this is a case where a mesh has morph targets and skinned meshes