-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.html
304 lines (282 loc) · 10.5 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
<html style="height: 100%; width: 100%">
<head>
<title>schattenspiel</title>
</head>
<body style="height: 100%; width: 100%; margin: 0; background-color: white">
<textarea
id="code"
style="
background-color: transparent;
width: 100%;
height: 100%;
position: fixed;
top: 0;
left: 0;
border: 0;
outline: none;
padding: 10px;
resize: none;
color: black;
font-size: 16px;
"
spellcheck="false"
></textarea>
<canvas id="canvas" style="width: 100%; height: 100%"></canvas>
<script>
// read base64 code from url
let urlCode = window.location.hash.slice(1);
if (urlCode) {
urlCode = atob(urlCode);
console.log("loaded code from url!");
}
// use urlCode or fall back to default shadertoy example
const initialShader =
urlCode ||
`void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
// Normalized pixel coordinates (from 0 to 1)
vec2 uv = fragCoord/iResolution.xy;
// Time varying pixel color
vec3 col = 0.5 + 0.5*cos(iTime+uv.xyx+vec3(0,2,4));
// Output to screen
fragColor = vec4(col,1.0);
}`;
function main() {
// set up code input
const input = document.querySelector("#code");
input.value = initialShader;
window.codestyle = (attr, value) => (input.style[attr] = value);
// vertex shader
const vs = `
attribute vec4 a_position;
void main() {
gl_Position = a_position;
}
`;
// set up canvas
const canvas = document.querySelector("#canvas");
const gl = canvas.getContext("webgl");
const rect = canvas.getBoundingClientRect();
canvas.width = rect.width; // * window.devicePixelRatio;
canvas.height = rect.height; // * window.devicePixelRatio;
// mouse logic
let mouseX = 0;
let mouseY = 0;
document.addEventListener("mousemove", (e) => {
const { left, height, top } = canvas.getBoundingClientRect();
mouseX = e.clientX - left;
mouseY = height - (e.clientY - top) - 1;
});
// animation frame logic
let requestId;
function requestFrame(render) {
if (!requestId) {
requestId = requestAnimationFrame(render);
}
}
function cancelFrame() {
if (requestId) {
cancelAnimationFrame(requestId);
requestId = undefined;
}
}
// runs on eval
let then = 0;
let time = 0;
function updateShader(mainImageFunction) {
// fragment shader
const fs = `
precision highp float;
uniform vec2 iResolution;
uniform vec2 iMouse;
uniform float iTime;
uniform sampler2D iFeedback;
${mainImageFunction}
void main() {
mainImage(gl_FragColor, gl_FragCoord.xy);
}`;
cancelFrame();
const program = createProgramFromSources(gl, [vs, fs]);
const positionLoc = gl.getAttribLocation(program, "a_position");
const resolutionLoc = gl.getUniformLocation(program, "iResolution");
const mouseLoc = gl.getUniformLocation(program, "iMouse");
const timeLoc = gl.getUniformLocation(program, "iTime");
const vertices = new Float32Array([
-1.0, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0,
]);
const vertexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
// set up feedback ping pong textures
let [tex0, tex1] = [makeTexture(gl), makeTexture(gl)];
const framebuffer = gl.createFramebuffer();
function render(now) {
requestId = undefined;
now *= 0.001; // convert to seconds
const elapsedTime = Math.min(now - then, 0.1);
time += elapsedTime;
then = now;
resizeCanvasToDisplaySize(gl.canvas);
gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
gl.framebufferTexture2D(
gl.FRAMEBUFFER,
gl.COLOR_ATTACHMENT0,
gl.TEXTURE_2D,
tex0,
0
);
gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
gl.useProgram(program);
gl.enableVertexAttribArray(positionLoc);
gl.vertexAttribPointer(positionLoc, 2, gl.FLOAT, false, 0, 0);
gl.uniform2f(resolutionLoc, gl.canvas.width, gl.canvas.height);
gl.uniform2f(mouseLoc, mouseX, mouseY);
gl.uniform1f(timeLoc, time);
gl.uniform1i(gl.getUniformLocation(program, "iFeedback"), 0);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, tex1);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); // draw to texture
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
[tex0, tex1] = [tex1, tex0];
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); // draw to canvas
requestFrame(render);
}
requestFrame(render);
}
// start rendering
updateShader(input.value);
// update on ctrl+enter
input.addEventListener("keydown", (e) => {
if ((e.ctrlKey || e.altKey) && e.key === "Enter") {
updateShader(input.value);
window.location.hash = "#" + btoa(input.value);
console.log("update", input.value);
}
});
}
main();
function makeTexture(gl) {
const texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texImage2D(
gl.TEXTURE_2D,
0,
gl.RGBA,
canvas.width,
canvas.height,
0,
gl.RGBA,
gl.UNSIGNED_BYTE,
null
);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
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.bindTexture(gl.TEXTURE_2D, null);
return texture;
}
// the rest is boilerplate code, loosely based on https://webglfundamentals.org/webgl/resources/webgl-utils.js
/*
* Copyright 2021 GFXFundamentals.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of GFXFundamentals. nor the names of his
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
function loadShader(gl, shaderSource, shaderType) {
const shader = gl.createShader(shaderType);
gl.shaderSource(shader, shaderSource);
gl.compileShader(shader);
const compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
if (!compiled) {
const lastError = gl.getShaderInfoLog(shader);
console.error(
"*** Error compiling shader '" +
shader +
"':" +
lastError +
`\n` +
shaderSource
.split("\n")
.map((l, i) => `${i + 1}: ${l}`)
.join("\n")
);
gl.deleteShader(shader);
return null;
}
return shader;
}
function resizeCanvasToDisplaySize(canvas, multiplier) {
multiplier = multiplier || 1;
const width = (canvas.clientWidth * multiplier) | 0;
const height = (canvas.clientHeight * multiplier) | 0;
if (canvas.width !== width || canvas.height !== height) {
canvas.width = width;
canvas.height = height;
return true;
}
return false;
}
function createProgramFromSources(
gl,
shaderSources,
opt_attribs,
opt_locations
) {
const shaders = [
loadShader(gl, shaderSources[0], gl.VERTEX_SHADER),
loadShader(gl, shaderSources[1], gl.FRAGMENT_SHADER),
];
return createProgram(gl, shaders, opt_attribs, opt_locations);
}
function createProgram(gl, shaders, opt_attribs, opt_locations) {
const program = gl.createProgram();
shaders.forEach(function (shader) {
gl.attachShader(program, shader);
});
if (opt_attribs) {
opt_attribs.forEach(function (attrib, ndx) {
gl.bindAttribLocation(
program,
opt_locations ? opt_locations[ndx] : ndx,
attrib
);
});
}
gl.linkProgram(program);
const linked = gl.getProgramParameter(program, gl.LINK_STATUS);
if (!linked) {
const lastError = gl.getProgramInfoLog(program);
console.error("Error in program linking:" + lastError);
gl.deleteProgram(program);
return null;
}
return program;
}
</script>
</body>
</html>