Realistic watercolor drawings
Watercolor app with brush library, textured tips and texture import
Maksim6134b32a0228
diff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..f06235c--- /dev/null+++ b/.gitignore@@ -0,0 +1,2 @@+node_modules+distdiff --git a/README.md b/README.mdnew file mode 100644index 0000000..df5f402--- /dev/null+++ b/README.md@@ -0,0 +1,112 @@+# Watercolor++A watercolour painting app in plain TypeScript and WebGL2, with no runtime dependencies.+It combines ideas from two projects:++- **[inkwash](https://github.com/johnowhitaker/inkwash)**: the GPU fluid simulation (velocity /+ pressure / vorticity grid), a wetness field that confines flow to wet paper, pigment that only+ moves where wet, and "fixing" pigment into the paper. Reference copy in `../_reference/inkwash-main`.+- **water-brush** (the parent folder): the spectral Kubelka-Munk data from spectral.js+ (`src/filters/ColorAdder.js`) and the watercolour look (blotchy edges, tide lines, granulation).++```bash+npm install+npm run dev # http://localhost:5173+npm run build # static site in dist/+```++No runtime dependencies. Vite and TypeScript are only used at build time; the UI is plain DOM,+and the simulation, colour science and rendering are TypeScript + GLSL.++## Colour mixing++Pigment is stored as a **spectrum** rather than RGB, so mixes behave like paint:+yellow + blue gives green, rose + ultramarine gives violet, and sienna + ultramarine gives a neutral grey.++1. A picked colour is upsampled to a 38-band reflectance curve (spectral.js method) and converted+ to spectral absorbance `A(λ) = −ln R(λ)`.+2. `A(λ)` is projected onto a 7-vector basis (uncentred SVD of absorbance over the sRGB gamut,+ fitted offline, see `src/engine/spectralData.ts`). Absorbance is linear in concentration, so+ these coefficients can be added, advected and diffused by the fluid sim and the mix stays+ physically subtractive (Beer–Lambert, the transparent-glaze model that suits watercolour).+3. The display shader rebuilds the spectrum at 16 wavelengths, applies `exp(−A)`, and integrates+ to sRGB with a fitted quadrature.++Accuracy against the full 38-band model: mean ΔE_OK ≈ 0.1–0.2 (×100 scale) for single colours,+dilutions, mixes and glazes, well below the visible threshold (~2). The coefficients are signed:+never clamp them.++Seven coefficients + white-gouache coverage fit exactly in two RGBA16F textures.++## Simulation++| layer | format | |+|---|---|---|+| velocity, pressure | RG16F / R16F, 256 px short side | water flow (from inkwash) |+| wet | R16F, document res | standing water; dries exponentially |+| ink | 2× RGBA16F (MRT), ping-pong | mobile pigment coefficients + white |+| fixed | 2× RGBA16F | pigment settled into the paper ("Dry") |+| paper | RGBA8 | procedural cold-press relief, generated once |++Pigment transport (`advectInkFS`) moves pigment with the water flow and exchanges it between+neighbouring texels through *fluxes gated by the wetness of both sides*. That conserves pigment+and keeps it from seeping onto dry paper, so wet-on-dry strokes get hard edges and wet-in-wet+strokes bloom as far as the water reaches. A capillary term pushes pigment down the wetness+gradient toward the drying edge, where it gets stranded: the dark tide line of a dried wash.++## Performance++- **Dirty-rect simulation.** Every document-resolution pass is scissored to the region that is+ actually wet. The region grows only as fast as the wet front can move.+- **Sleeps when dry.** Once the water has evaporated below the threshold where anything can+ move, the sim stops and so does `requestAnimationFrame`. An idle canvas uses no GPU time.+- **Partial redraws.** Only the changed region of the canvas is re-composited.+- **Undo through copy-on-write tiles.** Before a 128 px tile is first modified in a step it is+ copied into an atlas. Undo blits the tiles back. The fixed layer is snapshotted only when+ fixing. Memory is bounded and the oldest steps are evicted.+- Document capped at 2048 × 1536. Coalesced pointer events, with distance-based stamp+ spacing so deposits don't depend on the input event rate.++## Brushes++The Brush and Water tools paint with the selected brush from the library (the dab thumbnail at the+top of the tool bar, or `,` / `.` to cycle). Every brush is a **tip texture** plus behaviour, all in+`src/engine/brushes.ts`:++| | |+|---|---|+| Round, Detail, Rigger | pointed rounds from a #8 down to a liner that holds a lot of paint |+| Flat, Filbert, Dagger | shaped tips held at a fixed angle; an Apple Pencil's tilt turns them, so strokes go thick and thin with direction |+| Hake, Fan, Dry Brush | tips that follow the stroke; bristle gaps become streaks along the mark |+| Mop | floods the paper for washes |+| Sponge, Stipple, Spatter | dabbed and scattered marks: cells, dots, flicked droplets |+| Sumi | hairline to broad with pressure, fibrous edge |++Tips are generated procedurally (noise, Worley cells, hair segments) into a 192² texture in *tip+space*, which the stamp shader maps onto a rotated ellipse of the brush's aspect ratio. Each+preset sets spacing, scatter, dabs per stamp, size-vs-pressure, speed thinning, water capacity+and `grain`: how much the paper's tooth gates the deposit. A dry brush (or any brush that has+run out of water) only touches the peaks of the paper, so the stroke breaks up; pressing harder+reaches into the valleys.++**Import texture…** in the library turns any PNG/JPG into a brush tip (dark marks on white are+inverted automatically; alpha is respected). Imported brushes are kept in `localStorage`.+Drop an image anywhere on the page to import it.++## Using it++| | |+|---|---|+| **, .** | previous / next brush |+| **B** Brush | wet paint: pigment and water |+| **W** Water | clear water: wets paper, pushes paint around |+| **P** Pen | ink line, feathers into wet areas |+| **L** Lift | blot with a tissue: lifts wet (unfixed) paint |+| **D** Dry | flash-dry and fix paint into the paper, so you can glaze over it |+| **1–9, 0** | pigments; the last is white gouache |+| **[ ]** | size |+| **⌘Z** | undo |+| **S** / **F** | save PNG / fullscreen |++Stylus: pressure shapes the stroke. The barrel button switches to water and the eraser end+lifts. On iPad, once an Apple Pencil has been used, your finger becomes the water brush.diff --git a/index.html b/index.htmlnew file mode 100644index 0000000..cf1f192--- /dev/null+++ b/index.html@@ -0,0 +1,17 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no, viewport-fit=cover" />+ <meta name="mobile-web-app-capable" content="yes" />+ <meta name="apple-mobile-web-app-capable" content="yes" />+ <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%270 0 32 32%27%3E%3Ccircle cx=%2716%27 cy=%2716%27 r=%2713%27 fill=%27%232338a8%27 opacity=%27.8%27/%3E%3C/svg%3E" />+ <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />+ <meta name="theme-color" content="#e9e5dc" />+ <title>Watercolor</title>+ </head>+ <body>+ <div id="root"></div>+ <script type="module" src="/src/main.ts"></script>+ </body>+</html>diff --git a/package-lock.json b/package-lock.jsonnew file mode 100644index 0000000..6191938--- /dev/null+++ b/package-lock.json@@ -0,0 +1,1204 @@+{+ "name": "watercolor",+ "version": "0.1.0",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "watercolor",+ "version": "0.1.0",+ "devDependencies": {+ "typescript": "^7.0.2",+ "vite": "^8.3.2"+ }+ },+ "node_modules/@oxc-project/types": {+ "version": "0.152.0",+ "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.152.0.tgz",+ "integrity": "sha512-oM/5rLBm2tPkg0iBgkH/FOeR3PCDpY19GTgAZjMFM8h9WI9VW7cLgzp6nwtarYKmovavIQZ+Fe/RKX/8C8O/Rw==",+ "dev": true,+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/oxc-project"+ }+ },+ "node_modules/@rolldown/binding-android-arm-eabi": {+ "version": "1.2.12",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.12.tgz",+ "integrity": "sha512-dB/a1214qKfHMXCpgqR4OZT+jS4kTyEXbQGJPqzobt5EwH5rX080pxE37alt3RzvR1bf1Yz/yGqRfrYAxuPw0A==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-android-arm64": {+ "version": "1.2.12",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.12.tgz",+ "integrity": "sha512-7KHFgQ5VJxIHcLlrwrc3Xbds7oTNQT7Pgi9gQCJKrd2VGab/UksIOYp6VD8MzCstGxOKMgNamPwUCfxPdP1OHg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-darwin-arm64": {+ "version": "1.2.12",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.12.tgz",+ "integrity": "sha512-3YIhqHD96nA5SaYNRBR16HnGv4oavZvXfD/ayHM+oYZ0WD/8lBAtf6zQua4kEyAvpqrluKXl0lnOBoiNby7x9w==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-darwin-x64": {+ "version": "1.2.12",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.12.tgz",+ "integrity": "sha512-UuuJ35MFw4gmFOrE9pEqIV+K3syIKveph+Qc1/ljHZVdoDW4pz/JHR/eMVom+TZGl/5OOvGJOWaOCVt3ZfqhxA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-freebsd-x64": {+ "version": "1.2.12",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.12.tgz",+ "integrity": "sha512-uMvssit0a4W+/7D8CbHUvG719mH3R2jwXAlh/XcPvuHTE0g++LymF88DCGNX0HM2rBOn0xrzgXktIB6fLSJBTQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-linux-arm-gnueabihf": {+ "version": "1.2.12",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.12.tgz",+ "integrity": "sha512-XcFu0R0xWnwzSf4IQgFH1rJIckPN1pLy2R+4r9IDB7Yfu/ys9cVqfa4pBrMHj7a3gl8mIR4nRNPg0e5IvEVs6g==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-linux-arm64-gnu": {+ "version": "1.2.12",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.12.tgz",+ "integrity": "sha512-260UrKgn8tz39ak+SMDOirKzr7V04M9dWPw5llW00SwBivCZoWcRBKV1d8cXnRkUmSZA3BdiUmBHWk7734Ulpw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-linux-arm64-musl": {+ "version": "1.2.12",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.12.tgz",+ "integrity": "sha512-5YK1I9SqDkbPgc1IA8BgDl34suqUS2q0KWnBrirm0E51YjOs6eo6dV6jbQfNE/argHRSvd0QUGgtpIoYx+WWpw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "libc": [+ "musl"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-linux-ppc64-gnu": {+ "version": "1.2.12",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.12.tgz",+ "integrity": "sha512-Rkcrmp7eFRg74yL5fXEU91JEWbdEPLevWwGtXpmhbjlD1StScbWTmO94Bhly+Mo+ketKYkdmM1vNUKeWSlx8cQ==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-linux-s390x-gnu": {+ "version": "1.2.12",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.12.tgz",+ "integrity": "sha512-qvK4DuAsQc2BSjlx+Xr+IzOIvvxbGZqxFwdWfG6F518Erj0GGISyQbJ6pIappnOxlNPzNHvo/L0BwB30GZ+zVw==",+ "cpu": [+ "s390x"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-linux-x64-gnu": {+ "version": "1.2.12",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.12.tgz",+ "integrity": "sha512-Q9uLBO53Xd4QIq1WOycVQyPP1O4HhraEV2qqb3uTrnVw6QZih9duY4vNXOivL1xoUS1/z+W8eF4NMfl2a8Sdjw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-linux-x64-musl": {+ "version": "1.2.12",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.12.tgz",+ "integrity": "sha512-3IBxWFMjbOZskDPKv8Lf9BCnahlKuHthWkYnyIxOH/QcJrFcS4EmcenthApkwr/5+nEqZlLzeYbxeMaX7A5u4g==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "libc": [+ "musl"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-openharmony-arm64": {+ "version": "1.2.12",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.12.tgz",+ "integrity": "sha512-xtX61xg4LKPkPWilZU1ynKClz5Gj4bf74LML4r3eVLWumKnGjoEr1OSHQhMdbBDoYTi+yjrujvpZe2pUnqCrrA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openharmony"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-win32-arm64-msvc": {+ "version": "1.2.12",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.12.tgz",+ "integrity": "sha512-At7fPB6PCaIjzgIhEZFxuT+BBFqiQibJDT4d3PhiR3f4E7bbMZF4aKblbFfEM3sETRDd1YiQx/+U/g/B/ou5Ew==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-win32-x64-msvc": {+ "version": "1.2.12",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.12.tgz",+ "integrity": "sha512-WIw2haVKwjuYdXkHaoC0mF8Le71TuCBxjrdKqLbJGctbBABj+ClfmNvtbOnzpq3RokNo5+V1qhtSzJyXorsklQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/pluginutils": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz",+ "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@typescript/typescript-aix-ppc64": {+ "version": "7.0.2",+ "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz",+ "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "aix"+ ],+ "engines": {+ "node": ">=16.20.0"+ }+ },+ "node_modules/@typescript/typescript-darwin-arm64": {+ "version": "7.0.2",+ "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz",+ "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=16.20.0"+ }+ },+ "node_modules/@typescript/typescript-darwin-x64": {+ "version": "7.0.2",+ "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz",+ "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=16.20.0"+ }+ },+ "node_modules/@typescript/typescript-freebsd-arm64": {+ "version": "7.0.2",+ "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz",+ "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=16.20.0"+ }+ },+ "node_modules/@typescript/typescript-freebsd-x64": {+ "version": "7.0.2",+ "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz",+ "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=16.20.0"+ }+ },+ "node_modules/@typescript/typescript-linux-arm": {+ "version": "7.0.2",+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz",+ "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=16.20.0"+ }+ },+ "node_modules/@typescript/typescript-linux-arm64": {+ "version": "7.0.2",+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz",+ "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=16.20.0"+ }+ },+ "node_modules/@typescript/typescript-linux-loong64": {+ "version": "7.0.2",+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz",+ "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==",+ "cpu": [+ "loong64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=16.20.0"+ }+ },+ "node_modules/@typescript/typescript-linux-mips64el": {+ "version": "7.0.2",+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz",+ "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==",+ "cpu": [+ "mips64el"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=16.20.0"+ }+ },+ "node_modules/@typescript/typescript-linux-ppc64": {+ "version": "7.0.2",+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz",+ "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=16.20.0"+ }+ },+ "node_modules/@typescript/typescript-linux-riscv64": {+ "version": "7.0.2",+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz",+ "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=16.20.0"+ }+ },+ "node_modules/@typescript/typescript-linux-s390x": {+ "version": "7.0.2",+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz",+ "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==",+ "cpu": [+ "s390x"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=16.20.0"+ }+ },+ "node_modules/@typescript/typescript-linux-x64": {+ "version": "7.0.2",+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz",+ "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=16.20.0"+ }+ },+ "node_modules/@typescript/typescript-netbsd-arm64": {+ "version": "7.0.2",+ "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz",+ "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=16.20.0"+ }+ },+ "node_modules/@typescript/typescript-netbsd-x64": {+ "version": "7.0.2",+ "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz",+ "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=16.20.0"+ }+ },+ "node_modules/@typescript/typescript-openbsd-arm64": {+ "version": "7.0.2",+ "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz",+ "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=16.20.0"+ }+ },+ "node_modules/@typescript/typescript-openbsd-x64": {+ "version": "7.0.2",+ "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz",+ "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=16.20.0"+ }+ },+ "node_modules/@typescript/typescript-sunos-x64": {+ "version": "7.0.2",+ "resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz",+ "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "sunos"+ ],+ "engines": {+ "node": ">=16.20.0"+ }+ },+ "node_modules/@typescript/typescript-win32-arm64": {+ "version": "7.0.2",+ "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz",+ "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=16.20.0"+ }+ },+ "node_modules/@typescript/typescript-win32-x64": {+ "version": "7.0.2",+ "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz",+ "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=16.20.0"+ }+ },+ "node_modules/detect-libc": {+ "version": "2.1.2",+ "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",+ "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/fdir": {+ "version": "6.5.0",+ "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",+ "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=12.0.0"+ },+ "peerDependencies": {+ "picomatch": "^3 || ^4"+ },+ "peerDependenciesMeta": {+ "picomatch": {+ "optional": true+ }+ }+ },+ "node_modules/fsevents": {+ "version": "2.3.3",+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",+ "dev": true,+ "hasInstallScript": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"+ }+ },+ "node_modules/lightningcss": {+ "version": "1.33.0",+ "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz",+ "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==",+ "dev": true,+ "license": "MPL-2.0",+ "dependencies": {+ "detect-libc": "^2.0.3"+ },+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ },+ "optionalDependencies": {+ "lightningcss-android-arm64": "1.33.0",+ "lightningcss-darwin-arm64": "1.33.0",+ "lightningcss-darwin-x64": "1.33.0",+ "lightningcss-freebsd-x64": "1.33.0",+ "lightningcss-linux-arm-gnueabihf": "1.33.0",+ "lightningcss-linux-arm64-gnu": "1.33.0",+ "lightningcss-linux-arm64-musl": "1.33.0",+ "lightningcss-linux-x64-gnu": "1.33.0",+ "lightningcss-linux-x64-musl": "1.33.0",+ "lightningcss-win32-arm64-msvc": "1.33.0",+ "lightningcss-win32-x64-msvc": "1.33.0"+ }+ },+ "node_modules/lightningcss-android-arm64": {+ "version": "1.33.0",+ "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz",+ "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-darwin-arm64": {+ "version": "1.33.0",+ "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz",+ "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-darwin-x64": {+ "version": "1.33.0",+ "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz",+ "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-freebsd-x64": {+ "version": "1.33.0",+ "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz",+ "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-linux-arm-gnueabihf": {+ "version": "1.33.0",+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz",+ "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-linux-arm64-gnu": {+ "version": "1.33.0",+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz",+ "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-linux-arm64-musl": {+ "version": "1.33.0",+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz",+ "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "libc": [+ "musl"+ ],+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-linux-x64-gnu": {+ "version": "1.33.0",+ "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz",+ "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-linux-x64-musl": {+ "version": "1.33.0",+ "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz",+ "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "libc": [+ "musl"+ ],+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-win32-arm64-msvc": {+ "version": "1.33.0",+ "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz",+ "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-win32-x64-msvc": {+ "version": "1.33.0",+ "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz",+ "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/nanoid": {+ "version": "3.3.19",+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.19.tgz",+ "integrity": "sha512-Y2tUNy4ouw6tq5oDSKeQYGOyhkUBhNOcGV/02KC+6kd9eDGqdZd++mjMiIDilrBYvjEnCYvVtsuHCuP+okSfug==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "bin": {+ "nanoid": "bin/nanoid.cjs"+ },+ "engines": {+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"+ }+ },+ "node_modules/picocolors": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",+ "dev": true,+ "license": "ISC"+ },+ "node_modules/picomatch": {+ "version": "4.0.7",+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz",+ "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/sponsors/jonschlinkert"+ }+ },+ "node_modules/postcss": {+ "version": "8.5.28",+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz",+ "integrity": "sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==",+ "dev": true,+ "funding": [+ {+ "type": "opencollective",+ "url": "https://opencollective.com/postcss/"+ },+ {+ "type": "tidelift",+ "url": "https://tidelift.com/funding/github/npm/postcss"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "nanoid": "^3.3.18",+ "picocolors": "^1.1.1",+ "source-map-js": "^1.2.1"+ },+ "engines": {+ "node": "^10 || ^12 || >=14"+ }+ },+ "node_modules/rolldown": {+ "version": "1.2.12",+ "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.12.tgz",+ "integrity": "sha512-8wafseiaG80xmXSfqidUNqZcylTlhmPZZt+za2m+js2sFZ8dTNlhIOV2WcbIPx2hgwPBJpEUGFAMZ9bgBBLTSQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@oxc-project/types": "=0.152.0",+ "@rolldown/pluginutils": "^1.0.0"+ },+ "bin": {+ "rolldown": "bin/cli.mjs"+ },+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ },+ "optionalDependencies": {+ "@rolldown/binding-android-arm-eabi": "1.2.12",+ "@rolldown/binding-android-arm64": "1.2.12",+ "@rolldown/binding-darwin-arm64": "1.2.12",+ "@rolldown/binding-darwin-x64": "1.2.12",+ "@rolldown/binding-freebsd-x64": "1.2.12",+ "@rolldown/binding-linux-arm-gnueabihf": "1.2.12",+ "@rolldown/binding-linux-arm64-gnu": "1.2.12",+ "@rolldown/binding-linux-arm64-musl": "1.2.12",+ "@rolldown/binding-linux-ppc64-gnu": "1.2.12",+ "@rolldown/binding-linux-s390x-gnu": "1.2.12",+ "@rolldown/binding-linux-x64-gnu": "1.2.12",+ "@rolldown/binding-linux-x64-musl": "1.2.12",+ "@rolldown/binding-openharmony-arm64": "1.2.12",+ "@rolldown/binding-win32-arm64-msvc": "1.2.12",+ "@rolldown/binding-win32-x64-msvc": "1.2.12"+ }+ },+ "node_modules/source-map-js": {+ "version": "1.2.2",+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz",+ "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==",+ "dev": true,+ "license": "BSD-3-Clause",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/tinyglobby": {+ "version": "0.2.17",+ "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",+ "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "fdir": "^6.5.0",+ "picomatch": "^4.0.4"+ },+ "engines": {+ "node": ">=12.0.0"+ },+ "funding": {+ "url": "https://github.com/sponsors/SuperchupuDev"+ }+ },+ "node_modules/typescript": {+ "version": "7.0.2",+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz",+ "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==",+ "dev": true,+ "license": "Apache-2.0",+ "bin": {+ "tsc": "bin/tsc"+ },+ "engines": {+ "node": ">=16.20.0"+ },+ "optionalDependencies": {+ "@typescript/typescript-aix-ppc64": "7.0.2",+ "@typescript/typescript-darwin-arm64": "7.0.2",+ "@typescript/typescript-darwin-x64": "7.0.2",+ "@typescript/typescript-freebsd-arm64": "7.0.2",+ "@typescript/typescript-freebsd-x64": "7.0.2",+ "@typescript/typescript-linux-arm": "7.0.2",+ "@typescript/typescript-linux-arm64": "7.0.2",+ "@typescript/typescript-linux-loong64": "7.0.2",+ "@typescript/typescript-linux-mips64el": "7.0.2",+ "@typescript/typescript-linux-ppc64": "7.0.2",+ "@typescript/typescript-linux-riscv64": "7.0.2",+ "@typescript/typescript-linux-s390x": "7.0.2",+ "@typescript/typescript-linux-x64": "7.0.2",+ "@typescript/typescript-netbsd-arm64": "7.0.2",+ "@typescript/typescript-netbsd-x64": "7.0.2",+ "@typescript/typescript-openbsd-arm64": "7.0.2",+ "@typescript/typescript-openbsd-x64": "7.0.2",+ "@typescript/typescript-sunos-x64": "7.0.2",+ "@typescript/typescript-win32-arm64": "7.0.2",+ "@typescript/typescript-win32-x64": "7.0.2"+ }+ },+ "node_modules/vite": {+ "version": "8.3.2",+ "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.2.tgz",+ "integrity": "sha512-SQr1x6W5vVSbROg7vsyXIaxK9b0G7zsT68acdWWRmnBUsgDieLCRG+Rep9WdZgcposvv/GSnr4GUUBqB3vXq6w==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "lightningcss": "^1.33.0",+ "picomatch": "^4.0.7",+ "postcss": "^8.5.28",+ "rolldown": "~1.2.11",+ "tinyglobby": "^0.2.17"+ },+ "bin": {+ "vite": "bin/vite.js"+ },+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ },+ "funding": {+ "url": "https://github.com/vitejs/vite?sponsor=1"+ },+ "optionalDependencies": {+ "fsevents": "~2.3.3"+ },+ "peerDependencies": {+ "@types/node": "^20.19.0 || >=22.12.0",+ "@vitejs/devtools": "^0.7.1",+ "esbuild": "^0.27.0 || ^0.28.0",+ "jiti": ">=1.21.0",+ "less": "^4.0.0",+ "sass": "^1.70.0",+ "sass-embedded": "^1.70.0",+ "stylus": ">=0.54.8",+ "sugarss": "^5.0.0",+ "terser": "^5.16.0",+ "tsx": "^4.8.1",+ "yaml": "^2.4.2"+ },+ "peerDependenciesMeta": {+ "@types/node": {+ "optional": true+ },+ "@vitejs/devtools": {+ "optional": true+ },+ "esbuild": {+ "optional": true+ },+ "jiti": {+ "optional": true+ },+ "less": {+ "optional": true+ },+ "sass": {+ "optional": true+ },+ "sass-embedded": {+ "optional": true+ },+ "stylus": {+ "optional": true+ },+ "sugarss": {+ "optional": true+ },+ "terser": {+ "optional": true+ },+ "tsx": {+ "optional": true+ },+ "yaml": {+ "optional": true+ }+ }+ }+ }+}diff --git a/package.json b/package.jsonnew file mode 100644index 0000000..094ac2f--- /dev/null+++ b/package.json@@ -0,0 +1,16 @@+{+ "name": "watercolor",+ "private": true,+ "version": "0.1.0",+ "type": "module",+ "scripts": {+ "dev": "vite",+ "build": "tsc -b && vite build",+ "preview": "vite preview",+ "typecheck": "tsc -b"+ },+ "devDependencies": {+ "typescript": "^7.0.2",+ "vite": "^8.3.2"+ }+}diff --git a/src/engine/Engine.ts b/src/engine/Engine.tsnew file mode 100644index 0000000..69a5d0d--- /dev/null+++ b/src/engine/Engine.ts@@ -0,0 +1,972 @@+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 * as S from './shaders';+import { pigmentFromHex, type Pigment } from './spectral';++export type Tool = 'brush' | 'water' | 'pen' | 'lift';++/** All sliders are normalised 0..1. */+export interface Params {+ size: number;+ water: number; // how much water the brush carries+ load: number; // pigment concentration on the brush+ flow: number; // strength of the water's motion+ bleed: number; // diffusion of pigment through wet paper+ dry: number; // drying speed+ edge: number; // tide-line darkening at drying edges+ granulation: number; // pigment settling into the paper grain+}++export const DEFAULT_PARAMS: Params = {+ size: 0.5, water: 0.6, load: 0.5, flow: 0.45, bleed: 0.5, dry: 0.4, edge: 0.5, granulation: 0.45,+};++export interface EngineCallbacks {+ onHistoryChange?(canUndo: boolean): void;+ /** The active tool changed for the current stroke (pencil barrel / finger-as-water). */+ onStrokeTool?(tool: Tool | null): void;+}++interface Sample { x: number; y: number; p: number; t: number; tx: number; ty: number }++interface Stroke {+ pointerId: number;+ pointerType: string;+ tool: Tool;+ started: boolean;+ ending: boolean;+ x: number; y: number; // smoothed position (uv)+ t: number; // time of last sample (ms)+ speed: number; // doc heights / second+ simPressure: number; // pressure stand-in for mice and fingers+ carry: number; // distance travelled since the last stamp (doc heights)+ travelled: number;+ moved: boolean; // received movement this frame+ dx: number; dy: number; // smoothed direction (aspect-corrected, unit-ish)+ angle: number; // tip angle of the last dab (radians, doc frame)+ azimuth: number | null; // pen tilt direction, when the pen is tilted enough to tell+}++const DEG = Math.PI / 180;++interface HistoryMeta { wetAgo: number; wetPeak: number; active: Rect | null }++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 };+const HALF_FLOAT_RGBA: Format = { internal: WebGL2RenderingContext.RGBA16F, format: WebGL2RenderingContext.RGBA, type: WebGL2RenderingContext.HALF_FLOAT };+const RGBA8: Format = { internal: WebGL2RenderingContext.RGBA8, format: WebGL2RenderingContext.RGBA, type: WebGL2RenderingContext.UNSIGNED_BYTE };++const SIM_BASE = 256; // short side of the velocity / pressure grid+const 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 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 clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));+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 };++export class WatercolorEngine {+ params: Params = { ...DEFAULT_PARAMS };+ tool: Tool = 'brush';+ pigment: Pigment = pigmentFromHex('#2338a8');+ brush: Brush = buildBrush(BRUSH_PRESETS[0]);+ /** Once an Apple Pencil / stylus is seen, fingers paint with clear water. */+ fingerIsWater = true;++ private tipTextures = new Map<string, WebGLTexture>();+ private lastDir: [number, number] = [1, 0]; // direction of the last stroke, for the first dab+ private lastAngle = 0; // tip angle shown by the hover cursor++ private g: GL;+ private gl: WebGL2RenderingContext;+ private programs: Record<string, Program>;+ private canvasSize: [number, number] = [1, 1];+ private dpr = 1;+ private view = { x: 0, y: 0, w: 1, h: 1 }; // document placement in canvas px++ // document state+ private dw = 1; private dh = 1;+ private velocity!: DoubleTarget;+ private pressure!: DoubleTarget;+ private divergence!: Target;+ private curl!: Target;+ private ink!: DoubleTarget;+ private fixed!: Target;+ private wet!: DoubleTarget;+ private paper!: Target;+ private history!: History;++ // simulation bookkeeping+ private active: Rect | null = null; // document texels the sim must process+ private painted: Rect | null = null; // where mobile pigment may exist (since the last fix)+ private dirty: Rect | null = null; // document texels to redraw+ private dirtyAll = true;+ private lastWet = -Infinity; // ms timestamp of the last water added+ private wetPeak = 0;+ private minAwakeUntil = 0;+ private fixTimer = 0;+ private flowSpeed = 0; // upper bound on water speed (sim texels / s)+ private growCarry = 0; // fractional texels the active rect still has to grow+ private brushNow = { x: 0, y: 0, r: 0 };+ private raf = 0;+ private lastFrame = 0;++ // input+ private stroke: Stroke | null = null;+ private queue: Sample[] = [];+ private pencilSeen = false;+ private hover = { x: 0, y: 0, inside: false, type: 'mouse' };+ private force = { value: 0, t: -Infinity };+ private disposers: (() => void)[] = [];++ constructor(private canvas: HTMLCanvasElement, private cursor: HTMLElement | null, private callbacks: EngineCallbacks = {}) {+ const gl = canvas.getContext('webgl2', {+ alpha: false, depth: false, stencil: false, antialias: false, preserveDrawingBuffer: true,+ powerPreference: 'high-performance',+ });+ if (!gl) throw new Error('WebGL2 is not available in this browser.');+ if (!gl.getExtension('EXT_color_buffer_float') && !gl.getExtension('EXT_color_buffer_half_float'))+ throw new Error('This GPU cannot render to floating-point textures.');+ this.gl = gl;+ this.g = new GL(gl);+ gl.disable(gl.BLEND);+ this.programs = {+ splat: this.g.program(S.splatFS),+ stamp: this.g.program(S.stampFS),+ advectVelocity: this.g.program(S.advectVelocityFS),+ divergence: this.g.program(S.divergenceFS),+ pressure: this.g.program(S.pressureFS),+ gradient: this.g.program(S.gradientSubtractFS),+ curl: this.g.program(S.curlFS),+ vorticity: this.g.program(S.vorticityFS),+ scale: this.g.program(S.scaleFS),+ advectWet: this.g.program(S.advectWetFS),+ 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),+ display: this.g.program(S.displayFS),+ };+ this.fitCanvas();+ this.createDocument();+ this.attachInput();+ this.schedule();+ }++ /* ------------------------------------------------------------------ setup */++ private fitCanvas() {+ this.dpr = Math.min(window.devicePixelRatio || 1, 2);+ const r = this.canvas.getBoundingClientRect();+ 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();+ }++ private fitView() {+ 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 };+ this.dirtyAll = true;+ }++ /** (Re)create the document to fill the current canvas. Discards the painting. */+ private createDocument() {+ const [cw, ch] = this.canvasSize;+ const s = Math.min(1, MAX_DOC_LONG / Math.max(cw, ch), MAX_DOC_SHORT / Math.min(cw, ch));+ this.dw = Math.round(cw * s); this.dh = Math.round(ch * s);+ 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);+ this.pressure = g.double(sim.w, sim.h, [HALF_FLOAT_R], gl.NEAREST);+ this.divergence = g.target(sim.w, sim.h, [HALF_FLOAT_R], gl.NEAREST);+ this.curl = g.target(sim.w, sim.h, [HALF_FLOAT_R], gl.NEAREST);+ this.ink = g.double(this.dw, this.dh, [HALF_FLOAT_RGBA, HALF_FLOAT_RGBA], gl.LINEAR);+ 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, [+ { 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);++ this.active = null;+ this.painted = null;+ this.lastWet = -Infinity;+ this.wetPeak = 0;+ this.fixTimer = 0;+ this.fitView();+ this.callbacks.onHistoryChange?.(false);+ }++ /* ------------------------------------------------------------- public API */++ setParams(p: Partial<Params>) { Object.assign(this.params, p); }++ setPigment(p: Pigment) { this.pigment = p; }++ setTool(t: Tool) { this.tool = t; this.updateCursor(); }++ setBrush(b: Brush) {+ this.brush = b;+ this.lastAngle = b.rotation === 'fixed' ? b.angle * DEG : b.rotation === 'follow' ? Math.atan2(this.lastDir[1], this.lastDir[0]) + b.angle * DEG : 0;+ this.updateCursor();+ }++ /** Drop the GPU copy of a brush tip (after a custom brush is removed or replaced). */+ forgetBrush(id: string) {+ const t = this.tipTextures.get(id);+ if (t) { this.gl.deleteTexture(t); this.tipTextures.delete(id); }+ }++ private tipTexture(b: Brush): WebGLTexture {+ let t = this.tipTextures.get(b.id);+ if (t) return t;+ const { gl } = this;+ t = gl.createTexture()!;+ gl.activeTexture(gl.TEXTURE0);+ gl.bindTexture(gl.TEXTURE_2D, t);+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.R8, b.tipSize, b.tipSize, 0, gl.RED, gl.UNSIGNED_BYTE, b.tipData);+ 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.tipTextures.set(b.id, t);+ return t;+ }++ /** Dry everything and bake the mobile pigment into the paper. */+ fix() {+ if (!this.painted || this.fixTimer > 0) return;+ this.beginStep();+ // the fixed layer only ever changes here, so it is only snapshotted here+ this.history.protect(1, this.painted, this.fixed.views);+ this.fixTimer = FIX_DURATION;+ // mobile pigment only exists where strokes have been, so only that needs settling+ this.touch(this.painted);+ this.schedule();+ }++ clear() {+ this.stroke = null;+ this.queue = [];+ this.createDocument();+ this.schedule();+ }++ undo() {+ if (!this.history.canUndo) return;+ this.stroke = null;+ this.queue = [];+ this.fixTimer = 0;+ this.sleep();+ const ink = this.ink, wet = this.wet;+ const res = this.history.undo([+ [[ink.read.views[0], ink.write.views[0]], [ink.read.views[1], ink.write.views[1]], [wet.read.views[0], wet.write.views[0]]],+ [[this.fixed.views[0]], [this.fixed.views[1]]],+ ]);+ if (!res) return;+ const meta = res.meta as HistoryMeta;+ 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 (res.rect) {+ this.dirty = union(this.dirty, res.rect);+ this.painted = union(this.painted, res.rect);+ }+ this.callbacks.onHistoryChange?.(this.history.canUndo);+ this.schedule();+ }++ get canUndo() { return this.history.canUndo; }++ /** Render the document at full resolution and return it as a PNG. */+ async exportPNG(): Promise<Blob> {+ 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);+ 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]);+ const c = document.createElement('canvas');+ c.width = dw; c.height = dh;+ const ctx = c.getContext('2d')!;+ const img = ctx.createImageData(dw, dh);+ const row = dw * 4;+ for (let y = 0; y < dh; y++) img.data.set(px.subarray((dh - 1 - y) * row, (dh - y) * row), y * row);+ ctx.putImageData(img, 0, 0);+ return new Promise((resolve, reject) => c.toBlob(b => (b ? resolve(b) : reject(new Error('export failed'))), 'image/png'));+ }++ resize() {+ this.fitCanvas();+ this.schedule();+ }++ destroy() {+ cancelAnimationFrame(this.raf);+ this.disposers.forEach(d => d());+ this.tipTextures.forEach(t => this.gl.deleteTexture(t));+ this.tipTextures.clear();+ this.g.disposeTargets();+ }++ /* ------------------------------------------------------------------ input */++ private toUv(e: { clientX: number; clientY: number }): [number, number] {+ const r = this.canvas.getBoundingClientRect();+ const cx = (e.clientX - r.left) * this.dpr;+ const cy = this.canvasSize[1] - (e.clientY - r.top) * this.dpr;+ return [(cx - this.view.x) / this.view.w, (cy - this.view.y) / this.view.h];+ }++ private attachInput() {+ const c = this.canvas;+ const on = <K extends keyof HTMLElementEventMap>(el: HTMLElement | Window, type: K, fn: (e: HTMLElementEventMap[K]) => void, opts?: AddEventListenerOptions) => {+ el.addEventListener(type, fn as EventListener, opts);+ this.disposers.push(() => el.removeEventListener(type, fn as EventListener, opts));+ };++ on(c, 'pointerdown', e => {+ e.preventDefault();+ 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 */ }+ let tool = this.tool;+ if (e.pointerType === 'touch' && this.pencilSeen && this.fingerIsWater) tool = 'water';+ if (e.pointerType === 'pen' && e.buttons & 32) tool = 'lift'; // eraser end+ else if (e.pointerType === 'pen' && e.buttons & 2) tool = tool === 'water' ? 'brush' : 'water'; // barrel button+ this.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,+ dx: this.lastDir[0], dy: this.lastDir[1], angle: this.lastAngle, azimuth: null,+ };+ if (tool !== this.tool) this.callbacks.onStrokeTool?.(tool);+ this.beginStep();+ this.pushSample(e);+ this.trackHover(e);+ this.schedule();+ });++ on(c, 'pointermove', e => {+ if (e.pointerType === 'pen') this.pencilSeen = true;+ this.trackHover(e);+ if (!this.stroke || e.pointerId !== this.stroke.pointerId) return;+ const events = e.getCoalescedEvents?.() ?? [];+ for (const s of events.length ? events : [e]) this.pushSample(s);+ this.schedule();+ });++ const end = (e: PointerEvent) => {+ if (!this.stroke || e.pointerId !== this.stroke.pointerId) return;+ this.stroke.ending = true;+ this.schedule();+ };+ on(c, 'pointerup', end);+ on(c, 'pointercancel', end);+ on(c, 'pointerleave', () => { this.hover.inside = false; this.updateCursor(); });+ on(c, 'contextmenu', e => e.preventDefault());+ on(window, 'blur', () => { if (this.stroke) this.stroke.ending = true; });++ // macOS Force Touch trackpads report pressure through a WebKit-only event+ on(c, 'webkitmouseforcechanged' as keyof HTMLElementEventMap, (e: Event) => {+ const f = (e as unknown as { webkitForce?: number }).webkitForce;+ if (typeof f === 'number') this.force = { value: clamp((f - 1) / 1.7, 0.04, 1), t: performance.now() };+ });+ }++ private pushSample(e: PointerEvent) {+ const [x, y] = this.toUv(e);+ let p = -1;+ if (e.pointerType === 'pen') p = e.pressure > 0 ? Math.pow(e.pressure, 0.8) : 0.5;+ else if (e.pointerType === 'mouse' && performance.now() - this.force.t < 3000) p = this.force.value;+ this.queue.push({ x, y, p, t: e.timeStamp, tx: e.tiltX || 0, ty: e.tiltY || 0 });+ }++ private trackHover(e: PointerEvent) {+ this.hover.x = e.clientX; this.hover.y = e.clientY;+ this.hover.inside = true; this.hover.type = e.pointerType;+ this.updateCursor();+ }++ private updateCursor() {+ const el = this.cursor;+ if (!el) return;+ if (!this.hover.inside || this.hover.type === 'touch') { 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';+ const b = this.brush;+ const d = Math.max(4, (2 * r * this.view.h) / this.dpr);+ const h = shaped ? Math.max(3, d * b.aspect) : d;+ // doc uv has y up, the screen has y down, so the angle flips+ const angle = shaped && b.rotation !== 'random' ? -(this.stroke?.angle ?? this.lastAngle) : 0;+ el.style.opacity = '1';+ el.style.width = `${d}px`;+ el.style.height = `${h}px`;+ el.style.transform = `translate(${this.hover.x - d / 2}px, ${this.hover.y - h / 2}px) rotate(${angle}rad)`;+ el.style.borderRadius = shaped && b.aspect < 0.6 ? `${h * 0.4}px / 50%` : '50%';+ el.dataset.tool = tool;+ }++ /* -------------------------------------------------------------- strokes */++ private sizeMult() { return Math.pow(3, (this.params.size - 0.5) * 2); }++ /** Footprint radius in document heights. */+ private radius(tool: Tool, pr: number, speed: number) {+ const m = this.sizeMult();+ switch (tool) {+ case 'pen': return (0.0016 + 0.0042 * pr) * clamp(1.12 - speed * 0.3, 0.55, 1.12) * m;+ case 'brush': return this.brushRadius(pr, speed);+ case 'water': return this.brushRadius(pr, speed) * 1.3 * (1 + Math.min(speed, 2.5) * 0.12);+ case 'lift': return (0.012 + 0.03 * pr) * m;+ }+ }++ /** Half the long axis of the current brush's footprint, in document heights. */+ private brushRadius(pr: number, speed: number) {+ const b = this.brush;+ const t = Math.pow(clamp(pr, 0, 1), b.pressureSize);+ // preset sizes describe the full footprint; 0.8 keeps a hard-pressed stroke on a desktop screen sane+ return (b.size[0] + (b.size[1] - b.size[0]) * t) * clamp(1 - speed * b.speedThin, 0.4, 1) * this.sizeMult() * 0.8;+ }++ /** Tip angle for the next dab, in the document frame. */+ private brushAngle(s: Stroke) {+ const b = this.brush;+ let a: number;+ if (b.rotation === 'random') a = Math.random() * Math.PI * 2;+ else if (b.rotation === 'follow') a = Math.atan2(s.dy, s.dx) + b.angle * DEG;+ else a = s.azimuth ?? b.angle * DEG;+ if (b.angleJitter) a += (Math.random() - 0.5) * 2 * b.angleJitter * DEG;+ s.angle = a;+ if (b.rotation !== 'random') this.lastAngle = a;+ return a;+ }++ private pressureOf(s: Stroke, p: number) { return p >= 0 ? p : s.simPressure; }++ private processInput(dt: number) {+ const s = this.stroke;+ if (!s) return;+ s.moved = false;+ const aspect = this.dw / this.dh;+ for (const q of this.queue) {+ // a tilted pen tells us which way it leans; a vertical one tells us nothing+ 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);+ continue;+ }+ const sdt = Math.max(q.t - s.t, 1) / 1000;+ s.t = q.t;+ // light smoothing; mice get a little more than styluses+ const 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 len = Math.hypot(dx, dy);+ 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));+ 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);+ 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);+ }+ 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;+ this.callbacks.onStrokeTool?.(null);+ }+ }++ /** Dab spacing as a fraction of the footprint radius. */+ private spacingFrac(tool: Tool) {+ const b = this.brush;+ // flat tips need tighter spacing: the footprint is thin across one axis+ return tool === 'brush' || tool === 'water' ? b.spacing * Math.sqrt(b.aspect) : 0.5;+ }++ /** One dab of the current tool. `moving` = 0 with `dt` set means a dwell. */+ private stamp(s: Stroke, x: number, y: number, pr: number, vx: number, vy: number, moving: number, dt = 0) {+ const P = this.params;+ const r = this.radius(s.tool, pr, s.speed);+ const dwell = moving ? 1 : dt * 8;+ switch (s.tool) {+ case 'brush': {+ const b = this.brush;+ // the brush empties as it travels; a dry brush skips the valleys of the paper+ const reservoir = 0.25 + 0.75 * Math.exp(-s.travelled / ((1.5 + 3 * P.water) * b.capacity));+ const dryness = clamp(b.grain + (1 - b.grain) * clamp((0.5 - reservoir) * 2.5, 0, 1) * 0.6, 0, 1);+ const grainThr = 0.74 - 0.45 * pr - 0.05 * P.water; // pressing harder reaches into the valleys+ const conc = 0.15 * Math.exp(P.load * 2.8) * reservoir * (0.6 + 0.4 * pr) * b.load;+ // spacing / profile integral -> ~conc in the stroke, normalised for sparse tips+ const norm = clamp(Math.sqrt(0.5 / b.tipMean), 0.7, 2.2);+ const amount = conc * Math.min(b.spacing, 1) / 1.8 * norm * dwell;+ const wet = (0.25 + 0.75 * P.water) * (0.7 + 0.3 * pr) * b.water * (0.4 + 0.6 * reservoir);+ const c = this.pigment.coeffs;+ const c0 = [c[0] * amount, c[1] * amount, c[2] * amount, c[3] * amount];+ const c1 = [c[4] * amount, c[5] * amount, c[6] * amount, this.pigment.white * amount * 1.6];+ this.eachDab(s, x, y, r, (dx, dy, dr, angle) => {+ this.brushInk(dx, dy, dr, angle, c0, c1, dryness, grainThr);+ // soft brushes wet a little beyond the tip; textured ones keep their edges+ this.brushWet(dx, dy, dr * (1 + 0.12 * b.wetRound), angle, wet, b.wetRound, dryness, grainThr);+ });+ if (moving) this.splatVelocity(x, y, r * 1.2, vx, vy, (15 + P.flow * 95) * 0.25 * b.flow);+ break;+ }+ case 'water': {+ const b = this.brush;+ const reservoir = 0.25 + 0.75 * Math.exp(-s.travelled / ((3 + 4 * P.water) * b.capacity));+ const amp = (0.35 + 0.65 * P.water) * (0.5 + 0.5 * pr) * clamp(b.water, 0.6, 1.5) * (0.7 + 0.3 * reservoir);+ const dryness = b.grain * 0.7;+ const grainThr = 0.55 - 0.3 * pr;+ this.eachDab(s, x, y, r, (dx, dy, dr, angle) => {+ this.brushWet(dx, dy, dr, angle, amp, Math.max(b.wetRound, 0.3), dryness, grainThr);+ });+ this.brushNow = { x, y, r };+ if (moving) this.splatVelocity(x, y, r * 1.15, vx, vy, (15 + P.flow * 95) * b.flow);+ else {+ const a = Math.random() * Math.PI * 2, m = (6 + 26 * P.flow) * pr;+ this.splatVelocityRaw(x, y, r * 0.9, Math.cos(a) * m, Math.sin(a) * m);+ }+ break;+ }+ case 'pen': {+ const dens = (0.9 + 1.6 * pr) * clamp(1.25 - s.speed * 0.45, 0.6, 1.25) * (0.5 + P.load);+ const amount = dens * 0.5 / 1.8 * dwell;+ const c = this.pigment.coeffs;+ this.splatInk(x, y, r, [c[0] * amount, c[1] * amount, c[2] * amount, c[3] * amount],+ [c[4] * amount, c[5] * amount, c[6] * amount, this.pigment.white * amount * 3], 2);+ this.splatWet(x, y, r * 2.6, 0.13, 1); // fresh ink is faintly wet, so it feathers a little+ break;+ }+ case 'lift': {+ const amount = Math.min(0.9, 0.22 * dwell);+ this.lift(x, y, r, amount);+ break;+ }+ }+ }++ /* --------------------------------------------------------------- splats */++ /** Run `fn` for every dab of a stamp: one for most brushes, a scattered burst for spatter. */+ private eachDab(s: Stroke, x: number, y: number, r: number, fn: (x: number, y: number, r: number, angle: number) => void) {+ const b = this.brush;+ const aspect = this.dw / this.dh;+ for (let i = 0; i < b.dabs; i++) {+ let dx = x, dy = y, dr = r;+ if (b.scatter > 0) {+ const a = Math.random() * Math.PI * 2, m = Math.sqrt(Math.random()) * b.scatter * r;+ dx += (Math.cos(a) * m) / aspect; dy += Math.sin(a) * m;+ }+ if (b.sizeJitter > 0) dr *= clamp(1 + (Math.random() * 2 - 1) * b.sizeJitter, 0.15, 2);+ fn(dx, dy, dr, this.brushAngle(s));+ }+ }++ private drawStamp(t: Target, x: number, y: number, r: number, angle: number, c0: number[], c1: number[], round: number, grain: number, grainThr: number) {+ const { gl, g } = this;+ const b = this.brush;+ const p = this.programs.stamp;+ p.bind();+ gl.uniform1i(p.u.uTip, g.bindTex(0, this.tipTexture(b)));+ gl.uniform1i(p.u.uPaper, g.bindTex(1, this.paper.tex[0]));+ gl.uniform1f(p.u.uAspect, t.w / t.h);+ gl.uniform2f(p.u.uPoint, x, y);+ gl.uniform1f(p.u.uRadius, r);+ gl.uniform1f(p.u.uTipAspect, b.aspect);+ gl.uniform2f(p.u.uAxis, Math.cos(angle), Math.sin(angle));+ gl.uniform1f(p.u.uRound, round);+ gl.uniform1f(p.u.uGrain, grain);+ gl.uniform1f(p.u.uGrainThr, grainThr);+ gl.uniform4fv(p.u.uColor0, c0);+ gl.uniform4fv(p.u.uColor1, c1);+ g.draw(t, this.stampRect(x, y, r, t.w, t.h, Math.sqrt(1 + b.aspect * b.aspect) * 1.02));+ }++ private brushInk(x: number, y: number, r: number, angle: number, c0: number[], c1: number[], grain: number, grainThr: number) {+ const { gl } = this;+ this.touch(this.stampRect(x, y, r, this.dw, this.dh, 1.5));+ gl.enable(gl.BLEND);+ gl.blendEquation(gl.FUNC_ADD);+ gl.blendFunc(gl.ONE, gl.ONE);+ this.drawStamp(this.ink.read, x, y, r, angle, c0, c1, 0, grain, grainThr);+ gl.disable(gl.BLEND);+ }++ private brushWet(x: number, y: number, r: number, angle: number, amount: number, round: number, grain: number, grainThr: number) {+ const { gl } = this;+ this.touch(this.stampRect(x, y, r, this.dw, this.dh, 1.5));+ gl.enable(gl.BLEND);+ gl.blendEquation(gl.MAX);+ this.drawStamp(this.wet.read, x, y, r, angle, [amount, 0, 0, 0], [0, 0, 0, 0], round, grain, grainThr);+ gl.blendEquation(gl.FUNC_ADD);+ gl.disable(gl.BLEND);+ this.wetPeak = Math.max(this.wetPeak * this.wetDecay(), amount);+ this.lastWet = performance.now();+ }++ /** Rect (in texels of a w×h grid) covered by a stamp of radius r (doc heights). */+ private stampRect(x: number, y: number, r: number, w: number, h: number, extent: number): Rect {+ const e = Math.ceil(r * extent * h) + 2;+ const cx = Math.round(x * w), cy = Math.round(y * h);+ 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) {+ if (rect.x1 <= rect.x0 || rect.y1 <= rect.y0) return;+ const next = union(this.active, rect);+ this.history.protect(0, next, this.snapshotLayers());+ this.active = next;+ this.painted = union(this.painted, rect);+ this.dirty = union(this.dirty, rect);+ if (wake) this.minAwakeUntil = Math.max(this.minAwakeUntil, performance.now() + 250);+ }++ private snapshotLayers() {+ return [this.ink.read.views[0], this.ink.read.views[1], this.wet.read.views[0]];+ }++ private drawSplat(t: Target, x: number, y: number, r: number, c0: number[], c1: number[], hardness: number, extent: number) {+ const { gl, g } = this;+ const p = this.programs.splat;+ p.bind();+ gl.uniform1f(p.u.uAspect, t.w / t.h);+ gl.uniform2f(p.u.uPoint, x, y);+ gl.uniform1f(p.u.uRadius, r);+ gl.uniform1f(p.u.uHardness, hardness);+ gl.uniform4fv(p.u.uColor0, c0);+ gl.uniform4fv(p.u.uColor1, c1);+ g.draw(t, this.stampRect(x, y, r, t.w, t.h, extent));+ }++ private splatInk(x: number, y: number, r: number, c0: number[], c1: number[], hardness: number) {+ const { gl } = this;+ const extent = hardness > 1.4 ? 2.2 : 3.2;+ this.touch(this.stampRect(x, y, r, this.dw, this.dh, extent));+ gl.enable(gl.BLEND);+ gl.blendEquation(gl.FUNC_ADD);+ gl.blendFunc(gl.ONE, gl.ONE);+ this.drawSplat(this.ink.read, x, y, r, c0, c1, hardness, extent);+ gl.disable(gl.BLEND);+ }++ private splatWet(x: number, y: number, r: number, amount: number, hardness: number) {+ const { gl } = this;+ const extent = hardness > 1.4 ? 2.2 : 3.2;+ this.touch(this.stampRect(x, y, r, this.dw, this.dh, extent));+ gl.enable(gl.BLEND);+ gl.blendEquation(gl.MAX);+ this.drawSplat(this.wet.read, x, y, r, [amount, 0, 0, 0], [0, 0, 0, 0], hardness, extent);+ gl.blendEquation(gl.FUNC_ADD);+ gl.disable(gl.BLEND);+ this.wetPeak = Math.max(this.wetPeak * this.wetDecay(), amount);+ this.lastWet = performance.now();+ }++ private splatVelocity(x: number, y: number, r: number, vx: number, vy: number, force: number) {+ let fx = vx * force, fy = vy * force;+ const m = Math.hypot(fx, fy), vmax = 240;+ if (m > vmax) { fx *= vmax / m; fy *= vmax / m; }+ this.flowSpeed = Math.max(this.flowSpeed, Math.min(m, vmax));+ this.splatVelocityRaw(x, y, r, fx, fy);+ }++ private splatVelocityRaw(x: number, y: number, r: number, fx: number, fy: number) {+ const { gl } = this;+ gl.enable(gl.BLEND);+ gl.blendEquation(gl.FUNC_ADD);+ gl.blendFunc(gl.ONE, gl.ONE);+ this.drawSplat(this.velocity.read, x, y, r, [fx, fy, 0, 0], [0, 0, 0, 0], 1, 3);+ gl.disable(gl.BLEND);+ }++ private lift(x: number, y: number, r: number, amount: number) {+ const { gl, g } = this;+ const rect = this.stampRect(x, y, r, this.dw, this.dh, 2);+ this.touch(rect);+ const p = this.programs.lift;+ p.bind();+ gl.uniform1f(p.u.uAspect, this.dw / this.dh);+ gl.uniform2f(p.u.uPoint, x, y);+ gl.uniform1f(p.u.uRadius, r);+ gl.enable(gl.BLEND);+ gl.blendEquation(gl.FUNC_ADD);+ gl.blendFunc(gl.ZERO, gl.ONE_MINUS_SRC_COLOR);+ gl.uniform1f(p.u.uAmount, amount);+ g.draw(this.ink.read, rect);+ gl.uniform1f(p.u.uAmount, amount * 0.8); // the tissue soaks up water too+ g.draw(this.wet.read, rect);+ gl.disable(gl.BLEND);+ }++ /* ----------------------------------------------------------- simulation */++ private dryTau() { return this.fixTimer > 0 ? 0.25 : 2 + (1 - this.params.dry) * 16; }++ private wetDecay() { return Math.exp(-(performance.now() - this.lastWet) / 1000 / this.dryTau()); }++ /** Time (ms) until standing water everywhere has dried below the threshold. */+ private wetUntil() {+ if (this.wetPeak <= WET_THRESHOLD) return this.lastWet;+ return this.lastWet + this.dryTau() * Math.log(this.wetPeak / WET_THRESHOLD) * 1000;+ }++ private beginStep() {+ const now = performance.now();+ const meta: HistoryMeta = { wetAgo: now - this.lastWet, wetPeak: this.wetPeak, active: this.active ? { ...this.active } : null };+ this.history.begin(meta);+ if (this.active) this.history.protect(0, this.active, this.snapshotLayers());+ this.callbacks.onHistoryChange?.(true);+ }++ private step(dt: number) {+ const { gl, g, programs: P } = this;+ const fixing = this.fixTimer > 0;+ if (fixing) {+ this.fixTimer -= dt;+ if (this.fixTimer <= 0) {+ // everything has flash-dried: let the sim sleep so the next stroke starts+ // from a small active region (and a small undo snapshot)+ this.wetPeak = 0;+ this.minAwakeUntil = 0;+ this.painted = null;+ }+ }+ const vel = this.velocity;+ const simTexel = [1 / vel.w, 1 / vel.h];+ const texel = [1 / this.dw, 1 / this.dh];+ const flow = this.params.flow;+ const rect = this.active!;++ P.advectVelocity.bind();+ gl.uniform1i(P.advectVelocity.u.uVelocity, g.bindTex(0, vel.read.tex[0]));+ gl.uniform1i(P.advectVelocity.u.uWet, g.bindTex(1, this.wet.read.tex[0]));+ gl.uniform2fv(P.advectVelocity.u.uTexel, simTexel);+ gl.uniform1f(P.advectVelocity.u.uDt, dt);+ gl.uniform1f(P.advectVelocity.u.uDissipation, Math.exp(-dt * (3.0 - flow * 2.4)) * (fixing ? Math.exp(-dt * 7) : 1));+ g.draw(vel.write); vel.swap();++ P.curl.bind();+ gl.uniform1i(P.curl.u.uVelocity, g.bindTex(0, vel.read.tex[0]));+ gl.uniform2fv(P.curl.u.uTexel, simTexel);+ g.draw(this.curl);++ P.vorticity.bind();+ gl.uniform1i(P.vorticity.u.uVelocity, g.bindTex(0, vel.read.tex[0]));+ gl.uniform1i(P.vorticity.u.uCurl, g.bindTex(1, this.curl.tex[0]));+ gl.uniform2fv(P.vorticity.u.uTexel, simTexel);+ gl.uniform1f(P.vorticity.u.uCurlAmount, 4 + flow * 22);+ gl.uniform1f(P.vorticity.u.uDt, dt);+ g.draw(vel.write); vel.swap();++ P.divergence.bind();+ gl.uniform1i(P.divergence.u.uVelocity, g.bindTex(0, vel.read.tex[0]));+ gl.uniform2fv(P.divergence.u.uTexel, simTexel);+ g.draw(this.divergence);++ P.scale.bind();+ gl.uniform1i(P.scale.u.uTex, g.bindTex(0, this.pressure.read.tex[0]));+ gl.uniform1f(P.scale.u.uValue, 0.8);+ g.draw(this.pressure.write); this.pressure.swap();++ P.pressure.bind();+ gl.uniform1i(P.pressure.u.uDivergence, g.bindTex(1, this.divergence.tex[0]));+ gl.uniform2fv(P.pressure.u.uTexel, simTexel);+ for (let i = 0; i < PRESSURE_ITERATIONS; i++) {+ gl.uniform1i(P.pressure.u.uPressure, g.bindTex(0, this.pressure.read.tex[0]));+ g.draw(this.pressure.write); this.pressure.swap();+ }++ P.gradient.bind();+ gl.uniform1i(P.gradient.u.uPressure, g.bindTex(0, this.pressure.read.tex[0]));+ gl.uniform1i(P.gradient.u.uVelocity, g.bindTex(1, vel.read.tex[0]));+ gl.uniform2fv(P.gradient.u.uTexel, simTexel);+ g.draw(vel.write); vel.swap();++ // water: dries on a timescale set by the DRY slider (flash-dries while fixing)+ P.advectWet.bind();+ gl.uniform1i(P.advectWet.u.uVelocity, g.bindTex(0, vel.read.tex[0]));+ gl.uniform1i(P.advectWet.u.uWet, g.bindTex(1, this.wet.read.tex[0]));+ gl.uniform2fv(P.advectWet.u.uSimTexel, simTexel);+ gl.uniform2fv(P.advectWet.u.uTexel, texel);+ gl.uniform1f(P.advectWet.u.uDt, dt);+ gl.uniform1f(P.advectWet.u.uDecay, Math.exp(-dt / this.dryTau()));+ gl.uniform1f(P.advectWet.u.uSpread, 0.12);+ g.draw(this.wet.write, rect); this.wet.swap();++ // fixing: bleach under white gouache, then settle mobile pigment into the paper+ const settle = fixing ? 1 - Math.exp(-dt * 5) : 0;+ if (fixing) {+ gl.enable(gl.BLEND);+ gl.blendEquation(gl.FUNC_ADD);+ gl.blendFunc(gl.ZERO, gl.SRC_COLOR);+ P.bleach.bind();+ gl.uniform1i(P.bleach.u.uInkB, g.bindTex(0, this.ink.read.tex[1]));+ gl.uniform1f(P.bleach.u.uSettle, settle);+ g.draw(this.fixed, rect);+ gl.blendFunc(gl.ONE, gl.ONE);+ P.settle.bind();+ gl.uniform1i(P.settle.u.uInkA, g.bindTex(0, this.ink.read.tex[0]));+ gl.uniform1i(P.settle.u.uInkB, g.bindTex(1, this.ink.read.tex[1]));+ gl.uniform1f(P.settle.u.uSettle, settle);+ g.draw(this.fixed, rect);+ gl.disable(gl.BLEND);+ }++ // pigment: flows, bleeds and gathers at drying edges, only where wet+ const p = P.advectInk;+ p.bind();+ gl.uniform1i(p.u.uVelocity, g.bindTex(0, vel.read.tex[0]));+ gl.uniform1i(p.u.uInkA, g.bindTex(1, this.ink.read.tex[0]));+ gl.uniform1i(p.u.uInkB, g.bindTex(2, this.ink.read.tex[1]));+ gl.uniform1i(p.u.uWet, g.bindTex(3, this.wet.read.tex[0]));+ gl.uniform2fv(p.u.uSimTexel, simTexel);+ gl.uniform2fv(p.u.uTexel, texel);+ gl.uniform1f(p.u.uDt, dt);+ gl.uniform1f(p.u.uBleed, this.params.bleed);+ gl.uniform1f(p.u.uEdge, this.params.edge * 1.4);+ gl.uniform1f(p.u.uAspect, this.dw / this.dh);+ gl.uniform1f(p.u.uKeep, 1 - settle);+ gl.uniform3f(p.u.uBrush, this.brushNow.x, this.brushNow.y, this.brushNow.r);+ g.draw(this.ink.write, rect); this.ink.swap();++ this.dirty = union(this.dirty, rect);+ }++ /** Make both halves of the ping-pong buffers identical, then stop simulating. */+ private sleep() {+ const rect = this.active;+ if (rect) {+ const { g } = this;+ const w = rect.x1 - rect.x0, h = rect.y1 - rect.y0;+ for (const d of [this.ink, this.wet])+ d.read.views.forEach((v, i) => g.blit(v, rect.x0, rect.y0, d.write.views[i], rect.x0, rect.y0, w, h));+ }+ for (const d of [this.velocity, this.pressure]) { this.g.clearTarget(d.read); this.g.clearTarget(d.write); }+ this.active = null;+ this.wetPeak = 0;+ this.flowSpeed = 0;+ }++ /* -------------------------------------------------------------- display */++ private drawDisplay(target: Target | null, view: { x: number; y: number; w: number; h: number }, scissor: Rect | null) {+ const { gl, g } = this;+ const p = this.programs.display;+ p.bind();+ gl.uniform1i(p.u.uInkA, g.bindTex(0, this.ink.read.tex[0]));+ gl.uniform1i(p.u.uInkB, g.bindTex(1, this.ink.read.tex[1]));+ gl.uniform1i(p.u.uFixedA, g.bindTex(2, this.fixed.tex[0]));+ gl.uniform1i(p.u.uFixedB, g.bindTex(3, this.fixed.tex[1]));+ gl.uniform1i(p.u.uWet, g.bindTex(4, this.wet.read.tex[0]));+ gl.uniform1i(p.u.uPaper, g.bindTex(5, this.paper.tex[0]));+ gl.uniform4f(p.u.uView, view.x, view.y, view.w, view.h);+ gl.uniform2f(p.u.uTexel, 1 / this.dw, 1 / this.dh);+ gl.uniform1f(p.u.uGranulation, this.params.granulation * 0.55);+ gl.uniform1f(p.u.uEdgeDarken, 0.8);+ gl.uniform3fv(p.u.uDesk, DESK);+ g.draw(target, scissor, this.canvasSize);+ }++ private render() {+ if (!this.dirtyAll && !this.dirty) return;+ let rect: Rect | null = null;+ if (!this.dirtyAll && this.dirty) {+ const v = this.view, d = this.dirty;+ rect = {+ x0: Math.floor(v.x + (d.x0 / this.dw) * v.w) - 2, y0: Math.floor(v.y + (d.y0 / this.dh) * v.h) - 2,+ x1: Math.ceil(v.x + (d.x1 / this.dw) * v.w) + 2, y1: Math.ceil(v.y + (d.y1 / this.dh) * v.h) + 2,+ };+ }+ this.drawDisplay(null, this.view, rect);+ this.dirty = null;+ this.dirtyAll = false;+ }++ /* ------------------------------------------------------------ main loop */++ private schedule() {+ if (!this.raf) {+ this.lastFrame = performance.now();+ this.raf = requestAnimationFrame(this.frame);+ }+ }++ private frame = (now: number) => {+ this.raf = 0;+ const dt = clamp((now - this.lastFrame) / 1000, 1 / 240, 1 / 30);+ this.lastFrame = now;+ this.brushNow.r = 0;++ this.processInput(dt);++ const awake = this.active !== null &&+ (this.stroke !== null || this.fixTimer > 0 || now < this.minAwakeUntil || now < this.wetUntil());+ if (awake) {+ // Grow the simulated region as fast as the wet front can move: slow diffusive+ // creep plus a share of the (decaying) flow speed+ this.flowSpeed *= Math.exp(-dt * (3.0 - this.params.flow * 2.4));+ // (velocity is masked to ~0 at the wet front, so the front itself only creeps)+ this.growCarry += 0.4 + Math.min(3, 0.15 * this.flowSpeed * dt * (this.dw / this.velocity.w));+ const grow = Math.floor(this.growCarry);+ 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.step(dt);+ }+ this.render();+ if (!awake && this.active) this.sleep();+ if (awake || this.stroke) this.schedule();+ };+}diff --git a/src/engine/brushes.ts b/src/engine/brushes.tsnew file mode 100644index 0000000..6fbfc20--- /dev/null+++ b/src/engine/brushes.ts@@ -0,0 +1,319 @@+// Brushes: a tip texture (the footprint of one dab) plus the behaviour that turns+// dabs into a stroke. Tips are procedural, generated once at startup in tip space:+// a square from -1..1 where x is the brush's long axis and y its short axis; the+// engine maps that square onto a rotated ellipse of the brush's aspect ratio.++export type Rotation =+ | 'follow' // long axis follows the stroke direction (+ angle)+ | 'fixed' // held at a fixed angle, or at the pen's tilt azimuth when available+ | 'random'; // every dab lands at a random angle++export interface BrushPreset {+ id: string;+ name: string;+ hint: string;+ /** Generator in tip space, or raw 8-bit tip data (custom imported brushes). */+ tip: ((n: number, noise: Noise) => Float32Array) | Uint8Array;+ /** short axis / long axis of the footprint (1 = round). */+ aspect: number;+ rotation: Rotation;+ /** Degrees. For 'follow' this is an offset from the stroke direction. */+ angle: number;+ angleJitter: number;+ /** Footprint radius (half the long axis, in document heights) at pressure 0 and 1. */+ size: [number, number];+ /** Exponent on pressure for size: < 1 responds early, > 1 only when pressing hard. */+ pressureSize: number;+ /** How much a fast stroke thins the line. */+ speedThin: number;+ /** Distance between dabs as a fraction of the radius. */+ spacing: number;+ /** Random offset per dab as a fraction of the radius. */+ scatter: number;+ /** Dabs per stamp (spatter). */+ dabs: number;+ /** Random radius variation per dab, 0..1. */+ sizeJitter: number;+ /** Multipliers on the global sliders. */+ water: number;+ load: number;+ flow: number;+ /** How far the brush paints before it runs dry, relative to the round. */+ capacity: number;+ /** 0..1: how much the paper's tooth gates the deposit (dry brush skips the valleys). */+ grain: number;+ /** 0..1: how much the water footprint is a soft ellipse rather than the textured tip. */+ wetRound: number;+ custom?: boolean;+}++/** A preset with its tip baked to 8-bit data. */+export interface Brush extends Omit<BrushPreset, 'tip'> {+ tipSize: number;+ tipData: Uint8Array;+ /** Mean tip value over the tip square; used to normalise deposit between brushes. */+ tipMean: number;+}++export const TIP_SIZE = 192;+const DEG = Math.PI / 180;++/* ----------------------------------------------------------------- noise */++export class Noise {+ private state: number;+ constructor(private seed: number) { this.state = seed | 0 || 1; }++ /** mulberry32 */+ rnd(): number {+ this.state = (this.state + 0x6d2b79f5) | 0;+ let t = Math.imul(this.state ^ (this.state >>> 15), 1 | this.state);+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ }++ hash(ix: number, iy: number): number {+ let h = (Math.imul(ix, 374761393) + Math.imul(iy, 668265263) + Math.imul(this.seed, 982451653)) | 0;+ h = Math.imul(h ^ (h >>> 13), 1274126177);+ return ((h ^ (h >>> 16)) >>> 0) / 4294967296;+ }++ value(x: number, y: number): number {+ const ix = Math.floor(x), iy = Math.floor(y);+ let fx = x - ix, fy = y - iy;+ fx = fx * fx * (3 - 2 * fx); fy = fy * fy * (3 - 2 * fy);+ const a = this.hash(ix, iy), b = this.hash(ix + 1, iy), c = this.hash(ix, iy + 1), d = this.hash(ix + 1, iy + 1);+ return a + (b - a) * fx + (c - a) * fy + (a - b - c + d) * fx * fy;+ }++ fbm(x: number, y: number, octaves = 4): number {+ let v = 0, amp = 0.5, sum = 0;+ for (let i = 0; i < octaves; i++) {+ v += amp * this.value(x, y); sum += amp;+ x = x * 2.03 + 17.1; y = y * 2.01 + 9.7; amp *= 0.5;+ }+ return v / sum;+ }++ /** Distances to the nearest and second-nearest jittered cell point. */+ worley(x: number, y: number): [number, number] {+ const ix = Math.floor(x), iy = Math.floor(y);+ let f1 = 9, f2 = 9;+ for (let j = -1; j <= 1; j++) for (let i = -1; i <= 1; i++) {+ const cx = ix + i, cy = iy + j;+ const px = cx + this.hash(cx, cy), py = cy + this.hash(cx + 71, cy + 13);+ const d = Math.hypot(px - x, py - y);+ if (d < f1) { f2 = f1; f1 = d; } else if (d < f2) f2 = d;+ }+ return [f1, f2];+ }+}++/* ---------------------------------------------------------- tip helpers */++const clamp01 = (v: number) => Math.min(1, Math.max(0, v));+const smoothstep = (a: number, b: number, x: number) => { const t = clamp01((x - a) / (b - a)); return t * t * (3 - 2 * t); };+/** 1 inside, fading to 0 between radius `hard` and 1. */+const soft = (r: number, hard: number) => 1 - smoothstep(hard, 1, r);++type TipFn = (u: number, v: number, r: number, ang: number) => number;++function tip(fn: TipFn): (n: number) => Float32Array {+ return n => {+ const out = new Float32Array(n * n);+ for (let j = 0; j < n; j++) {+ const v = ((j + 0.5) / n) * 2 - 1;+ for (let i = 0; i < n; i++) {+ const u = ((i + 0.5) / n) * 2 - 1;+ out[j * n + i] = clamp01(fn(u, v, Math.hypot(u, v), Math.atan2(v, u)));+ }+ }+ return out;+ };+}++/** Sum of thin hairs (line segments) with a gaussian cross-section. */+function hairs(segments: [number, number, number, number][], width: number, u: number, v: number) {+ let sum = 0;+ for (const [ax, ay, bx, by] of segments) {+ const dx = bx - ax, dy = by - ay, len2 = dx * dx + dy * dy;+ const t = clamp01(((u - ax) * dx + (v - ay) * dy) / len2);+ const d = Math.hypot(u - ax - dx * t, v - ay - dy * t);+ sum += Math.exp(-(d * d) / (width * width));+ }+ return sum;+}++/* --------------------------------------------------------------- presets */++const BASE: Omit<BrushPreset, 'id' | 'name' | 'hint' | 'tip'> = {+ aspect: 1, rotation: 'fixed', angle: 0, angleJitter: 0,+ size: [0.011, 0.05], pressureSize: 1, speedThin: 0,+ spacing: 0.3, scatter: 0, dabs: 1, sizeJitter: 0,+ water: 1, load: 1, flow: 1, capacity: 1, grain: 0, wetRound: 0.6,+};++const define = (p: Partial<BrushPreset> & Pick<BrushPreset, 'id' | 'name' | 'hint' | 'tip'>): BrushPreset => ({ ...BASE, ...p });++export const BRUSH_PRESETS: BrushPreset[] = [+ define({+ id: 'round', name: 'Round', hint: 'A pointed round #8: the everyday brush',+ tip: (n, N) => tip((u, v, r, ang) => {+ const rr = r * (1 + 0.08 * (N.fbm(ang * 0.8 + 3, r * 2.5) * 2 - 1));+ return soft(rr, 0.3) * (1 - 0.12 * N.fbm(u * 5, v * 5));+ })(n),+ }),+ define({+ id: 'detail', name: 'Detail', hint: 'A small round #2 for fine work',+ size: [0.0025, 0.014], pressureSize: 0.9, water: 0.7, load: 1.15, capacity: 0.6, spacing: 0.28, wetRound: 0.8,+ tip: n => tip((_u, _v, r) => soft(r, 0.55))(n),+ }),+ define({+ id: 'rigger', name: 'Rigger', hint: 'Long thin liner: holds a lot of paint for continuous lines',+ size: [0.0015, 0.0065], pressureSize: 0.7, speedThin: 0.08, water: 0.55, load: 1.3, capacity: 1.8, spacing: 0.25, wetRound: 0.9,+ tip: n => tip((_u, _v, r) => soft(r, 0.65))(n),+ }),+ define({+ id: 'flat', name: 'Flat', hint: 'A ½" flat: thick or thin depending on direction; tilt the pen to turn it',+ aspect: 0.26, rotation: 'fixed', angle: 40, angleJitter: 1.5,+ size: [0.02, 0.038], pressureSize: 1.4, spacing: 0.14, water: 0.8, wetRound: 0.25,+ tip: (n, N) => tip((u, v) => {+ const chisel = 0.06 * (N.fbm(v * 3 + 9, 2, 3) * 2 - 1);+ const ex = 1 - smoothstep(0.8, 0.98, Math.abs(u) + chisel);+ const ey = 1 - smoothstep(0.8, 1, Math.abs(v));+ const bristles = 1 - 0.4 * smoothstep(0.4, 0.75, N.fbm(u * 10, v * 0.7, 3));+ return ex * ey * bristles;+ })(n),+ }),+ define({+ id: 'hake', name: 'Hake', hint: 'Wide soft goat-hair wash brush; streaky, carries lots of water',+ aspect: 0.2, rotation: 'follow', angle: 90, angleJitter: 2,+ size: [0.05, 0.08], pressureSize: 1.6, spacing: 0.1, water: 1.6, load: 0.75, flow: 1.2, capacity: 2.2, wetRound: 0.5,+ tip: (n, N) => tip((u, v) => {+ const ex = 1 - smoothstep(0.72, 1, Math.abs(u) + 0.1 * (N.fbm(v * 2 + 4, 1, 3) * 2 - 1));+ const ey = 1 - smoothstep(0.55, 1, Math.abs(v));+ const bristles = 1 - 0.65 * smoothstep(0.35, 0.7, N.fbm(u * 16, v * 0.9, 3));+ const gaps = smoothstep(0.25, 0.45, N.fbm(u * 7 + 20, v * 0.4, 2));+ return ex * ey * bristles * (0.4 + 0.6 * gaps);+ })(n),+ }),+ define({+ id: 'filbert', name: 'Filbert', hint: 'Oval tip: soft rounded marks that change with direction',+ aspect: 0.55, rotation: 'fixed', angle: 25, angleJitter: 2,+ size: [0.012, 0.036], spacing: 0.18, wetRound: 0.5,+ tip: (n, N) => tip((u, _v, r) => soft(r, 0.45) * (1 - 0.25 * N.fbm(u * 8, 0.7, 3)))(n),+ }),+ define({+ id: 'mop', name: 'Mop', hint: 'Big squirrel mop: floods the paper for washes',+ size: [0.03, 0.075], pressureSize: 0.8, spacing: 0.25, water: 1.8, load: 0.8, flow: 1.3, capacity: 2.6, wetRound: 0.7,+ tip: (n, N) => tip((u, v, r, ang) => {+ const rr = r * (1 + 0.22 * (N.fbm(ang * 1.2, 1.7, 3) * 2 - 1));+ return Math.pow(soft(rr, 0.1), 1.3) * (1 - 0.25 * N.fbm(u * 3, v * 3));+ })(n),+ }),+ define({+ id: 'dry', name: 'Dry Brush', hint: 'Scruffy bristles with little water: skips over the paper tooth',+ aspect: 0.75, rotation: 'follow', angle: 0, angleJitter: 8,+ size: [0.012, 0.036], spacing: 0.12, water: 0.2, load: 1.1, capacity: 0.6, grain: 0.9, wetRound: 0,+ tip: (n, N) => tip((u, v, r) => {+ const holes = smoothstep(0.42, 0.62, N.fbm(u * 5.5, v * 5.5, 5));+ const streaks = 1 - 0.3 * N.fbm(u * 14, v * 1.2, 3);+ return soft(r, 0.2) * holes * streaks;+ })(n),+ }),+ define({+ id: 'fan', name: 'Fan', hint: 'Splayed hairs: grass, fur and fine parallel texture',+ aspect: 0.5, rotation: 'follow', angle: 90, angleJitter: 3,+ size: [0.02, 0.045], pressureSize: 1.2, spacing: 0.1, water: 0.3, load: 1.0, capacity: 0.8, grain: 0.5, wetRound: 0,+ tip: (n, N) => {+ const segs: [number, number, number, number][] = [];+ for (let i = 0; i < 13; i++) {+ const x = -0.95 + (1.9 * i) / 12 + (N.rnd() - 0.5) * 0.08;+ segs.push([x * 0.25, -1.3, x, 0.75 + N.rnd() * 0.25]);+ }+ return tip((u, v) => Math.min(1, hairs(segs, 0.045, u, v)) * (1 - smoothstep(0.85, 1, Math.abs(v))))(n);+ },+ }),+ define({+ id: 'sponge', name: 'Sponge', hint: 'Natural sponge: dabbed cellular texture for foliage and stone',+ rotation: 'random', size: [0.025, 0.05], pressureSize: 0.7, spacing: 0.55, scatter: 0.3, sizeJitter: 0.3,+ water: 0.5, load: 0.9, capacity: 1.2, grain: 0.45, wetRound: 0.1,+ tip: (n, N) => tip((u, v, r) => {+ const [f1, f2] = N.worley(u * 4.5, v * 4.5);+ return soft(r, 0.55) * smoothstep(0.03, 0.14, f2 - f1) * (0.55 + 0.45 * N.fbm(u * 7, v * 7, 3));+ })(n),+ }),+ define({+ id: 'spatter', name: 'Spatter', hint: 'Flicked droplets: sparse at a light touch, dense when pressing',+ rotation: 'random', size: [0.003, 0.008], pressureSize: 0.8, spacing: 4.5, scatter: 10, dabs: 5, sizeJitter: 0.75,+ water: 1.3, load: 1.1, capacity: 1.5, wetRound: 0,+ tip: n => tip((_u, _v, r) => soft(r, 0.72))(n),+ }),+ define({+ id: 'sumi', name: 'Sumi', hint: 'Oriental brush: hairline to broad with pressure, fibrous edges',+ size: [0.002, 0.052], pressureSize: 1.3, speedThin: 0.12, spacing: 0.22, water: 0.8, load: 1.3, capacity: 1.2, wetRound: 0.75,+ tip: (n, N) => tip((_u, _v, r, ang) => {+ const rr = r * (1 + 0.35 * (N.fbm(ang * 2.5 + r * 2, 1, 3) * 2 - 1));+ return Math.pow(soft(rr, 0.25), 1.5) * (1 - 0.3 * N.fbm(r * 8, ang * 3, 3));+ })(n),+ }),+ define({+ id: 'dagger', name: 'Dagger', hint: 'Sword liner: calligraphic strokes from a tapered blade',+ aspect: 0.38, rotation: 'fixed', angle: 55, angleJitter: 1,+ size: [0.006, 0.03], pressureSize: 1.1, speedThin: 0.06, spacing: 0.15, load: 1.1, capacity: 1.4, wetRound: 0.3,+ tip: n => tip((u, v) => {+ const t = (u + 1) / 2;+ const w = Math.sqrt(Math.max(0, 4 * t * (1 - t))) * (1 - 0.5 * t);+ return 1 - smoothstep(w * 0.8, w, Math.abs(v));+ })(n),+ }),+ define({+ id: 'stipple', name: 'Stipple', hint: 'A cluster of hard dots: pointillist texture',+ rotation: 'random', size: [0.015, 0.035], pressureSize: 0.8, spacing: 0.7, scatter: 0.2, sizeJitter: 0.2,+ water: 0.35, load: 1.1, grain: 0.3, wetRound: 0,+ tip: (n, N) => {+ const dots: [number, number, number][] = [];+ while (dots.length < 46) {+ const x = N.rnd() * 2 - 1, y = N.rnd() * 2 - 1;+ if (Math.hypot(x, y) < 0.86) dots.push([x, y, 0.06 + N.rnd() * 0.08]);+ }+ return tip((u, v) => {+ let m = 0;+ for (const [x, y, rd] of dots) m = Math.max(m, soft(Math.hypot(u - x, v - y) / rd, 0.6));+ return m;+ })(n);+ },+ }),+];++/** Behaviour for an imported texture: a textured round that follows the stroke. */+export const CUSTOM_BASE: Omit<BrushPreset, 'id' | 'name' | 'hint' | 'tip'> = {+ ...BASE, rotation: 'follow', angleJitter: 4, spacing: 0.2, wetRound: 0.4,+};++/* ------------------------------------------------------------- building */++export function buildBrush(preset: BrushPreset, seed = 7): Brush {+ const { tip: source, ...rest } = preset;+ let tipData: Uint8Array, tipSize: number;+ if (source instanceof Uint8Array) {+ tipData = source;+ tipSize = Math.round(Math.sqrt(source.length));+ } else {+ tipSize = TIP_SIZE;+ const f = source(tipSize, new Noise(seed + hashString(preset.id)));+ tipData = new Uint8Array(f.length);+ for (let i = 0; i < f.length; i++) tipData[i] = Math.round(clamp01(f[i]) * 255);+ }+ let sum = 0;+ for (let i = 0; i < tipData.length; i++) sum += tipData[i];+ return { ...rest, tipSize, tipData, tipMean: Math.max(0.01, sum / (255 * tipData.length)) };+}++function hashString(s: string) {+ let h = 2166136261;+ for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 16777619);+ return h >>> 0;+}++export { DEG as DEGREES };diff --git a/src/engine/gl.ts b/src/engine/gl.tsnew file mode 100644index 0000000..ef37905--- /dev/null+++ b/src/engine/gl.ts@@ -0,0 +1,181 @@+// Minimal WebGL2 plumbing: full-screen-triangle programs and (multi-)render targets.++export const QUAD_VS = `#version 300 es+precision highp float;+layout(location=0) in vec2 aPos;+out vec2 vUv;+void main(){ vUv = aPos * 0.5 + 0.5; gl_Position = vec4(aPos, 0.0, 1.0); }`;++export interface Program {+ bind(): void;+ /** Uniform locations by name (missing/optimised-out uniforms are null). */+ u: Record<string, WebGLUniformLocation | null>;+}++export interface Rect { x0: number; y0: number; x1: number; y1: number }++export interface Format { internal: number; format: number; type: number }++/** A framebuffer with one or more colour attachments of identical size. */+export interface Target {+ w: number;+ h: number;+ fbo: WebGLFramebuffer;+ tex: WebGLTexture[];+ /** Single-attachment framebuffers per texture, used as blit sources/destinations. */+ views: WebGLFramebuffer[];+}++export interface DoubleTarget {+ w: number;+ h: number;+ readonly read: Target;+ readonly write: Target;+ swap(): void;+}++export class GL {+ readonly gl: WebGL2RenderingContext;+ private vs: WebGLShader;+ private resources: (() => void)[] = [];++ constructor(gl: WebGL2RenderingContext) {+ this.gl = gl;+ this.vs = this.compile(gl.VERTEX_SHADER, QUAD_VS);+ const vao = gl.createVertexArray();+ gl.bindVertexArray(vao);+ const vbo = gl.createBuffer();+ gl.bindBuffer(gl.ARRAY_BUFFER, vbo);+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW);+ gl.enableVertexAttribArray(0);+ gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);+ }++ private compile(type: number, src: string): WebGLShader {+ const { gl } = this;+ const s = gl.createShader(type)!;+ gl.shaderSource(s, src);+ gl.compileShader(s);+ if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) {+ const numbered = src.split('\n').map((l, i) => `${i + 1}: ${l}`).join('\n');+ throw new Error(`${gl.getShaderInfoLog(s)}\n${numbered}`);+ }+ return s;+ }++ program(fs: string): Program {+ const { gl } = this;+ const p = gl.createProgram()!;+ gl.attachShader(p, this.vs);+ gl.attachShader(p, this.compile(gl.FRAGMENT_SHADER, fs));+ gl.linkProgram(p);+ if (!gl.getProgramParameter(p, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(p) ?? 'link failed');+ const u: Record<string, WebGLUniformLocation | null> = {};+ const n = gl.getProgramParameter(p, gl.ACTIVE_UNIFORMS);+ for (let i = 0; i < n; i++) {+ const info = gl.getActiveUniform(p, i)!;+ u[info.name.replace(/\[0\]$/, '')] = gl.getUniformLocation(p, info.name);+ }+ return { u, bind: () => gl.useProgram(p) };+ }++ target(w: number, h: number, formats: Format[], filter: number): Target {+ const { gl } = this;+ const fbo = gl.createFramebuffer()!;+ gl.bindFramebuffer(gl.FRAMEBUFFER, fbo);+ const tex: WebGLTexture[] = [];+ const views: WebGLFramebuffer[] = [];+ formats.forEach((f, i) => {+ const t = gl.createTexture()!;+ gl.bindTexture(gl.TEXTURE_2D, t);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filter);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filter);+ 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);+ gl.texStorage2D(gl.TEXTURE_2D, 1, f.internal, w, h);+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, t, 0);+ tex.push(t);+ });+ gl.drawBuffers(formats.map((_, i) => gl.COLOR_ATTACHMENT0 + i));+ const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);+ if (status !== gl.FRAMEBUFFER_COMPLETE) throw new Error(`framebuffer incomplete: 0x${status.toString(16)}`);+ for (const t of tex) {+ const v = gl.createFramebuffer()!;+ gl.bindFramebuffer(gl.FRAMEBUFFER, v);+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, t, 0);+ views.push(v);+ }+ const target = { w, h, fbo, tex, views };+ this.clearTarget(target);+ this.resources.push(() => {+ gl.deleteFramebuffer(fbo);+ views.forEach(v => gl.deleteFramebuffer(v));+ tex.forEach(t => gl.deleteTexture(t));+ });+ return target;+ }++ double(w: number, h: number, formats: Format[], filter: number): DoubleTarget {+ let a = this.target(w, h, formats, filter);+ let b = this.target(w, h, formats, filter);+ return {+ w, h,+ get read() { return a; },+ get write() { return b; },+ swap() { const t = a; a = b; b = t; },+ };+ }++ clearTarget(t: Target, rect?: Rect) {+ const { gl } = this;+ gl.bindFramebuffer(gl.FRAMEBUFFER, t.fbo);+ if (rect) this.scissor(rect);+ gl.clearColor(0, 0, 0, 0);+ gl.clear(gl.COLOR_BUFFER_BIT);+ gl.disable(gl.SCISSOR_TEST);+ }++ scissor(r: Rect) {+ const { gl } = this;+ gl.enable(gl.SCISSOR_TEST);+ gl.scissor(r.x0, r.y0, Math.max(0, r.x1 - r.x0), Math.max(0, r.y1 - r.y0));+ }++ /** Draw the full-screen triangle into `target` (or the canvas), optionally scissored. */+ draw(target: Target | null, rect?: Rect | null, canvasSize?: [number, number]) {+ const { gl } = this;+ if (target) {+ gl.bindFramebuffer(gl.FRAMEBUFFER, target.fbo);+ gl.viewport(0, 0, target.w, target.h);+ } else {+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);+ gl.viewport(0, 0, canvasSize![0], canvasSize![1]);+ }+ if (rect) this.scissor(rect);+ gl.drawArrays(gl.TRIANGLES, 0, 3);+ if (rect) gl.disable(gl.SCISSOR_TEST);+ }++ bindTex(unit: number, tex: WebGLTexture): number {+ const { gl } = this;+ gl.activeTexture(gl.TEXTURE0 + unit);+ gl.bindTexture(gl.TEXTURE_2D, tex);+ return unit;+ }++ /** Copy a rectangle between single-texture framebuffers (same format). */+ blit(src: WebGLFramebuffer, sx: number, sy: number, dst: WebGLFramebuffer, dx: number, dy: number, w: number, h: number) {+ const { gl } = this;+ gl.bindFramebuffer(gl.READ_FRAMEBUFFER, src);+ gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, dst);+ gl.blitFramebuffer(sx, sy, sx + w, sy + h, dx, dy, dx + w, dy + h, gl.COLOR_BUFFER_BIT, gl.NEAREST);+ gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);+ gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null);+ }++ /** Free every target created so far (used on document re-creation). */+ disposeTargets() {+ this.resources.forEach(f => f());+ this.resources = [];+ }+}diff --git a/src/engine/history.ts b/src/engine/history.tsnew file mode 100644index 0000000..dea8900--- /dev/null+++ b/src/engine/history.ts@@ -0,0 +1,116 @@+import type { Format, GL, Rect, Target } from './gl';++const TILE = 128;++/** A set of layers snapshotted together, with its own atlas and slot pool. */+class Pool {+ readonly atlas: Target[];+ readonly cols: number;+ readonly free: number[] = [];++ constructor(g: GL, tiles: number, formats: Format[]) {+ const maxTex = g.gl.getParameter(g.gl.MAX_TEXTURE_SIZE) as number;+ this.cols = Math.min(tiles, Math.floor(maxTex / TILE));+ const rows = Math.ceil(tiles / this.cols);+ // one single-attachment atlas per layer, so blits stay 1:1+ this.atlas = formats.map(f => g.target(this.cols * TILE, rows * TILE, [f], g.gl.NEAREST));+ for (let i = tiles - 1; i >= 0; i--) this.free.push(i);+ }+}++interface Step {+ /** 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;+}++/**+ * 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+ * copies tiles not yet saved for the current step into an atlas; undo blits them+ * 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.+ */+export class History {+ private pools: Pool[];+ private tilesX: number;+ private tilesY: number;+ private steps: Step[] = [];+ private maxSteps = 50;++ /** `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);+ const tiles = this.tilesX * this.tilesY;+ this.pools = groups.map(gr => new Pool(g, Math.ceil(tiles * gr.documents), gr.formats));+ }++ get canUndo() { return this.steps.length > 0; }++ begin(meta: unknown) {+ this.steps.push({ tiles: this.pools.map(() => new Map()), meta });+ while (this.steps.length > this.maxSteps) this.dropOldest();+ }++ /** 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;+ const 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));+ for (let ty = ty0; ty <= ty1; ty++) {+ for (let tx = tx0; tx <= tx1; tx++) {+ const id = ty * this.tilesX + tx;+ if (saved.has(id)) continue;+ while (!pool.free.length && this.steps.length > 1) this.dropOldest();+ const slot = pool.free.pop();+ if (slot === undefined) return; // a pool holds at least one whole document+ saved.set(id, slot);+ this.copyTile(pool, id, slot, layers, true);+ }+ }+ }++ /**+ * Restore the last step. `layers[p][i]` lists every framebuffer that should receive+ * layer i of pool p (both halves of a ping-pong pair). Returns the step's meta.+ */+ undo(layers: WebGLFramebuffer[][][]): { meta: unknown; rect: Rect | null } | null {+ const step = this.steps.pop();+ if (!step) return null;+ let rect: Rect | null = null;+ step.tiles.forEach((saved, p) => {+ const pool = this.pools[p];+ for (const [id, slot] of saved) {+ 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) };+ 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);+ }+ });+ return { meta: step.meta, rect };+ }++ private dropOldest() {+ const s = this.steps.shift();+ if (s) s.tiles.forEach((saved, p) => { for (const slot of saved.values()) this.pools[p].free.push(slot); });+ }++ private copyTile(pool: Pool, id: number, slot: number, layers: WebGLFramebuffer[], save: boolean) {+ const tx = (id % this.tilesX) * TILE, ty = Math.floor(id / this.tilesX) * TILE;+ const sx = (slot % pool.cols) * TILE, sy = Math.floor(slot / pool.cols) * TILE;+ const w = Math.min(TILE, this.w - tx), h = Math.min(TILE, this.h - ty);+ layers.forEach((fb, i) => {+ const atlas = pool.atlas[i].views[0];+ if (save) this.g.blit(fb, tx, ty, atlas, sx, sy, w, h);+ else this.g.blit(atlas, sx, sy, fb, tx, ty, w, h);+ });+ }+}diff --git a/src/engine/shaders.ts b/src/engine/shaders.tsnew file mode 100644index 0000000..3da9a94--- /dev/null+++ b/src/engine/shaders.ts@@ -0,0 +1,328 @@+import { displayBasisGLSL } from './spectral';++// Texture layout+// velocity RG16F (sim grid) water flow, in sim texels / second+// wet R16F (document grid) standing water on the paper+// 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++const HEADER = `#version 300 es+precision highp float;+in vec2 vUv;+`;++/** Circular stamp; MRT so one draw writes both pigment textures. */+export const splatFS = `${HEADER}+layout(location=0) out vec4 o0;+layout(location=1) out vec4 o1;+uniform float uAspect, uRadius, uHardness;+uniform vec2 uPoint;+uniform vec4 uColor0, uColor1;+void main(){+ vec2 p = vUv - uPoint; p.x *= uAspect;+ float d = dot(p, p) / (uRadius * uRadius);+ float f = exp(-pow(d, uHardness));+ o0 = uColor0 * f;+ o1 = uColor1 * f;+}`;++// Textured brush dab. The tip texture's square (-1..1) is mapped onto an ellipse of+// the brush's aspect, rotated by uAxis. uRound mixes toward a plain soft ellipse+// (used for the water footprint); uGrain gates the deposit by the paper's height so+// a dry brush only touches the peaks of the tooth.+export const stampFS = `${HEADER}+layout(location=0) out vec4 o0;+layout(location=1) out vec4 o1;+uniform sampler2D uTip, uPaper;+uniform float uAspect, uRadius, uTipAspect, uRound, uGrain, uGrainThr;+uniform vec2 uPoint, uAxis;+uniform vec4 uColor0, uColor1;+void main(){+ vec2 p = vUv - uPoint; p.x *= uAspect;+ vec2 q = vec2(dot(p, uAxis), dot(p, vec2(-uAxis.y, uAxis.x))) / uRadius;+ q.y /= uTipAspect;+ if (abs(q.x) > 1.0 || abs(q.y) > 1.0) discard;+ float t = texture(uTip, q * 0.5 + 0.5).r;+ float d = dot(q, q);+ float round = 1.0 - smoothstep(0.15, 1.0, d);+ float f = mix(t, round, uRound);+ float h = texture(uPaper, vUv).g;+ f *= mix(1.0, smoothstep(uGrainThr - 0.08, uGrainThr + 0.08, h), uGrain);+ o0 = uColor0 * f;+ o1 = uColor1 * f;+}`;++// Water flow: self-advect, damp, and confine to wet paper.+export const advectVelocityFS = `${HEADER}+out vec4 o;+uniform sampler2D uVelocity, uWet;+uniform vec2 uTexel;+uniform float uDt, uDissipation;+void main(){+ vec2 coord = vUv - uDt * texture(uVelocity, vUv).xy * uTexel;+ vec2 vel = texture(uVelocity, coord).xy * uDissipation;+ float w = texture(uWet, vUv).x;+ o = vec4(vel * smoothstep(0.005, 0.2, w), 0.0, 1.0);+}`;++export const divergenceFS = `${HEADER}+out vec4 o;+uniform sampler2D uVelocity; uniform vec2 uTexel;+void main(){+ float L = texture(uVelocity, vUv - vec2(uTexel.x, 0.0)).x;+ float R = texture(uVelocity, vUv + vec2(uTexel.x, 0.0)).x;+ float B = texture(uVelocity, vUv - vec2(0.0, uTexel.y)).y;+ float T = texture(uVelocity, vUv + vec2(0.0, uTexel.y)).y;+ o = vec4(0.5 * (R - L + T - B), 0.0, 0.0, 1.0);+}`;++export const pressureFS = `${HEADER}+out vec4 o;+uniform sampler2D uPressure, uDivergence; uniform vec2 uTexel;+void main(){+ float L = texture(uPressure, vUv - vec2(uTexel.x, 0.0)).x;+ float R = texture(uPressure, vUv + vec2(uTexel.x, 0.0)).x;+ float B = texture(uPressure, vUv - vec2(0.0, uTexel.y)).x;+ float T = texture(uPressure, vUv + vec2(0.0, uTexel.y)).x;+ o = vec4((L + R + B + T - texture(uDivergence, vUv).x) * 0.25, 0.0, 0.0, 1.0);+}`;++export const gradientSubtractFS = `${HEADER}+out vec4 o;+uniform sampler2D uPressure, uVelocity; uniform vec2 uTexel;+void main(){+ float L = texture(uPressure, vUv - vec2(uTexel.x, 0.0)).x;+ float R = texture(uPressure, vUv + vec2(uTexel.x, 0.0)).x;+ float B = texture(uPressure, vUv - vec2(0.0, uTexel.y)).x;+ float T = texture(uPressure, vUv + vec2(0.0, uTexel.y)).x;+ o = vec4(texture(uVelocity, vUv).xy - 0.5 * vec2(R - L, T - B), 0.0, 1.0);+}`;++export const curlFS = `${HEADER}+out vec4 o;+uniform sampler2D uVelocity; uniform vec2 uTexel;+void main(){+ float L = texture(uVelocity, vUv - vec2(uTexel.x, 0.0)).y;+ float R = texture(uVelocity, vUv + vec2(uTexel.x, 0.0)).y;+ float B = texture(uVelocity, vUv - vec2(0.0, uTexel.y)).x;+ float T = texture(uVelocity, vUv + vec2(0.0, uTexel.y)).x;+ o = vec4(0.5 * ((R - L) - (T - B)), 0.0, 0.0, 1.0);+}`;++export const vorticityFS = `${HEADER}+out vec4 o;+uniform sampler2D uVelocity, uCurl;+uniform vec2 uTexel; uniform float uCurlAmount, uDt;+void main(){+ float L = texture(uCurl, vUv - vec2(uTexel.x, 0.0)).x;+ float R = texture(uCurl, vUv + vec2(uTexel.x, 0.0)).x;+ float B = texture(uCurl, vUv - vec2(0.0, uTexel.y)).x;+ float T = texture(uCurl, vUv + vec2(0.0, uTexel.y)).x;+ float C = texture(uCurl, vUv).x;+ vec2 force = 0.5 * vec2(abs(T) - abs(B), abs(R) - abs(L));+ force /= length(force) + 1e-4;+ force *= uCurlAmount * C * vec2(1.0, -1.0);+ o = vec4(clamp(texture(uVelocity, vUv).xy + force * uDt, -1000.0, 1000.0), 0.0, 1.0);+}`;++export const scaleFS = `${HEADER}+out vec4 o;+uniform sampler2D uTex; uniform float uValue;+void main(){ o = texture(uTex, vUv) * uValue; }`;++// Water: carried a little by the flow, creeps outward, evaporates.+export const advectWetFS = `${HEADER}+out vec4 o;+uniform sampler2D uVelocity, uWet;+uniform vec2 uSimTexel, uTexel;+uniform float uDt, uDecay, uSpread;+void main(){+ vec2 coord = vUv - uDt * texture(uVelocity, vUv).xy * uSimTexel * 0.6;+ float w = texture(uWet, coord).x;+ vec2 b = uTexel * 1.6;+ float n = (texture(uWet, coord + vec2(b.x, 0.0)).x + texture(uWet, coord - vec2(b.x, 0.0)).x+ + texture(uWet, coord + vec2(0.0, b.y)).x + texture(uWet, coord - vec2(0.0, b.y)).x) * 0.25;+ o = vec4(mix(w, n, uSpread) * uDecay, 0.0, 0.0, 1.0);+}`;++// Pigment transport. Three effects, all confined to wet paper:+// 1. advection by the water's flow (semi-Lagrangian),+// 2. diffusion between neighbouring wet texels (bleeding),+// 3. capillary flow down the wetness gradient toward the drying edge, where it is+// stranded -> the dark "tide line" of a dried wash.+// 2 and 3 are written as fluxes across texel faces, gated by the mobility of both+// sides, so pigment is conserved and never seeps onto dry paper: wet-on-dry strokes+// keep hard edges, wet-in-wet strokes bloom as far as the water reaches.+export const advectInkFS = `${HEADER}+layout(location=0) out vec4 oA;+layout(location=1) out vec4 oB;+uniform sampler2D uVelocity, uInkA, uInkB, uWet;+uniform vec2 uSimTexel, uTexel;+uniform float uDt, uBleed, uEdge, uAspect, uKeep;+uniform vec3 uBrush; // x, y, radius (radius <= 0: no brush down)++float mobility(float w){ return smoothstep(0.02, 0.45, w); }++void face(vec2 off, float w, float m, vec4 A, vec4 B, float diffusion, float edge,+ inout vec4 dA, inout vec4 dB){+ vec2 uv = vUv + off;+ float wn = texture(uWet, uv).x;+ float g = m * mobility(wn);+ if (g <= 0.0) return;+ vec4 An = texture(uInkA, uv), Bn = texture(uInkB, uv);+ float d = diffusion * g;+ // positive: water (and pigment) drifts from this texel toward the drier neighbour+ float e = clamp(edge * (w - wn), -0.08, 0.08) * g;+ dA += d * (An - A) - (e > 0.0 ? e * A : e * An);+ dB += d * (Bn - B) - (e > 0.0 ? e * B : e * Bn);+}++void main(){+ float w = texture(uWet, vUv).x;+ float m = mobility(w);+ vec4 A = texture(uInkA, vUv), B = texture(uInkB, vUv);+ if (m < 0.002){ oA = A * uKeep; oB = B * uKeep; return; }++ vec2 vel = texture(uVelocity, vUv).xy;+ vec2 coord = vUv - uDt * vel * uSimTexel * m;+ vec4 a = mix(A, texture(uInkA, coord), m);+ vec4 b = mix(B, texture(uInkB, coord), m);++ float brush = 0.0;+ if (uBrush.z > 0.0){+ vec2 d = vUv - uBrush.xy; d.x *= uAspect;+ brush = exp(-dot(d, d) / (uBrush.z * uBrush.z));+ }+ float diffusion = clamp(uBleed * (0.25 + 1.3 * brush) * 0.3, 0.0, 0.15);+ vec4 dA = vec4(0.0), dB = vec4(0.0);+ face(vec2( uTexel.x, 0.0), w, m, A, B, diffusion, uEdge, dA, dB);+ face(vec2(-uTexel.x, 0.0), w, m, A, B, diffusion, uEdge, dA, dB);+ face(vec2(0.0, uTexel.y), w, m, A, B, diffusion, uEdge, dA, dB);+ face(vec2(0.0, -uTexel.y), w, m, A, B, diffusion, uEdge, dA, dB);++ // no clamping: basis coefficients are signed (only the spectrum they encode is positive)+ oA = (a + dA) * uKeep;+ oB = vec4((b + dB).rgb, max(b.a + dB.a, 0.0)) * uKeep;+}`;++// "Fix": mobile pigment settles into the paper. Drawn with additive blending into+// the fixed layer, after bleachFS has faded what lies under white gouache.+export const settleFS = `${HEADER}+layout(location=0) out vec4 oA;+layout(location=1) out vec4 oB;+uniform sampler2D uInkA, uInkB;+uniform float uSettle;+void main(){+ vec4 A = texture(uInkA, vUv), B = texture(uInkB, vUv);+ float keep = 1.0 - (1.0 - exp(-2.2 * B.a)) * uSettle;+ oA = A * uSettle * keep;+ oB = vec4(B.rgb * uSettle * keep, 0.0);+}`;++// Multiplicative pass (blend ZERO, SRC_COLOR): white gouache bleaches the fixed+// pigment beneath it, so after fixing it reads as paper and can be painted over.+export const bleachFS = `${HEADER}+layout(location=0) out vec4 oA;+layout(location=1) out vec4 oB;+uniform sampler2D uInkB;+uniform float uSettle;+void main(){+ float keep = 1.0 - (1.0 - exp(-2.2 * texture(uInkB, vUv).a)) * uSettle;+ oA = vec4(keep);+ oB = vec4(keep);+}`;++// Multiplicative stamp (blend ZERO, ONE_MINUS_SRC_COLOR): blotting with a tissue.+export const liftFS = `${HEADER}+layout(location=0) out vec4 o0;+layout(location=1) out vec4 o1;+uniform float uAspect, uRadius, uAmount;+uniform vec2 uPoint;+void main(){+ vec2 p = vUv - uPoint; p.x *= uAspect;+ float f = uAmount * exp(-pow(dot(p, p) / (uRadius * uRadius), 2.0));+ o0 = vec4(f);+ o1 = vec4(f);+}`;++// Cold-press paper, generated once per document.+export const paperFS = `${HEADER}+out vec4 o;+uniform vec2 uRes;+uniform 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){+ 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);+}+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;+}+void 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);+}`;++/** Final composite: spectral reconstruction of pigment on paper. */+export const displayFS = `${HEADER}+out vec4 o;+uniform sampler2D uInkA, uInkB, uFixedA, uFixedB, uWet, uPaper;+uniform vec4 uView; // canvas px -> document uv: uv = (fragCoord - xy) / zw+uniform vec2 uTexel; // document texel size+uniform float uGranulation, uEdgeDarken;+uniform vec3 uDesk;++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));+}+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; }++ vec4 paper = texture(uPaper, uv);+ vec4 iB = texture(uInkB, uv);+ vec4 a = texture(uInkA, uv) + texture(uFixedA, uv);+ vec3 b = iB.rgb + texture(uFixedB, uv).rgb;++ // Granulation: pigment settles into the valleys of the paper.+ float d0 = a.x;+ float gran = 1.0 + uGranulation * (0.5 - paper.g) * 2.2;+ // Edge darkening from the density gradient keeps fine pen work crisp.+ float l = density(uv - vec2(uTexel.x, 0.0)), r = density(uv + vec2(uTexel.x, 0.0));+ float bt = density(uv - vec2(0.0, uTexel.y)), t = density(uv + vec2(0.0, uTexel.y));+ float edge = min(length(vec2(r - l, t - bt)) / (d0 + 1.0), 1.0);+ float k = gran * (1.0 + uEdgeDarken * edge);+ a *= k; b *= k;++ vec3 rgb = vec3(0.0);+ float tr;+${displayBasisGLSL()}++ // Paper: warm white, lit relief, faint fibre mottling (linear light).+ vec3 paperCol = vec3(0.925, 0.905, 0.855) * (0.93 + 0.1 * paper.r) * (0.985 + 0.03 * paper.b);+ vec3 col = rgb * paperCol;++ // 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);+ col = mix(col, vec3(0.96, 0.955, 0.94) * (0.96 + 0.05 * paper.r), cov);++ // Wet paper reads darker and slightly cool.+ float ws = smoothstep(0.02, 0.7, texture(uWet, uv).x);+ col *= vec3(1.0) - ws * vec3(0.12, 0.11, 0.08);++ o = vec4(toSRGB(col), 1.0);+}`;diff --git a/src/engine/spectral.ts b/src/engine/spectral.tsnew file mode 100644index 0000000..ee04f2c--- /dev/null+++ b/src/engine/spectral.ts@@ -0,0 +1,95 @@+import { BASIS, DISPLAY_BANDS, DISPLAY_RGB_WEIGHTS, PRIMARIES, SPECTRAL_EPSILON } from './spectralData';++/** Number of absorbance coefficients stored per texel. */+export const COEFFS = 7;++/**+ * A pigment: 7 absorbance coefficients for its masstone at concentration 1,+ * plus white-gouache coverage (opaque, sits on top rather than absorbing).+ */+export interface Pigment {+ coeffs: Float32Array;+ white: number;+}++const uncompand = (x: number) => (x < 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4));+const compand = (x: number) => (x < 0.0031308 ? x * 12.92 : 1.055 * Math.pow(x, 1 / 2.4) - 0.055);+const clamp01 = (x: number) => Math.min(1, Math.max(0, x));++export function hexToRgb(hex: string): [number, number, number] {+ const n = parseInt(hex.replace('#', ''), 16);+ return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255];+}++export function rgbToHex([r, g, b]: readonly number[]): string {+ const to = (v: number) => Math.round(clamp01(v) * 255).toString(16).padStart(2, '0');+ return `#${to(r)}${to(g)}${to(b)}`;+}++/** spectral.js upsampling: sRGB -> 38-band reflectance curve. */+function reflectance(srgb: readonly number[]): number[] {+ let [r, g, b] = srgb.map(uncompand);+ const w = Math.min(r, g, b);+ r -= w; g -= w; b -= w;+ const c = Math.min(g, b), m = Math.min(r, b), y = Math.min(r, g);+ const rr = Math.min(Math.max(0, r - b), Math.max(0, r - g));+ const gg = Math.min(Math.max(0, g - b), Math.max(0, g - r));+ const bb = Math.min(Math.max(0, b - g), Math.max(0, b - r));+ return PRIMARIES.map(k =>+ Math.max(SPECTRAL_EPSILON, w + c * k[0] + m * k[1] + y * k[2] + rr * k[3] + gg * k[4] + bb * k[5]));+}++/** A transparent pigment whose masstone (concentration 1 on white paper) is `hex`. */+export function pigmentFromHex(hex: string): Pigment {+ const absorbance = reflectance(hexToRgb(hex)).map(v => -Math.log(v));+ const coeffs = new Float32Array(COEFFS);+ for (let k = 0; k < COEFFS; k++) {+ let s = 0;+ for (let i = 0; i < absorbance.length; i++) s += BASIS[k][i] * absorbance[i];+ coeffs[k] = s;+ }+ return { coeffs, white: 0 };+}++export const WHITE_GOUACHE: Pigment = { coeffs: new Float32Array(COEFFS), white: 1 };++/**+ * CPU mirror of the display shader's colour reconstruction (without paper texture):+ * linear sRGB of a layer holding `coeffs` absorbance over white paper.+ */+export function coeffsToLinear(coeffs: ArrayLike<number>): [number, number, number] {+ const out: [number, number, number] = [0, 0, 0];+ DISPLAY_BANDS.forEach((band, i) => {+ let a = 0;+ for (let k = 0; k < COEFFS; k++) a += coeffs[k] * BASIS[k][band];+ const t = Math.exp(-Math.max(a, 0));+ for (let j = 0; j < 3; j++) out[j] += t * DISPLAY_RGB_WEIGHTS[i][j];+ });+ return out;+}++export function coeffsToHex(coeffs: ArrayLike<number>): string {+ return rgbToHex(coeffsToLinear(coeffs).map(v => compand(clamp01(v))));+}++/** Pigments mixed (or glazed) at the given concentrations, as a CSS colour. */+export function mixToHex(parts: { pigment: Pigment; amount: number }[]): string {+ const sum = new Float32Array(COEFFS);+ for (const { pigment, amount } of parts)+ for (let k = 0; k < COEFFS; k++) sum[k] += pigment.coeffs[k] * amount;+ return coeffsToHex(sum);+}++/** Basis value at the display bands, laid out for the shader: vec4 + vec3 per band. */+export function displayBasisGLSL(): string {+ const f = (v: number) => (Number.isInteger(v) ? v.toFixed(1) : v.toPrecision(7));+ const lines: string[] = [];+ DISPLAY_BANDS.forEach((band, i) => {+ const b = BASIS.map(v => v[band]);+ const w = DISPLAY_RGB_WEIGHTS[i];+ lines.push(+ ` tr = exp(-max(dot(a, vec4(${b.slice(0, 4).map(f).join(',')})) + dot(b, vec3(${b.slice(4, 7).map(f).join(',')})), 0.0));\n` ++ ` rgb += tr * vec3(${w.map(f).join(',')});`);+ });+ return lines.join('\n');+}diff --git a/src/engine/spectralData.ts b/src/engine/spectralData.tsnew file mode 100644index 0000000..94515af--- /dev/null+++ b/src/engine/spectralData.ts@@ -0,0 +1,23 @@+// Generated from spectral.js reflectance data (Ronald van Wijnen, MIT) by an offline fit.+// Do not edit by hand.+//+// Pigment model: a colour's spectral absorbance A(λ) = -ln R(λ) (38 bands, 380–750nm)+// is projected onto a 7-vector basis (uncentred SVD of absorbance spectra across the+// sRGB gamut). Absorbance is linear in pigment concentration, so these coefficients+// can be added, advected and diffused by the fluid sim while mixing stays physically+// subtractive (blue + yellow = green). Reconstruction error vs. the full 38-band model+// averages ΔE_OK ≈ 0.1 (×100 scale), well under the visible threshold.++export const SPECTRAL_EPSILON = 1e-4;++/** Reflectance of the 6 spectral.js primaries (cyan, magenta, yellow, red, green, blue) per band. */+export const PRIMARIES: readonly (readonly number[])[] = [[0.96853629,0.51567122,0.02055257,0.03147571,0.49108579,0.97901834],[0.96855103,0.5401552,0.02059936,0.03146636,0.46944057,0.97901649],[0.96859338,0.62645502,0.02062723,0.03140624,0.4016578,0.97901118],[0.96877345,0.75595012,0.02073387,0.03119611,0.2449042,0.97892146],[0.96942204,0.92826996,0.02114202,0.03053888,0.0682688,0.97858555],[0.97143709,0.97223624,0.02233154,0.02856855,0.02732883,0.97743705],[0.97541862,0.98616174,0.02556857,0.02459485,0.013606,0.97428075],[0.98074186,0.98955255,0.03330189,0.0192952,0.01000187,0.96663223],[0.98580992,0.98676237,0.05185294,0.01423112,0.01284127,0.94822893],[0.98971194,0.97312575,0.10087639,0.01033111,0.02636635,0.89937713],[0.99238027,0.91944277,0.24000413,0.00765876,0.07058713,0.76070164],[0.99409844,0.32564851,0.53589066,0.00593693,0.70421692,0.4642044],[0.995172,0.13820628,0.79874659,0.00485616,0.85473994,0.20123039],[0.99576545,0.05015143,0.91186529,0.00426186,0.95081565,0.08808402],[0.99593552,0.02912336,0.95399623,0.00409039,0.9717037,0.04592894],[0.99564041,0.02421691,0.97137099,0.00438375,0.97651888,0.02860373],[0.99464769,0.02660696,0.97939505,0.00537525,0.97429245,0.02060067],[0.99229579,0.03407586,0.98345207,0.00772962,0.97012917,0.01656701],[0.98638762,0.04835936,0.98553736,0.0136612,0.9425863,0.01451549],[0.96829712,0.0001172,0.98648905,0.03181352,0.99989207,0.01357964],[0.89228016,0.00008554,0.98674535,0.10791525,0.99989891,0.01331243],[0.53740239,0.85267882,0.98657555,0.46249516,0.13823139,0.01347661],[0.15360445,0.93188793,0.98611877,0.84604333,0.06968113,0.01387181],[0.05705719,0.94810268,0.98559942,0.94275572,0.05628787,0.01435472],[0.03126539,0.94200977,0.98507063,0.96860996,0.06111561,0.01479836],[0.02205445,0.91478045,0.98460039,0.97783966,0.08987709,0.0151525],[0.01802271,0.87065445,0.98425301,0.98187757,0.13656016,0.01540513],[0.0161346,0.78827548,0.98403909,0.98377315,0.22169624,0.01557233],[0.01520947,0.65738359,0.98388535,0.98470202,0.32176956,0.0156571],[0.01475977,0.59909403,0.98376116,0.98515481,0.36157329,0.01571025],[0.01454263,0.56817268,0.98368246,0.98537114,0.4836192,0.01571916],[0.01444459,0.54031997,0.98365023,0.98546685,0.46488579,0.01572133],[0.01439897,0.52110241,0.98361309,0.98550011,0.47440306,0.01572502],[0.0143762,0.51041094,0.98357259,0.98551031,0.4857699,0.01571717],[0.01436343,0.50526577,0.98353856,0.98550741,0.49267971,0.01571905],[0.01435687,0.5025508,0.98351247,0.98551323,0.49625685,0.01571059],[0.0143537,0.50126452,0.98350101,0.98551563,0.49807754,0.01569728],[0.01435408,0.50083021,0.98350852,0.98551547,0.49889859,0.0157002]];++/** Absorbance basis: 7 vectors × 38 bands. */+export const BASIS: readonly (readonly number[])[] = [[0.1441295,0.1442537,0.1447023,0.1481238,0.1558969,0.1598567,0.1620447,0.1627555,0.1616249,0.1577825,0.1510664,0.1434845,0.1548815,0.1665376,0.1732235,0.176503,0.1775172,0.1768919,0.1748587,0.1783071,0.17098,0.1527153,0.1627231,0.169401,0.1714174,0.170287,0.1680602,0.1648873,0.162965,0.1626282,0.159549,0.1605975,0.1607086,0.1606138,0.1605312,0.1604933,0.1604751,0.160461],[-0.2038064,-0.203989,-0.2047454,-0.2096147,-0.2221909,-0.229624,-0.2342462,-0.2354314,-0.2303617,-0.2137209,-0.1783547,-0.124576,-0.08767601,-0.06654336,-0.05408394,-0.04631953,-0.04068168,-0.03551027,-0.02914774,-0.01869558,0.01093349,0.05936064,0.1243476,0.151563,0.1619576,0.1663112,0.1683766,0.1696986,0.171131,0.1718488,0.1723758,0.1726696,0.172894,0.1730376,0.1731037,0.1731485,0.1731795,0.1731822],[0.03137849,0.03651497,0.05369401,0.09161207,0.1575574,0.1842324,0.1949895,0.1940139,0.181434,0.1530233,0.09984866,-0.09188325,-0.1765157,-0.2432063,-0.2743489,-0.2876131,-0.2893418,-0.2831437,-0.2674148,-0.3019731,-0.2652804,0.04536814,0.1224234,0.1512875,0.1570717,0.1463656,0.128849,0.1015794,0.07210673,0.06066822,0.0405239,0.04040221,0.03731743,0.03480428,0.03341753,0.03269546,0.03233622,0.03218968],[0.3475249,0.3394636,0.3120142,0.2222812,0.02525531,-0.07617525,-0.131711,-0.1551115,-0.1569514,-0.1445308,-0.1209759,0.1224517,0.04911107,-0.01336119,-0.05756325,-0.0821194,-0.0923594,-0.09218955,-0.0876826,-0.1097293,-0.08213999,-0.2512941,-0.2629964,-0.2346993,-0.1994343,-0.1372833,-0.07003431,0.01097949,0.07361673,0.09292193,0.1495078,0.1393326,0.1419586,0.1459523,0.1484407,0.1497109,0.1503627,0.1506628],[0.06142204,0.05786618,0.04493868,-0.001667544,-0.1239341,-0.18922,-0.2092335,-0.1813051,-0.09951376,0.04750551,0.2508217,0.4173112,0.3464263,0.2114988,0.1065638,0.0396658,0.001179382,-0.02244844,-0.04379864,-0.2757395,-0.4358296,0.002079004,0.08929734,0.1616104,0.1808936,0.1600107,0.1229764,0.06541057,-0.001589698,-0.02956237,-0.06381081,-0.07050402,-0.07924397,-0.08523274,-0.08834905,-0.09000503,-0.09082922,-0.09112351],[-0.2849056,-0.2809993,-0.2670309,-0.2146758,-0.04397425,0.07688784,0.1561441,0.1960707,0.2022741,0.1829012,0.1568899,0.1352822,0.1607311,0.1282205,0.08742798,0.05524357,0.03074158,0.007401419,-0.02492709,-0.144013,-0.2534114,-0.279643,-0.284807,-0.2400265,-0.1937673,-0.1278778,-0.06158691,0.0106791,0.06228573,0.07793386,0.1189043,0.1120231,0.1139095,0.1167035,0.118432,0.119318,0.1197796,0.1199808],[-0.04867795,-0.03848097,-0.006388283,0.0006091587,-0.0367139,-0.0675538,-0.07838973,-0.06227753,-0.01207089,0.08113584,0.2171174,0.1783848,0.06910126,-0.09273659,-0.1425212,-0.1316225,-0.07574946,0.0125239,0.1328408,-0.1632446,0.05201528,0.7089535,0.1776335,-0.1592273,-0.2833049,-0.2661033,-0.1976904,-0.09221338,-0.02023599,-0.004615753,0.08051684,0.05602729,0.05512528,0.058801,0.06145249,0.06280478,0.06355499,0.06393252]];++/** Band indices sampled by the display shader (16-point fitted quadrature). */+export const DISPLAY_BANDS: readonly number[] = [2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32];++/** Linear-sRGB weight of each display band: rgb = Σ_i exp(-A(λ_i)) · weight_i. */+export const DISPLAY_RGB_WEIGHTS: readonly (readonly number[])[] = [[0.007598756,0.0144316,0.02304203],[-0.07190809,-0.05764169,0.1207272],[0.299773,0.0127048,0.3249726],[-0.2579063,-0.06517872,0.4461339],[0.07037487,0.05889296,0.1350291],[-0.2104469,0.1285821,0.09775973],[-0.02718884,0.2208098,-0.09346024],[-0.3172512,0.4457301,0.04248862],[0.2293731,0.1134161,-0.06150663],[0.1930991,0.1395861,-0.01283952],[0.5274069,0.03838932,-0.02348521],[0.3899227,0.07193636,0.01268301],[-0.165677,-0.2589753,-0.01230862],[0.5972293,0.3119106,-0.00548141],[-0.197781,0.08099158,0.05785604],[-0.06596648,-0.2556352,-0.05165295]];diff --git a/src/main.ts b/src/main.tsnew file mode 100644index 0000000..e095a53--- /dev/null+++ b/src/main.ts@@ -0,0 +1,397 @@+import { BRUSH_PRESETS, buildBrush, type Brush } from './engine/brushes';+import { DEFAULT_PARAMS, WatercolorEngine, type Params, type Tool } from './engine/Engine';+import { mixToHex } from './engine/spectral';+import { PALETTE, customEntry, type PaletteEntry } from './palette';+import { loadCustomBrushes, makeCustomBrush, saveCustomBrushes, tipFromImage } from './ui/customBrushes';+import { icon } from './ui/icons';+import { drawStroke, drawThumb, forgetTipImages } from './ui/preview';+import './styles.css';++const TOOLS: { id: Tool; label: string; key: string; hint: string }[] = [+ { id: 'brush', label: 'Brush', key: 'B', hint: 'Wet paint: pigment and water' },+ { id: 'water', label: 'Water', key: 'W', hint: 'Clear water: wets paper, moves paint' },+ { id: 'pen', label: 'Pen', key: 'P', hint: 'Ink line in the current colour' },+ { id: 'lift', label: 'Lift', key: 'L', hint: 'Blot with a tissue: lifts wet paint' },+];++const SLIDERS: { key: keyof Params; label: string }[] = [+ { key: 'size', label: 'Size' },+ { key: 'water', label: 'Water' },+ { key: 'load', label: 'Pigment' },+ { key: 'flow', label: 'Flow' },+ { key: 'bleed', label: 'Bleed' },+ { key: 'edge', label: 'Edges' },+ { key: 'granulation', label: 'Grain' },+ { key: 'dry', label: 'Dry speed' },+];++const BRUSH_KEY = 'watercolor.brush';++/** Dab-like swatch: masstone at the centre, diluted towards the rim. */+function swatchBackground(e: PaletteEntry): string {+ if (e.pigment.white) return `radial-gradient(circle at 40% 38%, #fff, ${e.hex} 70%)`;+ const at = (c: number) => mixToHex([{ pigment: e.pigment, amount: c }]);+ return `radial-gradient(circle at 42% 40%, ${at(0.55)}, ${at(1)} 55%, ${at(1.25)} 72%, ${at(0.7)} 100%)`;+}++const button = (action: string, iconName: string, label: string, title: string) =>+ `<button data-action="${action}" title="${title}">${icon(iconName)}<span>${label}</span></button>`;++const esc = (s: string) => s.replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c]!);++const root = document.getElementById('root')!;+root.innerHTML = `+ <canvas class="paper"></canvas>+ <div class="cursor"></div>+ <div class="hint">Pick a brush and a pigment, then paint.<br>Water moves paint only where the paper is wet.</div>+ <nav class="panel tools" aria-label="Tools">+ <button class="tool pick" data-action="library" title="Brushes (, and . to cycle)" aria-haspopup="listbox">+ <canvas class="thumb" width="28" height="28"></canvas><span class="brushname"></span>+ </button>+ <hr>+ ${TOOLS.map(t => `<button class="tool" data-tool="${t.id}" title="${t.label} (${t.key}): ${t.hint}">${icon(t.id)}<span>${t.label}</span></button>`).join('')}+ </nav>+ <div class="panel library" hidden role="dialog" aria-label="Brushes">+ <div class="library-head">+ <span>Brushes</span>+ <span class="sub">Shape follows the stroke, pen tilt or a set angle. Dry brushes skip the paper tooth.</span>+ <button class="icon" data-action="library" title="Close">${icon('close', 16)}</button>+ </div>+ <div class="brushes" role="listbox" aria-label="Brush library"></div>+ <div class="library-foot">+ <button class="import" data-action="import" title="Use an image as a brush tip: dark marks on white, or white on transparent">${icon('plus', 16)}<span>Import texture…</span></button>+ <span class="note">PNG or JPG. Light background is inverted automatically.</span>+ </div>+ <input type="file" accept="image/*" hidden>+ </div>+ <div class="panel actions">+ ${button('undo', 'undo', 'Undo', 'Undo (⌘Z)')}+ ${button('dry', 'dry', 'Dry', 'Dry and fix the painting into the paper (D)')}+ ${button('clear', 'clear', 'Clear', 'Clear the paper')}+ ${button('save', 'save', 'Save', 'Save PNG (S)')}+ ${button('settings', 'sliders', 'Settings', 'Brush & water settings')}+ </div>+ <div class="panel settings" hidden>+ ${SLIDERS.map(s => `<label class="slider"><span>${s.label}</span><input type="range" min="0" max="1" step="0.01" data-param="${s.key}"></label>`).join('')}+ <button class="reset" data-action="reset">Reset</button>+ </div>+ <div class="panel palette">+ <div class="swatches" role="listbox" aria-label="Pigments">+ ${PALETTE.map((e, i) => `<button class="swatch" role="option" data-index="${i}" title="${e.name}${i < 9 ? ` (${i + 1})` : i === PALETTE.length - 1 ? ' (0)' : ''}"></button>`).join('')}+ <label class="swatch custom" title="Custom pigment"><input type="color" value="#7a3b8f"></label>+ </div>+ <div class="well" title="Spectral mix of your last two pigments"><span class="name"></span><span class="mix"></span></div>+ </div>+ <div class="toast" hidden></div>`;++const $ = <T extends HTMLElement = HTMLElement>(sel: string) => root.querySelector<T>(sel)!;+const $$ = <T extends HTMLElement = HTMLElement>(sel: string) => [...root.querySelectorAll<T>(sel)];++const canvas = $<HTMLCanvasElement>('canvas.paper');+const settings = $('.settings');+const library = $('.library');+const brushList = $('.brushes');+const pickBtn = $('.tool.pick');+const pickThumb = $<HTMLCanvasElement>('.tool.pick .thumb');+const fileInput = $<HTMLInputElement>('.library input[type="file"]');+const undoBtn = $<HTMLButtonElement>('[data-action="undo"]');+const clearBtn = $('[data-action="clear"]');+const settingsBtn = $('[data-action="settings"]');+const customSwatch = $('.swatch.custom');+const customInput = $<HTMLInputElement>('.swatch.custom input');+const toast = $('.toast');+const sliders = $$<HTMLInputElement>('[data-param]');+const swatchButtons = $$('.swatch[data-index]');+swatchButtons.forEach((b, i) => { b.style.background = swatchBackground(PALETTE[i]); });++/* ---------------------------------------------------------------- state */++let engine: WatercolorEngine;+let tool: Tool = 'brush';+let strokeTool: Tool | null = null;+let params: Params = { ...DEFAULT_PARAMS };+let current: PaletteEntry = PALETTE[5];+let previous: PaletteEntry = PALETTE[0];+let confirmTimer = 0;+let toastTimer = 0;++const builtIn: Brush[] = BRUSH_PRESETS.map(p => buildBrush(p));+let customs: Brush[] = [];+const allBrushes = () => [...builtIn, ...customs];+let brush: Brush = builtIn[0];++try {+ engine = new WatercolorEngine(canvas, $('.cursor'), {+ onHistoryChange: can => { undoBtn.disabled = !can; },+ onStrokeTool: t => { strokeTool = t; renderTools(); },+ });+} catch (e) {+ root.innerHTML = `<div class="error"><p>${e instanceof Error ? e.message : String(e)}</p><p class="sub">A browser with WebGL2 is required.</p></div>`;+ throw e;+}+if (import.meta.env.DEV) (window as unknown as { engine: WatercolorEngine }).engine = engine;++/* ------------------------------------------------------------ rendering */++function renderTools() {+ const shown = strokeTool ?? tool;+ for (const b of $$('[data-tool]')) {+ b.classList.toggle('on', b.dataset.tool === shown);+ b.setAttribute('aria-pressed', String(b.dataset.tool === tool));+ }+}++function renderParams() {+ for (const s of sliders) s.value = String(params[s.dataset.param as keyof Params]);+}++function renderPalette() {+ swatchButtons.forEach((b, i) => {+ const on = PALETTE[i].name === current.name;+ b.classList.toggle('on', on);+ b.setAttribute('aria-selected', String(on));+ });+ const custom = current.name === 'Custom';+ customSwatch.classList.toggle('on', custom);+ customSwatch.style.background = custom ? swatchBackground(current) : '';+ $('.well .name').textContent = current.name;+ const mix = $('.well .mix');+ if (current.pigment.white || previous.pigment.white) { mix.innerHTML = ''; return; }+ const wet = mixToHex([{ pigment: previous.pigment, amount: 0.5 }, { pigment: current.pigment, amount: 0.5 }]);+ mix.innerHTML = `<i style="background:${previous.hex}"></i>+<i style="background:${current.hex}"></i>=<i style="background:${wet}"></i>`;+}++/** Colour used for brush previews: the current pigment, or ink for white gouache. */+const previewHex = () => (current.pigment.white ? '#3b4552' : current.hex);++/** Rebuild the library's cards (on load, and when custom brushes change). */+function buildLibrary() {+ brushList.innerHTML = allBrushes().map(b => `+ <div class="brush${b.custom ? ' custom' : ''}" role="option" data-brush="${esc(b.id)}" aria-selected="false" tabindex="0" title="${esc(b.hint)}">+ <canvas class="stroke" width="150" height="44"></canvas>+ <span class="label">${esc(b.name)}</span>+ ${b.custom ? `<button class="icon remove" data-remove="${esc(b.id)}" title="Remove this brush">${icon('close', 14)}</button>` : ''}+ </div>`).join('');+ renderPreviews();+ renderBrush();+}++function renderPreviews() {+ const hex = previewHex();+ const byId = new Map(allBrushes().map(b => [b.id, b]));+ for (const el of $$('.brush[data-brush]')) {+ const b = byId.get(el.dataset.brush!);+ if (b) drawStroke(el.querySelector('canvas')!, b, hex);+ }+ drawThumb(pickThumb, brush, hex);+}++function renderBrush() {+ for (const el of $$('.brush[data-brush]')) {+ const on = el.dataset.brush === brush.id;+ el.classList.toggle('on', on);+ el.setAttribute('aria-selected', String(on));+ }+ $('.tool.pick .brushname').textContent = brush.name;+ pickBtn.title = `${brush.name}: ${brush.hint}. Open the brush library (, and . to cycle)`;+ drawThumb(pickThumb, brush, previewHex());+}++/* -------------------------------------------------------------- actions */++function setTool(t: Tool) {+ tool = t;+ engine.setTool(t);+ renderTools();+}++function setParams(p: Partial<Params>) {+ params = { ...params, ...p };+ engine.setParams(params);+ renderParams();+}++function choose(e: PaletteEntry) {+ if (current.hex !== e.hex) previous = current;+ current = e;+ engine.setPigment(e.pigment);+ if (tool === 'water' || tool === 'lift') setTool('brush');+ renderPalette();+ renderPreviews();+}++function chooseBrush(b: Brush, scroll = false) {+ brush = b;+ engine.setBrush(b);+ if (tool === 'pen' || tool === 'lift') setTool('brush');+ renderBrush();+ try { localStorage.setItem(BRUSH_KEY, b.id); } catch { /* storage blocked */ }+ if (scroll) brushList.querySelector(`[data-brush="${CSS.escape(b.id)}"]`)?.scrollIntoView({ block: 'nearest' });+}++function cycleBrush(dir: 1 | -1) {+ const list = allBrushes();+ const i = list.findIndex(b => b.id === brush.id);+ chooseBrush(list[(i + dir + list.length) % list.length], true);+ showToast(brush.name);+}++function showToast(text: string) {+ clearTimeout(toastTimer);+ toast.textContent = text;+ toast.hidden = false;+ toastTimer = window.setTimeout(() => { toast.hidden = true; }, 1200);+}++async function importTexture(file: File) {+ try {+ const tip = await tipFromImage(file);+ const name = file.name.replace(/\.[^.]+$/, '').replace(/[-_]+/g, ' ').trim().slice(0, 22) || 'Imported';+ const b = makeCustomBrush(`custom-${Date.now().toString(36)}`, name, tip);+ customs.push(b);+ if (!saveCustomBrushes(customs)) showToast('Brush added, but could not be saved for next time');+ buildLibrary();+ chooseBrush(b, true);+ } catch (e) {+ showToast(e instanceof Error ? e.message : 'Could not read that image');+ }+}++function removeBrush(id: string) {+ const b = customs.find(c => c.id === id);+ if (!b) return;+ customs = customs.filter(c => c.id !== id);+ saveCustomBrushes(customs);+ engine.forgetBrush(id);+ forgetTipImages(id);+ if (brush.id === id) chooseBrush(builtIn[0]);+ buildLibrary();+}++async function save() {+ const blob = await engine.exportPNG();+ const a = document.createElement('a');+ a.href = URL.createObjectURL(blob);+ a.download = `watercolor-${new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19)}.png`;+ a.click();+ setTimeout(() => URL.revokeObjectURL(a.href), 4000);+}++function setConfirmClear(on: boolean) {+ clearTimeout(confirmTimer);+ clearBtn.classList.toggle('danger', on);+ clearBtn.querySelector('span')!.textContent = on ? 'Sure?' : 'Clear';+ if (on) confirmTimer = window.setTimeout(() => setConfirmClear(false), 2500);+}++function clear() {+ if (!clearBtn.classList.contains('danger')) { setConfirmClear(true); return; }+ engine.clear();+ setConfirmClear(false);+}++function toggleSettings(force?: boolean) {+ settings.hidden = force === undefined ? !settings.hidden : !force;+ settingsBtn.classList.toggle('on', !settings.hidden);+ settingsBtn.setAttribute('aria-expanded', String(!settings.hidden));+}++function toggleLibrary(force?: boolean) {+ library.hidden = force === undefined ? !library.hidden : !force;+ pickBtn.classList.toggle('open', !library.hidden);+ pickBtn.setAttribute('aria-expanded', String(!library.hidden));+ if (!library.hidden) brushList.querySelector<HTMLElement>('.brush.on')?.scrollIntoView({ block: 'nearest' });+}++/* --------------------------------------------------------------- wiring */++root.addEventListener('click', e => {+ const el = (e.target as Element).closest<HTMLElement>('[data-tool], [data-action], [data-index], [data-brush], [data-remove]');+ if (!el) return;+ if (el.dataset.remove) { removeBrush(el.dataset.remove); return; }+ if (el.dataset.tool) setTool(el.dataset.tool as Tool);+ else if (el.dataset.brush) { const b = allBrushes().find(x => x.id === el.dataset.brush); if (b) chooseBrush(b); }+ else if (el.dataset.index) choose(PALETTE[Number(el.dataset.index)]);+ else switch (el.dataset.action) {+ case 'undo': engine.undo(); break;+ case 'dry': engine.fix(); break;+ case 'clear': clear(); break;+ case 'save': void save(); break;+ case 'settings': toggleSettings(); break;+ case 'library': toggleLibrary(); break;+ case 'import': fileInput.click(); break;+ case 'reset': setParams(DEFAULT_PARAMS); break;+ }+});++brushList.addEventListener('keydown', e => {+ if (e.key !== 'Enter' && e.key !== ' ') return;+ const el = (e.target as Element).closest<HTMLElement>('[data-brush]');+ const b = el && allBrushes().find(x => x.id === el.dataset.brush);+ if (b) { e.preventDefault(); chooseBrush(b); }+});++fileInput.addEventListener('change', () => {+ const f = fileInput.files?.[0];+ fileInput.value = '';+ if (f) void importTexture(f);+});++// drop an image anywhere to make a brush from it+root.addEventListener('dragover', e => { if (e.dataTransfer?.types.includes('Files')) e.preventDefault(); });+root.addEventListener('drop', e => {+ const f = e.dataTransfer?.files?.[0];+ if (f && f.type.startsWith('image/')) { e.preventDefault(); void importTexture(f); }+});++settings.addEventListener('input', e => {+ const s = e.target as HTMLInputElement;+ if (s.dataset.param) setParams({ [s.dataset.param]: Number(s.value) });+});++customInput.addEventListener('input', () => choose(customEntry(customInput.value)));++canvas.addEventListener('pointerdown', () => $('.hint').classList.add('gone'), { once: true });+// painting dismisses the library so it never covers the work for long+canvas.addEventListener('pointerdown', () => { if (!library.hidden) toggleLibrary(false); });++window.addEventListener('resize', () => { engine.resize(); renderPreviews(); });++window.addEventListener('keydown', e => {+ if (e.target instanceof HTMLInputElement && e.target.type !== 'range') return;+ const k = e.key.toLowerCase();+ if ((e.metaKey || e.ctrlKey) && k === 'z') { e.preventDefault(); engine.undo(); return; }+ if (e.metaKey || e.ctrlKey || e.altKey) return;+ if (k === 'escape') { toggleLibrary(false); toggleSettings(false); return; }+ const t = TOOLS.find(x => x.key.toLowerCase() === k);+ if (t) setTool(t.id);+ else if (k === '[' || k === ']') setParams({ size: Math.min(1, Math.max(0, params.size + (k === ']' ? 0.05 : -0.05))) });+ else if (k === ',' || k === '<') cycleBrush(-1);+ else if (k === '.' || k === '>') cycleBrush(1);+ else if (k === 'd') engine.fix();+ else if (k === 's') void save();+ else if (k === 'f') {+ if (document.fullscreenElement) void document.exitFullscreen();+ else void document.documentElement.requestFullscreen?.();+ } else if (/^[1-9]$/.test(k)) choose(PALETTE[Number(k) - 1]);+ else if (k === '0') choose(PALETTE[PALETTE.length - 1]);+});++/* ----------------------------------------------------------------- init */++engine.setPigment(current.pigment);+engine.setBrush(brush);+undoBtn.disabled = true;+renderTools();+renderParams();+renderPalette();+buildLibrary();++void loadCustomBrushes().then(list => {+ customs = list;+ let wanted: string | null = null;+ try { wanted = localStorage.getItem(BRUSH_KEY); } catch { /* storage blocked */ }+ buildLibrary();+ const b = wanted && allBrushes().find(x => x.id === wanted);+ if (b) chooseBrush(b);+});diff --git a/src/palette.ts b/src/palette.tsnew file mode 100644index 0000000..dc60a2d--- /dev/null+++ b/src/palette.ts@@ -0,0 +1,31 @@+import { pigmentFromHex, WHITE_GOUACHE, type Pigment } from './engine/spectral';++export interface PaletteEntry {+ name: string;+ /** Masstone: the colour at full strength on white paper. */+ hex: string;+ pigment: Pigment;+}++const entry = (name: string, hex: string): PaletteEntry => ({ name, hex, pigment: pigmentFromHex(hex) });++/** A small split-primary watercolour palette plus earths, neutrals and white gouache. */+export const PALETTE: PaletteEntry[] = [+ entry('Hansa Yellow', '#f6d409'),+ entry('New Gamboge', '#f0a202'),+ entry('Pyrrol Scarlet', '#e0301e'),+ entry('Quinacridone Rose', '#d0306a'),+ entry('Dioxazine Violet', '#4b2c7a'),+ entry('French Ultramarine', '#2338a8'),+ entry('Phthalo Blue', '#0e5a9c'),+ entry('Phthalo Green', '#0b6e5a'),+ entry('Sap Green', '#4f7d2a'),+ entry('Yellow Ochre', '#c8902e'),+ entry('Burnt Sienna', '#a0522d'),+ entry('Burnt Umber', '#5c3a21'),+ entry("Payne's Grey", '#3b4552'),+ entry('Lamp Black', '#1b1b1f'),+ { name: 'White Gouache', hex: '#f7f5ef', pigment: WHITE_GOUACHE },+];++export const customEntry = (hex: string): PaletteEntry => entry('Custom', hex);diff --git a/src/styles.css b/src/styles.cssnew file mode 100644index 0000000..da430a6--- /dev/null+++ b/src/styles.css@@ -0,0 +1,214 @@+:root {+ --ink: #2a2a33;+ --ink-soft: rgba(42, 42, 51, 0.55);+ --ink-faint: rgba(42, 42, 51, 0.28);+ --glass: rgba(246, 243, 236, 0.78);+ --line: rgba(42, 42, 51, 0.12);+ --accent: #2338a8;+ --radius: 14px;+ color-scheme: light;+}++* { box-sizing: border-box; }++[hidden] { display: none !important; }++html, body, #root { margin: 0; height: 100%; overflow: hidden; background: #dbd7cf; }++body {+ font: 12px/1.3 "Avenir Next", "Helvetica Neue", system-ui, sans-serif;+ color: var(--ink);+ -webkit-user-select: none; user-select: none;+ -webkit-touch-callout: none;+ overscroll-behavior: none;+}++button { font: inherit; color: inherit; }++.paper {+ position: fixed; inset: 0; width: 100%; height: 100%;+ touch-action: none; cursor: none; display: block;+}++.cursor {+ position: fixed; left: 0; top: 0; z-index: 4;+ border: 1px solid rgba(42, 42, 51, 0.55); border-radius: 50%;+ pointer-events: none; opacity: 0;+ transition: width 0.08s, height 0.08s, opacity 0.2s, border-color 0.2s;+}+.cursor[data-tool="water"] { border-color: rgba(60, 90, 160, 0.55); box-shadow: inset 0 0 10px rgba(60, 90, 160, 0.15); }+.cursor[data-tool="lift"] { border-style: dashed; }++.hint {+ position: fixed; left: 50%; top: 46%; transform: translate(-50%, -50%);+ z-index: 3; pointer-events: none; text-align: center;+ font-size: 11px; letter-spacing: 0.3em; text-transform: uppercase; line-height: 2.2;+ color: rgba(42, 42, 51, 0.35);+ transition: opacity 1.2s ease;+}+.hint.gone { opacity: 0; }++/* floating panels */+.panel {+ position: fixed; z-index: 5;+ background: var(--glass);+ -webkit-backdrop-filter: blur(14px) saturate(1.2); backdrop-filter: blur(14px) saturate(1.2);+ border: 1px solid var(--line);+ border-radius: var(--radius);+ box-shadow: 0 6px 24px rgba(40, 35, 25, 0.08);+}++.panel button {+ background: none; border: 0; cursor: pointer;+ display: flex; flex-direction: column; align-items: center; gap: 3px;+ padding: 7px 8px; border-radius: 10px;+ color: var(--ink-soft);+ transition: background 0.15s, color 0.15s;+}+.panel button span { font-size: 9px; letter-spacing: 0.14em; text-transform: uppercase; }+.panel button:hover:not(:disabled) { color: var(--ink); background: rgba(42, 42, 51, 0.06); }+.panel button:disabled { opacity: 0.35; cursor: default; }+.panel button.on { color: var(--ink); background: rgba(42, 42, 51, 0.09); }+.panel button.danger { color: #a0281c; }++.tools {+ left: calc(14px + env(safe-area-inset-left)); top: 50%; transform: translateY(-50%);+ display: flex; flex-direction: column; gap: 2px; padding: 6px;+}+.tools .tool { width: 56px; }+.tools hr { width: 32px; border: 0; border-top: 1px solid var(--line); margin: 3px auto; }++/* current brush: a dab thumbnail that opens the library */+.tool.pick .thumb { width: 28px; height: 28px; display: block; }+.tool.pick .brushname { max-width: 52px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.panel .tool.pick.open { color: var(--ink); background: rgba(42, 42, 51, 0.09); }++/* brush library */+.library {+ left: calc(84px + env(safe-area-inset-left)); top: 50%; transform: translateY(-50%);+ width: 356px; max-height: calc(100vh - 28px);+ display: flex; flex-direction: column;+}+.library-head {+ display: grid; grid-template-columns: 1fr auto; align-items: start; column-gap: 8px;+ padding: 12px 10px 8px 14px; border-bottom: 1px solid var(--line);+}+.library-head > span:first-child { font-size: 9px; letter-spacing: 0.14em; text-transform: uppercase; color: var(--ink); }+.library-head .sub { grid-column: 1; font-size: 10px; color: var(--ink-faint); line-height: 1.4; margin-top: 3px; }+.library-head .icon { grid-column: 2; grid-row: 1 / span 2; }+.panel button.icon { padding: 4px; border-radius: 8px; flex-direction: row; }++.brushes {+ display: grid; grid-template-columns: 1fr 1fr; gap: 6px;+ padding: 10px; overflow-y: auto; overscroll-behavior: contain; scrollbar-width: thin;+}+.brush {+ position: relative; display: flex; flex-direction: column; gap: 4px;+ padding: 6px 8px 7px; border-radius: 10px; cursor: pointer;+ border: 1px solid transparent;+ background: rgba(255, 255, 255, 0.35);+ transition: background 0.15s, border-color 0.15s, transform 0.15s;+}+.brush:hover { background: rgba(255, 255, 255, 0.6); }+.brush:focus-visible { outline: 2px solid rgba(42, 42, 51, 0.5); outline-offset: 1px; }+.brush.on { background: rgba(255, 255, 255, 0.75); border-color: rgba(42, 42, 51, 0.55); }+.brush .stroke { width: 150px; height: 44px; display: block; max-width: 100%; }+.brush .label { font-size: 9px; letter-spacing: 0.14em; text-transform: uppercase; color: var(--ink-soft); }+.brush.on .label { color: var(--ink); }+.brush .remove { position: absolute; top: 4px; right: 4px; opacity: 0; color: var(--ink-faint); }+.brush:hover .remove, .brush.on .remove { opacity: 1; }+.brush .remove:hover { color: #a0281c; }++.library-foot { display: flex; align-items: center; gap: 10px; padding: 8px 10px 10px; border-top: 1px solid var(--line); }+.panel .import { flex-direction: row; gap: 6px; padding: 6px 10px; border: 1px dashed var(--ink-faint); }+.panel .import span { font-size: 9px; letter-spacing: 0.14em; text-transform: uppercase; }+.library-foot .note { font-size: 10px; color: var(--ink-faint); line-height: 1.35; }++.toast {+ position: fixed; left: 50%; top: calc(18px + env(safe-area-inset-top)); transform: translateX(-50%);+ z-index: 6; pointer-events: none;+ padding: 7px 14px; border-radius: 999px;+ background: rgba(42, 42, 51, 0.82); color: #f6f3ec;+ font-size: 10px; letter-spacing: 0.14em; text-transform: uppercase;+}++.actions {+ right: calc(14px + env(safe-area-inset-right)); top: calc(14px + env(safe-area-inset-top));+ display: flex; gap: 2px; padding: 5px;+}++.settings {+ right: calc(14px + env(safe-area-inset-right)); top: calc(84px + env(safe-area-inset-top));+ width: 230px; padding: 14px 16px 10px;+ display: flex; flex-direction: column; gap: 9px;+}+.slider { display: grid; grid-template-columns: 64px 1fr; align-items: center; gap: 10px; }+.slider span { font-size: 9px; letter-spacing: 0.14em; text-transform: uppercase; color: var(--ink-soft); }+.settings .reset { align-self: flex-end; padding: 4px 6px; font-size: 9px; letter-spacing: 0.14em; text-transform: uppercase; }++input[type="range"] {+ -webkit-appearance: none; appearance: none;+ width: 100%; height: 22px; background: transparent; margin: 0; cursor: pointer;+}+input[type="range"]::-webkit-slider-runnable-track { height: 1px; background: var(--ink-faint); }+input[type="range"]::-webkit-slider-thumb {+ -webkit-appearance: none; appearance: none;+ width: 12px; height: 12px; margin-top: -6px; border-radius: 50%;+ background: #f6f3ec; border: 1px solid rgba(42, 42, 51, 0.7);+}+input[type="range"]::-moz-range-track { height: 1px; background: var(--ink-faint); }+input[type="range"]::-moz-range-thumb { width: 11px; height: 11px; border-radius: 50%; background: #f6f3ec; border: 1px solid rgba(42, 42, 51, 0.7); }++.palette {+ left: 50%; transform: translateX(-50%);+ bottom: calc(14px + env(safe-area-inset-bottom));+ max-width: calc(100vw - 28px);+ padding: 8px 10px 6px;+ display: flex; flex-direction: column; align-items: center; gap: 4px;+}+.swatches { display: flex; gap: 6px; overflow-x: auto; max-width: 100%; padding: 4px 2px; scrollbar-width: none; }+.swatches::-webkit-scrollbar { display: none; }++.panel .swatch, .swatch {+ flex: 0 0 auto;+ width: 30px; height: 30px; padding: 0; border-radius: 47% 53% 50% 50% / 52% 48% 52% 48%;+ border: 1px solid rgba(42, 42, 51, 0.12);+ cursor: pointer; position: relative;+ transition: transform 0.15s ease, box-shadow 0.15s ease;+}+.panel .swatch:hover { transform: translateY(-2px); background-color: transparent; }+.swatch.on { transform: translateY(-3px) scale(1.08); box-shadow: 0 0 0 2px #f6f3ec, 0 0 0 3px rgba(42, 42, 51, 0.6); }+.swatch.custom {+ display: block; overflow: hidden;+ background: conic-gradient(from 30deg, #e0301e, #f6d409, #4f7d2a, #0e5a9c, #4b2c7a, #d0306a, #e0301e);+}+.swatch.custom input { opacity: 0; position: absolute; inset: 0; width: 100%; height: 100%; cursor: pointer; border: 0; padding: 0; }++.well { display: flex; gap: 12px; align-items: center; min-height: 16px; font-size: 9px; letter-spacing: 0.14em; text-transform: uppercase; color: var(--ink-soft); }+.well .mix { display: inline-flex; align-items: center; gap: 4px; color: var(--ink-faint); }+.well .mix i { display: inline-block; width: 10px; height: 10px; border-radius: 50%; border: 1px solid rgba(42, 42, 51, 0.15); }++.error {+ position: fixed; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center;+ font-size: 12px; letter-spacing: 0.2em; text-transform: uppercase; color: var(--ink-soft); padding: 24px; text-align: center;+}+.error .sub { color: var(--ink-faint); }++/* phones: compact chrome */+@media (max-width: 640px) {+ .tools { top: calc(10px + env(safe-area-inset-top)); left: calc(10px + env(safe-area-inset-left)); transform: none; flex-direction: row; }+ .tools .tool { width: auto; }+ .tools hr { width: 1px; height: 24px; border-top: 0; border-left: 1px solid var(--line); margin: auto 2px; }+ .actions { top: auto; bottom: calc(96px + env(safe-area-inset-bottom)); right: calc(10px + env(safe-area-inset-right)); }+ .panel button span { display: none; }+ .library {+ left: 10px; right: 10px; top: auto; transform: none; width: auto;+ bottom: calc(150px + env(safe-area-inset-bottom)); max-height: 46vh;+ }+ .library-head .sub, .library-foot .note { display: none; }+ .brush .stroke { width: 100%; height: 40px; }+ .panel .import span { display: inline; }+ .toast { top: calc(60px + env(safe-area-inset-top)); }+ .settings { top: auto; bottom: calc(150px + env(safe-area-inset-bottom)); right: 10px; }+ .palette { bottom: calc(10px + env(safe-area-inset-bottom)); }+}diff --git a/src/ui/customBrushes.ts b/src/ui/customBrushes.tsnew file mode 100644index 0000000..90715d0--- /dev/null+++ b/src/ui/customBrushes.ts@@ -0,0 +1,84 @@+import { buildBrush, CUSTOM_BASE, TIP_SIZE, type Brush } from '../engine/brushes';++const KEY = 'watercolor.customBrushes';++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> {+ const bmp = await createImageBitmap(file);+ const n = TIP_SIZE;+ const c = document.createElement('canvas');+ c.width = n; c.height = n;+ const ctx = c.getContext('2d', { willReadFrequently: true })!;+ const s = Math.min(n / bmp.width, n / bmp.height) * 0.96;+ const w = bmp.width * s, h = bmp.height * s;+ ctx.drawImage(bmp, (n - w) / 2, (n - h) / 2, w, h);+ bmp.close?.();+ const d = ctx.getImageData(0, 0, n, n).data;+ // Is the background light? Sample the border of the drawn image.+ let border = 0, count = 0, opaque = 0;+ const x0 = Math.floor((n - w) / 2), y0 = Math.floor((n - h) / 2), x1 = Math.ceil((n + w) / 2) - 1, y1 = Math.ceil((n + h) / 2) - 1;+ const lum = (i: number) => (0.2126 * d[i * 4] + 0.7152 * d[i * 4 + 1] + 0.0722 * d[i * 4 + 2]) / 255;+ for (let x = x0; x <= x1; x++) for (const y of [y0, y1]) { const i = y * n + x; if (d[i * 4 + 3] > 200) { border += lum(i); opaque++; } count++; }+ for (let y = y0; y <= y1; y++) for (const x of [x0, x1]) { const i = y * n + x; if (d[i * 4 + 3] > 200) { border += lum(i); opaque++; } count++; }+ const invert = opaque > count * 0.5 && border / opaque > 0.5;+ const out = new Uint8Array(n * n);+ let max = 0;+ const vals = new Float32Array(n * n);+ for (let i = 0; i < n * n; i++) {+ const a = d[i * 4 + 3] / 255;+ const v = a * (invert ? 1 - lum(i) : lum(i));+ vals[i] = v; if (v > max) max = v;+ }+ if (max <= 0) throw new Error('That image is empty.');+ for (let i = 0; i < n * n; i++) out[i] = Math.round((vals[i] / max) * 255);+ return out;+}++export function makeCustomBrush(id: string, name: string, tip: Uint8Array): Brush {+ return buildBrush({ ...CUSTOM_BASE, id, name, hint: 'Imported texture', tip, custom: true });+}++function tipToPng(tip: Uint8Array): string {+ const n = Math.round(Math.sqrt(tip.length));+ const c = document.createElement('canvas');+ c.width = n; c.height = n;+ const ctx = c.getContext('2d')!;+ const img = ctx.createImageData(n, n);+ for (let i = 0; i < n * n; i++) { img.data[i * 4] = img.data[i * 4 + 1] = img.data[i * 4 + 2] = tip[i]; img.data[i * 4 + 3] = 255; }+ ctx.putImageData(img, 0, 0);+ return c.toDataURL('image/png');+}++function readStored(): Stored[] {+ try { return JSON.parse(localStorage.getItem(KEY) ?? '[]') as Stored[]; } catch { return []; }+}++/** 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) }));+ localStorage.setItem(KEY, JSON.stringify(items));+ return true;+ } catch { return false; }+}++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 */ }+ }+ return out;+}diff --git a/src/ui/icons.ts b/src/ui/icons.tsnew file mode 100644index 0000000..0869c9e--- /dev/null+++ b/src/ui/icons.ts@@ -0,0 +1,21 @@+const PATHS: Record<string, string> = {+ brush: 'M19 3c-3 1.5-7.5 6-9.5 9l2.5 2.5c3-2 7.5-6.5 9-9.5L19 3ZM9 13.5c-2 0-3.5 1.5-3.5 3.5 0 1.5-1 2.5-2.5 3 3 1.5 8 1 8.5-3.5L9 13.5Z',+ water: 'M12 3.5c-3 4-6 7.2-6 10.5a6 6 0 0 0 12 0c0-3.3-3-6.5-6-10.5Z M9 14.5a3 3 0 0 0 3 3',+ pen: 'M14.5 4.5l5 5L9 20H4v-5L14.5 4.5Z M12.5 6.5l5 5 M4 20l5.5-5.5',+ lift: 'M5 8.5c2-1.5 4-1.5 6 0s4 1.5 6 0l2 9c-2 1.5-4 1.5-6 0s-4-1.5-6 0l-2-9Z M8 3.5c1 .8 2 .8 3 0',+ undo: 'M9 5.5 4 10.5l5 5 M4 10.5h10a4.75 4.75 0 0 1 0 9.5h-3',+ dry: 'M12 8a4 4 0 1 0 0 8 4 4 0 0 0 0-8Z M12 2v2.5 M12 19.5V22 M2 12h2.5 M19.5 12H22 M4.9 4.9l1.8 1.8 M17.3 17.3l1.8 1.8 M4.9 19.1l1.8-1.8 M17.3 6.7l1.8-1.8',+ clear: 'M5 7h14 M10 7V4.5h4V7 M7 7l1 13h8l1-13',+ save: 'M12 4v11 M7.5 10.5 12 15l4.5-4.5 M5 19.5h14',+ 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',+ close: 'M6 6l12 12 M18 6 6 18',+ chevron: 'M9 6l6 6-6 6',+};++/** Inline SVG markup for a 20px stroke icon. */+export function icon(name: string, size = 20): string {+ return `<svg viewBox="0 0 24 24" width="${size}" height="${size}" fill="none" stroke="currentColor" stroke-width="1.5"+ stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="${PATHS[name]}"/></svg>`;+}diff --git a/src/ui/preview.ts b/src/ui/preview.tsnew file mode 100644index 0000000..c588f31--- /dev/null+++ b/src/ui/preview.ts@@ -0,0 +1,99 @@+import { DEGREES, type Brush } from '../engine/brushes';+import { hexToRgb } from '../engine/spectral';++const tipCache = new Map<string, HTMLCanvasElement>();++/** The tip as a tinted RGBA image (alpha = tip value). */+export function tipImage(b: Brush, hex: string): HTMLCanvasElement {+ const key = `${b.id}|${hex}`;+ let c = tipCache.get(key);+ if (c) return c;+ const n = b.tipSize;+ c = document.createElement('canvas');+ c.width = n; c.height = n;+ const ctx = c.getContext('2d')!;+ const img = ctx.createImageData(n, n);+ const [r, g, bl] = hexToRgb(hex).map(v => Math.round(v * 255));+ for (let i = 0; i < n * n; i++) {+ img.data[i * 4] = r; img.data[i * 4 + 1] = g; img.data[i * 4 + 2] = bl;+ img.data[i * 4 + 3] = b.tipData[i];+ }+ ctx.putImageData(img, 0, 0);+ tipCache.set(key, c);+ return c;+}++export function forgetTipImages(id: string) {+ for (const k of [...tipCache.keys()]) if (k.startsWith(`${id}|`)) tipCache.delete(k);+}++function prepare(canvas: HTMLCanvasElement) {+ const dpr = Math.min(window.devicePixelRatio || 1, 2);+ // logical size: the CSS box when laid out, else the markup's size (hidden panels have no layout)+ if (!canvas.dataset.w) { canvas.dataset.w = String(canvas.clientWidth || canvas.width); canvas.dataset.h = String(canvas.clientHeight || canvas.height); }+ const w = Number(canvas.dataset.w), h = Number(canvas.dataset.h);+ canvas.width = Math.round(w * dpr); canvas.height = Math.round(h * dpr);+ const ctx = canvas.getContext('2d')!;+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);+ ctx.clearRect(0, 0, w, h);+ return { ctx, w, h };+}++/** A single dab, showing the tip's shape at its resting angle. */+export function drawThumb(canvas: HTMLCanvasElement, b: Brush, hex: string) {+ const { ctx, w, h } = prepare(canvas);+ const img = tipImage(b, hex);+ const R = Math.min(w, h) * 0.46;+ const angle = b.rotation === 'random' ? 0.5 : b.rotation === 'follow' ? b.angle * DEGREES : b.angle * DEGREES;+ ctx.save();+ ctx.translate(w / 2, h / 2);+ ctx.rotate(-angle);+ ctx.globalAlpha = 0.9;+ if (b.dabs > 1) {+ for (let i = 0; i < b.dabs; i++) {+ const a = (i / b.dabs) * Math.PI * 2 + 0.7, m = R * (0.2 + 0.7 * ((i * 7919) % 13) / 13), s = R * 0.22 * (0.4 + ((i * 104729) % 7) / 7);+ ctx.drawImage(img, Math.cos(a) * m - s, Math.sin(a) * m - s, s * 2, s * 2);+ }+ } else {+ ctx.drawImage(img, -R, -R * b.aspect, R * 2, R * 2 * b.aspect);+ }+ ctx.restore();+}++/** A short pressure-shaped stroke painted with the brush's dab rules. */+export function drawStroke(canvas: HTMLCanvasElement, b: Brush, hex: string) {+ const { ctx, w, h } = prepare(canvas);+ const img = tipImage(b, hex);+ // scale so the biggest brushes fit and the smallest stay visible+ const R = Math.min(h * 0.42, Math.max(3.5, 15 * Math.sqrt(b.size[1] / 0.05)));+ const norm = Math.min(Math.max(Math.sqrt(0.5 / b.tipMean), 0.7), 2.2);+ const alpha = Math.min(0.85, Math.max(0.05, 0.42 * Math.min(b.spacing, 1) * Math.sqrt(b.aspect) * norm * b.load));+ const x0 = 10, x1 = w - 10, ym = h / 2;+ const point = (t: number) => ({ x: x0 + (x1 - x0) * t, y: ym + Math.sin(t * Math.PI * 2) * h * 0.14 });+ let seed = 17;+ const rnd = () => { seed = (seed * 16807) % 2147483647; return seed / 2147483647; };+ const spacing = Math.max(1, R * b.spacing * Math.sqrt(b.aspect));+ const length = (x1 - x0) * 1.08;+ let fixedAngle = b.angle * DEGREES;+ ctx.globalAlpha = alpha;+ for (let d = 0; d <= length; d += spacing) {+ const t = d / length;+ const p = point(t), q = point(Math.min(1, t + 0.01));+ const pr = Math.min(1, Math.max(0.2, Math.sin(t * Math.PI) * 1.15));+ const r = R * (0.25 + 0.75 * Math.pow(pr, b.pressureSize));+ const dir = Math.atan2(-(q.y - p.y), q.x - p.x);+ for (let i = 0; i < b.dabs; i++) {+ let angle = b.rotation === 'random' ? rnd() * Math.PI * 2 : b.rotation === 'follow' ? dir + b.angle * DEGREES : fixedAngle;+ angle += (rnd() - 0.5) * 2 * b.angleJitter * DEGREES;+ let x = p.x, y = p.y, rr = r;+ if (b.scatter) { const a = rnd() * Math.PI * 2, m = Math.sqrt(rnd()) * b.scatter * r; x += Math.cos(a) * m; y += Math.sin(a) * m; }+ if (b.sizeJitter) rr *= Math.max(0.15, 1 + (rnd() * 2 - 1) * b.sizeJitter);+ ctx.save();+ ctx.translate(x, y);+ ctx.rotate(-angle);+ ctx.drawImage(img, -rr, -rr * b.aspect, rr * 2, rr * 2 * b.aspect);+ ctx.restore();+ }+ }+ ctx.globalAlpha = 1;+}diff --git a/tsconfig.json b/tsconfig.jsonnew file mode 100644index 0000000..75947b0--- /dev/null+++ b/tsconfig.json@@ -0,0 +1,17 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "lib": ["ES2022", "DOM", "DOM.Iterable"],+ "module": "ESNext",+ "moduleResolution": "bundler",+ "strict": true,+ "noUnusedLocals": true,+ "noUnusedParameters": true,+ "noFallthroughCasesInSwitch": true,+ "isolatedModules": true,+ "skipLibCheck": true,+ "noEmit": true,+ "types": ["vite/client"]+ },+ "include": ["src", "vite.config.ts"]+}diff --git a/vite.config.ts b/vite.config.tsnew file mode 100644index 0000000..0229c22--- /dev/null+++ b/vite.config.ts@@ -0,0 +1,6 @@+import { defineConfig } from 'vite';++export default defineConfig({+ base: './',+ server: { host: true },+});