-
Notifications
You must be signed in to change notification settings - Fork 0
/
webgl2_exercise.html
697 lines (582 loc) · 19.6 KB
/
webgl2_exercise.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
<!doctype html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<meta name="author" content="Mike McKenna">
<title>A WebGL2 Exercise</title>
<!-- Turn off highlighting during mouse drag. -->
<style>
body {
text-align: center;
/* Turn off highlighting during mouse drag */
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
-webkit-touch-callout: none;
-webkit-user-select: none;
user-select: none;
}
table {
margin: auto;
text-align: left
}
button {
width: 120px;
margin-top: 2px
}
.slider-input {
width: 240px
}
.slider-text {
min-width: 20px
}
</style>
</head>
<body onload="startGraphics()">
<h2>A WebGL2 Exercise</h2>
Click on the image and drag.<br>
<canvas id="theCanvas" width="480" height="480"></canvas>
<!-- Use tables to better align html elements. Consider using more CSS. -->
<table>
<tr>
<td>Points per Dimension</td>
<td>
<input id="pointsPerDimSlider" type="range" class="slider-input"
value="40" min="0" max="64" step="1"
oninput="setPointsPerDim(); draw()">
</td>
<td class="slider-text">
<output id="pointsPerDimText">40</output>
</td>
</tr>
<tr>
<td>Point Size</td>
<td>
<input id="pointSizeSlider" type="range" class="slider-input"
value="1" min="0" max="8" step="0.1"
oninput="setPointSize(); draw()">
</td>
<td class="slider-text">
<output id="pointSizeText">1</output>
</td>
</tr>
<tr>
<td colspan="3">
<button onclick="resetSliders()">Reset Sliders</button>
<button id="autoRotateButton" onclick="clickAutoRotate()"
>Run Auto Rotate</button>
<output id="fpsText"></output>
</td>
</tr>
</table>
<div style="line-height: 6px"> </div>
<table>
<tr style="vertical-align: top">
<td>WebGL renderer:</td>
<td><output id="webglRenderer">unknown</output></td>
</tr>
<tr style="vertical-align: top">
<td>WebGL vendor:</td>
<td><output id="webglVendor">unknown</output></td>
</tr>
<tr><td> </td></tr>
<tr>
<td colspan="2">Other exercises are <a href="index.html">here</a>.</td>
</tr>
</table>
</body>
<script>
"use strict"
// The javascript here forgoes three.js to more closely play with WebGL.
//
// Global constants.
//
// black on white
const foreground = 0.0;
const background = 1.0;
const dimmed = 0.8;
// white on black
//const foreground = 1.0;
//const background = 0.0;
//const dimmed = 0.33333;
const viewerZ = 8.0;
//
// Define range and cubeCenterZ so that the image fits within [-1,1]^2.
//
// Range of the cube along each axis, plus or minus:
const range = (0.95 * viewerZ)
/ (Math.sqrt(3.0 + 3.0 * viewerZ * viewerZ) - 1.0);
const cubeCenterZ = -range;
// Matrix of accumulated rotations, in column major order:
const R = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
// Define the cube corners, edges, and faces.
// The unrotated corners are at these locations:
//
// 6-------7
// |\ /|
// | 2---3 |
// | | | |
// | 0---1 |
// |/ \|
// 4-------5
const numCorners = 8;
const numEdges = 12;
const numFaces = 6;
const corners = [
[ -range, -range, -range ], // left down back
[ range, -range, -range ], // right down back
[ -range, range, -range ], // left up back
[ range, range, -range ], // right up back
[ -range, -range, range ], // left down front
[ range, -range, range ], // right down front
[ -range, range, range ], // left up front
[ range, range, range ] // right up front
];
// For each edge, define the two corners:
const edgeChildCorners = [
[ 0, 1 ],
[ 2, 3 ],
[ 4, 5 ],
[ 6, 7 ],
[ 0, 2 ],
[ 1, 3 ],
[ 4, 6 ],
[ 5, 7 ],
[ 0, 4 ],
[ 1, 5 ],
[ 2, 6 ],
[ 3, 7 ]
];
const faceNormals = [
[ -1.0, 0.0, 0.0 ], // left face
[ 1.0, 0.0, 0.0 ], // right face
[ 0.0,-1.0, 0.0 ], // down face
[ 0.0, 1.0, 0.0 ], // up face
[ 0.0, 0.0,-1.0 ], // back face
[ 0.0, 0.0, 1.0 ] // front face
];
// For each edge, define the two adjacent faces:
const edgeParentFaces = [
[ 2, 4 ],
[ 3, 4 ],
[ 2, 5 ],
[ 3, 5 ],
[ 0, 4 ],
[ 1, 4 ],
[ 0, 5 ],
[ 1, 5 ],
[ 0, 2 ],
[ 1, 2 ],
[ 0, 3 ],
[ 1, 3 ]
];
// Points per Dimension variables:
var pointsPerDim = -1;
var pointsPerDimSlider;
var pointsPerDimText;
var numPoints;
// Point Size variables:
var pointSizeSlider;
var pointSizeText;
// Auto Rotate variables:
var autoRotateButton;
const runAutoRotateText = "Run Auto Rotate";
const stopAutoRotateText = "Stop Auto Rotate";
var autoRotateIsRunning = false;
var fpsText;
var fpsCount;
var fpsStartTime;
// Webgl variables:
var gl;
var aspectAdjustLoc;
var pointSizeLoc;
var RLoc;
var startAndDeltaLoc;
var pointData;
const edgeData = new Uint8Array(numEdges * 8);
// mouse action variables:
var mouseIsDown = false;
var prevMouseX;
var prevMouseY;
//
// Main function.
//
function startGraphics()
{
//
// Initialize webgl2.
//
gl = document.getElementById("theCanvas").getContext("webgl2");
if (!gl)
{
const errorMsg = "ERROR: This browser does not offer a webgl2 context.";
console.log(errorMsg);
alert(errorMsg);
return;
}
gl.clearColor(background, background, background, 1.0); // r,g,b,opaque
// Get the renderer and vendor debug info.
const rendererInfo = gl.getExtension("WEBGL_debug_renderer_info");
if (rendererInfo)
{
document.getElementById("webglRenderer").value =
gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
document.getElementById("webglVendor").value =
gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
}
// Get some of the html items.
//
pointsPerDimSlider = document.getElementById("pointsPerDimSlider");
pointsPerDimText = document.getElementById("pointsPerDimText");
pointSizeSlider = document.getElementById("pointSizeSlider");
pointSizeText = document.getElementById("pointSizeText");
autoRotateButton = document.getElementById("autoRotateButton");
fpsText = document.getElementById("fpsText");
//
// Compile the shaders.
//
const vertexShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertexShader,
document.getElementById("vertexShaderCode").innerHTML);
gl.compileShader(vertexShader);
if (!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS))
{
const errorMsg = "ERROR: Failed to compile vertex shader: " +
gl.getShaderInfoLog(vertexShader);
console.log(errorMsg);
alert(errorMsg);
return;
}
const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragmentShader,
document.getElementById("fragmentShaderCode").innerHTML);
gl.compileShader(fragmentShader);
if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS))
{
const errorMsg = "ERROR: Failed to compile fragment shader: " +
gl.getShaderInfoLog(fragmentShader);
console.log(errorMsg);
alert(errorMsg);
return;
}
const program = gl.createProgram();
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);
gl.linkProgram(program);
//
// Set up a few things that won't change.
//
gl.useProgram(program);
gl.enable(gl.DEPTH_TEST);
gl.uniform1f(gl.getUniformLocation(program, "viewerZ" ), viewerZ);
gl.uniform1f(gl.getUniformLocation(program, "cubeCenterZ"), cubeCenterZ);
gl.uniform1f(gl.getUniformLocation(program, "foreground" ), foreground);
gl.uniform1f(gl.getUniformLocation(program, "dimmed" ), dimmed);
aspectAdjustLoc = gl.getUniformLocation(program, "aspectAdjust");
pointSizeLoc = gl.getUniformLocation(program, "pointSize");
RLoc = gl.getUniformLocation(program, "R");
startAndDeltaLoc = gl.getUniformLocation(program, "startAndDelta");
gl.bindVertexArray(gl.createVertexArray());
gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());
const positionLoc = gl.getAttribLocation(program, "position");
gl.enableVertexAttribArray(positionLoc);
gl.vertexAttribIPointer(positionLoc, 4, gl.UNSIGNED_BYTE, 4, 0);
// Define edge data, two points per edge.
//
var di = 0;
var i;
for (i = 0; i < numEdges; ++i)
{
var cornerIdx = edgeChildCorners[i][0];
edgeData[di++] = cornerIdx & 1;
edgeData[di++] = ((cornerIdx & 2) ? 1 : 0);
edgeData[di++] = ((cornerIdx & 4) ? 1 : 0);
edgeData[di++] = 0; // edge is not dimmed for now
cornerIdx = edgeChildCorners[i][1];
edgeData[di++] = cornerIdx & 1;
edgeData[di++] = ((cornerIdx & 2) ? 1 : 0);
edgeData[di++] = ((cornerIdx & 4) ? 1 : 0);
edgeData[di++] = 0; // edge is not dimmed for now
}
// Define interior point data.
setPointsPerDim();
// Draw the first image.
//
rotate( [0, 0, -cubeCenterZ], [0.15, -0.1, -cubeCenterZ ] );
draw();
// Define functions that will respond to mouse actions and redraw.
//
gl.canvas.onmousedown = mouseDownEvent;
document.onmouseup = mouseUpEvent;
document.onmousemove = mouseMoveEvent;
}
function rotate(fromV, toV)
{
// Convert vector-to-vector pivot into rotation matrix deltaR.
const cosTheta =
dotProduct(fromV, toV) /
Math.sqrt(dotProduct(fromV, fromV) * dotProduct(toV, toV));
const kos = 1 - cosTheta;
const temp = 1 - cosTheta * cosTheta;
const sinTheta = ((temp > 0.0) ? Math.sqrt(temp) : 0.0);
const axis = [(fromV[1] * toV[2]) - (fromV[2] * toV[1]),
(fromV[2] * toV[0]) - (fromV[0] * toV[2]),
(fromV[0] * toV[1]) - (fromV[1] * toV[0])];
const axisLen = Math.sqrt(dotProduct(axis, axis));
axis[0] /= axisLen;
axis[1] /= axisLen;
axis[2] /= axisLen;
// Define matrix deltaR in column-major order in case we send it to GLSL.
const deltaR = [
kos * axis[0] * axis[0] + cosTheta,
kos * axis[0] * axis[1] + sinTheta * axis[2],
kos * axis[0] * axis[2] - sinTheta * axis[1],
kos * axis[0] * axis[1] - sinTheta * axis[2],
kos * axis[1] * axis[1] + cosTheta,
kos * axis[1] * axis[2] + sinTheta * axis[0],
kos * axis[0] * axis[2] + sinTheta * axis[1],
kos * axis[1] * axis[2] - sinTheta * axis[0],
kos * axis[2] * axis[2] + cosTheta
];
// Apply deltaR to accumulated rotation R.
var i;
for (i = 0; i < 9; i += 3)
{
const old0 = R[i ];
const old1 = R[i + 1];
const old2 = R[i + 2];
R[i ] = deltaR[0] * old0 + deltaR[3] * old1 + deltaR[6] * old2;
R[i + 1] = deltaR[1] * old0 + deltaR[4] * old1 + deltaR[7] * old2;
R[i + 2] = deltaR[2] * old0 + deltaR[5] * old1 + deltaR[8] * old2;
}
}
function draw()
{
const deltaZ = viewerZ - cubeCenterZ;
const Rinv_VminusC = [ R[2] * deltaZ, R[5] * deltaZ, R[8] * deltaZ ];
// Determine which edges are in back of the cube.
//
var i;
for (i = 0; i < numEdges; ++i)
{
// If both parent faces are rotated away from the viewer, dim the edge.
//
// To avoid rotating corner and face normals for each iteration of
// this loop, we instead apply the inverse rotation to the viewer,
// which was calculated once before this loop.
const corner = corners[edgeChildCorners[i][0]];
const Rinv_cornerToViewer = [ Rinv_VminusC[0] - corner[0],
Rinv_VminusC[1] - corner[1],
Rinv_VminusC[2] - corner[2] ];
const faces = edgeParentFaces[i];
edgeData[8 * i + 3] = edgeData[8 * i + 7] =
(((dotProduct(Rinv_cornerToViewer, faceNormals[faces[0]]) < 0.0) &&
(dotProduct(Rinv_cornerToViewer, faceNormals[faces[1]]) < 0.0) )
? 1 // dimmed
: 0); // not dimmed
}
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
//
// To be safe, we set uniforms only after we have cleared the image.
// (Could setting uniforms before clearing the image affect images that
// are still in the pipeline? Maybe not, but let's be safe anyway.)
//
// Determine the aspect ratio.
const width = gl.drawingBufferWidth;
const height = gl.drawingBufferHeight;
gl.viewport(0, 0, width, height);
if (height < width)
{
gl.uniform2f(aspectAdjustLoc, width / height, 1.0);
}
else
{
gl.uniform2f(aspectAdjustLoc, 1.0, height / width);
}
// Send other uniform data to the GPU.
gl.uniform1f(pointSizeLoc, pointSizeSlider.value);
gl.uniformMatrix3fv(RLoc, false, R);
// Execute the shader program twice.
gl.uniform2f(startAndDeltaLoc, -range, 2 * range);
gl.bufferData(gl.ARRAY_BUFFER, edgeData , gl.DYNAMIC_DRAW);
gl.drawArrays(gl.LINES , 0, numEdges * 2);
if ((pointsPerDim > 0) && (pointSizeSlider.value > 0.0))
{
const pointCoordDelta = 2.0 * range / pointsPerDim;
const pointFirstCoord = -range + pointCoordDelta * 0.5;
gl.uniform2f(startAndDeltaLoc, pointFirstCoord, pointCoordDelta);
gl.bufferData(gl.ARRAY_BUFFER, pointData, gl.DYNAMIC_DRAW);
gl.drawArrays(gl.POINTS, 0, numPoints);
}
}
function dotProduct(v1, v2)
{
return (v1[0] * v2[0]) + (v1[1] * v2[1]) + (v1[2] * v2[2]);
}
function setPointsPerDim()
{
const sliderValue = pointsPerDimSlider.value;
pointsPerDimText.value = sliderValue;
if (pointsPerDim == sliderValue)
{
return;
}
pointsPerDim = sliderValue;
numPoints = pointsPerDim * pointsPerDim * pointsPerDim;
pointData = new Uint8Array(numPoints * 4);
var pointIdx = 0;
var i0, i1, i2;
for (i0 = 0; i0 < pointsPerDim; ++i0)
{
for (i1 = 0; i1 < pointsPerDim; ++i1)
{
for (i2 = 0; i2 < pointsPerDim; ++i2)
{
pointData[pointIdx++] = i0;
pointData[pointIdx++] = i1;
pointData[pointIdx++] = i2;
pointData[pointIdx++] = 0; // point is never dimmed
}
}
}
}
function setPointSize()
{
pointSizeText.value = parseFloat(pointSizeSlider.value).toFixed(1);
}
function resetSliders()
{
pointsPerDimSlider.value = 40;
pointSizeSlider.value = 1;
setPointsPerDim();
setPointSize();
draw();
}
function clickAutoRotate()
{
switch(autoRotateButton.innerHTML)
{
case runAutoRotateText : runAutoRotate() ; break;
case stopAutoRotateText: stopAutoRotate(); break;
default:
const erroMsg = "ERROR: autoRotateButton has unexpected innerHTML '"
+ autoRotateButton.innerHTML + "'";
console.log(errorMsg);
alert(errorMsg);
stopAutoRotate();
break;
}
}
function runAutoRotate()
{
autoRotateIsRunning = true;
autoRotateButton.innerHTML = stopAutoRotateText;
fpsText.value = "FPS = 0.0";
fpsCount = 0;
fpsStartTime = performance.now();
window.requestAnimationFrame(loopAutoRotate);
}
function loopAutoRotate(timestamp)
{
if (autoRotateIsRunning)
{
const halfPixel = 0.5 * getPixelEdgeLen();
rotate( [ -halfPixel, -halfPixel, -cubeCenterZ ],
[ halfPixel, halfPixel, -cubeCenterZ ] );
draw();
++fpsCount;
const newTime = performance.now();
if (newTime - fpsStartTime >= 1000.0)
{
var rateValue = 1000.0 * fpsCount / (newTime - fpsStartTime);
fpsText.value = "FPS = " + rateValue.toFixed(1);
fpsCount = 0;
fpsStartTime = performance.now();
}
window.requestAnimationFrame(loopAutoRotate);
}
}
function stopAutoRotate()
{
autoRotateIsRunning = false;
autoRotateButton.innerHTML = runAutoRotateText;
}
function mouseDownEvent(event)
{
mouseIsDown = true;
prevMouseX = event.clientX;
prevMouseY = event.clientY;
stopAutoRotate();
}
function mouseUpEvent(event)
{
mouseIsDown = false;
}
function mouseMoveEvent(event)
{
if (!mouseIsDown)
{
return;
}
const newX = event.clientX;
const newY = event.clientY;
if ((newX == prevMouseX) && (newY == prevMouseY))
{
return;
}
// Convert the mouse movement into "from" and "to" vectors for a rotation.
const pixelEdgeLen = getPixelEdgeLen();
// Note: Mouse Y coord goes downward, but vertex Y coord goes upward.
const deltaX = (newX - prevMouseX) * pixelEdgeLen;
const deltaY = -(newY - prevMouseY) * pixelEdgeLen;
rotate( [ -0.5 * deltaX, -0.5 * deltaY, -cubeCenterZ ],
[ 0.5 * deltaX, 0.5 * deltaY, -cubeCenterZ ] );
draw();
prevMouseX = newX;
prevMouseY = newY;
}
function getPixelEdgeLen()
{
const width = gl.drawingBufferWidth;
const height = gl.drawingBufferHeight;
return (2.0 / ((height < width) ? height : width));
}
</script>
<script type="glsl" id="vertexShaderCode">#version 300 es
precision highp float;
uniform float viewerZ;
uniform float cubeCenterZ;
uniform float foreground;
uniform float dimmed;
uniform vec2 aspectAdjust;
uniform float pointSize;
uniform mat3 R;
uniform vec2 startAndDelta;
in uvec4 position;
flat out float brightness;
void main()
{
vec4 floatPos = vec4(position);
// Apply the dimming switch.
brightness = foreground - floatPos[3] * (foreground - dimmed);
vec3 rotatedPoint =
R * (startAndDelta[0] + startAndDelta[1] * vec3(floatPos));
gl_Position = vec4(rotatedPoint.xy / aspectAdjust,
// Negate Z to convert from world Z to opengl Z.
// Also, compress Z to stay within the clip planes.
-0.01 * rotatedPoint.z,
// The 4th coordinate is the perspective divider.
(viewerZ - cubeCenterZ - rotatedPoint.z) / viewerZ);
gl_PointSize = pointSize;
}
</script>
<script type="glsl" id="fragmentShaderCode">#version 300 es
precision highp float;
flat in float brightness;
out vec4 outputColor;
void main()
{
outputColor = vec4(brightness, brightness, brightness, 1.0);
}
</script>
</html>