Repository navigation
Expand file tree
/
Copy pathModelInstanceCollection.js
More file actions
1789 lines (1559 loc) · 61.9 KB
/
Copy pathModelInstanceCollection.js
File metadata and controls
1789 lines (1559 loc) · 61.9 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 BoundingSphere from "../Core/BoundingSphere.js";
// import Cartesian3 from "../Core/Cartesian3.js";
// import clone from "../Core/clone.js";
// import Color from "../Core/Color.js";
// import ComponentDatatype from "../Core/ComponentDatatype.js";
// import defaultValue from "../Core/defaultValue.js";
// import defer from "../Core/defer.js";
// import defined from "../Core/defined.js";
// import deprecationWarning from "../Core/deprecationWarning.js";
// import destroyObject from "../Core/destroyObject.js";
// import DeveloperError from "../Core/DeveloperError.js";
// import ImageBasedLighting from "./ImageBasedLighting.js";
// import Matrix4 from "../Core/Matrix4.js";
// import PrimitiveType from "../Core/PrimitiveType.js";
// import Resource from "../Core/Resource.js";
// import RuntimeError from "../Core/RuntimeError.js";
// import Transforms from "../Core/Transforms.js";
// import Buffer from "../Renderer/Buffer.js";
// import BufferUsage from "../Renderer/BufferUsage.js";
// import DrawCommand from "../Renderer/DrawCommand.js";
// import Pass from "../Renderer/Pass.js";
// import RenderState from "../Renderer/RenderState.js";
// import ShaderSource from "../Renderer/ShaderSource.js";
// import ForEach from "./GltfPipeline/ForEach.js";
// import Model from "./Model.js";
// import ModelInstance from "./ModelInstance.js";
// import ModelUtility from "./ModelUtility.js";
// import SceneMode from "./SceneMode.js";
// import ShadowMode from "./ShadowMode.js";
// import SplitDirection from "./SplitDirection.js";
import * as Cesium from 'cesium';
const {
BoundingSphere,
Cartesian3,
clone,
Color,
ComponentDatatype,
// defaultValue,
defer,
defined,
deprecationWarning,
destroyObject,
DeveloperError,
ImageBasedLighting,
Quaternion,
Matrix3,
Matrix4,
PrimitiveType,
Resource,
RuntimeError,
Transforms,
Buffer,
BufferUsage,
DrawCommand,
Pass,
RenderState,
ShaderSource,
ForEach,
Model,
// ModelInstance,
ModelUtility,
SceneMode,
ShadowMode,
SplitDirection,
} = Cesium;
class ModelInstance {
get instanceId() { return this._instanceId; }
get model() { return this.primitive?._model; }
get modelMatrix() { return Matrix4.clone(this._modelMatrix); }
set modelMatrix(value) {
Matrix4.clone(value, this._modelMatrix);
// this.primitive.expandBoundingSphere(this._modelMatrix);
this.primitive._dirty = true;
}
constructor(collection, modelMatrix, instanceId) {
/** @type {ModelInstanceCollection} */
this.primitive = collection;
this._modelMatrix = Matrix4.clone(modelMatrix);
this._instanceId = instanceId;
}
}
const LoadState = {
NEEDS_LOAD: 0,
LOADING: 1,
LOADED: 2,
FAILED: 3,
};
/**
* A 3D model instance collection. All instances reference the same underlying model, but have unique
* per-instance properties like model matrix, pick id, etc.
*
* Instances are rendered relative-to-center and for best results instances should be positioned close to one another.
* Otherwise there may be precision issues if, for example, instances are placed on opposite sides of the globe.
*
* @alias ModelInstanceCollection
* @constructor
*
* @param {Object} options Object with the following properties:
* @param {Object[]} [options.instances] An array of instances, where each instance contains a modelMatrix and optional batchId when options.batchTable is defined.
* @param {Cesium3DTileBatchTable} [options.batchTable] The batch table of the instanced 3D Tile.
* @param {Resource|String} [options.url] The url to the .gltf file.
* @param {Object} [options.requestType] The request type, used for request prioritization
* @param {Object|ArrayBuffer|Uint8Array} [options.gltf] A glTF JSON object, or a binary glTF buffer.
* @param {Resource|String} [options.basePath=''] The base path that paths in the glTF JSON are relative to.
* @param {Boolean} [options.dynamic=false] Hint if instance model matrices will be updated frequently.
* @param {Boolean} [options.show=true] Determines if the collection will be shown.
* @param {Boolean} [options.allowPicking=true] When <code>true</code>, each instance is pickable with {@link Scene#pick}.
* @param {Boolean} [options.asynchronous=true] Determines if model WebGL resource creation will be spread out over several frames or block until completion once all glTF files are loaded.
* @param {Boolean} [options.incrementallyLoadTextures=true] Determine if textures may continue to stream in after the model is loaded.
* @param {ShadowMode} [options.shadows=ShadowMode.ENABLED] Determines whether the collection casts or receives shadows from light sources.
* @param {Cartesian3} [options.lightColor] The light color when shading models. When <code>undefined</code> the scene's light color is used instead.
* @param {ImageBasedLighting} [options.imageBasedLighting] The properties for managing image-based lighting for this tileset.
* @param {Boolean} [options.backFaceCulling=true] Whether to cull back-facing geometry. When true, back face culling is determined by the glTF material's doubleSided property; when false, back face culling is disabled.
* @param {Boolean} [options.showCreditsOnScreen=false] Whether to display the credits of this model on screen.
* @param {SplitDirection} [options.splitDirection=SplitDirection.NONE] The {@link SplitDirection} split to apply to this collection.
* @param {Boolean} [options.debugShowBoundingVolume=false] For debugging only. Draws the bounding sphere for the collection.
* @param {Boolean} [options.debugWireframe=false] For debugging only. Draws the instances in wireframe.
* @exception {DeveloperError} Must specify either <options.gltf> or <options.url>, but not both.
* @exception {DeveloperError} Shader program cannot be optimized for instancing. Parameters cannot have any of the following semantics: MODEL, MODELINVERSE, MODELVIEWINVERSE, MODELVIEWPROJECTIONINVERSE, MODELINVERSETRANSPOSE.
*
* @private
*/
function ModelInstanceCollection(options) {
options = options ?? {};
//>>includeStart('debug', pragmas.debug);
if (!defined(options.gltf) && !defined(options.url)) {
throw new DeveloperError("Either options.gltf or options.url is required.");
}
if (defined(options.gltf) && defined(options.url)) {
throw new DeveloperError(
"Cannot pass in both options.gltf and options.url."
);
}
//>>includeEnd('debug');
this._buffers = [];
this.show = options.show ?? true;
this._instancingSupported = false;
this._dynamic = options.dynamic ?? false;
this._allowPicking = options.allowPicking ?? true;
this._ready = false;
this._readyPromise = defer();
this._state = LoadState.NEEDS_LOAD;
this._dirty = true; // false;
// Undocumented options
this._cull = options.cull ?? true;
this._opaquePass = options.opaquePass ?? Pass.OPAQUE;
/** @type {ModelInstance[]} */
this._instances = createInstances(this, options.instances);
/** @type {number} 这个属性是为了用户修改 instances 的长度时,标记为 _dirty */
this._instanceLength = this._instances.length;
// When the model instance collection is backed by an i3dm tile,
// use its batch table resources to modify the shaders, attributes, and uniform maps.
this._batchTable = options.batchTable;
this._model = undefined;
/** @type {Float32Array} */
this._vertexBufferTypedArray = undefined; // Hold onto the vertex buffer contents when dynamic is true
/** @type {Cesium.Buffer} */
this._vertexBuffer = undefined;
this._batchIdBuffer = undefined;
this._instancedUniformsByProgram = undefined;
this._drawCommands = [];
this._modelCommands = undefined;
this._renderStates = undefined;
this._disableCullingRenderStates = undefined;
/** @type {Cesium.BoundingSphere} new 的时候根据 instance matrices 设置,所以需要动态更新时不准确 */
// this._boundingSphere = createBoundingSphere(this);
/** @type {Cesium.Cartesian3} new 的时候根据 instance matrices 设置,所以需要动态更新时不准确 */
// this._center = Cartesian3.clone(this._boundingSphere.center);
this._rtcTransform = new Matrix4();
this._rtcModelView = new Matrix4(); // Holds onto uniform
this._mode = undefined;
this.modelMatrix = Matrix4.clone(Matrix4.IDENTITY);
this._modelMatrix = Matrix4.clone(this.modelMatrix);
// Passed on to Model
this._url = Resource.createIfNeeded(options.url);
this._requestType = options.requestType;
this._gltf = options.gltf;
this._basePath = Resource.createIfNeeded(options.basePath);
this._asynchronous = options.asynchronous;
this._incrementallyLoadTextures = options.incrementallyLoadTextures;
this._upAxis = options.upAxis; // Undocumented option
this._forwardAxis = options.forwardAxis; // Undocumented option
this.shadows = options.shadows ?? ShadowMode.ENABLED;
this._shadows = this.shadows;
this._pickIdLoaded = options.pickIdLoaded;
/**
* The {@link SplitDirection} to apply to this collection.
*
* @type {SplitDirection}
* @default {@link SplitDirection.NONE}
*/
this.splitDirection = options.splitDirection ?? SplitDirection.NONE;
this.debugShowBoundingVolume = options.debugShowBoundingVolume ?? false;
this._debugShowBoundingVolume = false;
this.debugWireframe = options.debugWireframe ?? false;
this._debugWireframe = false;
if (defined(options.imageBasedLighting)) {
this._imageBasedLighting = options.imageBasedLighting;
this._shouldDestroyImageBasedLighting = false;
} else {
this._imageBasedLighting = new ImageBasedLighting();
this._shouldDestroyImageBasedLighting = true;
}
this.backFaceCulling = options.backFaceCulling ?? true;
this._backFaceCulling = this.backFaceCulling;
this.showCreditsOnScreen = options.showCreditsOnScreen ?? false;
}
Object.defineProperties(ModelInstanceCollection.prototype, {
allowPicking: {
get: function () {
return this._allowPicking;
},
},
instances: {
get: function() {
return this._instances;
}
},
length: {
get: function () {
return this._instances.length;
},
},
activeAnimations: {
get: function () {
return this._model.activeAnimations;
},
},
ready: {
get: function () {
return this._ready;
},
},
readyPromise: {
get: function () {
return this._readyPromise.promise;
},
},
imageBasedLighting: {
get: function () {
return this._imageBasedLighting;
},
set: function (value) {
if (value !== this._imageBasedLighting) {
if (
this._shouldDestroyImageBasedLighting &&
!this._imageBasedLighting.isDestroyed()
) {
this._imageBasedLighting.destroy();
}
this._imageBasedLighting = value;
this._shouldDestroyImageBasedLighting = false;
}
},
},
});
function createInstances(collection, instancesOptions) {
instancesOptions = instancesOptions ?? [];
const length = instancesOptions.length;
const instances = new Array(length);
for (let i = 0; i < length; ++i) {
const instanceOptions = instancesOptions[i];
const modelMatrix = instanceOptions.modelMatrix;
const instanceId = instanceOptions.batchId ?? i;
instances[i] = new ModelInstance(collection, modelMatrix, instanceId);
}
return instances;
}
function createBoundingSphere(collection) {
const instancesLength = collection.length;
const points = new Array(instancesLength);
for (let i = 0; i < instancesLength; ++i) {
points[i] = Matrix4.getTranslation(
collection._instances[i]._modelMatrix,
new Cartesian3()
);
}
return BoundingSphere.fromPoints(points);
}
const scratchCartesian = new Cartesian3();
const scratchMatrix = new Matrix4();
// ModelInstanceCollection.prototype.expandBoundingSphere = function (instanceModelMatrix) {
// const translation = Matrix4.getTranslation(instanceModelMatrix, scratchCartesian);
// BoundingSphere.expand(this._boundingSphere, translation, this._boundingSphere);
// };
function getCheckUniformSemanticFunction(
modelSemantics,
supportedSemantics,
programId,
uniformMap
) {
return function (uniform, uniformName) {
const semantic = uniform.semantic;
if (defined(semantic) && modelSemantics.indexOf(semantic) > -1) {
if (supportedSemantics.indexOf(semantic) > -1) {
uniformMap[uniformName] = semantic;
} else {
throw new RuntimeError(
`${
"Shader program cannot be optimized for instancing. " + 'Uniform "'
}${uniformName}" in program "${programId}" uses unsupported semantic "${semantic}"`
);
}
}
};
}
function getInstancedUniforms(collection, programId) {
if (defined(collection._instancedUniformsByProgram)) {
return collection._instancedUniformsByProgram[programId];
}
const instancedUniformsByProgram = {};
collection._instancedUniformsByProgram = instancedUniformsByProgram;
// When using CESIUM_RTC_MODELVIEW the CESIUM_RTC center is ignored. Instances are always rendered relative-to-center.
const modelSemantics = [
"MODEL",
"MODELVIEW",
"CESIUM_RTC_MODELVIEW",
"MODELVIEWPROJECTION",
"MODELINVERSE",
"MODELVIEWINVERSE",
"MODELVIEWPROJECTIONINVERSE",
"MODELINVERSETRANSPOSE",
"MODELVIEWINVERSETRANSPOSE",
];
const supportedSemantics = [
"MODELVIEW",
"CESIUM_RTC_MODELVIEW",
"MODELVIEWPROJECTION",
"MODELVIEWINVERSETRANSPOSE",
];
const techniques = collection._model._sourceTechniques;
for (const techniqueId in techniques) {
if (techniques.hasOwnProperty(techniqueId)) {
const technique = techniques[techniqueId];
const program = technique.program;
// Different techniques may share the same program, skip if already processed.
// This assumes techniques that share a program do not declare different semantics for the same uniforms.
if (!defined(instancedUniformsByProgram[program])) {
const uniformMap = {};
instancedUniformsByProgram[program] = uniformMap;
ForEach.techniqueUniform(
technique,
getCheckUniformSemanticFunction(
modelSemantics,
supportedSemantics,
programId,
uniformMap
)
);
}
}
}
return instancedUniformsByProgram[programId];
}
function getVertexShaderCallback(collection) {
return function (vs, programId) {
const instancedUniforms = getInstancedUniforms(collection, programId);
const usesBatchTable = defined(collection._batchTable);
let renamedSource = ShaderSource.replaceMain(vs, "czm_instancing_main");
let globalVarsHeader = "";
let globalVarsMain = "";
for (const uniform in instancedUniforms) {
if (instancedUniforms.hasOwnProperty(uniform)) {
const semantic = instancedUniforms[uniform];
let varName;
if (semantic === "MODELVIEW" || semantic === "CESIUM_RTC_MODELVIEW") {
varName = "czm_instanced_modelView";
} else if (semantic === "MODELVIEWPROJECTION") {
varName = "czm_instanced_modelViewProjection";
globalVarsHeader += "mat4 czm_instanced_modelViewProjection;\n";
globalVarsMain +=
"czm_instanced_modelViewProjection = czm_projection * czm_instanced_modelView;\n";
} else if (semantic === "MODELVIEWINVERSETRANSPOSE") {
varName = "czm_instanced_modelViewInverseTranspose";
globalVarsHeader += "mat3 czm_instanced_modelViewInverseTranspose;\n";
globalVarsMain +=
"czm_instanced_modelViewInverseTranspose = mat3(czm_instanced_modelView);\n";
}
// Remove the uniform declaration
let regex = new RegExp(`uniform.*${uniform}.*`);
renamedSource = renamedSource.replace(regex, "");
// Replace all occurrences of the uniform with the global variable
regex = new RegExp(`${uniform}\\b`, "g");
renamedSource = renamedSource.replace(regex, varName);
}
}
// czm_instanced_model is the model matrix of the instance relative to center
// czm_instanced_modifiedModelView is the transform from the center to view
// czm_instanced_nodeTransform is the local offset of the node within the model
const uniforms =
"uniform mat4 czm_instanced_modifiedModelView;\n" +
"uniform mat4 czm_instanced_nodeTransform;\n";
let batchIdAttribute;
let pickAttribute;
let pickVarying;
if (usesBatchTable) {
batchIdAttribute = "attribute float a_batchId;\n";
pickAttribute = "";
pickVarying = "";
} else {
batchIdAttribute = "";
pickAttribute =
"attribute vec4 pickColor;\n" + "varying vec4 v_pickColor;\n";
pickVarying = " v_pickColor = pickColor;\n";
}
let instancedSource =
`${uniforms + globalVarsHeader}mat4 czm_instanced_modelView;\n` +
`attribute vec4 czm_modelMatrixRow0;\n` +
`attribute vec4 czm_modelMatrixRow1;\n` +
`attribute vec4 czm_modelMatrixRow2;\n${batchIdAttribute}${pickAttribute}${renamedSource}void main()\n` +
`{\n` +
` mat4 czm_instanced_model = mat4(czm_modelMatrixRow0.x, czm_modelMatrixRow1.x, czm_modelMatrixRow2.x, 0.0, czm_modelMatrixRow0.y, czm_modelMatrixRow1.y, czm_modelMatrixRow2.y, 0.0, czm_modelMatrixRow0.z, czm_modelMatrixRow1.z, czm_modelMatrixRow2.z, 0.0, czm_modelMatrixRow0.w, czm_modelMatrixRow1.w, czm_modelMatrixRow2.w, 1.0);\n` +
` czm_instanced_modelView = czm_instanced_modifiedModelView * czm_instanced_model * czm_instanced_nodeTransform;\n${globalVarsMain} czm_instancing_main();\n${pickVarying}}\n`;
if (usesBatchTable) {
const gltf = collection._model.gltfInternal;
const diffuseAttributeOrUniformName = ModelUtility.getDiffuseAttributeOrUniform(
gltf,
programId
);
instancedSource = collection._batchTable.getVertexShaderCallback(
true,
"a_batchId",
diffuseAttributeOrUniformName
)(instancedSource);
}
return instancedSource;
};
}
function getFragmentShaderCallback(collection) {
return function (fs, programId) {
const batchTable = collection._batchTable;
if (defined(batchTable)) {
const gltf = collection._model.gltfInternal;
const diffuseAttributeOrUniformName = ModelUtility.getDiffuseAttributeOrUniform(
gltf,
programId
);
fs = batchTable.getFragmentShaderCallback(
true,
diffuseAttributeOrUniformName,
false
)(fs);
} else {
fs = `varying vec4 v_pickColor;\n${fs}`;
}
return fs;
};
}
function createModifiedModelView(collection, context) {
return function () {
return Matrix4.multiply(
context.uniformState.view,
collection._rtcTransform,
collection._rtcModelView
);
};
}
function createNodeTransformFunction(node) {
return function () {
return node.computedMatrix;
};
}
function getUniformMapCallback(collection, context) {
return function (uniformMap, programId, node) {
uniformMap = clone(uniformMap);
uniformMap.czm_instanced_modifiedModelView = createModifiedModelView(
collection,
context
);
uniformMap.czm_instanced_nodeTransform = createNodeTransformFunction(node);
// Remove instanced uniforms from the uniform map
const instancedUniforms = getInstancedUniforms(collection, programId);
for (const uniform in instancedUniforms) {
if (instancedUniforms.hasOwnProperty(uniform)) {
delete uniformMap[uniform];
}
}
if (defined(collection._batchTable)) {
uniformMap = collection._batchTable.getUniformMapCallback()(uniformMap);
}
return uniformMap;
};
}
function getVertexShaderNonInstancedCallback(collection) {
return function (vs, programId) {
if (defined(collection._batchTable)) {
const gltf = collection._model.gltfInternal;
const diffuseAttributeOrUniformName = ModelUtility.getDiffuseAttributeOrUniform(
gltf,
programId
);
vs = collection._batchTable.getVertexShaderCallback(
true,
"a_batchId",
diffuseAttributeOrUniformName
)(vs);
// Treat a_batchId as a uniform rather than a vertex attribute
vs = `uniform float a_batchId\n;${vs}`;
}
return vs;
};
}
function getFragmentShaderNonInstancedCallback(collection) {
return function (fs, programId) {
const batchTable = collection._batchTable;
if (defined(batchTable)) {
const gltf = collection._model.gltfInternal;
const diffuseAttributeOrUniformName = ModelUtility.getDiffuseAttributeOrUniform(
gltf,
programId
);
fs = batchTable.getFragmentShaderCallback(
true,
diffuseAttributeOrUniformName,
false
)(fs);
} else {
fs = `uniform vec4 czm_pickColor;\n${fs}`;
}
return fs;
};
}
function getUniformMapNonInstancedCallback(collection) {
return function (uniformMap) {
if (defined(collection._batchTable)) {
uniformMap = collection._batchTable.getUniformMapCallback()(uniformMap);
}
return uniformMap;
};
}
function getVertexBufferTypedArray(collection) {
const instances = collection._instances;
const instancesLength = collection.length;
const collectionCenter = collection._center;
const vertexSizeInFloats = 12;
let bufferData = collection._vertexBufferTypedArray;
if (!defined(bufferData)) {
bufferData = new Float32Array(instancesLength * vertexSizeInFloats);
}
if (collection._dynamic) {
// Hold onto the buffer data so we don't have to allocate new memory every frame.
collection._vertexBufferTypedArray = bufferData;
}
for (let i = 0; i < instancesLength; ++i) {
const modelMatrix = instances[i]._modelMatrix;
// Instance matrix is relative to center
const instanceMatrix = Matrix4.clone(modelMatrix, scratchMatrix);
instanceMatrix[12] -= collectionCenter.x;
instanceMatrix[13] -= collectionCenter.y;
instanceMatrix[14] -= collectionCenter.z;
const offset = i * vertexSizeInFloats;
// First three rows of the model matrix
bufferData[offset + 0] = instanceMatrix[0];
bufferData[offset + 1] = instanceMatrix[4];
bufferData[offset + 2] = instanceMatrix[8];
bufferData[offset + 3] = instanceMatrix[12];
bufferData[offset + 4] = instanceMatrix[1];
bufferData[offset + 5] = instanceMatrix[5];
bufferData[offset + 6] = instanceMatrix[9];
bufferData[offset + 7] = instanceMatrix[13];
bufferData[offset + 8] = instanceMatrix[2];
bufferData[offset + 9] = instanceMatrix[6];
bufferData[offset + 10] = instanceMatrix[10];
bufferData[offset + 11] = instanceMatrix[14];
}
return bufferData;
}
function createVertexBuffer(collection, context) {
let i;
const instances = collection._instances;
const instancesLength = collection.length;
const dynamic = collection._dynamic;
const usesBatchTable = defined(collection._batchTable);
if (usesBatchTable) {
const batchIdBufferData = new Uint16Array(instancesLength);
for (i = 0; i < instancesLength; ++i) {
batchIdBufferData[i] = instances[i]._instanceId;
}
collection._batchIdBuffer = Buffer.createVertexBuffer({
context: context,
typedArray: batchIdBufferData,
usage: BufferUsage.STATIC_DRAW,
});
}
if (!usesBatchTable) {
const pickIdBuffer = new Uint8Array(instancesLength * 4);
for (i = 0; i < instancesLength; ++i) {
const pickId = collection._pickIds[i];
const pickColor = pickId.color;
const offset = i * 4;
pickIdBuffer[offset] = Color.floatToByte(pickColor.red);
pickIdBuffer[offset + 1] = Color.floatToByte(pickColor.green);
pickIdBuffer[offset + 2] = Color.floatToByte(pickColor.blue);
pickIdBuffer[offset + 3] = Color.floatToByte(pickColor.alpha);
}
collection._pickIdBuffer = Buffer.createVertexBuffer({
context: context,
typedArray: pickIdBuffer,
usage: BufferUsage.STATIC_DRAW,
});
}
const vertexBufferTypedArray = getVertexBufferTypedArray(collection);
collection._vertexBuffer = Buffer.createVertexBuffer({
context: context,
typedArray: vertexBufferTypedArray,
usage: dynamic ? BufferUsage.STREAM_DRAW : BufferUsage.STATIC_DRAW,
});
}
// function updateVertexBuffer(collection) {
// const vertexBufferTypedArray = getVertexBufferTypedArray(collection);
// collection._vertexBuffer.copyFromArrayView(vertexBufferTypedArray);
// }
function createPickIds(collection, context) {
// PERFORMANCE_IDEA: we could skip the pick buffer completely by allocating
// a continuous range of pickIds and then converting the base pickId + batchId
// to RGBA in the shader. The only consider is precision issues, which might
// not be an issue in WebGL 2.
const instances = collection._instances;
const instancesLength = instances.length;
const pickIds = new Array(instancesLength);
for (let i = 0; i < instancesLength; ++i) {
pickIds[i] = context.createPickId(instances[i]);
}
return pickIds;
}
function createModel(collection, context) {
const instancingSupported = collection._instancingSupported;
if (!instancingSupported) {
deprecationWarning(
"cpuModelInstancing",
"Support for rendering instanced models on the CPU has been deprecated and will be removed in CesiumJS 1.97."
);
}
const usesBatchTable = defined(collection._batchTable);
const allowPicking = collection._allowPicking;
const modelOptions = {
url: collection._url,
// requestType: collection._requestType,
gltf: collection._gltf,
basePath: collection._basePath,
shadows: collection._shadows,
// cacheKey: undefined,
asynchronous: collection._asynchronous,
allowPicking: allowPicking,
incrementallyLoadTextures: collection._incrementallyLoadTextures,
upAxis: collection._upAxis,
forwardAxis: collection._forwardAxis,
// precreatedAttributes: undefined,
// vertexShaderLoaded: undefined,
// fragmentShaderLoaded: undefined,
// uniformMapLoaded: undefined,
// pickIdLoaded: collection._pickIdLoaded,
ignoreCommands: true,
opaquePass: collection._opaquePass,
imageBasedLighting: collection._imageBasedLighting,
showOutline: collection.showOutline,
showCreditsOnScreen: collection.showCreditsOnScreen,
};
if (!usesBatchTable) {
collection._pickIds = createPickIds(collection, context);
}
if (instancingSupported) {
// createVertexBuffer(collection, context);
// const vertexSizeInFloats = 12;
// const componentSizeInBytes = ComponentDatatype.getSizeInBytes(
// ComponentDatatype.FLOAT
// );
// const instancedAttributes = {
// czm_modelMatrixRow0: {
// index: 0, // updated in Model
// vertexBuffer: collection._vertexBuffer,
// componentsPerAttribute: 4,
// componentDatatype: ComponentDatatype.FLOAT,
// normalize: false,
// offsetInBytes: 0,
// strideInBytes: componentSizeInBytes * vertexSizeInFloats,
// instanceDivisor: 1,
// },
// czm_modelMatrixRow1: {
// index: 0, // updated in Model
// vertexBuffer: collection._vertexBuffer,
// componentsPerAttribute: 4,
// componentDatatype: ComponentDatatype.FLOAT,
// normalize: false,
// offsetInBytes: componentSizeInBytes * 4,
// strideInBytes: componentSizeInBytes * vertexSizeInFloats,
// instanceDivisor: 1,
// },
// czm_modelMatrixRow2: {
// index: 0, // updated in Model
// vertexBuffer: collection._vertexBuffer,
// componentsPerAttribute: 4,
// componentDatatype: ComponentDatatype.FLOAT,
// normalize: false,
// offsetInBytes: componentSizeInBytes * 8,
// strideInBytes: componentSizeInBytes * vertexSizeInFloats,
// instanceDivisor: 1,
// },
// };
// When using a batch table, add a batch id attribute
// if (usesBatchTable) {
// instancedAttributes.a_batchId = {
// index: 0, // updated in Model
// vertexBuffer: collection._batchIdBuffer,
// componentsPerAttribute: 1,
// componentDatatype: ComponentDatatype.UNSIGNED_SHORT,
// normalize: false,
// offsetInBytes: 0,
// strideInBytes: 0,
// instanceDivisor: 1,
// };
// }
// if (!usesBatchTable) {
// instancedAttributes.pickColor = {
// index: 0, // updated in Model
// vertexBuffer: collection._pickIdBuffer,
// componentsPerAttribute: 4,
// componentDatatype: ComponentDatatype.UNSIGNED_BYTE,
// normalize: true,
// offsetInBytes: 0,
// strideInBytes: 0,
// instanceDivisor: 1,
// };
// }
// FIXME: 没有了!
// 用 InstancingPipelineStage?
// InstancingPipelineStage.process 只会调用一次!
// DrawCommand 只会构建一次,然后 instanceCount 就定下来了
// 需要每一帧动态更新 attribute 和 instanceCount
// 需要更新的 3 个 attribute:
// a_instancingTransformRow0
// a_instancingTransformRow1
// a_instancingTransformRow2
// modelOptions.precreatedAttributes = instancedAttributes;
// modelOptions.vertexShaderLoaded = getVertexShaderCallback(collection);
// modelOptions.fragmentShaderLoaded = getFragmentShaderCallback(collection);
// modelOptions.uniformMapLoaded = getUniformMapCallback(collection, context);
// 用 GltfLoader 自己创建 new Model() ?
if (defined(collection._url)) {
// modelOptions.cacheKey = `${collection._url.getUrlComponent()}#instanced`;
}
} else {
debugger;
modelOptions.vertexShaderLoaded = getVertexShaderNonInstancedCallback(
collection
);
modelOptions.fragmentShaderLoaded = getFragmentShaderNonInstancedCallback(
collection
);
modelOptions.uniformMapLoaded = getUniformMapNonInstancedCallback(
collection,
context
);
}
if (defined(collection._url)) {
fromGltfAsync(modelOptions).then(model => {
collection._model = model;
collection._model.errorEvent.addEventListener(function (error) {
collection._state = LoadState.FAILED;
collection._readyPromise.reject(error);
});
});
} else {
debugger;
collection._model = new Model(modelOptions);
}
}
function makeModelOptions(loader, modelType, options) {
return {
loader: loader,
type: modelType,
resource: options.resource,
show: options.show,
modelMatrix: options.modelMatrix,
scale: options.scale,
enableVerticalExaggeration: options.enableVerticalExaggeration,
minimumPixelSize: options.minimumPixelSize,
maximumScale: options.maximumScale,
id: options.id,
allowPicking: options.allowPicking,
clampAnimations: options.clampAnimations,
shadows: options.shadows,
debugShowBoundingVolume: options.debugShowBoundingVolume,
enableDebugWireframe: options.enableDebugWireframe,
debugWireframe: options.debugWireframe,
cull: options.cull,
opaquePass: options.opaquePass,
customShader: options.customShader,
content: options.content,
heightReference: options.heightReference,
scene: options.scene,
distanceDisplayCondition: options.distanceDisplayCondition,
color: options.color,
colorBlendAmount: options.colorBlendAmount,
colorBlendMode: options.colorBlendMode,
edgeDisplayMode: options.edgeDisplayMode,
silhouetteColor: options.silhouetteColor,
silhouetteSize: options.silhouetteSize,
enableShowOutline: options.enableShowOutline,
showOutline: options.showOutline,
outlineColor: options.outlineColor,
clippingPlanes: options.clippingPlanes,
clippingPolygons: options.clippingPolygons,
lightColor: options.lightColor,
imageBasedLighting: options.imageBasedLighting,
backFaceCulling: options.backFaceCulling,
credit: options.credit,
showCreditsOnScreen: options.showCreditsOnScreen,
splitDirection: options.splitDirection,
projectTo2D: options.projectTo2D,
enablePick: options.enablePick,
featureIdLabel: options.featureIdLabel,
instanceFeatureIdLabel: options.instanceFeatureIdLabel,
pointCloudShading: options.pointCloudShading,
classificationType: options.classificationType,
pickObject: options.pickObject,
};
}
async function fromGltfAsync(options) {
options = options ?? Cesium.Frozen.EMPTY_OBJECT;
// options.gltf is used internally for 3D Tiles. It can be a Resource, a URL
// to a glTF/glb file, a binary glTF buffer, or a JSON object containing the
// glTF contents.
const gltf = options.url ?? options.gltf;
const loaderOptions = {
releaseGltfJson: options.releaseGltfJson,
asynchronous: options.asynchronous,
incrementallyLoadTextures: options.incrementallyLoadTextures,
upAxis: options.upAxis,
forwardAxis: options.forwardAxis,
loadAttributesFor2D: options.projectTo2D,
enablePick: options.enablePick,
loadIndicesForWireframe: options.enableDebugWireframe,
loadPrimitiveOutline: options.enableShowOutline,
loadForClassification: defined(options.classificationType),
};
const basePath = options.basePath ?? "";
const baseResource = Resource.createIfNeeded(basePath);
if (defined(gltf.asset)) {
loaderOptions.gltfJson = gltf;
loaderOptions.baseResource = baseResource;
loaderOptions.gltfResource = baseResource;
} else if (gltf instanceof Uint8Array) {
loaderOptions.typedArray = gltf;
loaderOptions.baseResource = baseResource;
loaderOptions.gltfResource = baseResource;
} else {
loaderOptions.gltfResource = Resource.createIfNeeded(gltf);
}
const loader = new Cesium.GltfLoader(loaderOptions);
const is3DTiles = false; // defined(options.content);
const type = is3DTiles ? Cesium.ModelType.TILE_GLTF : Cesium.ModelType.GLTF;
const resource = loaderOptions.gltfResource;
const modelOptions = makeModelOptions(loader, type, options);
modelOptions.resource = resource;
modelOptions.environmentMapOptions = options.environmentMapOptions;
try {
// This load the gltf JSON and ensures the gltf is valid
// Further resource loading is handled synchronously in loader.process(), and requires
// hooking into model's update() as the frameState is needed
await loader.load();
} catch (error) {
loader.destroy();
throw ModelUtility.getError("model", resource, error);
}
const gltfCallback = options.gltfCallback;
if (defined(gltfCallback)) {
//>>includeStart('debug', pragmas.debug);
Check.typeOf.func("options.gltfCallback", gltfCallback);
//>>includeEnd('debug');
gltfCallback(loader.gltfJson);
}
const model = new Model(modelOptions);
const resourceCredits = model._resource.credits;
if (defined(resourceCredits)) {
const length = resourceCredits.length;
for (let i = 0; i < length; i++) {
model._resourceCredits.push(Credit.clone(resourceCredits[i]));
}
}
return model;
}
function updateWireframe(collection, force) {
if (collection._debugWireframe !== collection.debugWireframe || force) {
collection._debugWireframe = collection.debugWireframe;
// This assumes the original primitive was TRIANGLES and that the triangles
// are connected for the wireframe to look perfect.
const primitiveType = collection.debugWireframe
? PrimitiveType.LINES