-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathindex.html
6993 lines (5923 loc) · 191 KB
/
index.html
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
<!DOCTYPE html>
<html>
<body></body>
<script language=javascript>
;(function(e,t,n){function i(n,s){if(!t[n]){if(!e[n]){var o=typeof require=="function"&&require;if(!s&&o)return o(n,!0);if(r)return r(n,!0);throw new Error("Cannot find module '"+n+"'")}var u=t[n]={exports:{}};e[n][0].call(u.exports,function(t){var r=e[n][1][t];return i(r?r:t)},u,u.exports)}return t[n].exports}var r=typeof require=="function"&&require;for(var s=0;s<n.length;s++)i(n[s]);return i})({1:[function(require,module,exports){
"use strict";
var glslify = require("glslify");
var drawTriangle = require("a-big-triangle");
var createShader = require("glslify/adapter.js")("\n#define GLSLIFY 1\n\nattribute vec2 position;\nvarying vec2 uv;\nvoid main() {\n uv = position;\n gl_Position = vec4(position, 0, 1);\n}", "\n#define GLSLIFY 1\n\nprecision mediump float;\nfloat b_x_beckmannDistribution(float x, float roughness) {\n float NdotH = max(x, 0.0);\n float cos2Alpha = NdotH * NdotH;\n float tan2Alpha = (cos2Alpha - 1.0) / cos2Alpha;\n float roughness2 = roughness * roughness;\n float denom = max(3.141592653589793 * roughness2 * cos2Alpha * cos2Alpha, 0.00001);\n return exp(tan2Alpha / roughness2) / denom;\n}\nfloat a_x_cookTorranceSpecular(vec3 lightDirection, vec3 viewDirection, vec3 surfaceNormal, float roughness, float fresnel) {\n float VdotN = max(dot(viewDirection, surfaceNormal), 0.0);\n float LdotN = max(dot(lightDirection, surfaceNormal), 0.0);\n vec3 H = normalize(lightDirection + viewDirection);\n float NdotH = max(dot(surfaceNormal, H), 0.0);\n float VdotH = max(dot(viewDirection, H), 0.000001);\n float LdotH = max(dot(lightDirection, H), 0.000001);\n float G1 = (2.0 * NdotH * VdotN) / VdotH;\n float G2 = (2.0 * NdotH * LdotN) / LdotH;\n float G = min(1.0, min(G1, G2));\n float D = b_x_beckmannDistribution(NdotH, roughness);\n float F = pow(1.0 - VdotN, fresnel);\n return G * F * D / max(3.14159265 * VdotN, 0.000001);\n}\nvarying vec2 uv;\nuniform vec3 lightPosition;\nvoid main() {\n float r = sqrt(dot(uv, uv));\n float theta = atan(uv.y, uv.x);\n float phi = asin(r);\n vec3 normal = vec3(cos(theta) * sin(phi), sin(theta) * sin(phi), -cos(phi));\n vec3 position = vec3(normal.xy, normal.z + 5.0);\n vec3 eyeDir = normalize(-position);\n vec3 lightDir = normalize(lightPosition - position);\n if(r > 1.0 || dot(normal, eyeDir) < 0.0) {\n gl_FragColor = vec4(0.0, 0.0, 1.0, 1.0);\n } else {\n float power = (a_x_cookTorranceSpecular(lightDir, eyeDir, normal, 0.2, 1.0) + 0.25);\n gl_FragColor = vec4(power, power, power, 1.0);\n }\n}", [{"name":"lightPosition","type":"vec3"}], [{"name":"position","type":"vec2"}]);
var canvas = document.createElement("canvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
canvas.style.left = "0px";
canvas.style.top = "0px";
canvas.style.position = "absolute";
document.body.appendChild(canvas);
var gl = canvas.getContext("webgl");
var shader = createShader(gl);
function render() {
shader.bind();
var theta = Date.now() * 0.0005;
var x = Math.cos(theta);
var y = Math.sin(theta);
shader.uniforms.lightPosition = [100 * x, 10, 100 * y];
drawTriangle(gl);
requestAnimationFrame(render);
}
render();
},{"glslify/adapter.js":2,"glslify":3,"a-big-triangle":4}],3:[function(require,module,exports){
module.exports = noop
function noop() {
throw new Error(
'You should bundle your code ' +
'using `glslify` as a transform.'
)
}
},{}],2:[function(require,module,exports){
module.exports = programify
var shader = require('gl-shader-core')
function programify(vertex, fragment, uniforms, attributes) {
return function(gl) {
return shader(gl, vertex, fragment, uniforms, attributes)
}
}
},{"gl-shader-core":5}],4:[function(require,module,exports){
'use strict'
var weakMap = typeof WeakMap === 'undefined' ? require('weakmap') : WeakMap
var createBuffer = require('gl-buffer')
var createVAO = require('gl-vao')
var TriangleCache = new weakMap()
function createABigTriangle(gl) {
var triangleVAO = TriangleCache.get(gl)
if(!triangleVAO) {
var buf = createBuffer(gl, new Float32Array([-1, -1, -1, 4, 4, -1]))
triangleVAO = createVAO(gl, [
{ buffer: buf,
type: gl.FLOAT,
size: 2
}
])
TriangleCache.set(gl, triangleVAO)
}
triangleVAO.bind()
gl.drawArrays(gl.TRIANGLES, 0, 3)
triangleVAO.unbind()
}
module.exports = createABigTriangle
},{"weakmap":6,"gl-buffer":7,"gl-vao":8}],6:[function(require,module,exports){
(function(){/* (The MIT License)
*
* Copyright (c) 2012 Brandon Benvie <http://bbenvie.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the 'Software'), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included with all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
// Original WeakMap implementation by Gozala @ https://gist.github.com/1269991
// Updated and bugfixed by Raynos @ https://gist.github.com/1638059
// Expanded by Benvie @ https://github.com/Benvie/harmony-collections
void function(global, undefined_, undefined){
var getProps = Object.getOwnPropertyNames,
defProp = Object.defineProperty,
toSource = Function.prototype.toString,
create = Object.create,
hasOwn = Object.prototype.hasOwnProperty,
funcName = /^\n?function\s?(\w*)?_?\(/;
function define(object, key, value){
if (typeof key === 'function') {
value = key;
key = nameOf(value).replace(/_$/, '');
}
return defProp(object, key, { configurable: true, writable: true, value: value });
}
function nameOf(func){
return typeof func !== 'function'
? '' : 'name' in func
? func.name : toSource.call(func).match(funcName)[1];
}
// ############
// ### Data ###
// ############
var Data = (function(){
var dataDesc = { value: { writable: true, value: undefined } },
datalock = 'return function(k){if(k===s)return l}',
uids = create(null),
createUID = function(){
var key = Math.random().toString(36).slice(2);
return key in uids ? createUID() : uids[key] = key;
},
globalID = createUID(),
storage = function(obj){
if (hasOwn.call(obj, globalID))
return obj[globalID];
if (!Object.isExtensible(obj))
throw new TypeError("Object must be extensible");
var store = create(null);
defProp(obj, globalID, { value: store });
return store;
};
// common per-object storage area made visible by patching getOwnPropertyNames'
define(Object, function getOwnPropertyNames(obj){
var props = getProps(obj);
if (hasOwn.call(obj, globalID))
props.splice(props.indexOf(globalID), 1);
return props;
});
function Data(){
var puid = createUID(),
secret = {};
this.unlock = function(obj){
var store = storage(obj);
if (hasOwn.call(store, puid))
return store[puid](secret);
var data = create(null, dataDesc);
defProp(store, puid, {
value: new Function('s', 'l', datalock)(secret, data)
});
return data;
}
}
define(Data.prototype, function get(o){ return this.unlock(o).value });
define(Data.prototype, function set(o, v){ this.unlock(o).value = v });
return Data;
}());
var WM = (function(data){
var validate = function(key){
if (key == null || typeof key !== 'object' && typeof key !== 'function')
throw new TypeError("Invalid WeakMap key");
}
var wrap = function(collection, value){
var store = data.unlock(collection);
if (store.value)
throw new TypeError("Object is already a WeakMap");
store.value = value;
}
var unwrap = function(collection){
var storage = data.unlock(collection).value;
if (!storage)
throw new TypeError("WeakMap is not generic");
return storage;
}
var initialize = function(weakmap, iterable){
if (iterable !== null && typeof iterable === 'object' && typeof iterable.forEach === 'function') {
iterable.forEach(function(item, i){
if (item instanceof Array && item.length === 2)
set.call(weakmap, iterable[i][0], iterable[i][1]);
});
}
}
function WeakMap(iterable){
if (this === global || this == null || this === WeakMap.prototype)
return new WeakMap(iterable);
wrap(this, new Data);
initialize(this, iterable);
}
function get(key){
validate(key);
var value = unwrap(this).get(key);
return value === undefined_ ? undefined : value;
}
function set(key, value){
validate(key);
// store a token for explicit undefined so that "has" works correctly
unwrap(this).set(key, value === undefined ? undefined_ : value);
}
function has(key){
validate(key);
return unwrap(this).get(key) !== undefined;
}
function delete_(key){
validate(key);
var data = unwrap(this),
had = data.get(key) !== undefined;
data.set(key, undefined);
return had;
}
function toString(){
unwrap(this);
return '[object WeakMap]';
}
try {
var src = ('return '+delete_).replace('e_', '\\u0065'),
del = new Function('unwrap', 'validate', src)(unwrap, validate);
} catch (e) {
var del = delete_;
}
var src = (''+Object).split('Object');
var stringifier = function toString(){
return src[0] + nameOf(this) + src[1];
};
define(stringifier, stringifier);
var prep = { __proto__: [] } instanceof Array
? function(f){ f.__proto__ = stringifier }
: function(f){ define(f, stringifier) };
prep(WeakMap);
[toString, get, set, has, del].forEach(function(method){
define(WeakMap.prototype, method);
prep(method);
});
return WeakMap;
}(new Data));
var defaultCreator = Object.create
? function(){ return Object.create(null) }
: function(){ return {} };
function createStorage(creator){
var weakmap = new WM;
creator || (creator = defaultCreator);
function storage(object, value){
if (value || arguments.length === 2) {
weakmap.set(object, value);
} else {
value = weakmap.get(object);
if (value === undefined) {
value = creator(object);
weakmap.set(object, value);
}
}
return value;
}
return storage;
}
if (typeof module !== 'undefined') {
module.exports = WM;
} else if (typeof exports !== 'undefined') {
exports.WeakMap = WM;
} else if (!('WeakMap' in global)) {
global.WeakMap = WM;
}
WM.createStorage = createStorage;
if (global.WeakMap)
global.WeakMap.createStorage = createStorage;
}((0, eval)('this'));
})()
},{}],5:[function(require,module,exports){
'use strict'
var createUniformWrapper = require('./lib/create-uniforms')
var createAttributeWrapper = require('./lib/create-attributes')
var makeReflect = require('./lib/reflect')
//Shader object
function Shader(gl, prog, vertShader, fragShader) {
this.gl = gl
this.handle = prog
this.attributes = null
this.uniforms = null
this.types = null
this.vertexShader = vertShader
this.fragmentShader = fragShader
}
//Binds the shader
Shader.prototype.bind = function() {
this.gl.useProgram(this.handle)
}
//Destroy shader, release resources
Shader.prototype.dispose = function() {
var gl = this.gl
gl.deleteShader(this.vertexShader)
gl.deleteShader(this.fragmentShader)
gl.deleteProgram(this.handle)
}
Shader.prototype.updateExports = function(uniforms, attributes) {
var locations = new Array(uniforms.length)
var program = this.handle
var gl = this.gl
var doLink = relinkUniforms.bind(void 0,
gl,
program,
locations,
uniforms
)
doLink()
this.types = {
uniforms: makeReflect(uniforms),
attributes: makeReflect(attributes)
}
this.attributes = createAttributeWrapper(
gl,
program,
attributes,
doLink
)
Object.defineProperty(this, 'uniforms', createUniformWrapper(
gl,
program,
uniforms,
locations
))
}
//Relinks all uniforms
function relinkUniforms(gl, program, locations, uniforms) {
for(var i=0; i<uniforms.length; ++i) {
locations[i] = gl.getUniformLocation(program, uniforms[i].name)
}
}
//Compiles and links a shader program with the given attribute and vertex list
function createShader(
gl
, vertSource
, fragSource
, uniforms
, attributes) {
//Compile vertex shader
var vertShader = gl.createShader(gl.VERTEX_SHADER)
gl.shaderSource(vertShader, vertSource)
gl.compileShader(vertShader)
if(!gl.getShaderParameter(vertShader, gl.COMPILE_STATUS)) {
var errLog = gl.getShaderInfoLog(vertShader)
console.error('gl-shader: Error compling vertex shader:', errLog)
throw new Error('gl-shader: Error compiling vertex shader:' + errLog)
}
//Compile fragment shader
var fragShader = gl.createShader(gl.FRAGMENT_SHADER)
gl.shaderSource(fragShader, fragSource)
gl.compileShader(fragShader)
if(!gl.getShaderParameter(fragShader, gl.COMPILE_STATUS)) {
var errLog = gl.getShaderInfoLog(fragShader)
console.error('gl-shader: Error compiling fragment shader:', errLog)
throw new Error('gl-shader: Error compiling fragment shader:' + errLog)
}
//Link program
var program = gl.createProgram()
gl.attachShader(program, fragShader)
gl.attachShader(program, vertShader)
//Optional default attriubte locations
attributes.forEach(function(a) {
if (typeof a.location === 'number')
gl.bindAttribLocation(program, a.location, a.name)
})
gl.linkProgram(program)
if(!gl.getProgramParameter(program, gl.LINK_STATUS)) {
var errLog = gl.getProgramInfoLog(program)
console.error('gl-shader: Error linking shader program:', errLog)
throw new Error('gl-shader: Error linking shader program:' + errLog)
}
//Return final linked shader object
var shader = new Shader(
gl,
program,
vertShader,
fragShader
)
shader.updateExports(uniforms, attributes)
return shader
}
module.exports = createShader
},{"./lib/create-uniforms":9,"./lib/create-attributes":10,"./lib/reflect":11}],10:[function(require,module,exports){
'use strict'
module.exports = createAttributeWrapper
//Shader attribute class
function ShaderAttribute(gl, program, location, dimension, name, constFunc, relink) {
this._gl = gl
this._program = program
this._location = location
this._dimension = dimension
this._name = name
this._constFunc = constFunc
this._relink = relink
}
var proto = ShaderAttribute.prototype
proto.pointer = function setAttribPointer(type, normalized, stride, offset) {
var gl = this._gl
gl.vertexAttribPointer(this._location, this._dimension, type||gl.FLOAT, !!normalized, stride||0, offset||0)
this._gl.enableVertexAttribArray(this._location)
}
Object.defineProperty(proto, 'location', {
get: function() {
return this._location
}
, set: function(v) {
if(v !== this._location) {
this._location = v
this._gl.bindAttribLocation(this._program, v, this._name)
this._gl.linkProgram(this._program)
this._relink()
}
}
})
//Adds a vector attribute to obj
function addVectorAttribute(gl, program, location, dimension, obj, name, doLink) {
var constFuncArgs = [ 'gl', 'v' ]
var varNames = []
for(var i=0; i<dimension; ++i) {
constFuncArgs.push('x'+i)
varNames.push('x'+i)
}
constFuncArgs.push([
'if(x0.length===void 0){return gl.vertexAttrib', dimension, 'f(v,', varNames.join(), ')}else{return gl.vertexAttrib', dimension, 'fv(v,x0)}'
].join(''))
var constFunc = Function.apply(undefined, constFuncArgs)
var attr = new ShaderAttribute(gl, program, location, dimension, name, constFunc, doLink)
Object.defineProperty(obj, name, {
set: function(x) {
gl.disableVertexAttribArray(attr._location)
constFunc(gl, attr._location, x)
return x
}
, get: function() {
return attr
}
, enumerable: true
})
}
//Create shims for attributes
function createAttributeWrapper(gl, program, attributes, doLink) {
var obj = {}
for(var i=0, n=attributes.length; i<n; ++i) {
var a = attributes[i]
var name = a.name
var type = a.type
var location = gl.getAttribLocation(program, name)
switch(type) {
case 'bool':
case 'int':
case 'float':
addVectorAttribute(gl, program, location, 1, obj, name, doLink)
break
default:
if(type.indexOf('vec') >= 0) {
var d = type.charCodeAt(type.length-1) - 48
if(d < 2 || d > 4) {
throw new Error('gl-shader: Invalid data type for attribute ' + name + ': ' + type)
}
addVectorAttribute(gl, program, location, d, obj, name, doLink)
} else {
throw new Error('gl-shader: Unknown data type for attribute ' + name + ': ' + type)
}
break
}
}
return obj
}
},{}],11:[function(require,module,exports){
'use strict'
module.exports = makeReflectTypes
//Construct type info for reflection.
//
// This iterates over the flattened list of uniform type values and smashes them into a JSON object.
//
// The leaves of the resulting object are either indices or type strings representing primitive glslify types
function makeReflectTypes(uniforms, useIndex) {
var obj = {}
for(var i=0; i<uniforms.length; ++i) {
var n = uniforms[i].name
var parts = n.split(".")
var o = obj
for(var j=0; j<parts.length; ++j) {
var x = parts[j].split("[")
if(x.length > 1) {
if(!(x[0] in o)) {
o[x[0]] = []
}
o = o[x[0]]
for(var k=1; k<x.length; ++k) {
var y = parseInt(x[k])
if(k<x.length-1 || j<parts.length-1) {
if(!(y in o)) {
if(k < x.length-1) {
o[y] = []
} else {
o[y] = {}
}
}
o = o[y]
} else {
if(useIndex) {
o[y] = i
} else {
o[y] = uniforms[i].type
}
}
}
} else if(j < parts.length-1) {
if(!(x[0] in o)) {
o[x[0]] = {}
}
o = o[x[0]]
} else {
if(useIndex) {
o[x[0]] = i
} else {
o[x[0]] = uniforms[i].type
}
}
}
}
return obj
}
},{}],7:[function(require,module,exports){
"use strict"
var pool = require("typedarray-pool")
var ops = require("ndarray-ops")
var ndarray = require("ndarray")
var webglew = require("webglew")
var SUPPORTED_TYPES = [
"uint8",
"uint8_clamped",
"uint16",
"uint32",
"int8",
"int16",
"int32",
"float32" ]
function GLBuffer(gl, type, handle, length, usage) {
this.gl = gl
this.type = type
this.handle = handle
this.length = length
this.usage = usage
}
var proto = GLBuffer.prototype
proto.bind = function() {
this.gl.bindBuffer(this.type, this.handle)
}
proto.dispose = function() {
this.gl.deleteBuffer(this.handle)
}
function updateTypeArray(gl, type, len, usage, data, offset) {
var dataLen = data.length * data.BYTES_PER_ELEMENT
if(offset < 0) {
gl.bufferData(type, data, usage)
return dataLen
}
if(dataLen + offset > len) {
throw new Error("gl-buffer: If resizing buffer, must not specify offset")
}
gl.bufferSubData(type, offset, data)
return len
}
function makeScratchTypeArray(array, dtype) {
var res = pool.malloc(array.length, dtype)
var n = array.length
for(var i=0; i<n; ++i) {
res[i] = array[i]
}
return res
}
function isPacked(shape, stride) {
var n = 1
for(var i=stride.length-1; i>=0; --i) {
if(stride[i] !== n) {
return false
}
n *= shape[i]
}
return true
}
proto.update = function(array, offset) {
if(typeof offset !== "number") {
offset = -1
}
this.bind()
if(typeof array === "object" && typeof array.shape !== "undefined") { //ndarray
var dtype = array.dtype
if(SUPPORTED_TYPES.indexOf(dtype) < 0) {
dtype = "float32"
}
if(this.type === this.gl.ELEMENT_ARRAY_BUFFER) {
var wgl = webglew(this.gl)
var ext = wgl.OES_element_index_uint
if(ext && dtype !== "uint16") {
dtype = "uint32"
} else {
dtype = "uint16"
}
}
if(dtype === array.dtype && isPacked(array.shape, array.stride)) {
if(array.offset === 0 && array.data.length === array.shape[0]) {
this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, array.data, offset)
} else {
this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, array.data.subarray(array.offset, array.shape[0]), offset)
}
} else {
var tmp = pool.malloc(array.size, dtype)
var ndt = ndarray(tmp, array.shape)
ops.assign(ndt, array)
if(offset < 0) {
this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, tmp, offset)
} else {
this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, tmp.subarray(0, array.size), offset)
}
pool.free(tmp)
}
} else if(Array.isArray(array)) { //Vanilla array
var t
if(this.type === this.gl.ELEMENT_ARRAY_BUFFER) {
t = makeScratchTypeArray(array, "uint16")
} else {
t = makeScratchTypeArray(array, "float32")
}
if(offset < 0) {
this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, t, offset)
} else {
this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, t.subarray(0, array.length), offset)
}
pool.free(t)
} else if(typeof array === "object" && typeof array.length === "number") { //Typed array
this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, array, offset)
} else if(typeof array === "number" || array === undefined) { //Number/default
if(offset >= 0) {
throw new Error("gl-buffer: Cannot specify offset when resizing buffer")
}
array = array | 0
if(array <= 0) {
array = 1
}
this.gl.bufferData(this.type, array|0, this.usage)
this.length = array
} else { //Error, case should not happen
throw new Error("gl-buffer: Invalid data type")
}
}
function createBuffer(gl, data, type, usage) {
webglew(gl)
type = type || gl.ARRAY_BUFFER
usage = usage || gl.DYNAMIC_DRAW
if(type !== gl.ARRAY_BUFFER && type !== gl.ELEMENT_ARRAY_BUFFER) {
throw new Error("gl-buffer: Invalid type for webgl buffer, must be either gl.ARRAY_BUFFER or gl.ELEMENT_ARRAY_BUFFER")
}
if(usage !== gl.DYNAMIC_DRAW && usage !== gl.STATIC_DRAW && usage !== gl.STREAM_DRAW) {
throw new Error("gl-buffer: Invalid usage for buffer, must be either gl.DYNAMIC_DRAW, gl.STATIC_DRAW or gl.STREAM_DRAW")
}
var handle = gl.createBuffer()
var result = new GLBuffer(gl, type, handle, 0, usage)
result.update(data)
return result
}
module.exports = createBuffer
},{"typedarray-pool":12,"ndarray-ops":13,"ndarray":14,"webglew":15}],8:[function(require,module,exports){
"use strict"
var webglew = require("webglew")
var createVAONative = require("./lib/vao-native.js")
var createVAOEmulated = require("./lib/vao-emulated.js")
function createVAO(gl, attributes, elements, elementsType) {
var ext = webglew(gl).OES_vertex_array_object
var vao
if(ext) {
vao = createVAONative(gl, ext)
} else {
vao = createVAOEmulated(gl)
}
vao.update(attributes, elements, elementsType)
return vao
}
module.exports = createVAO
},{"./lib/vao-native.js":16,"./lib/vao-emulated.js":17,"webglew":18}],16:[function(require,module,exports){
"use strict"
var bindAttribs = require("./do-bind.js")
function VertexAttribute(location, dimension, a, b, c, d) {
this.location = location
this.dimension = dimension
this.a = a
this.b = b
this.c = c
this.d = d
}
VertexAttribute.prototype.bind = function(gl) {
switch(this.dimension) {
case 1:
gl.vertexAttrib1f(this.location, this.a)
break
case 2:
gl.vertexAttrib2f(this.location, this.a, this.b)
break
case 3:
gl.vertexAttrib3f(this.location, this.a, this.b, this.c)
break
case 4:
gl.vertexAttrib4f(this.location, this.a, this.b, this.c, this.d)
break
}
}
function VAONative(gl, ext, handle) {
this.gl = gl
this._ext = ext
this.handle = handle
this._attribs = []
this._useElements = false
this._elementsType = gl.UNSIGNED_SHORT
}
VAONative.prototype.bind = function() {
this._ext.bindVertexArrayOES(this.handle)
for(var i=0; i<this._attribs.length; ++i) {
this._attribs[i].bind(this.gl)
}
}
VAONative.prototype.unbind = function() {
this._ext.bindVertexArrayOES(null)
}
VAONative.prototype.dispose = function() {
this._ext.deleteVertexArrayOES(this.handle)
}
VAONative.prototype.update = function(attributes, elements, elementsType) {
this.bind()
bindAttribs(this.gl, elements, attributes)
this.unbind()
this._attribs.length = 0
if(attributes)
for(var i=0; i<attributes.length; ++i) {
var a = attributes[i]
if(typeof a === "number") {
this._attribs.push(new VertexAttribute(i, 1, a))
} else if(Array.isArray(a)) {
this._attribs.push(new VertexAttribute(i, a.length, a[0], a[1], a[2], a[3]))
}
}
this._useElements = !!elements
this._elementsType = elementsType || this.gl.UNSIGNED_SHORT
}
VAONative.prototype.draw = function(mode, count, offset) {
offset = offset || 0
var gl = this.gl
if(this._useElements) {
gl.drawElements(mode, count, this._elementsType, offset)
} else {
gl.drawArrays(mode, offset, count)
}
}
function createVAONative(gl, ext) {
return new VAONative(gl, ext, ext.createVertexArrayOES())
}
module.exports = createVAONative
},{"./do-bind.js":19}],17:[function(require,module,exports){
"use strict"
var bindAttribs = require("./do-bind.js")
function VAOEmulated(gl) {
this.gl = gl
this._elements = null
this._attributes = null
this._elementsType = gl.UNSIGNED_SHORT
}
VAOEmulated.prototype.bind = function() {
bindAttribs(this.gl, this._elements, this._attributes)
}
VAOEmulated.prototype.update = function(attributes, elements, elementsType) {
this._elements = elements
this._attributes = attributes
this._elementsType = elementsType || this.gl.UNSIGNED_SHORT
}
VAOEmulated.prototype.dispose = function() { }
VAOEmulated.prototype.unbind = function() { }
VAOEmulated.prototype.draw = function(mode, count, offset) {
offset = offset || 0
var gl = this.gl
if(this._elements) {
gl.drawElements(mode, count, this._elementsType, offset)
} else {
gl.drawArrays(mode, offset, count)
}
}
function createVAOEmulated(gl) {
return new VAOEmulated(gl)
}
module.exports = createVAOEmulated
},{"./do-bind.js":19}],19:[function(require,module,exports){
"use strict"
function doBind(gl, elements, attributes) {
if(elements) {
elements.bind()
} else {
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null)
}
var nattribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS)|0
if(attributes) {
if(attributes.length > nattribs) {
throw new Error("gl-vao: Too many vertex attributes")
}
for(var i=0; i<attributes.length; ++i) {
var attrib = attributes[i]
if(attrib.buffer) {
var buffer = attrib.buffer
var size = attrib.size || 4
var type = attrib.type || gl.FLOAT
var normalized = !!attrib.normalized
var stride = attrib.stride || 0
var offset = attrib.offset || 0
buffer.bind()
gl.enableVertexAttribArray(i)
gl.vertexAttribPointer(i, size, type, normalized, stride, offset)
} else {
if(typeof attrib === "number") {
gl.vertexAttrib1f(i, attrib)
} else if(attrib.length === 1) {
gl.vertexAttrib1f(i, attrib[0])
} else if(attrib.length === 2) {
gl.vertexAttrib2f(i, attrib[0], attrib[1])
} else if(attrib.length === 3) {
gl.vertexAttrib3f(i, attrib[0], attrib[1], attrib[2])
} else if(attrib.length === 4) {
gl.vertexAttrib4f(i, attrib[0], attrib[1], attrib[2], attrib[3])
} else {
throw new Error("gl-vao: Invalid vertex attribute")
}
gl.disableVertexAttribArray(i)
}
}
for(; i<nattribs; ++i) {
gl.disableVertexAttribArray(i)
}
} else {
gl.bindBuffer(gl.ARRAY_BUFFER, null)
for(var i=0; i<nattribs; ++i) {
gl.disableVertexAttribArray(i)
}
}
}
module.exports = doBind
},{}],9:[function(require,module,exports){
'use strict'
var dup = require('dup')
var coallesceUniforms = require('./reflect')
module.exports = createUniformWrapper
//Binds a function and returns a value
function identity(x) {
var c = new Function('y', 'return function(){return y}')
return c(x)
}
//Create shims for uniforms
function createUniformWrapper(gl, program, uniforms, locations) {
function makeGetter(index) {
var proc = new Function('gl', 'prog', 'locations',
'return function(){return gl.getUniform(prog,locations[' + index + '])}')
return proc(gl, program, locations)
}
function makePropSetter(path, index, type) {
switch(type) {
case 'bool':
case 'int':
case 'sampler2D':
case 'samplerCube':
return 'gl.uniform1i(locations[' + index + '],obj' + path + ')'
case 'float':
return 'gl.uniform1f(locations[' + index + '],obj' + path + ')'
default:
var vidx = type.indexOf('vec')
if(0 <= vidx && vidx <= 1 && type.length === 4 + vidx) {
var d = type.charCodeAt(type.length-1) - 48
if(d < 2 || d > 4) {
throw new Error('gl-shader: Invalid data type')