-
Notifications
You must be signed in to change notification settings - Fork 1
/
shader.js
350 lines (303 loc) · 12.2 KB
/
shader.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
import { Program } from "./ast.js";
import { unwrap } from "./util.js";
/**
* Get the fragment shader source code.
* @param {string} core
* @param {string[]} additional_lines
* @param {Precision} precision
* @typedef {"lowp" | "mediump" | "highp"} Precision
*/
export function get_fragment_shader_source(core, additional_lines, precision) {
let variable_text = "";
for (const var_text of additional_lines) {
variable_text += ` ${var_text};\n`;
}
return `#version 300 es
precision ${precision} float;
precision ${precision} int;
uniform float wrap_value;
uniform int t, mx, my, kx, ky;
uniform float t_f, mx_f, my_f, kx_f, ky_f;
uniform vec3 color;
out vec4 fragColor;
void main() {
float sx_f = gl_FragCoord.x - 0.5;
float sy_f = gl_FragCoord.y - 0.5;
int sx = int(sx_f);
int sy = int(sy_f);
${variable_text}
int value = ${core};
value = value % int(wrap_value);
value = value < 0 ? value + int(wrap_value) : value;
float value_out = float(value) / (wrap_value - 1.0);
fragColor = vec4(value_out * color, 1.0);
}`;
}
/**
* Get the vertex shader source code.
*/
export function get_vertex_shader_source() {
return `#version 300 es
in vec4 aVertexPosition;
void main() {
gl_Position = aVertexPosition;
}`;
}
/**
* Turn a bytebeat containing variables into a bytebeat core and its additional variables.
* @param {string} bytebeat
* @returns {[string, string[]]}
*/
function exact_parse_program(bytebeat) {
let split = bytebeat.split(";");
console.assert(split.length > 0);
const core = split[split.length - 1].trim();
if (split.length == 1) {
return [core, []];
}
const additional_variables = split.slice(0, split.length - 1).map((x) => x.trim());
return [core, additional_variables];
}
/**
* Load the given shader into the given context.
* @param {WebGL2RenderingContext} gl the context to load the shader into
* @param {number} type The type of shader being
* compiled. This should be equal to gl.VERTEX_SHADER or gl.FRAGMENT_SHADER.
* @param {string} source The source code of the shader to load.
* @returns {WebGLShader | Error} The compiled shader, or an error if the shader did not compile successfully.
*/
function loadShader(gl, type, source) {
const shader = gl.createShader(type);
if (shader == null) {
return new Error("Expected shader to be non-null!");
}
// 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)) {
let shader_name = type == gl.VERTEX_SHADER ? "vertex" : "fragement";
let msg = `An error occurred compiling the ${shader_name} shader: ${gl.getShaderInfoLog(shader)}\n\n=== Shader Source ===\n\n${source}`;
gl.deleteShader(shader);
return new Error(msg);
}
return shader;
}
/**
* Initialize a WebGLProgram from the given vertex and fragment shaders.
* @param {WebGL2RenderingContext} gl the context to load the program into
* @param {string} vsSource The source of the vertex shader.
* @param {string} fsSource The source of the fragment shader.
* @returns {WebGLProgram | Error} The compiled program, or an error if the program could not be compiled
*/
function initShaderProgram(gl, vsSource, fsSource) {
const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);
const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);
if (vertexShader instanceof Error) { return vertexShader; }
if (fragmentShader instanceof Error) { return fragmentShader; }
// Create the shader program
const shaderProgram = gl.createProgram();
if (shaderProgram == null) {
return new Error("Expected gl.createProgram() to return a WebGLProgram, got null.");
}
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)) {
return new Error(`Unable to initialize the shader program: ${gl.getProgramInfoLog(shaderProgram)}`);
}
return shaderProgram;
}
/**
* Initialize a WebGL buffers containing a square. The square will cover the entire canvas
* and is where we render our Bytebeat art.
* @param {WebGL2RenderingContext} gl
* @returns {WebGLBuffer}
*/
function initBuffers(gl) {
// Create a buffer for the square's positions.
const positionBuffer = gl.createBuffer();
if (positionBuffer == null) {
throw new Error("Couldn't create a WebGLBuffer!");
}
// Select the positionBuffer as the one to apply buffer
// operations to from here out.
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
// Now create an array of positions for the square.
const positions = [
1.0, 1.0,
-1.0, 1.0,
1.0, -1.0,
-1.0, -1.0,
];
// Now pass the list of positions into WebGL to build the
// shape. We do this by creating a Float32Array from the
// JavaScript array, then use it to fill the current buffer.
gl.bufferData(gl.ARRAY_BUFFER,
new Float32Array(positions),
gl.STATIC_DRAW);
return positionBuffer;
}
/**
* @typedef {{
* wrap_value: number,
* time: number,
* color: import("./util.js").RGBColor,
* mouse_x: number,
* mouse_y: number,
* keyboard_x: number,
* keyboard_y: number,
* }} BytebeatParams
*/
/**
* Set the uniforms for the bytebeat. This function is mainly used to pass values like mouse position
* into the shader.
* @param {WebGL2RenderingContext} gl
* @param {ProgramInfo} programInfo
* @param {BytebeatParams} params
*/
function setUniforms(gl, programInfo, params) {
gl.useProgram(programInfo.program);
gl.uniform1f(programInfo.uniforms.wrap_value, params.wrap_value);
gl.uniform3fv(programInfo.uniforms.color, params.color.toFloat());
gl.uniform1i(programInfo.uniforms.time, Math.trunc(params.time));
gl.uniform1f(programInfo.uniforms.time_float, params.time);
gl.uniform1f(programInfo.uniforms.mouse_x_float, params.mouse_x);
gl.uniform1i(programInfo.uniforms.mouse_x, Math.trunc(params.mouse_x));
gl.uniform1f(programInfo.uniforms.mouse_y_float, params.mouse_y);
gl.uniform1i(programInfo.uniforms.mouse_y, Math.trunc(params.mouse_y));
gl.uniform1f(programInfo.uniforms.keyboard_x_float, params.keyboard_x);
gl.uniform1i(programInfo.uniforms.keyboard_x, Math.trunc(params.keyboard_x));
gl.uniform1f(programInfo.uniforms.keyboard_y_float, params.keyboard_y);
gl.uniform1i(programInfo.uniforms.keyboard_y, Math.trunc(params.keyboard_y));
}
/**
* Render the given bytebeat.
* @param {WebGL2RenderingContext} gl
* @param {number} positionAttributeIndex
*/
function render(gl, positionAttributeIndex) {
// Set the clear color to solid black
gl.clearColor(0.0, 0.0, 0.0, 1.0);
// Set the clear value for the depth buffer
gl.clearDepth(1.0);
// Enable depth testing
gl.enable(gl.DEPTH_TEST);
// Set that near things obscure far things
gl.depthFunc(gl.LEQUAL);
// Clear the canvas before we start drawing on it.
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
// Tell WebGL how to pull out the positions from the position
// buffer into the vertexPosition attribute.
{
const numComponents = 2; // pull out 2 values per iteration
const type = gl.FLOAT; // the data in the buffer is 32bit floats
const normalize = false; // don't normalize
const stride = 0; // how many bytes to get from one set of values to the next
// 0 = use type and numComponents above
const offset = 0; // how many bytes inside the buffer to start from
gl.vertexAttribPointer(
positionAttributeIndex,
numComponents,
type,
normalize,
stride,
offset);
gl.enableVertexAttribArray(
positionAttributeIndex);
}
{
const offset = 0;
const vertexCount = 4;
gl.drawArrays(gl.TRIANGLE_STRIP, offset, vertexCount);
}
}
/**
* @param {WebGL2RenderingContext} gl
* @param {string} bytebeat
* @param {Precision} precision
* @returns {[WebGLProgram | Error, string, "raw" | "parsed"]}
*/
function try_both_parse_methods(gl, bytebeat, precision) {
const vsSource = get_vertex_shader_source();
const fsSource1 = get_fragment_shader_source(...exact_parse_program(bytebeat), precision);
const shaderProgram1 = initShaderProgram(gl, vsSource, fsSource1);
if (shaderProgram1 instanceof WebGLProgram) {
return [shaderProgram1, fsSource1, "raw"];
}
const program = Program.parse(bytebeat);
if (program instanceof Error) {
console.log(program);
// Return the first program's errors, for better user error msg display.
return [shaderProgram1, fsSource1, "raw"];
}
const [core, additional_lines] = exact_parse_program(program.toString("pretty"));
const fsSource2 = get_fragment_shader_source(core, additional_lines, precision);
const shaderProgram2 = initShaderProgram(gl, vsSource, fsSource2);
return [shaderProgram2, fsSource2, "parsed"];
}
/**
* @param {WebGL2RenderingContext} gl
* @param {WebGLProgram} shaderProgram
* @return {typeof programInfo}
* @typedef {ReturnType<typeof program_info>} ProgramInfo
*/
function program_info(gl, shaderProgram) {
let programInfo = {
program: shaderProgram,
uniforms: {
color: gl.getUniformLocation(shaderProgram, "color"),
wrap_value: gl.getUniformLocation(shaderProgram, "wrap_value"),
time: gl.getUniformLocation(shaderProgram, "t"),
time_float: gl.getUniformLocation(shaderProgram, "t_f"),
mouse_x: gl.getUniformLocation(shaderProgram, "mx"),
mouse_y: gl.getUniformLocation(shaderProgram, "my"),
mouse_x_float: gl.getUniformLocation(shaderProgram, "mx_f"),
mouse_y_float: gl.getUniformLocation(shaderProgram, "my_f"),
keyboard_x: gl.getUniformLocation(shaderProgram, "kx"),
keyboard_y: gl.getUniformLocation(shaderProgram, "ky"),
keyboard_x_float: gl.getUniformLocation(shaderProgram, "kx_f"),
keyboard_y_float: gl.getUniformLocation(shaderProgram, "ky_f"),
},
attribs: {
position: unwrap(gl.getAttribLocation(shaderProgram, "aVertexPosition")),
},
};
return programInfo;
}
/**
* Compile a Bytebeat. This returns a ProgramInfo containing the program and it's various buffer
* locations.
* @param {WebGL2RenderingContext} gl the context to render with
* @param {string} bytebeat the bytebeat program
* @param {Precision} precision
* @return {[ProgramInfo | Error, string, "raw" | "parsed"]}
*/
export function compileBytebeat(gl, bytebeat, precision) {
const [shaderProgram, fsSource, parse_type] = try_both_parse_methods(gl, bytebeat, precision);
if (shaderProgram instanceof Error) { return [shaderProgram, fsSource, parse_type]; }
// programInfo contains the attribute and uniform locations, which is how we can interact with
// the shader. (See the vertex shader for where these are used).
// An attribute is a variable in the vertex shader and is available to JS. It is usually used for
// model data, vertex coordinates, color information, etc.
// A varying is a variable that is declared by the vertex shader and passed to the fragment shader.
// A uniform is a variable set up by JS, but remains constant across the whole frame. This usually
// stores "global" information, like lighting information. It is available to the vertex and
// fragment shader.
// See also: https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Data
const programInfo = program_info(gl, shaderProgram);
initBuffers(gl);
return [programInfo, fsSource, parse_type];
}
/**
* Render the bytebeat with the given parameters
* @param {WebGL2RenderingContext} gl
* @param {ProgramInfo} programInfo
* @param {BytebeatParams} params
*/
export function renderBytebeat(gl, programInfo, params) {
setUniforms(gl, programInfo, params);
render(gl, programInfo.attribs.position);
}