-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
webgl.ts
92 lines (75 loc) · 2.22 KB
/
webgl.ts
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
import { WebGLCanvas } from "../src/webgl/mod.ts";
const window = new WebGLCanvas({
title: "Deno DWM + Native WebGL",
width: 800,
height: 600,
resizable: true,
});
const gl = window.getContext("webgl");
addEventListener("resize", (event) => {
gl.viewport(0, 0, event.width, event.height);
});
// deno-lint-ignore no-explicit-any
let vertBuffer: any, shaderProg: any, shaderVertPosAttr: any;
function init() {
vertBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertBuffer);
const verts = [
0.0,
1.0,
0.0,
1.0,
-1.0,
0.0,
-1.0,
-1.0,
0.0,
];
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(verts), gl.STATIC_DRAW);
const checkShaderCompile = function (shader: WebGLShader, type: string) {
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
const errmes = type + " shader compile failed: " +
gl.getShaderInfoLog(shader);
throw new Error(errmes);
}
};
const vertShaderSource = `
attribute vec3 vertPos;
void main(void) {
gl_Position = vec4(vertPos, 1.0);
}`;
const vertShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertShader, vertShaderSource);
gl.compileShader(vertShader);
checkShaderCompile(vertShader, "vertex");
const fragShaderSource = `
void main(void) {
gl_FragColor = vec4(0.0, 0.0, 1.0, 1.0);
}`;
const fragShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragShader, fragShaderSource);
gl.compileShader(fragShader);
checkShaderCompile(fragShader, "fragment");
shaderProg = gl.createProgram();
gl.attachShader(shaderProg, vertShader);
gl.attachShader(shaderProg, fragShader);
gl.linkProgram(shaderProg);
shaderVertPosAttr = gl.getAttribLocation(shaderProg, "vertPos");
gl.enableVertexAttribArray(shaderVertPosAttr);
}
function draw() {
gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.enable(gl.DEPTH_TEST);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
gl.useProgram(shaderProg);
gl.bindBuffer(gl.ARRAY_BUFFER, vertBuffer);
gl.vertexAttribPointer(shaderVertPosAttr, 3, gl.FLOAT, false, 0, 0);
gl.drawArrays(gl.TRIANGLES, 0, 3);
}
function frame() {
draw();
requestAnimationFrame(frame);
}
init();
requestAnimationFrame(frame);
await window.run();