forked from evanw/webgl-water
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lightgl.js
2068 lines (1902 loc) · 69.2 KB
/
lightgl.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
/*
* lightgl.js
* http://github.com/evanw/lightgl.js/
*
* Copyright 2011 Evan Wallace
* Released under the MIT license
*/
var GL = (function() {
// src/main.js
// The internal `gl` variable holds the current WebGL context.
var gl;
var GL = {
// ### Initialization
//
// `GL.create()` creates a new WebGL context and augments it with more
// methods. The alpha channel is disabled by default because it usually causes
// unintended transparencies in the canvas.
create: function(options) {
options = options || {};
var canvas = document.createElement('canvas');
canvas.width = 800;
canvas.height = 600;
if (!('alpha' in options)) options.alpha = false;
try { gl = canvas.getContext('webgl', options); } catch (e) {}
try { gl = gl || canvas.getContext('experimental-webgl', options); } catch (e) {}
if (!gl) throw new Error('WebGL not supported');
gl.HALF_FLOAT_OES = 0x8D61;
addMatrixStack();
addImmediateMode();
addEventListeners();
addOtherMethods();
return gl;
},
// `GL.keys` contains a mapping of key codes to booleans indicating whether
// that key is currently pressed.
keys: {},
// Export all external classes.
Matrix: Matrix,
Indexer: Indexer,
Buffer: Buffer,
Mesh: Mesh,
HitTest: HitTest,
Raytracer: Raytracer,
Shader: Shader,
Texture: Texture,
Vector: Vector
};
// ### Matrix stack
//
// Implement the OpenGL modelview and projection matrix stacks, along with some
// other useful GLU matrix functions.
function addMatrixStack() {
gl.MODELVIEW = ENUM | 1;
gl.PROJECTION = ENUM | 2;
var tempMatrix = new Matrix();
var resultMatrix = new Matrix();
gl.modelviewMatrix = new Matrix();
gl.projectionMatrix = new Matrix();
var modelviewStack = [];
var projectionStack = [];
var matrix, stack;
gl.matrixMode = function(mode) {
switch (mode) {
case gl.MODELVIEW:
matrix = 'modelviewMatrix';
stack = modelviewStack;
break;
case gl.PROJECTION:
matrix = 'projectionMatrix';
stack = projectionStack;
break;
default:
throw new Error('invalid matrix mode ' + mode);
}
};
gl.loadIdentity = function() {
Matrix.identity(gl[matrix]);
};
gl.loadMatrix = function(m) {
var from = m.m, to = gl[matrix].m;
for (var i = 0; i < 16; i++) {
to[i] = from[i];
}
};
gl.multMatrix = function(m) {
gl.loadMatrix(Matrix.multiply(gl[matrix], m, resultMatrix));
};
gl.perspective = function(fov, aspect, near, far) {
gl.multMatrix(Matrix.perspective(fov, aspect, near, far, tempMatrix));
};
gl.frustum = function(l, r, b, t, n, f) {
gl.multMatrix(Matrix.frustum(l, r, b, t, n, f, tempMatrix));
};
gl.ortho = function(l, r, b, t, n, f) {
gl.multMatrix(Matrix.ortho(l, r, b, t, n, f, tempMatrix));
};
gl.scale = function(x, y, z) {
gl.multMatrix(Matrix.scale(x, y, z, tempMatrix));
};
gl.translate = function(x, y, z) {
gl.multMatrix(Matrix.translate(x, y, z, tempMatrix));
};
gl.rotate = function(a, x, y, z) {
gl.multMatrix(Matrix.rotate(a, x, y, z, tempMatrix));
};
gl.lookAt = function(ex, ey, ez, cx, cy, cz, ux, uy, uz) {
gl.multMatrix(Matrix.lookAt(ex, ey, ez, cx, cy, cz, ux, uy, uz, tempMatrix));
};
gl.pushMatrix = function() {
stack.push(Array.prototype.slice.call(gl[matrix].m));
};
gl.popMatrix = function() {
var m = stack.pop();
gl[matrix].m = hasFloat32Array ? new Float32Array(m) : m;
};
gl.project = function(objX, objY, objZ, modelview, projection, viewport) {
modelview = modelview || gl.modelviewMatrix;
projection = projection || gl.projectionMatrix;
viewport = viewport || gl.getParameter(gl.VIEWPORT);
var point = projection.transformPoint(modelview.transformPoint(new Vector(objX, objY, objZ)));
return new Vector(
viewport[0] + viewport[2] * (point.x * 0.5 + 0.5),
viewport[1] + viewport[3] * (point.y * 0.5 + 0.5),
point.z * 0.5 + 0.5
);
};
gl.unProject = function(winX, winY, winZ, modelview, projection, viewport) {
modelview = modelview || gl.modelviewMatrix;
projection = projection || gl.projectionMatrix;
viewport = viewport || gl.getParameter(gl.VIEWPORT);
var point = new Vector(
(winX - viewport[0]) / viewport[2] * 2 - 1,
(winY - viewport[1]) / viewport[3] * 2 - 1,
winZ * 2 - 1
);
return Matrix.inverse(Matrix.multiply(projection, modelview, tempMatrix), resultMatrix).transformPoint(point);
};
gl.matrixMode(gl.MODELVIEW);
}
// ### Immediate mode
//
// Provide an implementation of OpenGL's deprecated immediate mode. This is
// depricated for a reason: constantly re-specifying the geometry is a bad
// idea for performance. You should use a `GL.Mesh` instead, which specifies
// the geometry once and caches it on the graphics card. Still, nothing
// beats a quick `gl.begin(gl.POINTS); gl.vertex(1, 2, 3); gl.end();` for
// debugging. This intentionally doesn't implement fixed-function lighting
// because it's only meant for quick debugging tasks.
function addImmediateMode() {
var immediateMode = {
mesh: new Mesh({ coords: true, colors: true, triangles: false }),
mode: -1,
coord: [0, 0, 0, 0],
color: [1, 1, 1, 1],
pointSize: 1,
shader: new Shader('\
uniform float pointSize;\
varying vec4 color;\
varying vec4 coord;\
void main() {\
color = gl_Color;\
coord = gl_TexCoord;\
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;\
gl_PointSize = pointSize;\
}\
', '\
uniform sampler2D texture;\
uniform float pointSize;\
uniform bool useTexture;\
varying vec4 color;\
varying vec4 coord;\
void main() {\
gl_FragColor = color;\
if (useTexture) gl_FragColor *= texture2D(texture, coord.xy);\
}\
')
};
gl.pointSize = function(pointSize) {
immediateMode.shader.uniforms({ pointSize: pointSize });
};
gl.begin = function(mode) {
if (immediateMode.mode != -1) throw new Error('mismatched gl.begin() and gl.end() calls');
immediateMode.mode = mode;
immediateMode.mesh.colors = [];
immediateMode.mesh.coords = [];
immediateMode.mesh.vertices = [];
};
gl.color = function(r, g, b, a) {
immediateMode.color = (arguments.length == 1) ? r.toArray().concat(1) : [r, g, b, a || 1];
};
gl.texCoord = function(s, t) {
immediateMode.coord = (arguments.length == 1) ? s.toArray(2) : [s, t];
};
gl.vertex = function(x, y, z) {
immediateMode.mesh.colors.push(immediateMode.color);
immediateMode.mesh.coords.push(immediateMode.coord);
immediateMode.mesh.vertices.push(arguments.length == 1 ? x.toArray() : [x, y, z]);
};
gl.end = function() {
if (immediateMode.mode == -1) throw new Error('mismatched gl.begin() and gl.end() calls');
immediateMode.mesh.compile();
immediateMode.shader.uniforms({
useTexture: !!gl.getParameter(gl.TEXTURE_BINDING_2D)
}).draw(immediateMode.mesh, immediateMode.mode);
immediateMode.mode = -1;
};
}
// ### Improved mouse events
//
// This adds event listeners on the `gl.canvas` element that call
// `gl.onmousedown()`, `gl.onmousemove()`, and `gl.onmouseup()` with an
// augmented event object. The event object also has the properties `x`, `y`,
// `deltaX`, `deltaY`, and `dragging`.
function addEventListeners() {
var context = gl, oldX = 0, oldY = 0, buttons = {}, hasOld = false;
var has = Object.prototype.hasOwnProperty;
function isDragging() {
for (var b in buttons) {
if (has.call(buttons, b) && buttons[b]) return true;
}
return false;
}
function augment(original) {
// Make a copy of original, a native `MouseEvent`, so we can overwrite
// WebKit's non-standard read-only `x` and `y` properties (which are just
// duplicates of `pageX` and `pageY`). We can't just use
// `Object.create(original)` because some `MouseEvent` functions must be
// called in the context of the original event object.
var e = {};
for (var name in original) {
if (typeof original[name] == 'function') {
e[name] = (function(callback) {
return function() {
callback.apply(original, arguments);
};
})(original[name]);
} else {
e[name] = original[name];
}
}
e.original = original;
e.x = e.pageX;
e.y = e.pageY;
for (var obj = gl.canvas; obj; obj = obj.offsetParent) {
e.x -= obj.offsetLeft;
e.y -= obj.offsetTop;
}
if (hasOld) {
e.deltaX = e.x - oldX;
e.deltaY = e.y - oldY;
} else {
e.deltaX = 0;
e.deltaY = 0;
hasOld = true;
}
oldX = e.x;
oldY = e.y;
e.dragging = isDragging();
e.preventDefault = function() {
e.original.preventDefault();
};
e.stopPropagation = function() {
e.original.stopPropagation();
};
return e;
}
function mousedown(e) {
gl = context;
if (!isDragging()) {
// Expand the event handlers to the document to handle dragging off canvas.
on(document, 'mousemove', mousemove);
on(document, 'mouseup', mouseup);
off(gl.canvas, 'mousemove', mousemove);
off(gl.canvas, 'mouseup', mouseup);
}
buttons[e.which] = true;
e = augment(e);
if (gl.onmousedown) gl.onmousedown(e);
e.preventDefault();
}
function mousemove(e) {
gl = context;
e = augment(e);
if (gl.onmousemove) gl.onmousemove(e);
e.preventDefault();
}
function mouseup(e) {
gl = context;
buttons[e.which] = false;
if (!isDragging()) {
// Shrink the event handlers back to the canvas when dragging ends.
off(document, 'mousemove', mousemove);
off(document, 'mouseup', mouseup);
on(gl.canvas, 'mousemove', mousemove);
on(gl.canvas, 'mouseup', mouseup);
}
e = augment(e);
if (gl.onmouseup) gl.onmouseup(e);
e.preventDefault();
}
function reset() {
hasOld = false;
}
function resetAll() {
buttons = {};
hasOld = false;
}
on(gl.canvas, 'mousedown', mousedown);
on(gl.canvas, 'mousemove', mousemove);
on(gl.canvas, 'mouseup', mouseup);
on(gl.canvas, 'mouseover', reset);
on(gl.canvas, 'mouseout', reset);
on(document, 'contextmenu', resetAll);
}
// ### Automatic keyboard state
//
// The current keyboard state is stored in `GL.keys`, a map of integer key
// codes to booleans indicating whether that key is currently pressed. Certain
// keys also have named identifiers that can be used directly, such as
// `GL.keys.SPACE`. Values in `GL.keys` are initially undefined until that
// key is pressed for the first time. If you need a boolean value, you can
// cast the value to boolean by applying the not operator twice (as in
// `!!GL.keys.SPACE`).
function mapKeyCode(code) {
var named = {
8: 'BACKSPACE',
9: 'TAB',
13: 'ENTER',
16: 'SHIFT',
27: 'ESCAPE',
32: 'SPACE',
37: 'LEFT',
38: 'UP',
39: 'RIGHT',
40: 'DOWN'
};
return named[code] || (code >= 65 && code <= 90 ? String.fromCharCode(code) : null);
}
function on(element, name, callback) {
element.addEventListener(name, callback);
}
function off(element, name, callback) {
element.removeEventListener(name, callback);
}
on(document, 'keydown', function(e) {
if (!e.altKey && !e.ctrlKey && !e.metaKey) {
var key = mapKeyCode(e.keyCode);
if (key) GL.keys[key] = true;
GL.keys[e.keyCode] = true;
}
});
on(document, 'keyup', function(e) {
if (!e.altKey && !e.ctrlKey && !e.metaKey) {
var key = mapKeyCode(e.keyCode);
if (key) GL.keys[key] = false;
GL.keys[e.keyCode] = false;
}
});
function addOtherMethods() {
// ### Multiple contexts
//
// When using multiple contexts in one web page, `gl.makeCurrent()` must be
// called before issuing commands to a different context.
(function(context) {
gl.makeCurrent = function() {
gl = context;
};
})(gl);
// ### Animation
//
// Call `gl.animate()` to provide an animation loop that repeatedly calls
// `gl.onupdate()` and `gl.ondraw()`.
gl.animate = function() {
var post =
window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
function(callback) { setTimeout(callback, 1000 / 60); };
var time = new Date().getTime();
var context = gl;
function update() {
gl = context;
var now = new Date().getTime();
if (gl.onupdate) gl.onupdate((now - time) / 1000);
if (gl.ondraw) gl.ondraw();
post(update);
time = now;
}
update();
};
// ### Fullscreen
//
// Provide an easy way to get a fullscreen app running, including an
// automatic 3D perspective projection matrix by default. This should be
// called once.
//
// Just fullscreen, no automatic camera:
//
// gl.fullscreen({ camera: false });
//
// Adjusting field of view, near plane distance, and far plane distance:
//
// gl.fullscreen({ fov: 45, near: 0.1, far: 1000 });
//
// Adding padding from the edge of the window:
//
// gl.fullscreen({ paddingLeft: 250, paddingBottom: 60 });
//
gl.fullscreen = function(options) {
options = options || {};
var top = options.paddingTop || 0;
var left = options.paddingLeft || 0;
var right = options.paddingRight || 0;
var bottom = options.paddingBottom || 0;
if (!document.body) {
throw new Error('document.body doesn\'t exist yet (call gl.fullscreen() from ' +
'window.onload() or from inside the <body> tag)');
}
document.body.appendChild(gl.canvas);
document.body.style.overflow = 'hidden';
gl.canvas.style.position = 'absolute';
gl.canvas.style.left = left + 'px';
gl.canvas.style.top = top + 'px';
function resize() {
gl.canvas.width = window.innerWidth - left - right;
gl.canvas.height = window.innerHeight - top - bottom;
gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
if (options.camera || !('camera' in options)) {
gl.matrixMode(gl.PROJECTION);
gl.loadIdentity();
gl.perspective(options.fov || 45, gl.canvas.width / gl.canvas.height,
options.near || 0.1, options.far || 1000);
gl.matrixMode(gl.MODELVIEW);
}
if (gl.ondraw) gl.ondraw();
}
on(window, 'resize', resize);
resize();
};
}
// A value to bitwise-or with new enums to make them distinguishable from the
// standard WebGL enums.
var ENUM = 0x12340000;
// src/matrix.js
// Represents a 4x4 matrix stored in row-major order that uses Float32Arrays
// when available. Matrix operations can either be done using convenient
// methods that return a new matrix for the result or optimized methods
// that store the result in an existing matrix to avoid generating garbage.
var hasFloat32Array = (typeof Float32Array != 'undefined');
// ### new GL.Matrix([elements])
//
// This constructor takes 16 arguments in row-major order, which can be passed
// individually, as a list, or even as four lists, one for each row. If the
// arguments are omitted then the identity matrix is constructed instead.
function Matrix() {
var m = Array.prototype.concat.apply([], arguments);
if (!m.length) {
m = [
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
];
}
this.m = hasFloat32Array ? new Float32Array(m) : m;
}
Matrix.prototype = {
// ### .inverse()
//
// Returns the matrix that when multiplied with this matrix results in the
// identity matrix.
inverse: function() {
return Matrix.inverse(this, new Matrix());
},
// ### .transpose()
//
// Returns this matrix, exchanging columns for rows.
transpose: function() {
return Matrix.transpose(this, new Matrix());
},
// ### .multiply(matrix)
//
// Returns the concatenation of the transforms for this matrix and `matrix`.
// This emulates the OpenGL function `glMultMatrix()`.
multiply: function(matrix) {
return Matrix.multiply(this, matrix, new Matrix());
},
// ### .transformPoint(point)
//
// Transforms the vector as a point with a w coordinate of 1. This
// means translations will have an effect, for example.
transformPoint: function(v) {
var m = this.m;
return new Vector(
m[0] * v.x + m[1] * v.y + m[2] * v.z + m[3],
m[4] * v.x + m[5] * v.y + m[6] * v.z + m[7],
m[8] * v.x + m[9] * v.y + m[10] * v.z + m[11]
).divide(m[12] * v.x + m[13] * v.y + m[14] * v.z + m[15]);
},
// ### .transformPoint(vector)
//
// Transforms the vector as a vector with a w coordinate of 0. This
// means translations will have no effect, for example.
transformVector: function(v) {
var m = this.m;
return new Vector(
m[0] * v.x + m[1] * v.y + m[2] * v.z,
m[4] * v.x + m[5] * v.y + m[6] * v.z,
m[8] * v.x + m[9] * v.y + m[10] * v.z
);
}
};
// ### GL.Matrix.inverse(matrix[, result])
//
// Returns the matrix that when multiplied with `matrix` results in the
// identity matrix. You can optionally pass an existing matrix in `result`
// to avoid allocating a new matrix. This implementation is from the Mesa
// OpenGL function `__gluInvertMatrixd()` found in `project.c`.
Matrix.inverse = function(matrix, result) {
result = result || new Matrix();
var m = matrix.m, r = result.m;
r[0] = m[5]*m[10]*m[15] - m[5]*m[14]*m[11] - m[6]*m[9]*m[15] + m[6]*m[13]*m[11] + m[7]*m[9]*m[14] - m[7]*m[13]*m[10];
r[1] = -m[1]*m[10]*m[15] + m[1]*m[14]*m[11] + m[2]*m[9]*m[15] - m[2]*m[13]*m[11] - m[3]*m[9]*m[14] + m[3]*m[13]*m[10];
r[2] = m[1]*m[6]*m[15] - m[1]*m[14]*m[7] - m[2]*m[5]*m[15] + m[2]*m[13]*m[7] + m[3]*m[5]*m[14] - m[3]*m[13]*m[6];
r[3] = -m[1]*m[6]*m[11] + m[1]*m[10]*m[7] + m[2]*m[5]*m[11] - m[2]*m[9]*m[7] - m[3]*m[5]*m[10] + m[3]*m[9]*m[6];
r[4] = -m[4]*m[10]*m[15] + m[4]*m[14]*m[11] + m[6]*m[8]*m[15] - m[6]*m[12]*m[11] - m[7]*m[8]*m[14] + m[7]*m[12]*m[10];
r[5] = m[0]*m[10]*m[15] - m[0]*m[14]*m[11] - m[2]*m[8]*m[15] + m[2]*m[12]*m[11] + m[3]*m[8]*m[14] - m[3]*m[12]*m[10];
r[6] = -m[0]*m[6]*m[15] + m[0]*m[14]*m[7] + m[2]*m[4]*m[15] - m[2]*m[12]*m[7] - m[3]*m[4]*m[14] + m[3]*m[12]*m[6];
r[7] = m[0]*m[6]*m[11] - m[0]*m[10]*m[7] - m[2]*m[4]*m[11] + m[2]*m[8]*m[7] + m[3]*m[4]*m[10] - m[3]*m[8]*m[6];
r[8] = m[4]*m[9]*m[15] - m[4]*m[13]*m[11] - m[5]*m[8]*m[15] + m[5]*m[12]*m[11] + m[7]*m[8]*m[13] - m[7]*m[12]*m[9];
r[9] = -m[0]*m[9]*m[15] + m[0]*m[13]*m[11] + m[1]*m[8]*m[15] - m[1]*m[12]*m[11] - m[3]*m[8]*m[13] + m[3]*m[12]*m[9];
r[10] = m[0]*m[5]*m[15] - m[0]*m[13]*m[7] - m[1]*m[4]*m[15] + m[1]*m[12]*m[7] + m[3]*m[4]*m[13] - m[3]*m[12]*m[5];
r[11] = -m[0]*m[5]*m[11] + m[0]*m[9]*m[7] + m[1]*m[4]*m[11] - m[1]*m[8]*m[7] - m[3]*m[4]*m[9] + m[3]*m[8]*m[5];
r[12] = -m[4]*m[9]*m[14] + m[4]*m[13]*m[10] + m[5]*m[8]*m[14] - m[5]*m[12]*m[10] - m[6]*m[8]*m[13] + m[6]*m[12]*m[9];
r[13] = m[0]*m[9]*m[14] - m[0]*m[13]*m[10] - m[1]*m[8]*m[14] + m[1]*m[12]*m[10] + m[2]*m[8]*m[13] - m[2]*m[12]*m[9];
r[14] = -m[0]*m[5]*m[14] + m[0]*m[13]*m[6] + m[1]*m[4]*m[14] - m[1]*m[12]*m[6] - m[2]*m[4]*m[13] + m[2]*m[12]*m[5];
r[15] = m[0]*m[5]*m[10] - m[0]*m[9]*m[6] - m[1]*m[4]*m[10] + m[1]*m[8]*m[6] + m[2]*m[4]*m[9] - m[2]*m[8]*m[5];
var det = m[0]*r[0] + m[1]*r[4] + m[2]*r[8] + m[3]*r[12];
for (var i = 0; i < 16; i++) r[i] /= det;
return result;
};
// ### GL.Matrix.transpose(matrix[, result])
//
// Returns `matrix`, exchanging columns for rows. You can optionally pass an
// existing matrix in `result` to avoid allocating a new matrix.
Matrix.transpose = function(matrix, result) {
result = result || new Matrix();
var m = matrix.m, r = result.m;
r[0] = m[0]; r[1] = m[4]; r[2] = m[8]; r[3] = m[12];
r[4] = m[1]; r[5] = m[5]; r[6] = m[9]; r[7] = m[13];
r[8] = m[2]; r[9] = m[6]; r[10] = m[10]; r[11] = m[14];
r[12] = m[3]; r[13] = m[7]; r[14] = m[11]; r[15] = m[15];
return result;
};
// ### GL.Matrix.multiply(left, right[, result])
//
// Returns the concatenation of the transforms for `left` and `right`. You can
// optionally pass an existing matrix in `result` to avoid allocating a new
// matrix. This emulates the OpenGL function `glMultMatrix()`.
Matrix.multiply = function(left, right, result) {
result = result || new Matrix();
var a = left.m, b = right.m, r = result.m;
r[0] = a[0] * b[0] + a[1] * b[4] + a[2] * b[8] + a[3] * b[12];
r[1] = a[0] * b[1] + a[1] * b[5] + a[2] * b[9] + a[3] * b[13];
r[2] = a[0] * b[2] + a[1] * b[6] + a[2] * b[10] + a[3] * b[14];
r[3] = a[0] * b[3] + a[1] * b[7] + a[2] * b[11] + a[3] * b[15];
r[4] = a[4] * b[0] + a[5] * b[4] + a[6] * b[8] + a[7] * b[12];
r[5] = a[4] * b[1] + a[5] * b[5] + a[6] * b[9] + a[7] * b[13];
r[6] = a[4] * b[2] + a[5] * b[6] + a[6] * b[10] + a[7] * b[14];
r[7] = a[4] * b[3] + a[5] * b[7] + a[6] * b[11] + a[7] * b[15];
r[8] = a[8] * b[0] + a[9] * b[4] + a[10] * b[8] + a[11] * b[12];
r[9] = a[8] * b[1] + a[9] * b[5] + a[10] * b[9] + a[11] * b[13];
r[10] = a[8] * b[2] + a[9] * b[6] + a[10] * b[10] + a[11] * b[14];
r[11] = a[8] * b[3] + a[9] * b[7] + a[10] * b[11] + a[11] * b[15];
r[12] = a[12] * b[0] + a[13] * b[4] + a[14] * b[8] + a[15] * b[12];
r[13] = a[12] * b[1] + a[13] * b[5] + a[14] * b[9] + a[15] * b[13];
r[14] = a[12] * b[2] + a[13] * b[6] + a[14] * b[10] + a[15] * b[14];
r[15] = a[12] * b[3] + a[13] * b[7] + a[14] * b[11] + a[15] * b[15];
return result;
};
// ### GL.Matrix.identity([result])
//
// Returns an identity matrix. You can optionally pass an existing matrix in
// `result` to avoid allocating a new matrix. This emulates the OpenGL function
// `glLoadIdentity()`.
Matrix.identity = function(result) {
result = result || new Matrix();
var m = result.m;
m[0] = m[5] = m[10] = m[15] = 1;
m[1] = m[2] = m[3] = m[4] = m[6] = m[7] = m[8] = m[9] = m[11] = m[12] = m[13] = m[14] = 0;
return result;
};
// ### GL.Matrix.perspective(fov, aspect, near, far[, result])
//
// Returns a perspective transform matrix, which makes far away objects appear
// smaller than nearby objects. The `aspect` argument should be the width
// divided by the height of your viewport and `fov` is the top-to-bottom angle
// of the field of view in degrees. You can optionally pass an existing matrix
// in `result` to avoid allocating a new matrix. This emulates the OpenGL
// function `gluPerspective()`.
Matrix.perspective = function(fov, aspect, near, far, result) {
var y = Math.tan(fov * Math.PI / 360) * near;
var x = y * aspect;
return Matrix.frustum(-x, x, -y, y, near, far, result);
};
// ### GL.Matrix.frustum(left, right, bottom, top, near, far[, result])
//
// Sets up a viewing frustum, which is shaped like a truncated pyramid with the
// camera where the point of the pyramid would be. You can optionally pass an
// existing matrix in `result` to avoid allocating a new matrix. This emulates
// the OpenGL function `glFrustum()`.
Matrix.frustum = function(l, r, b, t, n, f, result) {
result = result || new Matrix();
var m = result.m;
m[0] = 2 * n / (r - l);
m[1] = 0;
m[2] = (r + l) / (r - l);
m[3] = 0;
m[4] = 0;
m[5] = 2 * n / (t - b);
m[6] = (t + b) / (t - b);
m[7] = 0;
m[8] = 0;
m[9] = 0;
m[10] = -(f + n) / (f - n);
m[11] = -2 * f * n / (f - n);
m[12] = 0;
m[13] = 0;
m[14] = -1;
m[15] = 0;
return result;
};
// ### GL.Matrix.ortho(left, right, bottom, top, near, far[, result])
//
// Returns an orthographic projection, in which objects are the same size no
// matter how far away or nearby they are. You can optionally pass an existing
// matrix in `result` to avoid allocating a new matrix. This emulates the OpenGL
// function `glOrtho()`.
Matrix.ortho = function(l, r, b, t, n, f, result) {
result = result || new Matrix();
var m = result.m;
m[0] = 2 / (r - l);
m[1] = 0;
m[2] = 0;
m[3] = -(r + l) / (r - l);
m[4] = 0;
m[5] = 2 / (t - b);
m[6] = 0;
m[7] = -(t + b) / (t - b);
m[8] = 0;
m[9] = 0;
m[10] = -2 / (f - n);
m[11] = -(f + n) / (f - n);
m[12] = 0;
m[13] = 0;
m[14] = 0;
m[15] = 1;
return result;
};
// ### GL.Matrix.scale(x, y, z[, result])
//
// This emulates the OpenGL function `glScale()`. You can optionally pass an
// existing matrix in `result` to avoid allocating a new matrix.
Matrix.scale = function(x, y, z, result) {
result = result || new Matrix();
var m = result.m;
m[0] = x;
m[1] = 0;
m[2] = 0;
m[3] = 0;
m[4] = 0;
m[5] = y;
m[6] = 0;
m[7] = 0;
m[8] = 0;
m[9] = 0;
m[10] = z;
m[11] = 0;
m[12] = 0;
m[13] = 0;
m[14] = 0;
m[15] = 1;
return result;
};
// ### GL.Matrix.translate(x, y, z[, result])
//
// This emulates the OpenGL function `glTranslate()`. You can optionally pass
// an existing matrix in `result` to avoid allocating a new matrix.
Matrix.translate = function(x, y, z, result) {
result = result || new Matrix();
var m = result.m;
m[0] = 1;
m[1] = 0;
m[2] = 0;
m[3] = x;
m[4] = 0;
m[5] = 1;
m[6] = 0;
m[7] = y;
m[8] = 0;
m[9] = 0;
m[10] = 1;
m[11] = z;
m[12] = 0;
m[13] = 0;
m[14] = 0;
m[15] = 1;
return result;
};
// ### GL.Matrix.rotate(a, x, y, z[, result])
//
// Returns a matrix that rotates by `a` degrees around the vector `x, y, z`.
// You can optionally pass an existing matrix in `result` to avoid allocating
// a new matrix. This emulates the OpenGL function `glRotate()`.
Matrix.rotate = function(a, x, y, z, result) {
if (!a || (!x && !y && !z)) {
return Matrix.identity(result);
}
result = result || new Matrix();
var m = result.m;
var d = Math.sqrt(x*x + y*y + z*z);
a *= Math.PI / 180; x /= d; y /= d; z /= d;
var c = Math.cos(a), s = Math.sin(a), t = 1 - c;
m[0] = x * x * t + c;
m[1] = x * y * t - z * s;
m[2] = x * z * t + y * s;
m[3] = 0;
m[4] = y * x * t + z * s;
m[5] = y * y * t + c;
m[6] = y * z * t - x * s;
m[7] = 0;
m[8] = z * x * t - y * s;
m[9] = z * y * t + x * s;
m[10] = z * z * t + c;
m[11] = 0;
m[12] = 0;
m[13] = 0;
m[14] = 0;
m[15] = 1;
return result;
};
// ### GL.Matrix.lookAt(ex, ey, ez, cx, cy, cz, ux, uy, uz[, result])
//
// Returns a matrix that puts the camera at the eye point `ex, ey, ez` looking
// toward the center point `cx, cy, cz` with an up direction of `ux, uy, uz`.
// You can optionally pass an existing matrix in `result` to avoid allocating
// a new matrix. This emulates the OpenGL function `gluLookAt()`.
Matrix.lookAt = function(ex, ey, ez, cx, cy, cz, ux, uy, uz, result) {
result = result || new Matrix();
var m = result.m;
var e = new Vector(ex, ey, ez);
var c = new Vector(cx, cy, cz);
var u = new Vector(ux, uy, uz);
var f = e.subtract(c).unit();
var s = u.cross(f).unit();
var t = f.cross(s).unit();
m[0] = s.x;
m[1] = s.y;
m[2] = s.z;
m[3] = -s.dot(e);
m[4] = t.x;
m[5] = t.y;
m[6] = t.z;
m[7] = -t.dot(e);
m[8] = f.x;
m[9] = f.y;
m[10] = f.z;
m[11] = -f.dot(e);
m[12] = 0;
m[13] = 0;
m[14] = 0;
m[15] = 1;
return result;
};
// src/mesh.js
// Represents indexed triangle geometry with arbitrary additional attributes.
// You need a shader to draw a mesh; meshes can't draw themselves.
//
// A mesh is a collection of `GL.Buffer` objects which are either vertex buffers
// (holding per-vertex attributes) or index buffers (holding the order in which
// vertices are rendered). By default, a mesh has a position vertex buffer called
// `vertices` and a triangle index buffer called `triangles`. New buffers can be
// added using `addVertexBuffer()` and `addIndexBuffer()`. Two strings are
// required when adding a new vertex buffer, the name of the data array on the
// mesh instance and the name of the GLSL attribute in the vertex shader.
//
// Example usage:
//
// var mesh = new GL.Mesh({ coords: true, lines: true });
//
// // Default attribute "vertices", available as "gl_Vertex" in
// // the vertex shader
// mesh.vertices = [[0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0]];
//
// // Optional attribute "coords" enabled in constructor,
// // available as "gl_TexCoord" in the vertex shader
// mesh.coords = [[0, 0], [1, 0], [0, 1], [1, 1]];
//
// // Custom attribute "weights", available as "weight" in the
// // vertex shader
// mesh.addVertexBuffer('weights', 'weight');
// mesh.weights = [1, 0, 0, 1];
//
// // Default index buffer "triangles"
// mesh.triangles = [[0, 1, 2], [2, 1, 3]];
//
// // Optional index buffer "lines" enabled in constructor
// mesh.lines = [[0, 1], [0, 2], [1, 3], [2, 3]];
//
// // Upload provided data to GPU memory
// mesh.compile();
// ### new GL.Indexer()
//
// Generates indices into a list of unique objects from a stream of objects
// that may contain duplicates. This is useful for generating compact indexed
// meshes from unindexed data.
function Indexer() {
this.unique = [];
this.indices = [];
this.map = {};
}
Indexer.prototype = {
// ### .add(v)
//
// Adds the object `obj` to `unique` if it hasn't already been added. Returns
// the index of `obj` in `unique`.
add: function(obj) {
var key = JSON.stringify(obj);
if (!(key in this.map)) {
this.map[key] = this.unique.length;
this.unique.push(obj);
}
return this.map[key];
}
};
// ### new GL.Buffer(target, type)
//
// Provides a simple method of uploading data to a GPU buffer. Example usage:
//
// var vertices = new GL.Buffer(gl.ARRAY_BUFFER, Float32Array);
// var indices = new GL.Buffer(gl.ELEMENT_ARRAY_BUFFER, Uint16Array);
// vertices.data = [[0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0]];
// indices.data = [[0, 1, 2], [2, 1, 3]];
// vertices.compile();
// indices.compile();
//
function Buffer(target, type) {
this.buffer = null;
this.target = target;
this.type = type;
this.data = [];
}
Buffer.prototype = {
// ### .compile(type)
//
// Upload the contents of `data` to the GPU in preparation for rendering. The
// data must be a list of lists where each inner list has the same length. For
// example, each element of data for vertex normals would be a list of length three.
// This will remember the data length and element length for later use by shaders.
// The type can be either `gl.STATIC_DRAW` or `gl.DYNAMIC_DRAW`, and defaults to
// `gl.STATIC_DRAW`.
//
// This could have used `[].concat.apply([], this.data)` to flatten
// the array but Google Chrome has a maximum number of arguments so the
// concatenations are chunked to avoid that limit.
compile: function(type) {
var data = [];
for (var i = 0, chunk = 10000; i < this.data.length; i += chunk) {
data = Array.prototype.concat.apply(data, this.data.slice(i, i + chunk));
}
var spacing = this.data.length ? data.length / this.data.length : 0;
if (spacing != Math.round(spacing)) throw new Error('buffer elements not of consistent size, average size is ' + spacing);
this.buffer = this.buffer || gl.createBuffer();
this.buffer.length = data.length;
this.buffer.spacing = spacing;
gl.bindBuffer(this.target, this.buffer);
gl.bufferData(this.target, new this.type(data), type || gl.STATIC_DRAW);
}
};
// ### new GL.Mesh([options])
//
// Represents a collection of vertex buffers and index buffers. Each vertex
// buffer maps to one attribute in GLSL and has a corresponding property set
// on the Mesh instance. There is one vertex buffer by default: `vertices`,
// which maps to `gl_Vertex`. The `coords`, `normals`, and `colors` vertex
// buffers map to `gl_TexCoord`, `gl_Normal`, and `gl_Color` respectively,
// and can be enabled by setting the corresponding options to true. There are
// two index buffers, `triangles` and `lines`, which are used for rendering
// `gl.TRIANGLES` and `gl.LINES`, respectively. Only `triangles` is enabled by
// default, although `computeWireframe()` will add a normal buffer if it wasn't
// initially enabled.
function Mesh(options) {
options = options || {};
this.vertexBuffers = {};
this.indexBuffers = {};
this.addVertexBuffer('vertices', 'gl_Vertex');
if (options.coords) this.addVertexBuffer('coords', 'gl_TexCoord');
if (options.normals) this.addVertexBuffer('normals', 'gl_Normal');
if (options.colors) this.addVertexBuffer('colors', 'gl_Color');
if (!('triangles' in options) || options.triangles) this.addIndexBuffer('triangles');
if (options.lines) this.addIndexBuffer('lines');
}
Mesh.prototype = {
// ### .addVertexBuffer(name, attribute)
//
// Add a new vertex buffer with a list as a property called `name` on this object
// and map it to the attribute called `attribute` in all shaders that draw this mesh.
addVertexBuffer: function(name, attribute) {
var buffer = this.vertexBuffers[attribute] = new Buffer(gl.ARRAY_BUFFER, Float32Array);
buffer.name = name;
this[name] = [];
},