-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathglb-parser.js
2501 lines (2133 loc) · 89.6 KB
/
glb-parser.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
import { Debug } from '../../core/debug.js';
import { path } from '../../core/path.js';
import { Color } from '../../core/math/color.js';
import { Mat4 } from '../../core/math/mat4.js';
import { math } from '../../core/math/math.js';
import { Vec2 } from '../../core/math/vec2.js';
import { Vec3 } from '../../core/math/vec3.js';
import { BoundingBox } from '../../core/shape/bounding-box.js';
import {
typedArrayTypes, typedArrayTypesByteSize,
ADDRESS_CLAMP_TO_EDGE, ADDRESS_MIRRORED_REPEAT, ADDRESS_REPEAT,
BUFFER_STATIC,
CULLFACE_NONE, CULLFACE_BACK,
FILTER_NEAREST, FILTER_LINEAR, FILTER_NEAREST_MIPMAP_NEAREST, FILTER_LINEAR_MIPMAP_NEAREST, FILTER_NEAREST_MIPMAP_LINEAR, FILTER_LINEAR_MIPMAP_LINEAR,
INDEXFORMAT_UINT8, INDEXFORMAT_UINT16, INDEXFORMAT_UINT32,
PRIMITIVE_LINELOOP, PRIMITIVE_LINESTRIP, PRIMITIVE_LINES, PRIMITIVE_POINTS, PRIMITIVE_TRIANGLES, PRIMITIVE_TRIFAN, PRIMITIVE_TRISTRIP,
SEMANTIC_POSITION, SEMANTIC_NORMAL, SEMANTIC_TANGENT, SEMANTIC_COLOR, SEMANTIC_BLENDINDICES, SEMANTIC_BLENDWEIGHT,
SEMANTIC_TEXCOORD0, SEMANTIC_TEXCOORD1, SEMANTIC_TEXCOORD2, SEMANTIC_TEXCOORD3, SEMANTIC_TEXCOORD4, SEMANTIC_TEXCOORD5, SEMANTIC_TEXCOORD6, SEMANTIC_TEXCOORD7,
TYPE_INT8, TYPE_UINT8, TYPE_INT16, TYPE_UINT16, TYPE_INT32, TYPE_UINT32, TYPE_FLOAT32
} from '../../platform/graphics/constants.js';
import { IndexBuffer } from '../../platform/graphics/index-buffer.js';
import { Texture } from '../../platform/graphics/texture.js';
import { VertexBuffer } from '../../platform/graphics/vertex-buffer.js';
import { VertexFormat } from '../../platform/graphics/vertex-format.js';
import { http } from '../../platform/net/http.js';
import {
BLEND_NONE, BLEND_NORMAL, LIGHTFALLOFF_INVERSESQUARED,
PROJECTION_ORTHOGRAPHIC, PROJECTION_PERSPECTIVE,
ASPECT_MANUAL, ASPECT_AUTO, SPECOCC_AO
} from '../../scene/constants.js';
import { GraphNode } from '../../scene/graph-node.js';
import { Light, lightTypes } from '../../scene/light.js';
import { Mesh } from '../../scene/mesh.js';
import { Morph } from '../../scene/morph.js';
import { MorphTarget } from '../../scene/morph-target.js';
import { calculateNormals } from '../../scene/procedural.js';
import { Render } from '../../scene/render.js';
import { Skin } from '../../scene/skin.js';
import { StandardMaterial } from '../../scene/materials/standard-material.js';
import { Entity } from '../entity.js';
import { INTERPOLATION_CUBIC, INTERPOLATION_LINEAR, INTERPOLATION_STEP } from '../anim/constants.js';
import { AnimCurve } from '../anim/evaluator/anim-curve.js';
import { AnimData } from '../anim/evaluator/anim-data.js';
import { AnimTrack } from '../anim/evaluator/anim-track.js';
import { Asset } from '../asset/asset.js';
import { ABSOLUTE_URL } from '../asset/constants.js';
import { dracoDecode } from './draco-decoder.js';
// resources loaded from GLB file that the parser returns
class GlbResources {
gltf;
nodes;
scenes;
animations;
textures;
materials;
variants;
meshVariants;
meshDefaultMaterials;
renders;
skins;
lights;
cameras;
destroy() {
// render needs to dec ref meshes
if (this.renders) {
this.renders.forEach((render) => {
render.meshes = null;
});
}
}
}
const isDataURI = (uri) => {
return /^data:.*,.*$/i.test(uri);
};
const getDataURIMimeType = (uri) => {
return uri.substring(uri.indexOf(':') + 1, uri.indexOf(';'));
};
const getNumComponents = (accessorType) => {
switch (accessorType) {
case 'SCALAR': return 1;
case 'VEC2': return 2;
case 'VEC3': return 3;
case 'VEC4': return 4;
case 'MAT2': return 4;
case 'MAT3': return 9;
case 'MAT4': return 16;
default: return 3;
}
};
const getComponentType = (componentType) => {
switch (componentType) {
case 5120: return TYPE_INT8;
case 5121: return TYPE_UINT8;
case 5122: return TYPE_INT16;
case 5123: return TYPE_UINT16;
case 5124: return TYPE_INT32;
case 5125: return TYPE_UINT32;
case 5126: return TYPE_FLOAT32;
default: return 0;
}
};
const getComponentSizeInBytes = (componentType) => {
switch (componentType) {
case 5120: return 1; // int8
case 5121: return 1; // uint8
case 5122: return 2; // int16
case 5123: return 2; // uint16
case 5124: return 4; // int32
case 5125: return 4; // uint32
case 5126: return 4; // float32
default: return 0;
}
};
const getComponentDataType = (componentType) => {
switch (componentType) {
case 5120: return Int8Array;
case 5121: return Uint8Array;
case 5122: return Int16Array;
case 5123: return Uint16Array;
case 5124: return Int32Array;
case 5125: return Uint32Array;
case 5126: return Float32Array;
default: return null;
}
};
const gltfToEngineSemanticMap = {
'POSITION': SEMANTIC_POSITION,
'NORMAL': SEMANTIC_NORMAL,
'TANGENT': SEMANTIC_TANGENT,
'COLOR_0': SEMANTIC_COLOR,
'JOINTS_0': SEMANTIC_BLENDINDICES,
'WEIGHTS_0': SEMANTIC_BLENDWEIGHT,
'TEXCOORD_0': SEMANTIC_TEXCOORD0,
'TEXCOORD_1': SEMANTIC_TEXCOORD1,
'TEXCOORD_2': SEMANTIC_TEXCOORD2,
'TEXCOORD_3': SEMANTIC_TEXCOORD3,
'TEXCOORD_4': SEMANTIC_TEXCOORD4,
'TEXCOORD_5': SEMANTIC_TEXCOORD5,
'TEXCOORD_6': SEMANTIC_TEXCOORD6,
'TEXCOORD_7': SEMANTIC_TEXCOORD7
};
// order vertexDesc to match the rest of the engine
const attributeOrder = {
[SEMANTIC_POSITION]: 0,
[SEMANTIC_NORMAL]: 1,
[SEMANTIC_TANGENT]: 2,
[SEMANTIC_COLOR]: 3,
[SEMANTIC_BLENDINDICES]: 4,
[SEMANTIC_BLENDWEIGHT]: 5,
[SEMANTIC_TEXCOORD0]: 6,
[SEMANTIC_TEXCOORD1]: 7,
[SEMANTIC_TEXCOORD2]: 8,
[SEMANTIC_TEXCOORD3]: 9,
[SEMANTIC_TEXCOORD4]: 10,
[SEMANTIC_TEXCOORD5]: 11,
[SEMANTIC_TEXCOORD6]: 12,
[SEMANTIC_TEXCOORD7]: 13
};
// returns a function for dequantizing the data type
const getDequantizeFunc = (srcType) => {
// see https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization#encoding-quantized-data
switch (srcType) {
case TYPE_INT8: return x => Math.max(x / 127.0, -1.0);
case TYPE_UINT8: return x => x / 255.0;
case TYPE_INT16: return x => Math.max(x / 32767.0, -1.0);
case TYPE_UINT16: return x => x / 65535.0;
default: return x => x;
}
};
// dequantize an array of data
const dequantizeArray = (dstArray, srcArray, srcType) => {
const convFunc = getDequantizeFunc(srcType);
const len = srcArray.length;
for (let i = 0; i < len; ++i) {
dstArray[i] = convFunc(srcArray[i]);
}
return dstArray;
};
// get accessor data, making a copy and patching in the case of a sparse accessor
const getAccessorData = (gltfAccessor, bufferViews, flatten = false) => {
const numComponents = getNumComponents(gltfAccessor.type);
const dataType = getComponentDataType(gltfAccessor.componentType);
if (!dataType) {
return null;
}
let result;
if (gltfAccessor.sparse) {
// handle sparse data
const sparse = gltfAccessor.sparse;
// get indices data
const indicesAccessor = {
count: sparse.count,
type: 'SCALAR'
};
const indices = getAccessorData(Object.assign(indicesAccessor, sparse.indices), bufferViews, true);
// data values data
const valuesAccessor = {
count: sparse.count,
type: gltfAccessor.type,
componentType: gltfAccessor.componentType
};
const values = getAccessorData(Object.assign(valuesAccessor, sparse.values), bufferViews, true);
// get base data
if (gltfAccessor.hasOwnProperty('bufferView')) {
const baseAccessor = {
bufferView: gltfAccessor.bufferView,
byteOffset: gltfAccessor.byteOffset,
componentType: gltfAccessor.componentType,
count: gltfAccessor.count,
type: gltfAccessor.type
};
// make a copy of the base data since we'll patch the values
result = getAccessorData(baseAccessor, bufferViews, true).slice();
} else {
// there is no base data, create empty 0'd out data
result = new dataType(gltfAccessor.count * numComponents);
}
for (let i = 0; i < sparse.count; ++i) {
const targetIndex = indices[i];
for (let j = 0; j < numComponents; ++j) {
result[targetIndex * numComponents + j] = values[i * numComponents + j];
}
}
} else {
if (gltfAccessor.hasOwnProperty("bufferView")) {
const bufferView = bufferViews[gltfAccessor.bufferView];
if (flatten && bufferView.hasOwnProperty('byteStride')) {
// flatten stridden data
const bytesPerElement = numComponents * dataType.BYTES_PER_ELEMENT;
const storage = new ArrayBuffer(gltfAccessor.count * bytesPerElement);
const tmpArray = new Uint8Array(storage);
let dstOffset = 0;
for (let i = 0; i < gltfAccessor.count; ++i) {
// no need to add bufferView.byteOffset because accessor takes this into account
let srcOffset = (gltfAccessor.byteOffset || 0) + i * bufferView.byteStride;
for (let b = 0; b < bytesPerElement; ++b) {
tmpArray[dstOffset++] = bufferView[srcOffset++];
}
}
result = new dataType(storage);
} else {
result = new dataType(bufferView.buffer,
bufferView.byteOffset + (gltfAccessor.byteOffset || 0),
gltfAccessor.count * numComponents);
}
} else {
result = new dataType(gltfAccessor.count * numComponents);
}
}
return result;
};
// get accessor data as (unnormalized, unquantized) Float32 data
const getAccessorDataFloat32 = (gltfAccessor, bufferViews) => {
const data = getAccessorData(gltfAccessor, bufferViews, true);
if (data instanceof Float32Array || !gltfAccessor.normalized) {
// if the source data is quantized (say to int16), but not normalized
// then reading the values of the array is the same whether the values
// are stored as float32 or int16. so probably no need to convert to
// float32.
return data;
}
const float32Data = new Float32Array(data.length);
dequantizeArray(float32Data, data, getComponentType(gltfAccessor.componentType));
return float32Data;
};
// returns a dequantized bounding box for the accessor
const getAccessorBoundingBox = (gltfAccessor) => {
let min = gltfAccessor.min;
let max = gltfAccessor.max;
if (!min || !max) {
return null;
}
if (gltfAccessor.normalized) {
const ctype = getComponentType(gltfAccessor.componentType);
min = dequantizeArray([], min, ctype);
max = dequantizeArray([], max, ctype);
}
return new BoundingBox(
new Vec3((max[0] + min[0]) * 0.5, (max[1] + min[1]) * 0.5, (max[2] + min[2]) * 0.5),
new Vec3((max[0] - min[0]) * 0.5, (max[1] - min[1]) * 0.5, (max[2] - min[2]) * 0.5)
);
};
const getPrimitiveType = (primitive) => {
if (!primitive.hasOwnProperty('mode')) {
return PRIMITIVE_TRIANGLES;
}
switch (primitive.mode) {
case 0: return PRIMITIVE_POINTS;
case 1: return PRIMITIVE_LINES;
case 2: return PRIMITIVE_LINELOOP;
case 3: return PRIMITIVE_LINESTRIP;
case 4: return PRIMITIVE_TRIANGLES;
case 5: return PRIMITIVE_TRISTRIP;
case 6: return PRIMITIVE_TRIFAN;
default: return PRIMITIVE_TRIANGLES;
}
};
const generateIndices = (numVertices) => {
const dummyIndices = new Uint16Array(numVertices);
for (let i = 0; i < numVertices; i++) {
dummyIndices[i] = i;
}
return dummyIndices;
};
const generateNormals = (sourceDesc, indices) => {
// get positions
const p = sourceDesc[SEMANTIC_POSITION];
if (!p || p.components !== 3) {
return;
}
let positions;
if (p.size !== p.stride) {
// extract positions which aren't tightly packed
const srcStride = p.stride / typedArrayTypesByteSize[p.type];
const src = new typedArrayTypes[p.type](p.buffer, p.offset, p.count * srcStride);
positions = new typedArrayTypes[p.type](p.count * 3);
for (let i = 0; i < p.count; ++i) {
positions[i * 3 + 0] = src[i * srcStride + 0];
positions[i * 3 + 1] = src[i * srcStride + 1];
positions[i * 3 + 2] = src[i * srcStride + 2];
}
} else {
// position data is tightly packed so we can use it directly
positions = new typedArrayTypes[p.type](p.buffer, p.offset, p.count * 3);
}
const numVertices = p.count;
// generate indices if necessary
if (!indices) {
indices = generateIndices(numVertices);
}
// generate normals
const normalsTemp = calculateNormals(positions, indices);
const normals = new Float32Array(normalsTemp.length);
normals.set(normalsTemp);
sourceDesc[SEMANTIC_NORMAL] = {
buffer: normals.buffer,
size: 12,
offset: 0,
stride: 12,
count: numVertices,
components: 3,
type: TYPE_FLOAT32
};
};
const flipTexCoordVs = (vertexBuffer) => {
let i, j;
const floatOffsets = [];
const shortOffsets = [];
const byteOffsets = [];
for (i = 0; i < vertexBuffer.format.elements.length; ++i) {
const element = vertexBuffer.format.elements[i];
if (element.name === SEMANTIC_TEXCOORD0 ||
element.name === SEMANTIC_TEXCOORD1) {
switch (element.dataType) {
case TYPE_FLOAT32:
floatOffsets.push({ offset: element.offset / 4 + 1, stride: element.stride / 4 });
break;
case TYPE_UINT16:
shortOffsets.push({ offset: element.offset / 2 + 1, stride: element.stride / 2 });
break;
case TYPE_UINT8:
byteOffsets.push({ offset: element.offset + 1, stride: element.stride });
break;
}
}
}
const flip = (offsets, type, one) => {
const typedArray = new type(vertexBuffer.storage);
for (i = 0; i < offsets.length; ++i) {
let index = offsets[i].offset;
const stride = offsets[i].stride;
for (j = 0; j < vertexBuffer.numVertices; ++j) {
typedArray[index] = one - typedArray[index];
index += stride;
}
}
};
if (floatOffsets.length > 0) {
flip(floatOffsets, Float32Array, 1.0);
}
if (shortOffsets.length > 0) {
flip(shortOffsets, Uint16Array, 65535);
}
if (byteOffsets.length > 0) {
flip(byteOffsets, Uint8Array, 255);
}
};
// given a texture, clone it
// NOTE: CPU-side texture data will be shared but GPU memory will be duplicated
const cloneTexture = (texture) => {
const shallowCopyLevels = (texture) => {
const result = [];
for (let mip = 0; mip < texture._levels.length; ++mip) {
let level = [];
if (texture.cubemap) {
for (let face = 0; face < 6; ++face) {
level.push(texture._levels[mip][face]);
}
} else {
level = texture._levels[mip];
}
result.push(level);
}
return result;
};
const result = new Texture(texture.device, texture); // duplicate texture
result._levels = shallowCopyLevels(texture); // shallow copy the levels structure
return result;
};
// given a texture asset, clone it
const cloneTextureAsset = (src) => {
const result = new Asset(src.name + '_clone',
src.type,
src.file,
src.data,
src.options);
result.loaded = true;
result.resource = cloneTexture(src.resource);
src.registry.add(result);
return result;
};
const createVertexBufferInternal = (device, sourceDesc, flipV) => {
const positionDesc = sourceDesc[SEMANTIC_POSITION];
if (!positionDesc) {
// ignore meshes without positions
return null;
}
const numVertices = positionDesc.count;
// generate vertexDesc elements
const vertexDesc = [];
for (const semantic in sourceDesc) {
if (sourceDesc.hasOwnProperty(semantic)) {
const element = {
semantic: semantic,
components: sourceDesc[semantic].components,
type: sourceDesc[semantic].type,
normalize: !!sourceDesc[semantic].normalize
};
if (!VertexFormat.isElementValid(device, element)) {
// WebGP does not support some formats and we need to remap it to one larger, for example int16x3 -> int16x4
// TODO: this might need the actual data changes if this element is the last one in the vertex, as it might
// try to read outside of the vertex buffer.
element.components++;
}
vertexDesc.push(element);
}
}
// sort vertex elements by engine-ideal order
vertexDesc.sort((lhs, rhs) => {
return attributeOrder[lhs.semantic] - attributeOrder[rhs.semantic];
});
let i, j, k;
let source, target, sourceOffset;
const vertexFormat = new VertexFormat(device, vertexDesc);
// check whether source data is correctly interleaved
let isCorrectlyInterleaved = true;
for (i = 0; i < vertexFormat.elements.length; ++i) {
target = vertexFormat.elements[i];
source = sourceDesc[target.name];
sourceOffset = source.offset - positionDesc.offset;
if ((source.buffer !== positionDesc.buffer) ||
(source.stride !== target.stride) ||
(source.size !== target.size) ||
(sourceOffset !== target.offset)) {
isCorrectlyInterleaved = false;
break;
}
}
// create vertex buffer
const vertexBuffer = new VertexBuffer(device,
vertexFormat,
numVertices,
BUFFER_STATIC);
const vertexData = vertexBuffer.lock();
const targetArray = new Uint32Array(vertexData);
let sourceArray;
if (isCorrectlyInterleaved) {
// copy data
sourceArray = new Uint32Array(positionDesc.buffer,
positionDesc.offset,
numVertices * vertexBuffer.format.size / 4);
targetArray.set(sourceArray);
} else {
let targetStride, sourceStride;
// copy data and interleave
for (i = 0; i < vertexBuffer.format.elements.length; ++i) {
target = vertexBuffer.format.elements[i];
targetStride = target.stride / 4;
source = sourceDesc[target.name];
sourceStride = source.stride / 4;
// ensure we don't go beyond the end of the arraybuffer when dealing with
// interlaced vertex formats
sourceArray = new Uint32Array(source.buffer, source.offset, (source.count - 1) * sourceStride + (source.size + 3) / 4);
let src = 0;
let dst = target.offset / 4;
const kend = Math.floor((source.size + 3) / 4);
for (j = 0; j < numVertices; ++j) {
for (k = 0; k < kend; ++k) {
targetArray[dst + k] = sourceArray[src + k];
}
src += sourceStride;
dst += targetStride;
}
}
}
if (flipV) {
flipTexCoordVs(vertexBuffer);
}
vertexBuffer.unlock();
return vertexBuffer;
};
const createVertexBuffer = (device, attributes, indices, accessors, bufferViews, flipV, vertexBufferDict) => {
// extract list of attributes to use
const useAttributes = {};
const attribIds = [];
for (const attrib in attributes) {
if (attributes.hasOwnProperty(attrib) && gltfToEngineSemanticMap.hasOwnProperty(attrib)) {
useAttributes[attrib] = attributes[attrib];
// build unique id for each attribute in format: Semantic:accessorIndex
attribIds.push(attrib + ':' + attributes[attrib]);
}
}
// sort unique ids and create unique vertex buffer ID
attribIds.sort();
const vbKey = attribIds.join();
// return already created vertex buffer if identical
let vb = vertexBufferDict[vbKey];
if (!vb) {
// build vertex buffer format desc and source
const sourceDesc = {};
for (const attrib in useAttributes) {
const accessor = accessors[attributes[attrib]];
const accessorData = getAccessorData(accessor, bufferViews);
const bufferView = bufferViews[accessor.bufferView];
const semantic = gltfToEngineSemanticMap[attrib];
const size = getNumComponents(accessor.type) * getComponentSizeInBytes(accessor.componentType);
const stride = bufferView && bufferView.hasOwnProperty('byteStride') ? bufferView.byteStride : size;
sourceDesc[semantic] = {
buffer: accessorData.buffer,
size: size,
offset: accessorData.byteOffset,
stride: stride,
count: accessor.count,
components: getNumComponents(accessor.type),
type: getComponentType(accessor.componentType),
normalize: accessor.normalized
};
}
// generate normals if they're missing (this should probably be a user option)
if (!sourceDesc.hasOwnProperty(SEMANTIC_NORMAL)) {
generateNormals(sourceDesc, indices);
}
// create and store it in the dictionary
vb = createVertexBufferInternal(device, sourceDesc, flipV);
vertexBufferDict[vbKey] = vb;
}
return vb;
};
const createSkin = (device, gltfSkin, accessors, bufferViews, nodes, glbSkins) => {
let i, j, bindMatrix;
const joints = gltfSkin.joints;
const numJoints = joints.length;
const ibp = [];
if (gltfSkin.hasOwnProperty('inverseBindMatrices')) {
const inverseBindMatrices = gltfSkin.inverseBindMatrices;
const ibmData = getAccessorData(accessors[inverseBindMatrices], bufferViews, true);
const ibmValues = [];
for (i = 0; i < numJoints; i++) {
for (j = 0; j < 16; j++) {
ibmValues[j] = ibmData[i * 16 + j];
}
bindMatrix = new Mat4();
bindMatrix.set(ibmValues);
ibp.push(bindMatrix);
}
} else {
for (i = 0; i < numJoints; i++) {
bindMatrix = new Mat4();
ibp.push(bindMatrix);
}
}
const boneNames = [];
for (i = 0; i < numJoints; i++) {
boneNames[i] = nodes[joints[i]].name;
}
// create a cache key from bone names and see if we have matching skin
const key = boneNames.join('#');
let skin = glbSkins.get(key);
if (!skin) {
// create the skin and add it to the cache
skin = new Skin(device, ibp, boneNames);
glbSkins.set(key, skin);
}
return skin;
};
const createDracoMesh = (device, primitive, accessors, bufferViews, meshVariants, meshDefaultMaterials, promises) => {
// create the mesh
const result = new Mesh(device);
result.aabb = getAccessorBoundingBox(accessors[primitive.attributes.POSITION]);
// create vertex description
const vertexDesc = [];
for (const [name, index] of Object.entries(primitive.attributes)) {
const accessor = accessors[index];
const semantic = gltfToEngineSemanticMap[name];
const componentType = getComponentType(accessor.componentType);
vertexDesc.push({
semantic: semantic,
components: getNumComponents(accessor.type),
type: componentType,
normalize: accessor.normalized ?? (semantic === SEMANTIC_COLOR && (componentType === TYPE_UINT8 || componentType === TYPE_UINT16))
});
}
promises.push(new Promise((resolve, reject) => {
// decode draco data
const dracoExt = primitive.extensions.KHR_draco_mesh_compression;
dracoDecode(bufferViews[dracoExt.bufferView].slice().buffer, (err, decompressedData) => {
if (err) {
console.log(err);
reject(err);
} else {
// worker reports order of attributes as array of attribute unique_id
const order = { };
for (const [name, index] of Object.entries(dracoExt.attributes)) {
order[gltfToEngineSemanticMap[name]] = decompressedData.attributes.indexOf(index);
}
// order vertexDesc
vertexDesc.sort((a, b) => {
return order[a.semantic] - order[b.semantic];
});
// draco decompressor will generate normals if they are missing
if (!primitive.attributes?.NORMAL) {
vertexDesc.splice(1, 0, {
semantic: 'NORMAL',
components: 3,
type: TYPE_FLOAT32
});
}
const vertexFormat = new VertexFormat(device, vertexDesc);
// create vertex buffer
const numVertices = decompressedData.vertices.byteLength / vertexFormat.size;
const indexFormat = numVertices <= 65535 ? INDEXFORMAT_UINT16 : INDEXFORMAT_UINT32;
const numIndices = decompressedData.indices.byteLength / (numVertices <= 65535 ? 2 : 4);
Debug.call(() => {
if (numVertices !== accessors[primitive.attributes.POSITION].count) {
Debug.warn('mesh has invalid vertex count');
}
if (numIndices !== accessors[primitive.indices].count) {
Debug.warn('mesh has invalid index count');
}
});
const vertexBuffer = new VertexBuffer(device, vertexFormat, numVertices, BUFFER_STATIC, decompressedData.vertices);
const indexBuffer = new IndexBuffer(device, indexFormat, numIndices, BUFFER_STATIC, decompressedData.indices);
result.vertexBuffer = vertexBuffer;
result.indexBuffer[0] = indexBuffer;
result.primitive[0].type = getPrimitiveType(primitive);
result.primitive[0].base = 0;
result.primitive[0].count = indexBuffer ? numIndices : numVertices;
result.primitive[0].indexed = !!indexBuffer;
resolve();
}
});
}));
// handle material variants
if (primitive?.extensions?.KHR_materials_variants) {
const variants = primitive.extensions.KHR_materials_variants;
const tempMapping = {};
variants.mappings.forEach((mapping) => {
mapping.variants.forEach((variant) => {
tempMapping[variant] = mapping.material;
});
});
meshVariants[result.id] = tempMapping;
}
meshDefaultMaterials[result.id] = primitive.material;
return result;
};
const createMesh = (device, gltfMesh, accessors, bufferViews, flipV, vertexBufferDict, meshVariants, meshDefaultMaterials, assetOptions, promises) => {
const meshes = [];
gltfMesh.primitives.forEach((primitive) => {
if (primitive.extensions?.KHR_draco_mesh_compression) {
// handle draco compressed mesh
meshes.push(createDracoMesh(device, primitive, accessors, bufferViews, meshVariants, meshDefaultMaterials, promises));
} else {
// handle uncompressed mesh
let indices = primitive.hasOwnProperty('indices') ? getAccessorData(accessors[primitive.indices], bufferViews, true) : null;
const vertexBuffer = createVertexBuffer(device, primitive.attributes, indices, accessors, bufferViews, flipV, vertexBufferDict);
const primitiveType = getPrimitiveType(primitive);
// build the mesh
const mesh = new Mesh(device);
mesh.vertexBuffer = vertexBuffer;
mesh.primitive[0].type = primitiveType;
mesh.primitive[0].base = 0;
mesh.primitive[0].indexed = (indices !== null);
// index buffer
if (indices !== null) {
let indexFormat;
if (indices instanceof Uint8Array) {
indexFormat = INDEXFORMAT_UINT8;
} else if (indices instanceof Uint16Array) {
indexFormat = INDEXFORMAT_UINT16;
} else {
indexFormat = INDEXFORMAT_UINT32;
}
// 32bit index buffer is used but not supported
if (indexFormat === INDEXFORMAT_UINT32 && !device.extUintElement) {
// #if _DEBUG
if (vertexBuffer.numVertices > 0xFFFF) {
console.warn('Glb file contains 32bit index buffer but these are not supported by this device - it may be rendered incorrectly.');
}
// #endif
// convert to 16bit
indexFormat = INDEXFORMAT_UINT16;
indices = new Uint16Array(indices);
}
if (indexFormat === INDEXFORMAT_UINT8 && device.isWebGPU) {
Debug.warn('Glb file contains 8bit index buffer but these are not supported by WebGPU - converting to 16bit.');
// convert to 16bit
indexFormat = INDEXFORMAT_UINT16;
indices = new Uint16Array(indices);
}
const indexBuffer = new IndexBuffer(device, indexFormat, indices.length, BUFFER_STATIC, indices);
mesh.indexBuffer[0] = indexBuffer;
mesh.primitive[0].count = indices.length;
} else {
mesh.primitive[0].count = vertexBuffer.numVertices;
}
if (primitive.hasOwnProperty("extensions") && primitive.extensions.hasOwnProperty("KHR_materials_variants")) {
const variants = primitive.extensions.KHR_materials_variants;
const tempMapping = {};
variants.mappings.forEach((mapping) => {
mapping.variants.forEach((variant) => {
tempMapping[variant] = mapping.material;
});
});
meshVariants[mesh.id] = tempMapping;
}
meshDefaultMaterials[mesh.id] = primitive.material;
let accessor = accessors[primitive.attributes.POSITION];
mesh.aabb = getAccessorBoundingBox(accessor);
// morph targets
if (primitive.hasOwnProperty('targets')) {
const targets = [];
primitive.targets.forEach((target, index) => {
const options = {};
if (target.hasOwnProperty('POSITION')) {
accessor = accessors[target.POSITION];
options.deltaPositions = getAccessorDataFloat32(accessor, bufferViews);
options.deltaPositionsType = TYPE_FLOAT32;
options.aabb = getAccessorBoundingBox(accessor);
}
if (target.hasOwnProperty('NORMAL')) {
accessor = accessors[target.NORMAL];
// NOTE: the morph targets can't currently accept quantized normals
options.deltaNormals = getAccessorDataFloat32(accessor, bufferViews);
options.deltaNormalsType = TYPE_FLOAT32;
}
// name if specified
if (gltfMesh.hasOwnProperty('extras') &&
gltfMesh.extras.hasOwnProperty('targetNames')) {
options.name = gltfMesh.extras.targetNames[index];
} else {
options.name = index.toString(10);
}
// default weight if specified
if (gltfMesh.hasOwnProperty('weights')) {
options.defaultWeight = gltfMesh.weights[index];
}
options.preserveData = assetOptions.morphPreserveData;
targets.push(new MorphTarget(options));
});
mesh.morph = new Morph(targets, device, {
preferHighPrecision: assetOptions.morphPreferHighPrecision
});
}
meshes.push(mesh);
}
});
return meshes;
};
const extractTextureTransform = (source, material, maps) => {
let map;
const texCoord = source.texCoord;
if (texCoord) {
for (map = 0; map < maps.length; ++map) {
material[maps[map] + 'MapUv'] = texCoord;
}
}
const zeros = [0, 0];
const ones = [1, 1];
const textureTransform = source.extensions?.KHR_texture_transform;
if (textureTransform) {
const offset = textureTransform.offset || zeros;
const scale = textureTransform.scale || ones;
const rotation = textureTransform.rotation ? (-textureTransform.rotation * math.RAD_TO_DEG) : 0;
const tilingVec = new Vec2(scale[0], scale[1]);
const offsetVec = new Vec2(offset[0], 1.0 - scale[1] - offset[1]);
for (map = 0; map < maps.length; ++map) {
material[`${maps[map]}MapTiling`] = tilingVec;
material[`${maps[map]}MapOffset`] = offsetVec;
material[`${maps[map]}MapRotation`] = rotation;
}
}
};
const extensionPbrSpecGlossiness = (data, material, textures) => {
let color, texture;
if (data.hasOwnProperty('diffuseFactor')) {
color = data.diffuseFactor;
// Convert from linear space to sRGB space
material.diffuse.set(Math.pow(color[0], 1 / 2.2), Math.pow(color[1], 1 / 2.2), Math.pow(color[2], 1 / 2.2));
material.opacity = color[3];
} else {
material.diffuse.set(1, 1, 1);
material.opacity = 1;
}
if (data.hasOwnProperty('diffuseTexture')) {
const diffuseTexture = data.diffuseTexture;
texture = textures[diffuseTexture.index];
material.diffuseMap = texture;
material.diffuseMapChannel = 'rgb';
material.opacityMap = texture;
material.opacityMapChannel = 'a';
extractTextureTransform(diffuseTexture, material, ['diffuse', 'opacity']);
}
material.useMetalness = false;
if (data.hasOwnProperty('specularFactor')) {
color = data.specularFactor;
// Convert from linear space to sRGB space
material.specular.set(Math.pow(color[0], 1 / 2.2), Math.pow(color[1], 1 / 2.2), Math.pow(color[2], 1 / 2.2));
} else {
material.specular.set(1, 1, 1);
}
if (data.hasOwnProperty('glossinessFactor')) {
material.gloss = data.glossinessFactor;
} else {
material.gloss = 1.0;
}
if (data.hasOwnProperty('specularGlossinessTexture')) {
const specularGlossinessTexture = data.specularGlossinessTexture;
material.specularEncoding = 'srgb';
material.specularMap = material.glossMap = textures[specularGlossinessTexture.index];
material.specularMapChannel = 'rgb';
material.glossMapChannel = 'a';
extractTextureTransform(specularGlossinessTexture, material, ['gloss', 'metalness']);
}
};
const extensionClearCoat = (data, material, textures) => {
if (data.hasOwnProperty('clearcoatFactor')) {
material.clearCoat = data.clearcoatFactor * 0.25; // TODO: remove temporary workaround for replicating glTF clear-coat visuals
} else {
material.clearCoat = 0;
}
if (data.hasOwnProperty('clearcoatTexture')) {
const clearcoatTexture = data.clearcoatTexture;
material.clearCoatMap = textures[clearcoatTexture.index];
material.clearCoatMapChannel = 'r';
extractTextureTransform(clearcoatTexture, material, ['clearCoat']);
}
if (data.hasOwnProperty('clearcoatRoughnessFactor')) {
material.clearCoatGloss = data.clearcoatRoughnessFactor;
} else {
material.clearCoatGloss = 0;
}
if (data.hasOwnProperty('clearcoatRoughnessTexture')) {