-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
1179 lines (1063 loc) · 35.4 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<!-- These examples based on https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Tutorial -->
<html>
<head>
<title>WebGL Play</title>
<meta charset="utf-8">
<style>
canvas {
border: 2px solid black;
background-color: black;
}
</style>
<script src="lib/gl-matrix-min.js" ></script>
<!--<script src="https://cdnjs.cloudflare.com/ajax/libs/gl-matrix/2.8.1/gl-matrix-min.js"
integrity="sha512-zhHQR0/H5SEBL3Wn6yYSaTTZej12z0hVZKOv3TwCUXT1z5qeqGcXJLLrbERYRScEDDpYIJhPC1fk31gqR783iQ=="
crossorigin="anonymous"></script>-->
<script>
if(typeof mat4 === 'undefined'){
mat4 = glMatrix.mat4;
}
</script>
</head>
<body>
<div id="msgBlk">
<!-- -->
<h1>WebGL Test 1</h1>
<canvas id="canvas-1" width="600" height="400">Canvas not supported!</canvas>
<script defer>
function test1(){
// first, get canvas element by ID
const canvas = document.querySelector('#canvas-1');
// Initialize the GL context
const gl = canvas.getContext('webgl');
// check if WebGL is not supported
if (!gl) {
// no WebGL :(
alert('Unable to initialize WebGL. Your browser or machine may not support it.');
return;
}
// Set clear color to dark blue, fully opaque
gl.clearColor(0.0, 0.0, 0.30, 1.0);
// Clear the color buffer with specified clear color
gl.clear(gl.COLOR_BUFFER_BIT);
}
test1();
</script>
<!-- -->
<h1>WebGL Test 2</h1>
<div>FPS: <span id="fps-2">?</span></div>
<canvas id="canvas-2" width="600" height="400">Canvas not supported!</canvas>
<script>
function initWebGL(canvasID){
// first, get canvas element by ID
const canvas = document.querySelector('#'+canvasID);
// Initialize the GL context
const gl = canvas.getContext('webgl');
// check if WebGL is not supported
if (!gl) {
// no WebGL :(
return null;
}
return gl;
}
// compile shader program
function loadShader(gl, type, source) {
const shader = gl.createShader(type);
// Send the source to the shader object
gl.shaderSource(shader, source);
// Compile the shader program
gl.compileShader(shader);
// See if it compiled successfully
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
alert('An error occurred compiling the shaders: ' + gl.getShaderInfoLog(shader));
gl.deleteShader(shader);
return null;
}
return shader;
}
// Initialize a shader program, so WebGL knows how to draw our data
function initShaderProgram(gl, vsSource, fsSource) {
const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);
if(!vertexShader){throw('Failed to compile vertex shader program');}
const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);
if(!fragmentShader){throw('Failed to compile fragment shader program');}
// Create the shader program
const shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertexShader);
gl.attachShader(shaderProgram, fragmentShader);
gl.linkProgram(shaderProgram);
// If creating the shader program failed, alert
if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
alert('Unable to initialize the shader program: ' + gl.getProgramInfoLog(shaderProgram));
return null;
}
return shaderProgram;
}
var test2 = {
framecounter: 0,
// initialize vertex buffers
initBuffers: function(gl){
// make a graphics buffer (handle)
const vertexBuffer = gl.createBuffer();
// then load the data into the graphics buffer
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
gl.bufferData(
gl.ARRAY_BUFFER,
new Float32Array([
-1.0, 1.0,
1.0, 1.0,
-1.0, -1.0,
1.0, -1.0
]),
gl.STATIC_DRAW
);
return {myquad: vertexBuffer}
},
// draw cycle
drawScene: function(gl, shaderProgramData, buffers, time_ms){
const pi = Math.PI;
//
gl.clearColor(0.0, 0.0, 0.30, 1.0); // Paint background color dark blue, fully opaque
gl.clearDepth(1.0); // clear the scene
gl.enable(gl.DEPTH_TEST); // enable depth
gl.depthFunc(gl.LEQUAL); // hide far stuff behind close stuff
// clear the canvas
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
// set perspective
const fieldOfView = 45 * pi / 180; //// in radians
const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
const zNear = 0.1; // depth clipping
const zFar = 100.0;// depth clipping
const projectionMatrix = mat4.create();
mat4.perspective(
projectionMatrix, // first arg is destination
fieldOfView,
aspect,
zNear,
zFar
);
// now position the 3D model
const modelViewMatrix = mat4.create();
mat4.translate(modelViewMatrix, // move model away from viewer
modelViewMatrix, [0.0, 0.0, -4]);
const period_ms = 4000;
const rotation = (time_ms % period_ms) / period_ms * pi;
mat4.rotate(
modelViewMatrix, modelViewMatrix,
rotation,
[0, 0, 1] // Z-axis rotation
);
// set model buffer and shader data
const vectorSize = 2; // 2D vertices
const type = gl.FLOAT; // 32bit floats in buffer
const normalize = false; // disable normalizing
const stride = 0; // disable stride
const offset = 0; // start of data in buffer
gl.bindBuffer(gl.ARRAY_BUFFER, buffers.myquad);
gl.vertexAttribPointer(
shaderProgramData.attribLocations.vertexPosition,
vectorSize,
type,
normalize,
stride,
offset
);
gl.enableVertexAttribArray(shaderProgramData.attribLocations.vertexPosition);
gl.useProgram(shaderProgramData.shader);
// set shader uniforms (eg lighting)
gl.uniformMatrix4fv(
shaderProgramData.uniformLocations.projectionMatrix,
false,
projectionMatrix
);
gl.uniformMatrix4fv(
shaderProgramData.uniformLocations.modelViewMatrix,
false,
modelViewMatrix
);
// FINALLY, draw triangles from the vertex buffer
const vertexCount = 4;
gl.drawArrays(gl.TRIANGLE_STRIP, offset, vertexCount);
},
// test 2 main
main: function(){
const gl = initWebGL("canvas-2");
if(gl === null) return; // WebGL not supported :(
// shaders
const vectorShaderSrc = `
attribute vec4 aVertexPosition;
uniform mat4 uModelViewMatrix;
uniform mat4 uProjectionMatrix;
void main() {
gl_Position = uProjectionMatrix * uModelViewMatrix * aVertexPosition;
}
`;
const fragmentShaderSrc = `
void main() {
gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
}
`;
// shake-and-bake the shader code
const shaderProgram = initShaderProgram(gl, vectorShaderSrc, fragmentShaderSrc);
// graphics program parameters (aka uniforms)
const shaderProgramData = {
shader: shaderProgram,
// uniforms and attributes defined in vector shader program
attribLocations: {
vertexPosition: gl.getAttribLocation(shaderProgram, 'aVertexPosition'),
},
uniformLocations: {
projectionMatrix: gl.getUniformLocation(shaderProgram, 'uProjectionMatrix'),
modelViewMatrix: gl.getUniformLocation(shaderProgram, 'uModelViewMatrix'),
},
};
// create 3D model data and store it in the graphics buffer
const buffers = this.initBuffers(gl);
// draw the graphics buffers to the scene with animation
const renderLoop = function(time_ms){ // closure callback looping
test2.drawScene(gl, shaderProgramData, buffers, time_ms);
test2.framecounter = test2.framecounter + 1;
requestAnimationFrame(renderLoop);
}
requestAnimationFrame(renderLoop);
// finally, show FPS in HTML (because text rendering in GL is ****!)
const fpsUpdateInterval = 250;
window.setInterval(function(){
document.querySelector('#fps-2').textContent = 1000*(test2.framecounter / fpsUpdateInterval);
test2.framecounter = 0;
}, fpsUpdateInterval);
}
}
test2.main();
</script>
<!-- -->
<h1>WebGL Test 3</h1>
<div>FPS: <span id="fps-3">?</span></div>
<canvas id="canvas-3" width="600" height="400">Canvas not supported!</canvas>
<script>
var test3 = {
framecounter: 0,
// initialize vertex buffers
initBuffers: function(gl){
// make a graphics buffer (handle)
const vertexBuffer = gl.createBuffer();
// then load the data into the graphics buffer
/* NOTE:
gl.bindBuffer and gl.bufferData - enums
gl.ARRAY_BUFFER which represents vertex data.
gl.ELEMENT_ARRAY_BUFFER which represents index data.
gl.STATIC_DRAW − Data will be specified once and used many times.
gl.STREAM_DRAW − Data will be specified once and used a few times.
gl.DYNAMIC_DRAW − Data will be specified repeatedly and used many times.
*/
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
gl.bufferData(
gl.ARRAY_BUFFER,
new Float32Array([
/* 2-----3
/| /|
/ | / |
6-----7 |
| 0--|--1
| / | /
|/ |/
4-----5 */
-1.0, -1.0, -1.0, // index #0
1.0, -1.0, -1.0, // index #1
-1.0, 1.0, -1.0, // index #2
1.0, 1.0, -1.0, // index #3
-1.0, -1.0, 1.0, // index #4
1.0, -1.0, 1.0, // index #5
-1.0, 1.0, 1.0, // index #6
1.0, 1.0, 1.0, // index #7
]),
gl.STATIC_DRAW
);
const indexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
gl.bufferData(
gl.ELEMENT_ARRAY_BUFFER,
new Uint16Array([
4,5,7, 7,6,4, // front quad
1,0,2, 2,3,1, // back quad
0,4,6, 6,2,0, // left quad
1,3,7, 7,5,1, // right quad
0,1,5, 5,4,0, // bottom quad
2,6,7, 7,3,2, // top quad
]),
gl.STATIC_DRAW
);
// load color data
const colors = [
0.0, 0.0, 0.0, 1.0, // black
0.5, 0.5, 0.0, 1.0, // brown
1.0, 0.0, 0.0, 1.0, // red
1.0, 0.5, 0.0, 1.0, // orange
1.0, 1.0, 0.0, 1.0, // yellow
0.0, 1.0, 0.0, 1.0, // green
0.0, 0.0, 1.0, 1.0, // blue
0.5, 0.0, 1.0, 1.0, // violet
];
const colorBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);
// return
return {cubeVerts: vertexBuffer, cubeIdxs: indexBuffer, qcolor: colorBuffer}
},
// draw cycle
drawScene: function(gl, shaderProgramData, buffers, time_ms){
const pi = Math.PI;
//
gl.clearColor(0.0, 0.0, 0.30, 1.0); // Paint background color dark blue, fully opaque
gl.clearDepth(1.0); // clear the scene
gl.enable(gl.DEPTH_TEST); // enable depth
gl.depthFunc(gl.LEQUAL); // hide far stuff behind close stuff
// clear the canvas
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
// set perspective
const fieldOfView = 45 * pi / 180; //// in radians
const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
const zNear = 0.1; // depth clipping
const zFar = 100.0;// depth clipping
const projectionMatrix = mat4.create();
mat4.perspective(
projectionMatrix, // first arg is destination
fieldOfView,
aspect,
zNear,
zFar
);
// now position the 3D model
const modelViewMatrix = mat4.create();
mat4.translate(modelViewMatrix, // move model away from viewer
modelViewMatrix, [0.0, 0.0, -4]);
const period_ms = 2000;
const rotation = (time_ms % (period_ms*3)) / (period_ms*3) * 2 * pi;
const rotation2 = (time_ms % (period_ms*5)) / (period_ms*5) * 2 * pi;
mat4.rotate(
modelViewMatrix, modelViewMatrix,
-1*rotation,
[0, 0, 1] // Z-axis rotation
);
mat4.rotate(
modelViewMatrix, modelViewMatrix,
-1*rotation2,
[0, 1, 0] // Y-axis rotation
);
// set model buffer and shader data
{
const vectorSize = 3; // 3D vertices
const type = gl.FLOAT; // 32bit floats in buffer
const normalize = false; // disable normalizing
const stride = 0; // disable stride
const offset = 0; // start of data in buffer
gl.bindBuffer(gl.ARRAY_BUFFER, buffers.cubeVerts);
gl.vertexAttribPointer(
shaderProgramData.attribLocations.vertexPosition,
vectorSize,
type,
normalize,
stride,
offset
);
gl.enableVertexAttribArray(shaderProgramData.attribLocations.vertexPosition);
gl.useProgram(shaderProgramData.shader);
// set shader uniforms (eg lighting)
gl.uniformMatrix4fv(
shaderProgramData.uniformLocations.projectionMatrix,
false,
projectionMatrix
);
gl.uniformMatrix4fv(
shaderProgramData.uniformLocations.modelViewMatrix,
false,
modelViewMatrix
);
}
// add color
{
const numComponents = 4;
const type = gl.FLOAT;
const normalize = false;
const stride = 0;
const offset = 0;
gl.bindBuffer(gl.ARRAY_BUFFER, buffers.qcolor);
gl.vertexAttribPointer(
shaderProgramData.attribLocations.vertexColor,
numComponents,
type,
normalize,
stride,
offset);
gl.enableVertexAttribArray(
shaderProgramData.attribLocations.vertexColor);
}
// FINALLY, draw triangles from the vertex buffer with the index buffer
{
const indexCount = 6*6;
const offset = 0;
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffers.cubeIdxs);
gl.drawElements(gl.TRIANGLES, indexCount, gl.UNSIGNED_SHORT, offset);
}
},
// test 3 main
main: function(){
const gl = initWebGL("canvas-3");
if(gl === null) return; // WebGL not supported :(
// shaders
const vectorShaderSrc = `
attribute vec4 aVertexPosition;
attribute vec4 aVertexColor;
uniform mat4 uModelViewMatrix;
uniform mat4 uProjectionMatrix;
varying lowp vec4 vColor;
void main(void) {
gl_Position = uProjectionMatrix * uModelViewMatrix * aVertexPosition;
vColor = aVertexColor;
}
`;
const fragmentShaderSrc = `
varying lowp vec4 vColor;
void main(void) {
gl_FragColor = vColor;
}
`;
// shake-and-bake the shader code
const shaderProgram = initShaderProgram(gl, vectorShaderSrc, fragmentShaderSrc);
// graphics program parameters (aka uniforms)
const shaderProgramData = {
shader: shaderProgram,
// uniforms and attributes defined in vector shader program
attribLocations: {
vertexPosition: gl.getAttribLocation(shaderProgram, 'aVertexPosition'),
vertexColor: gl.getAttribLocation(shaderProgram, 'aVertexColor'),
},
uniformLocations: {
projectionMatrix: gl.getUniformLocation(shaderProgram, 'uProjectionMatrix'),
modelViewMatrix: gl.getUniformLocation(shaderProgram, 'uModelViewMatrix'),
},
};
// create 3D model data and store it in the graphics buffer
const buffers = this.initBuffers(gl);
// draw the graphics buffers to the scene with animation
const renderLoop = function(time_ms){ // closure callback looping
test3.drawScene(gl, shaderProgramData, buffers, time_ms);
test3.framecounter = test3.framecounter + 1;
requestAnimationFrame(renderLoop);
}
requestAnimationFrame(renderLoop);
// finally, show FPS in HTML (because text rendering in GL is ****!)
const fpsUpdateInterval = 250;
window.setInterval(function(){
document.querySelector('#fps-3').textContent = 1000*(test3.framecounter / fpsUpdateInterval);
test3.framecounter = 0;
}, fpsUpdateInterval);
}
}
test3.main();
</script>
<!-- -->
<h1>WebGL Test 4</h1>
<div>FPS: <span id="fps-4">?</span></div>
<canvas id="canvas-4" width="600" height="400">Canvas not supported!</canvas>
<script>
texture1DataURI = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAA7DAAAOwwHHb6hkAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAAAcdJREFUOI2Nk0trE2EUhp+5Of3aCCMYE9BW8bIwi7gqrhRBQdx0oYKkCO5ciAt/g5BVESqtCIrFCxYLKngFRSi40RSxEkh3NTgBoY1NA51kbpkZF1KkMxP0wLs57/O9nHPgk15GUURKmWaNO7evMl66TqF4LA0BQDaAuIZ8l8kHFxGjGjfvXoJ2M8FsSt4BxDV97wrm8BIDikwr95PJ6csJZlOJCbrNBu+ac3iSR0YdwA1cPq6+ob5USZ8g3ph5PYE34qIrOgqgazpqXmH27a3UADXD1ht+W1ugl+2hSRqDukBTNCzHYnFtgTgLoEKw9fpdE6EI7J5NGAZYjoXYJmhsNIizAPKf5l9ZvkUQBeREDkVWMYYMwijEDmw27DZxPhFwSBzACz1abgtZk3E8B9d32Z/Zx3Yx+O+AG2Nldv3I4oc+1ZEqju9g/DKYuFBOPIYAqfZlPnGZlXaTx4vPeXjtKePls5SOjjGc3Z3YH0Ctfv6UapwSRWbUJ5zeeYT1ZZP1ZbNPQKWSasyfryH5ElN77nPiWSGVAVA73U6q8fVknTPnDvJhts7oo739A7qd9IDDr/K8n/tO4UWefgyAVDpeTP3O/1u/AaLcv2vVmnEBAAAAAElFTkSuQmCC";
function isPowerOf2(number){
if(number === 1024 || number === 512 || number === 256 || number === 128 || number === 64 || number === 32 || number === 16 || number === 8 || number === 4 || number === 2 || number === 2 || number === 1){
return true;
} else {
var n = 2048;
while(n < number){
n *= 2;
}
if(n === number){
return true;
}
}
return false;
}
var test4 = {
framecounter: 0,
// initialize vertex buffers
initBuffers: function(gl){
// load a graphics buffer for vertex data
const cubeVertices = [
-1.0, -1.0, -1.0, // index #0
1.0, -1.0, -1.0, // index #1
-1.0, 1.0, -1.0, // index #2
1.0, 1.0, -1.0, // index #3
-1.0, -1.0, 1.0, // index #4
1.0, -1.0, 1.0, // index #5
-1.0, 1.0, 1.0, // index #6
1.0, 1.0, 1.0, // index #7
]
const vertexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
gl.bufferData(
gl.ARRAY_BUFFER,
new Float32Array(cubeVertices),
gl.STATIC_DRAW
);
const cubeIndices = [
4,5,7, 7,6,4, // front quad
1,0,2, 2,3,1, // back quad
0,4,6, 6,2,0, // left quad
1,3,7, 7,5,1, // right quad
0,1,5, 5,4,0, // bottom quad
2,6,7, 7,3,2, // top quad
]
const indexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
gl.bufferData(
gl.ELEMENT_ARRAY_BUFFER,
new Uint16Array(cubeIndices),
gl.STATIC_DRAW
);
// load texture data
/* 2-----3
/| /|
/ | / |
6-----7 |
| 0--|--1
| / | /
|/ |/
4-----5 */
const textureCoordinates = [ // manually doing this SUCKS! Use a 3D model file format!
// Note: gl.ELEMENT_ARRAY_BUFFER for 3-per-triangle coordinates (matches index buffer)
// gl.ARRAY_BUFFER for per-vertex coordinates (matches vertex buffer)
0,0, // index #0
1,0, // index #1
0,1, // index #2
1,1, // index #3
1,1, // index #4
0,1, // index #5
1,0, // index #6
0,0, // index #7
];
const texture = gl.createTexture();
{
gl.bindTexture(gl.TEXTURE_2D, texture);
const level = 0; // Mipmap level
const internalFormat = gl.RGBA;
const srcFormat = gl.RGBA;
const srcType = gl.UNSIGNED_BYTE;
const image = new Image(); // HTML Image Element outside the DOM
image.onload = function() {
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texImage2D(
gl.TEXTURE_2D, level, internalFormat,
srcFormat, srcType, image
// image can be ImageData, HTMLImageElement, HTMLVideoElement, or HTMLCanvasElement
// or replace [srcFormat, srcType, image]
// with [width, height, border, format, type, ArrayBufferView srcData, srcOffset]
);
// go ahead with mip-mapping the image if possible
if (isPowerOf2(image.width) && isPowerOf2(image.height)) {
gl.generateMipmap(gl.TEXTURE_2D);
} else {
// non power-of-2 mips not supported
// Note: S = U = X dimension of image, T = V = Y dimension
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
}
};
image.src = texture1DataURI;
}
const textureCoordBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, textureCoordBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(textureCoordinates), gl.STATIC_DRAW);
// load color data
const colors = [
0.0, 0.0, 0.0, 1.0, // black
0.5, 0.5, 0.0, 1.0, // brown
1.0, 0.0, 0.0, 1.0, // red
1.0, 0.5, 0.0, 1.0, // orange
1.0, 1.0, 0.0, 1.0, // yellow
0.0, 1.0, 0.0, 1.0, // green
0.0, 0.0, 1.0, 1.0, // blue
0.5, 0.0, 1.0, 1.0, // violet
];
const colorBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);
// return
return {cubeVerts: vertexBuffer, cubeIdxs: indexBuffer, cubeTex: texture, cubeTexCoords: textureCoordBuffer}
},
// draw cycle
drawScene: function(gl, shaderProgramData, buffers, time_ms){
const pi = Math.PI;
//
gl.clearColor(0.0, 0.0, 0.30, 1.0); // Paint background color dark blue, fully opaque
gl.clearDepth(1.0); // clear the scene
gl.enable(gl.DEPTH_TEST); // enable depth
gl.depthFunc(gl.LEQUAL); // hide far stuff behind close stuff
// clear the canvas
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
// set perspective
const fieldOfView = 45 * pi / 180; //// in radians
const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
const zNear = 0.1; // depth clipping
const zFar = 100.0;// depth clipping
const projectionMatrix = mat4.create();
mat4.perspective(
projectionMatrix, // first arg is destination
fieldOfView,
aspect,
zNear,
zFar
);
// now position the 3D model
const modelViewMatrix = mat4.create();
mat4.translate(modelViewMatrix, // move model away from viewer
modelViewMatrix, [0.0, 0.0, -4]);
const period_ms = 2000;
const rotation = (time_ms % (period_ms*3)) / (period_ms*3) * 2 * pi;
const rotation2 = (time_ms % (period_ms*5)) / (period_ms*5) * 2 * pi;
mat4.rotate(
modelViewMatrix, modelViewMatrix,
-1*rotation,
[0, 0, 1] // Z-axis rotation
);
mat4.rotate(
modelViewMatrix, modelViewMatrix,
-1*rotation2,
[0, 1, 0] // Y-axis rotation
);
// set model buffer and shader data
{
const vectorSize = 3; // 3D vertices
const type = gl.FLOAT; // 32bit floats in buffer
const normalize = false; // disable normalizing
const stride = 0; // disable stride
const offset = 0; // start of data in buffer
gl.bindBuffer(gl.ARRAY_BUFFER, buffers.cubeVerts);
gl.vertexAttribPointer(
shaderProgramData.attribLocations.vertexPosition,
vectorSize,
type,
normalize,
stride,
offset
);
gl.enableVertexAttribArray(shaderProgramData.attribLocations.vertexPosition);
gl.useProgram(shaderProgramData.shader);
// set shader uniforms (eg lighting)
gl.uniformMatrix4fv(
shaderProgramData.uniformLocations.projectionMatrix,
false,
projectionMatrix
);
gl.uniformMatrix4fv(
shaderProgramData.uniformLocations.modelViewMatrix,
false,
modelViewMatrix
);
}
// texture
{
const vecSize = 2; // texture coordinates are 2D
const type = gl.FLOAT; // 32 bit float
const normalize = false;
const stride = 0;
const offset = 0;
gl.bindBuffer(gl.ARRAY_BUFFER, buffers.cubeTexCoords);
gl.vertexAttribPointer(shaderProgramData.attribLocations.textureCoord, vecSize, type, normalize, stride, offset);
gl.enableVertexAttribArray(shaderProgramData.attribLocations.textureCoord);
}
// FINALLY, draw triangles from the vertex buffer with the index buffer
{
const indexCount = 6*6;
const offset = 0;
gl.activeTexture(gl.TEXTURE0);
// Bind the texture to texture unit 0
gl.bindTexture(gl.TEXTURE_2D, buffers.cubeTex);
// Tell the shader we bound the texture to texture unit 0
gl.uniform1i(shaderProgramData.uniformLocations.texSampler, 0);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffers.cubeIdxs);
gl.drawElements(gl.TRIANGLES, indexCount, gl.UNSIGNED_SHORT, offset);
}
},
// test 4 main
main: function(){
const gl = initWebGL("canvas-4");
if(gl === null) return; // WebGL not supported :(
// shaders
const vectorShaderSrc = `
attribute vec4 aVertexPosition;
attribute vec2 aTextureCoord;
uniform mat4 uModelViewMatrix;
uniform mat4 uProjectionMatrix;
varying highp vec2 vTextureCoord;
void main(void) {
gl_Position = uProjectionMatrix * uModelViewMatrix * aVertexPosition;
vTextureCoord = aTextureCoord;
}
`;
const fragmentShaderSrc = `
uniform sampler2D uSampler;
varying highp vec2 vTextureCoord;
void main(void) {
gl_FragColor = texture2D(uSampler, vTextureCoord);
}
`;
// shake-and-bake the shader code
const shaderProgram = initShaderProgram(gl, vectorShaderSrc, fragmentShaderSrc);
// graphics program parameters (aka uniforms)
const shaderProgramData = {
shader: shaderProgram,
// uniforms and attributes defined in vector shader program
attribLocations: {
vertexPosition: gl.getAttribLocation(shaderProgram, 'aVertexPosition'),
textureCoord: gl.getAttribLocation(shaderProgram, 'aTextureCoord'),
},
uniformLocations: {
projectionMatrix: gl.getUniformLocation(shaderProgram, 'uProjectionMatrix'),
modelViewMatrix: gl.getUniformLocation(shaderProgram, 'uModelViewMatrix'),
texSampler: gl.getUniformLocation(shaderProgram, 'uSampler'),
},
};
// create 3D model data and store it in the graphics buffer
const buffers = this.initBuffers(gl);
// draw the graphics buffers to the scene with animation
const renderLoop = function(time_ms){ // closure callback looping
test4.drawScene(gl, shaderProgramData, buffers, time_ms);
test4.framecounter = test4.framecounter + 1;
requestAnimationFrame(renderLoop);
}
requestAnimationFrame(renderLoop);
// finally, show FPS in HTML (because text rendering in GL is ****!)
const fpsUpdateInterval = 250;
window.setInterval(function(){
document.querySelector('#fps-4').textContent = 1000*(test4.framecounter / fpsUpdateInterval);
test4.framecounter = 0;
}, fpsUpdateInterval);
}
}
test4.main();
</script>
<!-- -->
<h1>WebGL Test 5</h1>
<div>FPS: <span id="fps-5">?</span></div>
<canvas id="canvas-5" width="600" height="400">Canvas not supported!</canvas>
<script>
var test5 = {
framecounter: 0,
// initialize vertex buffers
initBuffers: function(gl){
// load a graphics buffer for vertex data
const cubeVertices = [
-1.0, -1.0, -1.0, // index #0
1.0, -1.0, -1.0, // index #1
-1.0, 1.0, -1.0, // index #2
1.0, 1.0, -1.0, // index #3
-1.0, -1.0, 1.0, // index #4
1.0, -1.0, 1.0, // index #5
-1.0, 1.0, 1.0, // index #6
1.0, 1.0, 1.0, // index #7
]
const vertexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
gl.bufferData(
gl.ARRAY_BUFFER,
new Float32Array(cubeVertices),
gl.STATIC_DRAW
);
const cubeIndices = [
4,5,7, 7,6,4, // front quad
1,0,2, 2,3,1, // back quad
0,4,6, 6,2,0, // left quad
1,3,7, 7,5,1, // right quad
0,1,5, 5,4,0, // bottom quad
2,6,7, 7,3,2, // top quad
]
const indexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
gl.bufferData(
gl.ELEMENT_ARRAY_BUFFER,
new Uint16Array(cubeIndices),
gl.STATIC_DRAW
);
/* 2-----3
/| /|
/ | / |
6-----7 |
| 0--|--1
| / | /
|/ |/
4-----5 */
// surface normals - manually doing this SUCKS! Use a 3D model file format or cross-product!
const normalVectors = [
// front
0,0,1, 0,0,1, 0,0,1, 0,0,1, 0,0,1, 0,0,1,
// back
0,0,-1, 0,0,-1, 0,0,-1, 0,0,-1, 0,0,-1, 0,0,-1,
// left
-1,0,0, -1,0,0, -1,0,0, -1,0,0, -1,0,0, -1,0,0,
// right
1,0,0, 1,0,0, 1,0,0, 1,0,0, 1,0,0, 1,0,0,
// bottom
0,-1,0, 0,-1,0, 0,-1,0, 0,-1,0, 0,-1,0, 0,-1,0,
// top
0,1,0, 0,1,0, 0,1,0, 0,1,0, 0,1,0, 0,1,0,
];
const normalBuffer = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, normalBuffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Float32Array(normalVectors), gl.STATIC_DRAW);
// load texture data
const textureCoordinates = [ // manually doing this SUCKS! Use a 3D model file format!
0,0, // index #0
1,0, // index #1
0,1, // index #2
1,1, // index #3
1,1, // index #4
0,1, // index #5
1,0, // index #6
0,0, // index #7
];
const texture = gl.createTexture();
{
gl.bindTexture(gl.TEXTURE_2D, texture);
const level = 0; // Mipmap level
const internalFormat = gl.RGBA;
const srcFormat = gl.RGBA;
const srcType = gl.UNSIGNED_BYTE;
const image = new Image(); // HTML Image Element outside the DOM
image.onload = function() {
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texImage2D(
gl.TEXTURE_2D, level, internalFormat,
srcFormat, srcType, image
// image can be ImageData, HTMLImageElement, HTMLVideoElement, or HTMLCanvasElement
// or replace [srcFormat, srcType, image]
// with [width, height, border, format, type, ArrayBufferView srcData, srcOffset]
);
// go ahead with mip-mapping the image if possible
if (isPowerOf2(image.width) && isPowerOf2(image.height)) {
gl.generateMipmap(gl.TEXTURE_2D);
} else {
// non power-of-2 mips not supported
// Note: S = U = X dimension of image, T = V = Y dimension
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
}
};
image.src = texture1DataURI;
}
const textureCoordBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, textureCoordBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(textureCoordinates), gl.STATIC_DRAW);
// load color data
const colors = [
0.0, 0.0, 0.0, 1.0, // black
0.5, 0.5, 0.0, 1.0, // brown
1.0, 0.0, 0.0, 1.0, // red
1.0, 0.5, 0.0, 1.0, // orange
1.0, 1.0, 0.0, 1.0, // yellow
0.0, 1.0, 0.0, 1.0, // green
0.0, 0.0, 1.0, 1.0, // blue
0.5, 0.0, 1.0, 1.0, // violet
];
const colorBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);
// return
return {cubeVerts: vertexBuffer, cubeIdxs: indexBuffer, cubeTex: texture, cubeTexCoords: textureCoordBuffer, cubeNorms: normalBuffer}
},
// draw cycle
drawScene: function(gl, shaderProgramData, buffers, time_ms){
const pi = Math.PI;
//
gl.clearColor(0.0, 0.0, 0.30, 1.0); // Paint background color dark blue, fully opaque
gl.clearDepth(1.0); // clear the scene
gl.enable(gl.DEPTH_TEST); // enable depth
gl.depthFunc(gl.LEQUAL); // hide far stuff behind close stuff
// clear the canvas
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
// set perspective
const fieldOfView = 45 * pi / 180; //// in radians
const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
const zNear = 0.1; // depth clipping
const zFar = 100.0;// depth clipping
const projectionMatrix = mat4.create();
mat4.perspective(
projectionMatrix, // first arg is destination
fieldOfView,
aspect,
zNear,
zFar
);
// now position the 3D model
const modelViewMatrix = mat4.create();
mat4.translate(modelViewMatrix, // move model away from viewer
modelViewMatrix, [0.0, 0.0, -4]);
const period_ms = 2000;
const rotation = (time_ms % (period_ms*3)) / (period_ms*3) * 2 * pi;
const rotation2 = (time_ms % (period_ms*5)) / (period_ms*5) * 2 * pi;
mat4.rotate(
modelViewMatrix, modelViewMatrix,
-1*rotation,
[0, 0, 1] // Z-axis rotation
);
mat4.rotate(
modelViewMatrix, modelViewMatrix,
-1*rotation2,