-
Notifications
You must be signed in to change notification settings - Fork 6
/
bundle.js
5939 lines (5264 loc) · 167 KB
/
bundle.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
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var canvas = document.body.appendChild(document.createElement('canvas'))
var triangle = require('a-big-triangle')
var context = require('gl-context')
var fit = require('canvas-fit')
var Shader = require('gl-shader')
var start = Date.now()
window.addEventListener('resize', fit(canvas, window, 0.25), false)
Toy(function(gl) {
return Shader(gl
, "#define GLSLIFY 1\n\nprecision mediump float;\n\nattribute vec2 position;\n\nvoid main() {\n gl_Position = vec4(position, 1, 1);\n}\n"
, "#define GLSLIFY 1\n\nprecision mediump float;\n\nuniform vec2 iResolution;\nuniform float iGlobalTime;\n\nfloat smin_2_0(float a, float b, float k) {\n float h = clamp(0.5 + 0.5 * (b - a) / k, 0.0, 1.0);\n return mix(b, a, h) - k * h * (1.0 - h);\n}\n\n\n\nmat3 calcLookAtMatrix_1_1(vec3 origin, vec3 target, float roll) {\n vec3 rr = vec3(sin(roll), cos(roll), 0.0);\n vec3 ww = normalize(target - origin);\n vec3 uu = normalize(cross(ww, rr));\n vec3 vv = normalize(cross(uu, ww));\n\n return mat3(uu, vv, ww);\n}\n\n\n\n\nvoid doCamera(out vec3 camPos, out vec3 camTar, float time, float mouseX) {\n float an = 0.8*iGlobalTime + 10.0*mouseX;\n camPos = vec3(3.5*sin(an),3.0,3.5*cos(an));\n camTar = vec3(0.0,0.0,0.0);\n}\n\nvec3 doBackground() {\n return vec3(0.0, 0.0, 0.0);\n}\n\nfloat doModel(vec3 p) {\n float r = 1.0;\n\n float c1 = length(p) - r;\n float c2 = length(p - vec3(0, 0.5, 2)) - 0.25;\n float gnd = p.y - 0.0;\n\n return min(c2, smin_2_0(c1, gnd, 1.0));\n}\n\nvec3 doMaterial(vec3 pos, vec3 nor) {\n return vec3(0.2,0.07,0.01);\n}\n\nvec3 doLighting(vec3 pos, vec3 nor, vec3 rd, float dis, vec3 mal) {\n vec3 lin = vec3(0.0);\n\n vec3 lig = normalize(vec3(1.0,0.7,0.9));\n float dif = max(dot(nor,lig),0.0);\n\n lin += dif*vec3(4.00,4.00,4.00);\n lin += vec3(0.50,0.50,0.50);\n\n vec3 col = mal*lin;\n\n col *= exp(-0.04*dis*dis);\n\n return col;\n}\n\nfloat calcIntersection(vec3 ro, vec3 rd) {\n const float maxd = 15.0;\n const float precis = 0.01;\n float h = precis*2.0;\n float t = 0.0;\n float res = -1.0;\n for (int i=0; i<30; i++) {\n if (h < precis || t > maxd) break;\n h = doModel(ro+rd*t);\n t += h;\n }\n\n if (t < maxd) res = t;\n return res;\n}\n\nvec3 calcNormal(vec3 pos) {\n const float eps = 0.002;\n\n const vec3 v1 = vec3( 1.0,-1.0,-1.0);\n const vec3 v2 = vec3(-1.0,-1.0, 1.0);\n const vec3 v3 = vec3(-1.0, 1.0,-1.0);\n const vec3 v4 = vec3( 1.0, 1.0, 1.0);\n\n return normalize( v1*doModel( pos + v1*eps ) +\n v2*doModel( pos + v2*eps ) +\n v3*doModel( pos + v3*eps ) +\n v4*doModel( pos + v4*eps ) );\n}\n\nvoid main() {\n vec2 p = (2.0*gl_FragCoord.xy-iResolution.xy)/iResolution.y;\n vec2 m = vec2(0.0)/iResolution.xy;\n\n vec3 ro, ta;\n doCamera(ro, ta, iGlobalTime, m.x);\n\n mat3 camMat = calcLookAtMatrix_1_1(ro, ta, sin(iGlobalTime) * 0.5);\n vec3 rd = normalize(camMat * vec3(p.xy,2.0));\n\n vec3 col = doBackground();\n float t = calcIntersection(ro, rd);\n if (t > -0.5) {\n vec3 pos = ro + t*rd;\n vec3 nor = calcNormal(pos);\n vec3 mal = doMaterial(pos, nor);\n\n col = doLighting(pos, nor, rd, t, mal);\n }\n\n col = pow(clamp(col,0.0,1.0), vec3(0.4545));\n\n gl_FragColor = vec4( col, 1.0 );\n}\n"
)
}, function(gl, shader) {
shader.uniforms.iResolution = [gl.drawingBufferWidth, gl.drawingBufferHeight]
shader.uniforms.iGlobalTime = (Date.now() - start) / 1000
})
// Extracted for gl-toy, need to do manual
// downsampling here :)
function Toy(shader, cb) {
var gl = context(canvas, render)
shader = shader(gl)
function render() {
var width = gl.drawingBufferWidth
var height = gl.drawingBufferHeight
gl.viewport(0, 0, width, height)
shader.bind()
cb(gl, shader)
triangle(gl)
}
}
},{"a-big-triangle":22,"canvas-fit":27,"gl-context":29,"gl-shader":31}],2:[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.unbind = function() {
this.gl.bindBuffer(this.type, null)
}
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
},{"ndarray":8,"ndarray-ops":3,"typedarray-pool":12,"webglew":14}],3:[function(require,module,exports){
"use strict"
var compile = require("cwise-compiler")
var EmptyProc = {
body: "",
args: [],
thisVars: [],
localVars: []
}
function fixup(x) {
if(!x) {
return EmptyProc
}
for(var i=0; i<x.args.length; ++i) {
var a = x.args[i]
if(i === 0) {
x.args[i] = {name: a, lvalue:true, rvalue: !!x.rvalue, count:x.count||1 }
} else {
x.args[i] = {name: a, lvalue:false, rvalue:true, count: 1}
}
}
if(!x.thisVars) {
x.thisVars = []
}
if(!x.localVars) {
x.localVars = []
}
return x
}
function pcompile(user_args) {
return compile({
args: user_args.args,
pre: fixup(user_args.pre),
body: fixup(user_args.body),
post: fixup(user_args.proc),
funcName: user_args.funcName
})
}
function makeOp(user_args) {
var args = []
for(var i=0; i<user_args.args.length; ++i) {
args.push("a"+i)
}
var wrapper = new Function("P", [
"return function ", user_args.funcName, "_ndarrayops(", args.join(","), ") {P(", args.join(","), ");return a0}"
].join(""))
return wrapper(pcompile(user_args))
}
var assign_ops = {
add: "+",
sub: "-",
mul: "*",
div: "/",
mod: "%",
band: "&",
bor: "|",
bxor: "^",
lshift: "<<",
rshift: ">>",
rrshift: ">>>"
}
;(function(){
for(var id in assign_ops) {
var op = assign_ops[id]
exports[id] = makeOp({
args: ["array","array","array"],
body: {args:["a","b","c"],
body: "a=b"+op+"c"},
funcName: id
})
exports[id+"eq"] = makeOp({
args: ["array","array"],
body: {args:["a","b"],
body:"a"+op+"=b"},
rvalue: true,
funcName: id+"eq"
})
exports[id+"s"] = makeOp({
args: ["array", "array", "scalar"],
body: {args:["a","b","s"],
body:"a=b"+op+"s"},
funcName: id+"s"
})
exports[id+"seq"] = makeOp({
args: ["array","scalar"],
body: {args:["a","s"],
body:"a"+op+"=s"},
rvalue: true,
funcName: id+"seq"
})
}
})();
var unary_ops = {
not: "!",
bnot: "~",
neg: "-",
recip: "1.0/"
}
;(function(){
for(var id in unary_ops) {
var op = unary_ops[id]
exports[id] = makeOp({
args: ["array", "array"],
body: {args:["a","b"],
body:"a="+op+"b"},
funcName: id
})
exports[id+"eq"] = makeOp({
args: ["array"],
body: {args:["a"],
body:"a="+op+"a"},
rvalue: true,
count: 2,
funcName: id+"eq"
})
}
})();
var binary_ops = {
and: "&&",
or: "||",
eq: "===",
neq: "!==",
lt: "<",
gt: ">",
leq: "<=",
geq: ">="
}
;(function() {
for(var id in binary_ops) {
var op = binary_ops[id]
exports[id] = makeOp({
args: ["array","array","array"],
body: {args:["a", "b", "c"],
body:"a=b"+op+"c"},
funcName: id
})
exports[id+"s"] = makeOp({
args: ["array","array","scalar"],
body: {args:["a", "b", "s"],
body:"a=b"+op+"s"},
funcName: id+"s"
})
exports[id+"eq"] = makeOp({
args: ["array", "array"],
body: {args:["a", "b"],
body:"a=a"+op+"b"},
rvalue:true,
count:2,
funcName: id+"eq"
})
exports[id+"seq"] = makeOp({
args: ["array", "scalar"],
body: {args:["a","s"],
body:"a=a"+op+"s"},
rvalue:true,
count:2,
funcName: id+"seq"
})
}
})();
var math_unary = [
"abs",
"acos",
"asin",
"atan",
"ceil",
"cos",
"exp",
"floor",
"log",
"round",
"sin",
"sqrt",
"tan"
]
;(function() {
for(var i=0; i<math_unary.length; ++i) {
var f = math_unary[i]
exports[f] = makeOp({
args: ["array", "array"],
pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
body: {args:["a","b"], body:"a=this_f(b)", thisVars:["this_f"]},
funcName: f
})
exports[f+"eq"] = makeOp({
args: ["array"],
pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
body: {args: ["a"], body:"a=this_f(a)", thisVars:["this_f"]},
rvalue: true,
count: 2,
funcName: f+"eq"
})
}
})();
var math_comm = [
"max",
"min",
"atan2",
"pow"
]
;(function(){
for(var i=0; i<math_comm.length; ++i) {
var f= math_comm[i]
exports[f] = makeOp({
args:["array", "array", "array"],
pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
body: {args:["a","b","c"], body:"a=this_f(b,c)", thisVars:["this_f"]},
funcName: f
})
exports[f+"s"] = makeOp({
args:["array", "array", "scalar"],
pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
body: {args:["a","b","c"], body:"a=this_f(b,c)", thisVars:["this_f"]},
funcName: f+"s"
})
exports[f+"eq"] = makeOp({ args:["array", "array"],
pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
body: {args:["a","b"], body:"a=this_f(a,b)", thisVars:["this_f"]},
rvalue: true,
count: 2,
funcName: f+"eq"
})
exports[f+"seq"] = makeOp({ args:["array", "scalar"],
pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
body: {args:["a","b"], body:"a=this_f(a,b)", thisVars:["this_f"]},
rvalue:true,
count:2,
funcName: f+"seq"
})
}
})();
var math_noncomm = [
"atan2",
"pow"
]
;(function(){
for(var i=0; i<math_noncomm.length; ++i) {
var f= math_noncomm[i]
exports[f+"op"] = makeOp({
args:["array", "array", "array"],
pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
body: {args:["a","b","c"], body:"a=this_f(c,b)", thisVars:["this_f"]},
funcName: f+"op"
})
exports[f+"ops"] = makeOp({
args:["array", "array", "scalar"],
pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
body: {args:["a","b","c"], body:"a=this_f(c,b)", thisVars:["this_f"]},
funcName: f+"ops"
})
exports[f+"opeq"] = makeOp({ args:["array", "array"],
pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
body: {args:["a","b"], body:"a=this_f(b,a)", thisVars:["this_f"]},
rvalue: true,
count: 2,
funcName: f+"opeq"
})
exports[f+"opseq"] = makeOp({ args:["array", "scalar"],
pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
body: {args:["a","b"], body:"a=this_f(b,a)", thisVars:["this_f"]},
rvalue:true,
count:2,
funcName: f+"opseq"
})
}
})();
exports.any = compile({
args:["array"],
pre: EmptyProc,
body: {args:[{name:"a", lvalue:false, rvalue:true, count:1}], body: "if(a){return true}", localVars: [], thisVars: []},
post: {args:[], localVars:[], thisVars:[], body:"return false"},
funcName: "any"
})
exports.all = compile({
args:["array"],
pre: EmptyProc,
body: {args:[{name:"x", lvalue:false, rvalue:true, count:1}], body: "if(!x){return false}", localVars: [], thisVars: []},
post: {args:[], localVars:[], thisVars:[], body:"return true"},
funcName: "all"
})
exports.sum = compile({
args:["array"],
pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"},
body: {args:[{name:"a", lvalue:false, rvalue:true, count:1}], body: "this_s+=a", localVars: [], thisVars: ["this_s"]},
post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"},
funcName: "sum"
})
exports.prod = compile({
args:["array"],
pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=1"},
body: {args:[{name:"a", lvalue:false, rvalue:true, count:1}], body: "this_s*=a", localVars: [], thisVars: ["this_s"]},
post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"},
funcName: "prod"
})
exports.norm2squared = compile({
args:["array"],
pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"},
body: {args:[{name:"a", lvalue:false, rvalue:true, count:2}], body: "this_s+=a*a", localVars: [], thisVars: ["this_s"]},
post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"},
funcName: "norm2squared"
})
exports.norm2 = compile({
args:["array"],
pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"},
body: {args:[{name:"a", lvalue:false, rvalue:true, count:2}], body: "this_s+=a*a", localVars: [], thisVars: ["this_s"]},
post: {args:[], localVars:[], thisVars:["this_s"], body:"return Math.sqrt(this_s)"},
funcName: "norm2"
})
exports.norminf = compile({
args:["array"],
pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"},
body: {args:[{name:"a", lvalue:false, rvalue:true, count:4}], body:"if(-a>this_s){this_s=-a}else if(a>this_s){this_s=a}", localVars: [], thisVars: ["this_s"]},
post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"},
funcName: "norminf"
})
exports.norm1 = compile({
args:["array"],
pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"},
body: {args:[{name:"a", lvalue:false, rvalue:true, count:3}], body: "this_s+=a<0?-a:a", localVars: [], thisVars: ["this_s"]},
post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"},
funcName: "norm1"
})
exports.sup = compile({
args: [ "array" ],
pre:
{ body: "this_h=-Infinity",
args: [],
thisVars: [ "this_h" ],
localVars: [] },
body:
{ body: "if(_inline_1_arg0_>this_h)this_h=_inline_1_arg0_",
args: [{"name":"_inline_1_arg0_","lvalue":false,"rvalue":true,"count":2} ],
thisVars: [ "this_h" ],
localVars: [] },
post:
{ body: "return this_h",
args: [],
thisVars: [ "this_h" ],
localVars: [] }
})
exports.inf = compile({
args: [ "array" ],
pre:
{ body: "this_h=Infinity",
args: [],
thisVars: [ "this_h" ],
localVars: [] },
body:
{ body: "if(_inline_1_arg0_<this_h)this_h=_inline_1_arg0_",
args: [{"name":"_inline_1_arg0_","lvalue":false,"rvalue":true,"count":2} ],
thisVars: [ "this_h" ],
localVars: [] },
post:
{ body: "return this_h",
args: [],
thisVars: [ "this_h" ],
localVars: [] }
})
exports.argmin = compile({
args:["index","array","shape"],
pre:{
body:"{this_v=Infinity;this_i=_inline_0_arg2_.slice(0)}",
args:[
{name:"_inline_0_arg0_",lvalue:false,rvalue:false,count:0},
{name:"_inline_0_arg1_",lvalue:false,rvalue:false,count:0},
{name:"_inline_0_arg2_",lvalue:false,rvalue:true,count:1}
],
thisVars:["this_i","this_v"],
localVars:[]},
body:{
body:"{if(_inline_1_arg1_<this_v){this_v=_inline_1_arg1_;for(var _inline_1_k=0;_inline_1_k<_inline_1_arg0_.length;++_inline_1_k){this_i[_inline_1_k]=_inline_1_arg0_[_inline_1_k]}}}",
args:[
{name:"_inline_1_arg0_",lvalue:false,rvalue:true,count:2},
{name:"_inline_1_arg1_",lvalue:false,rvalue:true,count:2}],
thisVars:["this_i","this_v"],
localVars:["_inline_1_k"]},
post:{
body:"{return this_i}",
args:[],
thisVars:["this_i"],
localVars:[]}
})
exports.argmax = compile({
args:["index","array","shape"],
pre:{
body:"{this_v=-Infinity;this_i=_inline_0_arg2_.slice(0)}",
args:[
{name:"_inline_0_arg0_",lvalue:false,rvalue:false,count:0},
{name:"_inline_0_arg1_",lvalue:false,rvalue:false,count:0},
{name:"_inline_0_arg2_",lvalue:false,rvalue:true,count:1}
],
thisVars:["this_i","this_v"],
localVars:[]},
body:{
body:"{if(_inline_1_arg1_>this_v){this_v=_inline_1_arg1_;for(var _inline_1_k=0;_inline_1_k<_inline_1_arg0_.length;++_inline_1_k){this_i[_inline_1_k]=_inline_1_arg0_[_inline_1_k]}}}",
args:[
{name:"_inline_1_arg0_",lvalue:false,rvalue:true,count:2},
{name:"_inline_1_arg1_",lvalue:false,rvalue:true,count:2}],
thisVars:["this_i","this_v"],
localVars:["_inline_1_k"]},
post:{
body:"{return this_i}",
args:[],
thisVars:["this_i"],
localVars:[]}
})
exports.random = makeOp({
args: ["array"],
pre: {args:[], body:"this_f=Math.random", thisVars:["this_f"]},
body: {args: ["a"], body:"a=this_f()", thisVars:["this_f"]},
funcName: "random"
})
exports.assign = makeOp({
args:["array", "array"],
body: {args:["a", "b"], body:"a=b"},
funcName: "assign" })
exports.assigns = makeOp({
args:["array", "scalar"],
body: {args:["a", "b"], body:"a=b"},
funcName: "assigns" })
exports.equals = compile({
args:["array", "array"],
pre: EmptyProc,
body: {args:[{name:"x", lvalue:false, rvalue:true, count:1},
{name:"y", lvalue:false, rvalue:true, count:1}],
body: "if(x!==y){return false}",
localVars: [],
thisVars: []},
post: {args:[], localVars:[], thisVars:[], body:"return true"},
funcName: "equals"
})
},{"cwise-compiler":4}],4:[function(require,module,exports){
"use strict"
var createThunk = require("./lib/thunk.js")
function Procedure() {
this.argTypes = []
this.shimArgs = []
this.arrayArgs = []
this.scalarArgs = []
this.offsetArgs = []
this.offsetArgIndex = []
this.indexArgs = []
this.shapeArgs = []
this.funcName = ""
this.pre = null
this.body = null
this.post = null
this.debug = false
}
function compileCwise(user_args) {
//Create procedure
var proc = new Procedure()
//Parse blocks
proc.pre = user_args.pre
proc.body = user_args.body
proc.post = user_args.post
//Parse arguments
var proc_args = user_args.args.slice(0)
proc.argTypes = proc_args
for(var i=0; i<proc_args.length; ++i) {
var arg_type = proc_args[i]
if(arg_type === "array") {
proc.arrayArgs.push(i)
proc.shimArgs.push("array" + i)
if(i < proc.pre.args.length && proc.pre.args[i].count>0) {
throw new Error("cwise: pre() block may not reference array args")
}
if(i < proc.post.args.length && proc.post.args[i].count>0) {
throw new Error("cwise: post() block may not reference array args")
}
} else if(arg_type === "scalar") {
proc.scalarArgs.push(i)
proc.shimArgs.push("scalar" + i)
} else if(arg_type === "index") {
proc.indexArgs.push(i)
if(i < proc.pre.args.length && proc.pre.args[i].count > 0) {
throw new Error("cwise: pre() block may not reference array index")
}
if(i < proc.body.args.length && proc.body.args[i].lvalue) {
throw new Error("cwise: body() block may not write to array index")
}
if(i < proc.post.args.length && proc.post.args[i].count > 0) {
throw new Error("cwise: post() block may not reference array index")
}
} else if(arg_type === "shape") {
proc.shapeArgs.push(i)
if(i < proc.pre.args.length && proc.pre.args[i].lvalue) {
throw new Error("cwise: pre() block may not write to array shape")
}
if(i < proc.body.args.length && proc.body.args[i].lvalue) {
throw new Error("cwise: body() block may not write to array shape")
}
if(i < proc.post.args.length && proc.post.args[i].lvalue) {
throw new Error("cwise: post() block may not write to array shape")
}
} else if(typeof arg_type === "object" && arg_type.offset) {
proc.argTypes[i] = "offset"
proc.offsetArgs.push({ array: arg_type.array, offset:arg_type.offset })
proc.offsetArgIndex.push(i)
} else {
throw new Error("cwise: Unknown argument type " + proc_args[i])
}
}
//Make sure at least one array argument was specified
if(proc.arrayArgs.length <= 0) {
throw new Error("cwise: No array arguments specified")
}
//Make sure arguments are correct
if(proc.pre.args.length > proc_args.length) {
throw new Error("cwise: Too many arguments in pre() block")
}
if(proc.body.args.length > proc_args.length) {
throw new Error("cwise: Too many arguments in body() block")
}
if(proc.post.args.length > proc_args.length) {
throw new Error("cwise: Too many arguments in post() block")
}
//Check debug flag
proc.debug = !!user_args.printCode || !!user_args.debug
//Retrieve name
proc.funcName = user_args.funcName || "cwise"
//Read in block size
proc.blockSize = user_args.blockSize || 64
return createThunk(proc)
}
module.exports = compileCwise
},{"./lib/thunk.js":6}],5:[function(require,module,exports){
"use strict"
var uniq = require("uniq")
function innerFill(order, proc, body) {
var dimension = order.length
, nargs = proc.arrayArgs.length
, has_index = proc.indexArgs.length>0
, code = []
, vars = []
, idx=0, pidx=0, i, j
for(i=0; i<dimension; ++i) {
vars.push(["i",i,"=0"].join(""))
}
//Compute scan deltas
for(j=0; j<nargs; ++j) {
for(i=0; i<dimension; ++i) {
pidx = idx
idx = order[i]
if(i === 0) {
vars.push(["d",j,"s",i,"=t",j,"p",idx].join(""))
} else {
vars.push(["d",j,"s",i,"=(t",j,"p",idx,"-s",pidx,"*t",j,"p",pidx,")"].join(""))
}
}
}
code.push("var " + vars.join(","))
//Scan loop
for(i=dimension-1; i>=0; --i) {
idx = order[i]
code.push(["for(i",i,"=0;i",i,"<s",idx,";++i",i,"){"].join(""))
}
//Push body of inner loop
code.push(body)
//Advance scan pointers
for(i=0; i<dimension; ++i) {
pidx = idx
idx = order[i]
for(j=0; j<nargs; ++j) {
code.push(["p",j,"+=d",j,"s",i].join(""))
}
if(has_index) {
if(i > 0) {
code.push(["index[",pidx,"]-=s",pidx].join(""))
}
code.push(["++index[",idx,"]"].join(""))
}
code.push("}")
}
return code.join("\n")
}
function outerFill(matched, order, proc, body) {
var dimension = order.length
, nargs = proc.arrayArgs.length
, blockSize = proc.blockSize
, has_index = proc.indexArgs.length > 0
, code = []
for(var i=0; i<nargs; ++i) {
code.push(["var offset",i,"=p",i].join(""))
}
//Generate matched loops
for(var i=matched; i<dimension; ++i) {
code.push(["for(var j"+i+"=SS[", order[i], "]|0;j", i, ">0;){"].join(""))
code.push(["if(j",i,"<",blockSize,"){"].join(""))
code.push(["s",order[i],"=j",i].join(""))
code.push(["j",i,"=0"].join(""))
code.push(["}else{s",order[i],"=",blockSize].join(""))
code.push(["j",i,"-=",blockSize,"}"].join(""))
if(has_index) {
code.push(["index[",order[i],"]=j",i].join(""))
}
}
for(var i=0; i<nargs; ++i) {
var indexStr = ["offset"+i]
for(var j=matched; j<dimension; ++j) {
indexStr.push(["j",j,"*t",i,"p",order[j]].join(""))
}
code.push(["p",i,"=(",indexStr.join("+"),")"].join(""))
}
code.push(innerFill(order, proc, body))
for(var i=matched; i<dimension; ++i) {
code.push("}")
}
return code.join("\n")
}
//Count the number of compatible inner orders
function countMatches(orders) {
var matched = 0, dimension = orders[0].length
while(matched < dimension) {
for(var j=1; j<orders.length; ++j) {
if(orders[j][matched] !== orders[0][matched]) {
return matched
}
}
++matched
}
return matched
}
//Processes a block according to the given data types
function processBlock(block, proc, dtypes) {
var code = block.body
var pre = []
var post = []
for(var i=0; i<block.args.length; ++i) {
var carg = block.args[i]
if(carg.count <= 0) {
continue
}
var re = new RegExp(carg.name, "g")
var ptrStr = ""
var arrNum = proc.arrayArgs.indexOf(i)
switch(proc.argTypes[i]) {
case "offset":
var offArgIndex = proc.offsetArgIndex.indexOf(i)
var offArg = proc.offsetArgs[offArgIndex]
arrNum = offArg.array
ptrStr = "+q" + offArgIndex
case "array":
ptrStr = "p" + arrNum + ptrStr
var localStr = "l" + i
var arrStr = "a" + arrNum
if(carg.count === 1) {
if(dtypes[arrNum] === "generic") {
if(carg.lvalue) {
pre.push(["var ", localStr, "=", arrStr, ".get(", ptrStr, ")"].join(""))
code = code.replace(re, localStr)
post.push([arrStr, ".set(", ptrStr, ",", localStr,")"].join(""))
} else {
code = code.replace(re, [arrStr, ".get(", ptrStr, ")"].join(""))
}
} else {
code = code.replace(re, [arrStr, "[", ptrStr, "]"].join(""))
}
} else if(dtypes[arrNum] === "generic") {
pre.push(["var ", localStr, "=", arrStr, ".get(", ptrStr, ")"].join(""))
code = code.replace(re, localStr)
if(carg.lvalue) {
post.push([arrStr, ".set(", ptrStr, ",", localStr,")"].join(""))
}
} else {
pre.push(["var ", localStr, "=", arrStr, "[", ptrStr, "]"].join(""))
code = code.replace(re, localStr)
if(carg.lvalue) {
post.push([arrStr, "[", ptrStr, "]=", localStr].join(""))
}
}
break
case "scalar":
code = code.replace(re, "Y" + proc.scalarArgs.indexOf(i))
break
case "index":
code = code.replace(re, "index")
break
case "shape":
code = code.replace(re, "shape")
break
}
}
return [pre.join("\n"), code, post.join("\n")].join("\n").trim()
}
function typeSummary(dtypes) {
var summary = new Array(dtypes.length)
var allEqual = true
for(var i=0; i<dtypes.length; ++i) {
var t = dtypes[i]
var digits = t.match(/\d+/)
if(!digits) {
digits = ""
} else {
digits = digits[0]
}
if(t.charAt(0) === 0) {
summary[i] = "u" + t.charAt(1) + digits
} else {
summary[i] = t.charAt(0) + digits
}
if(i > 0) {
allEqual = allEqual && summary[i] === summary[i-1]
}
}
if(allEqual) {
return summary[0]
}
return summary.join("")
}
//Generates a cwise operator
function generateCWiseOp(proc, typesig) {
//Compute dimension
var dimension = typesig[1].length|0
var orders = new Array(proc.arrayArgs.length)
var dtypes = new Array(proc.arrayArgs.length)
//First create arguments for procedure
var arglist = ["SS"]
var code = ["'use strict'"]
var vars = []
for(var j=0; j<dimension; ++j) {
vars.push(["s", j, "=SS[", j, "]"].join(""))
}
for(var i=0; i<proc.arrayArgs.length; ++i) {
arglist.push("a"+i)
arglist.push("t"+i)
arglist.push("p"+i)
dtypes[i] = typesig[2*i]
orders[i] = typesig[2*i+1]
for(var j=0; j<dimension; ++j) {
vars.push(["t",i,"p",j,"=t",i,"[",j,"]"].join(""))
}
}
for(var i=0; i<proc.scalarArgs.length; ++i) {
arglist.push("Y" + i)
}
if(proc.shapeArgs.length > 0) {
vars.push("shape=SS.slice(0)")
}
if(proc.indexArgs.length > 0) {
var zeros = new Array(dimension)
for(var i=0; i<dimension; ++i) {
zeros[i] = "0"
}
vars.push(["index=[", zeros.join(","), "]"].join(""))
}
for(var i=0; i<proc.offsetArgs.length; ++i) {
var off_arg = proc.offsetArgs[i]
var init_string = []