forked from sketchpunk/FunWithWebGL2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfungi.core.js
2256 lines (1910 loc) · 72.9 KB
/
fungi.core.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
var Fungi = (function(){
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Private Scope Variables and Constants
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
const DEG2RAD = Math.PI/180; //Cache result, one less operation to do for each update.
var gl = null,
CULLING_STATE = true, //Global state if the feature is enabled
BLENDING_STATE = false, //Same---
DEPTHTEST_STATE = true,
SAMPLE_ALPHA_COV_STATE = false;
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
function Init(canvasID){
if(Fungi.gl != null) return Fungi.gl;
var canvas = document.getElementById(canvasID);
gl = canvas.getContext("webgl2");
if(!gl){ console.error("WebGL context is not available."); return null; }
//...................................................
//Setup GL, Set all the default configurations we need.
gl.cullFace(gl.BACK); //Back is also default
gl.frontFace(gl.CCW); //Dont really need to set it, its ccw by default.
gl.enable(gl.DEPTH_TEST); //Shouldn't use this, use something else to add depth detection
gl.enable(gl.CULL_FACE); //Cull back face, so only show triangles that are created clockwise
gl.depthFunc(gl.LEQUAL); //Near things obscure far things
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); //Setup default alpha blending
//gl.clearColor(1.0,1.0,1.0,1.0); //Set clear color
//...................................................
//Methods
//Reset the canvas with our set background color.
gl.fClear = function(){ this.clear(this.COLOR_BUFFER_BIT | this.DEPTH_BUFFER_BIT); return this; };
gl.fClearColor = function(hex){
var a = Util.rgbArray(hex);
gl.clearColor(a[0],a[1],a[2],1.0);
return this;
}
//Create and fill our Array buffer.
gl.fCreateArrayBuffer = function(floatAry,isStatic,isUnbind){
if(isStatic === undefined) isStatic = true; //So we can call this function without setting isStatic
var buf = this.createBuffer();
this.bindBuffer(this.ARRAY_BUFFER,buf);
this.bufferData(this.ARRAY_BUFFER, floatAry, (isStatic)? this.STATIC_DRAW : this.DYNAMIC_DRAW );
if(isUnbind != false) this.bindBuffer(this.ARRAY_BUFFER,null);
return buf;
};
//Textures
gl.fLoadTexture = function(name,img,doYFlip,noMips){ var tex = Fungi.Res.Textures[name] = this.createTexture(); return this.fUpdateTexture(name,img,doYFlip,noMips); };
gl.fUpdateTexture = function(name,img,doYFlip,noMips){
var tex = this.mTextureCache[name];
if(doYFlip == true) this.pixelStorei(this.UNPACK_FLIP_Y_WEBGL, true); //Flip the texture by the Y Position, So 0,0 is bottom left corner.
this.bindTexture(this.TEXTURE_2D, tex); //Set text buffer for work
this.texImage2D(this.TEXTURE_2D, 0, this.RGBA, this.RGBA, this.UNSIGNED_BYTE, img); //Push image to GPU.
if(noMips === undefined || noMips == false){
this.texParameteri(this.TEXTURE_2D, this.TEXTURE_MAG_FILTER, this.LINEAR); //Setup up scaling
this.texParameteri(this.TEXTURE_2D, this.TEXTURE_MIN_FILTER, this.LINEAR_MIPMAP_NEAREST); //Setup down scaling
this.generateMipmap(this.TEXTURE_2D); //Precalc different sizes of texture for better quality rendering.
}else{
this.texParameteri(this.TEXTURE_2D, this.TEXTURE_MAG_FILTER, this.NEAREST);
this.texParameteri(this.TEXTURE_2D, this.TEXTURE_MIN_FILTER, this.NEAREST);
this.texParameteri(this.TEXTURE_2D, this.TEXTURE_WRAP_S, this.CLAMP_TO_EDGE);
this.texParameteri(this.TEXTURE_2D, this.TEXTURE_WRAP_T, this.CLAMP_TO_EDGE);
}
this.bindTexture(this.TEXTURE_2D,null); //Unbind
if(doYFlip == true) this.pixelStorei(this.UNPACK_FLIP_Y_WEBGL, false); //Stop flipping textures
return tex;
}
//imgAry must be 6 elements long and images placed in the right order
//RIGHT,LEFT,TOP,BOTTOM,BACK,FRONT
gl.fLoadCubeMap = function(name,imgAry){
if(imgAry.length != 6) return null;
//Cube Constants values increment, so easy to start with right and just add 1 in a loop
//To make the code easier costs by making the imgAry coming into the function to have
//the images sorted in the same way the constants are set.
// TEXTURE_CUBE_MAP_POSITIVE_X - Right :: TEXTURE_CUBE_MAP_NEGATIVE_X - Left
// TEXTURE_CUBE_MAP_POSITIVE_Y - Top :: TEXTURE_CUBE_MAP_NEGATIVE_Y - Bottom
// TEXTURE_CUBE_MAP_POSITIVE_Z - Back :: TEXTURE_CUBE_MAP_NEGATIVE_Z - Front
var tex = this.createTexture();
this.bindTexture(this.TEXTURE_CUBE_MAP,tex);
//push image to specific spot in the cube map.
for(var i=0; i < 6; i++){
this.texImage2D(this.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, this.RGBA, this.RGBA, this.UNSIGNED_BYTE, imgAry[i]);
}
this.texParameteri(this.TEXTURE_CUBE_MAP, this.TEXTURE_MAG_FILTER, this.LINEAR); //Setup up scaling
this.texParameteri(this.TEXTURE_CUBE_MAP, this.TEXTURE_MIN_FILTER, this.LINEAR); //Setup down scaling
this.texParameteri(this.TEXTURE_CUBE_MAP, this.TEXTURE_WRAP_S, this.CLAMP_TO_EDGE); //Stretch image to X position
this.texParameteri(this.TEXTURE_CUBE_MAP, this.TEXTURE_WRAP_T, this.CLAMP_TO_EDGE); //Stretch image to Y position
this.texParameteri(this.TEXTURE_CUBE_MAP, this.TEXTURE_WRAP_R, this.CLAMP_TO_EDGE); //Stretch image to Z position
//this.generateMipmap(this.TEXTURE_CUBE_MAP);
this.bindTexture(this.TEXTURE_CUBE_MAP,null);
Fungi.Res.Textures[name] = tex;
return tex;
};
//...................................................
//Setters - Getters
//Set the size of the canvas html element and the rendering view port
gl.fSetSize = function(w,h){
//set the size of the canvas, on chrome we need to set it 3 ways to make it work perfectly.
this.canvas.style.width = w + "px";
this.canvas.style.height = h + "px";
this.canvas.width = w;
this.canvas.height = h;
//when updating the canvas size, must reset the viewport of the canvas
//else the resolution webgl renders at will not change
this.viewport(0,0,w,h);
this.fWidth = w; //Need to save Width and Height to resize viewport for WebVR
this.fHeight = h;
return this;
}
//Set the size of the canvas to fill a % of the total screen.
gl.fFitScreen = function(wp,hp){ return this.fSetSize(window.innerWidth * (wp || 1),window.innerHeight * (hp || 1)); }
return Fungi.gl = gl;
}
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
class Util{
//Convert Hex colors to float arrays, can batch process a list into one big array.
//example : Fungi.Util.rgbArray("#FF0000","00FF00","#0000FF");
static rgbArray(){
if(arguments.length == 0) return null;
var rtn = [];
for(var i=0,c,p; i < arguments.length; i++){
if(arguments[i].length < 6) continue;
c = arguments[i]; //Just an alias(copy really) of the color text, make code smaller.
p = (c[0] == "#")?1:0; //Determine starting position in char array to start pulling from
rtn.push(
parseInt(c[p] +c[p+1],16) / 255.0,
parseInt(c[p+2] +c[p+3],16) / 255.0,
parseInt(c[p+4] +c[p+5],16) / 255.0
);
}
return rtn;
}
//Normalize x value to x range, then normalize to lerp the z range.
static map(x, xMin,xMax, zMin,zMax){ return (x - xMin) / (xMax - xMin) * (zMax-zMin) + zMin; }
static clamp(v,min,max){ return Math.max(min,Math.min(max,v)); }
static smoothStep(edge1, edge2, val){ //https://en.wikipedia.org/wiki/Smoothstep
var x = Math.max(0, Math.min(1, (val-edge1)/(edge2-edge1)));
return x*x*(3-2*x);
}
//Get a number between A and B from a normalized number.
static lerp(a,b,t){ return a + t * (b-a); }
static pointCloseToLine(x0,y0,x1,y1,px,py){
var dx = x1 - x0,
dy = y1 - y0,
t = ((px-x0)*dx + (py-y0)*dy) / (dx*dx+dy*dy),
x = Util.lerp(x0, x1, t),
y = Util.lerp(y0, y1, t);
return [x,y]
}
//static viewportSpace(xCanvas,yCanvas){ return [ xCanvas*2 / gl.fWidth - 1, 1 - yCanvas*2/ gl.fHeight ]; }
}
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Transform is like our Rendering container and a base class.
We extend Transform with Renderable which handles things that will get renders to the screen.
Then we have a camera which shapes how our renderables render had moves us around the world.
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
class Transform{
constructor(){
//Transformation Data
this.position = new Vec3(0);
this.scale = new Vec3(1);
this.rotation = new Quaternion();
this.localMatrix = new Matrix4();
this.worldMatrix = new Matrix4();
//Parent / Child Relations
this.children = [];
this._parent = null;
this.visible = true;
}
//----------------------------------------------
//region Setters/Getters
//R T F T
//00 04 08 12
//01 05 09 13
//02 06 10 14
//03 07 11 15
left(v,d){ return this._getDirection(0,1,2,d,v); }
up(v,d){ return this._getDirection(4,5,6,d,v); }
forward(v,d){ return this._getDirection(8,9,10,d,v); }
_getDirection(xi,yi,zi,d,v){
this.updateMatrix();
if(d == undefined) d = 1; //Distance
//d = d || 1; //Distance
v = v || new Vec3();
var x = this.localMatrix[xi], y = this.localMatrix[yi], z = this.localMatrix[zi],
m = Math.sqrt( x*x + y*y + z*z );
v[0] = x/m*d;
v[1] = y/m*d;
v[2] = z/m*d;
return v;
}
get parent(){ this._parent; }
set parent(p){
if(this._parent != null){ this._parent.removeChild(this); }
if(p != null) p.addChild(this); //addChild also sets parent
}
//Chaining functions, useful for initializing
setPosition(x,y,z){ this.position.set(x,y,z); return this; }
setScale(x,y,z){ this.scale.set(x,y,z); return this; }
//endregion
//----------------------------------------------
//region Methods
updateMatrixOLD(){
//Only Update the Matrix if its needed.
if(!this.position.isModified && !this.scale.isModified && !this.rotation.isModified) return this.localMatrix;
//Update our local Matrix
Matrix4.fromQuaternionTranslationScale(this.localMatrix, this.rotation, this.position, this.scale);
//Set the modified indicator to false on all the transforms.
this.position.isModified = false;
this.scale.isModified = false;
this.rotation.isModified = false;
return this.localMatrix;
}
updateMatrix(forceWorldUpdate){
var isDirty = (this.position.isModified || this.scale.isModified || this.rotation.isModified);
if(!isDirty && !forceWorldUpdate) return false;
else if(isDirty){
//Update our local Matrix
Matrix4.fromQuaternionTranslationScale(this.localMatrix, this.rotation, this.position, this.scale);
//Set the modified indicator to false on all the transforms.
this.position.isModified = false;
this.scale.isModified = false;
this.rotation.isModified = false;
}
//Figure out the world matrix.
if(this._parent != null){
Matrix4.mult(this.worldMatrix, this._parent.worldMatrix, this.localMatrix);
}else this.worldMatrix.copy(this.localMatrix); //if not parent, localMatrix is worldMatrix
return true;
}
addChild(c){
if(this.children.indexOf(c) == -1){ //check if child already exists
c._parent = this;
this.children.push(c);
}
return this;
}
removeChild(c){
var i = this.children.indexOf(c);
if(i != -1){
this.children[i]._parent = null;
this.children.splice(i,1);
}
return this;
}
//endregion
}
class Renderable extends Transform{
constructor(vao,matName){
super();
this.vao = vao;
this.material = (matName != null && matName !== undefined)? Fungi.Res.Materials[matName] : null;
}
setMaterial(matName){ this.material = Fungi.Res.Materials[matName]; }
draw(){
if(this.vao.count == 0) return;
gl.bindVertexArray(this.vao.id);
if(this.vao.isIndexed) gl.drawElements(this.material.drawMode, this.vao.count, gl.UNSIGNED_SHORT, 0);
else gl.drawArrays(this.material.drawMode, 0, this.vao.count);
}
}
class CameraOrbit extends Transform{
constructor(fov,near,far){
super();
//Setup the projection and invert matrices
this.ubo = Fungi.Res.Ubo[Fungi.UBO_TRANSFORM];
this.projectionMatrix = new Float32Array(16);
this.invertedLocalMatrix = new Float32Array(16);
var ratio = gl.canvas.width / gl.canvas.height;
Matrix4.perspective(this.projectionMatrix, fov || 45, ratio, near || 0.1, far || 100.0);
this.ubo.update("matProjection",this.projectionMatrix); //Initialize The Transform UBO.
//Orbit Camera will control things based on euler, its cheating but not ready for quaternions
this.euler = new Vec3();
}
//Override how this transfer creates the localMatrix : Call Update, not this function in render loop.
updateMatrix(){
//Only Update the Matrix if its needed.
//if(!this.position.isModified && !this.rotation.isModified && !this.euler.isModified) return this.localMatrix;
Quaternion.setFromEuler(this.rotation,this.euler.x,this.euler.y,this.euler.z,"YXZ");
Matrix4.fromQuaternion(this.localMatrix,this.rotation);
this.localMatrix.resetTranslation().translate(this.position);
//Set the modified indicator to false on all the transforms.
this.position.isModified = false;
this.rotation.isModified = false;
this.euler.isModified = false;
return this.localMatrix;
}
//Update the Matrices and UBO.
update(){
if(this.position.isModified || this.scale.isModified || this.euler.isModified) this.updateMatrix();
Matrix4.invert(this.invertedLocalMatrix,this.localMatrix);
this.ubo.update("matCameraView",this.invertedLocalMatrix,"posCamera",this.position);
}
setEulerDegrees(x,y,z){ this.euler.set(x * DEG2RAD,y * DEG2RAD,z * DEG2RAD); return this; }
}
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Fungi.Maths
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
class Vec3 extends Float32Array{
constructor(ini){
super(3);
if(ini instanceof Vec3 || (ini && ini.length == 3)){
this[0] = ini[0]; this[1] = ini[1]; this[2] = ini[2];
}else if(arguments.length == 3){
this[0] = arguments[0]; this[1] = arguments[1]; this[2] = arguments[2];
}else{
this[0] = this[1] = this[2] = ini || 0;
}
this.isModified = true;
}
//----------------------------------------------
//region XYZ Setters
set(x,y,z){ this[0] = x; this[1] = y; this[2] = z; this.isModified = true; return this;}
get x(){ return this[0]; } set x(val){ this[0] = val; this.isModified = true; }
get y(){ return this[1]; } set y(val){ this[1] = val; this.isModified = true; }
get z(){ return this[2]; } set z(val){ this[2] = val; this.isModified = true; }
//endregion
//----------------------------------------------
//region Methods
magnitude(v){
//Only get the magnitude of this vector
if(v === undefined) return Math.sqrt( this[0]*this[0] + this[1]*this[1] + this[2]*this[2] );
//Get magnitude based on another vector
var x = this[0] - v[0],
y = this[1] - v[1],
z = this[2] - v[2];
return Math.sqrt( x*x + y*y + z*z );
}
sqrMag(v){
//Only get the squared magnitude of this vector
if(v === undefined) return this[0]*this[0] + this[1]*this[1] + this[2]*this[2];
//Get squared magnitude based on another vector
var x = this[0] - v[0],
y = this[1] - v[1],
z = this[2] - v[2];
return x*x + y*y + z*z;
}
normalize(out){
var mag = Math.sqrt( this[0]*this[0] + this[1]*this[1] + this[2]*this[2] );
if(mag == 0) return this;
out = out || this;
out[0] = this[0] / mag;
out[1] = this[1] / mag;
out[2] = this[2] / mag;
if(out === this) this.isModified = true;
return this;
}
multi(v,out){
out = out || this;
out[0] = this[0] * v;
out[1] = this[1] * v;
out[2] = this[2] * v;
if(out === this) this.isModified = true;
return this;
}
add(v,out){
out = out || this;
out[0] = this[0] + v[0];
out[1] = this[1] + v[1];
out[2] = this[2] + v[2];
if(out === this) this.isModified = true;
return this;
}
sub(v,out){
out = out || this;
out[0] = this[0] - v[0];
out[1] = this[1] - v[1];
out[2] = this[2] - v[2];
if(out === this) this.isModified = true;
return this;
}
clone(){ return new Vec3().set(this.x,this.y,this.z); }
copy(v){
this[0] = v[0]; this[1] = v[1]; this[2] = v[2];
this.isModified = true;
return this;
}
transformMat3(m,out){
var x = this[0], y = this[1], z = this[2];
out = out || this;
out[0] = x * m[0] + y * m[3] + z * m[6];
out[1] = x * m[1] + y * m[4] + z * m[7];
out[2] = x * m[2] + y * m[5] + z * m[8];
return out;
}
transformMat4(m,out){
var x = this[0], y = this[1], z = this[2],
w = m[3] * x + m[7] * y + m[11] * z + m[15];
w = w || 1.0;
out = out || this;
out[0] = (m[0] * x + m[4] * y + m[8] * z + m[12]) / w;
out[1] = (m[1] * x + m[5] * y + m[9] * z + m[13]) / w;
out[2] = (m[2] * x + m[6] * y + m[10] * z + m[14]) / w;
return out;
}
static dot(a,b){ return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; }
static cross(a,b,out){
var ax = a[0], ay = a[1], az = a[2],
bx = b[0], by = b[1], bz = b[2];
out[0] = ay * bz - az * by;
out[1] = az * bx - ax * bz;
out[2] = ax * by - ay * bx;
return out;
}
//endregion
}
class Quaternion extends Float32Array{
constructor(){
super(4);
this[0] = this[1] = this[2] = 0;
this[3] = 1;
this.isModified = false;
}
//http://in2gpu.com/2016/03/14/opengl-fps-camera-quaternion/
//----------------------------------------------
//region Setter/Getters
reset(){ this[0] = this[1] = this[2] = 0; this[3] = 1; this.isModified = false; return this; }
get x(){ return this[0]; } set x(val){ this[0] = val; this.isModified = true; }
get y(){ return this[1]; } set y(val){ this[1] = val; this.isModified = true; }
get z(){ return this[2]; } set z(val){ this[2] = val; this.isModified = true; }
get w(){ return this[3]; } set w(val){ this[3] = val; this.isModified = true; }
rx(rad){ Quaternion.rotateX(this,this,rad); this.isModified = true; return this; }
ry(rad){ Quaternion.rotateY(this,this,rad); this.isModified = true; return this; }
rz(rad){ Quaternion.rotateZ(this,this,rad); this.isModified = true; return this; }
//ex(deg){ Quaternion.rotateX(this,this,deg * DEG2RAD); this.isModified = true; return this; }
//ey(deg){ Quaternion.rotateY(this,this,deg * DEG2RAD); this.isModified = true; return this; }
//ez(deg){ Quaternion.rotateZ(this,this,deg * DEG2RAD); this.isModified = true; return this; }
//endregion
normalize(out){
var len = this[0]*this[0] + this[1]*this[1] + this[2]*this[2] + this[3]*this[3];
if(len > 0){
len = 1 / Math.sqrt(len);
out = out || this;
out[0] = this[0] * len;
out[1] = this[1] * len;
out[2] = this[2] * len;
out[3] = this[3] * len;
if(out === this) this.isModified = true;
}
return this;
}
//----------------------------------------------
//region Static Methods
static multi(out,a,b){
var ax = a[0], ay = a[1], az = a[2], aw = a[3],
bx = b[0], by = b[1], bz = b[2], bw = b[3];
out[0] = ax * bw + aw * bx + ay * bz - az * by;
out[1] = ay * bw + aw * by + az * bx - ax * bz;
out[2] = az * bw + aw * bz + ax * by - ay * bx;
out[3] = aw * bw - ax * bx - ay * by - az * bz;
return out;
}
static multiVec3(out,q,v){
var ax = q[0], ay = q[1], az = q[2], aw = q[3],
bx = v[0], by = v[1], bz = v[2];
out[0] = ax + aw * bx + ay * bz - az * by;
out[1] = ay + aw * by + az * bx - ax * bz;
out[2] = az + aw * bz + ax * by - ay * bx;
return out;
}
//Ported to JS from C# example at https://pastebin.com/ubATCxJY
//Note, if Dir and Up are equal, a roll happends. Need to find a way to fix this.
static lookRotation(vDir, vUp, out){
var zAxis = new Vec3(vDir), //Forward
up = new Vec3(vUp),
xAxis = new Vec3(), //Right
yAxis = new Vec3();
zAxis.normalize();
Vec3.cross(up,zAxis,xAxis);
xAxis.normalize();
Vec3.cross(zAxis,xAxis,yAxis); //new up
//fromAxis - Mat3 to Quaternion
var m00 = xAxis.x, m01 = xAxis.y, m02 = xAxis.z,
m10 = yAxis.x, m11 = yAxis.y, m12 = yAxis.z,
m20 = zAxis.x, m21 = zAxis.y, m22 = zAxis.z,
t = m00 + m11 + m22,
x, y, z, w, s;
if(t > 0.0){
s = Math.sqrt(t + 1.0);
w = s * 0.5 ; // |w| >= 0.5
s = 0.5 / s;
x = (m12 - m21) * s;
y = (m20 - m02) * s;
z = (m01 - m10) * s;
}else if((m00 >= m11) && (m00 >= m22)){
S = Math.sqrt(1.0 + m00 - m11 - m22);
x = 0.5 * s;// |x| >= 0.5
s = 0.5 / s;
y = (m01 + m10) * s;
z = (m02 + m20) * s;
w = (m12 - m21) * s;
}else if(m11 > m22){
s = Math.sqrt(1.0 + m11 - m00 - m22);
y = 0.5 * s; // |y| >= 0.5
s = 0.5 / s;
x = (m10 + m01) * s;
z = (m21 + m12) * s;
w = (m20 - m02) * s;
}else{
s = Math.sqrt(1.0 + m22 - m00 - m11);
z = 0.5 * s; // |z| >= 0.5
s = 0.5 / s;
x = (m20 + m02) * s;
y = (m21 + m12) * s;
w = (m01 - m10) * s;
}
out[0] = x;
out[1] = y;
out[2] = z;
out[3] = w;
/*
var num8 = (m00 + m11) + m22;
if (num8 > 0.0){
var num = Math.sqrt(num8 + 1.0);
out.w = num * 0.5;
num = 0.5 / num;
out.x = (m12 - m21) * num;
out.y = (m20 - m02) * num;
out.z = (m01 - m10) * num;
return out;
}
if((m00 >= m11) && (m00 >= m22)){
var num7 = Math.sqrt(1.0 + m00 - m11 - m22);
var num4 = 0.5 / num7;
out.x = 0.5 * num7;
out.y = (m01 + m10) * num4;
out.z = (m02 + m20) * num4;
out.w = (m12 - m21) * num4;
return out;
}
if(m11 > m22){
var num6 = Math.sqrt(((1.0 + m11) - m00) - m22);
var num3 = 0.5 / num6;
out.x = (m10 + m01) * num3;
out.y = 0.5 * num6;
out.z = (m21 + m12) * num3;
out.w = (m20 - m02) * num3;
return out;
}
var num5 = Math.sqrt(((1.0 + m22) - m00) - m11);
var num2 = 0.5 / num5;
out.x = (m20 + m02) * num2;
out.y = (m21 + m12) * num2;
out.z = 0.5 * num5;
out.w = (m01 - m10) * num2;
return out;
*/
}
/*
setAxisAngle(axis, angle){
var halfAngle = angle * .5;
var s = Math.sin(halfAngle);
this[0] = axis[0] * s;
this[1] = axis[1] * s;
this[2] = axis[2] * s;
this[3] = Math.cos(halfAngle);
return this;
}
*/
//https://github.com/toji/gl-matrix/blob/master/src/gl-matrix/quat.js
static rotateX(out, a, rad){
rad *= 0.5;
var ax = a[0], ay = a[1], az = a[2], aw = a[3],
bx = Math.sin(rad), bw = Math.cos(rad);
out[0] = ax * bw + aw * bx;
out[1] = ay * bw + az * bx;
out[2] = az * bw - ay * bx;
out[3] = aw * bw - ax * bx;
return out;
}
static rotateY(out, a, rad) {
rad *= 0.5;
var ax = a[0], ay = a[1], az = a[2], aw = a[3],
by = Math.sin(rad), bw = Math.cos(rad);
out[0] = ax * bw - az * by;
out[1] = ay * bw + aw * by;
out[2] = az * bw + ax * by;
out[3] = aw * bw - ay * by;
return out;
}
static rotateZ(out, a, rad){
rad *= 0.5;
var ax = a[0], ay = a[1], az = a[2], aw = a[3],
bz = Math.sin(rad), bw = Math.cos(rad);
out[0] = ax * bw + ay * bz;
out[1] = ay * bw - ax * bz;
out[2] = az * bw + aw * bz;
out[3] = aw * bw - az * bz;
return out;
}
//https://github.com/mrdoob/three.js/blob/dev/src/math/Quaternion.js
static setFromEuler(out,x,y,z,order){
var c1 = Math.cos(x/2),
c2 = Math.cos(y/2),
c3 = Math.cos(z/2),
s1 = Math.sin(x/2),
s2 = Math.sin(y/2),
s3 = Math.sin(z/2);
switch(order){
case 'XYZ':
out[0] = s1 * c2 * c3 + c1 * s2 * s3;
out[1] = c1 * s2 * c3 - s1 * c2 * s3;
out[2] = c1 * c2 * s3 + s1 * s2 * c3;
out[3] = c1 * c2 * c3 - s1 * s2 * s3;
break;
case 'YXZ':
out[0] = s1 * c2 * c3 + c1 * s2 * s3;
out[1] = c1 * s2 * c3 - s1 * c2 * s3;
out[2] = c1 * c2 * s3 - s1 * s2 * c3;
out[3] = c1 * c2 * c3 + s1 * s2 * s3;
break;
case 'ZXY':
out[0] = s1 * c2 * c3 - c1 * s2 * s3;
out[1] = c1 * s2 * c3 + s1 * c2 * s3;
out[2] = c1 * c2 * s3 + s1 * s2 * c3;
out[3] = c1 * c2 * c3 - s1 * s2 * s3;
break;
case 'ZYX':
out[0] = s1 * c2 * c3 - c1 * s2 * s3;
out[1] = c1 * s2 * c3 + s1 * c2 * s3;
out[2] = c1 * c2 * s3 - s1 * s2 * c3;
out[3] = c1 * c2 * c3 + s1 * s2 * s3;
break;
case 'YZX':
out[0] = s1 * c2 * c3 + c1 * s2 * s3;
out[1] = c1 * s2 * c3 + s1 * c2 * s3;
out[2] = c1 * c2 * s3 - s1 * s2 * c3;
out[3] = c1 * c2 * c3 - s1 * s2 * s3;
break;
case 'XZY':
out[0] = s1 * c2 * c3 - c1 * s2 * s3;
out[1] = c1 * s2 * c3 - s1 * c2 * s3;
out[2] = c1 * c2 * s3 + s1 * s2 * c3;
out[3] = c1 * c2 * c3 + s1 * s2 * s3;
break;
}
}
//endregion
}
class Matrix4 extends Float32Array{
constructor(){ super(16); this[0] = this[5] = this[10] = this[15] = 1; } //Setup Identity
//----------------------------------------------
//region Methods
translate(ary){ Matrix4.translate(this,ary[0],ary[1],ary[2]); return this;}
resetTranslation(){ this[12] = this[13] = this[14] = 0; this[15] = 1; return this; }
//reset data back to identity.
reset(){
for(var i=0; i <= this.length; i++) this[i] = (i % 5 == 0)? 1 : 0; //only positions 0,5,10,15 need to be 1 else 0
return this;
}
//copy another matrix's data to this one.
copy(mat){
for(var i=0; i < 16; i++) this[i] = mat[i];
return this;
}
//endregion
//----------------------------------------------
//region Static
static identity(out){
for(var i=0; i <= out.length; i++) out[i] = (i % 5 == 0)? 1 : 0; //only positions 0,5,10,15 need to be 1 else 0
}
static perspective(out, fovy, aspect, near, far){
var f = 1.0 / Math.tan(fovy / 2),
nf = 1 / (near - far);
out[0] = f / aspect;
out[1] = 0;
out[2] = 0;
out[3] = 0;
out[4] = 0;
out[5] = f;
out[6] = 0;
out[7] = 0;
out[8] = 0;
out[9] = 0;
out[10] = (far + near) * nf;
out[11] = -1;
out[12] = 0;
out[13] = 0;
out[14] = (2 * far * near) * nf;
out[15] = 0;
}
static ortho(out, left, right, bottom, top, near, far) {
var lr = 1 / (left - right),
bt = 1 / (bottom - top),
nf = 1 / (near - far);
out[0] = -2 * lr;
out[1] = 0;
out[2] = 0;
out[3] = 0;
out[4] = 0;
out[5] = -2 * bt;
out[6] = 0;
out[7] = 0;
out[8] = 0;
out[9] = 0;
out[10] = 2 * nf;
out[11] = 0;
out[12] = (left + right) * lr;
out[13] = (top + bottom) * bt;
out[14] = (far + near) * nf;
out[15] = 1;
};
//make the rows into the columns
static transpose(out, a){
//If we are transposing ourselves we can skip a few steps but have to cache some values
if (out === a) {
var a01 = a[1], a02 = a[2], a03 = a[3], a12 = a[6], a13 = a[7], a23 = a[11];
out[1] = a[4];
out[2] = a[8];
out[3] = a[12];
out[4] = a01;
out[6] = a[9];
out[7] = a[13];
out[8] = a02;
out[9] = a12;
out[11] = a[14];
out[12] = a03;
out[13] = a13;
out[14] = a23;
}else{
out[0] = a[0];
out[1] = a[4];
out[2] = a[8];
out[3] = a[12];
out[4] = a[1];
out[5] = a[5];
out[6] = a[9];
out[7] = a[13];
out[8] = a[2];
out[9] = a[6];
out[10] = a[10];
out[11] = a[14];
out[12] = a[3];
out[13] = a[7];
out[14] = a[11];
out[15] = a[15];
}
return out;
}
//Calculates a 3x3 normal matrix (transpose inverse) from the 4x4 matrix
static normalMat3(out,a){
var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3],
a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7],
a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11],
a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15],
b00 = a00 * a11 - a01 * a10,
b01 = a00 * a12 - a02 * a10,
b02 = a00 * a13 - a03 * a10,
b03 = a01 * a12 - a02 * a11,
b04 = a01 * a13 - a03 * a11,
b05 = a02 * a13 - a03 * a12,
b06 = a20 * a31 - a21 * a30,
b07 = a20 * a32 - a22 * a30,
b08 = a20 * a33 - a23 * a30,
b09 = a21 * a32 - a22 * a31,
b10 = a21 * a33 - a23 * a31,
b11 = a22 * a33 - a23 * a32,
// Calculate the determinant
det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
if (!det) return null;
det = 1.0 / det;
out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
out[1] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
out[2] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
out[3] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
out[4] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
out[5] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
out[6] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
out[7] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
out[8] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
return out;
}
//New function derived from fromRotationTranslation, just took out the translation stuff.
static fromQuaternion(out, q){
// Quaternion math
var x = q[0], y = q[1], z = q[2], w = q[3],
x2 = x + x,
y2 = y + y,
z2 = z + z,
xx = x * x2,
xy = x * y2,
xz = x * z2,
yy = y * y2,
yz = y * z2,
zz = z * z2,
wx = w * x2,
wy = w * y2,
wz = w * z2;
out[0] = 1 - (yy + zz);
out[1] = xy + wz;
out[2] = xz - wy;
out[3] = 0;
out[4] = xy - wz;
out[5] = 1 - (xx + zz);
out[6] = yz + wx;
out[7] = 0;
out[8] = xz + wy;
out[9] = yz - wx;
out[10] = 1 - (xx + yy);
out[11] = 0;
return out;
}
//https://github.com/toji/gl-matrix/blob/master/src/gl-matrix/mat4.js
static fromQuaternionTranslation(out, q, v){
// Quaternion math
var x = q[0], y = q[1], z = q[2], w = q[3],
x2 = x + x,
y2 = y + y,
z2 = z + z,
xx = x * x2,
xy = x * y2,
xz = x * z2,
yy = y * y2,
yz = y * z2,
zz = z * z2,
wx = w * x2,
wy = w * y2,
wz = w * z2;
out[0] = 1 - (yy + zz);
out[1] = xy + wz;
out[2] = xz - wy;
out[3] = 0;
out[4] = xy - wz;
out[5] = 1 - (xx + zz);
out[6] = yz + wx;
out[7] = 0;
out[8] = xz + wy;
out[9] = yz - wx;
out[10] = 1 - (xx + yy);
out[11] = 0;
out[12] = v[0];
out[13] = v[1];
out[14] = v[2];
out[15] = 1;
return out;
}
static fromQuaternionTranslationScale(out, q, v, s){
// Quaternion math
var x = q[0], y = q[1], z = q[2], w = q[3],
x2 = x + x,
y2 = y + y,
z2 = z + z,
xx = x * x2,
xy = x * y2,
xz = x * z2,
yy = y * y2,
yz = y * z2,
zz = z * z2,
wx = w * x2,
wy = w * y2,
wz = w * z2,
sx = s[0],