54 lines
1.5 KiB
JavaScript
54 lines
1.5 KiB
JavaScript
"use strict";
|
|
|
|
async function fetchShaderSource(path) {
|
|
const response = await fetch(path);
|
|
const text = await response.text();
|
|
return text;
|
|
}
|
|
|
|
function compileShader(gl, type, source) {
|
|
const shader = gl.createShader(type);
|
|
gl.shaderSource(shader, source);
|
|
gl.compileShader(shader);
|
|
|
|
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
|
|
const info = gl.getShaderInfoLog(shader);
|
|
throw new Error(`Could not compile shader: ${info}`);
|
|
}
|
|
|
|
return shader;
|
|
}
|
|
|
|
async function fetchAndCompileShader(gl, type, path) {
|
|
const source = await fetchShaderSource(path);
|
|
return compileShader(gl, type, source);
|
|
}
|
|
|
|
function linkShaderProgram(gl, vertexShader, fragmentShader) {
|
|
const program = gl.createProgram();
|
|
gl.attachShader(program, vertexShader);
|
|
gl.attachShader(program, fragmentShader);
|
|
gl.linkProgram(program);
|
|
|
|
// check link status
|
|
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
|
|
const info = gl.getProgramInfoLog(program);
|
|
throw new Error(`Could not link shader program: ${info}`);
|
|
}
|
|
|
|
gl.validateProgram(program);
|
|
|
|
// check validation status
|
|
if (!gl.getProgramParameter(program, gl.VALIDATE_STATUS)) {
|
|
const info = gl.getProgramInfoLog(program);
|
|
throw new Error(`Could not validate shader program: ${info}`);
|
|
}
|
|
|
|
return program;
|
|
}
|
|
|
|
async function buildShaderProgram(gl, vertexPath, fragmentPath) {
|
|
let vertexShader = await fetchAndCompileShader(gl, gl.VERTEX_SHADER, vertexPath);
|
|
let fragmentShader = await fetchAndCompileShader(gl, gl.FRAGMENT_SHADER, fragmentPath);
|
|
return linkShaderProgram(gl, vertexShader, fragmentShader);
|
|
} |