forked from aboutcode-org/scancode.io
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsource-decodeI3S.js
More file actions
1656 lines (1512 loc) · 47.4 KB
/
Copy pathsource-decodeI3S.js
File metadata and controls
1656 lines (1512 loc) · 47.4 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 createTaskProcessorWorker from "./createTaskProcessorWorker.js";
import defaultValue from "../Core/defaultValue.js";
import defined from "../Core/defined.js";
import WebMercatorProjection from "../Core/WebMercatorProjection.js";
import Ellipsoid from "../Core/Ellipsoid.js";
import Cartographic from "../Core/Cartographic.js";
import Cartesian3 from "../Core/Cartesian3.js";
import Color from "../Core/Color.js";
import Matrix3 from "../Core/Matrix3.js";
import CesiumMath from "../Core/Math.js";
import dracoModule from "draco3d/draco_decoder_nodejs.js";
import srgbToLinear from "../Core/srgbToLinear.js";
let draco;
function bilinearInterpolate(tx, ty, h00, h10, h01, h11) {
const a = h00 * (1 - tx) + h10 * tx;
const b = h01 * (1 - tx) + h11 * tx;
return a * (1 - ty) + b * ty;
}
function sampleMap(u, v, width, data) {
const address = u + v * width;
return data[address];
}
function sampleGeoid(sampleX, sampleY, geoidData) {
const extent = geoidData.nativeExtent;
let x =
((sampleX - extent.west) / (extent.east - extent.west)) *
(geoidData.width - 1);
let y =
((sampleY - extent.south) / (extent.north - extent.south)) *
(geoidData.height - 1);
const xi = Math.floor(x);
let yi = Math.floor(y);
x -= xi;
y -= yi;
const xNext = xi < geoidData.width ? xi + 1 : xi;
let yNext = yi < geoidData.height ? yi + 1 : yi;
yi = geoidData.height - 1 - yi;
yNext = geoidData.height - 1 - yNext;
const h00 = sampleMap(xi, yi, geoidData.width, geoidData.buffer);
const h10 = sampleMap(xNext, yi, geoidData.width, geoidData.buffer);
const h01 = sampleMap(xi, yNext, geoidData.width, geoidData.buffer);
const h11 = sampleMap(xNext, yNext, geoidData.width, geoidData.buffer);
let finalHeight = bilinearInterpolate(x, y, h00, h10, h01, h11);
finalHeight = finalHeight * geoidData.scale + geoidData.offset;
return finalHeight;
}
function sampleGeoidFromList(lon, lat, geoidDataList) {
for (let i = 0; i < geoidDataList.length; i++) {
const localExtent = geoidDataList[i].nativeExtent;
let localPt = new Cartesian3();
if (geoidDataList[i].projectionType === "WebMercator") {
const radii = geoidDataList[i].projection._ellipsoid._radii;
const webMercatorProj = new WebMercatorProjection(
new Ellipsoid(radii.x, radii.y, radii.z),
);
localPt = webMercatorProj.project(new Cartographic(lon, lat, 0));
} else {
localPt.x = lon;
localPt.y = lat;
}
if (
localPt.x > localExtent.west &&
localPt.x < localExtent.east &&
localPt.y > localExtent.south &&
localPt.y < localExtent.north
) {
return sampleGeoid(localPt.x, localPt.y, geoidDataList[i]);
}
}
return 0;
}
function orthometricToEllipsoidal(
vertexCount,
position,
scale_x,
scale_y,
center,
geoidDataList,
fast,
) {
if (fast) {
// Geometry is already relative to the tile origin which has already been shifted to account for geoid height
// Nothing to do here
return;
}
// For more precision, sample the geoid height at each vertex and shift by the difference between that value and the height at the center of the tile
const centerHeight = sampleGeoidFromList(
center.longitude,
center.latitude,
geoidDataList,
);
for (let i = 0; i < vertexCount; ++i) {
const height = sampleGeoidFromList(
center.longitude + CesiumMath.toRadians(scale_x * position[i * 3]),
center.latitude + CesiumMath.toRadians(scale_y * position[i * 3 + 1]),
geoidDataList,
);
position[i * 3 + 2] += height - centerHeight;
}
}
function transformToLocal(
vertexCount,
positions,
normals,
cartographicCenter,
cartesianCenter,
parentRotation,
ellipsoidRadiiSquare,
scale_x,
scale_y,
) {
if (vertexCount === 0 || !defined(positions) || positions.length === 0) {
return;
}
const ellipsoid = new Ellipsoid(
Math.sqrt(ellipsoidRadiiSquare.x),
Math.sqrt(ellipsoidRadiiSquare.y),
Math.sqrt(ellipsoidRadiiSquare.z),
);
for (let i = 0; i < vertexCount; ++i) {
const indexOffset = i * 3;
const indexOffset1 = indexOffset + 1;
const indexOffset2 = indexOffset + 2;
const cartographic = new Cartographic();
cartographic.longitude =
cartographicCenter.longitude +
CesiumMath.toRadians(scale_x * positions[indexOffset]);
cartographic.latitude =
cartographicCenter.latitude +
CesiumMath.toRadians(scale_y * positions[indexOffset1]);
cartographic.height = cartographicCenter.height + positions[indexOffset2];
const position = {};
ellipsoid.cartographicToCartesian(cartographic, position);
position.x -= cartesianCenter.x;
position.y -= cartesianCenter.y;
position.z -= cartesianCenter.z;
const rotatedPosition = {};
Matrix3.multiplyByVector(parentRotation, position, rotatedPosition);
positions[indexOffset] = rotatedPosition.x;
positions[indexOffset1] = rotatedPosition.y;
positions[indexOffset2] = rotatedPosition.z;
if (defined(normals)) {
const normal = new Cartesian3(
normals[indexOffset],
normals[indexOffset1],
normals[indexOffset2],
);
const rotatedNormal = {};
Matrix3.multiplyByVector(parentRotation, normal, rotatedNormal);
normals[indexOffset] = rotatedNormal.x;
normals[indexOffset1] = rotatedNormal.y;
normals[indexOffset2] = rotatedNormal.z;
}
}
}
function cropUVs(vertexCount, uv0s, uvRegions) {
for (let vertexIndex = 0; vertexIndex < vertexCount; ++vertexIndex) {
const minU = uvRegions[vertexIndex * 4] / 65535.0;
const minV = uvRegions[vertexIndex * 4 + 1] / 65535.0;
const scaleU =
(uvRegions[vertexIndex * 4 + 2] - uvRegions[vertexIndex * 4]) / 65535.0;
const scaleV =
(uvRegions[vertexIndex * 4 + 3] - uvRegions[vertexIndex * 4 + 1]) /
65535.0;
uv0s[vertexIndex * 2] *= scaleU;
uv0s[vertexIndex * 2] += minU;
uv0s[vertexIndex * 2 + 1] *= scaleV;
uv0s[vertexIndex * 2 + 1] += minV;
}
}
function generateIndexArray(
vertexCount,
indices,
colors,
splitGeometryByColorTransparency,
) {
// Allocate array
const indexArray = new Uint32Array(vertexCount);
const vertexIndexFn = defined(indices)
? (vertexIndex) => indices[vertexIndex]
: (vertexIndex) => vertexIndex;
let transparentVertexOffset = 0;
if (splitGeometryByColorTransparency && defined(colors)) {
// The blending alpha mode for opaque colors is not rendered properly.
// If geometry contains both opaque and transparent colors we need to split vertices into two mesh primitives.
// Each mesh primitive could use a separate material with the specific alpha mode depending on the vertex trancparency.
const isVertexTransparentFn = (vertexIndex) =>
colors[vertexIndexFn(vertexIndex) * 4 + 3] < 255;
// Copy opaque vertices first
for (let vertexIndex = 0; vertexIndex < vertexCount; vertexIndex += 3) {
if (
!isVertexTransparentFn(vertexIndex) &&
!isVertexTransparentFn(vertexIndex + 1) &&
!isVertexTransparentFn(vertexIndex + 2)
) {
indexArray[transparentVertexOffset++] = vertexIndexFn(vertexIndex);
indexArray[transparentVertexOffset++] = vertexIndexFn(vertexIndex + 1);
indexArray[transparentVertexOffset++] = vertexIndexFn(vertexIndex + 2);
}
}
if (transparentVertexOffset > 0) {
// Copy transparent vertices
let offset = transparentVertexOffset;
for (let vertexIndex = 0; vertexIndex < vertexCount; vertexIndex += 3) {
if (
isVertexTransparentFn(vertexIndex) ||
isVertexTransparentFn(vertexIndex + 1) ||
isVertexTransparentFn(vertexIndex + 2)
) {
indexArray[offset++] = vertexIndexFn(vertexIndex);
indexArray[offset++] = vertexIndexFn(vertexIndex + 1);
indexArray[offset++] = vertexIndexFn(vertexIndex + 2);
}
}
} else {
// All vertices are tranparent
for (let vertexIndex = 0; vertexIndex < vertexCount; ++vertexIndex) {
indexArray[vertexIndex] = vertexIndexFn(vertexIndex);
}
}
} else {
// All vertices are considered opaque
transparentVertexOffset = vertexCount;
for (let vertexIndex = 0; vertexIndex < vertexCount; ++vertexIndex) {
indexArray[vertexIndex] = vertexIndexFn(vertexIndex);
}
}
return {
indexArray: indexArray,
transparentVertexOffset: transparentVertexOffset,
};
}
function getFeatureHash(symbologyData, outlinesHash, featureIndex) {
const featureHash = outlinesHash[featureIndex];
if (defined(featureHash)) {
return featureHash;
}
const newFeatureHash = (outlinesHash[featureIndex] = {
positions: {},
indices: {},
edges: {},
});
const featureSymbology = defaultValue(
symbologyData[featureIndex],
symbologyData.default,
);
newFeatureHash.hasOutline = defined(featureSymbology?.edges);
return newFeatureHash;
}
function addVertexToHash(indexHash, positionHash, vertexIndex, positions) {
if (!defined(indexHash[vertexIndex])) {
const startPositionIndex = vertexIndex * 3;
let coordinateHash = positionHash;
for (let index = 0; index < 3; index++) {
const coordinate = positions[startPositionIndex + index];
if (!defined(coordinateHash[coordinate])) {
coordinateHash[coordinate] = {};
}
coordinateHash = coordinateHash[coordinate];
}
if (!defined(coordinateHash.index)) {
coordinateHash.index = vertexIndex;
}
indexHash[vertexIndex] = coordinateHash.index;
}
}
function addEdgeToHash(
edgeHash,
vertexAIndex,
vertexBIndex,
vertexAIndexUnique,
vertexBIndexUnique,
normalIndex,
) {
let startVertexIndex;
let endVertexIndex;
if (vertexAIndexUnique < vertexBIndexUnique) {
startVertexIndex = vertexAIndexUnique;
endVertexIndex = vertexBIndexUnique;
} else {
startVertexIndex = vertexBIndexUnique;
endVertexIndex = vertexAIndexUnique;
}
let edgeStart = edgeHash[startVertexIndex];
if (!defined(edgeStart)) {
edgeStart = edgeHash[startVertexIndex] = {};
}
let edgeEnd = edgeStart[endVertexIndex];
if (!defined(edgeEnd)) {
edgeEnd = edgeStart[endVertexIndex] = {
normalsIndex: [],
outlines: [],
};
}
edgeEnd.normalsIndex.push(normalIndex);
if (
edgeEnd.outlines.length === 0 ||
vertexAIndex !== vertexAIndexUnique ||
vertexBIndex !== vertexBIndexUnique
) {
edgeEnd.outlines.push(vertexAIndex, vertexBIndex);
}
}
function generateOutlinesHash(
symbologyData,
featureIndexArray,
indexArray,
positions,
) {
const outlinesHash = [];
for (let i = 0; i < indexArray.length; i += 3) {
const featureIndex = defined(featureIndexArray)
? featureIndexArray[indexArray[i]]
: "default";
const featureHash = getFeatureHash(
symbologyData,
outlinesHash,
featureIndex,
);
if (!featureHash.hasOutline) {
continue;
}
const indexHash = featureHash.indices;
const positionHash = featureHash.positions;
for (let vertex = 0; vertex < 3; vertex++) {
const vertexIndex = indexArray[i + vertex];
addVertexToHash(indexHash, positionHash, vertexIndex, positions);
}
const edgeHash = featureHash.edges;
for (let vertex = 0; vertex < 3; vertex++) {
const vertexIndex = indexArray[i + vertex];
const nextVertexIndex = indexArray[i + ((vertex + 1) % 3)];
const uniqueVertexIndex = indexHash[vertexIndex];
const uniqueNextVertexIndex = indexHash[nextVertexIndex];
addEdgeToHash(
edgeHash,
vertexIndex,
nextVertexIndex,
uniqueVertexIndex,
uniqueNextVertexIndex,
i,
);
}
}
return outlinesHash;
}
const calculateFaceNormalA = new Cartesian3();
const calculateFaceNormalB = new Cartesian3();
const calculateFaceNormalC = new Cartesian3();
function calculateFaceNormal(normals, vertexAIndex, indexArray, positions) {
const positionAIndex = indexArray[vertexAIndex] * 3;
const positionBIndex = indexArray[vertexAIndex + 1] * 3;
const positionCIndex = indexArray[vertexAIndex + 2] * 3;
Cartesian3.fromArray(positions, positionAIndex, calculateFaceNormalA);
Cartesian3.fromArray(positions, positionBIndex, calculateFaceNormalB);
Cartesian3.fromArray(positions, positionCIndex, calculateFaceNormalC);
Cartesian3.subtract(
calculateFaceNormalB,
calculateFaceNormalA,
calculateFaceNormalB,
);
Cartesian3.subtract(
calculateFaceNormalC,
calculateFaceNormalA,
calculateFaceNormalC,
);
Cartesian3.cross(
calculateFaceNormalB,
calculateFaceNormalC,
calculateFaceNormalA,
);
const magnitude = Cartesian3.magnitude(calculateFaceNormalA);
if (magnitude !== 0) {
Cartesian3.divideByScalar(
calculateFaceNormalA,
magnitude,
calculateFaceNormalA,
);
}
const normalAIndex = vertexAIndex * 3;
const normalBIndex = (vertexAIndex + 1) * 3;
const normalCIndex = (vertexAIndex + 2) * 3;
Cartesian3.pack(calculateFaceNormalA, normals, normalAIndex);
Cartesian3.pack(calculateFaceNormalA, normals, normalBIndex);
Cartesian3.pack(calculateFaceNormalA, normals, normalCIndex);
}
const isEdgeSmoothA = new Cartesian3();
const isEdgeSmoothB = new Cartesian3();
function isEdgeSmooth(normals, normalAIndex, normalBIndex) {
Cartesian3.fromArray(normals, normalAIndex, isEdgeSmoothA);
Cartesian3.fromArray(normals, normalBIndex, isEdgeSmoothB);
const cosine = Cartesian3.dot(isEdgeSmoothA, isEdgeSmoothB);
const sine = Cartesian3.magnitude(
Cartesian3.cross(isEdgeSmoothA, isEdgeSmoothB, isEdgeSmoothA),
);
return Math.atan2(sine, cosine) < 0.25;
}
function addOutlinesForEdge(
outlines,
edgeData,
indexArray,
positions,
normals,
) {
if (edgeData.normalsIndex.length > 1) {
const normalsByIndex = positions.length === normals.length;
for (let indexA = 0; indexA < edgeData.normalsIndex.length; indexA++) {
const vertexAIndex = edgeData.normalsIndex[indexA];
if (!defined(normals[vertexAIndex * 3])) {
calculateFaceNormal(normals, vertexAIndex, indexArray, positions);
}
if (indexA === 0) {
continue;
}
for (let indexB = 0; indexB < indexA; indexB++) {
const vertexBIndex = edgeData.normalsIndex[indexB];
const normalAIndex = normalsByIndex
? indexArray[vertexAIndex] * 3
: vertexAIndex * 3;
const normalBIndex = normalsByIndex
? indexArray[vertexBIndex] * 3
: vertexBIndex * 3;
if (isEdgeSmooth(normals, normalAIndex, normalBIndex)) {
return;
}
}
}
}
outlines.push(...edgeData.outlines);
}
function addOutlinesForFeature(
outlines,
edgeHash,
indexArray,
positions,
normals,
) {
const edgeStartKeys = Object.keys(edgeHash);
for (let startIndex = 0; startIndex < edgeStartKeys.length; startIndex++) {
const edgeEnds = edgeHash[edgeStartKeys[startIndex]];
const edgeEndKeys = Object.keys(edgeEnds);
for (let endIndex = 0; endIndex < edgeEndKeys.length; endIndex++) {
const edgeData = edgeEnds[edgeEndKeys[endIndex]];
addOutlinesForEdge(outlines, edgeData, indexArray, positions, normals);
}
}
}
function generateOutlinesFromHash(
outlinesHash,
indexArray,
positions,
normals,
) {
const outlines = [];
const features = Object.keys(outlinesHash);
for (let featureIndex = 0; featureIndex < features.length; featureIndex++) {
const edgeHash = outlinesHash[features[featureIndex]].edges;
addOutlinesForFeature(outlines, edgeHash, indexArray, positions, normals);
}
return outlines;
}
function generateOutlinesIndexArray(
symbologyData,
featureIndexArray,
indexArray,
positions,
normals,
) {
if (!defined(symbologyData) || Object.keys(symbologyData).length === 0) {
return undefined;
}
const outlinesHash = generateOutlinesHash(
symbologyData,
featureIndexArray,
indexArray,
positions,
);
if (!defined(normals) || indexArray.length * 3 !== normals.length) {
// Need to calculate flat normals per faces
normals = [];
}
const outlines = generateOutlinesFromHash(
outlinesHash,
indexArray,
positions,
normals,
);
const outlinesIndexArray =
outlines.length > 0 ? new Uint32Array(outlines) : undefined;
return outlinesIndexArray;
}
function convertColorsArray(colors) {
// Colors are assumed to be normalized sRGB [0,255] while in glTF they are interpreted as linear.
// All values RGBA need to be stored as float to keep the precision after sRGB to linear conversion.
const colorsArray = new Float32Array(colors.length);
for (let index = 0; index < colors.length; index += 4) {
colorsArray[index] = srgbToLinear(Color.byteToFloat(colors[index]));
colorsArray[index + 1] = srgbToLinear(Color.byteToFloat(colors[index + 1]));
colorsArray[index + 2] = srgbToLinear(Color.byteToFloat(colors[index + 2]));
colorsArray[index + 3] = Color.byteToFloat(colors[index + 3]);
}
return colorsArray;
}
function generateNormals(
vertexCount,
indices,
positions,
normals,
uv0s,
colors,
featureIndex,
) {
const result = {
normals: undefined,
positions: undefined,
uv0s: undefined,
colors: undefined,
featureIndex: undefined,
vertexCount: undefined,
};
if (
vertexCount === 0 ||
!defined(positions) ||
positions.length === 0 ||
defined(normals)
) {
return result;
}
if (defined(indices)) {
result.vertexCount = indices.length;
result.positions = new Float32Array(indices.length * 3);
result.uv0s = defined(uv0s)
? new Float32Array(indices.length * 2)
: undefined;
result.colors = defined(colors)
? new Uint8Array(indices.length * 4)
: undefined;
result.featureIndex = defined(featureIndex)
? new Array(indices.length)
: undefined;
for (let i = 0; i < indices.length; i++) {
const index = indices[i];
result.positions[i * 3] = positions[index * 3];
result.positions[i * 3 + 1] = positions[index * 3 + 1];
result.positions[i * 3 + 2] = positions[index * 3 + 2];
if (defined(result.uv0s)) {
result.uv0s[i * 2] = uv0s[index * 2];
result.uv0s[i * 2 + 1] = uv0s[index * 2 + 1];
}
if (defined(result.colors)) {
result.colors[i * 4] = colors[index * 4];
result.colors[i * 4 + 1] = colors[index * 4 + 1];
result.colors[i * 4 + 2] = colors[index * 4 + 2];
result.colors[i * 4 + 3] = colors[index * 4 + 3];
}
if (defined(result.featureIndex)) {
result.featureIndex[i] = featureIndex[index];
}
}
vertexCount = indices.length;
positions = result.positions;
}
indices = new Array(vertexCount);
for (let i = 0; i < vertexCount; i++) {
indices[i] = i;
}
result.normals = new Float32Array(indices.length * 3);
for (let i = 0; i < indices.length; i += 3) {
calculateFaceNormal(result.normals, i, indices, positions);
}
return result;
}
function generateGltfBuffer(
vertexCount,
indices,
positions,
normals,
uv0s,
colors,
featureIndex,
parameters,
) {
if (vertexCount === 0 || !defined(positions) || positions.length === 0) {
return {
buffers: [],
bufferViews: [],
accessors: [],
meshes: [],
nodes: [],
nodesInScene: [],
};
}
const buffers = [];
const bufferViews = [];
const accessors = [];
const meshes = [];
const nodes = [];
const nodesInScene = [];
const rootExtensions = {};
const extensionsUsed = [];
// If we provide indices, then the vertex count is the length
// of that array, otherwise we assume non-indexed triangle
if (defined(indices)) {
vertexCount = indices.length;
}
// Generate index array
const { indexArray, transparentVertexOffset } = generateIndexArray(
vertexCount,
indices,
colors,
parameters.splitGeometryByColorTransparency,
);
// Push to the buffers, bufferViews and accessors
const indicesBlob = new Blob([indexArray], { type: "application/binary" });
const indicesURL = URL.createObjectURL(indicesBlob);
const endIndex = vertexCount;
// Feature index array gives a higher level of detail, each feature object can be accessed separately
const featureIndexArray =
parameters.enableFeatures && defined(featureIndex)
? new Float32Array(featureIndex.length)
: undefined;
let featureCount = 0;
if (defined(featureIndexArray)) {
for (let index = 0; index < featureIndex.length; ++index) {
featureIndexArray[index] = featureIndex[index];
const countByIndex = featureIndex[index] + 1;
if (featureCount < countByIndex) {
// Feature count is defined by the maximum feature index
featureCount = countByIndex;
}
}
}
// Outlines indices
let outlinesIndicesURL;
const outlinesIndexArray = generateOutlinesIndexArray(
parameters.symbologyData,
featureIndex,
indexArray,
positions,
normals,
);
if (defined(outlinesIndexArray)) {
const outlinesIndicesBlob = new Blob([outlinesIndexArray], {
type: "application/binary",
});
outlinesIndicesURL = URL.createObjectURL(outlinesIndicesBlob);
}
// POSITIONS
const meshPositions = positions.subarray(0, endIndex * 3);
const positionsBlob = new Blob([meshPositions], {
type: "application/binary",
});
const positionsURL = URL.createObjectURL(positionsBlob);
let minX = Number.POSITIVE_INFINITY;
let maxX = Number.NEGATIVE_INFINITY;
let minY = Number.POSITIVE_INFINITY;
let maxY = Number.NEGATIVE_INFINITY;
let minZ = Number.POSITIVE_INFINITY;
let maxZ = Number.NEGATIVE_INFINITY;
for (let i = 0; i < meshPositions.length / 3; i++) {
minX = Math.min(minX, meshPositions[i * 3 + 0]);
maxX = Math.max(maxX, meshPositions[i * 3 + 0]);
minY = Math.min(minY, meshPositions[i * 3 + 1]);
maxY = Math.max(maxY, meshPositions[i * 3 + 1]);
minZ = Math.min(minZ, meshPositions[i * 3 + 2]);
maxZ = Math.max(maxZ, meshPositions[i * 3 + 2]);
}
// NORMALS
const meshNormals = normals ? normals.subarray(0, endIndex * 3) : undefined;
let normalsURL;
if (defined(meshNormals)) {
const normalsBlob = new Blob([meshNormals], {
type: "application/binary",
});
normalsURL = URL.createObjectURL(normalsBlob);
}
// UV0s
const meshUv0s = uv0s ? uv0s.subarray(0, endIndex * 2) : undefined;
let uv0URL;
if (defined(meshUv0s)) {
const uv0Blob = new Blob([meshUv0s], { type: "application/binary" });
uv0URL = URL.createObjectURL(uv0Blob);
}
// COLORS
const meshColorsInBytes = defined(colors)
? convertColorsArray(colors.subarray(0, endIndex * 4))
: undefined;
let colorsURL;
if (defined(meshColorsInBytes)) {
const colorsBlob = new Blob([meshColorsInBytes], {
type: "application/binary",
});
colorsURL = URL.createObjectURL(colorsBlob);
}
// _FEATURE_ID_0
// The actual feature identifiers don't make much sense for reading attribute values, it is enough to use feature index
const meshFeatureId0 = defined(featureIndexArray)
? featureIndexArray.subarray(0, endIndex)
: undefined;
let featureId0URL;
if (defined(meshFeatureId0)) {
const featureId0Blob = new Blob([meshFeatureId0], {
type: "application/binary",
});
featureId0URL = URL.createObjectURL(featureId0Blob);
}
// Feature index property table
// This table has no practical use, but at least one property table is required to build a feature table
const meshPropertyTable0 = defined(featureIndexArray)
? new Float32Array(featureCount)
: undefined;
let propertyTable0URL;
if (defined(meshPropertyTable0)) {
// This table just maps the feature index to itself
for (let index = 0; index < meshPropertyTable0.length; ++index) {
meshPropertyTable0[index] = index;
}
const propertyTable0Blob = new Blob([meshPropertyTable0], {
type: "application/binary",
});
propertyTable0URL = URL.createObjectURL(propertyTable0Blob);
}
const attributes = {};
const extensions = {};
// POSITIONS
attributes.POSITION = accessors.length;
buffers.push({
uri: positionsURL,
byteLength: meshPositions.byteLength,
});
bufferViews.push({
buffer: buffers.length - 1,
byteOffset: 0,
byteLength: meshPositions.byteLength,
target: 34962,
});
accessors.push({
bufferView: bufferViews.length - 1,
byteOffset: 0,
componentType: 5126,
count: meshPositions.length / 3,
type: "VEC3",
max: [minX, minY, minZ],
min: [maxX, maxY, maxZ],
});
// NORMALS
if (defined(normalsURL)) {
attributes.NORMAL = accessors.length;
buffers.push({
uri: normalsURL,
byteLength: meshNormals.byteLength,
});
bufferViews.push({
buffer: buffers.length - 1,
byteOffset: 0,
byteLength: meshNormals.byteLength,
target: 34962,
});
accessors.push({
bufferView: bufferViews.length - 1,
byteOffset: 0,
componentType: 5126,
count: meshNormals.length / 3,
type: "VEC3",
});
}
// UV0
if (defined(uv0URL)) {
attributes.TEXCOORD_0 = accessors.length;
buffers.push({
uri: uv0URL,
byteLength: meshUv0s.byteLength,
});
bufferViews.push({
buffer: buffers.length - 1,
byteOffset: 0,
byteLength: meshUv0s.byteLength,
target: 34962,
});
accessors.push({
bufferView: bufferViews.length - 1,
byteOffset: 0,
componentType: 5126,
count: meshUv0s.length / 2,
type: "VEC2",
});
}
// COLORS
if (defined(colorsURL)) {
attributes.COLOR_0 = accessors.length;
buffers.push({
uri: colorsURL,
byteLength: meshColorsInBytes.byteLength,
});
bufferViews.push({
buffer: buffers.length - 1,
byteOffset: 0,
byteLength: meshColorsInBytes.byteLength,
target: 34962,
});
accessors.push({
bufferView: bufferViews.length - 1,
byteOffset: 0,
componentType: 5126,
count: meshColorsInBytes.length / 4,
type: "VEC4",
});
}
// _FEATURE_ID_0
if (defined(featureId0URL)) {
attributes._FEATURE_ID_0 = accessors.length;
buffers.push({
uri: featureId0URL,
byteLength: meshFeatureId0.byteLength,
});
bufferViews.push({
buffer: buffers.length - 1,
byteOffset: 0,
byteLength: meshFeatureId0.byteLength,
target: 34963,
});
accessors.push({
bufferView: bufferViews.length - 1,
byteOffset: 0,
componentType: 5126,
count: meshFeatureId0.length,
type: "SCALAR",
});
// Mesh features extension associates feature ids by vertex
extensions.EXT_mesh_features = {
featureIds: [
{
attribute: 0,
propertyTable: 0,
featureCount: featureCount,
},
],
};
extensionsUsed.push("EXT_mesh_features");
}
// Feature index property table
if (defined(propertyTable0URL)) {
buffers.push({
uri: propertyTable0URL,
byteLength: meshPropertyTable0.byteLength,
});
bufferViews.push({
buffer: buffers.length - 1,
byteOffset: 0,
byteLength: meshPropertyTable0.byteLength,
target: 34963,
});
rootExtensions.EXT_structural_metadata = {
schema: {
id: "i3s-metadata-schema-001",
name: "I3S metadata schema 001",
description: "The schema for I3S metadata",
version: "1.0",
classes: {
feature: {
name: "feature",
description: "Feature metadata",
properties: {
index: {
description: "The feature index",
type: "SCALAR",
componentType: "FLOAT32",
required: true,
},
},
},
},
},
propertyTables: [
{
name: "feature-indices-mapping",
class: "feature",
count: featureCount,
properties: {
index: {
values: bufferViews.length - 1,
},
},
},
],
};
extensionsUsed.push("EXT_structural_metadata");
}
// Outlines indices
if (defined(outlinesIndicesURL)) {
buffers.push({
uri: outlinesIndicesURL,
byteLength: outlinesIndexArray.byteLength,
});
bufferViews.push({
buffer: buffers.length - 1,
byteOffset: 0,
byteLength: outlinesIndexArray.byteLength,
target: 34963,
});
accessors.push({
bufferView: bufferViews.length - 1,
byteOffset: 0,
componentType: 5125,
count: outlinesIndexArray.length,
type: "SCALAR",
});
extensions.CESIUM_primitive_outline = {
indices: accessors.length - 1,
};
extensionsUsed.push("CESIUM_primitive_outline");
}
// INDICES
buffers.push({
uri: indicesURL,
byteLength: indexArray.byteLength,
});
bufferViews.push({
buffer: buffers.length - 1,