-
Notifications
You must be signed in to change notification settings - Fork 67
/
dof.html
396 lines (319 loc) · 14.1 KB
/
dof.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
<!DOCTYPE html>
<html>
<head>
<title>PicoGL.js: Depth of Field</title>
<meta charset="utf-8">
<script src="utils/compatibility.js"></script>
<script src="utils/gl-matrix.js"></script>
<script src="utils/utils.js"></script>
<link rel="stylesheet" href="../site/css/picogl-example.css">
</head>
<!--
The MIT License (MIT)
Copyright (c) 2017 Tarek Sherif
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-->
<!--
DOF algorithm from http://www.nutty.ca/?page_id=352&link=depth_of_field
-->
<body>
<div id="example-title">
PicoGL.js Example: Depth of Field
<div>
<a href="https://github.com/tsherif/picogl.js/blob/master/examples/dof.html">Source code</a>
</div>
</div>
<canvas id="gl-canvas"></canvas>
<script type="x-shader/vs" id="vertex-boxes">
#version 300 es
layout(location=0) in vec4 aPosition;
layout(location=1) in vec2 aUV;
layout(location=2) in vec3 aNormal;
layout(location=3) in mat4 uModel;
layout(std140) uniform SceneUniforms {
mat4 uViewProj;
vec4 uEyePosition;
vec4 uLightPosition;
};
out vec3 vPosition;
out vec2 vUV;
out vec3 vNormal;
void main() {
vec4 worldPosition = uModel * aPosition;
vPosition = worldPosition.xyz;
vUV = aUV;
vNormal = (uModel * vec4(aNormal, 0.0)).xyz;
gl_Position = uViewProj * worldPosition;
}
</script>
<script type="x-shader/fs" id="fragment-boxes">
#version 300 es
precision highp float;
layout(std140) uniform SceneUniforms {
mat4 uViewProj;
vec4 uEyePosition;
vec4 uLightPosition;
};
uniform sampler2D uTexture;
in vec3 vPosition;
in vec2 vUV;
in vec3 vNormal;
out vec4 fragColor;
void main() {
vec3 color = texture(uTexture, vUV).rgb;
vec3 normal = normalize(vNormal);
vec3 eyeVec = normalize(uEyePosition.xyz - vPosition);
vec3 incidentVec = normalize(vPosition - uLightPosition.xyz);
vec3 lightVec = -incidentVec;
float diffuse = max(dot(lightVec, normal), 0.0);
float highlight = pow(max(dot(eyeVec, reflect(incidentVec, normal)), 0.0), 100.0);
float ambient = 0.1;
fragColor = vec4(color * (diffuse + highlight + ambient), 1.0);
}
</script>
<script type="x-shader/vs" id="vertex-quad">
#version 300 es
layout(location=0) in vec4 aPosition;
void main() {
gl_Position = aPosition;
}
</script>
<script type="x-shader/fs" id="fragment-blur">
#version 300 es
precision highp float;
layout(std140, column_major) uniform;
#define MAX_BLUR 20.0
uniform DOFUniforms {
vec2 uDepthRange;
float uFocusDistance;
float uBlurCoefficient;
float uPPM;
};
uniform vec2 uTexelOffset;
uniform sampler2D uColor;
uniform sampler2D uDepth;
out vec4 fragColor;
void main() {
ivec2 fragCoord = ivec2(gl_FragCoord.xy);
ivec2 resolution = textureSize(uColor, 0) - 1;
// Convert to linear depth
float ndc = 2.0 * texelFetch(uDepth, fragCoord, 0).r - 1.0;
float depth = -(2.0 * uDepthRange.y * uDepthRange.x) / (ndc * (uDepthRange.y - uDepthRange.x) - uDepthRange.y - uDepthRange.x);
float deltaDepth = abs(uFocusDistance - depth);
// Blur more quickly in the foreground.
float xdd = depth < uFocusDistance ? abs(uFocusDistance - deltaDepth) : abs(uFocusDistance + deltaDepth);
float blurRadius = min(floor(uBlurCoefficient * (deltaDepth / xdd) * uPPM), MAX_BLUR);
vec4 color = vec4(0.0);
if (blurRadius > 1.0) {
float halfBlur = blurRadius * 0.5;
float count = 0.0;
for (float i = 0.0; i <= MAX_BLUR; ++i) {
if (i > blurRadius) {
break;
}
// texelFetch outside texture gives vec4(0.0) (undefined in ES 3)
ivec2 sampleCoord = clamp(fragCoord + ivec2(((i - halfBlur) * uTexelOffset)), ivec2(0), resolution);
color += texelFetch(uColor, sampleCoord, 0);
++count;
}
color /= count;
} else {
color = texelFetch(uColor, fragCoord, 0);
}
fragColor = color;
}
</script>
<script type="module">
import { PicoGL } from "../src/picogl.js";
utils.addTimerElement();
utils.instrumentAnimationFrame();
let canvas = document.getElementById("gl-canvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const NEAR = 0.1;
const FAR = 10.0;
const FOCAL_LENGTH = 1.0;
const FOCUS_DISTANCE = 2.0;
const MAGNIFICATION = FOCAL_LENGTH / Math.abs(FOCUS_DISTANCE - FOCAL_LENGTH);
const FSTOP = 2.8;
const BLUR_COEFFICIENT = FOCAL_LENGTH * MAGNIFICATION / FSTOP;
const PPM = Math.sqrt(canvas.width * canvas.width + canvas.height * canvas.height) / 35;
const NUM_ROWS = 5;
const BOXES_PER_ROW = 20;
const NUM_BOXES = BOXES_PER_ROW * NUM_ROWS;
let resized = false;
window.onresize = function() {
resized = true;
};
let app = PicoGL.createApp(canvas)
.enable(PicoGL.DEPTH_TEST)
.clearColor(0.0, 0.0, 0.0, 1.0);
let timer = app.createTimer();
let depthRange = vec2.fromValues(NEAR, FAR);
// SET UP PROGRAMS
let boxVsSource = document.getElementById("vertex-boxes").text;
let boxFsSource = document.getElementById("fragment-boxes").text;
let quadVsSource = document.getElementById("vertex-quad").text;
let blurFsSource = document.getElementById("fragment-blur").text;
// FRAMEBUFFERS
let colorTargetA = app.createTexture2D(app.width, app.height);
let colorTargetB = app.createTexture2D(app.width, app.height);
let depthTarget = app.createTexture2D(app.width, app.height, {
internalFormat: PicoGL.DEPTH_COMPONENT16
});
let boxBuffer = app.createFramebuffer().colorTarget(0, colorTargetA).depthTarget(depthTarget);
let hblurBuffer = app.createFramebuffer().colorTarget(0, colorTargetB);
let blurBuffer = app.createFramebuffer().colorTarget(0, colorTargetA);
// INSTANCED BOX GEOMETRY
let box = utils.createBox({dimensions: [1.0, 1.0, 1.0]})
let positions = app.createVertexBuffer(PicoGL.FLOAT, 3, box.positions);
let uv = app.createVertexBuffer(PicoGL.FLOAT, 2, box.uvs);
let normals = app.createVertexBuffer(PicoGL.FLOAT, 3, box.normals);
// PER-INSTANCE MODEL MATRICES
let modelMatrixData = new Float32Array(NUM_BOXES * 16);
let modelMatrices = app.createMatrixBuffer(PicoGL.FLOAT_MAT4, modelMatrixData);
let boxArray = app.createVertexArray()
.vertexAttributeBuffer(0, positions)
.vertexAttributeBuffer(1, uv)
.vertexAttributeBuffer(2, normals)
.instanceAttributeBuffer(3, modelMatrices);
// QUAD GEOMETRY
let quadPositions = app.createVertexBuffer(PicoGL.FLOAT, 2, new Float32Array([
-1, 1,
-1, -1,
1, -1,
-1, 1,
1, -1,
1, 1,
]));
let quadArray = app.createVertexArray()
.vertexAttributeBuffer(0, quadPositions);
// UNIFORM DATA
let projMatrix = mat4.create();
mat4.perspective(projMatrix, Math.PI / 2, canvas.width / canvas.height, NEAR, FAR);
let viewMatrix = mat4.create();
let eyePosition = vec3.fromValues(1, 1.5, 1);
mat4.lookAt(viewMatrix, eyePosition, vec3.fromValues(0, 0, 0), vec3.fromValues(0, 1, 0));
let viewProjMatrix = mat4.create();
mat4.multiply(viewProjMatrix, projMatrix, viewMatrix);
let lightPosition = vec3.fromValues(1, 1, 0.5);
let modelMatrix = mat4.create();
let rotateXMatrix = mat4.create();
let rotateYMatrix = mat4.create();
// UNIFORM BUFFERS
let sceneUniforms = app.createUniformBuffer([
PicoGL.FLOAT_MAT4,
PicoGL.FLOAT_VEC4,
PicoGL.FLOAT_VEC4
])
.set(0, viewProjMatrix)
.set(1, eyePosition)
.set(2, lightPosition)
.update();
let dofUniforms = app.createUniformBuffer([
PicoGL.FLOAT_VEC2,
PicoGL.FLOAT,
PicoGL.FLOAT,
PicoGL.FLOAT
])
.set(0, depthRange)
.set(1, FOCUS_DISTANCE)
.set(2, BLUR_COEFFICIENT)
.set(3, PPM)
.update();
// DOF BLUR DRAW CALLS
let hTexelOffset = vec2.fromValues(1.0, 0.0);
let vTexelOffset = vec2.fromValues(0.0, 1.0);
Promise.all([
app.createPrograms([boxVsSource, boxFsSource], [quadVsSource, blurFsSource]),
utils.loadImages(["img/webgl-logo.png"])
]).then(([
[boxProgram, blurProgram],
[image]
]) => {
let texture = app.createTexture2D(image, {
flipY: true,
maxAnisotropy: PicoGL.WEBGL_INFO.MAX_TEXTURE_ANISOTROPY
});
// SINGLE DRAW CALL FOR ALL BOXES
let boxes = new Array(NUM_BOXES);
let boxesDrawCall = app.createDrawCall(boxProgram, boxArray)
.uniformBlock("SceneUniforms", sceneUniforms)
.texture("uTexture", texture);
let boxI = 0;
for (let j = 0; j < NUM_ROWS; ++j) {
let rowOffset = (j - Math.floor(NUM_ROWS / 2));
for (let i = 0; i < BOXES_PER_ROW; ++i) {
boxes[boxI] = {
scale: [0.9, 0.9, 0.9],
rotate: [-boxI / Math.PI, 0, boxI / Math.PI],
translate: [-i + 2 - rowOffset, 0, -i + 2 + rowOffset],
modelMatrix: mat4.create(),
}
++boxI;
}
}
let hBlurDrawCall = app.createDrawCall(blurProgram, quadArray)
.uniformBlock("DOFUniforms", dofUniforms)
.uniform("uTexelOffset", hTexelOffset)
.texture("uColor", boxBuffer.colorAttachments[0])
.texture("uDepth", boxBuffer.depthAttachment);
let finalDrawCall = app.createDrawCall(blurProgram, quadArray)
.uniformBlock("DOFUniforms", dofUniforms)
.uniform("uTexelOffset", hTexelOffset)
.texture("uColor", hblurBuffer.colorAttachments[0])
.texture("uDepth", boxBuffer.depthAttachment);
function draw() {
if (resized) {
app.resize(window.innerWidth, window.innerHeight);
boxBuffer.resize();
hblurBuffer.resize();
blurBuffer.resize();
mat4.perspective(projMatrix, Math.PI / 2, app.canvas.width / app.canvas.height, 0.1, 10.0);
mat4.multiply(viewProjMatrix, projMatrix, viewMatrix);
sceneUniforms.set(0, viewProjMatrix).update();
resized = false;
}
if (timer.ready()) {
utils.updateTimerElement(timer.cpuTime, timer.gpuTime);
}
timer.start();
for (let i = 0, len = boxes.length; i < len; ++i) {
boxes[i].rotate[0] += 0.01;
boxes[i].rotate[1] += 0.02;
utils.xformMatrix(boxes[i].modelMatrix, boxes[i].translate, boxes[i].rotate, boxes[i].scale);
modelMatrixData.set(boxes[i].modelMatrix, i * 16);
}
modelMatrices.data(modelMatrixData);
// COLOR AND DEPTH
app.drawFramebuffer(boxBuffer).clear();
boxesDrawCall.draw();
// HORIZONTAL BLUR
app.drawFramebuffer(hblurBuffer).clear()
hBlurDrawCall.draw()
// VERTICAL BLUR
app.defaultDrawFramebuffer().clear()
finalDrawCall.draw();
timer.end();
requestAnimationFrame(draw);
}
requestAnimationFrame(draw);
});
</script>
<a href="https://github.com/tsherif/picogl.js" id="github-ribbon"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/365986a132ccd6a44c23a9169022c0b5c890c387/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f7265645f6161303030302e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png"></a>
<script src="../site/js/iframe.js"></script>
</body>
</html>