-
Notifications
You must be signed in to change notification settings - Fork 2
/
jasmine-opengl.js
2923 lines (2736 loc) · 134 KB
/
jasmine-opengl.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
// This is an OpenGL implementation for SqueakJS using WebGL.
// It is very much incomplete and currently only implements
// the subset of OpenGL that is used by Croquet Jasmine,
// but could be extended to support more.
// The functions are invoked via FFI, which takes care of
// converting the arguments and return values between JS
// and Smalltalk.
// The OpenGL context is global and created by B3DAcceleratorPlugin.
// Context switching is done by B3DAcceleratorPlugin.makeCurrent().
// helpful constant lookup:
// https://javagl.github.io/GLConstantsTranslator/GLConstantsTranslator.html
// TODO
// [ ] implement draw arrays
// [X] implement draw elements
// [ ] implement vertex buffer objects
// [X] implement material + lighting
// [X] implement clip planes
// [ ] implement fog
// [ ] implement tex coord gen
// [ ] fix glBitmap for size other than 640x480 (also, make pixel perfect)
// [ ] optimize list compilation glBegin/glEnd
// [ ] implement light attenuation
// [ ] implement spot lights
// [ ] implement color material
// [ ] emulate glLineWidth (WebGL usually only supports 1px lines)
// e.g. using https://wwwtyro.net/2019/11/18/instanced-lines.html
// [ ] full OpenGL 1.0 support
// [ ] full OpenGL 1.1 support
// [ ] full OpenGL 1.2 support
// [ ] full OpenGL 1.3 support
// [ ] full OpenGL 1.4 support
// [ ] full OpenGL 1.5 support
// [ ] some extensions?
// OpenGL constants (many missing in WebGL)
var GL;
function OpenGL() {
"use strict";
var DEBUG = 0;
// 0 = off
// 1 = some (errors, warnings)
// 2 = lots (function calls)
// 3 = all (call details)
var identity = new Float32Array([
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1,
]);
// Primitive attributes for glBegin/glEnd
var flagCounter = 0;
var HAS_NORMAL = 1 << flagCounter++;
var HAS_COLOR = 1 << flagCounter++;
var HAS_TEXCOORD = 1 << flagCounter++;
// additional flags for selecting shader
var USE_TEXTURE = 1 << flagCounter++;
var USE_ALPHA_TEST = 1 << flagCounter++;
var USE_POINT_SIZE = 1 << flagCounter++;
var NUM_LIGHTS_MASK = (1 << flagCounter++) // 3 bits for number of lights (0-7)
+ (1 << flagCounter++)
+ (1 << flagCounter++);
var NUM_CLIP_PLANES_MASK = (1 << flagCounter++) // 3 bits for number of clip planes (0-5)
+ (1 << flagCounter++)
+ (1 << flagCounter++);
var FOG_MASK = (1 << flagCounter++) // 2 bits for fog mode (off, linear, exp, exp2)
+ (1 << flagCounter++);
// this math is silly but fun ...
var NUM_LIGHTS_SHIFT = Math.floor(Math.log2(NUM_LIGHTS_MASK)) - 2;
var MAX_LIGHTS = (NUM_LIGHTS_MASK >> NUM_LIGHTS_SHIFT) + 1;
var ANY_LIGHTS = (MAX_LIGHTS-1) << NUM_LIGHTS_SHIFT;
if (ANY_LIGHTS !== NUM_LIGHTS_MASK) throw Error("OpenGL: bad NUM_LIGHTS_MASK");
var NUM_CLIP_PLANES_SHIFT = Math.floor(Math.log2(NUM_CLIP_PLANES_MASK)) - 2;
var MAX_CLIP_PLANES = (NUM_CLIP_PLANES_MASK >> NUM_CLIP_PLANES_SHIFT) + 1;
var ANY_CLIP_PLANES = (MAX_CLIP_PLANES-1) << NUM_CLIP_PLANES_SHIFT;
if (ANY_CLIP_PLANES !== NUM_CLIP_PLANES_MASK) throw Error("OpenGL: bad NUM_CLIP_PLANES_MASK");
var FOG_SHIFT = Math.floor(Math.log2(FOG_MASK)) - 1;
var MAX_FOG = (FOG_MASK >> FOG_SHIFT) + 1;
var ANY_FOG = (MAX_FOG-1) << FOG_SHIFT;
if (ANY_FOG !== FOG_MASK) throw Error("OpenGL: bad ANY_FOG");
var NO_FOG = 0;
var LINEAR_FOG = 1;
var EXP_FOG = 2;
var EXP2_FOG = 3;
var gl; // the emulated OpenGL state
var webgl; // the actual WebGL context
return {
getModuleName: function() { return 'libGL.so (jasmine)'; },
setInterpreter: function(anInterpreterProxy) {
this.vm = anInterpreterProxy.vm;
return true;
},
ffiFunctionNotFoundHandler: function(name, args) {
this.vm.warnOnce("OpenGL: UNIMPLEMENTED (missing) " + name);
if (DEBUG > 0) debugger;
return null; // do not fail but return nil
},
initialiseModule: function() {
DEBUG > 1 && console.log("OpenGL: initialiseModule");
if (!GL) initGLConstants();
// connect to B3DAcceleratorPlugin to get WebGL context
var modules = SqueakJS.vm.primHandler.loadedModules;
var B3DAcceleratorPlugin = modules['B3DAcceleratorPlugin'];
if (!B3DAcceleratorPlugin) throw Error("OpenGL: B3DAcceleratorPlugin not loaded");
this.GL = GL;
B3DAcceleratorPlugin.setOpenGL(this); // will call makeCurrent()
},
makeCurrent: function(renderer) {
if (webgl === renderer.webgl) return; // already current
DEBUG > 1 && console.log("OpenGL: makeCurrent", renderer);
webgl = renderer.webgl;
gl = renderer.opengl;
if (!gl) renderer.opengl = this.initGL();
},
initGL: function() {
DEBUG > 0 && console.log("OpenGL: initGL");
// if webgl-lint is loaded, configure it
const ext = webgl.getExtension('GMAN_debug_helper');
if (ext) ext.setConfiguration({
throwOnError: false,
});
// if Spector script is loaded, capture WebGL calls
if (typeof SPECTOR !== "undefined") {
var spector = new SPECTOR.Spector();
spector.captureContext(webgl);
spector.displayUI();
}
// initialize emulated OpenGL state
gl = {
alphaTest: false,
alphaFunc: null,
alphaRef: 0,
extensions: "ARB_texture_non_power_of_two SGIS_generate_mipmap",
color: new Float32Array(4),
normal: new Float32Array([0, 0, 1]),
texCoord: new Float32Array(2),
primitive: null, // for glBegin/glEnd
primitiveAttrs: 0, // for glVertex
clipPlanes: [], // clip plane equations
clientState: {}, // enabled arrays by attr
fogMode: GL.EXP, // fog mode
fogEnabled: false, // fog enabled
fogDensity: 1, // fog density
fogStart: 0, // fog start
fogEnd: 1, // fog end
fogColor: new Float32Array([0, 0, 0, 0]), // fog color
fogHint: GL.DONT_CARE, // fog hint
shaders: {}, // shader programs by attr/flags
matrixMode: 0, // current matrix mode
matrices: {}, // matrix stacks by mode
matrix: null, // current matrix (matrices[mode][0])
lightingEnabled: false,
lights: [], // light states
lightModelAmbient: null, // scene ambient color
material: null, // material state
textureIdGen: 0, // texture id generator
textures: {}, // webgl texture objects by id
texture: null, // texture
textureEnabled: false, // texture enabled
textureEnvMode: GL.MODULATE, // texture environment mode
listIdGen: 0, // display list id generator
lists: {}, // display lists by id
list: null, // current display list
listMode: 0, // current display list mode
listBase: 0, // base for glCallLists
pixelStoreUnpackRowLength: 0,
pixelStoreUnpackSkipRows: 0,
pixelStoreUnpackSkipPixels: 0,
rasterPos: new Float32Array(4),
rasterColor: new Float32Array([1, 1, 1, 1]),
bitmapTexture: null, // texture for glBitmap
bitmapVertexBuffer: null, // vertex buffer for glBitmap
bitmapShader: { // shader program for glBitmap
program: null,
locations: {},
}, // shader for glBitmap
viewport: new Int32Array([0, 0, 0, 0]),
depthRange: new Float32Array([0, 1]),
};
// set initial state
gl.matrices[GL.MODELVIEW] = [new Float32Array(identity)];
gl.matrices[GL.PROJECTION] = [new Float32Array(identity)];
gl.matrixMode = GL.MODELVIEW;
gl.matrix = gl.matrices[gl.matrixMode][0];
gl.color.set([1, 1, 1, 1]);
for (var i = 0; i < MAX_CLIP_PLANES; i++) {
gl.clipPlanes[i] = {
enabled: false,
equation: new Float32Array([0, 0, 0, 0]),
};
}
for (var i = 0; i < MAX_LIGHTS; i++) {
gl.lights[i] = {
enabled: false,
ambient: new Float32Array([0, 0, 0, 1]),
diffuse: new Float32Array(i === 0 ? [1, 1, 1, 1] : [0, 0, 0, 1]),
specular: new Float32Array(i === 0 ? [1, 1, 1, 1] : [0, 0, 0, 1]),
position: new Float32Array([0, 0, 1, 0]),
};
}
gl.lightModelAmbient = new Float32Array([0.2, 0.2, 0.2, 1]);
gl.material = {
ambient: new Float32Array([0.2, 0.2, 0.2, 1]),
diffuse: new Float32Array([0.8, 0.8, 0.8, 1]),
specular: new Float32Array([0, 0, 0, 1]),
emission: new Float32Array([0, 0, 0, 1]),
shininess: 0,
};
var clientStates = ["vertexArray", "normalArray", "colorArray", "textureCoordArray"];
for (var i = 0; i < clientStates.length; i++) {
var attr = clientStates[i];
gl.clientState[attr] = {
enabled: false,
size: 0,
type: GL.FLOAT,
stride: 0,
pointer: null,
// binding: null, TODO: support VBOs
}
}
return gl;
},
destroyGL: function(renderer) {
DEBUG > 0 && console.log("OpenGL: destroyGL");
// TODO: delete textures, arrays, shaders?
renderer.opengl = null;
webgl = null;
gl = null;
},
// FFI functions get JS args, return JS result
addToList: function(name, args) {
if (!gl.list) return false;
gl.list.commands.push({name: name, args: args});
if (gl.listMode === GL.COMPILE) {
DEBUG > 1 && console.log("[COMPILE]", name, args);
return true;
}
return false;
},
glAlphaFunc: function(func, ref) {
if (gl.listMode && this.addToList("glAlphaFunc", [func, ref])) return;
DEBUG > 1 && console.log("glAlphaFunc", GL_Symbol(func), ref);
gl.alphaFunc = func;
gl.alphaRef = ref;
},
glBegin: function(mode) {
if (gl.listMode && this.addToList("glBegin", [mode])) return;
DEBUG > 1 && console.log("glBegin", GL_Symbol(mode, 'POINTS'));
gl.primitive = {
mode: mode,
vertices: [],
vertexSize: 0,
vertexAttrs: 0,
}
gl.primitiveAttrs = 0;
},
glBindTexture: function(target, texture) {
if (gl.listMode && this.addToList("glBindTexture", [target, texture])) return;
DEBUG > 1 && console.log("glBindTexture", GL_Symbol(target), texture);
var textureObj = gl.textures[texture];
if (!textureObj) throw Error("OpenGL: texture not found");
webgl.bindTexture(target, textureObj);
gl.texture = textureObj;
},
glBitmap: function(width, height, xorig, yorig, xmove, ymove, bitmap) {
// bitmap is supposed to be declared as "GLubyte*" per OpenGL spec,
// which the FFI would convert to Uint8Array for us. However, the
// image FFI declaration uses "void*", probably because it makes no
// difference in C, a pointer is a pointer. In JS, we get an
// ArrayBuffer for "void*" so we need to convert it to Uint8Array
// ourselves.
if (!bitmap.buffer) bitmap = new Uint8Array(bitmap);
if (gl.listMode && this.addToList("glBitmap", [width, height, xorig, yorig, xmove, ymove, bitmap])) return;
DEBUG > 1 && console.log("glBitmap", width, height, xorig, yorig, xmove, ymove, bitmap);
if (width > 0 && height > 0) {
// we need to convert the 1-bit deep bitmap to a 1-byte
// per pixel texture in ALPHA format, with the bitmap
// mapping 0-bits to transparent, 1-bits to opaque,
// and then draw it as a textured quad covering the viewport
var texels = new Uint8Array(width * height);
var bytesPerRow = Math.ceil(width / 32) * 4;
for (var y = 0; y < height; y++) {
var byteIndex = y * bytesPerRow;
var bitIndex = 7;
for (var x = 0; x < width; x++) {
var bit = bitmap[byteIndex] & (1 << bitIndex);
if (bit) texels[y * width + x] = 255;
bitIndex--;
if (bitIndex < 0) {
byteIndex++;
bitIndex = 7;
}
}
}
// debug: print bitmap
// s=''; for (y = height -1 ; y >= 0; y--) { for (x = 0; x < width; x++) s += texels[y * width + x] ? '⬛️' : '⬜️'; s+='\n'}; console.log(s)
var texture = gl.bitmapTexture;
if (!texture) {
texture = gl.bitmapTexture = webgl.createTexture();
webgl.bindTexture(webgl.TEXTURE_2D, texture);
webgl.texParameteri(webgl.TEXTURE_2D, webgl.TEXTURE_MIN_FILTER, webgl.LINEAR);
webgl.texParameteri(webgl.TEXTURE_2D, webgl.TEXTURE_MAG_FILTER, webgl.LINEAR);
webgl.texParameteri(webgl.TEXTURE_2D, webgl.TEXTURE_WRAP_S, webgl.CLAMP_TO_EDGE);
webgl.texParameteri(webgl.TEXTURE_2D, webgl.TEXTURE_WRAP_T, webgl.CLAMP_TO_EDGE);
} else {
webgl.bindTexture(webgl.TEXTURE_2D, texture);
}
webgl.pixelStorei(webgl.UNPACK_ALIGNMENT, 1);
webgl.texImage2D(webgl.TEXTURE_2D, 0, webgl.ALPHA, width, height, 0, webgl.ALPHA, webgl.UNSIGNED_BYTE, texels);
webgl.pixelStorei(webgl.UNPACK_ALIGNMENT, 4);
webgl.disable(webgl.CULL_FACE);
webgl.disable(webgl.DEPTH_TEST);
webgl.disable(webgl.BLEND);
webgl.colorMask(true, true, true, true);
webgl.viewport(0, 0, webgl.drawingBufferWidth, webgl.drawingBufferHeight);
var vertexBuffer = gl.bitmapVertexBuffer;
if (!vertexBuffer) {
var vertices = new Float32Array([
0, 0,
1, 0,
0, 1,
1, 1,
]);
vertexBuffer = gl.bitmapVertexBuffer = webgl.createBuffer();
webgl.bindBuffer(webgl.ARRAY_BUFFER, vertexBuffer);
webgl.bufferData(webgl.ARRAY_BUFFER, vertices, webgl.STATIC_DRAW);
} else {
webgl.bindBuffer(webgl.ARRAY_BUFFER, vertexBuffer);
}
var shader = gl.bitmapShader;
if (!shader.program) {
shader.program = webgl.createProgram();
var vs = webgl.createShader(webgl.VERTEX_SHADER);
webgl.shaderSource(vs, `
attribute vec2 a_position;
uniform vec3 u_raster;
uniform vec2 u_rasterOffset;
uniform vec2 u_rasterScale;
uniform vec2 u_translate;
uniform vec2 u_scale;
varying vec2 v_texcoord;
void main() {
vec2 raster = u_raster.xy * u_rasterScale + u_rasterOffset;
vec2 pos = (a_position + raster) * u_scale + u_translate;
gl_Position = vec4(pos, u_raster.z, 1);
v_texcoord = a_position;
}
`);
webgl.compileShader(vs);
if (!webgl.getShaderParameter(vs, webgl.COMPILE_STATUS)) {
console.error("OpenGL: vertex shader compile error: " + webgl.getShaderInfoLog(vs));
debugger;
return;
}
var fs = webgl.createShader(webgl.FRAGMENT_SHADER);
webgl.shaderSource(fs, `
precision mediump float;
uniform sampler2D u_texture;
uniform vec4 u_color;
varying vec2 v_texcoord;
void main() {
float alpha = texture2D(u_texture, v_texcoord).a;
if (alpha < 0.5) discard;
gl_FragColor = u_color;
}
`);
webgl.compileShader(fs);
if (!webgl.getShaderParameter(fs, webgl.COMPILE_STATUS)) {
console.error("OpenGL: fragment shader compile error: " + webgl.getShaderInfoLog(fs));
debugger;
return;
}
webgl.attachShader(shader.program, vs);
webgl.attachShader(shader.program, fs);
webgl.linkProgram(shader.program);
if (!webgl.getProgramParameter(shader.program, webgl.LINK_STATUS)) {
console.error("OpenGL: shader link error: " + webgl.getProgramInfoLog(shader.program));
debugger
return;
}
shader.locations = {
a_position: webgl.getAttribLocation(shader.program, "a_position"),
u_texture: webgl.getUniformLocation(shader.program, "u_texture"),
u_color: webgl.getUniformLocation(shader.program, "u_color"),
u_raster: webgl.getUniformLocation(shader.program, "u_raster"),
u_rasterOffset: webgl.getUniformLocation(shader.program, "u_rasterOffset"),
u_rasterScale: webgl.getUniformLocation(shader.program, "u_rasterScale"),
u_translate: webgl.getUniformLocation(shader.program, "u_translate"),
u_scale: webgl.getUniformLocation(shader.program, "u_scale"),
};
}
webgl.useProgram(shader.program);
webgl.enableVertexAttribArray(shader.locations.a_position);
webgl.vertexAttribPointer(shader.locations.a_position, 2, webgl.FLOAT, false, 0, 0);
webgl.uniform1i(shader.locations.u_texture, 0);
webgl.uniform4fv(shader.locations.u_color, gl.rasterColor);
// these seem to work for 640x480... I can't figure out the right transform yet
if (!this.bitmapScale) this.bitmapScale = [0.0311, 0.0419];
if (!this.bitmapTranslate) this.bitmapTranslate = [-1, -1];
if (!this.bitmapRasterOffset) this.bitmapRasterOffset = [0, 0];
if (!this.bitmapRasterScale) this.bitmapRasterScale = [0.1, 0.1];
// these properties allow intereactive debugging
webgl.uniform3f(shader.locations.u_raster, gl.rasterPos[0] + xorig, gl.rasterPos[1] + yorig, gl.rasterPos[2]);
webgl.uniform2fv(shader.locations.u_rasterOffset, this.bitmapRasterOffset);
webgl.uniform2fv(shader.locations.u_rasterScale, this.bitmapRasterScale);
webgl.uniform2fv(shader.locations.u_translate, this.bitmapTranslate);
webgl.uniform2fv(shader.locations.u_scale, this.bitmapScale);
webgl.drawArrays(webgl.TRIANGLE_STRIP, 0, 4);
webgl.disableVertexAttribArray(shader.locations.a_position);
webgl.bindBuffer(webgl.ARRAY_BUFFER, null);
webgl.useProgram(null);
webgl.bindTexture(webgl.TEXTURE_2D, null);
webgl.enable(webgl.CULL_FACE);
webgl.enable(webgl.DEPTH_TEST);
webgl.enable(webgl.BLEND);
}
gl.rasterPos[0] += xmove;
gl.rasterPos[1] += ymove;
},
glBlendFunc: function(sfactor, dfactor) {
if (gl.listMode && this.addToList("glBlendFunc", [sfactor, dfactor])) return;
DEBUG > 1 && console.log("glBlendFunc", GL_Symbol(sfactor), GL_Symbol(dfactor));
webgl.blendFunc(sfactor, dfactor);
},
glCallList: function(list) {
if (gl.listMode && this.addToList("glCallList", [list])) return;
DEBUG > 1 && console.log("glCallList", list, "START");
this.executeList(list);
DEBUG > 1 && console.log("glCallList", list, "DONE");
},
glCallLists: function(n, type, lists) {
if (gl.listMode && this.addToList("glCallLists", [n, type, lists])) return;
DEBUG > 1 && console.log("glCallLists", n, GL_Symbol(type), lists);
var array;
switch (type) {
case GL.BYTE:
array = new Int8Array(lists);
break;
case GL.UNSIGNED_BYTE:
array = new Uint8Array(lists);
break;
case GL.INT:
array = new Int32Array(lists);
break;
case GL.UNSIGNED_INT:
array = new Uint32Array(lists);
break;
default:
if (DEBUG) console.log("UNIMPLEMENTED glCallLists type", GL_Symbol(type))
else this.vm.warnOnce("OpenGL: UNIMPLEMENTED glCallLists type " + GL_Symbol(type));
return;
}
for (var i = 0; i < n; i++) {
var list = gl.listBase + array[i];
this.executeList(list);
}
},
glClear: function(mask) {
if (gl.listMode && this.addToList("glClear", [mask])) return;
var maskString = "";
if (mask & webgl.COLOR_BUFFER_BIT) maskString += " COLOR";
if (mask & webgl.DEPTH_BUFFER_BIT) maskString += " DEPTH";
if (mask & webgl.STENCIL_BUFFER_BIT) maskString += " STENCIL";
DEBUG > 1 && console.log("glClear"+ maskString);
webgl.clear(mask);
// B3DAcceleratorPlugin will call vm.breakNow()
// to emulate double buffering (which will return
// control to the browser which will flush the canvas).
// We discourage breaking until then to avoid flicker
// glClear is a good place for that since it's usually
// called at least once per frame
this.vm.breakAfter(500);
},
glClearColor: function(red, green, blue, alpha) {
if (gl.listMode && this.addToList("glClearColor", [red, green, blue, alpha])) return;
DEBUG > 1 && console.log("glClearColor", red, green, blue, alpha);
webgl.clearColor(red, green, blue, alpha);
},
glColor3f: function(red, green, blue) {
if (gl.listMode && this.addToList("glColor3f", [red, green, blue])) return;
DEBUG > 1 && console.log("glColor3f", red, green, blue);
gl.color[0] = red;
gl.color[1] = green;
gl.color[2] = blue;
gl.color[3] = 1;
gl.primitiveAttrs |= HAS_COLOR;
},
glColor3fv: function(v) {
if (gl.listMode && this.addToList("glColor3fv", [v.slice()])) return;
DEBUG > 1 && console.log("glColor3fv", Array.from(v));
gl.color.set(v);
gl.color[3] = 1;
gl.primitiveAttrs |= HAS_COLOR;
},
glColor4d: function(red, green, blue, alpha) {
if (gl.listMode && this.addToList("glColor4d", [red, green, blue, alpha])) return;
DEBUG > 1 && console.log("glColor4d", red, green, blue, alpha);
gl.color[0] = red;
gl.color[1] = green;
gl.color[2] = blue;
gl.color[3] = alpha;
gl.primitiveAttrs |= HAS_COLOR;
},
glColor4f: function(red, green, blue, alpha) {
if (gl.listMode && this.addToList("glColor4f", [red, green, blue, alpha])) return;
DEBUG > 1 && console.log("glColor4f", red, green, blue, alpha);
gl.color[0] = red;
gl.color[1] = green;
gl.color[2] = blue;
gl.color[3] = alpha;
gl.primitiveAttrs |= HAS_COLOR;
},
glColor4fv: function(v) {
if (gl.listMode && this.addToList("glColor4fv", [v.slice()])) return;
DEBUG > 1 && console.log("glColor4fv", Array.from(v));
gl.color.set(v);
gl.primitiveAttrs |= HAS_COLOR;
},
glColorPointer: function(size, type, stride, pointer) {
if (gl.listMode && this.addToList("glColorPointer", [size, type, stride, pointer])) return;
DEBUG > 1 && console.log("glColorPointer", size, GL_Symbol(type), stride, pointer);
gl.clientState.colorArray.size = size;
gl.clientState.colorArray.type = type;
gl.clientState.colorArray.stride = stride;
gl.clientState.colorArray.pointer = pointer;
},
glColorMask: function(red, green, blue, alpha) {
if (gl.listMode && this.addToList("glColorMask", [red, green, blue, alpha])) return;
DEBUG > 1 && console.log("glColorMask", red, green, blue, alpha);
webgl.colorMask(red, green, blue, alpha);
},
glClipPlane: function(plane, equation) {
if (gl.listMode && this.addToList("glClipPlane", [plane, equation])) return;
DEBUG > 1 && console.log("glClipPlane", GL_Symbol(plane), Array.from(equation));
var clipPlane = gl.clipPlanes[plane - GL.CLIP_PLANE0];
// multiply by inverse of modelview matrix
var m = new Float32Array(16);
invertMatrix(gl.matrices[GL.MODELVIEW][0], m);
transposeMatrix(m);
multVec4(m, equation, clipPlane.equation);
},
glDeleteLists: function(list, range) {
DEBUG > 1 && console.log("glDeleteLists", list, range);
for (var i = 0; i < range; i++) {
delete gl.lists[list + i];
}
},
glDeleteTextures: function(n, textures) {
DEBUG > 1 && console.log("glDeleteTextures", n, Array.from(textures));
for (var i = 0; i < n; i++) {
var id = textures[i];
var texture = gl.textures[id];
if (texture) {
webgl.deleteTexture(texture);
if (gl.texture === texture) gl.texture = null;
}
delete gl.textures[id];
}
},
glDepthFunc: function(func) {
if (gl.listMode && this.addToList("glDepthFunc", [func])) return;
DEBUG > 1 && console.log("glDepthFunc", GL_Symbol(func));
webgl.depthFunc(func);
},
glDepthMask: function(flag) {
if (gl.listMode && this.addToList("glDepthMask", [flag])) return;
DEBUG > 1 && console.log("glDepthMask", flag);
webgl.depthMask(flag);
},
glDepthRange: function(zNear, zFar) {
if (gl.listMode && this.addToList("glDepthRange", [zNear, zFar])) return;
DEBUG > 1 && console.log("glDepthRange", zNear, zFar);
webgl.depthRange(zNear, zFar);
},
glDisable: function(cap) {
if (gl.listMode && this.addToList("glDisable", [cap])) return;
switch (cap) {
case GL.ALPHA_TEST:
DEBUG > 1 && console.log("glDisable GL_ALPHA_TEST");
gl.alphaTest = false;
break;
case webgl.BLEND:
DEBUG > 1 && console.log("glDisable GL_BLEND");
webgl.disable(webgl.BLEND);
break;
case GL.CLIP_PLANE0:
case GL.CLIP_PLANE1:
case GL.CLIP_PLANE2:
case GL.CLIP_PLANE3:
case GL.CLIP_PLANE4:
case GL.CLIP_PLANE5:
case GL.CLIP_PLANE6:
case GL.CLIP_PLANE7:
DEBUG > 1 && console.log("glDisable GL_CLIP_PLANE" + (cap - GL.CLIP_PLANE0));
gl.clipPlanes[cap - GL.CLIP_PLANE0].enabled = false;
break;
case webgl.CULL_FACE:
DEBUG > 1 && console.log("glDisable GL.CULL_FACE");
webgl.disable(webgl.CULL_FACE);
break;
case webgl.DEPTH_TEST:
DEBUG > 1 && console.log("glDisable GL_DEPTH_TEST");
webgl.disable(webgl.DEPTH_TEST);
break;
case GL.FOG:
DEBUG > 1 && console.log("glDisable GL_FOG");
gl.fogEnabled = false;
break;
case GL.NORMALIZE:
DEBUG > 1 && console.log("glDisable GL_NORMALIZE");
// we always normalize normals
break;
case GL.LIGHT0:
case GL.LIGHT1:
case GL.LIGHT2:
case GL.LIGHT3:
case GL.LIGHT4:
case GL.LIGHT5:
case GL.LIGHT6:
case GL.LIGHT7:
DEBUG > 1 && console.log("glDisable GL_LIGHT" + (cap - GL.LIGHT0));
gl.lights[cap - GL.LIGHT0].enabled = false;
break;
case GL.LIGHTING:
DEBUG > 1 && console.log("glDisable GL_LIGHTING");
gl.lightingEnabled = false;
break;
case webgl.POLYGON_OFFSET_FILL:
DEBUG > 1 && console.log("glDisable GL_POLYGON_OFFSET_FILL");
webgl.disable(webgl.POLYGON_OFFSET_FILL);
break;
case webgl.STENCIL_TEST:
DEBUG > 1 && console.log("glDisable GL_STENCIL_TEST");
webgl.disable(webgl.STENCIL_TEST);
break;
case webgl.TEXTURE_2D:
DEBUG > 1 && console.log("glDisable GL_TEXTURE_2D");
gl.textureEnabled = false;
break;
case GL.TEXTURE_GEN_S:
case GL.TEXTURE_GEN_T:
case GL.TEXTURE_GEN_R:
case GL.TEXTURE_GEN_Q:
if (DEBUG) console.log("UNIMPLEMENTED glDisable GL_TEXTURE_GEN_" + (cap - GL.TEXTURE_GEN_S));
else this.vm.warnOnce("OpenGL: UNIMPLEMENTED glDisable GL_TEXTURE_GEN_" + (cap - GL.TEXTURE_GEN_S));
break;
default:
if (DEBUG) console.log("UNIMPLEMENTED glDisable", GL_Symbol(cap));
else this.vm.warnOnce("OpenGL: UNIMPLEMENTED glDisable " + GL_Symbol(cap));
}
},
glDisableClientState: function(cap) {
if (gl.listMode && this.addToList("glDisableClientState", [cap])) return;
switch (cap) {
case GL.VERTEX_ARRAY:
DEBUG > 1 && console.log("glDisableClientState GL_VERTEX_ARRAY");
gl.clientState.vertexArray.enabled = false;
return;
case GL.NORMAL_ARRAY:
DEBUG > 1 && console.log("glDisableClientState GL_NORMAL_ARRAY");
gl.clientState.normalArray.enabled = false;
return;
case GL.COLOR_ARRAY:
DEBUG > 1 && console.log("glDisableClientState GL_COLOR_ARRAY");
gl.clientState.colorArray.enabled = false;
return;
case GL.TEXTURE_COORD_ARRAY:
DEBUG > 1 && console.log("glDisableClientState GL_TEXTURE_COORD_ARRAY");
gl.clientState.textureCoordArray.enabled = false;
return;
default:
if (DEBUG) console.log("UNIMPLEMENTED glDisableClientState", GL_Symbol(cap));
else this.vm.warnOnce("OpenGL: UNIMPLEMENTED glDisableClientState " + GL_Symbol(cap));
}
},
glDrawElements: function(mode, count, type, indicesPtr) {
if (gl.listMode && this.addToList("glDrawElements", [mode, count, type, indicesPtr])) return;
var indices;
switch (type) {
case GL.UNSIGNED_BYTE:
indices = new Uint8Array(indicesPtr);
break;
case GL.UNSIGNED_SHORT:
indices = new Uint16Array(indicesPtr);
break;
case GL.UNSIGNED_INT:
// not directly supported by WebGL without OES_element_index_uint
var indices32 = new Uint32Array(indicesPtr);
var max = Math.max.apply(null, indices32);
if (max > 0xFFFF) console.warn("OpenGL: glDrawElements with indices > 65535 not supported, truncating", max);
if (max <= 0xFF) {
indices = new Uint8Array(indices32.length);
type = GL.UNSIGNED_BYTE;
} else {
indices = new Uint16Array(indices32.length);
type = GL.UNSIGNED_SHORT;
}
for (var i = 0; i < count; i++) indices[i] = indices32[i];
break;
default:
if (DEBUG) console.log("UNIMPLEMENTED glDrawElements type", GL_Symbol(type));
else this.vm.warnOnce("OpenGL: UNIMPLEMENTED glDrawElements type " + GL_Symbol(type));
return;
}
var geometryFlags = 0;
if (gl.clientState.normalArray.enabled) geometryFlags |= HAS_NORMAL;
if (gl.clientState.colorArray.enabled) geometryFlags |= HAS_COLOR;
if (gl.clientState.textureCoordArray.enabled) geometryFlags |= HAS_TEXCOORD;
if (mode === GL.POINTS) geometryFlags |= USE_POINT_SIZE;
var shader = this.getShader(geometryFlags);
if (!shader.program) {
if (DEBUG) console.warn("UNIMPLEMENTED glDrawElements shader: " + shader.label);
else this.vm.warnOnce("OpenGL: UNIMPLEMENTED glDrawElements shader: " + shader.label);
return;
}
var vertexArray = gl.clientState.vertexArray;
if (!vertexArray.enabled || !vertexArray.pointer) {
DEBUG > 0 && console.warn("glDrawElements: GL_VERTEX_ARRAY incomplete, skipping");
return;
}
DEBUG > 1 && console.log("glDrawElements", GL_Symbol(mode, 'POINTS'), count, GL_Symbol(type), shader.label, Array.from(indices));
webgl.useProgram(shader.program);
this.setShaderUniforms(shader);
var loc = shader.locations;
var vertexBuffer = webgl.createBuffer();
webgl.bindBuffer(webgl.ARRAY_BUFFER, vertexBuffer);
webgl.bufferData(webgl.ARRAY_BUFFER, vertexArray.pointer, webgl.DYNAMIC_DRAW);
webgl.vertexAttribPointer(loc['aPosition'], vertexArray.size, vertexArray.type, false, vertexArray.stride, 0);
webgl.enableVertexAttribArray(loc['aPosition']);
var normalBuffer;
if (loc['aNormal'] >= 0) {
var normalArray = gl.clientState.normalArray;
normalBuffer = webgl.createBuffer();
webgl.bindBuffer(webgl.ARRAY_BUFFER, normalBuffer);
webgl.bufferData(webgl.ARRAY_BUFFER, normalArray.pointer, webgl.DYNAMIC_DRAW);
webgl.vertexAttribPointer(loc['aNormal'], normalArray.size, normalArray.type, false, normalArray.stride, 0);
webgl.enableVertexAttribArray(loc['aNormal']);
}
var colorBuffer;
if (loc['aColor'] >= 0) {
var colorArray = gl.clientState.colorArray;
colorBuffer = webgl.createBuffer();
webgl.bindBuffer(webgl.ARRAY_BUFFER, colorBuffer);
webgl.bufferData(webgl.ARRAY_BUFFER, colorArray.pointer, webgl.DYNAMIC_DRAW);
webgl.vertexAttribPointer(loc['aColor'], colorArray.size, colorArray.type, false, colorArray.stride, 0);
webgl.enableVertexAttribArray(loc['aColor']);
}
var texCoordBuffer;
if (loc['aTexCoord'] >= 0) {
var texCoordArray = gl.clientState.textureCoordArray;
texCoordBuffer = webgl.createBuffer();
webgl.bindBuffer(webgl.ARRAY_BUFFER, texCoordBuffer);
webgl.bufferData(webgl.ARRAY_BUFFER, texCoordArray.pointer, webgl.DYNAMIC_DRAW);
webgl.vertexAttribPointer(loc['aTexCoord'], texCoordArray.size, texCoordArray.type, false, texCoordArray.stride, 0);
webgl.enableVertexAttribArray(loc['aTexCoord']);
}
var indexBuffer = webgl.createBuffer();
webgl.bindBuffer(webgl.ELEMENT_ARRAY_BUFFER, indexBuffer);
webgl.bufferData(webgl.ELEMENT_ARRAY_BUFFER, indices, webgl.DYNAMIC_DRAW);
webgl.drawElements(mode, indices.length, type, 0);
webgl.useProgram(null);
webgl.bindBuffer(webgl.ELEMENT_ARRAY_BUFFER, null);
webgl.bindBuffer(webgl.ARRAY_BUFFER, null);
webgl.deleteBuffer(indexBuffer);
webgl.disableVertexAttribArray(loc['aPosition']);
webgl.deleteBuffer(vertexBuffer);
if (normalBuffer) {
webgl.disableVertexAttribArray(loc['aNormal']);
webgl.deleteBuffer(normalBuffer);
}
if (colorBuffer) {
webgl.disableVertexAttribArray(loc['aColor']);
webgl.deleteBuffer(colorBuffer);
}
if (texCoordBuffer) {
webgl.disableVertexAttribArray(loc['aTexCoord']);
webgl.deleteBuffer(texCoordBuffer);
}
},
glEnable: function(cap) {
if (gl.listMode && this.addToList("glEnable", [cap])) return;
switch (cap) {
case GL.ALPHA_TEST:
DEBUG > 1 && console.log("glEnable GL_ALPHA_TEST");
gl.alphaTest = true;
break;
case webgl.BLEND:
DEBUG > 1 && console.log("glEnable GL_BLEND");
webgl.enable(webgl.BLEND);
break;
case GL.CLIP_PLANE0:
case GL.CLIP_PLANE1:
case GL.CLIP_PLANE2:
case GL.CLIP_PLANE3:
case GL.CLIP_PLANE4:
case GL.CLIP_PLANE5:
case GL.CLIP_PLANE6:
case GL.CLIP_PLANE7:
DEBUG > 1 && console.log("glEnable GL_CLIP_PLANE" + (cap - GL.CLIP_PLANE0));
gl.clipPlanes[cap - GL.CLIP_PLANE0].enabled = true;
break;
case webgl.CULL_FACE:
DEBUG > 1 && console.log("glEnable GL_CULL_FACE");
webgl.enable(webgl.CULL_FACE);
break;
case webgl.DEPTH_TEST:
DEBUG > 1 && console.log("glEnable GL_DEPTH_TEST");
webgl.enable(webgl.DEPTH_TEST);
break;
case GL.FOG:
DEBUG > 1 && console.log("glEnable GL_FOG");
gl.fogEnabled = true;
break;
case GL.NORMALIZE:
DEBUG > 1 && console.log("glEnable GL_NORMALIZE");
// we always normalize normals
break;
case GL.LIGHT0:
case GL.LIGHT1:
case GL.LIGHT2:
case GL.LIGHT3:
case GL.LIGHT4:
case GL.LIGHT5:
case GL.LIGHT6:
case GL.LIGHT7:
DEBUG > 1 && console.log("glEnable GL_LIGHT" + (cap - GL.LIGHT0));
gl.lights[cap - GL.LIGHT0].enabled = true;
break;
case GL.LIGHTING:
DEBUG > 1 && console.log("glEnable GL_LIGHTING");
gl.lightingEnabled = true;
break;
case webgl.POLYGON_OFFSET_FILL:
DEBUG > 1 && console.log("glEnable GL_POLYGON_OFFSET_FILL");
webgl.enable(webgl.POLYGON_OFFSET_FILL);
break;
case webgl.STENCIL_TEST:
DEBUG > 1 && console.log("glEnable GL_STENCIL_TEST");
webgl.enable(webgl.STENCIL_TEST);
break;
case webgl.TEXTURE_2D:
DEBUG > 1 && console.log("glEnable GL_TEXTURE_2D");
gl.textureEnabled = true;
break;
case GL.TEXTURE_GEN_S:
case GL.TEXTURE_GEN_T:
case GL.TEXTURE_GEN_R:
case GL.TEXTURE_GEN_Q:
if (DEBUG) console.log("UNIMPLEMENTED glEnable GL_" + GL_Symbol(cap, "TEXTURE_GEN_S"));
else this.vm.warnOnce("OpenGL: UNIMPLEMENTED glEnable GL_" + GL_Symbol(cap, "TEXTURE_GEN_S"));
break;
default:
if (DEBUG) console.log("UNIMPLEMENTED glEnable", GL_Symbol(cap));
else this.vm.warnOnce("OpenGL: UNIMPLEMENTED glEnable " + GL_Symbol(cap));
}
},
glEnableClientState: function(cap) {
if (gl.listMode && this.addToList("glEnableClientState", [cap])) return;
switch (cap) {
case GL.VERTEX_ARRAY:
DEBUG > 1 && console.log("glEnableClientState GL_VERTEX_ARRAY");
gl.clientState.vertexArray.enabled = true;
return;
case GL.NORMAL_ARRAY:
DEBUG > 1 && console.log("glEnableClientState GL_NORMAL_ARRAY");
gl.clientState.normalArray.enabled = true;
return;
case GL.COLOR_ARRAY:
DEBUG > 1 && console.log("glEnableClientState GL_COLOR_ARRAY");
gl.clientState.colorArray.enabled = true;
return;
case GL.TEXTURE_COORD_ARRAY:
DEBUG > 1 && console.log("glEnableClientState GL_TEXTURE_COORD_ARRAY");
gl.clientState.textureCoordArray.enabled = true;
return;
default:
if (DEBUG) console.log("UNIMPLEMENTED glEnableClientState", GL_Symbol(cap));
else this.vm.warnOnce("OpenGL: UNIMPLEMENTED glEnableClientState " + GL_Symbol(cap));
}
},
glFog: function(pname, param) {
if (gl.listMode && this.addToList("glFog", [pname, param])) return;
switch (pname) {
case GL.FOG_MODE:
gl.fogMode = param;
DEBUG > 1 && console.log("glFog GL_FOG_MODE", GL_Symbol(param));
break;
case GL.FOG_DENSITY:
DEBUG > 1 && console.log("glFog GL_FOG_DENSITY", param);
gl.fogDensity = param;
break;
case GL.FOG_START:
DEBUG > 1 && console.log("glFog GL_FOG_START", param);
gl.fogStart = param;
break;
case GL.FOG_END:
DEBUG > 1 && console.log("glFog GL_FOG_END", param);
gl.fogEnd = param;
break;
case GL.FOG_COLOR:
DEBUG > 1 && console.log("glFog GL_FOG_COLOR", Array.from(param));
gl.fogColor.set(param);
break;
default:
if (DEBUG) console.log("UNIMPLEMENTED glFog", GL_Symbol(pname), param);
else this.vm.warnOnce("OpenGL: UNIMPLEMENTED glFog " + GL_Symbol(pname));
}
},
glFogi: function(pname, param) {
this.glFog(pname, param);
},
glFogf: function(pname, param) {
this.glFog(pname, param);
},
glFogiv: function(pname, params) {
// FOG_COLOR integer values are mapped linearly such that the most positive representable value maps to 1.0,
// and the most negative representable value maps to -1.0
this.glFog(pname, pname === GL.FOG_COLOR
? params.map(function(x) { return (x + 0.5) / (0x7FFFFFFF + 0.5); })
: params[0]);
},
glFogfv: function(pname, params) {
this.glFog(pname, pname === GL.FOG_COLOR ? params : params[0]);
},
getShader: function(geometryFlags) {
// geometryFlags: HAS_TEXCOORD, HAS_NORMAL, HAS_COLOR, USE_POINT_SIZE
var shaderFlags = geometryFlags;
if (gl.textureEnabled && gl.texture) shaderFlags |= USE_TEXTURE;