forked from constructVOD/constructVOD.github.io
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgltfworker.js
More file actions
11537 lines (8028 loc) · 251 KB
/
gltfworker.js
File metadata and controls
11537 lines (8028 loc) · 251 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
// @ts-check
'use strict';
// The MessagePort for communicating with the runtime
let msgPort = null;
let id = Math.random()
let buff = null;
let buffLights = null;
let drawVerts = null;
let drawLights = null;
let drawLightsBufferViews = []
let index = 0;
let gltf = null
let minBB = [Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY];
let maxBB = [Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY];
let buffLength = 0
const disabledNodes = new Map();
const nodeMorphWeights = new Map();
let activeNodes = [];
let nodeIndex = 0;
let drawMeshes = null
function initEventListeners(e) {
if (e.data && e.data["type"] === "construct-worker-init")
{
msgPort = e.data["port2"];
msgPort.onmessage = OnMessage;
OnReady();
}
}
// Receive the MessagePort from Construct
self.addEventListener("message", initEventListeners);
function OnMessage(e)
{
switch(e.data.type) {
case 'init':
break;
case 'gltf':
gltf = e.data.gltf
buffLength = e.data.buffLength
drawMeshes = e.data.drawMeshes
break
case 'updateAnimationPolygons':
buff = e.data.buff
updateAnimationPolygons(e.data.data)
break
case 'getPolygons':
buff = e.data.buff
getPolygons(e.data.data)
break
case 'release':
release();
self.close();
break;
case 'enableNode':
if (e.data.enable) {
disabledNodes.delete(e.data.nodeName)
} else {
disabledNodes.set(e.data.nodeName, true)
}
break;
case 'setNodeMorphWeight': {
const nodeName = e.data.nodeName
const index = e.data.index
const weight = e.data.weight
if (!nodeMorphWeights.has(nodeName)) nodeMorphWeights.set(nodeName, new Map())
nodeMorphWeights.get(nodeName).set(index, weight)
break;
}
case 'deleteNodeMorphWeight': {
const nodeName = e.data.nodeName
const index = e.data.index
if (!nodeMorphWeights.has(nodeName)) return
nodeMorphWeights.get(nodeName).delete(index)
break;
}
default:
console.warn('unknown message type:', e.data.type)
}
}
function packRGBA(r, g, b, a) {
// Convert floats to 8-bit integers
var red = Math.floor(r * 255);
var green = Math.floor(g * 255);
var blue = Math.floor(b * 255);
var alpha = Math.floor(a * 255);
// Pack RGBA values into a 32-bit integer
var packedRGBA = (alpha << 24) | (blue << 16) | (green << 8) | red;
return packedRGBA;
}
function release() {
self.removeEventListener("message", initEventListeners);
if (msgPort) {
msgPort.close();
msgPort = null;
}
buffLights = null
drawLights = null
// @ts-ignore
index = null
gltf = null
// @ts-ignore
minBB = null
// @ts-ignore
maxBB = null
// @ts-ignore
buffLength = null
}
function OnReady()
{
}
// Updates animation at index to be at time. Is used to play animation.
let blendState = 'init';
const lastTarget = new Array(2);
lastTarget[0] = [];
lastTarget[1] = [];
let lastTargetIndex = 0;
let blendTarget = [];
let blendTime = 0;
let lastIndex = 0;
let animationFinished = false;
let currentAnimationFrame = 0;
function smoothstep (min, max, value) {
var x = Math.max(0, Math.min(1, (value-min)/(max-min)));
return x*x*(3 - 2*x);
}
function updateAnimationPolygons(data) {
const animationData = data.animationData
const editorData = data.editorData
const lightEnable = editorData.lightEnable
const lightUpdate = editorData.lightUpdate
updateAnimation(animationData);
if (animationData.onScreen)
{
getPolygonsPrep(editorData);
}
// Post buffer to messagePort
// Last float in array will be tick that requested the update
if (animationData.onScreen)
{
drawVerts[drawVerts.length-1] = editorData.tick;
setBBInVerts(drawVerts, minBB, maxBB)
if (lightEnable && lightUpdate) updateLight(editorData)
let msg = {buff, activeNodes, buffLights, drawLightsBufferViews, drawLightsEnable: lightEnable, lightUpdate}
msgPort.postMessage(msg, [msg.buff, msg.buffLights])
drawVerts = null
buffLights = null
drawLightsBufferViews = []
drawLights = null
} else {
// No need to transfer data, worker us ready for next request
const msg = {type: 'status', status : { workerReady: true}, buff}
msgPort.postMessage(msg, [msg.buff])
drawVerts = null
buffLights = null
drawLightsBufferViews = []
drawLights = null
}
}
function getPolygons(data) {
const editorData = data.editorData
const lightEnable = editorData.lightEnable
const lightUpdate = editorData.lightUpdate
getPolygonsPrep(editorData);
// Post buffer to messagePort
// Last float in array will be tick that requested the update
drawVerts[drawVerts.length-1] = editorData.tick;
setBBInVerts(drawVerts, minBB, maxBB)
if (lightEnable && lightUpdate) updateLight(editorData)
let msg = {buff, activeNodes, buffLights, drawLightsBufferViews, drawLightsEnable: lightEnable, lightUpdate}
msgPort.postMessage(msg, [msg.buff, msg.buffLights])
buffLights = null
drawLightsBufferViews = []
drawLights = null
}
function setBBInVerts(verts, minBBox, maxBBox) {
let l = verts.length-2
verts[l--] = maxBBox[2]
verts[l--] = maxBBox[1]
verts[l--] = maxBBox[0]
verts[l--] = minBBox[2]
verts[l--] = minBBox[1]
verts[l--] = minBBox[0]
}
function updateAnimation(animationData)
{
// @ts-ignore
const vec3 = glMatrix.vec3;
// @ts-ignore
const quat = glMatrix.quat;
const index = animationData.index
let time = animationData.time
const onScreen = animationData.onScreen
const deltaTime = animationData.deltaTime
const animationBlend = animationData.animationBlend
const animationLoop = animationData.animationLoop
let anim = gltf.animations[index];
// Blend state machine
switch(blendState) {
case 'init':
if (animationBlend != 0 && lastIndex != index) {
blendState = 'blend'
blendTime = 0;
blendTarget = lastTarget[lastTargetIndex];
if (lastTargetIndex == 0) {
lastTargetIndex = 1;
} else {
lastTargetIndex = 0;
}
lastIndex = index;
}
break;
case 'blend':
if (lastIndex != index) {
blendState = 'blend'
blendTime = 0;
blendTarget = lastTarget[lastTargetIndex];
if (lastTargetIndex == 0) {
lastTargetIndex = 1;
} else {
lastTargetIndex = 0;
}
lastIndex = index;
break;
}
if (blendTime > animationBlend) {
blendState = 'idle'
break
}
blendTime += deltaTime
break;
case 'idle':
if (lastIndex != index) {
blendState = 'blend'
blendTime = 0;
blendTarget = lastTarget[lastTargetIndex];
if (lastTargetIndex == 0) {
lastTargetIndex = 1;
} else {
lastTargetIndex = 0;
}
lastIndex = index;
}
break;
default:
console.warn('[3DObject] bad blend state:', blendState)
}
lastTarget[lastTargetIndex] = [];
for(let i = 0; i < anim.channels.length; i++)
{
let c = anim.channels[i];
let timeValues = c.sampler.input;
let otherValues = c.sampler.output.data;
let target = c.target;
if (animationLoop)
{
time = (time-timeValues.min[0])%(timeValues.max[0]-timeValues.min[0]) + timeValues.min[0]; // loop
} else
{
if (time > timeValues.max[0])
{
time = timeValues.max[0]-0.01; // Stop on max time
if (animationFinished)
{
animationFinished = true;
}
}
}
// If not on screen no more animation required.
if (!onScreen) continue
//time = Math.min(Math.max(time, timeValues.min[0]), timeValues.max[0]); //clamp
timeValues = timeValues.data;
//find index in timeline
let t0, t1;
for(t0=0, t1=1; t0<timeValues.length-1; t0++, t1++)
if(time >= timeValues[t0] && time <= timeValues[t1])
break;
currentAnimationFrame = t0;
let t = (time - timeValues[t0])/(timeValues[t1] - timeValues[t0]);
currentAnimationFrame = Math.round(t0+t);
// Check if invalid state, if so, skip animation
// TODO: Change how change animation vs tick is handled to make sure this case does not happen
if (timeValues[t1] == null) break
if(target.path == "translation")
vec3.lerp(target.node.translation, otherValues.subarray(t0*3,t0*3+3), otherValues.subarray(t1*3,t1*3+3), t);
// vec3.lerp(otherValues.subarray(t0*3,t0*3+3), otherValues.subarray(t1*3,t1*3+3), t, target.node.translation);
else if(target.path == "rotation")
quat.slerp(target.node.rotation, otherValues.subarray(t0*4,t0*4+4), otherValues.subarray(t1*4,t1*4+4), t);
// quat4.slerp(otherValues.subarray(t0*4,t0*4+4), otherValues.subarray(t1*4,t1*4+4), t, target.node.rotation);
else if(target.path == "scale")
vec3.lerp(target.node.scale, otherValues.subarray(t0*3,t0*3+3), otherValues.subarray(t1*3,t1*3+3), t);
// vec3.lerp(otherValues.subarray(t0*3,t0*3+3), otherValues.subarray(t1*3,t1*3+3), t, target.node.scale);
else if(target.path == "weights") {
// Apply gltf morph target weights to node weights using lerp between two targets
const node = target.node;
node.weights = new Float32Array(node.mesh.primitives[0].targets.length);
const weights = node.weights;
const stride = weights.length
for (let j = 0; j < stride; j++) {
weights[j] = lerp(otherValues[t0*stride+j], otherValues[t1*stride+j], t);
}
}
// Blend to last animation if during blend
if (blendState == 'blend') {
const blend = blendTime == 0 ? 0 : blendTime/animationBlend;
const blendTargetI = blendTarget[i];
if (blendTargetI != null) {
if(target.path == "translation" && blendTargetI.path == "translation")
vec3.lerp(target.node.translation, blendTargetI.node.translation, target.node.translation, blend);
else if(target.path == "rotation" && blendTargetI.path == "rotation")
quat.slerp(target.node.rotation, blendTargetI.node.rotation, target.node.rotation, blend);
else if(target.path == "scale" && blendTargetI.path == "scale")
vec3.lerp(target.node.scale, blendTargetI.node.scale, target.node.scale, blend);
}
}
if (animationBlend != 0) {
const currentTarget = {};
currentTarget.node = {}
if (currentTarget.path == "translation") {
currentTarget.path = target.path;
currentTarget.node.translation = vec3.clone(target.node.translation);
} else if (target.path == "rotation") {
currentTarget.path = target.path;
currentTarget.node.rotation = quat.clone(target.node.rotation);
} else if (target.path == "scale") {
currentTarget.path = target.path;
currentTarget.node.scale = vec3.clone(target.node.scale);
}
lastTarget[lastTargetIndex].push(currentTarget);
}
}
}
function lerp( a, b, alpha ) {
const value = a + alpha * (b-a);
return value
}
// Updates scene graph, and as a second step sends transformed skinned mesh points to c2.
function getPolygonsPrep(editorData)
{
// @ts-ignore
const vec3 = glMatrix.vec3;
// @ts-ignore
const mat4 = glMatrix.mat4;
// @ts-ignore
const quat = glMatrix.quat;
// New array buffer for each frame
// Extra data: minBB, maxBB, tick
// buff = new ArrayBuffer((buffLength+7)*4)
drawVerts = new Float32Array(buff);
// One light per triangle
buffLights = new ArrayBuffer((buffLength)*4)
drawLights = new Uint32Array(buffLights)
// drawVerts index
index = 0;
const isEditor = editorData.isEditor
activeNodes = [];
nodeIndex = 0;
if (isEditor) {
const xScale = editorData.xScale;
const yScale = editorData.yScale;
const zScale = editorData.zScale;
const xAngle = editorData.xAngle
const yAngle = editorData.yAngle
const zAngle = editorData.zAngle
const x = editorData.x
const y = editorData.y
const z = editorData.z
quat.fromEuler(rotate, xAngle, yAngle, zAngle);
mat4.fromRotationTranslationScale(modelScaleRotate, rotate, [x,y,z], [xScale,-yScale,zScale]);
}
quat.fromEuler(rotationQuat, 0, 0, 0);
mat4.fromRotationTranslation(parentMatrix, rotationQuat, [0,0,0])
minBB = [Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY];
maxBB = [Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY];
// update all scene matrixes.
for(let i = 0; i < gltf.scene.nodes.length; i++)
{
transformNode(gltf.scene.nodes[i], parentMatrix, modelScaleRotate, isEditor);
}
quat.fromEuler(rotationQuat, 0, 0, 0);
// Check if the gltf scene root node has a rotation, translation or scale
const rootNode = gltf?.scene?.nodes[0]
let rootNodeXform = false
if (rootNode && (rootNode.rotation || rootNode.translation || rootNode.scale)) {
if (!rootNode.rotation) rootNode.rotation = quat.create();
if (!rootNode.translation) rootNode.translation = vec3.create();
if (!rootNode.scale) rootNode.scale = vec3.fromValues(1,1,1);
mat4.fromRotationTranslationScale(parentMatrix, rootNode.rotation, rootNode.translation, rootNode.scale)
rootNodeXform = true
}
for(let ii = 0; ii < gltf.skinnedNodes.length; ii++)
{
let node = gltf.skinnedNodes[ii];
node.rotation = rotationQuat;
//update bone matrixes
for(let jj = 0; jj < node.skin.joints.length; jj++)
{
let joint = node.skin.joints[jj];
mat4.multiply(joint.boneMatrix, node.invMatrix, joint.matrix);
mat4.multiply(joint.boneMatrix, joint.boneMatrix, joint.invBindMatrix);
}
for(let i = 0; i < node.mesh.primitives.length; i++)
{
let posData = node.mesh.primitives[i].attributes.POSITION.data;
let weights = node.mesh.primitives[i].attributes.WEIGHTS_0.data;
let joints = node.mesh.primitives[i].attributes.JOINTS_0.data;
// Don't animate disabled nodes
if (disabledNodes.get(node.name)) {
index+=posData.length;
nodeIndex++;
continue;
}
let morphActive = false;
let morphTargets = null;
let morphWeights = null;
const nodeMorphWeightSet = nodeMorphWeights.get(node.name)
if (node.weights || nodeMorphWeightSet) {
morphActive = true;
morphTargets = node.mesh.primitives[i].targets;
if (!node.weights) node.weights = new Float32Array(morphTargets.length);
morphWeights = [...node.weights];
if(nodeMorphWeightSet)
for(let j = 0; j < morphWeights.length; j++) {
if (nodeMorphWeightSet.has(j)) morphWeights[j] = nodeMorphWeightSet.get(j);
}
}
activeNodes.push(nodeIndex);
nodeIndex++;
for(let j=0; j<posData.length/3; j++)
{
let w = weights.subarray(j*4, j*4+4);
let b = joints.subarray(j*4, j*4+4);
let vin = posData.subarray(j*3, j*3+3)
let v = [0,0,0], vsum = [0,0,0];
if (morphActive) {
vin = morphTargetsXform(vin, j, morphWeights, morphTargets);
}
for(let i=0; i<4; i++)
{
vec3.transformMat4(v, vin, node.skin.joints[b[i]].boneMatrix);
vec3.scale(v, v, w[i]);
vec3.add(vsum, vsum, v);
}
if (rootNodeXform) {
// vec3.mul(vsum, vsum, rootNode.scale);
vec3.transformMat4(vsum, vsum, parentMatrix);
if (j==0) {
}
}
if (isEditor) {
vec3.transformMat4(vsum, vsum, modelScaleRotate );
}
const x = vsum[0]
const y = vsum[1]
const z = vsum[2]
if (minBB[0] > x) minBB[0] = x
if (minBB[1] > y) minBB[1] = y
if (minBB[2] > z) minBB[2] = z
if (maxBB[0] < x) maxBB[0] = x
if (maxBB[1] < y) maxBB[1] = y
if (maxBB[2] < z) maxBB[2] = z
drawVerts[index++] = x;
drawVerts[index++] = y;
drawVerts[index++] = z;
}
}
}
}
/*
Updates a node's matrix and all it's children nodes.
After that it transforms unskinned mesh points and sends them to c2.
*/
function transformNode(node, parentMat, modelScaleRotate, isEditor)
{
// @ts-ignore
const mat4 = glMatrix.mat4;
// @ts-ignore
const quat = glMatrix.quat;
// @ts-ignore
const vec3 = glMatrix.vec3;
if(parentMat != undefined)
mat4.copy(node.matrix, parentMat);
else
mat4.identity(node.matrix);
mat4.translate(node.matrix, node.matrix, node.translation);
mat4.multiply(node.matrix, node.matrix, mat4.fromQuat(dummyMat4Out, node.rotation));
mat4.scale(node.matrix, node.matrix, node.scale);
if(node.skin != undefined) mat4.invert(node.invMatrix, node.matrix);
// unskinned meshes
if(node.mesh != undefined && node.skin == undefined)
{
for(let i = 0; i < node.mesh.primitives.length; i++)
{
let posData = node.mesh.primitives[i].attributes.POSITION.data;
let v = [0,0,0];
if (disabledNodes.get(node.name)) {
index+=posData.length;
nodeIndex++;
continue;
}
let morphActive = false;
let morphTargets = null;
let morphWeights = null;
const nodeMorphWeightSet = nodeMorphWeights.get(node.name)
if (node.weights || nodeMorphWeightSet) {
morphActive = true;
morphTargets = node.mesh.primitives[i].targets;
if (!node.weights) node.weights = new Float32Array(morphTargets.length);
morphWeights = [...node.weights];
if(nodeMorphWeightSet)
for(let j = 0; j < morphWeights.length; j++) {
if (nodeMorphWeightSet.has(j)) morphWeights[j] = nodeMorphWeightSet.get(j);
}
}
activeNodes.push(nodeIndex);
nodeIndex++;
for(let j=0; j<posData.length/3; j++)
{
let vin = posData.subarray(j*3, j*3+3);
if (morphActive) {
vin = morphTargetsXform(vin, j, morphWeights, morphTargets);
}
vec3.transformMat4(v, vin, node.matrix);
if (isEditor) {
vec3.transformMat4(v, v, modelScaleRotate);
}
const x = v[0]
const y = v[1]
const z = v[2]
if (minBB[1] > y) minBB[1] = y
if (minBB[0] > x) minBB[0] = x
if (minBB[2] > z) minBB[2] = z
if (maxBB[0] < x) maxBB[0] = x
if (maxBB[1] < y) maxBB[1] = y
if (maxBB[2] < z) maxBB[2] = z
drawVerts[index++] = x;
drawVerts[index++] = y;
drawVerts[index++] = z;
}
}
}
if(node.children != undefined)
for(let i = 0; i < node.children.length; i++)
transformNode(node.children[i], node.matrix, modelScaleRotate, isEditor);
}
function morphTargetsXform(vin, index, weights, targets) {
// @ts-ignore
const vec3 = glMatrix.vec3;
vec3.copy(vout, vin);
for (let i = 0; i < targets.length; i++) {
const w = weights[i];
if (w == 0) continue;
const v = targets[i].POSITION.data.subarray(index * 3, index * 3 + 3);
vec3.scaleAndAdd(vout, vout, v, w);
}
return vout;
}
function calculateLight(v0, v1, v2, normal, viewDir, colorSum, c, modelRotate, lights, viewPos, ambientColor, cullEnable) {
// @ts-ignore
const vec3 = glMatrix.vec3;
// @ts-ignore
const vec4 = glMatrix.vec4;
vec3.transformMat4(v0, v0, modelRotate);
vec3.transformMat4(v1, v1, modelRotate);
vec3.transformMat4(v2, v2, modelRotate);
vec3.set(c, v0[0], v0[1], v0[2])
vec3.add(c,c,v1)
vec3.add(c,c,v2)
vec3.div(c,c,[3,3,3])
if (cullEnable) {
const cull = backfaceCullCCW(v0, v1, v2)
if (cull) return [0,0,0,0]
}
vec3.cross(normal, [v1[0]-v0[0], v1[1]-v0[1], v1[2]-v0[2]], [v2[0]-v0[0], v2[1]-v0[1], v2[2]-v0[2]])
vec3.normalize(normal, normal)
vec4.set(colorSum,0,0,0,0)
for (const light of Object.values(lights)) {
if (!light.enable) continue
const l = light.pos
const enableSpot = light.enableSpot
const enableSpecular = light.enableSpecular
const spotDir = light.spotDir
const cutoff = light.cutoff
const edge = light.edge
const color = light.color
const lightDir = vec3.fromValues(c[0]-l[0], c[1]-l[1], c[2]-l[2])
const distance = vec3.length(lightDir)
const attConstant = light.attConstant
const attLinear = light.attLinear
const attSquare = light.attSquare
vec3.normalize(lightDir, lightDir)
let dot = vec3.dot(normal, lightDir) * 0.5 + 0.5
let att = 1.0;
let specular = 0.0
if (enableSpot) {
const spotDirN = vec3.clone(spotDir)
vec3.normalize(spotDirN, spotDir)
att = vec3.dot(spotDirN, lightDir);
if (att < cutoff)
{
att = smoothstep(cutoff*(1-edge),cutoff, att);
} else {
att = 1.0;
}
}
if (enableSpecular && false) {
vec3.sub(viewDir, viewPos, c)
vec3.normalize(viewDir, viewDir)
const reflectDir = vec3.create()
const dotNI = vec3.create()
vec3.dot(dotNI, normal, lightDir)
vec3.scale(dotNI, dotNI, 2.0)
vec3.mul(dotNI, dotNI, normal)
vec3.sub(reflectDir,dotNI,lightDir)
// I - 2.0 * dot(N, I) * N.
vec3.sub(reflectDir, lightDir, normal)
vec3.normalize(reflectDir, reflectDir)
const spec = Math.pow(Math.max(vec3.dot(reflectDir, viewDir), 0.0), light.specularPower);
specular = light.specularAtt * spec;
}
att = att / (1.0 * attConstant + distance * attLinear + distance * distance * attSquare);
att = att + specular
dot = dot * dot * att
vec4.add(colorSum, colorSum, [dot*color[0], dot*color[1], dot*color[2], dot*color[3]])
}
// Add ambient color to colorSum
vec4.add(colorSum, colorSum, ambientColor)
// Clamp color
colorSum[0] = colorSum[0] < 0.0 ? 0.0 : colorSum[0] > 1.0 ? 1.0 : colorSum[0]
colorSum[1] = colorSum[1] < 0.0 ? 0.0 : colorSum[1] > 1.0 ? 1.0 : colorSum[1]
colorSum[2] = colorSum[2] < 0.0 ? 0.0 : colorSum[2] > 1.0 ? 1.0 : colorSum[2]
// colorSum[3] = colorSum[3] < 0.0 ? 0.0 : colorSum[3] > 1.0 ? 1.0 : colorSum[3]
colorSum[3] = 1
return colorSum
}
function backfaceCullCCW(v0, v1, v2) {
if (((v1[0]-v0[0])*(v2[1]-v1[1]))-((v1[1]-v0[1])*(v2[0]-v1[0]))<=0) return false
return true
}
function updateLight(editorData)
{
// @ts-ignore
const vec3 = glMatrix.vec3;
// @ts-ignore
const vec4 = glMatrix.vec4;
// @ts-ignore
const mat4 = glMatrix.mat4;
// @ts-ignore
const quat = glMatrix.quat;
const cannonBody = {quaternion: quat.create()}
const cannonSetRotation = false
const xScale = editorData.xScale;
const yScale = editorData.yScale;
const zScale = editorData.zScale;
const xAngle = editorData.xAngle
const yAngle = editorData.yAngle
const zAngle = editorData.zAngle
const x = editorData.x
const y = editorData.y
const z = editorData.z
const viewPos = editorData.viewPos
const ambientColor = editorData.ambientColor
const lights = editorData.lights
const cullEnable = editorData.cullEnable
typedVertsToDrawVerts()
// XXX Handle cannonBody and cannonSetRotation for light
if (cannonSetRotation && cannonBody) {
quat.set(rotate, cannonBody.quaternion.x, cannonBody.quaternion.y, cannonBody.quaternion.z, cannonBody.quaternion.w);
} else {
quat.fromEuler(rotate, xAngle, yAngle, zAngle);
}
// Need to manually create for lighting, since usually done in shader
mat4.fromRotationTranslationScale(modelRotate, rotate, [x,y,z], [xScale,-yScale,zScale]);
const length = drawVerts.length;
// Calculate for each triangle
let lightIndex = 0
drawLightsBufferViews.length = 0
for (let j=0; j < drawMeshes.length; j++)
{
// XXX Skip lighting if disabled
const drawLightsBufferStart = lightIndex
const drawMeshVerts = drawMeshes[j].drawVerts;
const drawIndices = drawMeshes[j].drawIndices;
for (let ii=0; ii<drawMeshVerts.length; ii++)
{
let v = drawMeshVerts[ii];
let ind = drawIndices[ii];
let triangleCount = ind.length/3;
for(let i = 0; i<triangleCount; i++)
{
let i3 = i*3;
let x0, y0, z0, x1, y1, z1, x2, y2, z2;
x0 = (v[ind[i3+0]*3+0]);
y0 = (v[ind[i3+0]*3+1]);
z0 = (v[ind[i3+0]*3+2]);
x1 = (v[ind[i3+1]*3+0]);
y1 = (v[ind[i3+1]*3+1]);
z1 = (v[ind[i3+1]*3+2]);
x2 = (v[ind[i3+2]*3+0]);
y2 = (v[ind[i3+2]*3+1]);
z2 = (v[ind[i3+2]*3+2]);
vec3.set(v0 ,x0, y0, z0)
vec3.set(v1 ,x1, y1, z1)
vec3.set(v2 ,x2, y2, z2)
// Vertex transformed by calculatLight
const colorSum = calculateLight(v0, v1, v2, normal, viewDir, colorSumCalc, c, modelRotate, lights, viewPos, ambientColor, cullEnable)
drawLights[lightIndex] = packRGBA(colorSum[0], colorSum[1], colorSum[2], colorSum[3])
lightIndex += 1
}
}
drawLightsBufferViews.push({start:drawLightsBufferStart, length:lightIndex-drawLightsBufferStart})
}
}
function typedVertsToDrawVerts() {
for (let j=0; j< drawMeshes.length; j++) {
const drawMeshVerts = drawMeshes[j].drawVerts;
const bufferViews = drawMeshes[j].bufferViews;
drawMeshVerts.length = 0
// XXX Slip inactive meshes if possible
for (let ii=0; ii<bufferViews.length; ii++)
{
const bufferView = bufferViews[ii];
let buffStart = bufferView.start;
// Convert typed array to regular array
// to speed access to data, net win is 10-20%
const v = new Array(bufferView.length);
for (let a=0; a<bufferView.length; a++) {
v[a] = drawVerts[buffStart+a];
}
drawMeshVerts.push(v);
}
}
}
function smoothstep (min, max, value) {
var x = Math.max(0, Math.min(1, (value-min)/(max-min)));
return x*x*(3 - 2*x);
};
/*!
@fileoverview gl-matrix - High performance matrix and vector operations
@author Brandon Jones
@author Colin MacKenzie IV
@version 3.3.0
Copyright (c) 2015-2020, Brandon Jones, Colin MacKenzie IV.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.glMatrix = {}));
}(this, (function (exports) { 'use strict';
/**
* Common utilities
* @module glMatrix
*/
// Configuration Constants
var EPSILON = 0.000001;
var ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array;
var RANDOM = Math.random;
/**
* Sets the type of array used when creating new vectors and matrices
*
* @param {Float32ArrayConstructor | ArrayConstructor} type Array type, such as Float32Array or Array
*/
function setMatrixArrayType(type) {
ARRAY_TYPE = type;
}
var degree = Math.PI / 180;
/**
* Convert Degree To Radian
*
* @param {Number} a Angle in Degrees
*/
function toRadian(a) {
return a * degree;
}
/**
* Tests whether or not the arguments have approximately the same value, within an absolute
* or relative tolerance of glMatrix.EPSILON (an absolute tolerance is used for values less
* than or equal to 1.0, and a relative tolerance is used for larger values)
*
* @param {Number} a The first number to test.
* @param {Number} b The second number to test.
* @returns {Boolean} True if the numbers are approximately equal, false otherwise.
*/
function equals(a, b) {
return Math.abs(a - b) <= EPSILON * Math.max(1.0, Math.abs(a), Math.abs(b));
}
if (!Math.hypot) Math.hypot = function () {
var y = 0,
i = arguments.length;
while (i--) {
y += arguments[i] * arguments[i];
}
return Math.sqrt(y);
};
var common = /*#__PURE__*/Object.freeze({
__proto__: null,
EPSILON: EPSILON,
get ARRAY_TYPE () { return ARRAY_TYPE;
},
RANDOM: RANDOM,
setMatrixArrayType: setMatrixArrayType,
toRadian: toRadian,
equals: equals
});
/**
* 2x2 Matrix
* @module mat2
*/
/**
* Creates a new identity mat2
*
* @returns {mat2} a new 2x2 matrix
*/
function create() {
var out = new ARRAY_TYPE(4);
if (ARRAY_TYPE != Float32Array) {
out[1] = 0;
out[2] = 0;
}
out[0] = 1;
out[3] = 1;
return out;
}
/**
* Creates a new mat2 initialized with values from an existing matrix
*
* @param {ReadonlyMat2} a matrix to clone
* @returns {mat2} a new 2x2 matrix
*/
function clone(a) {
var out = new ARRAY_TYPE(4);
out[0] = a[0];
out[1] = a[1];
out[2] = a[2];
out[3] = a[3];
return out;