-
Notifications
You must be signed in to change notification settings - Fork 0
/
shader-engine.js
84 lines (67 loc) · 2.35 KB
/
shader-engine.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
function initGl(canvas, width, height) {
const gl = canvas.getContext("webgl2");
if (gl === null) {
alert("Unable to initialize WebGL. Your browser or machine may not support it.");
return null;
}
gl.viewport(0, 0, width, height);
return gl;
}
function loadShader(gl, type, source) {
const shader = gl.createShader(type);
gl.shaderSource(shader, source);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
alert('An error occurred compiling the shaders: ' + gl.getShaderInfoLog(shader));
gl.deleteShader(shader);
return null;
}
return shader;
}
function initProgram(gl, vs_src, fs_src) {
const vs = loadShader(gl, gl.VERTEX_SHADER, vs_src);
const fs = loadShader(gl, gl.FRAGMENT_SHADER, fs_src);
const program = gl.createProgram();
gl.attachShader(program, vs);
gl.attachShader(program, fs);
gl.linkProgram(program);
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
alert('Unable to initialize the shader program: ' + gl.getProgramInfoLog(shaderProgram));
return null;
}
return program;
}
function makeQuad(gl) {
const quad = gl.createBuffer();
const positions = new Float32Array([
-1.0, 1.0,
1.0, 1.0,
-1.0, -1.0,
1.0, -1.0,
]);
gl.bindBuffer(gl.ARRAY_BUFFER, quad);
gl.bufferData(gl.ARRAY_BUFFER, positions, gl.STATIC_DRAW);
return quad;
}
function clear(gl) {
gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.clearDepth(1.0);
gl.enable(gl.DEPTH_TEST);
gl.depthFunc(gl.LEQUAL);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
}
function drawScene(gl, program, geometry, width, height, time, r1, r2, r3) {
const vertexPosition = gl.getAttribLocation(program, 'pos');
clear(gl);
gl.bindBuffer(gl.ARRAY_BUFFER, geometry);
gl.vertexAttribPointer(vertexPosition, 2, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(vertexPosition);
gl.useProgram(program);
gl.uniform1f(gl.getUniformLocation(program, 'iR1'), r1);
gl.uniform1f(gl.getUniformLocation(program, 'iR2'), r2);
gl.uniform1f(gl.getUniformLocation(program, 'iR3'), r3);
gl.uniform1f(gl.getUniformLocation(program, 'iTime'), time / 1000.0);
gl.uniform2f(gl.getUniformLocation(program, 'iResolution'), width, height);
/*gl.uniform1f(gl.getUniformLocation(program, 'iResolution'), time / 1000.0);*/
gl.drawArrays(gl.TRIANGLE_STRIP, 0 /* offset */, 4 /* vertexCount */);
}