outsource async fetching

This commit is contained in:
Emile Clark-Boman 2026-02-02 05:02:18 +10:00
parent 618a3aec23
commit 1683d2bbe9
3 changed files with 42 additions and 30 deletions

View file

@ -2,18 +2,31 @@ import { Smc } from "./smc/smc.js"
main();
async function fetchShader(uri, delegate) {
const res = await fetch(uri);
if (res.ok)
return await res.text();
this.raiseError(
SmcErr.FETCH_SHADER,
`Failed to load shader source ${url}: ${res.status} ${res.json()}`);
return ""
}
function main() {
const canvas = document.querySelector("#gl-canvas");
canvas.setAttribute('width', window.innerWidth);
canvas.setAttribute('height', window.innerHeight);
new Smc(canvas)
.setMaxFps(30)
.setProgram(builder =>
builder
// .fetchVertexShader("../shaders/segfault.glsl")
// .fetchFragmentShader("../shaders/segfault.glsl"))
)
.run();
fetchShader("../shaders/segfault.glsl")
.then(frag =>
new Smc(canvas)
.setMaxFps(30)
.setProgram(builder =>
builder
.addFragmentShader(frag))
.run()
);
}

View file

@ -71,19 +71,21 @@ class SmcProgramBuilder {
source
)
)
console.log(source)
this.#hasFragmentShader = true;
return this;
}
fetchVertexShader(uri) {
this.#fetchShader(uri, (source) => this.addVertexShader(source));
return this;
}
// fetchVertexShader(uri) {
// (async () => this.#fetchShader(uri, (source) => this.addVertexShader(source)))();
// return this;
// }
fetchFragmentShader(uri) {
this.#fetchShader(uri, (source) => this.addFragmentShader(source));
return this;
}
// async fetchFragmentShader(uri) {
// var delegate = (source) => this.addFragmentShader(source);
// var source = await this.#fetchShader(uri);
// return this;
// }
build() {
// avoid user accidental calls to build()
@ -117,18 +119,15 @@ class SmcProgramBuilder {
return shader;
}
#fetchShader(uri, delegate) {
return fetch(uri)
.then(res => {
if (res.ok)
delegate(res.text());
else {
this.raiseError(
SmcErr.FETCH_SHADER,
`Failed to load shader source ${url}: ${res.status} ${res.json()}`);
}
});
}
// async #fetchShader(uri, delegate) {
// const res = await fetch(uri);
// if (res.ok)
// return await res.text();
// this.raiseError(
// SmcErr.FETCH_SHADER,
// `Failed to load shader source ${url}: ${res.status} ${res.json()}`);
// return ""
// }
}

View file

@ -127,9 +127,9 @@ class Smc {
setProgram(delegate) {
const builder = new SmcProgramBuilder(this.#gl, this.raiseError);
delegate(builder); // i pray js passes by ref well...
var result = delegate(builder);
this.#program = builder.build();
this.#program = result.build();
if (!this.#gl.getProgramParameter(this.#program, this.#gl.LINK_STATUS)) {
const infoLog = this.#gl.getProgramInfoLog(this.#program);
this.raiseError(