-
Notifications
You must be signed in to change notification settings - Fork 0
/
Shader.ts
83 lines (69 loc) · 1.97 KB
/
Shader.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
export default class Shader {
public program: WebGLProgram;
private gl: WebGL2RenderingContext;
private numOfIndices: number;
constructor(
gl: WebGL2RenderingContext,
vShaderSrc: string,
fShaderSrc: string
) {
const program = gl.createProgram();
let compiled: boolean;
const vShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vShader, vShaderSrc);
gl.compileShader(vShader);
compiled = gl.getShaderParameter(vShader, gl.COMPILE_STATUS);
if (!compiled) {
console.warn(
"Vertex shader compiler log: " + gl.getShaderInfoLog(vShader)
);
}
const fShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fShader, fShaderSrc);
gl.compileShader(fShader);
compiled = gl.getShaderParameter(fShader, gl.COMPILE_STATUS);
if (!compiled) {
console.warn(
"Fragment shader compiler log: " + gl.getShaderInfoLog(fShader)
);
}
gl.attachShader(program, vShader);
gl.attachShader(program, fShader);
gl.deleteShader(vShader);
gl.deleteShader(fShader);
// todo: check failure
gl.linkProgram(program);
this.program = program;
this.gl = gl;
}
public use() {
this.gl.useProgram(this.program);
}
public set2fv(name: string, v: Float32Array) {
this.gl.uniform2fv(this.gl.getUniformLocation(this.program, name), v);
}
public setFloat(name: string, v: number) {
this.gl.uniform1f(this.gl.getUniformLocation(this.program, name), v);
}
public setMat4(name: string, mat4: Float32Array) {
this.gl.uniformMatrix4fv(
this.gl.getUniformLocation(this.program, name),
false,
mat4
);
}
public setNumOfIndices(n: number) {
this.numOfIndices = n;
}
public draw(buffer: WebGLVertexArrayObject, type?: GLenum) {
const { gl } = this;
gl.bindVertexArray(buffer);
gl.drawElements(
type || gl.TRIANGLES,
this.numOfIndices,
gl.UNSIGNED_SHORT,
0
);
gl.bindVertexArray(null);
}
}