-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathmesh-instance.js
More file actions
1443 lines (1240 loc) · 45 KB
/
mesh-instance.js
File metadata and controls
1443 lines (1240 loc) · 45 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 { Debug, DebugHelper } from '../core/debug.js';
import { BoundingBox } from '../core/shape/bounding-box.js';
import { BoundingSphere } from '../core/shape/bounding-sphere.js';
import { BindGroup } from '../platform/graphics/bind-group.js';
import { UniformBuffer } from '../platform/graphics/uniform-buffer.js';
import { VertexBuffer } from '../platform/graphics/vertex-buffer.js';
import { DrawCommands } from '../platform/graphics/draw-commands.js';
import { indexFormatByteSize } from '../platform/graphics/constants.js';
import {
LAYER_WORLD,
MASK_AFFECT_DYNAMIC, MASK_BAKE, MASK_AFFECT_LIGHTMAPPED,
RENDERSTYLE_SOLID,
SHADERDEF_UV0, SHADERDEF_UV1, SHADERDEF_VCOLOR, SHADERDEF_TANGENTS, SHADERDEF_NOSHADOW, SHADERDEF_SKIN,
SHADERDEF_SCREENSPACE, SHADERDEF_MORPH_POSITION, SHADERDEF_MORPH_NORMAL, SHADERDEF_BATCH,
SHADERDEF_LM, SHADERDEF_DIRLM, SHADERDEF_LMAMBIENT, SHADERDEF_INSTANCING, SHADERDEF_MORPH_TEXTURE_BASED_INT,
SHADOW_CASCADE_ALL
} from './constants.js';
import { GraphNode } from './graph-node.js';
import { getDefaultMaterial } from './materials/default-material.js';
import { LightmapCache } from './graphics/lightmap-cache.js';
import { DebugGraphics } from '../platform/graphics/debug-graphics.js';
import { hash32Fnv1a } from '../core/hash.js';
import { array } from '../core/array-utils.js';
import { PickerId } from './picker-id.js';
/**
* @import { BindGroupFormat } from '../platform/graphics/bind-group-format.js'
* @import { Camera } from './camera.js'
* @import { GSplatInstance } from './gsplat/gsplat-instance.js'
* @import { GraphicsDevice } from '../platform/graphics/graphics-device.js'
* @import { Material } from './materials/material.js'
* @import { Mesh } from './mesh.js'
* @import { MorphInstance } from './morph-instance.js'
* @import { CameraShaderParams } from './camera-shader-params.js'
* @import { Scene } from './scene.js'
* @import { ScopeId } from '../platform/graphics/scope-id.js'
* @import { Shader } from '../platform/graphics/shader.js'
* @import { SkinInstance } from './skin-instance.js'
* @import { StencilParameters } from '../platform/graphics/stencil-parameters.js'
* @import { Texture } from '../platform/graphics/texture.js'
* @import { UniformBufferFormat } from '../platform/graphics/uniform-buffer-format.js'
* @import { Vec3 } from '../core/math/vec3.js'
* @import { CameraComponent } from '../framework/components/camera/component.js';
*/
const _tmpAabb = new BoundingBox();
const _tempBoneAabb = new BoundingBox();
const _tempSphere = new BoundingSphere();
/** @type {Set<Mesh>} */
const _meshSet = new Set();
// internal array used to evaluate the hash for the shader instance
const lookupHashes = new Uint32Array(4);
/**
* Internal data structure used to store data used by hardware instancing.
*
* @ignore
*/
class InstancingData {
/** @type {VertexBuffer|null} */
vertexBuffer = null;
/**
* True if the vertex buffer is destroyed when the mesh instance is destroyed.
*
* @type {boolean}
*/
_destroyVertexBuffer = false;
/**
* @param {number} numObjects - The number of objects instanced.
*/
constructor(numObjects) {
this.count = numObjects;
}
destroy() {
if (this._destroyVertexBuffer) {
this.vertexBuffer?.destroy();
}
this.vertexBuffer = null;
}
}
/**
* Internal helper class for storing the shader and related mesh bind group in the shader cache.
*
* @ignore
*/
class ShaderInstance {
/**
* A shader.
*
* @type {Shader|undefined}
*/
shader;
/**
* A bind group storing mesh textures / samplers for the shader. but not the uniform buffer.
*
* @type {BindGroup|null}
*/
bindGroup = null;
/**
* A uniform buffer storing mesh uniforms for the shader.
*
* @type {UniformBuffer|null}
*/
uniformBuffer = null;
/**
* The full array of hashes used to lookup the pipeline, used in case of hash collision.
*
* @type {Uint32Array}
*/
hashes;
/**
* Returns the mesh bind group for the shader.
*
* @param {GraphicsDevice} device - The graphics device.
* @returns {BindGroup} - The mesh bind group.
*/
getBindGroup(device) {
// create bind group
if (!this.bindGroup) {
const shader = this.shader;
Debug.assert(shader);
const bindGroupFormat = shader.meshBindGroupFormat;
Debug.assert(bindGroupFormat);
this.bindGroup = new BindGroup(device, bindGroupFormat);
DebugHelper.setName(this.bindGroup, `MeshBindGroup_${this.bindGroup.id}`);
}
return this.bindGroup;
}
/**
* Returns the uniform buffer for the shader.
*
* @param {GraphicsDevice} device - The graphics device.
* @returns {UniformBuffer} - The uniform buffer.
*/
getUniformBuffer(device) {
// create uniform buffer
if (!this.uniformBuffer) {
const shader = this.shader;
Debug.assert(shader);
const ubFormat = shader.meshUniformBufferFormat;
Debug.assert(ubFormat);
this.uniformBuffer = new UniformBuffer(device, ubFormat, false);
}
return this.uniformBuffer;
}
destroy() {
this.bindGroup?.destroy();
this.bindGroup = null;
this.uniformBuffer?.destroy();
this.uniformBuffer = null;
}
}
/**
* @callback CalculateSortDistanceCallback
* Callback used by {@link Layer} to calculate the "sort distance" for a {@link MeshInstance},
* which determines its place in the render order.
* @param {MeshInstance} meshInstance - The mesh instance.
* @param {Vec3} cameraPosition - The position of the camera.
* @param {Vec3} cameraForward - The forward vector of the camera.
* @returns {void}
*/
/**
* An instance of a {@link Mesh}. A single mesh can be referenced by many mesh instances that can
* have different transforms and materials.
*
* ### Instancing
*
* Hardware instancing lets the GPU draw many copies of the same geometry with a single draw call.
* Use {@link setInstancing} to attach a vertex buffer that holds per-instance data
* (for example a mat4 world-matrix for every instance). Set {@link instancingCount}
* to control how many instances are rendered. Passing `null` to {@link setInstancing}
* disables instancing once again.
*
* ```javascript
* // vb is a vertex buffer with one 4×4 matrix per instance
* meshInstance.setInstancing(vb);
* meshInstance.instancingCount = numInstances;
* ```
*
* **Examples**
*
* - {@link https://playcanvas.github.io/#graphics/instancing-basic graphics/instancing-basic}
* - {@link https://playcanvas.github.io/#graphics/instancing-custom graphics/instancing-custom}
*
* ### GPU-Driven Indirect Rendering (WebGPU Only)
*
* Instead of issuing draw calls from the CPU, parameters are written into a GPU
* storage buffer and executed via indirect draw commands. Allocate one or more slots with
* `GraphicsDevice.getIndirectDrawSlot(count)`, then bind the mesh instance to those slots:
*
* ```javascript
* const slot = app.graphicsDevice.getIndirectDrawSlot(count);
* meshInstance.setIndirect(null, slot, count); // first arg can be a CameraComponent or null
* ```
*
* **Example**
*
* - {@link https://playcanvas.github.io/#compute/indirect-draw compute/indirect-draw}
*
* ### Multi-draw
*
* Multi-draw lets the engine submit multiple sub-draws with a single API call. On WebGL2 this maps
* to the `WEBGL_multi_draw` extension; on WebGPU, to indirect multi-draw. Use {@link setMultiDraw}
* to allocate a {@link DrawCommands} container, fill it with sub-draws using
* {@link DrawCommands#add} and finalize with {@link DrawCommands#update} whenever the data changes.
*
* Support: {@link GraphicsDevice#supportsMultiDraw} is true on WebGPU and commonly true on WebGL2
* (high coverage). When not supported, the engine can still render by issuing a fast internal loop
* of single draws using the multi-draw data.
*
* ```javascript
* // two indexed sub-draws from a single mesh
* const cmd = meshInstance.setMultiDraw(null, 2);
* cmd.add(0, 36, 1, 0);
* cmd.add(1, 60, 1, 36);
* cmd.update(2);
* ```
*
* @category Graphics
*/
class MeshInstance {
/**
* Enable shadow casting for this mesh instance. Use this property to enable/disable shadow
* casting without overhead of removing from scene. Note that this property does not add the
* mesh instance to appropriate list of shadow casters on a {@link Layer}, but allows mesh to
* be skipped from shadow casting while it is in the list already. Defaults to false.
*
* @type {boolean}
*/
castShadow = false;
/**
* Specifies a bitmask that controls which shadow cascades a mesh instance contributes
* to when rendered with a {@link LIGHTTYPE_DIRECTIONAL} light source.
* This setting is only effective if the {@link castShadow} property is enabled.
* Defaults to {@link SHADOW_CASCADE_ALL}, which means the mesh casts shadows into all available cascades.
*
* @type {number}
*/
shadowCascadeMask = SHADOW_CASCADE_ALL;
/**
* Controls whether the mesh instance can be culled by frustum culling (see
* {@link CameraComponent#frustumCulling}). Defaults to true.
*
* @type {boolean}
*/
cull = true;
/**
* Determines the rendering order of mesh instances. Only used when mesh instances are added to
* a {@link Layer} with {@link Layer#opaqueSortMode} or {@link Layer#transparentSortMode}
* (depending on the material) set to {@link SORTMODE_MANUAL}.
*
* @type {number}
*/
drawOrder = 0;
/**
* @type {number}
* @ignore
*/
_drawBucket = 127;
/**
* The graph node defining the transform for this instance.
*
* @type {GraphNode}
*/
node;
/**
* Enable rendering for this mesh instance. Use visible property to enable/disable rendering
* without overhead of removing from scene. But note that the mesh instance is still in the
* hierarchy and still in the draw call list.
*
* @type {boolean}
*/
visible = true;
/**
* Read this value in {@link Scene.EVENT_POSTCULL} event to determine if the object is actually going
* to be rendered.
*
* @type {boolean}
*/
visibleThisFrame = false;
/**
* Negative scale batching support.
*
* @type {number}
* @ignore
*/
flipFacesFactor = 1;
/**
* @type {GSplatInstance|null}
* @ignore
*/
gsplatInstance = null;
/** @ignore */
id = PickerId.get();
/**
* Custom function used to customize culling (e.g. for 2D UI elements).
*
* @type {Function|null}
* @ignore
*/
isVisibleFunc = null;
/**
* @type {InstancingData|null}
* @ignore
*/
instancingData = null;
/**
* @type {DrawCommands|null}
* @ignore
*/
indirectData = null;
/**
* Map of camera to their corresponding indirect draw data. Lazily allocated.
*
* @type {Map<Camera|null, DrawCommands>|null}
* @ignore
*/
drawCommands = null;
/**
* Stores mesh metadata used for indirect rendering. Lazily allocated on first access
* via getIndirectMetaData().
*
* @type {Int32Array|null}
* @ignore
*/
meshMetaData = null;
/**
* @type {Record<string, {scopeId: ScopeId|null, data: any, passFlags: number}>}
* @ignore
*/
parameters = {};
/**
* True if the mesh instance is pickable by the {@link Picker}. Defaults to true.
*
* @type {boolean}
* @ignore
*/
pick = true;
/**
* The stencil parameters for front faces or null if no stencil is enabled.
*
* @type {StencilParameters|null}
* @ignore
*/
stencilFront = null;
/**
* The stencil parameters for back faces or null if no stencil is enabled.
*
* @type {StencilParameters|null}
* @ignore
*/
stencilBack = null;
/**
* True if the material of the mesh instance is transparent. Optimization to avoid accessing
* the material. Updated by the material instance itself.
*
* @ignore
*/
transparent = false;
/** @private */
_aabb = new BoundingBox();
/** @private */
_aabbVer = -1;
/** @private */
_aabbMeshVer = -1;
/**
* @type {BoundingBox|null}
* @private
*/
_customAabb = null;
/** @private */
_updateAabb = true;
/** @private */
_updateAabbFunc = null;
/**
* The internal sorting key used by the shadow renderer.
*
* @ignore
*/
_sortKeyShadow = 0;
/**
* The internal sorting key used by the forward renderer, in case SORTMODE_MATERIALMESH sorting
* is used.
*
* @private
*/
_sortKeyForward = 0;
/**
* The internal sorting key used by the forward renderer, in case SORTMODE_BACK2FRONT or
* SORTMODE_FRONT2BACK sorting is used.
*
* @ignore
*/
_sortKeyDynamic = 0;
/** @private */
_layer = LAYER_WORLD;
/**
* @type {Material|null}
* @private
*/
_material = null;
/**
* @type {SkinInstance|null}
* @private
*/
_skinInstance = null;
/**
* @type {MorphInstance|null}
* @private
*/
_morphInstance = null;
/** @private */
_receiveShadow = true;
/** @private */
_renderStyle = RENDERSTYLE_SOLID;
/** @private */
_screenSpace = false;
/**
* The cache of shaders, indexed by a hash value.
*
* @type {Map<number, ShaderInstance>}
* @private
*/
_shaderCache = new Map();
/**
* 2 byte toggles, 2 bytes light mask; Default value is no toggles and mask = pc.MASK_AFFECT_DYNAMIC
*
* @private
*/
_shaderDefs = MASK_AFFECT_DYNAMIC << 16;
/**
* @type {CalculateSortDistanceCallback|null}
* @private
*/
_calculateSortDistance = null;
/**
* Create a new MeshInstance instance.
*
* @param {Mesh} mesh - The graphics mesh to instance.
* @param {Material} material - The material to use for this mesh instance.
* @param {GraphNode} [node] - The graph node defining the transform for this instance. This
* parameter is optional when used with {@link RenderComponent} and will use the node the
* component is attached to.
* @example
* // Create a mesh instance pointing to a 1x1x1 'cube' mesh
* const mesh = pc.Mesh.fromGeometry(app.graphicsDevice, new pc.BoxGeometry());
* const material = new pc.StandardMaterial();
*
* const meshInstance = new pc.MeshInstance(mesh, material);
*
* const entity = new pc.Entity();
* entity.addComponent('render', {
* meshInstances: [meshInstance]
* });
*
* // Add the entity to the scene hierarchy
* this.app.scene.root.addChild(entity);
*/
constructor(mesh, material, node = null) {
Debug.assert(!(mesh instanceof GraphNode), 'Incorrect parameters for MeshInstance\'s constructor. Use new MeshInstance(mesh, material, node)');
this.node = node; // The node that defines the transform of the mesh instance
this._mesh = mesh; // The mesh that this instance renders
mesh.incRefCount();
this.material = material; // The material with which to render this instance
if (mesh.vertexBuffer) {
const format = mesh.vertexBuffer.format;
this._shaderDefs |= format.hasUv0 ? SHADERDEF_UV0 : 0;
this._shaderDefs |= format.hasUv1 ? SHADERDEF_UV1 : 0;
this._shaderDefs |= format.hasColor ? SHADERDEF_VCOLOR : 0;
this._shaderDefs |= format.hasTangents ? SHADERDEF_TANGENTS : 0;
}
// 64-bit integer key that defines render order of this mesh instance
this.updateKey();
}
/**
* Sets the draw bucket for mesh instances. The draw bucket, an integer from 0 to 255 (default
* 127), serves as the primary sort key for mesh rendering. Meshes are sorted by draw bucket,
* then by sort mode. This setting is only effective when mesh instances are added to a
* {@link Layer} with its {@link Layer#opaqueSortMode} or {@link Layer#transparentSortMode}
* (depending on the material) set to {@link SORTMODE_BACK2FRONT}, {@link SORTMODE_FRONT2BACK},
* or {@link SORTMODE_MATERIALMESH}.
*
* Note: When {@link SORTMODE_BACK2FRONT} is used, a descending sort order is used; otherwise,
* an ascending sort order is used.
*
* @type {number}
*/
set drawBucket(bucket) {
// 8bit integer
this._drawBucket = Math.floor(bucket) & 0xff;
this.updateKey();
}
/**
* Gets the draw bucket for mesh instance.
*
* @type {number}
*/
get drawBucket() {
return this._drawBucket;
}
/**
* Sets the render style of the mesh instance. Can be:
*
* - {@link RENDERSTYLE_SOLID}
* - {@link RENDERSTYLE_WIREFRAME}
* - {@link RENDERSTYLE_POINTS}
*
* Defaults to {@link RENDERSTYLE_SOLID}.
*
* @type {number}
*/
set renderStyle(renderStyle) {
this._renderStyle = renderStyle;
this.mesh.prepareRenderState(renderStyle);
}
/**
* Gets the render style of the mesh instance.
*
* @type {number}
*/
get renderStyle() {
return this._renderStyle;
}
/**
* Sets the graphics mesh being instanced.
*
* @type {Mesh}
*/
set mesh(mesh) {
if (mesh === this._mesh) {
return;
}
if (this._mesh) {
this._mesh.decRefCount();
}
this._mesh = mesh;
if (mesh) {
mesh.incRefCount();
}
}
/**
* Gets the graphics mesh being instanced.
*
* @type {Mesh}
*/
get mesh() {
return this._mesh;
}
/**
* Sets the world space axis-aligned bounding box for this mesh instance.
*
* @type {BoundingBox}
*/
set aabb(aabb) {
this._aabb = aabb;
}
/**
* Gets the world space axis-aligned bounding box for this mesh instance.
*
* @type {BoundingBox}
*/
get aabb() {
// use specified world space aabb
if (!this._updateAabb) {
return this._aabb;
}
// callback function returning world space aabb
if (this._updateAabbFunc) {
return this._updateAabbFunc(this._aabb);
}
// use local space override aabb if specified
let localAabb = this._customAabb;
let toWorldSpace = !!localAabb;
// otherwise evaluate local aabb
if (!localAabb) {
localAabb = _tmpAabb;
if (this.skinInstance) {
// Initialize local bone AABBs if needed
if (!this.mesh.boneAabb) {
const morphTargets = this._morphInstance ? this._morphInstance.morph._targets : null;
this.mesh._initBoneAabbs(morphTargets);
}
// evaluate local space bounds based on all active bones
const boneUsed = this.mesh.boneUsed;
let first = true;
for (let i = 0; i < this.mesh.boneAabb.length; i++) {
if (boneUsed[i]) {
// transform bone AABB by bone matrix
_tempBoneAabb.setFromTransformedAabb(this.mesh.boneAabb[i], this.skinInstance.matrices[i]);
// add them up
if (first) {
first = false;
localAabb.center.copy(_tempBoneAabb.center);
localAabb.halfExtents.copy(_tempBoneAabb.halfExtents);
} else {
localAabb.add(_tempBoneAabb);
}
}
}
toWorldSpace = true;
} else if (this.node._aabbVer !== this._aabbVer || this.mesh._aabbVer !== this._aabbMeshVer) {
// local space bounding box - either from mesh or empty
if (this.mesh) {
localAabb.center.copy(this.mesh.aabb.center);
localAabb.halfExtents.copy(this.mesh.aabb.halfExtents);
} else {
localAabb.center.set(0, 0, 0);
localAabb.halfExtents.set(0, 0, 0);
}
// update local space bounding box by morph targets
if (this.mesh && this.mesh.morph) {
const morphAabb = this.mesh.morph.aabb;
localAabb._expand(morphAabb.getMin(), morphAabb.getMax());
}
toWorldSpace = true;
this._aabbVer = this.node._aabbVer;
this._aabbMeshVer = this.mesh._aabbVer;
}
}
// store world space bounding box
if (toWorldSpace) {
this._aabb.setFromTransformedAabb(localAabb, this.node.getWorldTransform());
}
return this._aabb;
}
/**
* Clear the internal shader cache.
*
* @ignore
*/
clearShaders() {
this._shaderCache.forEach((shaderInstance) => {
shaderInstance.destroy();
});
this._shaderCache.clear();
}
/**
* Returns the shader instance for the specified shader pass and light hash that is compatible
* with this mesh instance.
*
* @param {number} shaderPass - The shader pass index.
* @param {number} lightHash - The hash value of the lights that are affecting this mesh instance.
* @param {Scene} scene - The scene.
* @param {CameraShaderParams} cameraShaderParams - The camera shader parameters.
* @param {UniformBufferFormat} [viewUniformFormat] - The format of the view uniform buffer.
* @param {BindGroupFormat} [viewBindGroupFormat] - The format of the view bind group.
* @param {any} [sortedLights] - Array of arrays of lights.
* @returns {ShaderInstance} - the shader instance.
* @ignore
*/
getShaderInstance(shaderPass, lightHash, scene, cameraShaderParams, viewUniformFormat, viewBindGroupFormat, sortedLights) {
const shaderDefs = this._shaderDefs;
// unique hash for the required shader
lookupHashes[0] = shaderPass;
lookupHashes[1] = lightHash;
lookupHashes[2] = shaderDefs;
lookupHashes[3] = cameraShaderParams.hash;
const hash = hash32Fnv1a(lookupHashes);
// look up the cache
let shaderInstance = this._shaderCache.get(hash);
// cache miss in the shader cache of the mesh instance
if (!shaderInstance) {
const mat = this._material;
// get the shader from the material
shaderInstance = new ShaderInstance();
shaderInstance.shader = mat.variants.get(hash);
shaderInstance.hashes = new Uint32Array(lookupHashes);
// cache miss in the material variants
if (!shaderInstance.shader) {
// marker to allow us to see the source node for shader alloc
DebugGraphics.pushGpuMarker(this.mesh.device, `Node: ${this.node.name}`);
const shader = mat.getShaderVariant({
device: this.mesh.device,
scene: scene,
objDefs: shaderDefs,
cameraShaderParams: cameraShaderParams,
pass: shaderPass,
sortedLights: sortedLights,
viewUniformFormat: viewUniformFormat,
viewBindGroupFormat: viewBindGroupFormat,
vertexFormat: this.mesh.vertexBuffer?.format
});
DebugGraphics.popGpuMarker(this.mesh.device);
// add it to the material variants cache
mat.variants.set(hash, shader);
shaderInstance.shader = shader;
}
// add it to the mesh instance cache
this._shaderCache.set(hash, shaderInstance);
}
Debug.call(() => {
// due to a small number of shaders in the cache, and to avoid performance hit, we're not
// handling the hash collision. This is very unlikely but still possible. Check and report
// if it happens in the debug mode, allowing us to fix the issue.
if (!array.equals(shaderInstance.hashes, lookupHashes)) {
Debug.errorOnce('Hash collision in the shader cache for mesh instance. This is very unlikely but still possible. Please report this issue.');
}
});
return shaderInstance;
}
/**
* Sets the material used by this mesh instance.
*
* @type {Material}
*/
set material(material) {
this.clearShaders();
const prevMat = this._material;
// Remove the material's reference to this mesh instance
if (prevMat) {
prevMat.removeMeshInstanceRef(this);
}
this._material = material;
if (material) {
// Record that the material is referenced by this mesh instance
material.addMeshInstanceRef(this);
// update transparent flag based on material
this.transparent = material.transparent;
this.updateKey();
}
}
/**
* Gets the material used by this mesh instance.
*
* @type {Material}
*/
get material() {
return this._material;
}
/**
* @param {number} shaderDefs - The shader definitions to set.
* @private
*/
_updateShaderDefs(shaderDefs) {
if (shaderDefs !== this._shaderDefs) {
this._shaderDefs = shaderDefs;
this.clearShaders();
}
}
/**
* Sets the callback to calculate sort distance. In some circumstances mesh instances are
* sorted by a distance calculation to determine their rendering order. Set this callback to
* override the default distance calculation, which gives the dot product of the camera forward
* vector and the vector between the camera position and the center of the mesh instance's
* axis-aligned bounding box. This option can be particularly useful for rendering transparent
* meshes in a better order than the default.
*
* @type {CalculateSortDistanceCallback|null}
*/
set calculateSortDistance(calculateSortDistance) {
this._calculateSortDistance = calculateSortDistance;
}
/**
* Gets the callback to calculate sort distance.
*
* @type {CalculateSortDistanceCallback|null}
*/
get calculateSortDistance() {
return this._calculateSortDistance;
}
set receiveShadow(val) {
if (this._receiveShadow !== val) {
this._receiveShadow = val;
this._updateShaderDefs(val ? (this._shaderDefs & ~SHADERDEF_NOSHADOW) : (this._shaderDefs | SHADERDEF_NOSHADOW));
}
}
get receiveShadow() {
return this._receiveShadow;
}
set batching(val) {
this._updateShaderDefs(val ? (this._shaderDefs | SHADERDEF_BATCH) : (this._shaderDefs & ~SHADERDEF_BATCH));
}
get batching() {
return (this._shaderDefs & SHADERDEF_BATCH) !== 0;
}
/**
* Sets the skin instance managing skinning of this mesh instance. Set to null if skinning is
* not used.
*
* @type {SkinInstance|null}
*/
set skinInstance(val) {
this._skinInstance = val;
this._updateShaderDefs(val ? (this._shaderDefs | SHADERDEF_SKIN) : (this._shaderDefs & ~SHADERDEF_SKIN));
this._setupSkinUpdate();
}
/**
* Gets the skin instance managing skinning of this mesh instance.
*
* @type {SkinInstance|null}
*/
get skinInstance() {
return this._skinInstance;
}
/**
* Sets the morph instance managing morphing of this mesh instance. Set to null if morphing is
* not used.
*
* @type {MorphInstance|null}
*/
set morphInstance(val) {
// release existing
this._morphInstance?.destroy();
// assign new
this._morphInstance = val;
let shaderDefs = this._shaderDefs;
shaderDefs = (val && val.morph.morphPositions) ? (shaderDefs | SHADERDEF_MORPH_POSITION) : (shaderDefs & ~SHADERDEF_MORPH_POSITION);
shaderDefs = (val && val.morph.morphNormals) ? (shaderDefs | SHADERDEF_MORPH_NORMAL) : (shaderDefs & ~SHADERDEF_MORPH_NORMAL);
shaderDefs = (val && val.morph.intRenderFormat) ? (shaderDefs | SHADERDEF_MORPH_TEXTURE_BASED_INT) : (shaderDefs & ~SHADERDEF_MORPH_TEXTURE_BASED_INT);
this._updateShaderDefs(shaderDefs);
}
/**
* Gets the morph instance managing morphing of this mesh instance.
*
* @type {MorphInstance|null}
*/
get morphInstance() {
return this._morphInstance;
}
set screenSpace(val) {
if (this._screenSpace !== val) {
this._screenSpace = val;
this._updateShaderDefs(val ? (this._shaderDefs | SHADERDEF_SCREENSPACE) : (this._shaderDefs & ~SHADERDEF_SCREENSPACE));
}
}
get screenSpace() {
return this._screenSpace;
}
set key(val) {
this._sortKeyForward = val;
}
get key() {
return this._sortKeyForward;
}
/**
* Sets the mask controlling which {@link LightComponent}s light this mesh instance, which
* {@link CameraComponent} sees it and in which {@link Layer} it is rendered. Defaults to 1.
*
* @type {number}
*/
set mask(val) {
const toggles = this._shaderDefs & 0x0000FFFF;
this._updateShaderDefs(toggles | (val << 16));
}
/**
* Gets the mask controlling which {@link LightComponent}s light this mesh instance, which
* {@link CameraComponent} sees it and in which {@link Layer} it is rendered.
*
* @type {number}
*/
get mask() {
return this._shaderDefs >> 16;
}
/**
* Sets the number of instances when using hardware instancing to render the mesh.
*
* @type {number}
*/
set instancingCount(value) {