Commit 10b9b49a authored by Laureline Nevin's avatar Laureline Nevin ⌨️
Browse files

Added WebGL shader HMR support

parent 5b1d2ce5
Loading
Loading
Loading
Loading
+27 −9
Changes for src/app.ts: 27 added lines, 9 removed lines.
Original line number Diff line number Diff line
@@ -5,6 +5,8 @@ import {
    resizeCanvasToDisplaySize,
    ExportRectProgram,
    WebGLCanvasRenderingContext,
    SHADER_UPDATE_EVENT,
    shaderUpdateNotify,
} from './gl-program.ts';
import { ControlUpdateEvent, getStateDefaults, LIGHT_ANGLE_DEFAULTS, State } from './control.ts';
import { catchError, DEBUG, exportValues, getLightSourceVec, matToString, roundTo, VERBOSE } from './utils.ts';
@@ -30,7 +32,7 @@ export type RunPhase = (typeof RUN_PHASES)[number];

type LocString = string | Record<string, string>;
export class App {
    private readonly programs: {
    private programs!: {
        readonly relight: RelightProgram;
        readonly lightball: LightballProgram;
        readonly export: ExportRectProgram;
@@ -74,11 +76,20 @@ export class App {
            relight: this.getGLContext(document.querySelector('canvas#ivoire-display') as HTMLCanvasElement),
            lightball: this.getGLContext(document.querySelector('canvas#ivoire-lightball') as HTMLCanvasElement),
        };
        this.programs = {
            relight: new RelightProgram(this.gls.relight),
            lightball: new LightballProgram(this.gls.lightball),
            export: new ExportRectProgram(this.gls.relight),
        };

        this.setPrograms();

        if (import.meta.hot) {
            shaderUpdateNotify?.addEventListener(SHADER_UPDATE_EVENT, () => {
                console.debug('Recompiling WebGL programs…');
                try {
                    this.setPrograms();
                    this.requestRender();
                } catch (err: any) {
                    catchError(false, err);
                }
            });
        }

        this.rx = reactive(this.DEFAULT_RX_STATE);
        this.initControls();
@@ -122,6 +133,14 @@ export class App {
            .catch(catchError(true));
    }

    private setPrograms() {
        this.programs = {
            relight: new RelightProgram(this.gls.relight),
            lightball: new LightballProgram(this.gls.lightball),
            export: new ExportRectProgram(this.gls.relight),
        };
    }

    private makeI18n(translations: Record<string, Record<string, any>>): I18n {
        if (
            Object.keys(translations).length !== App.LANGS.length ||
@@ -413,7 +432,7 @@ export class App {
                ...exportedState,
                renderArea: this.source.totalSize,
                lightSource: getLightSourceVec(exportedState),
                exportParams: this.rx.phase === 'export' ? this.rx.raw().exportParams : null
                exportParams: this.rx.phase === 'export' ? this.rx.raw().exportParams : null,
            };

            let join = [...data.lightSource].map((v) => roundTo(v)).join(', ');
@@ -425,8 +444,7 @@ export class App {

            output += '\n' + this.programs.relight.renderSource(this.source, data);
            output += '\n' + this.programs.lightball.render(data);
            if (data.exportParams)
                output += '\n' + this.programs.export.render(data);
            if (data.exportParams) output += '\n' + this.programs.export.render(data);
        } else {
            this.programs.relight.clearCanvas();
        }
+63 −4
Changes for src/gl-program.ts: 63 added lines, 4 removed lines.
Original line number Diff line number Diff line
@@ -32,6 +32,52 @@ type CommonKeys<T, U> = {
    [K in keyof T]: K extends keyof U ? K : never;
}[keyof T];

const SHADERS = {
        relight: { vertex: rlghtVtxSource, fragment: rlghtFrgSource },
        lightball: { vertex: lghtbllVtxSource, fragment: lghtbllFrgSource },
        export: { vertex: exportRectVtxSource, fragment: exportRectFrgSource },
    },
    sourceIdx = [
        ['relight', 'vertex'],
        ['relight', 'fragment'],
        ['lightball', 'vertex'],
        ['lightball', 'fragment'],
        ['export', 'vertex'],
        ['export', 'fragment'],
    ] as const;
export const SHADER_UPDATE_EVENT = 'shaderupdate';
export const shaderUpdateNotify = import.meta.hot ? new EventTarget() : null;
if (import.meta.hot) {
    let updateDebounced = false;
    import.meta.hot.accept(
        [
            '/src/shaders/relight.vert',
            '/src/shaders/relight.frag',
            '/src/shaders/lightball.vert',
            '/src/shaders/lightball.frag',
            '/src/shaders/exportRect.vert',
            '/src/shaders/exportRect.frag',
        ],
        (newModules) => {
            console.debug('Vite module accept', newModules);
            newModules.forEach((mod, i) => {
                if (mod && typeof mod.default === 'string') {
                    console.debug(`Module ${sourceIdx[i]} updated:`);
                    SHADERS[sourceIdx[i][0]][sourceIdx[i][1]] = mod.default as string;
                }
            });
            if (!updateDebounced) {
                setTimeout(() => {
                    shaderUpdateNotify!.dispatchEvent(new Event(SHADER_UPDATE_EVENT));
                    updateDebounced = false;
                }, 250);
                updateDebounced = true;
            }
        },
    );
    import.meta.hot.on('vite:afterUpdate', (ev) => console.debug('vite:afterUpdate', ev));
}

abstract class GLProgramBase<Attribs extends string[], Uniforms extends string[]> {
    protected static DEFAULT_UNIFORMS = {
        lightVector: 'uLightVector',
@@ -48,6 +94,7 @@ abstract class GLProgramBase<Attribs extends string[], Uniforms extends string[]
    private static _MAX_VIEWPORT_SIZE: number;
    public readonly gl: WebGLRenderingContext;
    public readonly program: WebGLProgram;
    public static readonly sourceUpdate = shaderUpdateNotify;
    protected attributes: { [key in Attribs[number]]: GLAttribute };
    protected uniformLocations: { [key in keyof typeof GLProgramBase.DEFAULT_UNIFORMS]: WebGLUniformLocation } & {
        [key in Uniforms[number]]: WebGLUniformLocation;
@@ -230,7 +277,13 @@ export class RelightProgram extends GLProgramBase<
    };

    public constructor(gl: WebGLRenderingContext) {
        super(gl, rlghtVtxSource, rlghtFrgSource, RelightProgram.attributes, RelightProgram.uniformNames);
        super(
            gl,
            SHADERS.relight.vertex,
            SHADERS.relight.fragment,
            RelightProgram.attributes,
            RelightProgram.uniformNames,
        );
        const bgCol = [24, 16, 8, 0].map((v) => ((RelightProgram.CLEAR_COLOR >> v) & 0xff) / 0xff) as [
            number,
            number,
@@ -343,7 +396,13 @@ export class LightballProgram extends GLProgramBase<
    };

    constructor(gl: WebGLRenderingContext) {
        super(gl, lghtbllVtxSource, lghtbllFrgSource, LightballProgram.attributes, LightballProgram.uniformNames);
        super(
            gl,
            SHADERS.lightball.vertex,
            SHADERS.lightball.fragment,
            LightballProgram.attributes,
            LightballProgram.uniformNames,
        );
        this.buffers = {
            vertexPosition: this.initPositionBuffer(),
        };
@@ -413,8 +472,8 @@ export class ExportRectProgram extends GLProgramBase<
    constructor(gl: WebGLRenderingContext) {
        super(
            gl,
            exportRectVtxSource,
            exportRectFrgSource,
            SHADERS.export.vertex,
            SHADERS.export.fragment,
            ExportRectProgram.attributes,
            ExportRectProgram.uniformNames,
        );
+1 −1
Changes for vite.config.js: 1 added line, 1 removed line.
Original line number Diff line number Diff line
@@ -12,7 +12,7 @@ export default defineConfig({
        plugins: () => [glsl()],
    },
    server: {
        hmr: false, // Uncomment to disable hot reload
        // hmr: false, // Uncomment to disable hot reload
        proxy: {
            '/demo': {
                target: 'http://localhost/ivoire-datasets/',