-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
Copy pathClassificationModel.js
1077 lines (928 loc) · 39.8 KB
/
ClassificationModel.js
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
define([
'../Core/arraySlice',
'../Core/BoundingSphere',
'../Core/Cartesian3',
'../Core/Cartesian4',
'../Core/Color',
'../Core/combine',
'../Core/ComponentDatatype',
'../Core/defaultValue',
'../Core/defined',
'../Core/defineProperties',
'../Core/destroyObject',
'../Core/DeveloperError',
'../Core/FeatureDetection',
'../Core/IndexDatatype',
'../Core/Matrix4',
'../Core/PrimitiveType',
'../Core/RuntimeError',
'../Core/Transforms',
'../Core/WebGLConstants',
'../ThirdParty/GltfPipeline/addDefaults',
'../ThirdParty/GltfPipeline/ForEach',
'../ThirdParty/GltfPipeline/getAccessorByteStride',
'../ThirdParty/GltfPipeline/numberOfComponentsForType',
'../ThirdParty/GltfPipeline/parseGlb',
'../ThirdParty/GltfPipeline/updateVersion',
'../ThirdParty/when',
'./Axis',
'./ClassificationType',
'./ModelLoadResources',
'./ModelUtility',
'./processModelMaterialsCommon',
'./processPbrMaterials',
'./SceneMode',
'./Vector3DTileBatch',
'./Vector3DTilePrimitive'
], function(
arraySlice,
BoundingSphere,
Cartesian3,
Cartesian4,
Color,
combine,
ComponentDatatype,
defaultValue,
defined,
defineProperties,
destroyObject,
DeveloperError,
FeatureDetection,
IndexDatatype,
Matrix4,
PrimitiveType,
RuntimeError,
Transforms,
WebGLConstants,
addDefaults,
ForEach,
getAccessorByteStride,
numberOfComponentsForType,
parseGlb,
updateVersion,
when,
Axis,
ClassificationType,
ModelLoadResources,
ModelUtility,
processModelMaterialsCommon,
processPbrMaterials,
SceneMode,
Vector3DTileBatch,
Vector3DTilePrimitive) {
'use strict';
// Bail out if the browser doesn't support typed arrays, to prevent the setup function
// from failing, since we won't be able to create a WebGL context anyway.
if (!FeatureDetection.supportsTypedArrays()) {
return {};
}
var boundingSphereCartesian3Scratch = new Cartesian3();
var ModelState = ModelUtility.ModelState;
///////////////////////////////////////////////////////////////////////////
/**
* A 3D model for classifying other 3D assets based on glTF, the runtime 3D asset format.
* This is a special case when a model of a 3D tileset becomes a classifier when setting {@link Cesium3DTileset#classificationType}.
*
* @alias ClassificationModel
* @constructor
*
* @private
*
* @param {Object} options Object with the following properties:
* @param {ArrayBuffer|Uint8Array} options.gltf A binary glTF buffer.
* @param {Boolean} [options.show=true] Determines if the model primitive will be shown.
* @param {Matrix4} [options.modelMatrix=Matrix4.IDENTITY] The 4x4 transformation matrix that transforms the model from model to world coordinates.
* @param {Boolean} [options.debugShowBoundingVolume=false] For debugging only. Draws the bounding sphere for each draw command in the model.
* @param {Boolean} [options.debugWireframe=false] For debugging only. Draws the model in wireframe.
* @param {ClassificationType} [options.classificationType] What this model will classify.
*
* @exception {RuntimeError} Only binary glTF is supported.
* @exception {RuntimeError} Buffer data must be embedded in the binary glTF.
* @exception {RuntimeError} Only one node is supported for classification and it must have a mesh.
* @exception {RuntimeError} Only one mesh is supported when using b3dm for classification.
* @exception {RuntimeError} Only one primitive per mesh is supported when using b3dm for classification.
* @exception {RuntimeError} The mesh must have a position attribute.
* @exception {RuntimeError} The mesh must have a batch id attribute.
*/
function ClassificationModel(options) {
options = defaultValue(options, defaultValue.EMPTY_OBJECT);
var gltf = options.gltf;
if (gltf instanceof ArrayBuffer) {
gltf = new Uint8Array(gltf);
}
if (gltf instanceof Uint8Array) {
// Parse and update binary glTF
gltf = parseGlb(gltf);
updateVersion(gltf);
addDefaults(gltf);
processModelMaterialsCommon(gltf);
processPbrMaterials(gltf);
} else {
throw new RuntimeError('Only binary glTF is supported as a classifier.');
}
ForEach.buffer(gltf, function(buffer) {
if (!defined(buffer.extras._pipeline.source)) {
throw new RuntimeError('Buffer data must be embedded in the binary gltf.');
}
});
var gltfNodes = gltf.nodes;
var gltfMeshes = gltf.meshes;
var gltfNode = gltfNodes[0];
var meshId = gltfNode.mesh;
if (gltfNodes.length !== 1 || !defined(meshId)) {
throw new RuntimeError('Only one node is supported for classification and it must have a mesh.');
}
if (gltfMeshes.length !== 1) {
throw new RuntimeError('Only one mesh is supported when using b3dm for classification.');
}
var gltfPrimitives = gltfMeshes[0].primitives;
if (gltfPrimitives.length !== 1) {
throw new RuntimeError('Only one primitive per mesh is supported when using b3dm for classification.');
}
var gltfPositionAttribute = gltfPrimitives[0].attributes.POSITION;
if (!defined(gltfPositionAttribute)) {
throw new RuntimeError('The mesh must have a position attribute.');
}
var gltfBatchIdAttribute = gltfPrimitives[0].attributes._BATCHID;
if (!defined(gltfBatchIdAttribute)) {
throw new RuntimeError('The mesh must have a batch id attribute.');
}
this._gltf = gltf;
/**
* Determines if the model primitive will be shown.
*
* @type {Boolean}
*
* @default true
*/
this.show = defaultValue(options.show, true);
/**
* The 4x4 transformation matrix that transforms the model from model to world coordinates.
* When this is the identity matrix, the model is drawn in world coordinates, i.e., Earth's WGS84 coordinates.
* Local reference frames can be used by providing a different transformation matrix, like that returned
* by {@link Transforms.eastNorthUpToFixedFrame}.
*
* @type {Matrix4}
*
* @default {@link Matrix4.IDENTITY}
*
* @example
* var origin = Cesium.Cartesian3.fromDegrees(-95.0, 40.0, 200000.0);
* m.modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(origin);
*/
this.modelMatrix = Matrix4.clone(defaultValue(options.modelMatrix, Matrix4.IDENTITY));
this._modelMatrix = Matrix4.clone(this.modelMatrix);
this._ready = false;
this._readyPromise = when.defer();
/**
* This property is for debugging only; it is not for production use nor is it optimized.
* <p>
* Draws the bounding sphere for each draw command in the model. A glTF primitive corresponds
* to one draw command. A glTF mesh has an array of primitives, often of length one.
* </p>
*
* @type {Boolean}
*
* @default false
*/
this.debugShowBoundingVolume = defaultValue(options.debugShowBoundingVolume, false);
this._debugShowBoundingVolume = false;
/**
* This property is for debugging only; it is not for production use nor is it optimized.
* <p>
* Draws the model in wireframe.
* </p>
*
* @type {Boolean}
*
* @default false
*/
this.debugWireframe = defaultValue(options.debugWireframe, false);
this._debugWireframe = false;
this._classificationType = options.classificationType;
// Undocumented options
this._vertexShaderLoaded = options.vertexShaderLoaded;
this._classificationShaderLoaded = options.classificationShaderLoaded;
this._uniformMapLoaded = options.uniformMapLoaded;
this._pickIdLoaded = options.pickIdLoaded;
this._ignoreCommands = defaultValue(options.ignoreCommands, false);
this._upAxis = defaultValue(options.upAxis, Axis.Y);
this._batchTable = options.batchTable;
this._computedModelMatrix = new Matrix4(); // Derived from modelMatrix and axis
this._initialRadius = undefined; // Radius without model's scale property, model-matrix scale, animations, or skins
this._boundingSphere = undefined;
this._scaledBoundingSphere = new BoundingSphere();
this._state = ModelState.NEEDS_LOAD;
this._loadResources = undefined;
this._mode = undefined;
this._dirty = false; // true when the model was transformed this frame
this._nodeMatrix = new Matrix4();
this._primitive = undefined;
this._extensionsUsed = undefined; // Cached used glTF extensions
this._extensionsRequired = undefined; // Cached required glTF extensions
this._quantizedUniforms = undefined; // Quantized uniforms for WEB3D_quantized_attributes
this._buffers = {};
this._vertexArray = undefined;
this._shaderProgram = undefined;
this._uniformMap = undefined;
this._geometryByteLength = 0;
this._trianglesLength = 0;
// CESIUM_RTC extension
this._rtcCenter = undefined; // reference to either 3D or 2D
this._rtcCenterEye = undefined; // in eye coordinates
this._rtcCenter3D = undefined; // in world coordinates
this._rtcCenter2D = undefined; // in projected world coordinates
}
defineProperties(ClassificationModel.prototype, {
/**
* The object for the glTF JSON, including properties with default values omitted
* from the JSON provided to this model.
*
* @memberof ClassificationModel.prototype
*
* @type {Object}
* @readonly
*
* @default undefined
*/
gltf : {
get : function() {
return this._gltf;
}
},
/**
* The model's bounding sphere in its local coordinate system.
*
* @memberof ClassificationModel.prototype
*
* @type {BoundingSphere}
* @readonly
*
* @default undefined
*
* @exception {DeveloperError} The model is not loaded. Use ClassificationModel.readyPromise or wait for ClassificationModel.ready to be true.
*
* @example
* // Center in WGS84 coordinates
* var center = Cesium.Matrix4.multiplyByPoint(model.modelMatrix, model.boundingSphere.center, new Cesium.Cartesian3());
*/
boundingSphere : {
get : function() {
//>>includeStart('debug', pragmas.debug);
if (this._state !== ModelState.LOADED) {
throw new DeveloperError('The model is not loaded. Use ClassificationModel.readyPromise or wait for ClassificationModel.ready to be true.');
}
//>>includeEnd('debug');
var modelMatrix = this.modelMatrix;
var nonUniformScale = Matrix4.getScale(modelMatrix, boundingSphereCartesian3Scratch);
var scaledBoundingSphere = this._scaledBoundingSphere;
scaledBoundingSphere.center = Cartesian3.multiplyComponents(this._boundingSphere.center, nonUniformScale, scaledBoundingSphere.center);
scaledBoundingSphere.radius = Cartesian3.maximumComponent(nonUniformScale) * this._initialRadius;
if (defined(this._rtcCenter)) {
Cartesian3.add(this._rtcCenter, scaledBoundingSphere.center, scaledBoundingSphere.center);
}
return scaledBoundingSphere;
}
},
/**
* When <code>true</code>, this model is ready to render, i.e., the external binary, image,
* and shader files were downloaded and the WebGL resources were created. This is set to
* <code>true</code> right before {@link ClassificationModel#readyPromise} is resolved.
*
* @memberof ClassificationModel.prototype
*
* @type {Boolean}
* @readonly
*
* @default false
*/
ready : {
get : function() {
return this._ready;
}
},
/**
* Gets the promise that will be resolved when this model is ready to render, i.e., when the external binary, image,
* and shader files were downloaded and the WebGL resources were created.
* <p>
* This promise is resolved at the end of the frame before the first frame the model is rendered in.
* </p>
*
* @memberof ClassificationModel.prototype
* @type {Promise.<ClassificationModel>}
* @readonly
*
* @see ClassificationModel#ready
*/
readyPromise : {
get : function() {
return this._readyPromise.promise;
}
},
/**
* Returns true if the model was transformed this frame
*
* @memberof ClassificationModel.prototype
*
* @type {Boolean}
* @readonly
*
* @private
*/
dirty : {
get : function() {
return this._dirty;
}
},
/**
* Returns an object with all of the glTF extensions used.
*
* @memberof ClassificationModel.prototype
*
* @type {Object}
* @readonly
*/
extensionsUsed : {
get : function() {
if (!defined(this._extensionsUsed)) {
this._extensionsUsed = ModelUtility.getUsedExtensions(this.gltf);
}
return this._extensionsUsed;
}
},
/**
* Returns an object with all of the glTF extensions required.
*
* @memberof ClassificationModel.prototype
*
* @type {Object}
* @readonly
*/
extensionsRequired : {
get : function() {
if (!defined(this._extensionsRequired)) {
this._extensionsRequired = ModelUtility.getRequiredExtensions(this.gltf);
}
return this._extensionsRequired;
}
},
/**
* Gets the model's up-axis.
* By default models are y-up according to the glTF spec, however geo-referenced models will typically be z-up.
*
* @memberof ClassificationModel.prototype
*
* @type {Number}
* @default Axis.Y
* @readonly
*
* @private
*/
upAxis : {
get : function() {
return this._upAxis;
}
},
/**
* Gets the model's triangle count.
*
* @private
*/
trianglesLength : {
get : function() {
return this._trianglesLength;
}
},
/**
* Gets the model's geometry memory in bytes. This includes all vertex and index buffers.
*
* @private
*/
geometryByteLength : {
get : function() {
return this._geometryByteLength;
}
},
/**
* Gets the model's texture memory in bytes.
*
* @private
*/
texturesByteLength : {
get : function() {
return 0;
}
},
/**
* Gets the model's classification type.
* @memberof ClassificationModel.prototype
* @type {ClassificationType}
*/
classificationType : {
get : function() {
return this._classificationType;
}
}
});
///////////////////////////////////////////////////////////////////////////
function addBuffersToLoadResources(model) {
var gltf = model.gltf;
var loadResources = model._loadResources;
ForEach.buffer(gltf, function(buffer, id) {
loadResources.buffers[id] = buffer.extras._pipeline.source;
});
}
function parseBufferViews(model) {
var bufferViews = model.gltf.bufferViews;
var vertexBuffersToCreate = model._loadResources.vertexBuffersToCreate;
// Only ARRAY_BUFFER here. ELEMENT_ARRAY_BUFFER created below.
ForEach.bufferView(model.gltf, function(bufferView, id) {
if (bufferView.target === WebGLConstants.ARRAY_BUFFER) {
vertexBuffersToCreate.enqueue(id);
}
});
var indexBuffersToCreate = model._loadResources.indexBuffersToCreate;
var indexBufferIds = {};
// The Cesium Renderer requires knowing the datatype for an index buffer
// at creation type, which is not part of the glTF bufferview so loop
// through glTF accessors to create the bufferview's index buffer.
ForEach.accessor(model.gltf, function(accessor) {
var bufferViewId = accessor.bufferView;
var bufferView = bufferViews[bufferViewId];
if ((bufferView.target === WebGLConstants.ELEMENT_ARRAY_BUFFER) && !defined(indexBufferIds[bufferViewId])) {
indexBufferIds[bufferViewId] = true;
indexBuffersToCreate.enqueue({
id : bufferViewId,
componentType : accessor.componentType
});
}
});
}
function createVertexBuffer(bufferViewId, model) {
var loadResources = model._loadResources;
var bufferViews = model.gltf.bufferViews;
var bufferView = bufferViews[bufferViewId];
var vertexBuffer = loadResources.getBuffer(bufferView);
model._buffers[bufferViewId] = vertexBuffer;
model._geometryByteLength += vertexBuffer.byteLength;
}
function createIndexBuffer(bufferViewId, componentType, model) {
var loadResources = model._loadResources;
var bufferViews = model.gltf.bufferViews;
var bufferView = bufferViews[bufferViewId];
var indexBuffer = {
typedArray : loadResources.getBuffer(bufferView),
indexDatatype : componentType
};
model._buffers[bufferViewId] = indexBuffer;
model._geometryByteLength += indexBuffer.typedArray.byteLength;
}
function createBuffers(model) {
var loadResources = model._loadResources;
if (loadResources.pendingBufferLoads !== 0) {
return;
}
var vertexBuffersToCreate = loadResources.vertexBuffersToCreate;
var indexBuffersToCreate = loadResources.indexBuffersToCreate;
while (vertexBuffersToCreate.length > 0) {
createVertexBuffer(vertexBuffersToCreate.dequeue(), model);
}
while (indexBuffersToCreate.length > 0) {
var i = indexBuffersToCreate.dequeue();
createIndexBuffer(i.id, i.componentType, model);
}
}
function modifyShaderForQuantizedAttributes(shader, model) {
var primitive = model.gltf.meshes[0].primitives[0];
var result = ModelUtility.modifyShaderForQuantizedAttributes(model.gltf, primitive, shader);
model._quantizedUniforms = result.uniforms;
return result.shader;
}
function modifyShader(shader, callback) {
if (defined(callback)) {
shader = callback(shader);
}
return shader;
}
function createProgram(model) {
var gltf = model.gltf;
var positionName = ModelUtility.getAttributeOrUniformBySemantic(gltf, 'POSITION');
var batchIdName = ModelUtility.getAttributeOrUniformBySemantic(gltf, '_BATCHID');
var attributeLocations = {};
attributeLocations[positionName] = 0;
attributeLocations[batchIdName] = 1;
var modelViewProjectionName = ModelUtility.getAttributeOrUniformBySemantic(gltf, 'MODELVIEWPROJECTION');
var uniformDecl;
var toClip;
if (!defined(modelViewProjectionName)) {
var projectionName = ModelUtility.getAttributeOrUniformBySemantic(gltf, 'PROJECTION');
var modelViewName = ModelUtility.getAttributeOrUniformBySemantic(gltf, 'MODELVIEW');
if (!defined(modelViewName)) {
modelViewName = ModelUtility.getAttributeOrUniformBySemantic(gltf, 'CESIUM_RTC_MODELVIEW');
}
uniformDecl =
'uniform mat4 ' + modelViewName + ';\n' +
'uniform mat4 ' + projectionName + ';\n';
toClip = projectionName + ' * ' + modelViewName + ' * vec4(' + positionName + ', 1.0)';
} else {
uniformDecl = 'uniform mat4 ' + modelViewProjectionName + ';\n';
toClip = modelViewProjectionName + ' * vec4(' + positionName + ', 1.0)';
}
var computePosition = ' vec4 positionInClipCoords = ' + toClip + ';\n';
var vs =
'attribute vec3 ' + positionName + ';\n' +
'attribute float ' + batchIdName + ';\n' +
uniformDecl +
'void main() {\n' +
computePosition +
' gl_Position = czm_depthClampFarPlane(positionInClipCoords);\n' +
'}\n';
var fs =
'#ifdef GL_EXT_frag_depth\n' +
'#extension GL_EXT_frag_depth : enable\n' +
'#endif\n' +
'void main() \n' +
'{ \n' +
' gl_FragColor = vec4(1.0); \n' +
' czm_writeDepthClampedToFarPlane();\n' +
'}\n';
if (model.extensionsUsed.WEB3D_quantized_attributes) {
vs = modifyShaderForQuantizedAttributes(vs, model);
}
var drawVS = modifyShader(vs, model._vertexShaderLoaded);
var drawFS = modifyShader(fs, model._classificationShaderLoaded);
drawVS = ModelUtility.modifyVertexShaderForLogDepth(drawVS, toClip);
drawFS = ModelUtility.modifyFragmentShaderForLogDepth(drawFS);
model._shaderProgram = {
vertexShaderSource : drawVS,
fragmentShaderSource : drawFS,
attributeLocations : attributeLocations
};
}
function getAttributeLocations() {
return {
POSITION : 0,
_BATCHID : 1
};
}
function createVertexArray(model) {
var loadResources = model._loadResources;
if (!loadResources.finishedBuffersCreation() || defined(model._vertexArray)) {
return;
}
var rendererBuffers = model._buffers;
var gltf = model.gltf;
var accessors = gltf.accessors;
var meshes = gltf.meshes;
var primitives = meshes[0].primitives;
var primitive = primitives[0];
var attributeLocations = getAttributeLocations();
var attributes = {};
ForEach.meshPrimitiveAttribute(primitive, function(accessorId, attributeName) {
// Skip if the attribute is not used by the material, e.g., because the asset
// was exported with an attribute that wasn't used and the asset wasn't optimized.
var attributeLocation = attributeLocations[attributeName];
if (defined(attributeLocation)) {
var a = accessors[accessorId];
attributes[attributeName] = {
index: attributeLocation,
vertexBuffer: rendererBuffers[a.bufferView],
componentsPerAttribute: numberOfComponentsForType(a.type),
componentDatatype: a.componentType,
offsetInBytes: a.byteOffset,
strideInBytes: getAccessorByteStride(gltf, a)
};
}
});
var indexBuffer;
if (defined(primitive.indices)) {
var accessor = accessors[primitive.indices];
indexBuffer = rendererBuffers[accessor.bufferView];
}
model._vertexArray = {
attributes : attributes,
indexBuffer : indexBuffer
};
}
var gltfSemanticUniforms = {
PROJECTION : function(uniformState, model) {
return ModelUtility.getGltfSemanticUniforms().PROJECTION(uniformState, model);
},
MODELVIEW : function(uniformState, model) {
return ModelUtility.getGltfSemanticUniforms().MODELVIEW(uniformState, model);
},
CESIUM_RTC_MODELVIEW : function(uniformState, model) {
return ModelUtility.getGltfSemanticUniforms().CESIUM_RTC_MODELVIEW(uniformState, model);
},
MODELVIEWPROJECTION : function(uniformState, model) {
return ModelUtility.getGltfSemanticUniforms().MODELVIEWPROJECTION(uniformState, model);
}
};
function createUniformMap(model, context) {
if (defined(model._uniformMap)) {
return;
}
var uniformMap = {};
ForEach.technique(model.gltf, function(technique) {
ForEach.techniqueUniform(technique, function(uniform, uniformName) {
if (!defined(uniform.semantic) || !defined(gltfSemanticUniforms[uniform.semantic])) {
return;
}
uniformMap[uniformName] = gltfSemanticUniforms[uniform.semantic](context.uniformState, model);
});
});
model._uniformMap = uniformMap;
}
function createUniformsForQuantizedAttributes(model, primitive) {
return ModelUtility.createUniformsForQuantizedAttributes(model.gltf, primitive, model._quantizedUniforms);
}
function triangleCountFromPrimitiveIndices(primitive, indicesCount) {
switch (primitive.mode) {
case PrimitiveType.TRIANGLES:
return (indicesCount / 3);
case PrimitiveType.TRIANGLE_STRIP:
case PrimitiveType.TRIANGLE_FAN:
return Math.max(indicesCount - 2, 0);
default:
return 0;
}
}
function createPrimitive(model) {
var batchTable = model._batchTable;
var uniformMap = model._uniformMap;
var vertexArray = model._vertexArray;
var gltf = model.gltf;
var accessors = gltf.accessors;
var gltfMeshes = gltf.meshes;
var primitive = gltfMeshes[0].primitives[0];
var ix = accessors[primitive.indices];
var positionAccessor = primitive.attributes.POSITION;
var minMax = ModelUtility.getAccessorMinMax(gltf, positionAccessor);
var boundingSphere = BoundingSphere.fromCornerPoints(Cartesian3.fromArray(minMax.min), Cartesian3.fromArray(minMax.max));
var offset;
var count;
if (defined(ix)) {
count = ix.count;
offset = (ix.byteOffset / IndexDatatype.getSizeInBytes(ix.componentType)); // glTF has offset in bytes. Cesium has offsets in indices
}
else {
var positions = accessors[primitive.attributes.POSITION];
count = positions.count;
offset = 0;
}
// Update model triangle count using number of indices
model._trianglesLength += triangleCountFromPrimitiveIndices(primitive, count);
// Allow callback to modify the uniformMap
if (defined(model._uniformMapLoaded)) {
uniformMap = model._uniformMapLoaded(uniformMap);
}
// Add uniforms for decoding quantized attributes if used
if (model.extensionsUsed.WEB3D_quantized_attributes) {
var quantizedUniformMap = createUniformsForQuantizedAttributes(model, primitive);
uniformMap = combine(uniformMap, quantizedUniformMap);
}
var attribute = vertexArray.attributes.POSITION;
var componentDatatype = attribute.componentDatatype;
var typedArray = attribute.vertexBuffer;
var byteOffset = typedArray.byteOffset;
var bufferLength = typedArray.byteLength / ComponentDatatype.getSizeInBytes(componentDatatype);
var positionsBuffer = ComponentDatatype.createArrayBufferView(componentDatatype, typedArray.buffer, byteOffset, bufferLength);
attribute = vertexArray.attributes._BATCHID;
componentDatatype = attribute.componentDatatype;
typedArray = attribute.vertexBuffer;
byteOffset = typedArray.byteOffset;
bufferLength = typedArray.byteLength / ComponentDatatype.getSizeInBytes(componentDatatype);
var vertexBatchIds = ComponentDatatype.createArrayBufferView(componentDatatype, typedArray.buffer, byteOffset, bufferLength);
var buffer = vertexArray.indexBuffer.typedArray;
var indices;
if (vertexArray.indexBuffer.indexDatatype === IndexDatatype.UNSIGNED_SHORT) {
indices = new Uint16Array(buffer.buffer, buffer.byteOffset, buffer.byteLength / Uint16Array.BYTES_PER_ELEMENT);
} else {
indices = new Uint32Array(buffer.buffer, buffer.byteOffset, buffer.byteLength / Uint32Array.BYTES_PER_ELEMENT);
}
positionsBuffer = arraySlice(positionsBuffer);
vertexBatchIds = arraySlice(vertexBatchIds);
indices = arraySlice(indices, offset, offset + count);
var batchIds = [];
var indexCounts = [];
var indexOffsets = [];
var batchedIndices = [];
var currentId = vertexBatchIds[indices[0]];
batchIds.push(currentId);
indexOffsets.push(0);
var batchId;
var indexOffset;
var indexCount;
var indicesLength = indices.length;
for (var j = 1; j < indicesLength; ++j) {
batchId = vertexBatchIds[indices[j]];
if (batchId !== currentId) {
indexOffset = indexOffsets[indexOffsets.length - 1];
indexCount = j - indexOffset;
batchIds.push(batchId);
indexCounts.push(indexCount);
indexOffsets.push(j);
batchedIndices.push(new Vector3DTileBatch({
offset : indexOffset,
count : indexCount,
batchIds : [currentId],
color : Color.WHITE
}));
currentId = batchId;
}
}
indexOffset = indexOffsets[indexOffsets.length - 1];
indexCount = indicesLength - indexOffset;
indexCounts.push(indexCount);
batchedIndices.push(new Vector3DTileBatch({
offset : indexOffset,
count : indexCount,
batchIds : [currentId],
color : Color.WHITE
}));
var shader = model._shaderProgram;
var vertexShaderSource = shader.vertexShaderSource;
var fragmentShaderSource = shader.fragmentShaderSource;
var attributeLocations = shader.attributeLocations;
var pickId = defined(model._pickIdLoaded) ? model._pickIdLoaded() : undefined;
model._primitive = new Vector3DTilePrimitive({
classificationType : model._classificationType,
positions : positionsBuffer,
indices : indices,
indexOffsets : indexOffsets,
indexCounts : indexCounts,
batchIds : batchIds,
vertexBatchIds : vertexBatchIds,
batchedIndices : batchedIndices,
batchTable : batchTable,
boundingVolume : new BoundingSphere(), // updated in update()
_vertexShaderSource : vertexShaderSource,
_fragmentShaderSource : fragmentShaderSource,
_attributeLocations : attributeLocations,
_uniformMap : uniformMap,
_pickId : pickId,
_modelMatrix : new Matrix4(), // updated in update()
_boundingSphere : boundingSphere // used to update boundingVolume
});
// Release CPU resources
model._buffers = undefined;
model._vertexArray = undefined;
model._shaderProgram = undefined;
model._uniformMap = undefined;
}
function createRuntimeNodes(model) {
var loadResources = model._loadResources;
if (!loadResources.finished()) {
return;
}
if (defined(model._primitive)) {
return;
}
var gltf = model.gltf;
var nodes = gltf.nodes;
var gltfNode = nodes[0];
model._nodeMatrix = ModelUtility.getTransform(gltfNode, model._nodeMatrix);
createPrimitive(model);
}
function createResources(model, frameState) {
var context = frameState.context;
ModelUtility.checkSupportedGlExtensions(model.gltf.glExtensionsUsed, context);
createBuffers(model); // using glTF bufferViews
createProgram(model);
createVertexArray(model); // using glTF meshes
createUniformMap(model, context); // using glTF materials/techniques
createRuntimeNodes(model); // using glTF scene
}
///////////////////////////////////////////////////////////////////////////
var scratchComputedTranslation = new Cartesian4();
var scratchComputedMatrixIn2D = new Matrix4();
function updateNodeModelMatrix(model, modelTransformChanged, justLoaded, projection) {
var computedModelMatrix = model._computedModelMatrix;
if ((model._mode !== SceneMode.SCENE3D) && !model._ignoreCommands) {
var translation = Matrix4.getColumn(computedModelMatrix, 3, scratchComputedTranslation);
if (!Cartesian4.equals(translation, Cartesian4.UNIT_W)) {
computedModelMatrix = Transforms.basisTo2D(projection, computedModelMatrix, scratchComputedMatrixIn2D);
model._rtcCenter = model._rtcCenter3D;
} else {
var center = model.boundingSphere.center;
var to2D = Transforms.wgs84To2DModelMatrix(projection, center, scratchComputedMatrixIn2D);
computedModelMatrix = Matrix4.multiply(to2D, computedModelMatrix, scratchComputedMatrixIn2D);
if (defined(model._rtcCenter)) {
Matrix4.setTranslation(computedModelMatrix, Cartesian4.UNIT_W, computedModelMatrix);
model._rtcCenter = model._rtcCenter2D;
}
}
}
var primitive = model._primitive;
if (modelTransformChanged || justLoaded) {
Matrix4.multiplyTransformation(computedModelMatrix, model._nodeMatrix, primitive._modelMatrix);
BoundingSphere.transform(primitive._boundingSphere, primitive._modelMatrix, primitive._boundingVolume);
if (defined(model._rtcCenter)) {
Cartesian3.add(model._rtcCenter, primitive._boundingVolume.center, primitive._boundingVolume.center);
}
}
}
///////////////////////////////////////////////////////////////////////////
ClassificationModel.prototype.updateCommands = function(batchId, color) {
this._primitive.updateCommands(batchId, color);
};
ClassificationModel.prototype.update = function(frameState) {
if (frameState.mode === SceneMode.MORPHING) {
return;
}
if ((this._state === ModelState.NEEDS_LOAD) && defined(this.gltf)) {
this._state = ModelState.LOADING;
if (this._state !== ModelState.FAILED) {
var extensions = this.gltf.extensions;
if (defined(extensions) && defined(extensions.CESIUM_RTC)) {
var center = Cartesian3.fromArray(extensions.CESIUM_RTC.center);
if (!Cartesian3.equals(center, Cartesian3.ZERO)) {
this._rtcCenter3D = center;
var projection = frameState.mapProjection;
var ellipsoid = projection.ellipsoid;
var cartographic = ellipsoid.cartesianToCartographic(this._rtcCenter3D);
var projectedCart = projection.project(cartographic);
Cartesian3.fromElements(projectedCart.z, projectedCart.x, projectedCart.y, projectedCart);
this._rtcCenter2D = projectedCart;
this._rtcCenterEye = new Cartesian3();
this._rtcCenter = this._rtcCenter3D;
}
}
this._loadResources = new ModelLoadResources();
ModelUtility.parseBuffers(this);
}
}
var loadResources = this._loadResources;
var justLoaded = false;
if (this._state === ModelState.LOADING) {
// Transition from LOADING -> LOADED once resources are downloaded and created.
// Textures may continue to stream in while in the LOADED state.
if (loadResources.pendingBufferLoads === 0) {
ModelUtility.checkSupportedExtensions(this.extensionsRequired);
addBuffersToLoadResources(this);
parseBufferViews(this);
this._boundingSphere = ModelUtility.computeBoundingSphere(this);
this._initialRadius = this._boundingSphere.radius;