forked from processing-js/processing-js
-
Notifications
You must be signed in to change notification settings - Fork 1
/
processing.js
7390 lines (6474 loc) · 238 KB
/
processing.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
/*
P R O C E S S I N G . J S - @VERSION@
a port of the Processing visualization language
License : MIT
Developer : John Resig: http://ejohn.org
Web Site : http://processingjs.org
Java Version : http://processing.org
Github Repo. : http://github.com/jeresig/processing-js
Bug Tracking : http://processing-js.lighthouseapp.com
Mozilla POW! : http://wiki.Mozilla.org/Education/Projects/ProcessingForTheWeb
Maintained by : Seneca: http://zenit.senecac.on.ca/wiki/index.php/Processing.js
Hyper-Metrix: http://hyper-metrix.com/#Processing
BuildingSky: http://weare.buildingsky.net/pages/processing-js
*/
(function() {
this.Processing = function Processing(aElement, aCode) {
// Get the DOM element if string was passed
if (typeof aElement === "string") {
aElement = document.getElementById(aElement);
}
// The problem: if the HTML canvas dimensions differ from the
// dimensions specified in the size() call in the sketch, for
// 3D sketches, browsers will either not render or render the
// scene incorrectly. To fix this, we need to adjust the attributes
// of the canvas width and height.
// this regex needs to be cleaned up a bit
var r = "" + aCode.match(/size\s*\((?:.+),(?:.+),\s*(OPENGL|P3D)\s*\)\s*;/);
var dimensions = r.match(/[0-9]+/g);
if (dimensions) {
var sketchWidth = parseInt(dimensions[0], 10);
var sketchHeight = parseInt(dimensions[1], 10);
// only adjust the attributes if they differ
if (aElement.width !== sketchWidth || aElement.height !== sketchHeight) {
aElement.setAttribute("width", sketchWidth);
aElement.setAttribute("height", sketchHeight);
}
}
// Build an Processing functions and env. vars into 'p'
var p = Processing.build(aElement);
// Send aCode Processing syntax to be converted to JavaScript
if (aCode) {
p.init(aCode);
}
return p;
};
// Share lib space
Processing.lib = {};
// IE Unfriendly AJAX Method
var ajax = function(url) {
var AJAX = new window.XMLHttpRequest();
if (AJAX) {
AJAX.open("GET", url + "?t=" + new Date().getTime(), false);
AJAX.send(null);
return AJAX.responseText;
} else {
return false;
}
};
// Automatic Initialization Method
var init = function() {
var canvas = document.getElementsByTagName('canvas');
for (var i = 0, l = canvas.length; i < l; i++) {
// Get data-src instead of datasrc
var datasrc = canvas[i].getAttribute('data-src');
if (datasrc === null) {
// Temporary fallback for datasrc
datasrc = canvas[i].getAttribute('datasrc');
}
if (datasrc) {
// The problem: if the HTML canvas dimensions differ from the
// dimensions specified in the size() call in the sketch, for
// 3D sketches, browsers will either not render or render the
// scene incorrectly. To fix this, we need to adjust the attributes
// of the canvas width and height.
// Get the source, we'll need to find what the user has used in size()
var sketchSource = ajax(datasrc);
// get the dimensions
// this regex needs to be cleaned up a bit
var r = "" + sketchSource.match(/size\s*\((?:.+),(?:.+),\s*(OPENGL|P3D)\s*\)\s*;/);
var dimensions = r.match(/[0-9]+/g);
if (dimensions) {
var sketchWidth = parseInt(dimensions[0], 10);
var sketchHeight = parseInt(dimensions[1], 10);
// only adjust the attributes if they differ
if (canvas[i].width !== sketchWidth || canvas[i].height !== sketchHeight) {
canvas[i].setAttribute("width", sketchWidth);
canvas[i].setAttribute("height", sketchHeight);
}
}
Processing(canvas[i], sketchSource);
}
}
};
// Wrapper to easily deal with array names changes.
var newWebGLArray = function(data) {
return new WebGLFloatArray(data);
};
var createProgramObject = function(curContext, vetexShaderSource, fragmentShaderSource) {
var vertexShaderObject = curContext.createShader(curContext.VERTEX_SHADER);
curContext.shaderSource(vertexShaderObject, vetexShaderSource);
curContext.compileShader(vertexShaderObject);
if (!curContext.getShaderParameter(vertexShaderObject, curContext.COMPILE_STATUS)) {
throw curContext.getShaderInfoLog(vertexShaderObject);
}
var fragmentShaderObject = curContext.createShader(curContext.FRAGMENT_SHADER);
curContext.shaderSource(fragmentShaderObject, fragmentShaderSource);
curContext.compileShader(fragmentShaderObject);
if (!curContext.getShaderParameter(fragmentShaderObject, curContext.COMPILE_STATUS)) {
throw curContext.getShaderInfoLog(fragmentShaderObject);
}
var programObject = curContext.createProgram();
curContext.attachShader(programObject, vertexShaderObject);
curContext.attachShader(programObject, fragmentShaderObject);
curContext.linkProgram(programObject);
if (!curContext.getProgramParameter(programObject, curContext.LINK_STATUS)) {
throw "Error linking shaders.";
}
return programObject;
};
var programObject3D;
var programObject2D;
// Vertices are specified in a counter-clockwise order
// triangles are in this order: back, front, right, bottom, left, top
var boxVerts = [0.5, 0.5, -0.5, 0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5,
-0.5, 0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5,
-0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5,
0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, 0.5,
0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, -0.5, -0.5, 0.5, -0.5, 0.5,
-0.5, -0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, 0.5, -0.5, -0.5,
-0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5,
-0.5, 0.5, -0.5, -0.5, -0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5,
-0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5];
var boxNorms = [0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1,
0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1,
1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0,
0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0,
-1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0,
0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0];
var boxOutlineVerts = [0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, -0.5, 0.5, -0.5, -0.5,
-0.5, 0.5, -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5,
0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, -0.5,
-0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5,
0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, -0.5, -0.5,
-0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5];
var boxBuffer;
var boxNormBuffer;
var boxOutlineBuffer;
var sphereBuffer;
var lineBuffer;
var pointBuffer;
// Vertex shader for points and lines
var vertexShaderSource2D =
"attribute vec3 Vertex;" +
"uniform vec4 color;" +
"uniform mat4 model;" +
"uniform mat4 view;" +
"uniform mat4 projection;" +
"void main(void) {" +
" gl_FrontColor = color;" +
" gl_Position = projection * view * model * vec4(Vertex, 1.0);" +
"}";
var fragmentShaderSource2D =
"void main(void){" +
" gl_FragColor = gl_Color;" +
"}";
// Vertex shader for boxes and spheres
var vertexShaderSource3D =
"attribute vec3 Vertex;" +
"attribute vec3 Normal;" +
"uniform vec4 color;" +
"uniform bool usingMat;" +
"uniform vec3 specular;" +
"uniform vec3 mat_emissive;" +
"uniform vec3 mat_ambient;" +
"uniform vec3 mat_specular;" +
"uniform float shininess;" +
"uniform mat4 model;" +
"uniform mat4 view;" +
"uniform mat4 projection;" +
"uniform mat4 normalTransform;" +
"uniform int lightCount;" +
"uniform vec3 falloff;" +
"struct Light {" +
" bool dummy;" +
" int type;" +
" vec3 color;" +
" vec3 position;" +
" vec3 direction;" +
" float angle;" +
" vec3 halfVector;" +
" float concentration;" +
"};" +
"uniform Light lights[8];" +
"void AmbientLight( inout vec3 totalAmbient, in vec3 ecPos, in Light light ) {" +
// Get the vector from the light to the vertex
// Get the distance from the current vector to the light position
" float d = length( light.position - ecPos );" +
" float attenuation = 1.0 / ( falloff[0] + ( falloff[1] * d ) + ( falloff[2] * d * d ));" + " totalAmbient += light.color * attenuation;" +
"}" +
"void DirectionalLight( inout vec3 col, in vec3 ecPos, inout vec3 spec, in vec3 vertNormal, in Light light ) {" +
" float powerfactor = 0.0;" +
" float nDotVP = max(0.0, dot( vertNormal, light.position ));" +
" float nDotVH = max(0.0, dot( vertNormal, normalize( light.position-ecPos )));" +
" if( nDotVP != 0.0 ){" +
" powerfactor = pow( nDotVH, shininess );" +
" }" +
" col += light.color * nDotVP;" +
" spec += specular * powerfactor;" +
"}" +
"void PointLight( inout vec3 col, inout vec3 spec, in vec3 vertNormal, in vec3 ecPos, in vec3 eye, in Light light ) {" +
" float powerfactor;" +
// Get the vector from the light to the vertex
" vec3 VP = light.position - ecPos;" +
// Get the distance from the current vector to the light position
" float d = length( VP ); " +
// Normalize the light ray so it can be used in the dot product operation.
" VP = normalize( VP );" +
" float attenuation = 1.0 / ( falloff[0] + ( falloff[1] * d ) + ( falloff[2] * d * d ));" +
" float nDotVP = max( 0.0, dot( vertNormal, VP ));" +
" vec3 halfVector = normalize( VP + eye );" +
" float nDotHV = max( 0.0, dot( vertNormal, halfVector ));" +
" if( nDotVP == 0.0) {" +
" powerfactor = 0.0;" +
" }" +
" else{" +
" powerfactor = pow( nDotHV, shininess );" +
" }" +
" spec += specular * powerfactor * attenuation;" +
" col += light.color * nDotVP * attenuation;" +
"}" +
/*
*/
"void SpotLight( inout vec3 col, inout vec3 spec, in vec3 vertNormal, in vec3 ecPos, in vec3 eye, in Light light ) {" +
" float spotAttenuation;" +
" float powerfactor;" +
// calculate the vector from the current vertex to the light.
" vec3 VP = light.position - ecPos; " +
" vec3 ldir = normalize( light.direction );" +
// get the distance from the spotlight and the vertex
" float d = length( VP );" +
" VP = normalize( VP );" +
" float attenuation = 1.0 / ( falloff[0] + ( falloff[1] * d ) + ( falloff[2] * d * d ) );" +
// dot product of the vector from vertex to light and light direction.
" float spotDot = dot( VP, ldir );" +
// if the vertex falls inside the cone
" if( spotDot < cos( light.angle ) ) {" +
" spotAttenuation = pow( spotDot, light.concentration );" +
" }" +
" else{" +
" spotAttenuation = 1.0;" +
" }" +
" attenuation *= spotAttenuation;" +
" float nDotVP = max( 0.0, dot( vertNormal, VP ));" +
" vec3 halfVector = normalize( VP + eye );" +
" float nDotHV = max( 0.0, dot( vertNormal, halfVector ));" +
" if( nDotVP == 0.0 ) {" +
" powerfactor = 0.0;" +
" }" +
" else {" +
" powerfactor = pow( nDotHV, shininess );" +
" }" +
" spec += specular * powerfactor * attenuation;" +
" col += light.color * nDotVP * attenuation;" +
"}" +
"void main(void) {" +
" vec3 finalAmbient = vec3( 0.0, 0.0, 0.0 );" +
" vec3 finalDiffuse = vec3( 0.0, 0.0, 0.0 );" +
" vec3 finalSpecular = vec3( 0.0, 0.0, 0.0 );" +
" vec3 norm = vec3( normalTransform * vec4( Normal, 0.0 ) );" +
" vec4 ecPos4 = view * model * vec4(Vertex,1.0);" +
" vec3 ecPos = (vec3(ecPos4))/ecPos4.w;" +
" vec3 eye = vec3( 0.0, 0.0, 1.0 );" +
// If there were no lights this draw call, just use the
// assigned fill color of the shape and the specular value
" if( lightCount == 0 ) {" +
" gl_FrontColor = color + vec4(mat_specular,1.0);" +
" }" +
" else {" +
" for( int i = 0; i < lightCount; i++ ) {" +
" if( lights[i].type == 0 ) {" +
" AmbientLight( finalAmbient, ecPos, lights[i] );" +
" }" +
" else if( lights[i].type == 1 ) {" +
" DirectionalLight( finalDiffuse,ecPos, finalSpecular, norm, lights[i] );" +
" }" +
" else if( lights[i].type == 2 ) {" +
" PointLight( finalDiffuse, finalSpecular, norm, ecPos, eye, lights[i] );" +
" }" +
" else if( lights[i].type == 3 ) {" +
" SpotLight( finalDiffuse, finalSpecular, norm, ecPos, eye, lights[i] );" +
" }" +
" }" +
" if( usingMat == false ) {" +
" gl_FrontColor = vec4( " +
" vec3(color) * finalAmbient +" +
" vec3(color) * finalDiffuse +" +
" vec3(color) * finalSpecular," +
" color[3] );" +
" }" +
" else{" +
" gl_FrontColor = vec4( " +
" mat_emissive + " +
" (vec3(color) * mat_ambient * finalAmbient) + " +
" (vec3(color) * finalDiffuse) + " +
" (mat_specular * finalSpecular), " +
" color[3] );" +
" }" +
" }" +
" gl_Position = projection * view * model * vec4( Vertex, 1.0 );" +
"}";
var fragmentShaderSource3D =
"void main(void){" +
" gl_FragColor = gl_Color;" +
"}";
document.addEventListener('DOMContentLoaded', function() {
init();
}, false);
// Place-holder for debugging function
Processing.debug = function(e) {};
// Parse Processing (Java-like) syntax to JavaScript syntax with Regex
Processing.parse = function parse(aCode, p) {
// Force characters-as-bytes to work.
//aCode = aCode.replace(/('(.){1}')/g, "$1.charCodeAt(0)");
aCode = aCode.replace(/'.{1}'/g, function(all) {
return "(new Char(" + all + "))";
});
// Parse out @pjs directive, if any.
p.pjs = {
imageCache: {
pending: 0
}
}; // by default we have an empty imageCache, no more.
var dm = /\/\*\s*@pjs\s+((?:[^\*]|\*+[^\*\/])*)\*\//g.exec(aCode);
if (dm && dm.length === 2) {
var directives = dm.splice(1, 2)[0].replace('\n', '').replace('\r', '').split(';');
// We'll L/RTrim, and also remove any surrounding double quotes (e.g., just take string contents)
var clean = function(s) {
return s.replace(/^\s*\"?/, '').replace(/\"?\s*$/, '');
};
for (var i = 0, dl = directives.length; i < dl; i++) {
var pair = directives[i].split('=');
if (pair && pair.length === 2) {
var key = clean(pair[0]);
var value = clean(pair[1]);
// A few directives require work beyond storying key/value pairings
if (key === "preload") {
var list = value.split(',');
// All pre-loaded images will get put in imageCache, keyed on filename
for (var j = 0, ll = list.length; j < ll; j++) {
var imageName = clean(list[j]);
var img = new Image();
img.onload = (function() {
return function() {
p.pjs.imageCache.pending--;
};
}());
p.pjs.imageCache.pending++;
p.pjs.imageCache[imageName] = img;
img.src = imageName;
}
} else if (key === "opaque") {
p.canvas.mozOpaque = value === "true";
} else {
p.pjs[key] = value;
}
}
}
aCode = aCode.replace(dm[0], '');
}
// Saves all strings into an array
// masks all strings into <STRING n>
// to be replaced with the array strings after parsing is finished
var strings = [];
aCode = aCode.replace(/(["'])(\\\1|.)*?(\1)/g, function(all) {
strings.push(all);
return "<STRING " + (strings.length - 1) + ">";
});
// Windows newlines cause problems:
aCode = aCode.replace(/\r\n?/g, "\n");
// Remove end-of-line comments
aCode = aCode.replace(/\/\/.*\n/g, "\n");
// Weird parsing errors with %
aCode = aCode.replace(/([^\s])%([^\s])/g, "$1 % $2");
// Since frameRate() and frameRate are different things,
// we need to differentiate them somehow. So when we parse
// the Processing.js source, replace frameRate so it isn't
// confused with frameRate().
aCode = aCode.replace(/(\s*=\s*|\(*\s*)frameRate(\s*\)+?|\s*;)/, "$1p.FRAME_RATE$2");
// Simple convert a function-like thing to function
aCode = aCode.replace(/(?:static )?(\w+(?:\[\])* )(\w+)\s*(\([^\)]*\)\s*\{)/g, function(all, type, name, args) {
if (name === "if" || name === "for" || name === "while") {
return all;
} else {
return "processing." + name + " = function " + name + args;
}
});
// Attach import() to p{} bypassing JS command, allowing for extrernal library loading
//aCode = aCode.replace(/import \(|import\(/g, "p.Import(");
// Delete import statements, ie. import processing.video.*;
// https://processing-js.lighthouseapp.com/projects/41284/tickets/235-fix-parsing-of-java-import-statement
aCode = aCode.replace(/import\s+(.+);/g, "");
//replace catch (IOException e) to catch (e)
aCode = aCode.replace(/catch\s*\(\W*\w*\s+(\w*)\W*\)/g, "catch ($1)");
//delete the multiple catch block
var catchBlock = /(catch[^\}]*\})\W*catch[^\}]*\}/;
while (catchBlock.test(aCode)) {
aCode = aCode.replace(new RegExp(catchBlock), "$1");
}
Error.prototype.printStackTrace = function() {
this.toString();
};
// Force .length() to be .length
aCode = aCode.replace(/\.length\(\)/g, ".length");
// foo( int foo, float bar )
aCode = aCode.replace(/([\(,]\s*)(\w+)((?:\[\])+| )\s*(\w+\s*[\),])/g, "$1$4");
aCode = aCode.replace(/([\(,]\s*)(\w+)((?:\[\])+| )\s*(\w+\s*[\),])/g, "$1$4");
// float[] foo = new float[5];
aCode = aCode.replace(/new\s+(\w+)\s*((?:\[(?:[^\]]*)\])+)\s*(\{[^;]*\}\s*;)*/g, function(all, name, args, initVars) {
if (initVars) {
return initVars;
} else {
return "new ArrayList(" + args.replace(/\[\]/g, "[0]").slice(1, -1).split("][").join(", ") + ");";
}
});
// What does this do? This does the same thing as "Fix Array[] foo = {...} to [...]" below
aCode = aCode.replace(/(?:static )?\w+\[\]\s*(\w+)\[?\]?\s*=\s*\{.*?\};/g, function(all) {
return all.replace(/\{/g, "[").replace(/\}/g, "]");
});
// int|float foo;
var intFloat = /(\s*(?:int|float)\s+(?!\[\])*(?:\s*|[^\(;]*?,\s*))([a-zA-Z]\w*)\s*(,|;)/i;
while (intFloat.test(aCode)) {
aCode = (function() {
return aCode.replace(new RegExp(intFloat), function(all, type, name, sep) {
return type + " " + name + " = 0" + sep;
});
}());
}
// float foo = 5;
aCode = aCode.replace(/(?:static\s+)?(?:final\s+)?(\w+)((?:\[\s*\])+|\s)\s*(\w+)\[?\]?(\s*[=,;])/g, function(all, type, arr, name, sep) {
if (type === "return" || type === "else") {
return all;
} else {
return "var " + name + sep;
}
});
// Fix Array[] foo = {...} to [...]
aCode = aCode.replace(/\=\s*\{((.|\s)*?\};)/g, function(all, data) {
return "= [" + data.replace(/\{/g, "[").replace(/\}/g, "]");
});
// super() is a reserved word
aCode = aCode.replace(/super\(/g, "superMethod(");
// implements Int1, Int2
aCode = aCode.replace(/implements\s+(\w+\s*(,\s*\w+\s*)*) \{/g, function(all, interfaces) {
var names = interfaces.replace(/\s+/g, "").split(",");
return "{ var __psj_interfaces = new ArrayList([\"" + names.join("\", \"") + "\"]);";
});
var classes = ["int", "float", "boolean", "String", "byte", "double", "long", "ArrayList"];
var classReplace = function(all, name, extend, vars, last) {
classes.push(name);
var staticVar = "";
vars = vars.replace(/final\s+var\s+(\w+\s*=\s*.*?;)/g, function(all, setting) {
staticVar += " " + name + "." + setting;
return "";
});
// Move arguments up from constructor and wrap contents with
// a with(this), and unwrap constructor
return "function " + name + "() {with(this){\n " +
(extend ? "var __self=this;function superMethod(){extendClass(__self,arguments," + extend + ");}\n" : "") +
// Replace var foo = 0; with this.foo = 0;
// and force var foo; to become this.foo = null;
vars.replace(/\s*,\s*/g, ";\n this.").replace(/\b(var |final |public )+\s*/g, "this.").replace(/\b(var |final |public )+\s*/g, "this.").replace(/this\.(\w+);/g, "this.$1 = null;") +
(extend ? "extendClass(this, " + extend + ");\n" : "") +
"<CLASS " + name + " " + staticVar + ">" +
(typeof last === "string" ? last : name + "(");
};
var nextBrace = function(right) {
var rest = right,
position = 0,
leftCount = 1,
rightCount = 0;
while (leftCount !== rightCount) {
var nextLeft = rest.indexOf("{"),
nextRight = rest.indexOf("}");
if (nextLeft < nextRight && nextLeft !== -1) {
leftCount++;
rest = rest.slice(nextLeft + 1);
position += nextLeft + 1;
} else {
rightCount++;
rest = rest.slice(nextRight + 1);
position += nextRight + 1;
}
}
return right.slice(0, position - 1);
};
var matchClasses = /(?:public |abstract |static )*class (\w+)\s*(?:extends\s*(\w+)\s*)?\{\s*((?:.|\n)*?)\b\1\s*\(/g;
var matchNoCon = /(?:public |abstract |static )*class (\w+)\s*(?:extends\s*(\w+)\s*)?\{\s*((?:.|\n)*?)(processing)/g;
aCode = aCode.replace(matchClasses, classReplace);
aCode = aCode.replace(matchNoCon, classReplace);
var matchClass = /<CLASS (\w+) (.*?)>/,
m;
while ((m = aCode.match(matchClass))) {
var left = RegExp.leftContext,
allRest = RegExp.rightContext,
rest = nextBrace(allRest),
className = m[1],
staticVars = m[2] || "";
allRest = allRest.slice(rest.length + 1);
rest = (function() {
return rest.replace(new RegExp("\\b" + className + "\\(([^\\)]*?)\\)\\s*{", "g"), function(all, args) {
args = args.split(/,\s*?/);
if (args[0].match(/^\s*$/)) {
args.shift();
}
var fn = "if ( arguments.length === " + args.length + " ) {\n";
for (var i = 0; i < args.length; i++) {
fn += " var " + args[i] + " = arguments[" + i + "];\n";
}
return fn;
});
}());
// Fix class method names
// this.collide = function() { ... }
// and add closing } for with(this) ...
rest = (function() {
return rest.replace(/(?:public )?processing.\w+ = function (\w+)\((.*?)\)/g, function(all, name, args) {
return "ADDMETHOD(this, '" + name + "', function(" + args + ")";
});
}());
var matchMethod = /ADDMETHOD([\s\S]*?\{)/, mc, methods = "";
while ((mc = rest.match(matchMethod))) {
var prev = RegExp.leftContext,
allNext = RegExp.rightContext,
next = nextBrace(allNext);
methods += "addMethod" + mc[1] + next + "});";
rest = prev + allNext.slice(next.length + 1);
}
rest = methods + rest;
aCode = left + rest + "\n}}" + staticVars + allRest;
}
// Do some tidying up, where necessary
aCode = aCode.replace(/processing.\w+ = function addMethod/g, "addMethod");
// Check if 3D context is invoked -- this is not the best way to do this.
if (aCode.match(/size\((?:.+),(?:.+),\s*(OPENGL|P3D)\s*\);/)) {
p.use3DContext = true;
}
// Handle (int) Casting
aCode = aCode.replace(/\(int\)/g, "0|");
// Remove Casting
aCode = aCode.replace(new RegExp("\\((" + classes.join("|") + ")(\\[\\])*\\)", "g"), "");
// Force numbers to exist //
//aCode = aCode.replace(/([^.])(\w+)\s*\+=/g, "$1$2 = ($2||0) +");
var toNumbers = function(str) {
var ret = [];
str.replace(/(..)/g, function(str) {
ret.push(parseInt(str, 16));
});
return ret;
};
// Convert #aaaaaa into color
aCode = aCode.replace(/#([a-f0-9]{6})/ig, function(m, hex) {
var num = toNumbers(hex);
return "defaultColor(" + num[0] + "," + num[1] + "," + num[2] + ")";
});
// Convert 3.0f to just 3.0
aCode = aCode.replace(/(\d+)f/g, "$1");
// replaces all masked strings from <STRING n> to the appropriate string contained in the strings array
for (var n = 0; n < strings.length; n++) {
aCode = (function() {
return aCode.replace(new RegExp("(.*)(<STRING " + n + ">)(.*)", "g"), function(all, quoteStart, match, quoteEnd) {
var returnString = all,
notString = true,
quoteType = "",
escape = false;
for (var x = 0; x < quoteStart.length; x++) {
if (notString) {
if (quoteStart.charAt(x) === "\"" || quoteStart.charAt(x) === "'") {
quoteType = quoteStart.charAt(x);
notString = false;
}
} else {
if (!escape) {
if (quoteStart.charAt(x) === "\\") {
escape = true;
} else if (quoteStart.charAt(x) === quoteType) {
notString = true;
quoteType = "";
}
} else {
escape = false;
}
}
}
if (notString) { // Match is not inside a string
returnString = quoteStart + strings[n] + quoteEnd;
}
return returnString;
});
}());
}
return aCode;
};
function imageModeCorner(x, y, w, h, whAreSizes) {
return {
x: x,
y: y,
w: w,
h: h
};
}
function imageModeCorners(x, y, w, h, whAreSizes) {
return {
x: x,
y: y,
w: whAreSizes ? w : w - x,
h: whAreSizes ? h : h - y
};
}
function imageModeCenter(x, y, w, h, whAreSizes) {
return {
x: x - w / 2,
y: y - h / 2,
w: w,
h: h
};
}
// Attach Processing functions to 'p'
Processing.build = function buildProcessing(curElement) {
// Create the 'p' object
var p = {};
var curContext;
p.use3DContext = false; // default '2d' canvas context
p.canvas = curElement;
// Set Processing defaults / environment variables
p.name = 'Processing.js Instance';
p.PI = Math.PI;
p.TWO_PI = 2 * p.PI;
p.HALF_PI = p.PI / 2;
p.SINCOS_LENGTH = parseInt(360 / 0.5, 10);
p.MAX_FLOAT = 3.4028235e+38;
p.MIN_FLOAT = -3.4028235e+38;
p.MAX_INT = 2147483647;
p.MIN_INT = -2147483648;
p.CORNER = 0;
p.RADIUS = 1;
p.CENTER_RADIUS = 1;
p.CENTER = 2;
p.POLYGON = 2;
p.QUADS = 5;
p.TRIANGLES = 6;
p.POINTS = 7;
p.LINES = 8;
p.TRIANGLE_STRIP = 9;
p.TRIANGLE_FAN = 4;
p.QUAD_STRIP = 3;
p.CORNERS = 10;
p.CLOSE = true;
p.RGB = 1;
p.ARGB = 2;
p.HSB = 3;
p.ALPHA = 4;
p.CMYK = 5;
p.OPENGL = 'OPENGL';
p.P3D = 'P3D';
p.FRAME_RATE = 0;
p.focused = true;
p.ARROW = 'default';
p.CROSS = 'crosshair';
p.HAND = 'pointer';
p.MOVE = 'move';
p.TEXT = 'text';
p.WAIT = 'wait';
p.NOCURSOR = "url('data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=='), auto";
p.ALPHA_MASK = 0xff000000;
p.RED_MASK = 0x00ff0000;
p.GREEN_MASK = 0x0000ff00;
p.BLUE_MASK = 0x000000ff;
p.REPLACE = 0;
p.BLEND = 1 << 0;
p.ADD = 1 << 1;
p.SUBTRACT = 1 << 2;
p.LIGHTEST = 1 << 3;
p.DARKEST = 1 << 4;
p.DIFFERENCE = 1 << 5;
p.EXCLUSION = 1 << 6;
p.MULTIPLY = 1 << 7;
p.SCREEN = 1 << 8;
p.OVERLAY = 1 << 9;
p.HARD_LIGHT = 1 << 10;
p.SOFT_LIGHT = 1 << 11;
p.DODGE = 1 << 12;
p.BURN = 1 << 13;
p.PRECISIONB = 15; // fixed point precision is limited to 15 bits!!
p.PRECISIONF = 1 << p.PRECISIONB;
p.PREC_MAXVAL = p.PRECISIONF - 1;
p.PREC_ALPHA_SHIFT = 24 - p.PRECISIONB;
p.PREC_RED_SHIFT = 16 - p.PRECISIONB;
p.ROUND = 'round'; // Used by both cap and join.
p.SQUARE = 'butt'; // Used by cap.
p.PROJECT = 'square'; // Used by cap.
p.MITER = 'miter'; // Used by join.
p.BEVEL = 'bevel'; // Used by join.
p.CENTER = 88888880;
p.NORMAL_MODE_AUTO = 0;
p.NORMAL_MODE_SHAPE = 1;
p.NORMAL_MODE_VERTEX = 2;
p.MAX_LIGHTS = 8;
// Key Constants
// both key and keyCode will be equal to these values
p.BACKSPACE = 8;
p.TAB = 9;
p.ENTER = 10;
p.RETURN = 13;
p.ESC = 27;
p.DELETE = 127;
p.CODED = 0xffff;
// key will be CODED and keyCode will be this value
p.SHIFT = 16;
p.CONTROL = 17;
p.ALT = 18;
p.UP = 38;
p.RIGHT = 39;
p.DOWN = 40;
p.LEFT = 37;
var codedKeys = [p.SHIFT, p.CONTROL, p.ALT, p.UP, p.RIGHT, p.DOWN, p.LEFT];
// "Private" variables used to maintain state
var online = true,
doFill = true,
fillStyle = "rgba( 255, 255, 255, 1 )",
doStroke = true,
strokeStyle = "rgba( 204, 204, 204, 1 )",
lineWidth = 1,
loopStarted = false,
hasBackground = false,
doLoop = true,
looping = 0,
curRectMode = p.CORNER,
curEllipseMode = p.CENTER,
imageModeConvert = imageModeCorner,
normalX = 0,
normalY = 0,
normalZ = 0,
normalMode = p.NORMAL_MODE_AUTO,
inSetup = false,
inDraw = false,
curBackground = "rgba( 204, 204, 204, 1 )",
curFrameRate = 60,
curCursor = p.ARROW,
oldCursor = curElement.style.cursor,
curMsPerFrame = 1,
curShape = p.POLYGON,
curShapeCount = 0,
curvePoints = [],
curTightness = 0,
curveDetail = 20,
curveInited = false,
opacityRange = 255,
redRange = 255,
greenRange = 255,
blueRange = 255,
pathOpen = false,
mousePressed = false,
mouseDragging = false,
keyPressed = false,
curColorMode = p.RGB,
curTint = function() {},
curTextSize = 12,
curTextFont = "Arial",
getLoaded = false,
start = new Date().getTime(),
timeSinceLastFPS = start,
framesSinceLastFPS = 0,
lastTextPos = [0, 0, 0],
curveBasisMatrix,
curveToBezierMatrix,
curveDrawMatrix,
bezierBasisInverse,
bezierBasisMatrix;
// User can only have MAX_LIGHTS lights
var lightCount = 0;
//sphere stuff
var sphereDetailV = 0,
sphereDetailU = 0,
sphereX = [],
sphereY = [],
sphereZ = [],
sinLUT = new Array(p.SINCOS_LENGTH),
cosLUT = new Array(p.SINCOS_LENGTH),
sphereVerts,
sphereNorms;
// Camera defaults and settings
var cam,
cameraInv,
forwardTransform,
reverseTransform,
modelView,
modelViewInv,
userMatrixStack,
inverseCopy,
projection,
manipulatingCamera = false,
frustumMode = false,
cameraFOV = 60 * (Math.PI / 180),
cameraX = curElement.width / 2,
cameraY = curElement.height / 2,
cameraZ = cameraY / Math.tan(cameraFOV / 2),
cameraNear = cameraZ / 10,
cameraFar = cameraZ * 10,
cameraAspect = curElement.width / curElement.height;
var firstX, firstY, secondX, secondY, prevX, prevY;
// Stores states for pushStyle() and popStyle().
var styleArray = new Array(0);
// Glyph path storage for textFonts
p.glyphTable = {};
// Global vars for tracking mouse position
p.pmouseX = 0;
p.pmouseY = 0;
p.mouseX = 0;
p.mouseY = 0;
p.mouseButton = 0;
p.mouseDown = false;
p.mouseScroll = 0;
// Undefined event handlers to be replaced by user when needed
p.mouseClicked = undefined;
p.mouseDragged = undefined;
p.mouseMoved = undefined;
p.mousePressed = undefined;
p.mouseReleased = undefined;
p.mouseScrolled = undefined;
p.keyPressed = undefined;
p.keyReleased = undefined;
p.draw = undefined;
p.setup = undefined;
// The height/width of the canvas
p.width = curElement.width - 0;
p.height = curElement.height - 0;
// The current animation frame
p.frameCount = 0;
////////////////////////////////////////////////////////////////////////////
// Char handling
////////////////////////////////////////////////////////////////////////////
var charMap = {};