Realistic watercolor drawings
history
Maksim489f5ccdb596
diff --git a/src/app/App.tsx b/src/app/App.tsxindex 992c259..d9f66ac 100644--- a/src/app/App.tsx+++ b/src/app/App.tsx@@ -1,11 +1,14 @@import { useEffect, useState } from 'preact/hooks';import { ActionBar } from '../components/ActionBar';import { BrushLibrary } from '../components/BrushLibrary';-import { DropChoice, Ghost, Toast } from '../components/Overlays';+import { HistoryPanel } from '../components/HistoryPanel';+import { DropChoice, FillChoice, Ghost, Toast } from '../components/Overlays';import { Palette } from '../components/Palette';import { Paper } from '../components/Paper';+import { PaperPanel } from '../components/PaperPanel';import { SettingsPanel } from '../components/SettingsPanel';import { Toolbar } from '../components/Toolbar';+import { ZoomControl } from '../components/ZoomControl';import { ExportPanel } from '../export/ExportPanel';import { ReferencePanel } from '../reference/ReferencePanel';import { RefFrame } from '../reference/RefFrame';@@ -29,12 +32,16 @@ function Chrome() {<ActionBar /><SettingsPanel /><ReferencePanel />+ <PaperPanel />+ <HistoryPanel /><ExportPanel /><Palette />+ <ZoomControl />{[...app.panelTools.values()].map(({ def, tool }) => <def.Panel key={def.id} tool={tool} />)}<RefFrame /><Ghost /><DropChoice />+ <FillChoice /></>;}diff --git a/src/app/keyboard.ts b/src/app/keyboard.tsindex 24ba1e1..1850d04 100644--- a/src/app/keyboard.ts+++ b/src/app/keyboard.ts@@ -11,8 +11,21 @@ export function useKeyboard(app: AppStore) {const k = e.key.toLowerCase();if ((e.metaKey || e.ctrlKey) && k === 'z') { e.preventDefault(); if (e.shiftKey) app.redo(); else app.undo(); return; }if ((e.metaKey || e.ctrlKey) && k === 'y') { e.preventDefault(); app.redo(); return; }+ if ((e.metaKey || e.ctrlKey) && !e.shiftKey && k === 's') { e.preventDefault(); void app.project.save(); return; }+ if ((e.metaKey || e.ctrlKey) && !e.shiftKey && k === 'o') { e.preventDefault(); app.project.requestOpen(); return; }+ // zoom keys replace the browser's page zoom+ const zoomIn = k === '=' || k === '+', zoomOut = k === '-' || k === '_';+ if ((e.metaKey || e.ctrlKey) && !e.altKey && (zoomIn || zoomOut || e.code === 'Digit0')) {+ e.preventDefault();+ if (zoomIn) app.zoomIn(); else if (zoomOut) app.zoomOut(); else app.zoomTo(1);+ return;+ }if (e.metaKey || e.ctrlKey || e.altKey) return;if (k === 'escape') { app.escape(); return; }+ if (e.shiftKey && e.code === 'Digit1') { app.zoomToFit(); return; }+ if (e.shiftKey && e.code === 'Digit0') { app.zoomTo(1); return; }+ if (zoomIn) { app.zoomIn(); return; }+ if (zoomOut) { app.zoomOut(); return; }const tool = [...ENGINE_TOOLS, ...PANEL_TOOLS].find(t => t.key.toLowerCase() === k);if (tool) app.setTool(tool.id);else if (k === '[' || k === ']') app.setParams({ size: Math.min(1, Math.max(0, app.params.peek().size + (k === ']' ? 0.05 : -0.05))) });diff --git a/src/app/navigation.ts b/src/app/navigation.tsnew file mode 100644index 0000000..4a066cb--- /dev/null+++ b/src/app/navigation.ts@@ -0,0 +1,174 @@+import type { WatercolorEngine } from '../engine/Engine';++const LINE_PX = 16; // a wheel "line" in pixels+const WHEEL_ZOOM = 0.01; // zoom per pixel of ⌘ / pinch scroll+const WHEEL_STEP_MAX = 25; // a mouse wheel notch zooms by at most e^(25 * 0.01)++const isEditable = (t: EventTarget | null) =>+ t instanceof HTMLElement && (t.isContentEditable || t.tagName === 'TEXTAREA' || (t instanceof HTMLInputElement && t.type !== 'range'));++type Point = { x: number; y: number };+/** Safari's trackpad pinch (not in the DOM typings). */+type GestureEvent = UIEvent & { scale: number; clientX: number; clientY: number };++/**+ * Figma-style navigation of the sheet: scrolling pans, pinching or ⌘/Ctrl-scrolling+ * zooms about the pointer, Space-drag or middle-drag pans, and two fingers pan and+ * pinch on touch screens. Pointer listeners run in the capture phase so a pan never+ * reaches the engine or the panel tools as a stroke.+ */+export class Navigation {+ private disposers: (() => void)[] = [];+ private space = false;+ private drag: { id: number; x: number; y: number } | null = null;+ private touches = new Map<number, Point>();+ private touchNav: { x: number; y: number; d: number } | null = null;+ private gestureScale = 1;++ constructor(private engine: WatercolorEngine, private canvas: HTMLCanvasElement) {+ const on = (el: EventTarget, type: string, fn: (e: never) => void, opts?: AddEventListenerOptions) => {+ el.addEventListener(type, fn as EventListener, opts);+ this.disposers.push(() => el.removeEventListener(type, fn as EventListener, opts));+ };+ on(window, 'wheel', this.onWheel, { passive: false });+ on(window, 'keydown', this.onKeyDown);+ on(window, 'keyup', this.onKeyUp);+ on(window, 'blur', this.reset);+ on(window, 'pointerdown', this.onDown, { capture: true });+ on(window, 'pointermove', this.onMove, { capture: true });+ on(window, 'pointerup', this.onUp, { capture: true });+ on(window, 'pointercancel', this.onUp, { capture: true });+ // Safari reports trackpad pinches as gestures rather than ctrl + wheel+ on(window, 'gesturestart', this.onGestureStart, { passive: false });+ on(window, 'gesturechange', this.onGestureChange, { passive: false });+ on(window, 'gestureend', (e: Event) => e.preventDefault(), { passive: false });+ }++ destroy() { this.reset(); this.disposers.forEach(d => d()); }++ /** True while Space is held or a pan / pinch is under way. */+ private sync() {+ const panning = this.drag !== null || this.touchNav !== null;+ this.engine.navigating = this.space || panning;+ document.body.classList.toggle('space-pan', this.space);+ document.body.classList.toggle('panning', panning);+ }++ private reset = () => {+ this.space = false;+ this.drag = null;+ this.touches.clear();+ this.touchNav = null;+ this.sync();+ };++ private onWheel = (e: WheelEvent) => {+ const zoom = e.ctrlKey || e.metaKey;+ if (e.target !== this.canvas) {+ if (zoom) e.preventDefault(); // never zoom the page itself+ return;+ }+ e.preventDefault();+ const k = e.deltaMode === 1 ? LINE_PX : e.deltaMode === 2 ? window.innerHeight : 1;+ let dx = e.deltaX * k, dy = e.deltaY * k;+ if (zoom) {+ const d = Math.max(-WHEEL_STEP_MAX, Math.min(WHEEL_STEP_MAX, dy));+ this.engine.zoomAt(e.clientX, e.clientY, Math.exp(-d * WHEEL_ZOOM));+ } else {+ if (e.shiftKey && !dx) [dx, dy] = [dy, 0];+ this.engine.panBy(-dx, -dy);+ }+ };++ private onKeyDown = (e: KeyboardEvent) => {+ if (e.code !== 'Space' || isEditable(e.target)) return;+ e.preventDefault(); // no page scroll, no button press+ if (this.space) return;+ this.space = true;+ this.sync();+ };++ private onKeyUp = (e: KeyboardEvent) => {+ if (e.code !== 'Space' || !this.space) return;+ e.preventDefault();+ this.space = false;+ this.sync();+ };++ private onDown = (e: PointerEvent) => {+ if (e.target !== this.canvas) return;+ if (e.pointerType === 'touch') {+ this.touches.set(e.pointerId, { x: e.clientX, y: e.clientY });+ if (this.touches.size >= 2) {+ // a second finger: the first one's dab is taken back and both fingers navigate+ e.stopPropagation();+ if (!this.touchNav) this.engine.abortStroke();+ this.touchNav = this.measure();+ this.sync();+ return;+ }+ }+ if (e.button === 1 || this.space) {+ e.preventDefault(); // no middle-click autoscroll+ e.stopPropagation();+ this.drag = { id: e.pointerId, x: e.clientX, y: e.clientY };+ try { this.canvas.setPointerCapture(e.pointerId); } catch { /* pointer already gone */ }+ this.sync();+ }+ };++ private onMove = (e: PointerEvent) => {+ const d = this.drag;+ if (d && e.pointerId === d.id) {+ e.stopPropagation();+ this.engine.panBy(e.clientX - d.x, e.clientY - d.y);+ d.x = e.clientX; d.y = e.clientY;+ return;+ }+ const t = this.touches.get(e.pointerId);+ if (!t) return;+ t.x = e.clientX; t.y = e.clientY;+ const prev = this.touchNav;+ if (!prev) return;+ e.stopPropagation();+ const m = this.measure();+ this.engine.panBy(m.x - prev.x, m.y - prev.y);+ if (prev.d > 0 && m.d > 0) this.engine.zoomAt(m.x, m.y, m.d / prev.d);+ this.touchNav = m;+ };++ private onUp = (e: PointerEvent) => {+ if (this.drag?.id === e.pointerId) {+ e.stopPropagation();+ this.drag = null;+ this.sync();+ return;+ }+ if (!this.touches.delete(e.pointerId) || !this.touchNav) return;+ e.stopPropagation();+ // the fingers left keep panning from where they are, until the last one lifts+ this.touchNav = this.touches.size ? this.measure() : null;+ this.sync();+ };++ /** Midpoint and spread of the fingers down (spread 0 for one finger). */+ private measure() {+ const pts = [...this.touches.values()];+ const [a, b] = pts;+ if (!b) return { x: a.x, y: a.y, d: 0 };+ return { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2, d: Math.hypot(a.x - b.x, a.y - b.y) };+ }++ private onGestureStart = (e: GestureEvent) => {+ e.preventDefault();+ this.gestureScale = 1;+ };++ private onGestureChange = (e: GestureEvent) => {+ e.preventDefault();+ // on touch screens the pointer pinch above already handles it+ if (this.touches.size || e.target !== this.canvas) return;+ this.engine.zoomAt(e.clientX, e.clientY, e.scale / this.gestureScale);+ this.gestureScale = e.scale;+ };+}diff --git a/src/app/resize.ts b/src/app/resize.tsindex 4885125..54b050b 100644--- a/src/app/resize.ts+++ b/src/app/resize.ts@@ -3,3 +3,7 @@ import { signal } from '@preact/signals';/** Bumped on every window resize so layout-dependent effects (ghosts, frames, thumbnails) re-run. */export const resizeTick = signal(0);export const bumpResize = () => { resizeTick.value++; };++/** Bumped whenever the sheet is zoomed or panned, so overlays placed on the paper follow it. */+export const viewTick = signal(0);+export const bumpView = () => { viewTick.value++; };diff --git a/src/app/store.ts b/src/app/store.tsindex 62f12e8..eec690d 100644--- a/src/app/store.ts+++ b/src/app/store.ts@@ -1,24 +1,43 @@import { computed, effect, signal } from '@preact/signals';import { BRUSH_PRESETS, buildBrush, type Brush } from '../engine/brushes';-import { DEFAULT_PARAMS, WatercolorEngine, type Params, type Tool } from '../engine/Engine';+import { clampDocSize, DEFAULT_PARAMS, MAX_ZOOM, MIN_ZOOM, WatercolorEngine, type DocState, type DocumentSnapshot, type Params, type Tool } from '../engine/Engine';+import type { StepInfo } from '../engine/history';+import { DEFAULT_PAPER, PAPER_SIZES, PAPERS, type PaperPreset } from '../engine/papers';import { ExportStore } from '../export/ExportStore';-import { PALETTE, type PaletteEntry } from '../palette';-import { isRasterFile } from '../reference/decode';+import { customEntry, PALETTE, type PaletteEntry } from '../palette';+import { isProjectFile, type ProjectData } from '../project/format';+import { ProjectStore } from '../project/ProjectStore';+import { decodeImage, isRasterFile } from '../reference/decode';import { ReferenceStore } from '../reference/ReferenceStore';import type { ShapeStore } from '../shapes/ShapeStore';import { isSvgFile } from '../shapes/svgImport';-import { loadCustomBrushes, makeCustomBrush, saveCustomBrushes, tipFromImage } from '../ui/customBrushes';+import { brushFromStored, loadCustomBrushes, makeCustomBrush, saveCustomBrushes, tipFromImage } from '../ui/customBrushes';import { forgetTipImages } from '../ui/preview';-import { storedString } from './persisted';+import { Navigation } from './navigation';+import { persisted, storedString } from './persisted';import { ENGINE_TOOLS, PANEL_TOOLS } from './registry';+import { bumpView } from './resize';import { showToast } from './toast';import type { PanelTool, PanelToolDef } from './tools';/** An engine tool or the id of a panel tool from the registry. */export type UiTool = Tool | string;-export type PopoverId = 'settings' | 'reference' | 'save';+export type PopoverId = 'settings' | 'reference' | 'save' | 'paper' | 'history';const BRUSH_KEY = 'watercolor.brush';+const PAPER_KEY = 'watercolor.paper';+const PAPER_LOOK_KEY = 'watercolor.paperLook';+const PAPER_SIZE_KEY = 'watercolor.paperSize';+/** Zoom stops for the zoom buttons and keys (Figma-like). */+const ZOOM_STEPS = [0.02, 0.05, 0.1, 0.25, 0.33, 0.5, 0.67, 1, 1.5, 2, 3, 4, 6, 8, 12, 16, 24, 32];++/** The chosen sheet: a preset id from PAPER_SIZES and, for fixed sizes, the size in pixels. */+export interface PaperSizeChoice { preset: string; w: number; h: number }+const sanitizeSize = (v: PaperSizeChoice): PaperSizeChoice => {+ const preset = PAPER_SIZES.some(p => p.id === v.preset) ? v.preset : 'screen';+ const [w, h] = clampDocSize(Number(v.w) || 0, Number(v.h) || 0);+ return { preset, w, h };+};const isEngineTool = (t: UiTool): t is Tool => ENGINE_TOOLS.some(e => e.id === t);/**@@ -41,40 +60,66 @@ export class AppStore {readonly customs = signal<Brush[]>([]);readonly allBrushes = computed(() => [...this.builtIn, ...this.customs.value]);readonly brush = signal<Brush>(this.builtIn[0]);+ /** Texture strength of the paper, 0..1. */+ readonly paperLook = persisted(PAPER_LOOK_KEY, { texture: 1 }, v => ({ texture: Math.min(1, Math.max(0, Number(v.texture) || 0)) }));+ readonly paper = signal<PaperPreset>(PAPERS.find(p => p.id === storedString.get(PAPER_KEY)) ?? DEFAULT_PAPER);/** Colour used for brush previews: the current pigment, or ink for white gouache. */readonly previewHex = computed(() => (this.current.value.pigment.white ? '#3b4552' : this.current.value.hex));- readonly canUndo = signal(false);- readonly canRedo = signal(false);+ /** Every undo step, oldest first, and how many are applied. */+ readonly history = signal<{ list: StepInfo[]; index: number }>({ list: [], index: 0 });+ readonly canUndo = computed(() => this.history.value.index > 0);+ readonly canRedo = computed(() => this.history.value.index < this.history.value.list.length);/** Small panels that drop down under the action bar, one at a time. */readonly popover = signal<PopoverId | null>(null);readonly libraryOpen = signal(false);readonly confirmClear = signal(false);readonly hintGone = signal(false);+ /** The sheet as chosen in the Paper panel (remembered for next time). */+ readonly paperSize = persisted<PaperSizeChoice>(PAPER_SIZE_KEY, { preset: 'screen', w: 0, h: 0 }, sanitizeSize);+ /** The sheet as it is, in pixels. */+ readonly docSize = signal<[number, number]>([1, 1]);+ /** 1 = one sheet pixel per CSS pixel. */+ readonly zoom = signal(1);/** A dropped image waiting for the user to say what it is for. */readonly dropped = signal<{ file: File; x: number; y: number } | null>(null);readonly panelTools = new Map<string, { def: PanelToolDef; tool: PanelTool }>();readonly reference: ReferenceStore;readonly exporter: ExportStore;+ readonly project: ProjectStore;/** The active panel tool, if the current tool is one. */readonly activePanelTool = computed(() => this.panelTools.get(this.tool.value)?.tool ?? null);private confirmTimer = 0;+ private textureBefore: DocState | null = null;+ private readonly navigation: Navigation;constructor(canvas: HTMLCanvasElement, cursor: HTMLElement) {+ const size = this.paperSize.peek();this.engine = new WatercolorEngine(canvas, cursor, {- onHistoryChange: (u, r) => { this.canUndo.value = u; this.canRedo.value = r; },+ onHistoryChange: (list, index) => { this.history.value = { list, index }; },+ onDocumentChange: d => this.syncDocument(d),onStrokeTool: t => { this.strokeTool.value = t; },- });+ onViewChange: (z, d) => {+ this.zoom.value = z;+ const cur = this.docSize.peek();+ if (cur[0] !== d[0] || cur[1] !== d[1]) this.docSize.value = d;+ bumpView();+ },+ }, size.preset === 'screen' ? null : [size.w, size.h]);+ this.navigation = new Navigation(this.engine, canvas);const ctx = { engine: this.engine };for (const def of PANEL_TOOLS) this.panelTools.set(def.id, { def, tool: def.create(ctx) });this.reference = new ReferenceStore(this.engine);- this.exporter = new ExportStore(this.engine);+ this.exporter = new ExportStore(this.engine, () => this.paper.peek().name);+ this.project = new ProjectStore(this);- // mirror state into the engine+ // mirror state into the engine (paper and reference changes are recorded as undo steps by the actions below)effect(() => this.engine.setParams(this.params.value));effect(() => this.engine.setPigment(this.current.value.pigment));effect(() => this.engine.setBrush(this.brush.value));+ effect(() => { this.engine.setPaper(this.paper.value); storedString.set(PAPER_KEY, this.paper.value.id); });+ effect(() => { this.engine.paperTexture = this.paperLook.value.texture; });effect(() => { const t = this.tool.value; if (isEngineTool(t)) this.engine.setTool(t); });effect(() => { this.engine.interactive = isEngineTool(this.tool.value) && !this.reference.adjusting.value; });effect(() => storedString.set(BRUSH_KEY, this.brush.value.id));@@ -118,6 +163,32 @@ export class AppStore {if (t === 'pen' || t === 'lift') this.setTool('brush');}+ /** Swap the paper under the painting; the paint stays. One undo step. */+ choosePaper(p: PaperPreset) {+ if (p.id === this.paper.peek().id) return;+ const before = this.engine.documentState;+ this.paper.value = p; // the effect pushes it into the engine+ this.engine.recordChange('paper', `Paper: ${p.name}`, before);+ }++ /** Texture slider: `input` while dragging, `commit` when let go (one undo step per drag). */+ setPaperTexture(v: number, phase: 'input' | 'commit' = 'input') {+ this.textureBefore ??= this.engine.documentState;+ this.paperLook.value = { texture: v };+ if (phase !== 'commit') return;+ const before = this.textureBefore;+ this.textureBefore = null;+ if (before.paperStrength !== v) this.engine.recordChange('paper', `Paper texture ${Math.round(v * 100)}%`, before);+ }++ /** Paper / reference state changed inside the engine (undo, redo, project opened): follow it. */+ private syncDocument(d: DocState) {+ const p = PAPERS.find(x => x.id === d.paperId) ?? DEFAULT_PAPER;+ if (p.id !== this.paper.peek().id) this.paper.value = p;+ if (this.paperLook.peek().texture !== d.paperStrength) this.paperLook.value = { texture: d.paperStrength };+ this.reference.syncFrom(d.reference);+ }+cycleBrush(dir: 1 | -1) {const list = this.allBrushes.peek();const i = list.findIndex(b => b.id === this.brush.peek().id);@@ -153,8 +224,9 @@ export class AppStore {else void this.importTexture(file);}- /** A file dropped on the page: SVGs are traced, rasters ask whether they are a reference or a brush. */+ /** A file dropped on the page: projects open, SVGs are traced, rasters ask whether they are a reference or a brush. */dropFile(file: File, x: number, y: number): boolean {+ if (isProjectFile(file)) { void this.project.open(file); return true; }if (isSvgFile(file)) { this.importFile(file); return true; }if (isRasterFile(file)) { this.dropped.value = { file, x, y }; return true; }return false;@@ -172,8 +244,55 @@ export class AppStore {undo() { this.engine.undo(); }redo() { this.engine.redo(); }+ /** Go to the state after `index` steps (0 = before the first). */+ jumpTo(index: number) { this.engine.jumpTo(index); }dry() { this.engine.fix(); }+ /** Replace the painting with a saved project. */+ async openProject(data: ProjectData): Promise<void> {+ for (const p of this.panelTools.values()) p.tool.stop();+ this.reference.stopAdjust();+ const h = data.header;+ let image: HTMLCanvasElement | null = null;+ if (data.reference) {+ const bmp = await decodeImage(data.reference);+ image = document.createElement('canvas');+ image.width = bmp.width; image.height = bmp.height;+ image.getContext('2d')!.drawImage(bmp, 0, 0);+ bmp.close();+ }+ const [w, h2] = clampDocSize(h.doc.w, h.doc.h, this.engine.maxSide);+ const snapshot: DocumentSnapshot = {+ whole: { w: h.doc.w, h: h.doc.h, rect: h.paint.rect, layers: data.layers },+ paper: h.paper,+ wet: { wetAgo: h.paint.wetAgo, wetPeak: h.paint.wetPeak, active: h.paint.active, painted: h.paint.painted },+ reference: image && h.reference+ ? { image, rect: h.reference.rect, opacity: h.reference.opacity, visible: h.reference.visible }+ : { image: null, rect: { x: 0, y: 0, w: 1, h: 1 }, opacity: this.reference.opacity, visible: this.reference.visible },+ view: h.view ?? { zoom: 1, pan: [0, 0], fitted: true },+ };+ this.engine.restore(snapshot); // throws if the sheet does not fit this GPU+ this.paperSize.value = sanitizeSize({ preset: h.doc.sizePreset, w, h: h2 });+ this.params.value = { ...DEFAULT_PARAMS, ...h.tool.params };+ this.choose(PALETTE.find(e => e.hex.toLowerCase() === h.tool.hex.toLowerCase()) ?? customEntry(h.tool.hex));+ this.reference.forFill.value = !!(h.reference?.forFill && image);+ this.reference.askFill.value = false;+ let brush = this.allBrushes.peek().find(b => b.id === h.tool.brushId);+ if (!brush) {+ const stored = h.brushes.find(b => b.id === h.tool.brushId);+ if (stored) {+ try {+ brush = await brushFromStored(stored);+ this.customs.value = [...this.customs.value, brush];+ saveCustomBrushes(this.customs.value);+ } catch { /* a corrupt tip: fall back to the first brush */ }+ }+ }+ this.chooseBrush(brush ?? this.builtIn[0]);+ this.confirmClear.value = false;+ this.closePopovers();+ }+/** First press arms the button ("Sure?"), a second press within 2.5 s clears. */clear() {clearTimeout(this.confirmTimer);@@ -187,6 +306,23 @@ export class AppStore {this.confirmClear.value = false;}+ /**+ * Change the sheet. The painting keeps its size and stays centred: a bigger sheet adds+ * paper around it, a smaller one crops it. The change is one undo step.+ */+ setPaperSize(choice: PaperSizeChoice) {+ const [w, h] = choice.preset === 'screen' ? this.engine.screenSize : clampDocSize(choice.w, choice.h, this.engine.maxSide);+ for (const p of this.panelTools.values()) p.tool.stop();+ this.engine.resizeDocument(w, h);+ this.reference.syncRect();+ this.paperSize.value = { preset: choice.preset, w, h };+ }++ zoomIn() { this.engine.zoomTo(ZOOM_STEPS.find(z => z > this.zoom.peek() * 1.01) ?? MAX_ZOOM); }+ zoomOut() { this.engine.zoomTo([...ZOOM_STEPS].reverse().find(z => z < this.zoom.peek() / 1.01) ?? MIN_ZOOM); }+ zoomTo(z: number) { this.engine.zoomTo(z); }+ zoomToFit() { this.engine.zoomToFit(); }+/** Open or close one popover (toggling when `force` is omitted); opening one closes the rest. */togglePopover(name: PopoverId, force?: boolean) {const open = force ?? this.popover.peek() !== name;@@ -200,6 +336,7 @@ export class AppStore {/** Escape: the most transient thing goes first. */escape() {if (this.dropped.peek()) { this.closeDrop(); return; }+ if (this.reference.askFill.peek()) { this.reference.useForFill(false); return; }if (this.reference.stopAdjust()) return;for (const p of this.panelTools.values()) if (p.tool.stop()) return;this.toggleLibrary(false);@@ -211,5 +348,5 @@ export class AppStore {this.reference.syncRect();}- destroy() { this.engine.destroy(); }+ destroy() { this.navigation.destroy(); this.engine.destroy(); }}diff --git a/src/components/ActionBar.tsx b/src/components/ActionBar.tsxindex 4bfe27c..f5856c9 100644--- a/src/components/ActionBar.tsx+++ b/src/components/ActionBar.tsx@@ -23,9 +23,11 @@ export function ActionBar() {<Panel class="actions"><Action icon="undo" label="Undo" title="Undo (⌘Z)" disabled={!app.canUndo.value} onClick={() => app.undo()} /><Action icon="redo" label="Redo" title="Redo (⇧⌘Z)" disabled={!app.canRedo.value} onClick={() => app.redo()} />+ <Action icon="history" label="History" title="History: every step, click one to go back or forward to it" popover="history" onClick={() => app.togglePopover('history')} /><Action icon="dry" label="Dry" title="Dry and fix the painting into the paper (D)" onClick={() => app.dry()} /><Action icon="clear" label={sure ? 'Sure?' : 'Clear'} title="Clear the paper" danger={sure} onClick={() => app.clear()} /><Action icon="image" label="Ref" title="Reference image under the paint (R to show / hide)" popover="reference" onClick={() => app.togglePopover('reference')} />+ <Action icon="paper" label="Paper" title="Paper texture: swap the sheet at any time" popover="paper" onClick={() => app.togglePopover('paper')} /><Action icon="save" label="Save" title="Save image (S saves with the last settings)" popover="save" onClick={() => app.togglePopover('save')} /><Action icon="sliders" label="Settings" title="Brush & water settings" popover="settings" onClick={() => app.togglePopover('settings')} /></Panel>diff --git a/src/components/HistoryPanel.tsx b/src/components/HistoryPanel.tsxnew file mode 100644index 0000000..c4a8eb3--- /dev/null+++ b/src/components/HistoryPanel.tsx@@ -0,0 +1,40 @@+import { useApp } from '../app/context';+import type { StepKind } from '../engine/history';+import { Icon } from '../ui/Icon';+import { Panel, PanelHead } from '../ui/Panel';++const ICONS: Record<StepKind, string> = {+ stroke: 'brush', fill: 'fill', script: 'shape', dry: 'dry', clear: 'clear', resize: 'resize', paper: 'paper', reference: 'image',+};++/** A stroke's icon follows the tool it was made with. */+function iconFor(kind: StepKind, label: string) {+ if (kind === 'stroke') return label === 'Water' ? 'water' : label === 'Pen' ? 'pen' : label === 'Lift' ? 'lift' : 'brush';+ if (kind === 'script') return label.startsWith('Text') ? 'text' : 'shape';+ if (kind === 'fill') return label.startsWith('Water') ? 'water' : 'fill';+ return ICONS[kind];+}++/** Every undo step, newest first; click one to go back (or forward) to it. */+export function HistoryPanel() {+ const app = useApp();+ const { list, index } = app.history.value;+ const baseline = app.project.baseline.value;+ const rows = list.map((s, i) => ({ s, i: i + 1 })).reverse();+ return (+ <Panel class="popover history-panel" open={app.popover.value === 'history'} role="dialog" label="History">+ <PanelHead title="History" sub={list.length ? `${index} of ${list.length} steps applied. Click a step to go back or forward to it.` : 'Each stroke, fill, paper or reference change becomes a step here.'} />+ <div class="history-list" role="listbox" aria-label="History">+ {rows.map(({ s, i }) => (+ <button key={i} role="option" aria-selected={i === index} class={i === index ? 'on' : i > index ? 'undone' : ''}+ title={i > index ? 'Redo up to here' : i === index ? 'Current state' : 'Undo back to here'} onClick={() => app.jumpTo(i)}>+ <Icon name={iconFor(s.kind, s.label)} size={16} /><span>{s.label}</span>+ </button>+ ))}+ <button role="option" aria-selected={index === 0} class={index === 0 ? 'on' : ''} title="Before the first step" onClick={() => app.jumpTo(0)}>+ <Icon name={baseline === 'Opened project' ? 'folder' : 'paper'} size={16} /><span>{baseline}</span>+ </button>+ </div>+ </Panel>+ );+}diff --git a/src/components/Overlays.tsx b/src/components/Overlays.tsxindex c99b6f8..98938e9 100644--- a/src/components/Overlays.tsx+++ b/src/components/Overlays.tsx@@ -40,3 +40,18 @@ export function DropChoice() {</div>);}++/** After a reference is imported: should the Fill tool trace it? */+export function FillChoice() {+ const ref = useApp().reference;+ const ask = ref.askFill.value && ref.has.value;+ return (+ <div class="panel fill-choice" hidden={!ask} role="dialog" aria-label="Use the reference for fills">+ <p>Reference added. Use it as the tracing for fills?</p>+ <div class="row">+ <button class="on" onClick={() => ref.useForFill(true)}><Icon name="image" size={16} /><span>Trace for fills</span></button>+ <button onClick={() => ref.useForFill(false)}><span>Just a reference</span></button>+ </div>+ </div>+ );+}diff --git a/src/components/PaperPanel.tsx b/src/components/PaperPanel.tsxnew file mode 100644index 0000000..74f2b0c--- /dev/null+++ b/src/components/PaperPanel.tsx@@ -0,0 +1,147 @@+import { useEffect, useRef, useState } from 'preact/hooks';+import { useApp } from '../app/context';+import { resizeTick } from '../app/resize';+import { clampDocSize, MIN_DOC_SIDE } from '../engine/Engine';+import { PAPER_SIZES, PAPERS, type PaperPreset } from '../engine/papers';+import { Panel, PanelHead } from '../ui/Panel';+import { Seg } from '../ui/Seg';+import { Slider } from '../ui/Slider';++const SWATCH_W = 112, SWATCH_H = 64;++function PaperCard({ paper, selected, onPick }: { paper: PaperPreset; selected: boolean; onPick(): void }) {+ const app = useApp();+ const canvas = useRef<HTMLCanvasElement>(null);+ const open = app.popover.value === 'paper';+ const tick = resizeTick.value;+ // drawn at the scale the sheet has on screen, once the panel is first opened+ useEffect(() => {+ const c = canvas.current;+ if (!open || !c) return;+ const dpr = Math.min(window.devicePixelRatio || 1, 2);+ const src = app.engine.paperSwatch(paper, Math.round(SWATCH_W * dpr), Math.round(SWATCH_H * dpr));+ c.width = src.width; c.height = src.height;+ c.getContext('2d')!.drawImage(src, 0, 0);+ }, [open, paper, tick]);+ return (+ <div class={`paper-card${selected ? ' on' : ''}`} role="option" aria-selected={selected} tabIndex={0} title={paper.hint}+ onClick={onPick} onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onPick(); } }}>+ <canvas ref={canvas} class="sheet" style={{ width: `${SWATCH_W}px`, height: `${SWATCH_H}px` }} />+ <span class="label">{paper.name}</span>+ </div>+ );+}++const turn = (w: number, h: number, portrait: boolean): [number, number] => (portrait === h > w ? [w, h] : [h, w]);++/** Sheet size: presets or custom pixels, and the orientation. The painting is kept when it changes. */+function SizeSection() {+ const app = useApp();+ const open = app.popover.value === 'paper';+ const [dw, dh] = app.docSize.value;+ resizeTick.value; // "Screen" follows the window+ const [preset, setPreset] = useState(app.paperSize.peek().preset);+ const [portrait, setPortrait] = useState(dh > dw);+ const [custom, setCustom] = useState<[number, number]>([dw, dh]);+ const [armed, setArmed] = useState(false);+ const timer = useRef(0);++ // each time the panel opens, start from the sheet as it is+ useEffect(() => {+ if (!open) return;+ setPreset(app.paperSize.peek().preset);+ setPortrait(dh > dw);+ setCustom([dw, dh]);+ setArmed(false);+ }, [open]);+ useEffect(() => () => clearTimeout(timer.current), []);++ const def = PAPER_SIZES.find(p => p.id === preset) ?? PAPER_SIZES[0];+ const want: [number, number] = preset === 'screen' ? app.engine.screenSize+ : preset === 'custom' ? custom : turn(def.w, def.h, portrait);+ const [w, h] = clampDocSize(want[0], want[1], app.engine.maxSide);+ const clamped = preset === 'custom' && (w !== Math.round(want[0]) || h !== Math.round(want[1]));+ const same = w === dw && h === dh;+ const crops = w < dw || h < dh;+ const square = preset === 'screen' || (preset !== 'custom' && def.w === def.h);++ const pick = (id: string) => {+ if (id === 'custom' && preset !== 'custom') setCustom([w, h]);+ setPreset(id);+ setArmed(false);+ };+ const orient = (p: boolean) => {+ setPortrait(p);+ if (preset === 'custom') setCustom(turn(custom[0], custom[1], p));+ setArmed(false);+ };+ const apply = () => {+ clearTimeout(timer.current);+ // shrinking crops the painting: the first press asks+ if (crops && !armed) {+ setArmed(true);+ timer.current = window.setTimeout(() => setArmed(false), 2500);+ return;+ }+ setArmed(false);+ setCustom([w, h]); // show what was applied, after any clamping+ app.setPaperSize({ preset, w, h });+ };+ const setSide = (i: 0 | 1, v: string) => {+ const n = parseInt(v, 10);+ if (!Number.isFinite(n)) return;+ const next: [number, number] = [...custom];+ next[i] = n;+ setCustom(next);+ setArmed(false);+ };++ return (+ <div class="field paper-size">+ <span>Size · {dw} × {dh} px</span>+ <div class="sizes" role="radiogroup" aria-label="Paper size">+ {PAPER_SIZES.map(p => {+ const [pw, ph] = p.id === 'screen' ? app.engine.screenSize : turn(p.w, p.h, portrait);+ return (+ <button key={p.id} role="radio" aria-checked={p.id === preset} class={p.id === preset ? 'on' : ''} title={p.hint} onClick={() => pick(p.id)}>+ <b>{p.name}</b><i>{p.id === 'custom' ? 'W × H' : `${pw} × ${ph}`}</i>+ </button>+ );+ })}+ </div>+ {preset === 'custom' && (+ <div class="custom-size">+ <input class="text-input" type="number" min={MIN_DOC_SIDE} max={app.engine.maxSide} step={1} aria-label="Width in pixels"+ value={custom[0]} onChange={e => setSide(0, e.currentTarget.value)} />+ <em>×</em>+ <input class="text-input" type="number" min={MIN_DOC_SIDE} max={app.engine.maxSide} step={1} aria-label="Height in pixels"+ value={custom[1]} onChange={e => setSide(1, e.currentTarget.value)} />+ <em>px</em>+ </div>+ )}+ {clamped && <p class="note">Sheets are limited to about 4 megapixels ({app.engine.maxSide} px on the long side): this one will be {w} × {h} px.</p>}+ <Seg label="Orientation" value={portrait} onChange={orient}+ options={[{ id: false, label: 'Landscape', disabled: square }, { id: true, label: 'Portrait', disabled: square }]} />+ <button class="primary" disabled={same} onClick={apply}>+ {same ? 'Current size' : armed ? `Crop to ${w} × ${h}?` : `Apply ${w} × ${h}`}+ </button>+ <p class="note">The painting keeps its size, centred on the new sheet; a smaller sheet crops it. Undo brings the old sheet back; the steps before the change are forgotten.</p>+ </div>+ );+}++export function PaperPanel() {+ const app = useApp();+ const current = app.paper.value;+ return (+ <Panel class="popover paper-panel" open={app.popover.value === 'paper'} role="dialog" label="Paper">+ <PanelHead title="Paper" sub={current.hint} />+ <SizeSection />+ <Slider label="Texture" title="How strongly the paper's tooth, fibres and flecks show. Saved images use the same strength."+ value={app.paperLook.value.texture} onInput={v => app.setPaperTexture(v)} onChange={v => app.setPaperTexture(v, 'commit')} />+ <div class="papers" role="listbox" aria-label="Paper">+ {PAPERS.map(p => <PaperCard key={p.id} paper={p} selected={p.id === current.id} onPick={() => app.choosePaper(p)} />)}+ </div>+ </Panel>+ );+}diff --git a/src/components/ZoomControl.tsx b/src/components/ZoomControl.tsxnew file mode 100644index 0000000..d4ff688--- /dev/null+++ b/src/components/ZoomControl.tsx@@ -0,0 +1,18 @@+import { useApp } from '../app/context';+import { Icon } from '../ui/Icon';+import { Panel } from '../ui/Panel';++/** Zoom out / in, the current zoom (click for 100%) and zoom to fit, in the bottom-right corner. */+export function ZoomControl() {+ const app = useApp();+ const pct = Math.round(app.zoom.value * 100);+ return (+ <Panel class="zoom" role="toolbar" label="Zoom">+ <button title="Zoom out (⌘−)" aria-label="Zoom out" onClick={() => app.zoomOut()}><Icon name="minus" size={16} /></button>+ <button class="pct" title="Zoom to 100% (⇧0)" onClick={() => app.zoomTo(1)}>{pct}%</button>+ <button title="Zoom in (⌘+)" aria-label="Zoom in" onClick={() => app.zoomIn()}><Icon name="plus" size={16} /></button>+ <button title={'Zoom to fit (⇧1)\nScroll to pan, pinch or ⌘-scroll to zoom,\nhold Space or the middle button and drag to pan'}+ aria-label="Zoom to fit" onClick={() => app.zoomToFit()}><Icon name="fit" size={16} /></button>+ </Panel>+ );+}diff --git a/src/draw/StrokeWriter.ts b/src/draw/StrokeWriter.tsindex 2a426ec..8b9cac8 100644--- a/src/draw/StrokeWriter.ts+++ b/src/draw/StrokeWriter.ts@@ -22,6 +22,8 @@ export interface WriteOptions {taper: number;/** 0..1: hand tremor along the path. */wobble: number;+ /** Name of the undo step the whole write becomes. */+ label: string;}export interface WriteCallbacks {@@ -136,7 +138,7 @@ export class StrokeWriter {}if (this.phase === 'begin') {const [x, y] = this.at(run, 0);- if (this.engine.scriptBegin(tool, x, y, this.pressureAt(run, 0), this.first)) {+ if (this.engine.scriptBegin(tool, x, y, this.pressureAt(run, 0), this.first ? this.opts.label : false)) {this.first = false;this.phase = 'draw';this.dist = 0;diff --git a/src/engine/Engine.ts b/src/engine/Engine.tsindex 708e741..04f043f 100644--- a/src/engine/Engine.ts+++ b/src/engine/Engine.ts@@ -1,6 +1,7 @@import { BRUSH_PRESETS, buildBrush, type Brush } from './brushes';import { GL, type DoubleTarget, type Format, type Program, type Rect, type Target } from './gl';-import { History } from './history';+import { History, type StepInfo, type StepKind } from './history';+import { DEFAULT_PAPER, linearRGB, PAPERS, type PaperPreset } from './papers';import * as S from './shaders';import { pigmentFromHex, type Pigment } from './spectral';@@ -23,18 +24,48 @@ export const DEFAULT_PARAMS: Params = {};export interface EngineCallbacks {- onHistoryChange?(canUndo: boolean, canRedo: boolean): void;+ /** The undo history changed: every step (oldest first) and how many of them are applied. */+ onHistoryChange?(steps: StepInfo[], index: number): void;+ /** Paper or reference state changed from inside the engine (undo, redo, a project opened). */+ onDocumentChange?(state: DocState): void;/** The active tool changed for the current stroke (pencil barrel / finger-as-water). */onStrokeTool?(tool: Tool | null): void;+ /** The view was zoomed or panned (`zoom` 1 = one document texel per CSS pixel). */+ onViewChange?(zoom: number, docSize: [number, number]): void;}export type ExportFormat = 'png' | 'jpeg' | 'webp';export type ExportBackground = 'transparent' | 'paper' | 'white';-export interface ExportOptions { format: ExportFormat; background: ExportBackground; quality?: number }+/** `texture` false exports the paper (or white) as a flat sheet; true uses the on-screen texture strength. */+export interface ExportOptions { format: ExportFormat; background: ExportBackground; quality?: number; texture?: boolean }/** Placement of the reference image in document uv (y up): origin and size. */export interface RefRect { x: number; y: number; w: number; h: number }+export type LayerId = 'inkA' | 'inkB' | 'fixedA' | 'fixedB' | 'wet';++/**+ * The paint layers as half floats (RGBA for ink and fixed, one channel for wet), cropped+ * to `rect`, the texel rect holding everything ever painted (null: a blank sheet).+ */+export interface WholeDoc { w: number; h: number; rect: Rect | null; layers: Record<LayerId, Uint16Array> }++/** Document-level state that undo tracks besides the paint. */+export interface DocState {+ paperId: string;+ paperStrength: number;+ reference: { image: HTMLCanvasElement | null; rect: RefRect; opacity: number; visible: boolean };+}++/** Everything needed to bring a painting back exactly as it is. */+export interface DocumentSnapshot {+ whole: WholeDoc;+ paper: { id: string; seed: number; origin: [number, number]; scale: number; strength: number };+ wet: { wetAgo: number; wetPeak: number; active: Rect | null; painted: Rect | null };+ reference: DocState['reference'];+ view: { zoom: number; pan: [number, number]; fitted: boolean };+}+/** How the display shader composites: on screen (with the reference) or for an export. */const MODE = { screen: 0, paper: 1, transparent: 2, white: 3 } as const;const MAX_REF_SIDE = 4096;@@ -47,8 +78,10 @@ interface Stroke {tool: Tool;started: boolean;ending: boolean;- x: number; y: number; // smoothed position (uv)- t: number; // time of last sample (ms)+ x: number; y: number; // where the drawn stroke currently ends (uv)+ cx: number; cy: number; // latest smoothed sample: the curve's control point, drawn up to on the next sample+ pr: number; // pressure at (x, y), so pressure ramps along each curve+ t: number; // time of last sample (ms)speed: number; // doc heights / secondsimPressure: number; // pressure stand-in for mice and fingerscarry: number; // distance travelled since the last stamp (doc heights)@@ -62,7 +95,13 @@ interface Stroke {const DEG = Math.PI / 180;const SCRIPT_POINTER = -1;-interface HistoryMeta { wetAgo: number; wetPeak: number; active: Rect | null }+interface StepMeta {+ wetAgo: number; wetPeak: number; active: Rect | null; painted: Rect | null;+ doc: DocState;+ /** Boundary (resize) steps: the whole sheet as it was, and where its paper sat. */+ whole?: WholeDoc; paperOrigin?: [number, number];+}+const STROKE_LABEL: Record<Tool, string> = { brush: 'Brush stroke', water: 'Water', pen: 'Pen', lift: 'Lift' };const HALF_FLOAT_RG: Format = { internal: WebGL2RenderingContext.RG16F, format: WebGL2RenderingContext.RG, type: WebGL2RenderingContext.HALF_FLOAT };const HALF_FLOAT_R: Format = { internal: WebGL2RenderingContext.R16F, format: WebGL2RenderingContext.RED, type: WebGL2RenderingContext.HALF_FLOAT };@@ -75,13 +114,34 @@ const FILL_JITTER = 3; // px the paper grain roughens a bucket fill's frconst SIM_BASE = 256; // short side of the velocity / pressure gridconst PRESSURE_ITERATIONS = 20;-const MAX_DOC_LONG = 2048; // pigment / water grid limits (live state: ~56 bytes per texel)-const MAX_DOC_SHORT = 1536; // (plus an undo atlas of ~52 bytes per texel)+const SCREEN_DOC_LONG = 2048; // a "screen" sheet follows the window, within these limits+const SCREEN_DOC_SHORT = 1536;+const MAX_DOC_LONG = 3072; // pigment / water grid limits (live state: ~56 bytes per texel)+const MAX_DOC_PIXELS = 4_200_000; // (plus an undo atlas of ~52 bytes per texel)+export const MIN_DOC_SIDE = 256;+export const MIN_ZOOM = 0.02;+export const MAX_ZOOM = 32;+const FIT_PADDING = 24; // CSS px around the sheet when zoomed to fit+const PAN_KEEP = 48; // CSS px of the sheet that always stays on screenconst FIX_DURATION = 1.2;const WET_THRESHOLD = 0.004; // below this nothing moves, so the sim can sleep-const DESK = [0.86, 0.845, 0.815];+const MASK_BLOCK = 16; // texels per wet-mask cell+const MASK_EVERY = 10; // frames between wet-mask readbacks that trim the active rect+const MASK_MARGIN = MASK_BLOCK + 8;+const PROTECT_MARGIN = 24; // texels around a dab / fill band saved for undo, where its water and pigment spread to+const DESK = [1, 1, 1]; // the table the sheet lies on (sRGB)+const PAPER_UNITS = 1100; // paper features are drawn for a sheet this many texels tallconst clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));++/** A sheet size within the memory limits: the same shape, scaled down if too big. */+export function clampDocSize(w: number, h: number, maxSide = MAX_DOC_LONG): [number, number] {+ w = Math.max(MIN_DOC_SIDE, Math.round(w) || MIN_DOC_SIDE);+ h = Math.max(MIN_DOC_SIDE, Math.round(h) || MIN_DOC_SIDE);+ const s = Math.min(1, Math.min(MAX_DOC_LONG, maxSide) / Math.max(w, h), Math.sqrt(MAX_DOC_PIXELS / (w * h)));+ return [Math.max(MIN_DOC_SIDE, Math.round(w * s)), Math.max(MIN_DOC_SIDE, Math.round(h * s))];+}+const union = (a: Rect | null, b: Rect): Rect =>a ? { x0: Math.min(a.x0, b.x0), y0: Math.min(a.y0, b.y0), x1: Math.max(a.x1, b.x1), y1: Math.max(a.y1, b.y1) } : { ...b };@@ -94,10 +154,16 @@ export class WatercolorEngine {fingerIsWater = true;/** When false, pointers on the paper are ignored (another tool, e.g. text, is driving it). */interactive = true;+ private nav = false;private tipTextures = new Map<string, WebGLTexture>();+ private paperPreset: PaperPreset = DEFAULT_PAPER;+ private paperSeed = 0;+ private paperStrength = 1;+ private paperScale = 1; // paper units per texel, fixed when the sheet is made+ private paperOrigin: [number, number] = [0, 0]; // where the sheet sits in the paper's field (texels)// reference image: shown under the paint on screen only, never exported- private ref: { tex: WebGLTexture; aspect: number } | null = null;+ private ref: { tex: WebGLTexture; aspect: number; src: HTMLCanvasElement } | null = null;private refRect: RefRect = { x: 0, y: 0, w: 1, h: 1 };private refOpacity = 0.5;private refVisible = true;@@ -110,6 +176,9 @@ export class WatercolorEngine {private canvasSize: [number, number] = [1, 1];private dpr = 1;private view = { x: 0, y: 0, w: 1, h: 1 }; // document placement in canvas px+ private zoomLevel = 1; // 1 = one document texel per CSS px+ private pan: [number, number] = [0, 0]; // sheet centre from canvas centre (canvas px, y up)+ private fitMode = true; // keep the sheet fitted as the window changes// document stateprivate dw = 1; private dh = 1;@@ -121,11 +190,15 @@ export class WatercolorEngine {private fixed!: Target;private wet!: DoubleTarget;private paper!: Target;+ private wetMask!: Target; // coarse "is there water here" map, read back to bound the sim+ private maskPixels = new Uint8Array(0);+ private maskCounter = 0;private history!: History;// simulation bookkeepingprivate active: Rect | null = null; // document texels the sim must processprivate painted: Rect | null = null; // where mobile pigment may exist (since the last fix)+ private everPainted: Rect | null = null; // where any pigment, mobile or fixed, may existprivate dirty: Rect | null = null; // document texels to redrawprivate dirtyAll = true;private lastWet = -Infinity; // ms timestamp of the last water added@@ -137,6 +210,7 @@ export class WatercolorEngine {private brushNow = { x: 0, y: 0, r: 0 };private raf = 0;private lastFrame = 0;+ private seenEvictions = 0; // history.evictions as of the last onHistoryChange// inputprivate stroke: Stroke | null = null;@@ -147,7 +221,8 @@ export class WatercolorEngine {private force = { value: 0, t: -Infinity };private disposers: (() => void)[] = [];- constructor(private canvas: HTMLCanvasElement, private cursor: HTMLElement | null, private callbacks: EngineCallbacks = {}) {+ /** `size` is the sheet in texels; omitted, the sheet follows the window ("screen"). */+ constructor(private canvas: HTMLCanvasElement, private cursor: HTMLElement | null, private callbacks: EngineCallbacks = {}, size?: [number, number] | null) {const gl = canvas.getContext('webgl2', {alpha: false, depth: false, stencil: false, antialias: false, preserveDrawingBuffer: true,powerPreference: 'high-performance',@@ -170,15 +245,18 @@ export class WatercolorEngine {vorticity: this.g.program(S.vorticityFS),scale: this.g.program(S.scaleFS),advectWet: this.g.program(S.advectWetFS),+ wetMask: this.g.program(S.wetMaskFS),advectInk: this.g.program(S.advectInkFS),settle: this.g.program(S.settleFS),bleach: this.g.program(S.bleachFS),lift: this.g.program(S.liftFS),- paper: this.g.program(S.paperFS),+ paperField: this.g.program(S.paperFieldFS),+ paperLight: this.g.program(S.paperLightFS),+ paperSwatch: this.g.program(S.paperSwatchFS),display: this.g.program(S.displayFS),};this.fitCanvas();- this.createDocument();+ this.createDocument(size ?? this.screenSize);this.attachInput();this.schedule();}@@ -191,27 +269,47 @@ export class WatercolorEngine {const w = Math.max(2, Math.round(r.width * this.dpr)), h = Math.max(2, Math.round(r.height * this.dpr));this.canvas.width = w; this.canvas.height = h;this.canvasSize = [w, h];- this.fitView();+ if (this.fitMode) this.fitZoom(); else this.updateView();}- private fitView() {+ /** The zoom that shows the whole sheet with a margin. */+ private fitZoom() {const [cw, ch] = this.canvasSize;- const s = Math.min(cw / this.dw, ch / this.dh);- const w = this.dw * s, h = this.dh * s;- this.view = { x: (cw - w) / 2, y: (ch - h) / 2, w, h };+ const pad = 2 * FIT_PADDING * this.dpr;+ const z = Math.min((cw - pad) / this.dw, (ch - pad) / this.dh) / this.dpr;+ this.zoomLevel = clamp(z, MIN_ZOOM, MAX_ZOOM);+ this.pan = [0, 0];+ this.fitMode = true;+ this.updateView();+ }++ /** Place the sheet from zoom and pan; everything that maps pointers goes through `view`. */+ private updateView() {+ const [cw, ch] = this.canvasSize;+ const s = this.zoomLevel * this.dpr, w = this.dw * s, h = this.dh * s;+ // keep a strip of the sheet on screen so it can't be lost off the edge+ const keep = PAN_KEEP * this.dpr;+ const mx = Math.max(0, (cw + w) / 2 - keep), my = Math.max(0, (ch + h) / 2 - keep);+ this.pan = [clamp(this.pan[0], -mx, mx), clamp(this.pan[1], -my, my)];+ this.view = { x: (cw - w) / 2 + this.pan[0], y: (ch - h) / 2 + this.pan[1], w, h };this.dirtyAll = true;+ this.updateCursor();+ this.callbacks.onViewChange?.(this.zoomLevel, [this.dw, this.dh]);}- /** (Re)create the document to fill the current canvas. Discards the painting. */- private createDocument() {+ /** A sheet the shape of the window, in device pixels, within the "screen" limits. */+ get screenSize(): [number, number] {const [cw, ch] = this.canvasSize;- const s = Math.min(1, MAX_DOC_LONG / Math.max(cw, ch), MAX_DOC_SHORT / Math.min(cw, ch));- const oldAspect = this.aspect;- this.dw = Math.round(cw * s); this.dh = Math.round(ch * s);- // a reference placed on paper of another shape would be stretched; fit it afresh- if (this.ref && Math.abs(this.aspect - oldAspect) > 1e-3) this.fitReference();+ const s = Math.min(1, SCREEN_DOC_LONG / Math.max(cw, ch), SCREEN_DOC_SHORT / Math.min(cw, ch));+ return clampDocSize(cw * s, ch * s, this.maxSide);+ }++ /** The longest sheet side this GPU allows. */+ get maxSide() { return Math.min(MAX_DOC_LONG, this.gl.getParameter(this.gl.MAX_TEXTURE_SIZE) as number); }++ /** Allocate every document-sized target for a `dw`×`dh` sheet (the old ones are the caller's to free). */+ private allocateTargets() {const { gl, g } = this;- g.disposeTargets();const ar = this.dw / this.dh;const sim = ar > 1 ? { w: Math.round(SIM_BASE * ar), h: SIM_BASE } : { w: SIM_BASE, h: Math.round(SIM_BASE / ar) };this.velocity = g.double(sim.w, sim.h, [HALF_FLOAT_RG], gl.LINEAR);@@ -222,24 +320,289 @@ export class WatercolorEngine {this.fixed = g.target(this.dw, this.dh, [HALF_FLOAT_RGBA, HALF_FLOAT_RGBA], gl.LINEAR);this.wet = g.double(this.dw, this.dh, [HALF_FLOAT_R], gl.LINEAR);this.paper = g.target(this.dw, this.dh, [RGBA8], gl.LINEAR);- this.history = new History(g, this.dw, this.dh, [+ this.wetMask = g.target(Math.ceil(this.dw / MASK_BLOCK), Math.ceil(this.dh / MASK_BLOCK), [RGBA8], gl.NEAREST);+ this.maskPixels = new Uint8Array(this.wetMask.w * this.wetMask.h * 4);+ }++ private allocateHistory() {+ this.history = new History(this.g, this.dw, this.dh, [{ formats: [HALF_FLOAT_RGBA, HALF_FLOAT_RGBA, HALF_FLOAT_R], documents: 2 }, // mobile pigment + water{ formats: [HALF_FLOAT_RGBA, HALF_FLOAT_RGBA], documents: 1 }, // fixed pigment]);+ }- const p = this.programs.paper;- p.bind();- gl.uniform2f(p.u.uRes, this.dw, this.dh);- gl.uniform1f(p.u.uSeed, Math.random() * 0.3);- g.draw(this.paper);+ /** The targets that hold the sheet (not the sim grids, not the history atlases). */+ private docTargets(): Target[] {+ return [this.velocity.read, this.velocity.write, this.pressure.read, this.pressure.write, this.divergence, this.curl,+ this.ink.read, this.ink.write, this.fixed, this.wet.read, this.wet.write, this.paper, this.wetMask];+ }+ /** (Re)create a blank `w`×`h` sheet. Discards the painting. */+ private createDocument([w, h]: [number, number]) {+ const oldAspect = this.aspect;+ [this.dw, this.dh] = clampDocSize(w, h, this.maxSide);+ // a reference placed on paper of another shape would be stretched; fit it afresh+ if (this.ref && Math.abs(this.aspect - oldAspect) > 1e-3) this.fitReference();+ this.g.disposeTargets();+ this.allocateTargets();+ this.allocateHistory();++ this.paperSeed = Math.random();+ this.paperScale = PAPER_UNITS / this.dh;+ this.paperOrigin = [0, 0];+ this.drawPaper(this.paper, this.paperOrigin, this.paperScale);++ this.resetPaintState();+ if (this.fitMode) this.fitZoom(); else this.updateView();+ this.notifyHistory();+ }++ private resetPaintState() {this.active = null;this.painted = null;+ this.everPainted = null;+ this.dirty = null;+ this.dirtyAll = true;this.lastWet = -Infinity;this.wetPeak = 0;this.fixTimer = 0;- this.fitView();- this.callbacks.onHistoryChange?.(false, false);+ this.flowSpeed = 0;+ }++ /**+ * Change the sheet to `w`×`h` texels, keeping the painting at its size and centred:+ * a bigger sheet adds blank paper around it, a smaller one crops it. The paper grain+ * stays registered under the paint. The change is one undo step; the steps before it+ * are forgotten (their undo tiles belong to the old sheet).+ */+ resizeDocument(w: number, h: number) {+ [w, h] = clampDocSize(w, h, this.maxSide);+ const ow = this.dw, oh = this.dh;+ if (w === ow && h === oh) return;+ this.stroke = null;+ this.dropFill();+ this.queue = [];+ const { g } = this;+ const ox = Math.round((w - ow) / 2), oy = Math.round((h - oh) / 2);+ const meta: StepMeta = { ...this.currentMeta(), whole: this.captureWhole(), paperOrigin: [...this.paperOrigin] };+ const old = { targets: this.docTargets(), ink: this.ink.read, fixed: this.fixed, wet: this.wet.read };+ this.dw = w; this.dh = h;+ this.allocateTargets();+ this.history.beginBoundary({ kind: 'resize', label: `Resize ${w} × ${h}` }, meta, w, h);++ // the overlap of the old sheet (shifted by ox, oy) and the new one+ const sx = Math.max(0, -ox), sy = Math.max(0, -oy), dx = Math.max(0, ox), dy = Math.max(0, oy);+ const cw = Math.min(ow - sx, w - dx), ch = Math.min(oh - sy, h - dy);+ const copy = (src: Target, dsts: Target[]) => {+ if (cw > 0 && ch > 0) src.views.forEach((v, i) => dsts.forEach(d => g.blit(v, sx, sy, d.views[i], dx, dy, cw, ch)));+ };+ copy(old.ink, [this.ink.read, this.ink.write]);+ copy(old.wet, [this.wet.read, this.wet.write]);+ copy(old.fixed, [this.fixed]);+ old.targets.forEach(t => g.disposeTarget(t));++ this.paperOrigin = [this.paperOrigin[0] - ox, this.paperOrigin[1] - oy];+ this.drawPaper(this.paper, this.paperOrigin, this.paperScale);++ const shift = (r: Rect | null): Rect | null => {+ if (!r) return null;+ const n = { x0: Math.max(0, r.x0 + ox), y0: Math.max(0, r.y0 + oy), x1: Math.min(w, r.x1 + ox), y1: Math.min(h, r.y1 + oy) };+ return n.x1 > n.x0 && n.y1 > n.y0 ? n : null;+ };+ this.active = shift(this.active);+ this.painted = shift(this.painted);+ this.everPainted = shift(this.everPainted);+ this.dirty = null;+ const rr = this.refRect;+ this.refRect = { x: (rr.x * ow + ox) / w, y: (rr.y * oh + oy) / h, w: (rr.w * ow) / w, h: (rr.h * oh) / h };++ if (this.fitMode) this.fitZoom(); else this.updateView();+ this.notifyHistory();+ this.callbacks.onDocumentChange?.(this.docState());+ this.schedule();+ }++ /* ------------------------------------------------- whole-document state */++ /** The paint layers, cropped to where anything was ever painted. */+ private captureWhole(): WholeDoc {+ const r = this.everPainted;+ const { g, dw, dh } = this;+ const read = (fb: WebGLFramebuffer, ch: 1 | 4) => (r ? g.readHalf(fb, dw, dh, ch, r) : new Uint16Array(0));+ return {+ w: dw, h: dh, rect: r ? { ...r } : null,+ layers: {+ inkA: read(this.ink.read.views[0], 4), inkB: read(this.ink.read.views[1], 4),+ fixedA: read(this.fixed.views[0], 4), fixedB: read(this.fixed.views[1], 4),+ wet: read(this.wet.read.views[0], 1),+ },+ };+ }++ /** Put `whole`'s layers into the (blank) current targets; both halves of the ping-pong pairs. */+ private uploadWhole(whole: WholeDoc) {+ const r = whole.rect;+ if (!r) return;+ const { gl, g } = this;+ const w = r.x1 - r.x0, h = r.y1 - r.y0;+ const up = (tex: WebGLTexture, format: number, data: Uint16Array) => g.uploadHalf(tex, r.x0, r.y0, w, h, format, data);+ for (const t of [this.ink.read, this.ink.write]) { up(t.tex[0], gl.RGBA, whole.layers.inkA); up(t.tex[1], gl.RGBA, whole.layers.inkB); }+ up(this.fixed.tex[0], gl.RGBA, whole.layers.fixedA);+ up(this.fixed.tex[1], gl.RGBA, whole.layers.fixedB);+ for (const t of [this.wet.read, this.wet.write]) up(t.tex[0], gl.RED, whole.layers.wet);+ this.everPainted = { ...r };+ }++ /** Replace the sheet with `whole` (another size, usually), keeping the history atlases. */+ private applyWhole(whole: WholeDoc, paperOrigin: [number, number]) {+ const old = this.docTargets();+ this.dw = whole.w; this.dh = whole.h;+ this.allocateTargets();+ old.forEach(t => this.g.disposeTarget(t));+ this.history.resize(this.dw, this.dh);+ this.paperOrigin = [...paperOrigin];+ this.drawPaper(this.paper, this.paperOrigin, this.paperScale);+ this.everPainted = null;+ this.uploadWhole(whole);+ this.dirty = null;+ this.dirtyAll = true;+ if (this.fitMode) this.fitZoom(); else this.updateView();+ }++ private docState(): DocState {+ return {+ paperId: this.paperPreset.id,+ paperStrength: this.paperStrength,+ reference: { image: this.ref?.src ?? null, rect: { ...this.refRect }, opacity: this.refOpacity, visible: this.refVisible },+ };+ }++ /** Paper and reference state as undo tracks it. */+ get documentState(): DocState { return this.docState(); }++ /** Bring paper / reference state back (after undo, redo or a project opened). */+ private applyDocState(d: DocState) {+ const preset = PAPERS.find(p => p.id === d.paperId);+ if (preset && preset !== this.paperPreset) { this.paperPreset = preset; this.drawPaper(this.paper, this.paperOrigin, this.paperScale); }+ this.paperStrength = clamp(d.paperStrength, 0, 1);+ const r = d.reference;+ if (r.image !== (this.ref?.src ?? null)) this.uploadReference(r.image);+ this.refRect = { ...r.rect };+ this.refOpacity = r.opacity;+ this.refVisible = r.visible;+ this.dirtyAll = true;+ }++ /**+ * Record a document-level change that has already been applied (paper, reference) as+ * one undo step; `before` is the state to come back to.+ */+ recordChange(kind: StepKind, label: string, before: DocState) {+ this.dropFill();+ this.history.begin({ kind, label }, { ...this.currentMeta(), doc: before } satisfies StepMeta);+ this.notifyHistory();+ }++ /** The painting as it is now, ready to be saved. */+ snapshot(): DocumentSnapshot {+ const m = this.currentMeta();+ return {+ whole: this.captureWhole(),+ paper: { id: this.paperPreset.id, seed: this.paperSeed, origin: [...this.paperOrigin], scale: this.paperScale, strength: this.paperStrength },+ wet: { wetAgo: m.wetAgo, wetPeak: m.wetPeak, active: m.active, painted: m.painted },+ reference: m.doc.reference,+ view: { zoom: this.zoomLevel, pan: [...this.pan], fitted: this.fitMode },+ };+ }++ /** Replace the painting with a saved one. History starts afresh. */+ restore(s: DocumentSnapshot) {+ const [w, h] = clampDocSize(s.whole.w, s.whole.h, this.maxSide);+ if (w !== s.whole.w || h !== s.whole.h) throw new Error(`This sheet (${s.whole.w} × ${s.whole.h}) is too large for this GPU.`);+ this.stroke = null;+ this.dropFill();+ this.queue = [];+ if (this.ref) { this.gl.deleteTexture(this.ref.tex); this.ref = null; }+ this.g.disposeTargets();+ this.dw = w; this.dh = h;+ this.allocateTargets();+ this.allocateHistory();+ this.resetPaintState();++ this.paperPreset = PAPERS.find(p => p.id === s.paper.id) ?? DEFAULT_PAPER;+ this.paperSeed = s.paper.seed;+ this.paperScale = s.paper.scale || PAPER_UNITS / this.dh;+ this.paperOrigin = [...s.paper.origin];+ this.paperStrength = clamp(s.paper.strength, 0, 1);+ this.drawPaper(this.paper, this.paperOrigin, this.paperScale);++ this.uploadWhole(s.whole);+ const now = performance.now();+ this.lastWet = Number.isFinite(s.wet.wetAgo) ? now - s.wet.wetAgo : -Infinity;+ this.wetPeak = s.wet.wetPeak;+ this.active = s.wet.active ? { ...s.wet.active } : null;+ this.painted = s.wet.painted ? { ...s.wet.painted } : null;+ if (this.active) this.minAwakeUntil = now + 250;++ this.uploadReference(s.reference.image);+ this.refRect = { ...s.reference.rect };+ this.refOpacity = clamp(s.reference.opacity, 0, 1);+ this.refVisible = s.reference.visible;++ this.zoomLevel = clamp(s.view.zoom, MIN_ZOOM, MAX_ZOOM);+ this.pan = [...s.view.pan];+ this.fitMode = s.view.fitted;+ if (this.fitMode) this.fitZoom(); else this.updateView();+ this.notifyHistory();+ this.callbacks.onDocumentChange?.(this.docState());+ this.schedule();+ }++ /* ---------------------------------------------------------------- view */++ /** Current zoom: 1 shows one document texel per CSS pixel. */+ get zoom() { return this.zoomLevel; }++ /** True while the sheet is fitted to the window (it stays fitted as the window changes). */+ get fitted() { return this.fitMode; }++ /** While navigating (e.g. Space held) pointers on the paper pan instead of paint. */+ get navigating() { return this.nav; }+ set navigating(v: boolean) { this.nav = v; this.updateCursor(); }++ /** Zoom by `factor` keeping the document point under (clientX, clientY) in place. */+ zoomAt(clientX: number, clientY: number, factor: number) {+ const r = this.canvas.getBoundingClientRect();+ const [cw, ch] = this.canvasSize;+ const z = clamp(this.zoomLevel * factor, MIN_ZOOM, MAX_ZOOM);+ const k = z / this.zoomLevel;+ if (k === 1) return;+ const px = (clientX - r.left) * this.dpr, py = ch - (clientY - r.top) * this.dpr;+ // the sheet centre moves away from the fixed point by the zoom ratio+ const cx = cw / 2 + this.pan[0], cy = ch / 2 + this.pan[1];+ this.pan = [px - (px - cx) * k - cw / 2, py - (py - cy) * k - ch / 2];+ this.zoomLevel = z;+ this.fitMode = false;+ this.updateView();+ this.schedule();+ }++ /** Zoom to `z` about the middle of the window. */+ zoomTo(z: number) {+ const r = this.canvas.getBoundingClientRect();+ this.zoomAt(r.left + r.width / 2, r.top + r.height / 2, z / this.zoomLevel);+ }++ /** Show the whole sheet. */+ zoomToFit() { this.fitZoom(); this.schedule(); }++ /** Move the sheet by (dx, dy) CSS pixels. */+ panBy(dx: number, dy: number) {+ if (!dx && !dy) return;+ this.pan = [this.pan[0] + dx * this.dpr, this.pan[1] - dy * this.dpr];+ this.fitMode = false;+ this.updateView();+ this.schedule();}/* ------------------------------------------------------------- public API */@@ -282,10 +645,10 @@ export class WatercolorEngine {* rect around it. Opens one undo step for the whole wash. False while a stroke is* still on the paper.*/- fillBegin(field: Float32Array, bbox: Rect): boolean {+ fillBegin(field: Float32Array, bbox: Rect, label = 'Fill'): boolean {if (this.stroke) return false;if (field.length !== this.dw * this.dh * 2) throw new Error('fill field does not match the document');- this.beginStep(); // also drops any previous fill+ this.beginStep('fill', label); // also drops any previous fillconst tex = this.g.texture(this.dw, this.dh, FLOAT_RG, field, this.gl.NEAREST);this.fill = { tex, bbox: { ...bbox } };return true;@@ -360,15 +723,15 @@ export class WatercolorEngine {/*** Start a stroke driven by code rather than a pointer; it runs through the same* pipeline (spacing, speed thinning, dwell, undo). Returns false while another- * stroke is still on the paper. `newStep` opens an undo step; pass false to- * group several strokes (the letters of a word) into one.+ * stroke is still on the paper. A string `step` opens an undo step with that label;+ * pass false to group several strokes (the letters of a word) into one.*/- scriptBegin(tool: Tool, x: number, y: number, pressure: number, newStep = true): boolean {+ scriptBegin(tool: Tool, x: number, y: number, pressure: number, step: string | false = 'Stroke'): boolean {if (this.stroke) return false;- if (newStep) this.beginStep();+ if (step !== false) this.beginStep('script', step);this.stroke = {pointerId: SCRIPT_POINTER, pointerType: 'pen', tool, started: false, ending: false,- x: 0, y: 0, t: performance.now(), speed: 0, simPressure: 0.45, carry: 0, travelled: 0, moved: false,+ x: 0, y: 0, cx: 0, cy: 0, pr: 0, t: performance.now(), speed: 0, simPressure: 0.45, carry: 0, travelled: 0, moved: false,dx: this.lastDir[0], dy: this.lastDir[1], angle: this.lastAngle, azimuth: null,};this.queue.push({ x, y, p: clamp(pressure, 0.02, 1), t: performance.now(), tx: 0, ty: 0 });@@ -392,6 +755,89 @@ export class WatercolorEngine {setPigment(p: Pigment) { this.pigment = p; }+ /* ------------------------------------------------------------------ paper */++ get paperId() { return this.paperPreset.id; }++ /** How strongly the sheet's relief, fibres and flecks show (0: a flat tint, 1: full), on screen and in textured exports. */+ get paperTexture() { return this.paperStrength; }+ set paperTexture(v: number) {+ v = clamp(v, 0, 1);+ if (v === this.paperStrength) return;+ this.paperStrength = v;+ this.redraw();+ }++ /**+ * Swap the sheet under the painting. Only the paper changes: the paint stays, and+ * granulation and dry brush follow the new tooth from here on.+ */+ setPaper(p: PaperPreset) {+ if (p === this.paperPreset) return;+ this.paperPreset = p;+ this.drawPaper(this.paper, this.paperOrigin, this.paperScale);+ this.redraw();+ }++ /**+ * A preview of a paper at the scale it appears on screen: `w`×`h` device pixels of+ * the sheet with a granulating wash across one corner, as an sRGB canvas.+ */+ paperSwatch(p: PaperPreset, w: number, h: number): HTMLCanvasElement {+ const { gl, g } = this;+ const paper = g.target(w, h, [RGBA8], gl.LINEAR);+ const out = g.target(w, h, [RGBA8], gl.NEAREST);+ // one canvas pixel shows dh / view.h document texels+ this.drawPaper(paper, [w * 0.7, h * 1.3], this.paperScale * (this.dh / this.view.h), p);+ const s = this.programs.paperSwatch;+ s.bind();+ gl.uniform1i(s.u.uPaper, g.bindTex(0, paper.tex[0]));+ this.paperUniforms(s, p, 1);+ g.draw(out);+ const px = new Uint8Array(w * h * 4);+ gl.bindFramebuffer(gl.FRAMEBUFFER, out.fbo);+ gl.readPixels(0, 0, w, h, gl.RGBA, gl.UNSIGNED_BYTE, px);+ g.disposeTarget(paper);+ g.disposeTarget(out);+ const c = document.createElement('canvas');+ c.width = w; c.height = h;+ const ctx = c.getContext('2d')!;+ const img = ctx.createImageData(w, h);+ for (let y = 0; y < h; y++) img.data.set(px.subarray((h - 1 - y) * w * 4, (h - y) * w * 4), y * w * 4);+ ctx.putImageData(img, 0, 0);+ return c;+ }++ /** Generate a paper into `t`: `offset` places it on the sheet (texels), `scale` is paper units per texel. */+ private drawPaper(t: Target, offset: [number, number], scale: number, preset = this.paperPreset) {+ const { gl, g } = this;+ const field = g.target(t.w, t.h, [HALF_FLOAT_RGBA], gl.NEAREST);+ const f = this.programs.paperField;+ f.bind();+ gl.uniform2f(f.u.uRes, t.w, t.h);+ gl.uniform2f(f.u.uOffset, offset[0], offset[1]);+ gl.uniform1f(f.u.uScale, scale);+ gl.uniform1f(f.u.uSeed, this.paperSeed);+ gl.uniform1i(f.u.uKind, preset.kind);+ g.draw(field);+ const l = this.programs.paperLight;+ l.bind();+ gl.uniform1i(l.u.uField, g.bindTex(0, field.tex[0]));+ gl.uniform2f(l.u.uTexel, 1 / t.w, 1 / t.h);+ // the relief is drawn in paper units, so its slope per texel shrinks as texels get smaller+ gl.uniform1f(l.u.uBump, (preset.bump * 1.4) / scale);+ g.draw(t);+ g.disposeTarget(field);+ }++ private paperUniforms(p: Program, preset: PaperPreset, texture: number) {+ const { gl } = this;+ gl.uniform3fv(p.u.uPaperTint, linearRGB(preset.tint));+ gl.uniform3fv(p.u.uFleckTint, linearRGB(preset.fleck));+ gl.uniform1f(p.u.uMottle, preset.mottle);+ gl.uniform1f(p.u.uTexture, texture);+ }+setTool(t: Tool) { this.tool = t; this.updateCursor(); }setBrush(b: Brush) {@@ -408,38 +854,48 @@ export class WatercolorEngine {get referenceAspect() { return this.ref?.aspect ?? 0; }/**- * Show `img` under the paint (or remove it with null), fitted to the paper.- * It survives clearing the paper and is never part of an export.+ * Show `img` under the paint (or remove it with null), fitted to the paper, as one+ * undo step. It survives clearing the paper and is never part of an export.*/setReference(img: ImageBitmap | HTMLCanvasElement | null) {- const { gl } = this;- if (this.ref) { gl.deleteTexture(this.ref.tex); this.ref = null; }+ const before = this.docState();+ let src: HTMLCanvasElement | null = null;if (img) {- const max = Math.min(MAX_REF_SIDE, gl.getParameter(gl.MAX_TEXTURE_SIZE) as number);- let src: TexImageSource = img;+ const max = Math.min(MAX_REF_SIDE, this.gl.getParameter(this.gl.MAX_TEXTURE_SIZE) as number);+ // kept on the CPU as well, so the Fill tool can find areas on it (see readReferenceFlat)const s = Math.min(1, max / Math.max(img.width, img.height));- if (s < 1) {- const c = document.createElement('canvas');- c.width = Math.max(1, Math.round(img.width * s)); c.height = Math.max(1, Math.round(img.height * s));- c.getContext('2d')!.drawImage(img, 0, 0, c.width, c.height);- src = c;- }- const tex = gl.createTexture()!;- gl.activeTexture(gl.TEXTURE0);- gl.bindTexture(gl.TEXTURE_2D, tex);- gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, gl.RGBA, gl.UNSIGNED_BYTE, src);- gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);- this.ref = { tex, aspect: img.width / img.height };- this.fitReference();+ src = document.createElement('canvas');+ src.width = Math.max(1, Math.round(img.width * s)); src.height = Math.max(1, Math.round(img.height * s));+ src.getContext('2d')!.drawImage(img, 0, 0, src.width, src.height);}+ this.uploadReference(src);+ if (src) this.fitReference();+ this.recordChange('reference', src ? 'Reference added' : 'Reference removed', before);this.redraw();}+ /** The reference image as the engine keeps it (downscaled), or null. */+ referenceImage(): HTMLCanvasElement | null { return this.ref?.src ?? null; }++ /** Put `src` on the GPU as the reference (or drop it with null); placement is left alone. */+ private uploadReference(src: HTMLCanvasElement | null) {+ const { gl } = this;+ if (this.ref?.src === src) return;+ if (this.ref) { gl.deleteTexture(this.ref.tex); this.ref = null; }+ if (!src) return;+ const tex = gl.createTexture()!;+ gl.activeTexture(gl.TEXTURE0);+ gl.bindTexture(gl.TEXTURE_2D, tex);+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, gl.RGBA, gl.UNSIGNED_BYTE, src);+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);+ this.ref = { tex, aspect: src.width / src.height, src };+ }+/** The reference placed as large as fits, centred on the paper. */fitReference() {if (!this.ref) return;@@ -448,14 +904,49 @@ export class WatercolorEngine {this.referenceRect = { x: (1 - w) / 2, y: (1 - h) / 2, w, h };}+ /**+ * The reference as placed on the paper, at document resolution, over plain white+ * (where it does not cover the paper, and through any transparency). Same layout as+ * readFlat: RGBA8, opaque, row 0 is document y = 0. Null without a reference.+ */+ readReferenceFlat(): Uint8Array | null {+ if (!this.ref) return null;+ const { dw, dh } = this, r = this.refRect;+ const c = document.createElement('canvas');+ c.width = dw; c.height = dh;+ const ctx = c.getContext('2d', { willReadFrequently: true })!;+ ctx.fillStyle = '#fff';+ ctx.fillRect(0, 0, dw, dh);+ // canvas rows run top-down, document uv runs bottom-up+ ctx.drawImage(this.ref.src, r.x * dw, (1 - r.y - r.h) * dh, r.w * dw, r.h * dh);+ const top = ctx.getImageData(0, 0, dw, dh).data;+ const out = new Uint8Array(dw * dh * 4), row = dw * 4;+ for (let y = 0; y < dh; y++) out.set(top.subarray((dh - 1 - y) * row, (dh - y) * row), y * row);+ for (let i = 3; i < out.length; i += 4) out[i] = 255;+ return out;+ }+get referenceRect(): RefRect { return { ...this.refRect }; }- set referenceRect(r: RefRect) { this.refRect = { ...r }; this.redraw(); }+ set referenceRect(r: RefRect) {+ const c = this.refRect;+ if (r.x === c.x && r.y === c.y && r.w === c.w && r.h === c.h) return;+ this.refRect = { ...r };+ this.redraw();+ }get referenceOpacity() { return this.refOpacity; }- set referenceOpacity(v: number) { this.refOpacity = clamp(v, 0, 1); this.redraw(); }+ set referenceOpacity(v: number) {+ v = clamp(v, 0, 1);+ if (v === this.refOpacity) return;+ this.refOpacity = v;+ this.redraw();+ }++ /** Does the Fill tool find its areas on the reference (traced) rather than on the paint? */+ referenceForFill = false;get referenceVisible() { return this.refVisible; }- set referenceVisible(v: boolean) { this.refVisible = v; this.redraw(); }+ set referenceVisible(v: boolean) { if (v !== this.refVisible) { this.refVisible = v; this.redraw(); } }private redraw() { this.dirtyAll = true; this.schedule(); }@@ -485,7 +976,7 @@ export class WatercolorEngine {/** Dry everything and bake the mobile pigment into the paper. */fix() {if (!this.painted || this.fixTimer > 0) return;- this.beginStep();+ this.beginStep('dry', 'Dry');// the fixed layer only ever changes here, so it is only snapshotted herethis.history.protect(1, this.painted, this.fixed.views);this.fixTimer = FIX_DURATION;@@ -494,28 +985,57 @@ export class WatercolorEngine {this.schedule();}+ /** Wipe the paint as one undo step. The sheet (and its grain) stays. */clear() {this.stroke = null;- this.dropFill();this.queue = [];- this.createDocument();+ if (!this.everPainted && !this.fill) return; // already blank+ this.beginStep('clear', 'Clear');+ if (this.everPainted) {+ this.history.protect(0, this.everPainted, this.snapshotLayers());+ this.history.protect(1, this.everPainted, this.fixed.views);+ }+ for (const t of this.docTargets()) if (t !== this.paper) this.g.clearTarget(t);+ this.resetPaintState();+ this.notifyHistory();this.schedule();}+ /** Take back the stroke in progress as if it never happened (a touch that became a pinch). */+ abortStroke() {+ const s = this.stroke;+ if (!s) return;+ this.stroke = null;+ this.queue = [];+ if (s.pointerId !== SCRIPT_POINTER) this.callbacks.onStrokeTool?.(null);+ if (this.history.canUndo) { this.travel('undo'); this.history.discardRedo(); this.notifyHistory(); }+ }+undo() { if (this.history.canUndo) this.travel('undo'); }redo() { if (this.history.canRedo) this.travel('redo'); }+ /** Undo or redo until `index` steps are applied. */+ jumpTo(index: number) {+ const { index: now, list } = this.history.entries();+ index = clamp(Math.round(index), 0, list.length);+ for (let i = now; i > index && this.history.canUndo; i--) this.travel('undo', false);+ for (let i = now; i < index && this.history.canRedo; i++) this.travel('redo', false);+ this.notifyHistory();+ }+get canUndo() { return this.history.canUndo; }get canRedo() { return this.history.canRedo; }/** Step through history in either direction. */- private travel(dir: 'undo' | 'redo') {+ private travel(dir: 'undo' | 'redo', notify = true) {this.stroke = null;this.dropFill();this.queue = [];this.fixTimer = 0;- const metaNow = this.currentMeta();+ const next = dir === 'undo' ? this.history.peekUndo() : this.history.peekRedo();+ const metaNow: StepMeta = this.currentMeta();+ if (next?.boundary) { metaNow.whole = this.captureWhole(); metaNow.paperOrigin = [...this.paperOrigin]; }this.sleep();const ink = this.ink, wet = this.wet;const layers = [@@ -524,24 +1044,41 @@ export class WatercolorEngine {];const res = dir === 'undo' ? this.history.undo(layers, metaNow) : this.history.redo(layers, metaNow);if (!res) return;- const meta = res.meta as HistoryMeta;+ const meta = res.meta as StepMeta;const now = performance.now();- // the restored water keeps drying from where it was when the step began- this.lastWet = now - meta.wetAgo;- this.wetPeak = meta.wetPeak;- this.active = meta.active ? { ...meta.active } : null;+ if (meta.whole) {+ this.applyWhole(meta.whole, meta.paperOrigin ?? [0, 0]);+ this.painted = meta.painted ? { ...meta.painted } : null;+ }+ if (res.info.kind !== 'paper' && res.info.kind !== 'reference') {+ // the restored water keeps drying from where it was when the step began+ this.lastWet = now - meta.wetAgo;+ this.wetPeak = meta.wetPeak;+ this.active = meta.active ? { ...meta.active } : null;+ }if (res.rect) {this.dirty = union(this.dirty, res.rect);this.painted = union(this.painted, res.rect);+ this.everPainted = union(this.everPainted, res.rect);}- this.notifyHistory();+ this.applyDocState(meta.doc);+ this.callbacks.onDocumentChange?.(this.docState());+ if (notify) this.notifyHistory();this.schedule();}- private notifyHistory() { this.callbacks.onHistoryChange?.(this.history.canUndo, this.history.canRedo); }+ private notifyHistory() {+ this.seenEvictions = this.history.evictions;+ const { list, index } = this.history.entries();+ this.callbacks.onHistoryChange?.(list, index);+ }- private currentMeta(): HistoryMeta {- return { wetAgo: performance.now() - this.lastWet, wetPeak: this.wetPeak, active: this.active ? { ...this.active } : null };+ private currentMeta(): StepMeta {+ return {+ wetAgo: performance.now() - this.lastWet, wetPeak: this.wetPeak,+ active: this.active ? { ...this.active } : null, painted: this.painted ? { ...this.painted } : null,+ doc: this.docState(),+ };}/**@@ -551,7 +1088,7 @@ export class WatercolorEngine {async exportImage(o: ExportOptions): Promise<Blob> {const { dw, dh } = this;const bg = o.format === 'jpeg' && o.background === 'transparent' ? 'white' : o.background;- const px = this.readback(false, MODE[bg]);+ const px = this.readback(false, MODE[bg], o.texture ?? true);const c = document.createElement('canvas');c.width = dw; c.height = dh;const ctx = c.getContext('2d')!;@@ -568,16 +1105,14 @@ export class WatercolorEngine {}/** The composited document at full resolution as RGBA8 bytes, bottom row first. */- private readback(flat: boolean, mode: number = MODE.paper): Uint8Array {+ private readback(flat: boolean, mode: number = MODE.paper, texture = true): Uint8Array {const { gl, g, dw, dh } = this;const out = g.target(dw, dh, [RGBA8], gl.NEAREST);- this.drawDisplay(out, { x: 0, y: 0, w: dw, h: dh }, null, flat, mode);+ this.drawDisplay(out, { x: 0, y: 0, w: dw, h: dh }, null, flat, mode, texture);const px = new Uint8Array(dw * dh * 4);gl.bindFramebuffer(gl.FRAMEBUFFER, out.fbo);gl.readPixels(0, 0, dw, dh, gl.RGBA, gl.UNSIGNED_BYTE, px);- gl.deleteFramebuffer(out.fbo);- out.views.forEach(v => gl.deleteFramebuffer(v));- gl.deleteTexture(out.tex[0]);+ g.disposeTarget(out);return px;}@@ -615,7 +1150,7 @@ export class WatercolorEngine {on(c, 'pointerdown', e => {e.preventDefault();- if (!this.interactive) return;+ if (!this.interactive || this.nav || e.button === 1) return;if (this.stroke) return; // one stroke at a time (palm rejection)if (e.pointerType === 'pen') this.pencilSeen = true;try { c.setPointerCapture(e.pointerId); } catch { /* pointer already gone */ }@@ -625,11 +1160,11 @@ export class WatercolorEngine {else if (e.pointerType === 'pen' && e.buttons & 2) tool = tool === 'water' ? 'brush' : 'water'; // barrel buttonthis.stroke = {pointerId: e.pointerId, pointerType: e.pointerType, tool, started: false, ending: false,- x: 0, y: 0, t: e.timeStamp, speed: 0, simPressure: 0.45, carry: 0, travelled: 0, moved: false,+ x: 0, y: 0, cx: 0, cy: 0, pr: 0, t: e.timeStamp, speed: 0, simPressure: 0.45, carry: 0, travelled: 0, moved: false,dx: this.lastDir[0], dy: this.lastDir[1], angle: this.lastAngle, azimuth: null,};if (tool !== this.tool) this.callbacks.onStrokeTool?.(tool);- this.beginStep();+ this.beginStep('stroke', STROKE_LABEL[tool]);this.pushSample(e);this.trackHover(e);this.schedule();@@ -679,7 +1214,7 @@ export class WatercolorEngine {private updateCursor() {const el = this.cursor;if (!el) return;- if (!this.hover.inside || this.hover.type === 'touch' || !this.interactive) { el.style.opacity = '0'; return; }+ if (!this.hover.inside || this.hover.type === 'touch' || !this.interactive || this.nav) { el.style.opacity = '0'; return; }const tool = this.stroke?.tool ?? this.tool;const r = this.radius(tool, this.stroke ? this.pressureOf(this.stroke, -1) : 0.4, 0);const shaped = tool === 'brush' || tool === 'water';@@ -744,51 +1279,85 @@ export class WatercolorEngine {if (Math.hypot(q.tx, q.ty) > 12) s.azimuth = Math.atan2(-q.ty, q.tx);if (!s.started) {s.started = true;- s.x = q.x; s.y = q.y; s.t = q.t;- this.stamp(s, q.x, q.y, this.pressureOf(s, q.p), 0, 0, 1);+ s.x = s.cx = q.x; s.y = s.cy = q.y; s.t = q.t;+ s.pr = this.pressureOf(s, q.p);+ this.stamp(s, q.x, q.y, s.pr, 0, 0, 1);continue;}const sdt = Math.max(q.t - s.t, 1) / 1000;s.t = q.t;// light smoothing; mice get a little more than stylusesconst k = s.pointerType === 'mouse' ? 0.5 : 0.65;- const nx = s.x + (q.x - s.x) * k, ny = s.y + (q.y - s.y) * k;- const dx = (nx - s.x) * aspect, dy = ny - s.y;+ const nx = s.cx + (q.x - s.cx) * k, ny = s.cy + (q.y - s.cy) * k;+ const len = Math.hypot((nx - s.cx) * aspect, ny - s.cy);+ s.speed += (len / sdt - s.speed) * (1 - Math.exp(-sdt * 10));+ const target = clamp(1.18 - s.speed * 0.95, 0.12, 1);+ s.simPressure += (target - s.simPressure) * (1 - Math.exp(-sdt * 6));+ const pr = this.pressureOf(s, q.p);+ const vx = (nx - s.cx) / sdt, vy = (ny - s.cy) / sdt;+ if (s.pointerId === SCRIPT_POINTER) {+ // scripted glyphs keep their corners+ this.trace(s, nx, ny, nx, ny, pr, vx, vy);+ } else {+ // a fast mouse reports sparse samples (~8ms apart, often 50px+); curving through+ // their midpoints keeps the stroke round instead of a visible polyline+ this.trace(s, s.cx, s.cy, (s.cx + nx) / 2, (s.cy + ny) / 2, pr, vx, vy);+ }+ s.cx = nx; s.cy = ny;+ if (len > 0) s.moved = true;+ }+ this.queue = [];+ // the curve trails half a sample behind; catch up once the pointer rests or lifts+ if (s.started && (!s.moved || s.ending) && (s.x !== s.cx || s.y !== s.cy)) this.trace(s, s.cx, s.cy, s.cx, s.cy, s.pr, 0, 0);+ // resting in place: pigment keeps soaking in, water keeps pooling+ if (!s.moved && s.started && !s.ending) this.stamp(s, s.x, s.y, this.pressureOf(s, -1), 0, 0, 0, dt);+ if (s.ending) {+ this.stroke = null;+ if (s.pointerId !== SCRIPT_POINTER) this.callbacks.onStrokeTool?.(null);+ }+ }++ /**+ * Lay dabs along the quadratic from the stroke's end (s.x, s.y) through control (qx, qy)+ * to (ex, ey), every `spacing` of arc length so deposits don't depend on event rate.+ * Pressure ramps from s.pr to `pr`; direction follows the curve's tangent.+ */+ private trace(s: Stroke, qx: number, qy: number, ex: number, ey: number, pr: number, vx: number, vy: number) {+ const aspect = this.dw / this.dh;+ const x0 = s.x, y0 = s.y, pr0 = s.pr;+ const approx = Math.hypot((qx - x0) * aspect, qy - y0) + Math.hypot((ex - qx) * aspect, ey - qy);+ if (approx < 1e-7) return;+ const fine = this.radius(s.tool, Math.max(pr0, pr), s.speed) * this.spacingFrac(s.tool);+ const n = clamp(Math.ceil(approx / Math.max(fine, 1e-5)), 1, 48);+ let px = x0, py = y0;+ for (let i = 1; i <= n; i++) {+ const u = i / n, w = 1 - u;+ const cx = w * w * x0 + 2 * w * u * qx + u * u * ex;+ const cy = w * w * y0 + 2 * w * u * qy + u * u * ey;+ const dx = (cx - px) * aspect, dy = cy - py;const len = Math.hypot(dx, dy);+ const p = pr0 + (pr - pr0) * u;if (len > 1e-5) {// direction smoothing scaled by distance, so a jittery stylus doesn't spin a flat brush- const kd = 1 - Math.exp(-len / (this.radius(s.tool, this.pressureOf(s, q.p), s.speed) * 1.5 + 1e-4));+ const kd = 1 - Math.exp(-len / (this.radius(s.tool, p, s.speed) * 1.5 + 1e-4));s.dx += (dx / len - s.dx) * kd; s.dy += (dy / len - s.dy) * kd;const m = Math.hypot(s.dx, s.dy) || 1;s.dx /= m; s.dy /= m;this.lastDir = [s.dx, s.dy];}- s.speed += (len / sdt - s.speed) * (1 - Math.exp(-sdt * 10));- const target = clamp(1.18 - s.speed * 0.95, 0.12, 1);- s.simPressure += (target - s.simPressure) * (1 - Math.exp(-sdt * 6));- const pr = this.pressureOf(s, q.p);- const vx = (nx - s.x) / sdt, vy = (ny - s.y) / sdt;- // walk the segment, stamping every `spacing` so deposits don't depend on event rate- const spacing = this.radius(s.tool, pr, s.speed) * this.spacingFrac(s.tool);+ const spacing = this.radius(s.tool, p, s.speed) * this.spacingFrac(s.tool);let pos = 0;while (len - pos >= spacing - s.carry) {pos += spacing - s.carry;s.carry = 0;const t = pos / len;- this.stamp(s, s.x + (nx - s.x) * t, s.y + (ny - s.y) * t, pr, vx, vy, 1);+ this.stamp(s, px + (cx - px) * t, py + (cy - py) * t, p, vx, vy, 1);}s.carry += len - pos;s.travelled += len;- if (len > 0) s.moved = true;- s.x = nx; s.y = ny;- }- this.queue = [];- // resting in place: pigment keeps soaking in, water keeps pooling- if (!s.moved && s.started && !s.ending) this.stamp(s, s.x, s.y, this.pressureOf(s, -1), 0, 0, 0, dt);- if (s.ending) {- this.stroke = null;- if (s.pointerId !== SCRIPT_POINTER) this.callbacks.onStrokeTool?.(null);+ px = cx; py = cy;}+ s.x = ex; s.y = ey; s.pr = pr;}/** Dab spacing as a fraction of the footprint radius. */@@ -926,13 +1495,22 @@ export class WatercolorEngine {return { x0: clamp(cx - e, 0, w), y0: clamp(cy - e, 0, h), x1: clamp(cx + e, 0, w), y1: clamp(cy + e, 0, h) };}- /** Grow the simulated region, saving tiles for undo before anything in them changes. */- private touch(rect: Rect, wake = true) {+ /**+ * Grow the simulated region. With `save`, the tiles around `rect` are saved for undo+ * first: a step restores what its own dabs and fills touched (plus a margin for what+ * spread from them), while the rest of the sheet simply keeps drying. That keeps a+ * step's cost proportional to the stroke, not to everything that happens to be wet.+ */+ private touch(rect: Rect, wake = true, save = true) {if (rect.x1 <= rect.x0 || rect.y1 <= rect.y0) return;const next = union(this.active, rect);- this.history.protect(0, next, this.snapshotLayers());+ if (save) {+ const m = PROTECT_MARGIN;+ this.history.protect(0, { x0: Math.max(0, rect.x0 - m), y0: Math.max(0, rect.y0 - m), x1: Math.min(this.dw, rect.x1 + m), y1: Math.min(this.dh, rect.y1 + m) }, this.snapshotLayers());+ }this.active = next;this.painted = union(this.painted, rect);+ this.everPainted = union(this.everPainted, rect);this.dirty = union(this.dirty, rect);if (wake) this.minAwakeUntil = Math.max(this.minAwakeUntil, performance.now() + 250);}@@ -1026,10 +1604,9 @@ export class WatercolorEngine {return this.lastWet + this.dryTau() * Math.log(this.wetPeak / WET_THRESHOLD) * 1000;}- private beginStep() {+ private beginStep(kind: StepKind, label: string) {this.dropFill(); // a new action ends a running fill; its remaining bands never land in this step- this.history.begin(this.currentMeta());- if (this.active) this.history.protect(0, this.active, this.snapshotLayers());+ this.history.begin({ kind, label }, this.currentMeta());this.notifyHistory();}@@ -1147,6 +1724,48 @@ export class WatercolorEngine {this.dirty = union(this.dirty, rect);}+ /**+ * The active rect grows blindly each frame so the wet front can creep; left alone it+ * would cover the sheet in a minute, and every undo step would have to save all of+ * it. Now and then, find where there is actually water and cut the rect down to that.+ */+ private trimActive() {+ const a = this.active;+ if (!a) return;+ const { gl, g } = this;+ const m = this.wetMask;+ const p = this.programs.wetMask;+ p.bind();+ gl.uniform1i(p.u.uWet, g.bindTex(0, this.wet.read.tex[0]));+ gl.uniform2f(p.u.uBlock, 1 / m.w, 1 / m.h);+ gl.uniform1f(p.u.uThreshold, WET_THRESHOLD);+ g.draw(m);+ gl.bindFramebuffer(gl.FRAMEBUFFER, m.fbo);+ gl.readPixels(0, 0, m.w, m.h, gl.RGBA, gl.UNSIGNED_BYTE, this.maskPixels);+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);+ let x0 = m.w, y0 = m.h, x1 = -1, y1 = -1;+ const px = this.maskPixels;+ for (let y = 0; y < m.h; y++) for (let x = 0; x < m.w; x++) {+ if (!px[(y * m.w + x) * 4]) continue;+ if (x < x0) x0 = x; if (x > x1) x1 = x; if (y < y0) y0 = y; if (y > y1) y1 = y;+ }+ let next: Rect | null = null;+ if (x1 >= 0) {+ const wet = {+ x0: Math.max(0, x0 * MASK_BLOCK - MASK_MARGIN), y0: Math.max(0, y0 * MASK_BLOCK - MASK_MARGIN),+ x1: Math.min(this.dw, (x1 + 1) * MASK_BLOCK + MASK_MARGIN), y1: Math.min(this.dh, (y1 + 1) * MASK_BLOCK + MASK_MARGIN),+ };+ const r = { x0: Math.max(a.x0, wet.x0), y0: Math.max(a.y0, wet.y0), x1: Math.min(a.x1, wet.x1), y1: Math.min(a.y1, wet.y1) };+ if (r.x1 > r.x0 && r.y1 > r.y0) next = r;+ }+ if (next && next.x0 === a.x0 && next.y0 === a.y0 && next.x1 === a.x1 && next.y1 === a.y1) return;+ // the part being dropped was updated into alternating halves: make them agree before it is left alone+ const w = a.x1 - a.x0, h = a.y1 - a.y0;+ for (const d of [this.ink, this.wet])+ d.read.views.forEach((v, i) => g.blit(v, a.x0, a.y0, d.write.views[i], a.x0, a.y0, w, h));+ if (next) this.active = next; else this.sleep();+ }+/** Make both halves of the ping-pong buffers identical, then stop simulating. */private sleep() {const rect = this.active;@@ -1164,7 +1783,7 @@ export class WatercolorEngine {/* -------------------------------------------------------------- display */- private drawDisplay(target: Target | null, view: { x: number; y: number; w: number; h: number }, scissor: Rect | null, flat = false, mode: number = MODE.screen) {+ private drawDisplay(target: Target | null, view: { x: number; y: number; w: number; h: number }, scissor: Rect | null, flat = false, mode: number = MODE.screen, texture = true) {const { gl, g } = this;const p = this.programs.display;p.bind();@@ -1181,12 +1800,17 @@ export class WatercolorEngine {gl.uniform1f(p.u.uFlat, flat ? 1 : 0);gl.uniform3fv(p.u.uDesk, DESK);gl.uniform1i(p.u.uMode, mode);+ this.paperUniforms(p, this.paperPreset, texture ? this.paperStrength : 0);const ref = mode === MODE.screen && !flat && this.refVisible ? this.ref : null;gl.uniform1f(p.u.uRefOpacity, ref ? this.refOpacity : 0);// the sampler needs a texture bound either way; the paper stands in when there is nonegl.uniform1i(p.u.uRef, g.bindTex(6, ref ? ref.tex : this.paper.tex[0]));const r = this.refRect;gl.uniform4f(p.u.uRefRect, r.x, r.y, r.w, r.h);+ // the shadow grows with the sheet on screen, within a range that always reads as paper on a desk+ const shadow = mode === MODE.screen && !target ? clamp(Math.min(view.w, view.h) / this.dpr * 0.05, 14, 48) * this.dpr : 0;+ gl.uniform1f(p.u.uShadow, shadow);+ gl.uniform1f(p.u.uDpr, this.dpr);g.draw(target, scissor, this.canvasSize);}@@ -1234,11 +1858,14 @@ export class WatercolorEngine {if (grow > 0) {this.growCarry -= grow;const a = this.active!;- this.touch({ x0: Math.max(0, a.x0 - grow), y0: Math.max(0, a.y0 - grow), x1: Math.min(this.dw, a.x1 + grow), y1: Math.min(this.dh, a.y1 + grow) }, false);+ this.touch({ x0: Math.max(0, a.x0 - grow), y0: Math.max(0, a.y0 - grow), x1: Math.min(this.dw, a.x1 + grow), y1: Math.min(this.dh, a.y1 + grow) }, false, false);}this.step(dt);+ if (this.fixTimer <= 0 && ++this.maskCounter >= MASK_EVERY) { this.maskCounter = 0; this.trimActive(); }}this.render();+ // a stroke that ran the undo memory dry dropped old steps: the list should say so+ if (this.history.evictions !== this.seenEvictions) this.notifyHistory();if (!awake && this.active) this.sleep();if (awake || this.stroke) this.schedule();};diff --git a/src/engine/gl.ts b/src/engine/gl.tsindex 5610d3c..fdc6cd4 100644--- a/src/engine/gl.ts+++ b/src/engine/gl.ts@@ -1,5 +1,7 @@// Minimal WebGL2 plumbing: full-screen-triangle programs and (multi-)render targets.+import { f32ToF16 } from './half';+export const QUAD_VS = `#version 300 esprecision highp float;layout(location=0) in vec2 aPos;@@ -37,7 +39,7 @@ export interface DoubleTarget {export class GL {readonly gl: WebGL2RenderingContext;private vs: WebGLShader;- private resources: (() => void)[] = [];+ private resources = new Map<Target, () => void>();constructor(gl: WebGL2RenderingContext) {this.gl = gl;@@ -107,7 +109,7 @@ export class GL {}const target = { w, h, fbo, tex, views };this.clearTarget(target);- this.resources.push(() => {+ this.resources.set(target, () => {gl.deleteFramebuffer(fbo);views.forEach(v => gl.deleteFramebuffer(v));tex.forEach(t => gl.deleteTexture(t));@@ -188,9 +190,73 @@ export class GL {gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null);}++ /**+ * Read a single-attachment float framebuffer (a `Target.views[i]`) as half floats:+ * `channels` (1 or 4) per texel, rows bottom-up (row 0 is y = 0), within `rect`+ * (default: all of it). Reads HALF_FLOAT directly when the driver allows, else+ * FLOAT in bands converted on the CPU.+ */+ readHalf(fb: WebGLFramebuffer, w: number, h: number, channels: 1 | 4, rect?: Rect): Uint16Array {+ const { gl } = this;+ const x0 = rect?.x0 ?? 0, y0 = rect?.y0 ?? 0, rw = (rect?.x1 ?? w) - x0, rh = (rect?.y1 ?? h) - y0;+ const out = new Uint16Array(Math.max(0, rw * rh * channels));+ if (rw <= 0 || rh <= 0) return out;+ gl.bindFramebuffer(gl.FRAMEBUFFER, fb);+ gl.pixelStorei(gl.PACK_ALIGNMENT, 1);+ // RGBA / FLOAT is always allowed for a float colour buffer; RGBA / HALF_FLOAT only when the driver says so+ const type = gl.getParameter(gl.IMPLEMENTATION_COLOR_READ_TYPE) as number;+ const format = gl.getParameter(gl.IMPLEMENTATION_COLOR_READ_FORMAT) as number;+ const direct = format === gl.RGBA && type === gl.HALF_FLOAT;+ gl.getError(); // clear anything stale so a failed read below is caught+ const rows = Math.max(1, Math.floor((4 * 1024 * 1024) / (rw * 4))); // ~16 MiB of float32 per band+ const band32 = direct ? null : new Float32Array(rw * rows * 4);+ const band16 = direct && channels === 1 ? new Uint16Array(rw * rows * 4) : null;+ for (let y = 0; y < rh; y += rows) {+ const n = Math.min(rows, rh - y);+ if (direct && channels === 4) {+ gl.readPixels(x0, y0 + y, rw, n, gl.RGBA, gl.HALF_FLOAT, out.subarray(y * rw * 4, (y + n) * rw * 4));+ continue;+ }+ let src: Uint16Array;+ if (direct) {+ gl.readPixels(x0, y0 + y, rw, n, gl.RGBA, gl.HALF_FLOAT, band16!);+ src = band16!;+ } else {+ gl.readPixels(x0, y0 + y, rw, n, gl.RGBA, gl.FLOAT, band32!);+ if (channels === 4) { f32ToF16(band32!, out.subarray(y * rw * 4), n * rw * 4); continue; }+ src = new Uint16Array(n * rw * 4);+ f32ToF16(band32!, src, n * rw * 4);+ }+ const base = y * rw;+ for (let i = 0, m = n * rw; i < m; i++) out[base + i] = src[i * 4];+ }+ const err = gl.getError();+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);+ if (err) throw new Error('This GPU cannot read its paint layers back.');+ return out;+ }++ /** Upload half floats into a texStorage2D texture at (x, y); `format` is RGBA or RED to match it. */+ uploadHalf(tex: WebGLTexture, x: number, y: number, w: number, h: number, format: number, data: Uint16Array) {+ const { gl } = this;+ if (w <= 0 || h <= 0) return;+ gl.activeTexture(gl.TEXTURE0);+ gl.bindTexture(gl.TEXTURE_2D, tex);+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 2);+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);+ gl.texSubImage2D(gl.TEXTURE_2D, 0, x, y, w, h, format, gl.HALF_FLOAT, data);+ }++ /** Free one target now (a scratch target that should not live until disposeTargets). */+ disposeTarget(t: Target) {+ this.resources.get(t)?.();+ this.resources.delete(t);+ }+/** Free every target created so far (used on document re-creation). */disposeTargets() {this.resources.forEach(f => f());- this.resources = [];+ this.resources.clear();}}diff --git a/src/engine/half.ts b/src/engine/half.tsnew file mode 100644index 0000000..ab74616--- /dev/null+++ b/src/engine/half.ts@@ -0,0 +1,46 @@+// IEEE 754 binary16 <-> binary32, for moving half-float textures through the CPU.++const f32 = new Float32Array(1);+const u32 = new Uint32Array(f32.buffer);++/** One float -> half, round to nearest even; overflow -> Inf, NaN kept. */+export function toHalf(v: number): number {+ f32[0] = v;+ const x = u32[0];+ const sign = (x >>> 16) & 0x8000;+ let exp = (x >>> 23) & 0xff;+ let mant = x & 0x7fffff;+ if (exp === 0xff) return sign | 0x7c00 | (mant ? 0x200 : 0); // Inf / NaN+ const e = exp - 127 + 15;+ if (e >= 0x1f) return sign | 0x7c00; // overflow+ if (e <= 0) {+ if (e < -10) return sign; // underflow to zero+ mant |= 0x800000; // subnormal half+ const shift = 14 - e;+ let h = mant >>> shift;+ const rem = mant & ((1 << shift) - 1), half = 1 << (shift - 1);+ if (rem > half || (rem === half && (h & 1))) h++;+ return sign | h;+ }+ let h = (e << 10) | (mant >>> 13);+ const rem = mant & 0x1fff;+ if (rem > 0x1000 || (rem === 0x1000 && (h & 1))) h++; // may carry into the exponent: that is correct rounding+ return sign | h;+}++/** One half -> float. */+export function fromHalf(h: number): number {+ const sign = (h & 0x8000) ? -1 : 1;+ const exp = (h >>> 10) & 0x1f, mant = h & 0x3ff;+ if (exp === 0) return sign * mant * 2 ** -24;+ if (exp === 0x1f) return mant ? NaN : sign * Infinity;+ return sign * (1 + mant / 1024) * 2 ** (exp - 15);+}++export function f32ToF16(src: Float32Array, dst: Uint16Array, n = src.length): void {+ for (let i = 0; i < n; i++) dst[i] = toHalf(src[i]);+}++export function f16ToF32(src: Uint16Array, dst: Float32Array, n = src.length): void {+ for (let i = 0; i < n; i++) dst[i] = fromHalf(src[i]);+}diff --git a/src/engine/history.ts b/src/engine/history.tsindex 4234915..025bfcd 100644--- a/src/engine/history.ts+++ b/src/engine/history.ts@@ -5,6 +5,8 @@ const TILE = 128;/** A set of layers snapshotted together, with its own atlas and slot pool. */class Pool {readonly atlas: Target[];+ /** One tile per layer, so undo can swap a tile's content without allocating a slot. */+ readonly scratch: Target[];readonly cols: number;readonly free: number[] = [];@@ -14,17 +16,29 @@ class Pool {const rows = Math.ceil(tiles / this.cols);// one single-attachment atlas per layer, so blits stay 1:1this.atlas = formats.map(f => g.target(this.cols * TILE, rows * TILE, [f], g.gl.NEAREST));+ this.scratch = formats.map(f => g.target(TILE, TILE, [f], g.gl.NEAREST));for (let i = tiles - 1; i >= 0; i--) this.free.push(i);}++ dispose(g: GL) { [...this.atlas, ...this.scratch].forEach(t => g.disposeTarget(t)); }}-interface Step {+export type StepKind = 'stroke' | 'fill' | 'script' | 'dry' | 'clear' | 'resize' | 'paper' | 'reference';++/** What a step was, for the history list. */+export interface StepInfo { kind: StepKind; label: string }++interface Step extends StepInfo {/** per pool: tile index -> atlas slot holding that tile's content from before the step */tiles: Map<number, number>[];/** opaque engine state captured when the step began (wetness clock etc.) */meta: unknown;+ /** The sheet changed size at this step: its meta carries the whole old document, not tiles. */+ boundary?: boolean;}+interface Group { formats: Format[]; documents: number }+/*** Undo via copy-on-write tiles. Everything outside the simulation's active rect is* static, so before any texel is modified the engine calls `protect(...)`, which@@ -32,36 +46,88 @@ interface Step {* back. Layers are grouped into pools (e.g. the fixed layer only changes when the* painting is fixed, so it has its own pool and is only saved then). Each pool's* memory is bounded; the oldest steps are dropped to make room.+ *+ * Tiles only make sense for one sheet size, so a resize is a *boundary* step: it keeps+ * the whole old document in its meta instead, and crossing it (in either direction)+ * forgets the steps on the far side of the stack it lands on.*/export class History {- private pools: Pool[];- private tilesX: number;- private tilesY: number;+ private pools!: Pool[];+ private tilesX!: number;+ private tilesY!: number;private steps: Step[] = [];private redoSteps: Step[] = [];private maxSteps = 50;+ /** False after undo / redo until the next step begins: the sim settling then is saved only while slots are free. */+ private recording = false;+ /** Bumped whenever a step is dropped to make room, so the engine can tell the UI. */+ evictions = 0;/** `groups[i]` lists a pool's layer formats and its capacity in documents' worth of tiles. */- constructor(private g: GL, private w: number, private h: number, groups: { formats: Format[]; documents: number }[]) {- this.tilesX = Math.ceil(w / TILE);- this.tilesY = Math.ceil(h / TILE);+ constructor(private g: GL, private w: number, private h: number, private groups: Group[]) {+ this.allocate();+ }++ private allocate() {+ this.tilesX = Math.ceil(this.w / TILE);+ this.tilesY = Math.ceil(this.h / TILE);const tiles = this.tilesX * this.tilesY;- this.pools = groups.map(gr => new Pool(g, Math.ceil(tiles * gr.documents), gr.formats));+ this.pools = this.groups.map(gr => new Pool(this.g, Math.ceil(tiles * gr.documents), gr.formats));}get canUndo() { return this.steps.length > 0; }get canRedo() { return this.redoSteps.length > 0; }- begin(meta: unknown) {+ /** Every step, oldest first (applied ones, then undone ones), and how many are applied. */+ entries(): { list: StepInfo[]; index: number } {+ const info = (s: Step): StepInfo => ({ kind: s.kind, label: s.label });+ return { list: [...this.steps.map(info), ...[...this.redoSteps].reverse().map(info)], index: this.steps.length };+ }++ /** The step undo would take back, if any. */+ peekUndo(): (StepInfo & { boundary: boolean }) | null { return this.peek(this.steps); }+ /** The step redo would re-apply, if any. */+ peekRedo(): (StepInfo & { boundary: boolean }) | null { return this.peek(this.redoSteps); }++ private peek(stack: Step[]) {+ const s = stack[stack.length - 1];+ return s ? { kind: s.kind, label: s.label, boundary: !!s.boundary } : null;+ }++ begin(info: StepInfo, meta: unknown) {this.clearRedo(); // a new action forks history- this.steps.push({ tiles: this.pools.map(() => new Map()), meta });+ this.steps.push({ ...info, tiles: this.pools.map(() => new Map()), meta });+ this.recording = true;while (this.steps.length > this.maxSteps) this.dropOldest();}+ /**+ * Record a change of sheet size to `w`×`h`. Earlier steps hold tiles of the old sheet,+ * so they are forgotten; the step itself keeps the old document in `meta`.+ */+ beginBoundary(info: StepInfo, meta: unknown, w: number, h: number) {+ this.clearRedo();+ for (const s of this.steps) this.release(s);+ this.steps = [{ ...info, tiles: [], meta, boundary: true }];+ this.recording = true;+ this.resize(w, h);+ }++ /** Re-create the tile pools for a `w`×`h` sheet (after a boundary step was crossed). */+ resize(w: number, h: number) {+ for (const s of this.steps) { this.release(s); s.tiles = []; }+ for (const s of this.redoSteps) { this.release(s); s.tiles = []; }+ this.dispose();+ this.w = w; this.h = h;+ this.allocate();+ for (const s of [...this.steps, ...this.redoSteps]) if (!s.boundary) s.tiles = this.pools.map(() => new Map());+ }+/** Save not-yet-saved tiles of `rect` (document texels) of pool `p` before they change. */protect(p: number, rect: Rect, layers: WebGLFramebuffer[]) {const step = this.steps[this.steps.length - 1];if (!step) return;+ if (step.boundary) return; // the sim settling after a resize is restored wholesale with the old sheetconst pool = this.pools[p], saved = step.tiles[p];const tx0 = Math.max(0, Math.floor(rect.x0 / TILE)), tx1 = Math.min(this.tilesX - 1, Math.floor((rect.x1 - 1) / TILE));const ty0 = Math.max(0, Math.floor(rect.y0 / TILE)), ty1 = Math.min(this.tilesY - 1, Math.floor((rect.y1 - 1) / TILE));@@ -69,7 +135,8 @@ export class History {for (let tx = tx0; tx <= tx1; tx++) {const id = ty * this.tilesX + tx;if (saved.has(id)) continue;- const slot = this.allocSlot(pool, 'protect');+ // after an undo the paint keeps drying into the previous step; that is not worth losing a step for+ const slot = this.recording ? this.allocSlot(pool) : pool.free.pop();if (slot === undefined) return; // a pool holds at least one whole documentsaved.set(id, slot);this.copyTile(pool, id, slot, layers, true);@@ -84,59 +151,65 @@ export class History {* on redo. Returns the step's meta and the document rect that changed.*/undo(layers: WebGLFramebuffer[][][], metaNow: unknown) {- return this.swap(this.steps, this.redoSteps, layers, metaNow, 0);+ return this.swap(this.steps, this.redoSteps, layers, metaNow);}/** Re-apply the last undone step. */redo(layers: WebGLFramebuffer[][][], metaNow: unknown) {- return this.swap(this.redoSteps, this.steps, layers, metaNow, 1);+ return this.swap(this.redoSteps, this.steps, layers, metaNow);}/*** Undo and redo are the same move in opposite directions: pop a step from `from`,- * save the tiles it covers as they are now, restore its tiles, and push the saved- * ones onto `to`. `keep` says which stack is protected when slots run short.+ * swap the content of each of its tiles with what is on the sheet now (through a+ * scratch tile, so nothing is allocated and no other step can be lost), and push+ * the step, now holding the way back, onto `to`.*/- private swap(from: Step[], to: Step[], layers: WebGLFramebuffer[][][], metaNow: unknown, keep: 0 | 1): { meta: unknown; rect: Rect | null } | null {+ private swap(from: Step[], to: Step[], layers: WebGLFramebuffer[][][], metaNow: unknown): { meta: unknown; rect: Rect | null; info: StepInfo } | null {const step = from.pop();if (!step) return null;- const back: Step = { tiles: this.pools.map(() => new Map()), meta: metaNow };- let complete = true;+ this.recording = false;+ const info: StepInfo = { kind: step.kind, label: step.label };+ if (step.boundary) {+ // the far side of the other stack was made on a sheet of another size+ for (const s of to) this.release(s);+ to.length = 0;+ to.push({ ...info, tiles: [], meta: metaNow, boundary: true });+ return { meta: step.meta, rect: null, info };+ }+ const back: Step = { ...info, tiles: step.tiles, meta: metaNow };let rect: Rect | null = null;step.tiles.forEach((saved, p) => {const pool = this.pools[p];for (const [id, slot] of saved) {- if (complete) {- const now = this.allocSlot(pool, keep === 0 ? 'undo' : 'redo');- if (now === undefined) complete = false;- else { this.copyTile(pool, id, now, layers[p].map(l => l[0]), true); back.tiles[p].set(id, now); }- }- const copies = Math.max(...layers[p].map(l => l.length));- for (let c = 0; c < copies; c++)- this.copyTile(pool, id, slot, layers[p].map(l => l[Math.min(c, l.length - 1)]), false);const tx = id % this.tilesX, ty = Math.floor(id / this.tilesX);- const r = { x0: tx * TILE, y0: ty * TILE, x1: Math.min(this.w, (tx + 1) * TILE), y1: Math.min(this.h, (ty + 1) * TILE) };+ const w = Math.min(TILE, this.w - tx * TILE), h = Math.min(TILE, this.h - ty * TILE);+ const sx = (slot % pool.cols) * TILE, sy = Math.floor(slot / pool.cols) * TILE;+ layers[p].forEach((fbs, i) => {+ const atlas = pool.atlas[i].views[0], scratch = pool.scratch[i].views[0];+ this.g.blit(fbs[0], tx * TILE, ty * TILE, scratch, 0, 0, w, h); // now -> scratch+ for (const fb of fbs) this.g.blit(atlas, sx, sy, fb, tx * TILE, ty * TILE, w, h); // saved -> sheet (both halves)+ this.g.blit(scratch, 0, 0, atlas, sx, sy, w, h); // scratch -> slot: the way back+ });+ const r = { x0: tx * TILE, y0: ty * TILE, x1: tx * TILE + w, y1: ty * TILE + h };rect = rect ? { x0: Math.min(rect.x0, r.x0), y0: Math.min(rect.y0, r.y0), x1: Math.max(rect.x1, r.x1), y1: Math.max(rect.y1, r.y1) } : r;- pool.free.push(slot);}});- // without room for every tile the way back is lost: drop it rather than restore half a step later- if (complete) to.push(back); else this.release(back);- return { meta: step.meta, rect };+ to.push(back);+ return { meta: step.meta, rect, info };}/**- * A free slot of `pool`, making room if needed. While recording or undoing, redo- * steps go first (newest first: they are the cheapest to lose), then the oldest- * undo steps; the step being recorded is never dropped. While redoing, old undo- * steps go before the remaining redo steps.+ * A free slot of `pool`, making room if needed: the oldest undo steps go first (the+ * step being recorded never does), then redo steps, newest first. Only recording+ * allocates; undo and redo swap tiles in place.*/- private allocSlot(pool: Pool, mode: 'protect' | 'undo' | 'redo'): number | undefined {+ private allocSlot(pool: Pool): number | undefined {while (!pool.free.length) {- if (mode !== 'redo' && this.redoSteps.length) this.release(this.redoSteps.pop()!);- else if (this.steps.length > (mode === 'protect' ? 1 : 0)) this.release(this.steps.shift()!);- else if (mode === 'redo' && this.redoSteps.length) this.release(this.redoSteps.pop()!);+ if (this.steps.length > 1) this.release(this.steps.shift()!);+ else if (this.redoSteps.length) this.release(this.redoSteps.pop()!);else break;+ this.evictions++;}return pool.free.pop();}@@ -146,6 +219,19 @@ export class History {if (s) this.release(s);}+ /** Forget the redo stack (after an undone step should not come back). */+ discardRedo() { this.clearRedo(); }++ /** Free the atlases (when the document is replaced without disposing every target). */+ dispose() { this.pools.forEach(p => p.dispose(this.g)); }++ /** Forget everything (the document was replaced). */+ reset() {+ for (const s of this.steps) this.release(s);+ this.steps = [];+ this.clearRedo();+ }+private clearRedo() {for (const s of this.redoSteps) this.release(s);this.redoSteps = [];diff --git a/src/engine/papers.ts b/src/engine/papers.tsnew file mode 100644index 0000000..32678e6--- /dev/null+++ b/src/engine/papers.ts@@ -0,0 +1,56 @@+// Paper presets. Each picks one of the procedural height fields in paperFieldFS (`kind`)+// and says how the sheet looks: its colour, inclusions, how strongly the relief is lit+// and how cloudy the fibre formation is. The height also decides where pigment+// granulates and what a dry brush skips, so a paper changes how paint behaves too.++export interface PaperPreset {+ id: string;+ name: string;+ hint: string;+ /** Which height field the paper shader builds (see paperFieldFS). */+ kind: number;+ /** Sheet colour (sRGB). */+ tint: string;+ /** Colour of dark specks and inclusions (sRGB). */+ fleck: string;+ /** How strongly the relief is lit. */+ bump: number;+ /** Cloudiness of the sheet: uneven fibre formation, felt marks. */+ mottle: number;+}++export const PAPERS: PaperPreset[] = [+ { id: 'cold', name: 'Cold Press', hint: 'Medium tooth, natural white: the all-round watercolour sheet', kind: 0, tint: '#f6f3ec', fleck: '#8a8070', bump: 1.0, mottle: 0.05 },+ { id: 'hot', name: 'Hot Press', hint: 'Pressed smooth and bright: crisp edges, little granulation', kind: 1, tint: '#f8f7f3', fleck: '#8a8478', bump: 0.6, mottle: 0.04 },+ { id: 'rough', name: 'Rough', hint: 'Deep, knobbly tooth: dry brush breaks up, pigment pools in the hollows', kind: 2, tint: '#f5f1e8', fleck: '#857a68', bump: 0.8, mottle: 0.06 },+ { id: 'khadi', name: 'Khadi', hint: 'Handmade cotton rag: lumpy, cream, with fibres and specks', kind: 3, tint: '#efe7d6', fleck: '#6d5f4a', bump: 1.0, mottle: 0.12 },+ { id: 'washi', name: 'Washi', hint: 'Japanese kozo: smooth, cloudy, with long silky fibres', kind: 4, tint: '#f1ece0', fleck: '#7a6a52', bump: 0.8, mottle: 0.14 },+ { id: 'laid', name: 'Laid', hint: 'Ingres-style laid lines with chain lines every inch', kind: 5, tint: '#f2ebdb', fleck: '#8a7c64', bump: 1.0, mottle: 0.05 },+ { id: 'canvas', name: 'Canvas', hint: 'Primed cotton canvas board: a fine plain weave', kind: 6, tint: '#f3efe6', fleck: '#8a8070', bump: 1.0, mottle: 0.04 },+ { id: 'toned', name: 'Toned Sand', hint: 'Mi-Teintes-style honeycomb tooth on a warm tan sheet', kind: 7, tint: '#d9c8a6', fleck: '#6e5f45', bump: 1.0, mottle: 0.06 },+ { id: 'kraft', name: 'Kraft', hint: 'Recycled brown kraft: smooth, streaky, flecked', kind: 8, tint: '#b99872', fleck: '#4e3b28', bump: 0.8, mottle: 0.12 },+ { id: 'cellulose', name: 'Student', hint: 'Wood-pulp student paper: a regular machine-pressed texture', kind: 9, tint: '#f7f7f4', fleck: '#8a8a84', bump: 1.0, mottle: 0.03 },+];++export const DEFAULT_PAPER = PAPERS[0];++/** sRGB hex -> linear RGB, as the display shader mixes in linear light. */+export function linearRGB(hex: string): [number, number, number] {+ const n = parseInt(hex.slice(1), 16);+ const f = (c: number) => { c /= 255; return c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4); };+ return [f((n >> 16) & 255), f((n >> 8) & 255), f(n & 255)];+}++/** Sheet sizes in pixels (landscape; the orientation switch turns them). `screen` follows the window. */+export interface PaperSize { id: string; name: string; w: number; h: number; hint: string }++export const PAPER_SIZES: PaperSize[] = [+ { id: 'screen', name: 'Screen', w: 0, h: 0, hint: 'The shape of this window' },+ { id: 'square', name: 'Square', w: 1600, h: 1600, hint: '1:1' },+ { id: 'postcard', name: 'Postcard', w: 1800, h: 1200, hint: '6 × 4 in at 300 dpi' },+ { id: 'hd', name: 'HD', w: 1920, h: 1080, hint: '16:9 Full HD' },+ { id: 'a', name: 'A-series', w: 2000, h: 1414, hint: 'ISO A shape (√2), like A4' },+ { id: 'letter', name: 'Letter', w: 1980, h: 1530, hint: '11 × 8.5 in shape' },+ { id: 'large', name: 'Large', w: 2400, h: 1600, hint: '3:2, the largest preset' },+ { id: 'custom', name: 'Custom', w: 0, h: 0, hint: 'Any width and height' },+];diff --git a/src/engine/shaders.ts b/src/engine/shaders.tsindex 7cb34f0..2bbab80 100644--- a/src/engine/shaders.ts+++ b/src/engine/shaders.ts@@ -6,7 +6,7 @@ import { displayBasisGLSL } from './spectral';// ink 2 × RGBA16F (document) mobile pigment: A = absorbance coeffs 0..3,// B.rgb = coeffs 4..6, B.a = white gouache// fixed 2 × RGBA16F (document) pigment settled into the paper (no white)-// paper RGBA8 (document) r = lit relief, g = height, b = fibre+// paper RGBA8 (document) r = lit relief, g = height, b = mottle, a = fleckconst HEADER = `#version 300 esprecision highp float;@@ -132,6 +132,23 @@ out vec4 o;uniform sampler2D uTex; uniform float uValue;void main(){ o = texture(uTex, vUv) * uValue; }`;+// Where is there water at all? One output texel per block of the sheet: 1 where any of+// 8×8 taps across the block is wetter than uThreshold. Read back to bound the simulated region.+export const wetMaskFS = `${HEADER}+out vec4 o;+uniform sampler2D uWet;+uniform vec2 uBlock; // one output texel, in wet-texture uv+uniform float uThreshold;+void main(){+ vec2 base = vUv - uBlock * 0.5;+ float m = 0.0;+ for (int y = 0; y < 8; y++) for (int x = 0; x < 8; x++) {+ vec2 p = base + uBlock * (vec2(float(x), float(y)) + 0.5) / 8.0;+ m = max(m, texture(uWet, p).r);+ }+ o = vec4(m > uThreshold ? 1.0 : 0.0, 0.0, 0.0, 1.0);+}`;+// Water: carried a little by the flow, creeps outward, evaporates.export const advectWetFS = `${HEADER}out vec4 o;@@ -247,30 +264,280 @@ void main(){o1 = vec4(f);}`;-// Cold-press paper, generated once per document.-export const paperFS = `${HEADER}+// Paper, generated per document and whenever the paper is changed, in two passes.+// paperFieldFS builds the sheet's procedural field into a half-float target:+// x = height 0..1 (mean ~0.5), y = mottle 0..1 (fibre clumping, 0.5 neutral),+// z = fleck 0..1 (0.5 none, below: dark speck, above: light fibre).+// paperLightFS then lights the height from the upper left and packs the paper texture.+// Positions are in "units": a texel of a 1100-texel-tall sheet, about 0.18 mm, so the+// grain looks the same at any document size.+export const paperFieldFS = `${HEADER}out vec4 o;-uniform vec2 uRes;+uniform vec2 uRes, uOffset; // target size and where it sits on the sheet (texels)+uniform float uScale; // units per texeluniform float uSeed;-float hash(vec2 p){ p = fract(p * vec2(123.34, 456.21) + uSeed); p += dot(p, p + 45.32); return fract(p.x * p.y); }-float vnoise(vec2 p){+uniform int uKind;+const float PI = 3.14159265;++uint pcg(uint v){ uint s = v * 747796405u + 2891336453u; uint w = ((s >> ((s >> 28u) + 4u)) ^ s) * 277803737u; return (w >> 22u) ^ w; }+float hash(vec2 c, float salt){+ ivec2 i = ivec2(floor(c));+ return float(pcg(uint(i.x) + pcg(uint(i.y) + pcg(uint(salt) + uint(uSeed * 7919.0))))) * (1.0 / 4294967296.0);+}+vec2 hash2(vec2 c, float salt){ return vec2(hash(c, salt), hash(c, salt + 1.0)); }+float vnoise(vec2 p, float salt){vec2 i = floor(p), f = fract(p); f = f * f * (3.0 - 2.0 * f);- return mix(mix(hash(i), hash(i + vec2(1.0, 0.0)), f.x), mix(hash(i + vec2(0.0, 1.0)), hash(i + vec2(1.0, 1.0)), f.x), f.y);+ return mix(mix(hash(i, salt), hash(i + vec2(1.0, 0.0), salt), f.x),+ mix(hash(i + vec2(0.0, 1.0), salt), hash(i + vec2(1.0, 1.0), salt), f.x), f.y);+}+// normalised to 0..1; each octave rotated so the lattice never shows+float fbm(vec2 p, int oct, float salt){+ float v = 0.0, a = 0.5, n = 0.0;+ for (int i = 0; i < 6; i++){+ if (i >= oct) break;+ v += a * vnoise(p, salt + float(i) * 13.0); n += a;+ p = mat2(0.8, -0.6, 0.6, 0.8) * p * 2.03 + 17.1; a *= 0.5;+ }+ return v / n;+}+// distances to the nearest and second-nearest of a jittered lattice of points+vec2 cells(vec2 p, float jitter, float salt){+ vec2 i = floor(p), f = fract(p);+ float d1 = 9.0, d2 = 9.0;+ for (int y = -1; y <= 1; y++) for (int x = -1; x <= 1; x++){+ vec2 c = vec2(x, y);+ float d = length(c + 0.5 + (hash2(i + c, salt) - 0.5) * jitter - f);+ if (d < d1){ d2 = d1; d1 = d; } else if (d < d2) d2 = d;+ }+ return vec2(d1, d2);+}+// Rounded hills of random size and height scattered on a jittered grid; never polygonal+// like cells, because neighbouring hills simply add up. Roughly 0..1.+float blobs(vec2 p, float salt){+ vec2 i = floor(p), f = fract(p);+ float h = 0.0;+ for (int y = -1; y <= 1; y++) for (int x = -1; x <= 1; x++){+ vec2 c = vec2(x, y);+ vec4 r = vec4(hash2(i + c, salt), hash2(i + c, salt + 2.0));+ vec2 d = c + r.xy - f;+ float rad = 0.35 + 0.4 * r.z;+ h += (0.5 + 0.5 * r.w) * exp(-dot(d, d) / (rad * rad));+ }+ return h * 0.75;+}+float segment(vec2 p, vec2 a, vec2 b){+ vec2 pa = p - a, ba = b - a;+ return length(pa - ba * clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0));+}+// Thin strands scattered over a grid of 'cell' units, up to 'len' cells long and 'width'+// units wide; returns the coverage of the nearest. 'along' lines them up with x, the+// way a paper machine lays its fibres; 'density' is the share of grid slots that hold one.+float fibres(vec2 p, float cell, float len, float width, float density, float along, float salt){+ p /= cell;+ vec2 i = floor(p);+ float cov = 0.0;+ for (int y = -2; y <= 2; y++) for (int x = -2; x <= 2; x++){+ vec2 c = i + vec2(x, y);+ for (int k = 0; k < 2; k++){+ float s = salt + float(k) * 31.0;+ vec4 h = vec4(hash2(c, s), hash2(c, s + 2.0));+ if (h.w < density){+ float a = (h.z - 0.5) * PI * (1.0 - along);+ vec2 d = vec2(cos(a), sin(a)) * len * (0.35 + 0.65 * hash(c, s + 4.0)) * 0.5;+ float dist = segment(p, c + h.xy - d, c + h.xy + d) * cell;+ cov = max(cov, (1.0 - smoothstep(width * 0.5, width * 0.5 + 0.9, dist)) * (0.55 + 0.45 * hash(c, s + 5.0)));+ }+ }+ }+ return cov;+}+// small round specks: coverage of the nearest, 'density' of grid slots hold one+float specks(vec2 p, float cell, float radius, float density, float salt){+ vec2 i = floor(p / cell), f = p / cell - i;+ float cov = 0.0;+ for (int y = -1; y <= 1; y++) for (int x = -1; x <= 1; x++){+ vec2 c = vec2(x, y);+ if (hash(i + c, salt + 2.0) < density){+ float r = radius * (0.4 + 0.6 * hash(i + c, salt + 3.0));+ float d = length(c + hash2(i + c, salt) - f) * cell;+ cov = max(cov, 1.0 - smoothstep(r * 0.6, r + 0.6, d));+ }+ }+ return cov;+}+// distance to the nearest centre of a hexagonal lattice with spacing 1+float hexDist(vec2 p){+ const vec2 s = vec2(1.0, 1.7320508);+ vec2 a = mod(p, s) - s * 0.5, b = mod(p - s * 0.5, s) - s * 0.5;+ return min(length(a), length(b));+}+vec2 warp(vec2 p, float freq, float amount, float salt){+ return p + (vec2(fbm(p * freq, 3, salt), fbm(p * freq, 3, salt + 50.0)) - 0.5) * amount;+}++// Cold press: rounded, irregular bumps of mixed size (~0.5-2 mm) over a fine felt.+vec3 coldPress(vec2 p){+ vec2 q = warp(p, 0.02, 10.0, 100.0);+ float hills = blobs(q / 11.0, 110.0) * 0.6 + blobs(q / 5.5, 115.0) * 0.4;+ float h = hills * 0.5 + fbm(q * 0.09, 5, 120.0) * 0.38 + vnoise(p * 0.5, 130.0) * 0.12;+ return vec3(0.5 + (h - 0.5) * 1.3, fbm(p * 0.012, 4, 140.0), 0.5);+}+// Hot press: pressed nearly flat; only a faint felt and the fibres show.+vec3 hotPress(vec2 p){+ float h = fbm(p * 0.06, 4, 200.0) * 0.6 + vnoise(p * 0.4, 210.0) * 0.25 + fibres(p, 16.0, 2.5, 0.8, 0.3, 0.0, 220.0) * 0.05;+ return vec3(0.5 + (h - 0.4) * 0.45, fbm(p * 0.01, 4, 230.0), 0.5);+}+// Rough: big knobbly hills (~2-4 mm) with deep valleys between them.+vec3 rough(vec2 p){+ vec2 q = warp(p, 0.01, 40.0, 300.0);+ // hill size varies across the sheet, as on a mould-made rough+ float big = smoothstep(0.3, 0.7, fbm(p * 0.006, 3, 305.0));+ float hills = blobs(q / 26.0, 310.0) * (0.35 + 0.4 * big) + blobs(q / 12.0, 315.0) * (0.45 - 0.25 * big);+ float h = hills * 0.65 + fbm(q * 0.06, 5, 320.0) * 0.25 + vnoise(p * 0.45, 325.0) * 0.1;+ return vec3(0.5 + (h - 0.52) * 1.5, fbm(p * 0.01, 4, 330.0), 0.5);+}+// Khadi: handmade, lumpy at every scale, with raised fibres and dark inclusions.+vec3 khadi(vec2 p){+ vec2 q = warp(p, 0.008, 60.0, 400.0);+ float lumps = fbm(q * 0.035, 5, 410.0);+ vec2 c = cells(q / 13.0, 1.0, 420.0);+ float knobs = 1.0 - smoothstep(0.0, 0.9, c.x);+ float fib = fibres(warp(p, 0.05, 8.0, 430.0), 9.0, 3.0, 1.1, 0.6, 0.0, 440.0);+ float h = lumps * 0.5 + knobs * 0.3 + fbm(p * 0.2, 3, 450.0) * 0.16 + fib * 0.03;+ float dark = max(specks(p, 60.0, 2.0, 0.3, 460.0), fibres(warp(p, 0.06, 10.0, 465.0), 110.0, 0.4, 0.9, 0.3, 0.0, 470.0) * 0.6);+ return vec3(0.5 + (h - 0.5) * 1.6, fbm(p * 0.006, 4, 480.0) * 0.7 + fib * 0.25, 0.5 - dark * 0.35 + fib * 0.06);+}+// Washi: smooth and cloudy, a web of long kozo fibres lying on top, the odd bark speck.+vec3 washi(vec2 p){+ vec2 q = warp(p, 0.025, 28.0, 500.0);+ float longF = fibres(q, 42.0, 3.4, 1.3, 0.4, 0.0, 510.0) * (0.6 + 0.4 * vnoise(p * 0.05, 512.0));+ float fineF = fibres(warp(p, 0.05, 10.0, 515.0), 14.0, 3.0, 0.6, 0.45, 0.0, 520.0);+ float h = fbm(p * 0.05, 4, 530.0) * 0.8 + longF * 0.08 + fineF * 0.03;+ float cloud = fbm(p * 0.005, 5, 540.0);+ float bark = specks(p, 70.0, 1.6, 0.18, 550.0);+ return vec3(0.5 + (h - 0.42) * 0.7, cloud * 0.85 + longF * 0.15, 0.5 + longF * 0.16 + fineF * 0.05 - bark * 0.4);+}+// Laid: close laid lines (~1 mm) crossed by chain lines (~25 mm), over a soft felt.+vec3 laid(vec2 p){+ float wob = (fbm(p * vec2(0.004, 0.02), 3, 600.0) - 0.5) * 6.0;+ float lines = pow(0.5 + 0.5 * cos(2.0 * PI * (p.y + wob) / 5.6), 2.0);+ float cx = p.x + (fbm(p * vec2(0.02, 0.004), 3, 610.0) - 0.5) * 8.0;+ float dc = abs(fract(cx / 140.0) - 0.5) * 140.0; // distance to the nearest chain line+ float chain = 1.0 - smoothstep(1.0, 3.5, dc);+ float h = lines * 0.1 + chain * 0.05 + fbm(p * 0.08, 4, 620.0) * 0.6;+ // the sheet runs a touch thicker beside each chain line, and the laid lines read faintly in the tone+ float tone = 0.5 - 0.12 * exp(-dc / 12.0) - 0.06 * lines + (fbm(p * 0.01, 3, 630.0) - 0.5) * 0.6;+ return vec3(0.5 + (h - 0.36) * 1.1, tone, 0.5);+}+// Canvas: a plain weave of slightly uneven threads under a coat of gesso.+vec3 canvas(vec2 p){+ const float T = 8.0;+ p += (vec2(vnoise(p * 0.02, 700.0), vnoise(p * 0.02, 701.0)) - 0.5) * T * 1.2;+ vec2 c = p / T, i = floor(c), f = fract(c);+ float tx = 0.8 + 0.2 * hash(vec2(i.x, 0.0), 702.0) + 0.3 * (vnoise(vec2(i.x * 5.0, c.y * 0.35), 703.0) - 0.5);+ float ty = 0.8 + 0.2 * hash(vec2(0.0, i.y), 704.0) + 0.3 * (vnoise(vec2(c.x * 0.35, i.y * 5.0), 705.0) - 0.5);+ // where a thread crosses over, it shows as a rice-grain bump along its length;+ // over and under alternate, so the grains make a checkerboard+ vec2 d = f - 0.5;+ bool warpUp = mod(i.x + i.y, 2.0) > 0.5;+ d *= warpUp ? vec2(2.3, 1.15) : vec2(1.15, 2.3);+ float grain = max(0.0, 1.0 - dot(d, d)) * (warpUp ? tx : ty);+ float h = sqrt(grain) * 0.75 + fbm(p * 0.15, 3, 706.0) * 0.25;+ return vec3(0.5 + (h - 0.55) * 1.1, fbm(p * 0.01, 3, 707.0), 0.5);+}+// Toned (Mi-Teintes honeycomb): a regular mesh of shallow pits ~1.5 mm across.+vec3 toned(vec2 p){+ vec2 q = warp(p, 0.05, 7.0, 800.0) / 9.0;+ float d = hexDist(q) * (0.8 + 0.4 * vnoise(q * 2.0, 805.0));+ float rims = smoothstep(0.1, 0.55, d);+ float h = rims * 0.28 + fbm(p * 0.09, 4, 810.0) * 0.6 + fibres(p, 12.0, 2.0, 0.9, 0.35, 0.0, 820.0) * 0.04;+ return vec3(0.5 + (h - 0.42) * 1.2, fbm(p * 0.012, 4, 830.0), 0.5 - specks(p, 60.0, 1.2, 0.2, 840.0) * 0.3);}-float fbm(vec2 p){ float v = 0.0, a = 0.5; for (int i = 0; i < 5; i++){ v += a * vnoise(p); p = p * 2.03 + 17.1; a *= 0.5; } return v; }-// texel-scale features; scaled so the grain looks the same at any document size-float height(vec2 px){- float s = 1100.0 / uRes.y;- return fbm(px * 0.11 * s) * 0.7 + vnoise(px * 0.45 * s) * 0.3;+// Kraft: smooth, streaky along the machine direction, with dark bark and recycled flecks.+vec3 kraft(vec2 p){+ float h = fbm(p * 0.07, 4, 900.0) * 0.6 + vnoise(p * 0.35, 910.0) * 0.32 + fibres(p, 10.0, 2.5, 0.9, 0.6, 0.7, 920.0) * 0.04;+ float streak = fbm(p * vec2(0.004, 0.03), 5, 930.0);+ float dark = max(fibres(warp(p, 0.08, 10.0, 935.0), 60.0, 0.35, 0.7, 0.2, 0.6, 940.0) * 0.6, specks(p, 40.0, 1.3, 0.35, 950.0));+ float light = fibres(warp(p, 0.08, 10.0, 955.0), 70.0, 0.4, 1.0, 0.25, 0.5, 960.0);+ return vec3(0.5 + (h - 0.45) * 0.7, streak * 0.8 + fbm(p * 0.01, 3, 970.0) * 0.2, 0.5 - dark * 0.28 + light * 0.12);}+// Student (cellulose): a felt-pressed texture of small bumps all of one size, evenly spread.+vec3 student(vec2 p){+ vec2 q = warp(p, 0.03, 3.0, 995.0);+ vec2 c = cells(q / 7.0, 0.7, 1000.0);+ float bumps = 1.0 - smoothstep(0.0, 0.7, c.x);+ float h = bumps * 0.6 + fbm(p * 0.12, 3, 1010.0) * 0.4;+ return vec3(0.5 + (h - 0.48) * 1.1, fbm(p * 0.015, 3, 1020.0), 0.5);+}++void main(){+ vec2 p = (vUv * uRes + uOffset) * uScale;+ vec3 f;+ switch (uKind){+ case 1: f = hotPress(p); break;+ case 2: f = rough(p); break;+ case 3: f = khadi(p); break;+ case 4: f = washi(p); break;+ case 5: f = laid(p); break;+ case 6: f = canvas(p); break;+ case 7: f = toned(p); break;+ case 8: f = kraft(p); break;+ case 9: f = student(p); break;+ default: f = coldPress(p);+ }+ o = vec4(clamp(f, 0.0, 1.0), 1.0);+}`;++// Light the field's height from the upper left. Packs the paper texture:+// r = lit relief (0.5 flat), g = height, b = mottle, a = fleck.+export const paperLightFS = `${HEADER}+out vec4 o;+uniform sampler2D uField;+uniform vec2 uTexel;+uniform float uBump; // relief strength, already divided by units per texelvoid main(){- vec2 px = vUv * uRes;- float h = height(px);- float hx = height(px + vec2(1.0, 0.0)), hy = height(px + vec2(0.0, 1.0));- vec3 n = normalize(vec3((h - hx) * 2.2, (h - hy) * 2.2, 1.0));- float lit = clamp(0.88 + 0.5 * dot(n, normalize(vec3(-0.5, 0.6, 0.62))) - 0.38, 0.0, 1.0);- float fibre = fbm(px * 0.012 * 1100.0 / uRes.y + 5.3);- o = vec4(lit, h, fibre, 1.0);+ vec4 f = texture(uField, vUv);+ float l = texture(uField, vUv - vec2(uTexel.x, 0.0)).x, r = texture(uField, vUv + vec2(uTexel.x, 0.0)).x;+ float b = texture(uField, vUv - vec2(0.0, uTexel.y)).x, t = texture(uField, vUv + vec2(0.0, uTexel.y)).x;+ vec3 n = normalize(vec3((l - r) * uBump, (b - t) * uBump, 1.0));+ vec3 L = normalize(vec3(-0.5, 0.6, 0.62));+ // a little ambient occlusion: valleys sit in shadow whichever way the light falls+ float lit = 0.5 + (dot(n, L) - L.z) * 1.3 + (f.x - 0.5) * 0.25;+ o = vec4(clamp(lit, 0.0, 1.0), f.x, f.y, f.z);+}`;++/** The sheet's colour (linear) from a paper texel; shared by the display and the swatches. */+const PAPER_COLOUR = `+uniform vec3 uPaperTint, uFleckTint;+uniform float uMottle;+uniform float uTexture; // texture strength: 0 a flat sheet of the tint, 1 full relief+vec3 paperColour(vec4 paper, vec3 base){+ vec3 c = base * (1.0 + uTexture * ((paper.r - 0.5) * 0.32 + (paper.b - 0.5) * uMottle * 2.0));+ float fl = (paper.a - 0.5) * 2.0 * uTexture;+ return fl < 0.0 ? mix(c, uFleckTint, -fl) : mix(c, min(base * 1.1 + 0.02, vec3(1.0)), fl);+}`;++const TO_SRGB = `+vec3 toSRGB(vec3 c){+ c = clamp(c, 0.0, 1.0);+ return mix(c * 12.92, 1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, step(0.0031308, c));+}`;++/** A paper preview: the sheet with a granulating ultramarine wash across one corner. */+export const paperSwatchFS = `${HEADER}+out vec4 o;+uniform sampler2D uPaper;+${PAPER_COLOUR}+${TO_SRGB}+void main(){+ vec4 paper = texture(uPaper, vUv);+ vec3 c = paperColour(paper, uPaperTint);+ float x = vUv.x * 0.62 + (1.0 - vUv.y) * 0.38 + (paper.g - 0.5) * 0.03;+ float wash = smoothstep(0.6, 0.605, x);+ float gran = 1.0 + (0.5 - paper.g) * 2.4;+ float tide = 1.0 + 0.5 * exp(-(x - 0.6) * 90.0) * wash;+ c *= mix(vec3(1.0), pow(vec3(0.3, 0.38, 0.72), vec3(gran * tide)), wash);+ o = vec4(toSRGB(c), 1.0);}`;// Paint-bucket wash. uField holds, per document texel, the distance travelled from the@@ -315,16 +582,35 @@ uniform int uMode; // 0 screen, 1 export on paper, 2 export transparent,uniform sampler2D uRef; // reference image (screen only), sRGB, y upuniform vec4 uRefRect; // its placement in document uv: xy origin, zw sizeuniform float uRefOpacity;+uniform float uShadow; // screen only: size of the sheet's shadow on the desk (canvas px), 0 for exports+uniform float uDpr;+${PAPER_COLOUR}+${TO_SRGB}+float density(vec2 uv){ return texture(uInkA, uv).x + texture(uFixedA, uv).x; }-vec3 toSRGB(vec3 c){- c = clamp(c, 0.0, 1.0);- return mix(c * 12.92, 1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, step(0.0031308, c));+// Signed distance (canvas px) from p to the sheet, moved down by \`drop\`.+float sheetDist(vec2 p, float drop){+ vec2 q = abs(p - uView.xy - uView.zw * 0.5 + vec2(0.0, drop)) - uView.zw * 0.5;+ return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0);+}++// The sheet lying on the desk: a tight contact shadow at its edge and a soft one+// cast a little downward, as from a light above and in front.+vec3 desk(vec2 p){+ float R = uShadow;+ float contact = 1.0 - smoothstep(0.0, 0.12 * R, sheetDist(p, 0.03 * R));+ float d = max(sheetDist(p, 0.3 * R), 0.0) / R;+ float ambient = exp(-3.0 * d * d) * 0.75 + exp(-0.9 * d) * 0.25; // a soft core with a long, faint tail+ vec3 lin = pow(uDesk, vec3(2.2)) * (1.0 - 0.45 * contact) * (1.0 - 0.32 * ambient);+ return toSRGB(lin);}-float density(vec2 uv){ return texture(uInkA, uv).x + texture(uFixedA, uv).x; }void main(){vec2 uv = (gl_FragCoord.xy - uView.xy) / uView.zw;- if (uv.x < 0.0 || uv.y < 0.0 || uv.x > 1.0 || uv.y > 1.0){ o = vec4(uDesk, 1.0); return; }+ if (uv.x < 0.0 || uv.y < 0.0 || uv.x > 1.0 || uv.y > 1.0){+ o = vec4(uShadow > 0.0 ? desk(gl_FragCoord.xy) : uDesk, 1.0);+ return;+ }vec4 paper = mix(texture(uPaper, uv), vec4(0.5), uFlat);vec4 iB = texture(uInkB, uv);@@ -348,7 +634,7 @@ ${displayBasisGLSL()}// White gouache sits on top as an opaque layer, a little patchy on the tooth.float cov = 1.0 - exp(-2.2 * iB.a);cov = clamp(cov * (1.0 + (paper.g - 0.5) * 0.5), 0.0, 1.0);- vec3 gouache = vec3(0.96, 0.955, 0.94) * (0.96 + 0.05 * paper.r);+ vec3 gouache = vec3(0.96, 0.955, 0.94) * (1.0 + 0.1 * (paper.r - 0.5) * uTexture);if (uMode == 2){// Transparent: the pigment's transmittance over white, unmixed into colour + alpha@@ -363,9 +649,8 @@ ${displayBasisGLSL()}return;}- // Paper: warm white, lit relief, faint fibre mottling (linear light).- vec3 paperCol = uMode == 3 ? vec3(1.0)- : vec3(0.925, 0.905, 0.855) * (0.93 + 0.1 * paper.r) * (0.985 + 0.03 * paper.b);+ // Paper: the sheet's tint, lit relief, fibre mottling and flecks (linear light).+ vec3 paperCol = paperColour(paper, uMode == 3 ? vec3(1.0) : uPaperTint);// On screen, a reference image shows through the paper, under the paint.if (uMode == 0 && uRefOpacity > 0.0){vec2 ruv = (uv - uRefRect.xy) / uRefRect.zw;@@ -382,5 +667,11 @@ ${displayBasisGLSL()}float ws = uMode == 3 ? 0.0 : smoothstep(0.02, 0.7, texture(uWet, uv).x) * (1.0 - uFlat);col *= vec3(1.0) - ws * vec3(0.12, 0.11, 0.08);+ // On screen, the cut edge of the sheet catches a faint shade, so it reads as a thin card.+ if (uShadow > 0.0){+ float inside = -sheetDist(gl_FragCoord.xy, 0.0);+ col *= mix(0.9, 1.0, smoothstep(0.0, 1.5 * uDpr, inside));+ }+o = vec4(toSRGB(col), 1.0);}`;diff --git a/src/export/ExportPanel.tsx b/src/export/ExportPanel.tsxindex 0220ebc..a6d42be 100644--- a/src/export/ExportPanel.tsx+++ b/src/export/ExportPanel.tsx@@ -1,4 +1,7 @@+import { useEffect, useRef } from 'preact/hooks';import { useApp } from '../app/context';+import { PROJECT_EXT } from '../project/format';+import { Icon } from '../ui/Icon';import { Panel, PanelHead } from '../ui/Panel';import { Seg } from '../ui/Seg';import { Slider } from '../ui/Slider';@@ -8,16 +11,43 @@ export function ExportPanel() {const app = useApp();const ex = app.exporter;const s = ex.settings.value;+ const [w, h] = app.docSize.value;+ const project = app.project;+ const busy = project.busy.value;+ const file = useRef<HTMLInputElement>(null);+ // ⌘O asks for the picker; the input lives here+ const request = project.openRequest.value;+ useEffect(() => { if (request) file.current?.click(); }, [request]);return (<Panel class="popover export" open={app.popover.value === 'save'} role="dialog" label="Save image">- <PanelHead title="Save image" sub="The reference image is never included." />+ <PanelHead title="Save image" sub={`${w} × ${h} px, the size of the sheet. The reference image is never included.`} /><div class="field"><span>Background</span><Seg value={s.background} onChange={background => ex.set({ background })}options={BACKGROUNDS.map(b => ({ ...b, disabled: b.id === 'transparent' && s.format === 'jpeg' }))} /></div>+ <div class="field"><span>Paper texture</span>+ <Seg value={s.texture} onChange={texture => ex.set({ texture })} title={`Relief and fibres of the ${app.paper.value.name} paper`}+ options={[{ id: true, label: 'Textured', disabled: s.background === 'transparent' }, { id: false, label: 'Flat', disabled: s.background === 'transparent' }]} />+ </div><div class="field"><span>Format</span><Seg options={FORMATS} value={s.format} onChange={format => ex.set({ format })} /></div><Slider label="Quality" min={0.5} max={1} value={s.quality} hidden={s.format === 'png'} onInput={quality => ex.set({ quality })} /><button class="primary" onClick={() => void ex.save()}>Download</button>+ <div class="field project"><span>Project</span>+ <div class="project-buttons">+ <button class="primary" disabled={busy !== null} onClick={() => void project.save()}>+ {busy === 'saving' ? 'Saving…' : `Save project (.${PROJECT_EXT})`}+ </button>+ <button class="import" disabled={busy !== null} onClick={() => file.current?.click()}>+ <Icon name="folder" size={16} /><span>{busy === 'opening' ? 'Opening…' : 'Open project…'}</span>+ </button>+ </div>+ <p class="note">A project file keeps the wet paint, paper and reference so you can carry on later (⌘S / ⌘O). Undo history is not saved.</p>+ </div>+ <input ref={file} type="file" accept={`.${PROJECT_EXT}`} hidden onChange={e => {+ const el = e.currentTarget as HTMLInputElement, f = el.files?.[0];+ el.value = '';+ if (f) void project.open(f);+ }} /></Panel>);}diff --git a/src/export/ExportStore.ts b/src/export/ExportStore.tsindex 6f82355..fc8a0d5 100644--- a/src/export/ExportStore.ts+++ b/src/export/ExportStore.ts@@ -1,12 +1,13 @@import type { ExportBackground, ExportFormat, WatercolorEngine } from '../engine/Engine';import { persisted } from '../app/persisted';import { showToast } from '../app/toast';+import { downloadBlob, stampedName } from './download';const KEY = 'watercolor.export';-export interface ExportSettings { format: ExportFormat; background: ExportBackground; quality: number }+export interface ExportSettings { format: ExportFormat; background: ExportBackground; quality: number; texture: boolean }-const DEFAULTS: ExportSettings = { format: 'png', background: 'transparent', quality: 0.92 };+const DEFAULTS: ExportSettings = { format: 'png', background: 'transparent', quality: 0.92, texture: true };export const FORMATS: { id: ExportFormat; label: string; ext: string }[] = [{ id: 'png', label: 'PNG', ext: 'png' },{ id: 'jpeg', label: 'JPEG', ext: 'jpg' },@@ -14,7 +15,7 @@ export const FORMATS: { id: ExportFormat; label: string; ext: string }[] = [];export const BACKGROUNDS: { id: ExportBackground; label: string; title: string }[] = [{ id: 'transparent', label: 'Transparent', title: 'Transparent: only the paint, no paper' },- { id: 'paper', label: 'Paper', title: 'On the textured watercolour paper' },+ { id: 'paper', label: 'Paper', title: 'On the chosen paper' },{ id: 'white', label: 'White', title: 'On plain white' },];@@ -22,7 +23,8 @@ export const BACKGROUNDS: { id: ExportBackground; label: string; title: string }export class ExportStore {readonly settings = persisted<ExportSettings>(KEY, DEFAULTS);- constructor(private engine: WatercolorEngine) {}+ /** `paperName` names the current sheet in the confirmation. */+ constructor(private engine: WatercolorEngine, private paperName: () => string) {}set(p: Partial<ExportSettings>) {const s = { ...this.settings.value, ...p };@@ -33,16 +35,12 @@ export class ExportStore {/** Save straight away with the current settings. */async save() {- const { format, background, quality } = this.settings.peek();+ const { format, background, quality, texture } = this.settings.peek();try {- const blob = await this.engine.exportImage({ format, background, quality: format === 'png' ? undefined : quality });- const ext = FORMATS.find(f => f.id === format)!.ext;- const a = document.createElement('a');- a.href = URL.createObjectURL(blob);- a.download = `watercolor-${new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19)}.${ext}`;- a.click();- setTimeout(() => URL.revokeObjectURL(a.href), 4000);- const bg = background === 'transparent' ? 'transparent' : `on ${background}`;+ const blob = await this.engine.exportImage({ format, background, quality: format === 'png' ? undefined : quality, texture });+ downloadBlob(blob, stampedName(FORMATS.find(f => f.id === format)!.ext));+ const bg = background === 'transparent' ? 'transparent'+ : `on ${texture ? '' : 'flat '}${background === 'paper' ? this.paperName() : 'white'}`;showToast(`Saved ${FORMATS.find(f => f.id === format)!.label} · ${bg}`);} catch (e) {showToast(e instanceof Error ? e.message : 'Could not save the image');diff --git a/src/export/download.ts b/src/export/download.tsnew file mode 100644index 0000000..5d5eaa9--- /dev/null+++ b/src/export/download.ts@@ -0,0 +1,17 @@+/** Hand `blob` to the browser as a download named `name`. */+export function downloadBlob(blob: Blob, name: string) {+ const a = document.createElement('a');+ a.href = URL.createObjectURL(blob);+ a.download = name;+ a.click();+ setTimeout(() => URL.revokeObjectURL(a.href), 4000);+}++/** `watercolor-<date-time>.<ext>` */+export const stampedName = (ext: string) => `watercolor-${new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19)}.${ext}`;++export function formatBytes(n: number) {+ if (n < 1024) return `${n} B`;+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(0)} KB`;+ return `${(n / 1024 / 1024).toFixed(1)} MB`;+}diff --git a/src/fill/FillPanel.tsx b/src/fill/FillPanel.tsxindex d257e8c..17f961a 100644--- a/src/fill/FillPanel.tsx+++ b/src/fill/FillPanel.tsx@@ -12,17 +12,24 @@ const SLIDERS: SliderSpec<FillSettings>[] = [{ key: 'soft', label: 'Soft edge', hint: 'Feather the wash at the edge of the area' },];+const SOURCES: { id: boolean; label: string; title: string }[] = [+ { id: false, label: 'Paint', title: 'Areas end where the paint changes colour' },+ { id: true, label: 'Reference', title: 'Areas end at the lines of the reference image, like tracing it' },+];+const MODES: { id: FillSettings['mode']; label: string }[] = [{ id: 'paint', label: 'Paint' }, { id: 'water', label: 'Water' }];export function FillPanel({ tool }: { tool: FillStore }) {const app = useApp();const s = tool.settings.value;+ const ref = app.reference;return (<ToolPanel title="Fill" class="fill" open={tool.active.value} status={tool.status.value} busy={tool.progress.value !== null}sub="Tap an area of the paper; a wash of the current pigment spreads out from the tap until it meets a different colour."onStop={() => tool.stop()} onClose={() => app.setTool('brush')}><div class="tool-rows"><Row label="Fill with"><Seg options={MODES} value={s.mode} onChange={mode => tool.set({ mode })} /></Row>+ {ref.has.value && <Row label="Areas from"><Seg options={SOURCES} value={ref.forFill.value} onChange={on => ref.useForFill(on)} /></Row>}<SliderRows spec={SLIDERS} settings={s} onChange={p => tool.set(p)} /></div></ToolPanel>diff --git a/src/fill/FillStore.ts b/src/fill/FillStore.tsindex f258cb0..51da7ae 100644--- a/src/fill/FillStore.ts+++ b/src/fill/FillStore.ts@@ -64,13 +64,14 @@ export class FillStore implements PanelTool {this.picking.value = false;if (!this.active.peek()) return;const s = this.settings.peek();- const flat = engine.readFlat();+ // with a tracing reference, the areas come from its lines rather than from the paint+ const flat = (engine.referenceForFill && engine.readReferenceFlat()) || engine.readFlat();const tol = Math.round(s.tolerance * s.tolerance * 255); // 0.25 -> 16 of 255 per channelconst mask = pickRegion({ width: dw, height: dh, data: new Uint8ClampedArray(flat.buffer) }, px, py, tol);if (!mask) { showToast('Nothing to fill here'); return; }const region = distanceField(mask, dw, dh, px, py, EDGE_CAP);if (region.count < 4) { showToast('That area is too small to fill'); return; }- if (!engine.fillBegin(region.field, region.bbox)) { showToast('Wait for the stroke to finish'); return; }+ if (!engine.fillBegin(region.field, region.bbox, s.mode === 'water' ? 'Water fill' : 'Fill')) { showToast('Wait for the stroke to finish'); return; }this.run = { raf: 0, from: -0.5, maxDist: region.maxDist + engine.fillMargin, last: performance.now() };this.run.raf = requestAnimationFrame(this.frame);this.progress.value = 0;diff --git a/src/project/ProjectStore.ts b/src/project/ProjectStore.tsnew file mode 100644index 0000000..f8a86b6--- /dev/null+++ b/src/project/ProjectStore.ts@@ -0,0 +1,88 @@+import { signal } from '@preact/signals';+import type { AppStore } from '../app/store';+import { showToast } from '../app/toast';+import { downloadBlob, formatBytes, stampedName } from '../export/download';+import { storedTip } from '../ui/customBrushes';+import { FORMAT_VERSION, PROJECT_EXT, readProject, writeProject, type ProjectData } from './format';++const THUMB = 320;++const toBlob = (c: HTMLCanvasElement, type = 'image/png') =>+ new Promise<Blob>((resolve, reject) => c.toBlob(b => (b ? resolve(b) : reject(new Error('could not encode image'))), type));++/** Saving and opening whole paintings (.wcp files): paint, paper, reference and tool state. */+export class ProjectStore {+ readonly busy = signal<'saving' | 'opening' | null>(null);+ /** Bumped when a shortcut asks for the file picker (the panel owns the input). */+ readonly openRequest = signal(0);+ /** What the first row of the history list is called. */+ readonly baseline = signal<'Blank sheet' | 'Opened project'>('Blank sheet');++ constructor(private app: AppStore) {}++ requestOpen() { this.openRequest.value++; }++ async save() {+ if (this.busy.peek()) return;+ this.busy.value = 'saving';+ try {+ const { app } = this, { engine } = app;+ const s = engine.snapshot();+ const brush = app.brush.peek();+ const thumbnail = await this.thumbnail().catch(() => null);+ const data: ProjectData = {+ header: {+ app: 'watercolor', version: FORMAT_VERSION, created: new Date().toISOString(),+ doc: { w: s.whole.w, h: s.whole.h, sizePreset: app.paperSize.peek().preset },+ paper: s.paper,+ paint: { rect: s.whole.rect, ...s.wet },+ reference: s.reference.image+ ? { rect: s.reference.rect, opacity: s.reference.opacity, visible: s.reference.visible, forFill: app.reference.forFill.peek() }+ : null,+ tool: { params: app.params.peek(), hex: app.current.peek().hex, brushId: brush.id },+ brushes: brush.custom ? [storedTip(brush)] : [],+ view: s.view,+ blobs: [],+ },+ layers: s.whole.layers,+ reference: s.reference.image ? await toBlob(s.reference.image) : null,+ thumbnail,+ };+ const blob = await writeProject(data);+ downloadBlob(blob, stampedName(PROJECT_EXT));+ showToast(`Saved project · ${formatBytes(blob.size)}`);+ } catch (e) {+ showToast(e instanceof Error ? e.message : 'Could not save the project');+ } finally {+ this.busy.value = null;+ }+ }++ async open(file: File): Promise<boolean> {+ if (this.busy.peek()) return false;+ this.busy.value = 'opening';+ try {+ const data = await readProject(file);+ await this.app.openProject(data);+ this.baseline.value = 'Opened project';+ showToast(`Opened ${file.name}`);+ return true;+ } catch (e) {+ showToast(e instanceof Error ? e.message : 'Could not open that project');+ return false;+ } finally {+ this.busy.value = null;+ }+ }++ private async thumbnail(): Promise<Blob> {+ const full = await this.app.engine.exportImage({ format: 'png', background: 'paper', texture: true });+ const bmp = await createImageBitmap(full);+ const s = Math.min(1, THUMB / Math.max(bmp.width, bmp.height));+ const c = document.createElement('canvas');+ c.width = Math.max(1, Math.round(bmp.width * s)); c.height = Math.max(1, Math.round(bmp.height * s));+ c.getContext('2d')!.drawImage(bmp, 0, 0, c.width, c.height);+ bmp.close();+ return toBlob(c);+ }+}diff --git a/src/project/format.ts b/src/project/format.tsnew file mode 100644index 0000000..ee1f7c1--- /dev/null+++ b/src/project/format.ts@@ -0,0 +1,139 @@+// The .wcp project file: one binary with a JSON header and compressed layer blobs.+//+// 0 8 magic "WCPROJ\0\0"+// 8 4 u32 format version+// 12 4 u32 header length+// 16 n header JSON (UTF-8)+// then, per blob in header.blobs order: u32 stored length, u32 raw length, payload+//+// Everything little-endian. Layers are half floats (see Engine.WholeDoc), deflated with+// the browser's CompressionStream when it has one; images are PNG as they are.++import type { LayerId, Params, RefRect } from '../engine/Engine';+import type { Rect } from '../engine/gl';+import type { Stored } from '../ui/customBrushes';++export const PROJECT_EXT = 'wcp';+export const FORMAT_VERSION = 1;+const MAGIC = [0x57, 0x43, 0x50, 0x52, 0x4f, 0x4a, 0x00, 0x00]; // "WCPROJ\0\0"+const LAYERS: LayerId[] = ['inkA', 'inkB', 'fixedA', 'fixedB', 'wet'];+const CHANNELS: Record<LayerId, 1 | 4> = { inkA: 4, inkB: 4, fixedA: 4, fixedB: 4, wet: 1 };++export const isProjectFile = (f: File) => new RegExp(`\\.${PROJECT_EXT}$`, 'i').test(f.name);++type Codec = 'deflate-raw' | 'none';+export interface BlobEntry { id: LayerId | 'ref' | 'thumb'; codec: Codec; dtype: 'f16' | 'png'; channels?: 1 | 4; w?: number; h?: number }++export interface ProjectHeader {+ app: 'watercolor';+ version: number;+ created: string;+ doc: { w: number; h: number; sizePreset: string };+ paper: { id: string; seed: number; origin: [number, number]; scale: number; strength: number };+ paint: { rect: Rect | null; wetAgo: number; wetPeak: number; active: Rect | null; painted: Rect | null };+ reference: null | { rect: RefRect; opacity: number; visible: boolean; forFill: boolean };+ tool: { params: Params; hex: string; brushId: string };+ /** Custom brush tips the painting needs (the current one, if custom). */+ brushes: Stored[];+ view: { zoom: number; pan: [number, number]; fitted: boolean } | null;+ blobs: BlobEntry[];+}++export interface ProjectData {+ header: ProjectHeader;+ layers: Record<LayerId, Uint16Array>;+ reference: Blob | null;+ thumbnail: Blob | null;+}++const hasCompression = typeof CompressionStream === 'function' && typeof DecompressionStream === 'function';++const u32 = (n: number) => { const b = new Uint8Array(4); new DataView(b.buffer).setUint32(0, n, true); return b; };++async function deflate(bytes: Uint8Array): Promise<Blob> {+ const stream = new Blob([bytes as BlobPart]).stream().pipeThrough(new CompressionStream('deflate-raw'));+ return new Response(stream).blob();+}++async function inflate(part: Blob, rawLen: number): Promise<Uint8Array> {+ const stream = part.stream().pipeThrough(new DecompressionStream('deflate-raw'));+ const out = new Uint8Array(await new Response(stream).arrayBuffer());+ if (out.length !== rawLen) throw new Error('This project file is damaged.');+ return out;+}++/** Build the file. `header.blobs` is filled in here. */+export async function writeProject(p: ProjectData): Promise<Blob> {+ const blobs: BlobEntry[] = [];+ const parts: BlobPart[] = [];+ const add = async (entry: BlobEntry, raw: Uint8Array | Blob) => {+ const rawLen = raw instanceof Blob ? raw.size : raw.byteLength;+ let stored: Blob;+ if (entry.codec === 'deflate-raw' && hasCompression && raw instanceof Uint8Array) stored = await deflate(raw);+ else { entry.codec = 'none'; stored = raw instanceof Blob ? raw : new Blob([raw as BlobPart]); }+ blobs.push(entry);+ parts.push(u32(stored.size), u32(rawLen), stored);+ };+ const r = p.header.paint.rect;+ const cw = r ? r.x1 - r.x0 : 0, ch = r ? r.y1 - r.y0 : 0;+ for (const id of LAYERS) {+ const data = p.layers[id];+ if (data.length !== cw * ch * CHANNELS[id]) throw new Error(`layer ${id} does not match its rect`);+ await add({ id, codec: 'deflate-raw', dtype: 'f16', channels: CHANNELS[id], w: cw, h: ch },+ new Uint8Array(data.buffer, data.byteOffset, data.byteLength));+ }+ if (p.reference) await add({ id: 'ref', codec: 'none', dtype: 'png' }, p.reference);+ if (p.thumbnail) await add({ id: 'thumb', codec: 'none', dtype: 'png' }, p.thumbnail);+ const header = new TextEncoder().encode(JSON.stringify({ ...p.header, blobs }));+ return new Blob([new Uint8Array(MAGIC), u32(FORMAT_VERSION), u32(header.byteLength), header, ...parts], { type: 'application/octet-stream' });+}++/** Read a file written by `writeProject`. Throws an Error with a message fit for a toast. */+export async function readProject(file: Blob): Promise<ProjectData> {+ const bad = (why = 'This is not a watercolor project file.') => new Error(why);+ if (file.size < 16) throw bad();+ const head = new Uint8Array(await file.slice(0, 16).arrayBuffer());+ if (MAGIC.some((b, i) => head[i] !== b)) throw bad();+ const dv = new DataView(head.buffer);+ const version = dv.getUint32(8, true), headerLen = dv.getUint32(12, true);+ if (version > FORMAT_VERSION) throw bad('This project was saved by a newer version of the app.');+ if (16 + headerLen > file.size) throw bad('This project file is damaged.');+ let header: ProjectHeader;+ try { header = JSON.parse(new TextDecoder().decode(await file.slice(16, 16 + headerLen).arrayBuffer())) as ProjectHeader; }+ catch { throw bad('This project file is damaged.'); }+ if (header.app !== 'watercolor' || !Array.isArray(header.blobs) || !header.doc || !header.paper || !header.paint) throw bad('This project file is damaged.');++ const layers = {} as Record<LayerId, Uint16Array>;+ let reference: Blob | null = null, thumbnail: Blob | null = null;+ let pos = 16 + headerLen;+ for (const entry of header.blobs) {+ if (pos + 8 > file.size) throw bad('This project file is damaged.');+ const lens = new DataView(await file.slice(pos, pos + 8).arrayBuffer());+ const storedLen = lens.getUint32(0, true), rawLen = lens.getUint32(4, true);+ pos += 8;+ if (pos + storedLen > file.size) throw bad('This project file is damaged.');+ const part = file.slice(pos, pos + storedLen);+ pos += storedLen;+ if (entry.dtype === 'png') {+ const blob = part.slice(0, part.size, 'image/png');+ if (entry.id === 'ref') reference = blob; else if (entry.id === 'thumb') thumbnail = blob;+ continue;+ }+ if (!LAYERS.includes(entry.id as LayerId)) continue;+ let bytes: Uint8Array;+ if (entry.codec === 'none') bytes = new Uint8Array(await part.arrayBuffer());+ else if (hasCompression) bytes = await inflate(part, rawLen);+ else throw bad('This browser cannot open compressed projects.');+ const id = entry.id as LayerId;+ const expect = (entry.w ?? 0) * (entry.h ?? 0) * CHANNELS[id] * 2;+ if (bytes.byteLength !== rawLen || rawLen !== expect) throw bad('This project file is damaged.');+ layers[id] = new Uint16Array(bytes.buffer, bytes.byteOffset, bytes.byteLength / 2);+ }+ const r = header.paint.rect;+ const cw = r ? r.x1 - r.x0 : 0, ch = r ? r.y1 - r.y0 : 0;+ for (const id of LAYERS) {+ layers[id] ??= new Uint16Array(0);+ if (layers[id].length !== cw * ch * CHANNELS[id]) throw bad('This project file is damaged.');+ }+ return { header, layers, reference, thumbnail };+}diff --git a/src/reference/RefFrame.tsx b/src/reference/RefFrame.tsxindex f52dc4e..314fd1e 100644--- a/src/reference/RefFrame.tsx+++ b/src/reference/RefFrame.tsx@@ -1,6 +1,6 @@import { useEffect, useRef } from 'preact/hooks';import { useApp } from '../app/context';-import { resizeTick } from '../app/resize';+import { resizeTick, viewTick } from '../app/resize';const MIN_PX = 24; // smallest the reference can be scaled to, in CSS px@@ -28,7 +28,7 @@ export function RefFrame() {const gesture = useRef<Gesture | null>(null);const show = ref.adjusting.value && ref.has.value;- resizeTick.value; // re-place the frame after a resize+ resizeTick.value; viewTick.value; // re-place the frame after a resize, zoom or panconst r = ref.rect.value;const [l, t] = engine.docToClient(r.x, r.y + r.h);const [rr, b] = engine.docToClient(r.x + r.w, r.y);@@ -58,6 +58,7 @@ export function RefFrame() {const onDown = (e: PointerEvent) => {e.preventDefault();try { el.current!.setPointerCapture(e.pointerId); } catch { /* pointer already gone */ }+ if (!pointers.current.size) ref.beginGesture();pointers.current.set(e.pointerId, { x: e.clientX, y: e.clientY });beginGesture((e.target as HTMLElement).dataset.corner);};@@ -81,9 +82,12 @@ export function RefFrame() {};const release = (e: PointerEvent) => {if (!pointers.current.delete(e.pointerId)) return;+ const kind = gesture.current?.kind;// a pinch that loses a finger carries on as a move with the one left- if (pointers.current.size) beginGesture(); else gesture.current = null;+ if (pointers.current.size) beginGesture();+ else { gesture.current = null; ref.endGesture(kind === 'move' ? 'Reference moved' : 'Reference scaled'); }};+ const wheelTimer = useRef(0);// wheel must be non-passive to stop the page zooming; attach it by handuseEffect(() => {@@ -93,7 +97,11 @@ export function RefFrame() {e.preventDefault();// trackpad pinches arrive as ctrl+wheel with small deltasconst s = Math.exp(-e.deltaY * (e.ctrlKey ? 0.01 : 0.0015));+ ref.beginGesture();setBox(scaleAbout(box(), s, e.clientX, e.clientY));+ // a burst of wheel events is one scale+ clearTimeout(wheelTimer.current);+ wheelTimer.current = window.setTimeout(() => ref.endGesture('Reference scaled'), 400);};node.addEventListener('wheel', onWheel, { passive: false });return () => node.removeEventListener('wheel', onWheel);diff --git a/src/reference/ReferencePanel.tsx b/src/reference/ReferencePanel.tsxindex b59a64f..d2fd2d2 100644--- a/src/reference/ReferencePanel.tsx+++ b/src/reference/ReferencePanel.tsx@@ -16,13 +16,16 @@ export function ReferencePanel() {<Panel class="popover reference" open={app.popover.value === 'reference'} role="dialog" label="Reference image"><PanelHead title="Reference" sub="Shown under the paint to work from. Never exported." /><button class="import" onClick={() => file.current?.click()}><Icon name="plus" size={16} /><span>{has ? 'Replace image…' : 'Import image…'}</span></button>- <Slider label="Opacity" value={ref.opacity} disabled={!has} onInput={v => ref.setOpacity(v)} />+ <Slider label="Opacity" value={ref.opacity} disabled={!has} onInput={v => ref.setOpacity(v)} onChange={v => ref.setOpacity(v, 'commit')} /><div class="seg">{seg('Show', 'Show or hide the reference (R)', has && ref.visible, () => ref.setVisible(!ref.visible))}{seg('Move', 'Drag to move, drag a corner or pinch to scale', ref.adjusting.value, () => ref.setAdjust(!ref.adjusting.value))}{seg('Fit', 'Fit to the paper', false, () => ref.fit())}{seg('Remove', 'Remove the reference', false, () => ref.remove())}</div>+ <div class="seg">+ {seg('Trace for fill', 'The Fill tool finds its areas on this image instead of on the paint', has && ref.forFill.value, () => ref.useForFill(!ref.forFill.value))}+ </div><input ref={file} type="file" accept={IMAGE_ACCEPT} hidden onChange={e => {const el = e.currentTarget as HTMLInputElement, f = el.files?.[0];el.value = '';diff --git a/src/reference/ReferenceStore.ts b/src/reference/ReferenceStore.tsindex b6439a2..26a644d 100644--- a/src/reference/ReferenceStore.ts+++ b/src/reference/ReferenceStore.ts@@ -1,5 +1,5 @@import { effect, signal } from '@preact/signals';-import type { RefRect, WatercolorEngine } from '../engine/Engine';+import type { DocState, RefRect, WatercolorEngine } from '../engine/Engine';import { persisted } from '../app/persisted';import { showToast } from '../app/toast';import { decodeImage } from './decode';@@ -19,6 +19,12 @@ export class ReferenceStore {readonly adjusting = signal(false);/** Mirror of the engine's placement (document uv), so the frame can follow it. */readonly rect = signal<RefRect>({ x: 0, y: 0, w: 1, h: 1 });+ /** Does the Fill tool trace this image (find its areas on it) instead of on the paint? */+ readonly forFill = signal(false);+ /** Just imported: ask whether fills should trace it. */+ readonly askFill = signal(false);+ /** Document state when the current move / scale / opacity gesture began. */+ private before: DocState | null = null;constructor(readonly engine: WatercolorEngine) {effect(() => {@@ -27,15 +33,51 @@ export class ReferenceStore {engine.referenceVisible = visible;});effect(() => { engine.referenceRect = this.rect.value; });+ effect(() => { engine.referenceForFill = this.has.value && this.forFill.value; });}get visible() { return this.stored.value.visible; }get opacity() { return this.stored.value.opacity; }- setOpacity(v: number) { this.stored.value = { opacity: v, visible: true }; }+ /** Opacity slider: `input` while dragging, `commit` when let go (one undo step per drag). */+ setOpacity(v: number, phase: 'input' | 'commit' = 'input') {+ this.beginGesture();+ this.stored.value = { opacity: v, visible: true };+ if (phase === 'commit') this.endGesture('Reference opacity');+ }+setVisible(v: boolean) {+ if (v === this.visible) return;+ const before = this.engine.documentState;this.stored.value = { ...this.stored.value, visible: v };if (!v) this.setAdjust(false);+ if (this.has.peek()) this.engine.recordChange('reference', v ? 'Reference shown' : 'Reference hidden', before);+ }++ /** A move / scale / opacity gesture starts: remember where to come back to. */+ beginGesture() { this.before ??= this.engine.documentState; }++ /** The gesture ended: one undo step, if anything changed. */+ endGesture(label: string) {+ const b = this.before;+ this.before = null;+ if (!b || !this.has.peek()) return;+ const now = this.engine.documentState;+ const r0 = b.reference, r1 = now.reference;+ const same = r0.opacity === r1.opacity && r0.visible === r1.visible &&+ r0.rect.x === r1.rect.x && r0.rect.y === r1.rect.y && r0.rect.w === r1.rect.w && r0.rect.h === r1.rect.h;+ if (!same) this.engine.recordChange('reference', label, b);+ }++ /** Follow the engine after an undo, redo or project open. */+ syncFrom(r: DocState['reference']) {+ this.before = null;+ const has = r.image !== null;+ if (has !== this.has.peek()) { this.has.value = has; if (!has) { this.forFill.value = false; this.askFill.value = false; this.setAdjust(false); } }+ const c = this.rect.peek();+ if (c.x !== r.rect.x || c.y !== r.rect.y || c.w !== r.rect.w || c.h !== r.rect.h) this.rect.value = { ...r.rect };+ const s = this.stored.peek();+ if (s.opacity !== r.opacity || s.visible !== r.visible) this.stored.value = { opacity: r.opacity, visible: r.visible };}setAdjust(on: boolean) {@@ -54,9 +96,26 @@ export class ReferenceStore {showToast(this.visible ? 'Reference shown' : 'Reference hidden');}- fit() { this.engine.fitReference(); this.syncRect(); }+ fit() {+ if (!this.has.peek()) return;+ const before = this.engine.documentState;+ this.engine.fitReference();+ this.syncRect();+ this.engine.recordChange('reference', 'Reference fitted', before);+ }++ remove() {+ if (!this.has.peek()) return;+ this.setAdjust(false);+ this.engine.setReference(null); // records the step; syncFrom clears the rest+ this.has.value = false; this.forFill.value = false; this.askFill.value = false;+ }- remove() { this.setAdjust(false); this.engine.setReference(null); this.has.value = false; }+ /** Answer the after-import question (or change it later). */+ useForFill(on: boolean) {+ this.askFill.value = false;+ this.forFill.value = on && this.has.peek();+ }/** Pull the placement back from the engine (after it fitted or re-created the document). */syncRect() { this.rect.value = this.engine.referenceRect; }@@ -69,7 +128,9 @@ export class ReferenceStore {this.has.value = true;this.syncRect();if (!this.visible) this.setVisible(true);- showToast('Reference added');+ // each new image starts as a plain reference; the user says whether fills should trace it+ this.forFill.value = false;+ this.askFill.value = true;return true;} catch (e) {showToast(e instanceof Error ? e.message : 'Could not read that image');diff --git a/src/shapes/ShapeStore.ts b/src/shapes/ShapeStore.tsindex 2c0aa25..da60427 100644--- a/src/shapes/ShapeStore.ts+++ b/src/shapes/ShapeStore.ts@@ -2,7 +2,7 @@ import { computed, effect, signal, type ReadonlySignal } from '@preact/signals';import type { Tool, WatercolorEngine } from '../engine/Engine';import type { PanelTool, PaperGesture } from '../app/tools';import { persisted } from '../app/persisted';-import { resizeTick } from '../app/resize';+import { resizeTick, viewTick } from '../app/resize';import { showToast } from '../app/toast';import { hideGhost, setGhost } from '../draw/ghost';import { penSpeed, StrokeWriter } from '../draw/StrokeWriter';@@ -83,7 +83,7 @@ export class ShapeStore implements PanelTool {}private renderGhost() {- resizeTick.value;+ resizeTick.value; viewTick.value;const drag = this.drag.value;if (!this.active.value || !drag || this.drawing.value) { hideGhost(); return; }const a = this.engine.aspect;@@ -110,6 +110,7 @@ export class ShapeStore implements PanelTool {this.progress.value = [0, strokes.length];this.writer.write(strokes, d.a, {tool: s.tool, ref, speed: penSpeed(s.speed), pressure: s.pressure, taper: s.taper, wobble: s.wobble,+ label: s.kind === 'svg' ? `SVG: ${this.svg.peek()?.name ?? 'shape'}` : `Shape: ${SHAPES.find(k => k.id === s.kind)!.label}`,}, {onProgress: (done, total) => { this.progress.value = [done, total]; },onDone: () => { this.drawing.value = false; this.progress.value = null; },diff --git a/src/styles.css b/src/styles.cssindex 32adf0a..f67b53a 100644--- a/src/styles.css+++ b/src/styles.css@@ -13,7 +13,7 @@[hidden] { display: none !important; }-html, body, #root, .app { margin: 0; height: 100%; overflow: hidden; background: #dbd7cf; }+html, body, #root, .app { margin: 0; height: 100%; overflow: hidden; background: #fff; }body {font: 12px/1.3 "Avenir Next", "Helvetica Neue", system-ui, sans-serif;@@ -180,6 +180,14 @@ button { font: inherit; color: inherit; }/* asks what a dropped image is for */.drop-choice { z-index: 7; display: flex; gap: 4px; padding: 6px; }.drop-choice button { flex-direction: row; gap: 6px; padding: 8px 12px; }+.fill-choice {+ z-index: 7; left: 50%; top: calc(18px + env(safe-area-inset-top)); transform: translateX(-50%);+ display: flex; flex-direction: column; gap: 6px; padding: 10px 10px 6px; max-width: calc(100vw - 32px);+}+.fill-choice p { margin: 0 4px; font-size: 12px; color: var(--ink); }+.fill-choice .row { display: flex; gap: 4px; justify-content: flex-end; flex-wrap: wrap; }+.fill-choice button { flex-direction: row; gap: 6px; padding: 8px 12px; }+.fill-choice button span { display: inline; }.settings .reset { align-self: flex-end; padding: 4px 6px; font-size: 9px; letter-spacing: 0.14em; text-transform: uppercase; }@@ -314,3 +322,75 @@ input[type="range"]::-moz-range-thumb { width: 11px; height: 11px; border-radius.fontlist { max-height: 120px; }.tool-foot .credit { display: none; }}++/* paper picker */+.popover.paper-panel { width: 286px; max-height: calc(100vh - 156px); } /* clear of the zoom control */++.popover .project { border-top: 1px solid rgba(42, 42, 51, 0.08); padding-top: 10px; }+.popover .project-buttons { display: flex; gap: 6px; align-items: center; flex-wrap: wrap; }+.popover .project .note { margin: 0; font-size: 10px; line-height: 1.35; color: var(--ink-faint); }++/* ---- history ---- */+.popover.history-panel { width: 250px; max-height: calc(100vh - 156px); }+.history-list { display: flex; flex-direction: column; gap: 2px; overflow-y: auto; overscroll-behavior: contain; scrollbar-width: thin; margin: 0 -4px; padding: 0 4px; }+.panel .history-list button { flex-direction: row; justify-content: flex-start; gap: 8px; padding: 6px 8px; border-radius: 8px; text-align: left; }+.panel .history-list button span { font-size: 11px; letter-spacing: 0; text-transform: none; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.panel .history-list button svg { flex: none; }+.panel .history-list button.undone { opacity: 0.4; }+.panel .history-list button.on { background: rgba(255, 255, 255, 0.85); color: var(--ink); box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06); }+@media (max-width: 640px) {+ .popover.history-panel { max-height: 52vh; }+ .panel .history-list button span { display: inline; }+}+.papers {+ display: grid; grid-template-columns: 1fr 1fr; gap: 6px;+ overflow-y: auto; overscroll-behavior: contain; scrollbar-width: thin; margin: 0 -4px; padding: 0 4px 2px;+}+.paper-card {+ display: flex; flex-direction: column; gap: 4px; padding: 5px 5px 6px; border-radius: 10px; cursor: pointer;+ border: 1px solid transparent; background: rgba(255, 255, 255, 0.35);+ transition: background 0.15s, border-color 0.15s;+}+.paper-card:hover { background: rgba(255, 255, 255, 0.6); }+.paper-card:focus-visible { outline: 2px solid rgba(42, 42, 51, 0.5); outline-offset: 1px; }+.paper-card.on { background: rgba(255, 255, 255, 0.75); border-color: rgba(42, 42, 51, 0.55); }+.paper-card .sheet { display: block; max-width: 100%; border-radius: 6px; box-shadow: 0 0 0 1px rgba(42, 42, 51, 0.08); }+.paper-card .label { font-size: 9px; letter-spacing: 0.14em; text-transform: uppercase; color: var(--ink-soft); padding-left: 2px; }+.paper-card.on .label { color: var(--ink); }+@media (max-width: 640px) {+ .popover.paper-panel { max-height: 52vh; }+ .paper-card .sheet { width: 100% !important; height: auto !important; }+}++/* paper size */+.paper-panel .papers { min-height: 140px; }+.paper-size { gap: 7px; }+.sizes { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 3px; }+.panel .sizes button {+ gap: 1px; padding: 5px 2px; border-radius: 8px; min-width: 0;+ border: 1px solid transparent; background: rgba(255, 255, 255, 0.35);+}+.panel .sizes button.on { background: rgba(255, 255, 255, 0.85); border-color: rgba(42, 42, 51, 0.55); }+.sizes b { font-weight: 500; font-size: 9px; letter-spacing: 0.08em; text-transform: uppercase; white-space: nowrap; }+.sizes i { font-style: normal; font-size: 9px; color: var(--ink-faint); font-variant-numeric: tabular-nums; white-space: nowrap; }+.custom-size { display: flex; align-items: center; gap: 6px; }+.custom-size .text-input { font-size: 13px; padding: 6px 8px; font-variant-numeric: tabular-nums; }+.custom-size em { font-style: normal; font-size: 10px; color: var(--ink-soft); }+.paper-size .note { margin: 0; font-size: 10px; line-height: 1.35; color: var(--ink-faint); }++/* zoom */+.zoom {+ right: calc(14px + env(safe-area-inset-right)); bottom: calc(14px + env(safe-area-inset-bottom));+ display: flex; align-items: center; gap: 1px; padding: 4px;+}+.panel.zoom button { padding: 6px; border-radius: 8px; }+.panel.zoom .pct { min-width: 50px; font-size: 11px; font-variant-numeric: tabular-nums; }++/* navigating: Space held or a pan / pinch under way */+body.space-pan .paper { cursor: grab; }+body.panning .paper { cursor: grabbing; }+body.space-pan .cursor, body.panning .cursor { opacity: 0 !important; }++@media (max-width: 640px) {+ .zoom { right: auto; left: calc(10px + env(safe-area-inset-left)); bottom: calc(96px + env(safe-area-inset-bottom)); }+}diff --git a/src/text/TextStore.ts b/src/text/TextStore.tsindex 87a3db8..5d68b06 100644--- a/src/text/TextStore.ts+++ b/src/text/TextStore.ts@@ -2,7 +2,7 @@ import { computed, effect, signal, type ReadonlySignal } from '@preact/signals';import type { Tool, WatercolorEngine } from '../engine/Engine';import type { PanelTool, PaperGesture } from '../app/tools';import { persisted } from '../app/persisted';-import { resizeTick } from '../app/resize';+import { resizeTick, viewTick } from '../app/resize';import { showToast } from '../app/toast';import { hideGhost, setGhost } from '../draw/ghost';import { penSpeed, StrokeWriter } from '../draw/StrokeWriter';@@ -82,7 +82,7 @@ export class TextStore implements PanelTool {/** Client-space path of the ghost at the hovered anchor. */private renderGhost() {- resizeTick.value; // re-run after a resize+ resizeTick.value; viewTick.value; // re-run after a resize, zoom or panconst layout = this.layout.value, hover = this.hover.value;if (!this.active.value || !layout || !hover || this.writing.value) { hideGhost(); return; }const em = emSize(this.settings.value.size), a = this.engine.aspect;@@ -109,8 +109,10 @@ export class TextStore implements PanelTool {const strokes = layout.strokes.map(pl => pl.map(([x, y]) => [x * em, -y * em] as [number, number]));this.writing.value = true;this.progress.value = [0, strokes.length];+ const text = s.text.trim();this.writer.write(strokes, anchor, {tool: s.tool, ref: em, speed: penSpeed(s.speed), pressure: s.pressure, taper: s.taper, wobble: s.wobble,+ label: `Text “${text.length > 18 ? `${text.slice(0, 18)}…` : text}”`,}, {onProgress: (done, total) => { this.progress.value = [done, total]; },onDone: () => { this.writing.value = false; this.progress.value = null; },diff --git a/src/ui/Icon.tsx b/src/ui/Icon.tsxindex d9ae267..5940639 100644--- a/src/ui/Icon.tsx+++ b/src/ui/Icon.tsx@@ -12,11 +12,17 @@ const PATHS: Record<string, string> = {clear: 'M5 7h14 M10 7V4.5h4V7 M7 7l1 13h8l1-13',image: 'M4 5h16v14H4Z M4 16l5-5 4 4 2.5-2.5L20 17 M15.5 7.5a1.5 1.5 0 1 0 0 3 1.5 1.5 0 0 0 0-3Z',save: 'M12 4v11 M7.5 10.5 12 15l4.5-4.5 M5 19.5h14',+ paper: 'M6 3.5h8l4 4v13H6Z M14 3.5v4h4 M9 12.5c1-.8 2-.8 3 0s2 .8 3 0 M9 16c1-.8 2-.8 3 0s2 .8 3 0',sliders: 'M4 7h9 M17 7h3 M4 17h3 M11 17h9 M15 5v4 M9 15v4',library: 'M4 5.5h6v6H4Z M14 5.5h6v6h-6Z M4 14.5h6v6H4Z M14 14.5h6v6h-6Z',plus: 'M12 5v14 M5 12h14',+ minus: 'M5 12h14',+ fit: 'M4 9V4h5 M15 4h5v5 M20 15v5h-5 M9 20H4v-5 M8.5 8.5h7v7h-7Z',close: 'M6 6l12 12 M18 6 6 18',chevron: 'M9 6l6 6-6 6',+ history: 'M12 3.5a8.5 8.5 0 1 0 8.5 8.5 M3.5 12A8.5 8.5 0 0 1 12 3.5 M12 7.5V12l3 2 M3.5 7.5V12H8',+ resize: 'M4 4h7v7H4Z M11 11l9 9 M20 13v7h-7 M4 15v5h5',+ folder: 'M3.5 6.5h6l2 2.5h9v10h-17Z',};/** A stroke icon from the table above, or any 24×24 path via `d`. */diff --git a/src/ui/Slider.tsx b/src/ui/Slider.tsxindex 6fa9b41..80a7431 100644--- a/src/ui/Slider.tsx+++ b/src/ui/Slider.tsx@@ -5,14 +5,17 @@ export function Row({ label, title, children, hidden }: { label: string; title?:return <label class="slider" title={title} hidden={hidden}><span>{label}</span>{children}</label>;}-export function Slider({ label, value, min = 0, max = 1, step = 0.01, title, disabled, hidden, onInput }: {+export function Slider({ label, value, min = 0, max = 1, step = 0.01, title, disabled, hidden, onInput, onChange }: {label: string; value: number; min?: number; max?: number; step?: number; title?: string; disabled?: boolean; hidden?: boolean;onInput(v: number): void;+ /** The thumb was let go (once per drag), for things that record one undo step per adjustment. */+ onChange?(v: number): void;}) {return (<Row label={label} title={title} hidden={hidden}><input type="range" min={min} max={max} step={step} value={value} disabled={disabled}- onInput={e => onInput(Number((e.currentTarget as HTMLInputElement).value))} />+ onInput={e => onInput(Number((e.currentTarget as HTMLInputElement).value))}+ onChange={onChange ? e => onChange(Number((e.currentTarget as HTMLInputElement).value)) : undefined} /></Row>);}diff --git a/src/ui/customBrushes.ts b/src/ui/customBrushes.tsindex 8f6a049..399a42a 100644--- a/src/ui/customBrushes.ts+++ b/src/ui/customBrushes.ts@@ -3,7 +3,8 @@ import { decodeImage } from '../reference/decode';const KEY = 'watercolor.customBrushes';-interface Stored { id: string; name: string; png: string }+/** A custom brush as stored: its tip as a PNG data URL. */+export interface Stored { id: string; name: string; png: string }/** Read an image file into tip data: luminance (inverted on a light background) times alpha. */export async function tipFromImage(file: Blob): Promise<Uint8Array> {@@ -41,7 +42,7 @@ export function makeCustomBrush(id: string, name: string, tip: Uint8Array): Brusreturn buildBrush({ ...CUSTOM_BASE, id, name, hint: 'Imported texture', tip, custom: true });}-function tipToPng(tip: Uint8Array): string {+export function tipToPng(tip: Uint8Array): string {const n = Math.round(Math.sqrt(tip.length));const c = document.createElement('canvas');c.width = n; c.height = n;@@ -56,30 +57,35 @@ function readStored(): Stored[] {try { return JSON.parse(localStorage.getItem(KEY) ?? '[]') as Stored[]; } catch { return []; }}+export const storedTip = (b: Brush): Stored => ({ id: b.id, name: b.name, png: tipToPng(b.tipData) });+/** Persist the set of custom brushes. Fails quietly when storage is full or blocked. */export function saveCustomBrushes(brushes: Brush[]) {try {- const items: Stored[] = brushes.map(b => ({ id: b.id, name: b.name, png: tipToPng(b.tipData) }));+ const items: Stored[] = brushes.map(storedTip);localStorage.setItem(KEY, JSON.stringify(items));return true;} catch { return false; }}+/** Rebuild a brush from its stored form. */+export async function brushFromStored(s: Stored): Promise<Brush> {+ const blob = await (await fetch(s.png)).blob();+ const bmp = await createImageBitmap(blob);+ const c = document.createElement('canvas');+ c.width = bmp.width; c.height = bmp.height;+ const ctx = c.getContext('2d')!;+ ctx.drawImage(bmp, 0, 0);+ const d = ctx.getImageData(0, 0, bmp.width, bmp.height).data;+ const tip = new Uint8Array(bmp.width * bmp.height);+ for (let i = 0; i < tip.length; i++) tip[i] = d[i * 4];+ return makeCustomBrush(s.id, s.name, tip);+}+export async function loadCustomBrushes(): Promise<Brush[]> {const out: Brush[] = [];for (const s of readStored()) {- try {- const blob = await (await fetch(s.png)).blob();- const bmp = await createImageBitmap(blob);- const c = document.createElement('canvas');- c.width = bmp.width; c.height = bmp.height;- const ctx = c.getContext('2d')!;- ctx.drawImage(bmp, 0, 0);- const d = ctx.getImageData(0, 0, bmp.width, bmp.height).data;- const tip = new Uint8Array(bmp.width * bmp.height);- for (let i = 0; i < tip.length; i++) tip[i] = d[i * 4];- out.push(makeCustomBrush(s.id, s.name, tip));- } catch { /* skip a corrupt entry */ }+ try { out.push(await brushFromStored(s)); } catch { /* skip a corrupt entry */ }}return out;}