forked from jscad/OpenJSCAD.org
-
Notifications
You must be signed in to change notification settings - Fork 1
/
lightgl.js
2256 lines (2046 loc) · 69.7 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/texture.js
// Provides a simple wrapper around WebGL textures that supports render-to-texture.
// ### new GL.Texture(width, height[, options])
//
// The arguments `width` and `height` give the size of the texture in texels.
// WebGL texture dimensions must be powers of two unless `filter` is set to
// either `gl.NEAREST` or `gl.LINEAR` and `wrap` is set to `gl.CLAMP_TO_EDGE`
// (which they are by default).
//
// Texture parameters can be passed in via the `options` argument.
// Example usage:
//
// var t = new GL.Texture(256, 256, {
// // Defaults to gl.LINEAR, set both at once with "filter"
// magFilter: gl.NEAREST,
// minFilter: gl.LINEAR,
//
// // Defaults to gl.CLAMP_TO_EDGE, set both at once with "wrap"
// wrapS: gl.REPEAT,
// wrapT: gl.REPEAT,
//
// format: gl.RGB, // Defaults to gl.RGBA
// type: gl.FLOAT // Defaults to gl.UNSIGNED_BYTE
// });
function Texture(width, height, options) {
options = options || {};
this.id = gl.createTexture();
this.width = width;
this.height = height;
this.format = options.format || gl.RGBA;
this.type = options.type || gl.UNSIGNED_BYTE;
gl.bindTexture(gl.TEXTURE_2D, this.id);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, options.filter || options.magFilter || gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, options.filter || options.minFilter || gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, options.wrap || options.wrapS || gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, options.wrap || options.wrapT || gl.CLAMP_TO_EDGE);
gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, null);
}
var framebuffer;
var renderbuffer;
var checkerboardCanvas;
Texture.prototype = {
// ### .bind([unit])
//
// Bind this texture to the given texture unit (0-7, defaults to 0).
bind: function(unit) {
gl.activeTexture(gl.TEXTURE0 + (unit || 0));
gl.bindTexture(gl.TEXTURE_2D, this.id);
},
// ### .unbind([unit])
//
// Clear the given texture unit (0-7, defaults to 0).
unbind: function(unit) {
gl.activeTexture(gl.TEXTURE0 + (unit || 0));
gl.bindTexture(gl.TEXTURE_2D, null);
},
// ### .drawTo(callback[, options])
//
// Render all draw calls in `callback` to this texture. This method
// sets up a framebuffer with this texture as the color attachment
// and a renderbuffer as the depth attachment. The viewport is
// temporarily changed to the size of the texture.
//
// The depth buffer can be omitted via `options` as shown in the
// example below:
//
// texture.drawTo(function() {
// gl.clearColor(1, 0, 0, 1);
// gl.clear(gl.COLOR_BUFFER_BIT);
// }, { depth: false });
drawTo: function(callback, options) {
options = options || {};
var v = gl.getParameter(gl.VIEWPORT);
gl.viewport(0, 0, this.width, this.height);
framebuffer = framebuffer || gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.id, 0);
if(options.depth !== false) {
renderbuffer = renderbuffer || gl.createRenderbuffer();
gl.bindRenderbuffer(gl.RENDERBUFFER, renderbuffer);
if(this.width != renderbuffer.width || this.height != renderbuffer.height) {
renderbuffer.width = this.width;
renderbuffer.height = this.height;
gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, this.width, this.height);
}
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer);
}
callback();
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
gl.bindRenderbuffer(gl.RENDERBUFFER, null);
gl.viewport(v[0], v[1], v[2], v[3]);
},
// ### .swapWith(other)
//
// Switch this texture with `other`, useful for the ping-pong rendering
// technique used in multi-stage rendering.
swapWith: function(other) {
var temp;
temp = other.id;
other.id = this.id;
this.id = temp;
temp = other.width;
other.width = this.width;
this.width = temp;
temp = other.height;
other.height = this.height;
this.height = temp;
}
};
// ### GL.Texture.fromImage(image[, options])
//
// Return a new image created from `image`, an `<img>` tag.
Texture.fromImage = function(image, options) {
options = options || {};
var texture = new Texture(image.width, image.height, options);
try {
gl.texImage2D(gl.TEXTURE_2D, 0, texture.format, texture.format, texture.type, image);
} catch(e) {
if(window.location.protocol == 'file:') {
throw 'image not loaded for security reasons (serve this page over "http://" instead)';
} else {
throw 'image not loaded for security reasons (image must originate from the same ' +
'domain as this page or use Cross-Origin Resource Sharing)';
}
}
if(options.minFilter && options.minFilter != gl.NEAREST && options.minFilter != gl.LINEAR) {
gl.generateMipmap(gl.TEXTURE_2D);
}
return texture;
};
// ### GL.Texture.fromURL(url[, options])
//
// Returns a checkerboard texture that will switch to the correct texture when
// it loads.
Texture.fromURL = function(url, options) {
checkerboardCanvas = checkerboardCanvas || (function() {
var c = document.createElement('canvas').getContext('2d');
c.canvas.width = c.canvas.height = 128;
for(var y = 0; y < c.canvas.height; y += 16) {
for(var x = 0; x < c.canvas.width; x += 16) {
c.fillStyle = (x ^ y) & 16 ? '#FFF' : '#DDD';
c.fillRect(x, y, 16, 16);
}
}
return c.canvas;
})();
var texture = Texture.fromImage(checkerboardCanvas, options);
var image = new Image();
var context = gl;
image.onload = function() {
context.makeCurrent();
Texture.fromImage(image, options).swapWith(texture);
};
image.src = url;
return texture;
};
// 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 '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] = [];
},
// ### .addIndexBuffer(name)
//
// Add a new index buffer with a list as a property called `name` on this object.
addIndexBuffer: function(name) {
this.indexBuffers[name] = new Buffer(gl.ELEMENT_ARRAY_BUFFER, Uint16Array);
this[name] = [];
},
// ### .compile()
//
// Upload all attached buffers to the GPU in preparation for rendering. This
// doesn't need to be called every frame, only needs to be done when the data
// changes.
compile: function() {
for(var attribute in this.vertexBuffers) {
var buffer = this.vertexBuffers[attribute];
buffer.data = this[buffer.name];
buffer.compile();
}
for(var name in this.indexBuffers) {
var buffer = this.indexBuffers[name];
buffer.data = this[name];
buffer.compile();
}
},
// ### .transform(matrix)
//
// Transform all vertices by `matrix` and all normals by the inverse transpose
// of `matrix`.
transform: function(matrix) {
this.vertices = this.vertices.map(function(v) {
return matrix.transformPoint(Vector.fromArray(v)).toArray();
});
if(this.normals) {
var invTrans = matrix.inverse().transpose();
this.normals = this.normals.map(function(n) {
return invTrans.transformVector(Vector.fromArray(n)).unit().toArray();
});
}
this.compile();
return this;
},
// ### .computeNormals()
//
// Computes a new normal for each vertex from the average normal of the
// neighboring triangles. This means adjacent triangles must share vertices
// for the resulting normals to be smooth.
computeNormals: function() {
if(!this.normals) this.addVertexBuffer('normals', 'gl_Normal');
for(var i = 0; i < this.vertices.length; i++) {
this.normals[i] = new Vector();
}
for(var i = 0; i < this.triangles.length; i++) {
var t = this.triangles[i];
var a = Vector.fromArray(this.vertices[t[0]]);
var b = Vector.fromArray(this.vertices[t[1]]);
var c = Vector.fromArray(this.vertices[t[2]]);
var normal = b.subtract(a).cross(c.subtract(a)).unit();
this.normals[t[0]] = this.normals[t[0]].add(normal);
this.normals[t[1]] = this.normals[t[1]].add(normal);
this.normals[t[2]] = this.normals[t[2]].add(normal);
}
for(var i = 0; i < this.vertices.length; i++) {
this.normals[i] = this.normals[i].unit().toArray();
}
this.compile();
return this;
},
// ### .computeWireframe()
//
// Populate the `lines` index buffer from the `triangles` index buffer.
computeWireframe: function() {
var indexer = new Indexer();
for(var i = 0; i < this.triangles.length; i++) {
var t = this.triangles[i];
for(var j = 0; j < t.length; j++) {
var a = t[j],
b = t[(j + 1) % t.length];
indexer.add([Math.min(a, b), Math.max(a, b)]);
}
}
if(!this.lines) this.addIndexBuffer('lines');
this.lines = indexer.unique;
this.compile();
return this;
},
// ### .getAABB()
//
// Computes the axis-aligned bounding box, which is an object whose `min` and
// `max` properties contain the minimum and maximum coordinates of all vertices.
getAABB: function() {
var aabb = {
min: new Vector(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE)
};
aabb.max = aabb.min.negative();
for(var i = 0; i < this.vertices.length; i++) {
var v = Vector.fromArray(this.vertices[i]);
aabb.min = Vector.min(aabb.min, v);
aabb.max = Vector.max(aabb.max, v);
}
return aabb;
},
// ### .getBoundingSphere()
//
// Computes a sphere that contains all vertices (not necessarily the smallest
// sphere). The returned object has two properties, `center` and `radius`.
getBoundingSphere: function() {
var aabb = this.getAABB();
var sphere = {
center: aabb.min.add(aabb.max).divide(2),
radius: 0
};
for(var i = 0; i < this.vertices.length; i++) {
sphere.radius = Math.max(sphere.radius, Vector.fromArray(this.vertices[i]).subtract(sphere.center).length());
}
return sphere;
}
};
// ### GL.Mesh.plane([options])
//
// Generates a square 2x2 mesh the xy plane centered at the origin. The
// `options` argument specifies options to pass to the mesh constructor.
// Additional options include `detailX` and `detailY`, which set the tesselation
// in x and y, and `detail`, which sets both `detailX` and `detailY` at once.
// Two triangles are generated by default.
// Example usage:
//
// var mesh1 = GL.Mesh.plane();
// var mesh2 = GL.Mesh.plane({ detail: 5 });
// var mesh3 = GL.Mesh.plane({ detailX: 20, detailY: 40 });
//
Mesh.plane = function(options) {
options = options || {};
var mesh = new Mesh(options),
detailX = options.detailX || options.detail || 1,
detailY = options.detailY || options.detail || 1;
for(var y = 0; y <= detailY; y++) {
var t = y / detailY;
for(var x = 0; x <= detailX; x++) {
var s = x / detailX;
mesh.vertices.push([2 * s - 1, 2 * t - 1, 0]);
if(mesh.coords) mesh.coords.push([s, t]);
if(mesh.normals) mesh.normals.push([0, 0, 1]);
if(x < detailX && y < detailY) {
var i = x + y * (detailX + 1);
mesh.triangles.push([i, i + 1, i + detailX + 1]);
mesh.triangles.push([i + detailX + 1, i + 1, i + detailX + 2]);
}
}
}
mesh.compile();
return mesh;
};
var cubeData = [
[0, 4, 2, 6, -1, 0, 0], // -x
[1, 3, 5, 7, +1, 0, 0], // +x
[0, 1, 4, 5, 0, -1, 0], // -y
[2, 6, 3, 7, 0, +1, 0], // +y
[0, 2, 1, 3, 0, 0, -1], // -z
[4, 5, 6, 7, 0, 0, +1] // +z
];
function pickOctant(i) {
return new Vector((i & 1) * 2 - 1, (i & 2) - 1, (i & 4) / 2 - 1);
}
// ### GL.Mesh.cube([options])
//
// Generates a 2x2x2 box centered at the origin. The `options` argument
// specifies options to pass to the mesh constructor.
Mesh.cube = function(options) {
var mesh = new Mesh(options);
for(var i = 0; i < cubeData.length; i++) {
var data = cubeData[i],
v = i * 4;
for(var j = 0; j < 4; j++) {
var d = data[j];
mesh.vertices.push(pickOctant(d).toArray());
if(mesh.coords) mesh.coords.push([j & 1, (j & 2) / 2]);
if(mesh.normals) mesh.normals.push(data.slice(4, 7));
}
mesh.triangles.push([v, v + 1, v + 2]);
mesh.triangles.push([v + 2, v + 1, v + 3]);
}
mesh.compile();
return mesh;
};
// ### GL.Mesh.sphere([options])
//
// Generates a geodesic sphere of radius 1. The `options` argument specifies
// options to pass to the mesh constructor in addition to the `detail` option,
// which controls the tesselation level. The detail is `6` by default.
// Example usage:
//
// var mesh1 = GL.Mesh.sphere();
// var mesh2 = GL.Mesh.sphere({ detail: 2 });
//
Mesh.sphere = function(options) {
function tri(a, b, c) {
return flip ? [a, c, b] : [a, b, c];
}
function fix(x) {
return x + (x - x * x) / 2;
}
options = options || {};
var mesh = new Mesh(options);
var indexer = new Indexer(),
detail = options.detail || 6;
for(var octant = 0; octant < 8; octant++) {
var scale = pickOctant(octant);
var flip = scale.x * scale.y * scale.z > 0;
var data = [];
for(var i = 0; i <= detail; i++) {
// Generate a row of vertices on the surface of the sphere
// using barycentric coordinates.
for(var j = 0; i + j <= detail; j++) {
var a = i / detail;
var b = j / detail;
var c = (detail - i - j) / detail;
var vertex = {
vertex: new Vector(fix(a), fix(b), fix(c)).unit().multiply(scale).toArray()
};
if(mesh.coords) vertex.coord = scale.y > 0 ? [1 - a, c] : [c, 1 - a];
data.push(indexer.add(vertex));
}
// Generate triangles from this row and the previous row.
if(i > 0) {
for(var j = 0; i + j <= detail; j++) {
var a = (i - 1) * (detail + 1) + ((i - 1) - (i - 1) * (i - 1)) / 2 + j;
var b = i * (detail + 1) + (i - i * i) / 2 + j;
mesh.triangles.push(tri(data[a], data[a + 1], data[b]));
if(i + j < detail) {
mesh.triangles.push(tri(data[b], data[a + 1], data[b + 1]));
}
}
}
}
}
// Reconstruct the geometry from the indexer.
mesh.vertices = indexer.unique.map(function(v) {
return v.vertex;
});
if(mesh.coords) mesh.coords = indexer.unique.map(function(v) {
return v.coord;
});
if(mesh.normals) mesh.normals = mesh.vertices;
mesh.compile();
return mesh;
};
// ### GL.Mesh.load(json[, options])
//
// Creates a mesh from the JSON generated by the `convert/convert.py` script.
// Example usage:
//
// var data = {
// vertices: [[0, 0, 0], [1, 0, 0], [0, 1, 0]],
// triangles: [[0, 1, 2]]
// };
// var mesh = GL.Mesh.load(data);
//
Mesh.load = function(json, options) {
options = options || {};
if(!('coords' in options)) options.coords = !! json.coords;
if(!('normals' in options)) options.normals = !! json.normals;
if(!('colors' in options)) options.colors = !! json.colors;
if(!('triangles' in options)) options.triangles = !! json.triangles;
if(!('lines' in options)) options.lines = !! json.lines;
var mesh = new Mesh(options);
mesh.vertices = json.vertices;
if(mesh.coords) mesh.coords = json.coords;
if(mesh.normals) mesh.normals = json.normals;
if(mesh.colors) mesh.colors = json.colors;
if(mesh.triangles) mesh.triangles = json.triangles;
if(mesh.lines) mesh.lines = json.lines;
mesh.compile();
return mesh;
};
// src/vector.js
// Provides a simple 3D vector class. Vector operations can be done using member
// functions, which return new vectors, or static functions, which reuse
// existing vectors to avoid generating garbage.
function Vector(x, y, z) {
this.x = x || 0;
this.y = y || 0;
this.z = z || 0;
}
// ### Instance Methods
// The methods `add()`, `subtract()`, `multiply()`, and `divide()` can all
// take either a vector or a number as an argument.
Vector.prototype = {
negative: function() {
return new Vector(-this.x, -this.y, -this.z);
},
add: function(v) {
if(v instanceof Vector) return new Vector(this.x + v.x, this.y + v.y, this.z + v.z);
else return new Vector(this.x + v, this.y + v, this.z + v);
},
subtract: function(v) {
if(v instanceof Vector) return new Vector(this.x - v.x, this.y - v.y, this.z - v.z);
else return new Vector(this.x - v, this.y - v, this.z - v);
},
multiply: function(v) {
if(v instanceof Vector) return new Vector(this.x * v.x, this.y * v.y, this.z * v.z);
else return new Vector(this.x * v, this.y * v, this.z * v);
},
divide: function(v) {
if(v instanceof Vector) return new Vector(this.x / v.x, this.y / v.y, this.z / v.z);
else return new Vector(this.x / v, this.y / v, this.z / v);
},
equals: function(v) {
return this.x == v.x && this.y == v.y && this.z == v.z;
},
dot: function(v) {
return this.x * v.x + this.y * v.y + this.z * v.z;
},
cross: function(v) {
return new Vector(
this.y * v.z - this.z * v.y, this.z * v.x - this.x * v.z, this.x * v.y - this.y * v.x);
},
length: function() {
return Math.sqrt(this.dot(this));
},
unit: function() {
return this.divide(this.length());
},
min: function() {
return Math.min(Math.min(this.x, this.y), this.z);
},
max: function() {
return Math.max(Math.max(this.x, this.y), this.z);
},
toAngles: function() {
return {
theta: Math.atan2(this.z, this.x),
phi: Math.asin(this.y / this.length())
};
},
toArray: function(n) {
return [this.x, this.y, this.z].slice(0, n || 3);
},
clone: function() {
return new Vector(this.x, this.y, this.z);
},
init: function(x, y, z) {
this.x = x;
this.y = y;
this.z = z;
return this;
}
};
// ### Static Methods
// `Vector.randomDirection()` returns a vector with a length of 1 and a
// statistically uniform direction. `Vector.lerp()` performs linear
// interpolation between two vectors.
Vector.negative = function(a, b) {
b.x = -a.x;
b.y = -a.y;
b.z = -a.z;
return b;
};
Vector.add = function(a, b, c) {
if(b instanceof Vector) {
c.x = a.x + b.x;
c.y = a.y + b.y;
c.z = a.z + b.z;
} else {
c.x = a.x + b;
c.y = a.y + b;
c.z = a.z + b;
}
return c;
};
Vector.subtract = function(a, b, c) {
if(b instanceof Vector) {
c.x = a.x - b.x;
c.y = a.y - b.y;
c.z = a.z - b.z;
} else {
c.x = a.x - b;
c.y = a.y - b;
c.z = a.z - b;
}
return c;
};
Vector.multiply = function(a, b, c) {
if(b instanceof Vector) {
c.x = a.x * b.x;
c.y = a.y * b.y;
c.z = a.z * b.z;
} else {
c.x = a.x * b;
c.y = a.y * b;
c.z = a.z * b;
}
return c;
};
Vector.divide = function(a, b, c) {
if(b instanceof Vector) {
c.x = a.x / b.x;
c.y = a.y / b.y;
c.z = a.z / b.z;
} else {
c.x = a.x / b;
c.y = a.y / b;
c.z = a.z / b;
}
return c;
};
Vector.cross = function(a, b, c) {
c.x = a.y * b.z - a.z * b.y;
c.y = a.z * b.x - a.x * b.z;
c.z = a.x * b.y - a.y * b.x;
return c;
};
Vector.unit = function(a, b) {
var length = a.length();
b.x = a.x / length;
b.y = a.y / length;
b.z = a.z / length;
return b;
};
Vector.fromAngles = function(theta, phi) {
return new Vector(Math.cos(theta) * Math.cos(phi), Math.sin(phi), Math.sin(theta) * Math.cos(phi));
};
Vector.randomDirection = function() {
return Vector.fromAngles(Math.random() * Math.PI * 2, Math.asin(Math.random() * 2 - 1));
};
Vector.min = function(a, b) {
return new Vector(Math.min(a.x, b.x), Math.min(a.y, b.y), Math.min(a.z, b.z));
};
Vector.max = function(a, b) {
return new Vector(Math.max(a.x, b.x), Math.max(a.y, b.y), Math.max(a.z, b.z));
};
Vector.lerp = function(a, b, fraction) {
return b.subtract(a).multiply(fraction).add(a);
};
Vector.fromArray = function(a) {
return new Vector(a[0], a[1], a[2]);
};
// src/shader.js
// Provides a convenient wrapper for WebGL shaders. A few uniforms and attributes,
// prefixed with `gl_`, are automatically added to all shader sources to make
// simple shaders easier to write.
//
// Example usage:
//
// var shader = new GL.Shader('\
// void main() {\
// gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;\
// }\
// ', '\
// uniform vec4 color;\
// void main() {\
// gl_FragColor = color;\
// }\
// ');
//
// shader.uniforms({
// color: [1, 0, 0, 1]
// }).draw(mesh);
function regexMap(regex, text, callback) {
var result;
while((result = regex.exec(text)) !== null) {
callback(result);
}
}
// Non-standard names beginning with `gl_` must be mangled because they will
// otherwise cause a compiler error.
var LIGHTGL_PREFIX = 'LIGHTGL';
// ### new GL.Shader(vertexSource, fragmentSource)
//
// Compiles a shader program using the provided vertex and fragment shaders.
function Shader(vertexSource, fragmentSource) {
// Allow passing in the id of an HTML script tag with the source
function followScriptTagById(id) {
var element = document.getElementById(id);
return element ? element.text : id;
}
vertexSource = followScriptTagById(vertexSource);
fragmentSource = followScriptTagById(fragmentSource);
// Headers are prepended to the sources to provide some automatic functionality.
var header = '\
uniform mat3 gl_NormalMatrix;\
uniform mat4 gl_ModelViewMatrix;\
uniform mat4 gl_ProjectionMatrix;\
uniform mat4 gl_ModelViewProjectionMatrix;\
uniform mat4 gl_ModelViewMatrixInverse;\
uniform mat4 gl_ProjectionMatrixInverse;\
uniform mat4 gl_ModelViewProjectionMatrixInverse;\
';
var vertexHeader = header + '\
attribute vec4 gl_Vertex;\
attribute vec4 gl_TexCoord;\
attribute vec3 gl_Normal;\
attribute vec4 gl_Color;\
vec4 ftransform() {\
return gl_ModelViewProjectionMatrix * gl_Vertex;\
}\
';
var fragmentHeader = '\
precision highp float;\
' + header;
// Check for the use of built-in matrices that require expensive matrix
// multiplications to compute, and record these in `usedMatrices`.
var source = vertexSource + fragmentSource;
var usedMatrices = {};
regexMap(/\b(gl_[^;]*)\b;/g, header, function(groups) {
var name = groups[1];
if(source.indexOf(name) != -1) {
var capitalLetters = name.replace(/[a-z_]/g, '');
usedMatrices[capitalLetters] = LIGHTGL_PREFIX + name;
}
});
if(source.indexOf('ftransform') != -1) usedMatrices.MVPM = LIGHTGL_PREFIX + 'gl_ModelViewProjectionMatrix';
this.usedMatrices = usedMatrices;
// The `gl_` prefix must be substituted for something else to avoid compile
// errors, since it's a reserved prefix. This prefixes all reserved names with
// `_`. The header is inserted after any extensions, since those must come
// first.
function fix(header, source) {
var replaced = {};
var match = /^((\s*\/\/.*\n|\s*#extension.*\n)+)\^*$/.exec(source);
source = match ? match[1] + header + source.substr(match[1].length) : header + source;
regexMap(/\bgl_\w+\b/g, header, function(result) {
if(!(result in replaced)) {
source = source.replace(new RegExp('\\b' + result + '\\b', 'g'), LIGHTGL_PREFIX + result);
replaced[result] = true;
}
});
return source;
}
vertexSource = fix(vertexHeader, vertexSource);
fragmentSource = fix(fragmentHeader, fragmentSource);
// Compile and link errors are thrown as strings.
function compileSource(type, source) {
var shader = gl.createShader(type);
gl.shaderSource(shader, source);
gl.compileShader(shader);
if(!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
throw 'compile error: ' + gl.getShaderInfoLog(shader);
}
return shader;
}
this.program = gl.createProgram();
gl.attachShader(this.program, compileSource(gl.VERTEX_SHADER, vertexSource));
gl.attachShader(this.program, compileSource(gl.FRAGMENT_SHADER, fragmentSource));
gl.linkProgram(this.program);
if(!gl.getProgramParameter(this.program, gl.LINK_STATUS)) {
throw 'link error: ' + gl.getProgramInfoLog(this.program);
}
this.attributes = {};
this.uniformLocations = {};
// Sampler uniforms need to be uploaded using `gl.uniform1i()` instead of `gl.uniform1f()`.
// To do this automatically, we detect and remember all uniform samplers in the source code.
var isSampler = {};
regexMap(/uniform\s+sampler(1D|2D|3D|Cube)\s+(\w+)\s*;/g, vertexSource + fragmentSource, function(groups) {
isSampler[groups[2]] = 1;
});
this.isSampler = isSampler;
}
function isArray(obj) {
var str = Object.prototype.toString.call(obj);
return str == '[object Array]' || str == '[object Float32Array]';
}
function isNumber(obj) {
var str = Object.prototype.toString.call(obj);
return str == '[object Number]' || str == '[object Boolean]';
}
Shader.prototype = {
// ### .uniforms(uniforms)
//
// Set a uniform for each property of `uniforms`. The correct `gl.uniform*()` method is
// inferred from the value types and from the stored uniform sampler flags.
uniforms: function(uniforms) {
gl.useProgram(this.program);
for(var name in uniforms) {
var location = this.uniformLocations[name] || gl.getUniformLocation(this.program, name);
if(!location) continue;
this.uniformLocations[name] = location;
var value = uniforms[name];
if(value instanceof Vector) {
value = [value.x, value.y, value.z];
} else if(value instanceof Matrix) {
value = value.m;
}
if(isArray(value)) {
switch(value.length) {
case 1:
gl.uniform1fv(location, new Float32Array(value));
break;
case 2:
gl.uniform2fv(location, new Float32Array(value));
break;
case 3:
gl.uniform3fv(location, new Float32Array(value));
break;
case 4:
gl.uniform4fv(location, new Float32Array(value));
break;
// Matrices are automatically transposed, since WebGL uses column-major
// indices instead of row-major indices.
case 9:
gl.uniformMatrix3fv(location, false, new Float32Array([
value[0], value[3], value[6], value[1], value[4],
value[7], value[2], value[5], value[8]]));
break;
case 16:
gl.uniformMatrix4fv(location, false, new Float32Array([
value[0], value[4], value[8], value[12],
value[1], value[5], value[9], value[13],
value[2], value[6], value[10], value[14],
value[3], value[7], value[11], value[15]]));
break;
default:
throw 'don\'t know how to load uniform "' + name + '" of length ' + value.length;
}
} else if(isNumber(value)) {
(this.isSampler[name] ? gl.uniform1i : gl.uniform1f).call(gl, location, value);
} else {
throw 'attempted to set uniform "' + name + '" to invalid value ' + value;
}
}
return this;
},