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

Added mouse controls for export window resizing

parent 10b9b49a
Loading
Loading
Loading
Loading
+122 −10
Changes for src/app.ts: 122 added lines, 10 removed lines.
Original line number Diff line number Diff line
@@ -9,7 +9,16 @@ import {
    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';
import {
    arraysEq,
    catchError,
    DEBUG,
    exportValues,
    getLightSourceVec,
    matToString,
    roundTo,
    VERBOSE,
} from './utils.ts';
import { DownloadManager } from './download.ts';
import { Dataset, MemoryDataset, SingleDataset, TiledDataset } from './dataset.ts';
import { ExportWorkerData, ExportWorkerResult } from './workers/export.ts';
@@ -68,15 +77,16 @@ export class App {

        this.i18n = this.makeI18n(translations);

        this.state = getStateDefaults();
        (window as any).app = App._app = this;
        this.state.viewport.addEventListener(Viewport.ChangeEvent.type, () => this.updateRenderArea(false));

        this.gls = {
            relight: this.getGLContext(document.querySelector('canvas#ivoire-display') as HTMLCanvasElement),
            lightball: this.getGLContext(document.querySelector('canvas#ivoire-lightball') as HTMLCanvasElement),
        };

        this.state = getStateDefaults();
        (window as any).app = App._app = this;
        this.state.viewport.updateCanvasMat(this.gls.relight.canvas);
        this.state.viewport.addEventListener(Viewport.ChangeEvent.type, () => this.updateRenderArea(false));

        this.setPrograms();

        if (import.meta.hot) {
@@ -89,6 +99,7 @@ export class App {
                    catchError(false, err);
                }
            });
            import.meta.hot.on('vite:afterUpdate', () => this.requestRender());
        }

        this.rx = reactive(this.DEFAULT_RX_STATE);
@@ -757,10 +768,78 @@ export class App {
        exportDialog.close();
    }

    /**
     * Returns the coordinates of the given quadrant of the export window divided into thirds on both axes
     * @param x horizontal coordinate of the quadrant
     * @param y vertical coordinate of the quadrant
     */
    private getExportWindowQuadrant([x, y]: [0 | 1 | 2, 0 | 1 | 2]): vec2 {
        const params = this.rx.exportParams;
        return [params.offset[0] + (x * params.size[0]) / 2, params.offset[1] + (y * params.size[1]) / 2];
    }

    /**
     * Sets the coordinates of the given quadrant of the export window divided into thirds on both axes
     * @param x horizontal coordinate of the quadrant
     * @param y vertical coordinate of the quadrant
     * @param value position to set the given quadrant to
     * @param keepRatio whether aspect ratio should be kept unmodified by the operation
     */
    private setExportWindowQuadrant([x, y]: [0 | 1 | 2, 0 | 1 | 2], value: vec2, keepRatio = false) {
        const params = this.rx.exportParams;
        const prev = structuredClone(this.rx.raw().exportParams);
        const curVal = this.getExportWindowQuadrant([x, y]);
        const diff = vec2.sub([0, 0], value, curVal);
        if (x === 1 && y === 1) {
            // Center
            params.offset[0] += diff[0];
            params.offset[1] += diff[1];
        } else if (x === 1) {
            const nh = params.size[1] + diff[1] * (y - 1);
            if (y === 0) {
                params.offset[1] += diff[1]; // Bottom
            }
            if (keepRatio){
                const nw = (params.size[0] * nh) / params.size[1]
                params.offset[0] += (params.size[0] - nw) / 2;
                params.size[0] = nw;
            }
            params.size[1] = nh;
        } else if (y === 1) {
            const nw = params.size[0] + diff[0] * (x - 1);
            if (x === 0) {
                params.offset[0] += diff[0]; // Left
            }
            if (keepRatio){
                const nh = (params.size[1] * nw) / params.size[0];
                params.offset[1] += (params.size[1] - nh) / 2;
                params.size[1] = nh;
            }
            params.size[0] = nw;
        } else {
            // Corner
            params.size[0] += diff[0] * (x - 1);
            params.size[1] += diff[1] * (y - 1);
            if (x === 0)
                params.offset[0] += diff[0];
            if (y === 0)
                params.offset[1] += diff[1];
        }
        console.debug(
            `setExportWindowQuadrant(${[x, y]}, ${[roundTo(value)]}):
  cur:\t ${roundTo(curVal, 0).join(' : ')}
  new:\t ${roundTo(value, 0).join(' : ')}
  dif:\t ${roundTo(diff, 0).join(' : ')}
  pre:\t offset=${roundTo(prev.offset, 0)}, size=${roundTo(prev.size, 0)}
  par:\t offset=${roundTo(this.rx.exportParams.offset, 0)}, size=${roundTo(this.rx.exportParams.size, 0)}`,
        );
    }

    private bindPointerEvents() {
        const onPointerEvent = (ev: PointerEvent | WheelEvent) => {
            const viewport = this.state.viewport!;
            const pointerState = this.state.pointerState;
            if (!this.source) return;

            let lightball = pointerState.dragging
                ? pointerState.overLightball
@@ -785,14 +864,20 @@ export class App {
                    this.state.lighttheta = (1 - Math.min(lbdist / lbradius, 1)) * 90;
                } else {
                    let texCoord = viewport.screenToTexture(evpos);
                    if (pointerState.exportWindowHover) {
                        vec2.sub(texCoord, texCoord, pointerState.origin);
                        this.setExportWindowQuadrant(pointerState.exportWindowHover!, texCoord);
                    } else {
                        let diff = vec2.sub([0, 0], texCoord, pointerState.origin);
                        viewport.move(diff);
                    }
                }
                this.requestRender();
            };

            const highlight = () => {
                if (!ev.shiftKey || !DEBUG || !(ev.buttons & 1) || !this.source) return false;
            const highlight = DEBUG
                ? () => {
                      if (!ev.shiftKey || !(ev.buttons & 1) || !this.source) return false;
                      const texCoord = viewport.screenToTexture(evpos);
                      let changed = false;
                      const highlighted = [];
@@ -807,14 +892,36 @@ export class App {
                      if (changed) console.log(texCoord, 'highlighted:', highlighted);
                      this.requestRender();
                      return true;
                  }
                : () => false;

            const exportWindowPart = (pos: vec2): [0 | 1 | 2, 0 | 1 | 2] | null => {
                if (this.rx.phase !== 'export' || lightball) return null;
                const [x, y] = this.rx.exportParams.offset,
                    [w, h] = this.rx.exportParams.size;
                if (!new Rect(x, y, w, h).includes(pos)) return null;
                return [
                    pos[0] < x + w / 3 ? 0 : pos[0] < x + (w * 2) / 3 ? 1 : 2,
                    pos[1] < y + h / 3 ? 0 : pos[1] < y + (h * 2) / 3 ? 1 : 2,
                ];
            };

            if (ev instanceof PointerEvent && ev.type === 'pointerdown') {
                if (pointerState.dragging || !ev.isPrimary || ev.button !== 0) return;
                if (!highlight()) {
                    pointerState.dragging = true;
                    const texPos = viewport.screenToTexture(evpos);
                    pointerState.overLightball = lightball;
                    pointerState.origin = viewport.screenToTexture(evpos);
                    pointerState.origin = texPos;
                    pointerState.exportWindowHover = exportWindowPart(texPos);
                    if (pointerState.exportWindowHover) {
                        vec2.sub(
                            pointerState.origin,
                            pointerState.origin,
                            this.getExportWindowQuadrant(pointerState.exportWindowHover),
                        );
                    }
                    console.log(structuredClone(pointerState));
                    doUpdate();
                    window.addEventListener('wheel', onPointerEvent, { passive: false });
                }
@@ -825,17 +932,22 @@ export class App {
                pointerState.dragging = false;
                canvas.setPointerCapture(ev.pointerId);
                window.removeEventListener('wheel', onPointerEvent);
            } else if (ev instanceof PointerEvent && ev.type === 'pointermove') {
            } else if (ev instanceof PointerEvent && ev.type === 'pointermove')
                if (pointerState.dragging) {
                    doUpdate();
                } else {
                    highlight();
                    const windowPart = exportWindowPart(viewport.screenToTexture(evpos));
                    if (!arraysEq(windowPart, pointerState.exportWindowHover)) {
                        pointerState.exportWindowHover = windowPart;
                        this.requestRender();
                    }
                    if (lightball !== pointerState.overLightball) {
                        pointerState.overLightball = lightball;
                        this.requestRender();
                    }
                }
            } else if (ev instanceof WheelEvent && ev.type === 'wheel') {
            else if (ev instanceof WheelEvent && ev.type === 'wheel') {
                const SCROLL_FACTOR = 1.01;
                if (this.state.pointerState.dragging || ev.currentTarget === canvas) {
                    ev.stopPropagation();
+1 −0
Changes for src/control.ts: 1 added line, 0 removed lines.
Original line number Diff line number Diff line
@@ -259,6 +259,7 @@ export function getStateDefaults() {
            dragging: false,
            overLightball: false,
            origin: vec2.create(),
            exportWindowHover: null as [0 | 1 | 2, 0 | 1 | 2] | null, // Which quadrant of the export window is currently hovered
        },
    };
}
+12 −3
Changes for src/gl-program.ts: 12 added lines, 3 removed lines.
Original line number Diff line number Diff line
@@ -428,7 +428,11 @@ export class LightballProgram extends GLProgramBase<
            circle = vec3.fromValues(center[0], center[1], radius),
            alpha =
                LightballProgram.ALPHA[
                    data.pointerState.overLightball ? (data.pointerState.dragging ? 'active' : 'hover') : 'inactive'
                    data.pointerState.overLightball
                        ? data.pointerState.dragging
                            ? 'active'
                            : 'hover'
                        : 'inactive'
                ];

        gl.uniformMatrix4fv(this.uniformLocations.projectionMatrix, false, projection);
@@ -455,7 +459,7 @@ export class ExportRectProgram extends GLProgramBase<
> {
    public static readonly PARAMS = {
        cornerRadius: 25,
        lineSize: 4,
        lineSize: 1,
        color: [1, 1, 0, 0.5] as const,
    };
    static attributes = {
@@ -464,6 +468,7 @@ export class ExportRectProgram extends GLProgramBase<
    static uniformNames = {
        color: 'uColor',
        exportRect: 'uExportRect',
        windowPartHover: 'uWindowPartHover',
        lineWidth: 'uLineWidth',
        projectionMatrix: 'uProjectionMatrix',
        renderRect: 'uRenderRect',
@@ -499,12 +504,16 @@ export class ExportRectProgram extends GLProgramBase<

        gl.uniformMatrix4fv(this.uniformLocations.projectionMatrix, false, data.viewport.projectionMat);

        if (data.pointerState.exportWindowHover) {
            const windowPartVal = [...data.pointerState.exportWindowHover!, data.pointerState.dragging ? 2 : 1];
            gl.uniform3iv(this.uniformLocations.windowPartHover, windowPartVal);
        } else gl.uniform3i(this.uniformLocations.windowPartHover, -1, -1, 0);
        gl.uniform4f(this.uniformLocations.exportRect, ...data.exportParams!.offset, ...data.exportParams!.size);
        gl.uniform4f(this.uniformLocations.renderRect, 0, 0, ...data.renderArea);
        gl.uniform1f(this.uniformLocations.lineWidth, lineSize);
        gl.uniform4fv(this.uniformLocations.color, color);

        const area = new Rect(0, 0, ...data.renderArea).grow(lineSize);
        const area = new Rect(0, 0, ...data.renderArea).grow(lineSize * 4);
        this.setAttribute('vertexPosition');
        this.gl.bufferData(GL.ARRAY_BUFFER, area.vertexPositions(), GL.DYNAMIC_DRAW);
        gl.drawArrays(GL.TRIANGLE_STRIP, 0, 4);
+2 −15
Changes for src/main.ts: 2 added lines, 15 removed lines.
Original line number Diff line number Diff line
@@ -7,25 +7,12 @@ import { catchError } from './utils.ts';

DownloadManager.setBar(document.querySelector('progress#load-progress') as HTMLProgressElement);

const iconTpl = document.querySelector('template#svg-icon') as HTMLTemplateElement;
for (const el of document.querySelectorAll('*[data-icon]')) {
    const icon = el.getAttribute('data-icon');
    if (!icon) throw new Error();
    const content = iconTpl.content.cloneNode(true) as HTMLElement;
    const useTag = content.querySelector('use')!;
    useTag.setAttribute('href', useTag.getAttribute('href')!.replace('{{icon}}', icon));
    if (el.tagName.toLowerCase() === 'svg') {
        el.parentElement!.replaceChild(content, el);
    } else {
        el.replaceChildren(content);
        el.removeAttribute('data-icon');
    }
}

try {
    const app = new App({ en, fr });

    const vApp = createApp(app.rx);
    const iconTpl = document.querySelector('template#svg-icon') as HTMLTemplateElement;

    vApp.directive('icon', ({ el, exp, modifiers, effect }) => {
        effect(() => {
            if (!exp) throw new Error();
+10 −4
Changes for src/shaders/exportRect.frag: 10 added lines, 4 removed lines.
Original line number Diff line number Diff line
precision mediump float;

uniform ivec3 uWindowPartHover;
uniform mediump vec4 uColor;
uniform mediump vec4 uRenderRect;
uniform mediump vec4 uExportRect;
@@ -16,13 +17,18 @@ float rectDist(vec2 pos, vec4 rect) {
void main(void) {
    float dist = rectDist(vVertexCoord, uExportRect);
    if (dist < 0.) {
        vec4 windowPart = vec4(uExportRect.xy + vec2(uWindowPartHover.xy) * uExportRect.zw / 3.,
            uExportRect.zw / 3.);
        if (uWindowPartHover.z != 0 && rectDist(vVertexCoord, windowPart) <= 0.) {
            gl_FragColor = vec4(0., 0., 0., float(uWindowPartHover.z) * .2);
        } else {
            discard; // Inside export rectangle
    } else if (dist <= uLineWidth) {
        vec4 col = uColor;
        gl_FragColor = col;
        }
    } else if (dist <= uLineWidth * 4.) {
        gl_FragColor = uColor;
    } else if (rectDist(vVertexCoord, uRenderRect) <= 0.) {
        // In render area, outside of export window
        gl_FragColor = vec4(0., 0., 0., mod((vVertexCoord.x + vVertexCoord.y) / uLineWidth / 2., 2.) > 1. ? .2 : .1);
        gl_FragColor = vec4(0., 0., 0., mod((vVertexCoord.x + vVertexCoord.y) / (uLineWidth * 8.), 2.) > 1. ? .2 : .1);
    } else {
        // Outside of render area
        discard;
Loading