/
Shader.ts
75 lines (63 loc) · 1.98 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
import type Context from "#Context";
import type ShaderType from "#ShaderType";
import UnsupportedOperationError from "#UnsupportedOperationError";
import ShaderCompileError from "#ShaderCompileError";
import { DELETE_STATUS, COMPILE_STATUS } from "#constants";
/**
* A function which runs on the GPU.
* @see [Shaders](https://www.lakuna.pw/a/webgl/shaders)
*/
export default class Shader {
/**
* Creates a shader from source code.
* @param type The type of the shader.
* @param source The source code of the shader.
*/
public constructor(context: Context, type: ShaderType, source: string) {
this.context = context;
this.type = type;
this.source = source;
const shader: WebGLShader | null = context.internal.createShader(type);
if (!shader) {
throw new UnsupportedOperationError();
}
this.internal = shader;
context.internal.shaderSource(shader, source);
context.internal.compileShader(shader);
if (!this.compileStatus) {
const message: string = this.infoLog;
this.delete();
throw new ShaderCompileError(message);
}
}
/** The rendering context of this shader. */
public readonly context: Context;
/** The type of this shader. */
public readonly type: ShaderType;
/** The source code of this shader. */
public readonly source: string;
/** The WebGL API interface of this shader. */
public readonly internal: WebGLShader;
/** Whether this shader is flagged for deletion. */
public get deleteStatus(): boolean {
return this.context.internal.getShaderParameter(
this.internal,
DELETE_STATUS
);
}
/** Whether the last shader compilation was successful. */
public get compileStatus(): boolean {
return this.context.internal.getShaderParameter(
this.internal,
COMPILE_STATUS
);
}
/** The information log for this shader. */
public get infoLog(): string {
return this.context.internal.getShaderInfoLog(this.internal) ?? "";
}
/** Deletes this shader. */
public delete(): void {
this.context.internal.deleteShader(this.internal);
}
}