azulejeria 2.5.1 → 2.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +62 -0
- package/package.json +4 -3
- package/src/azulejeria.css +43 -0
- package/src/azulejeria.js +103 -16
- package/src/draw.js +448 -0
- package/test/draw.mjs +53 -0
package/README.md
CHANGED
|
@@ -26,6 +26,8 @@ Azulejería's tiles with it, and
|
|
|
26
26
|
[Knotwork](https://stepinto.dev/art/knotwork.html) is the viewer with the knots. The design is
|
|
27
27
|
written up [here](https://stepinto.dev/posts/tiles-painted-by-rule/) and
|
|
28
28
|
[here](https://stepinto.dev/posts/cut-tile-and-poured-cement/).
|
|
29
|
+
[Octavo](https://stepinto.dev/art/octavo.html) is the wall with a pad beside it: you draw one eighth of
|
|
30
|
+
the tile and the wall paints the rest (see Draw below).
|
|
29
31
|
|
|
30
32
|
```
|
|
31
33
|
npm install azulejeria
|
|
@@ -329,6 +331,66 @@ A beast's head is traced from a drawing of an Insular hound's head
|
|
|
329
331
|
hooks round under it and into its jaws. `eye` colours its eye.
|
|
330
332
|
`strandPath` and `ribbon` are exported for drawing a strand yourself.
|
|
331
333
|
|
|
334
|
+
## Draw
|
|
335
|
+
|
|
336
|
+
```js
|
|
337
|
+
import { drawnMotif, DRAW_PAINTERS, mountPad, encodeDrawing, decodeDrawing } from 'azulejeria/draw';
|
|
338
|
+
|
|
339
|
+
const wall = createWall(canvas, {
|
|
340
|
+
palettes, presets,
|
|
341
|
+
motifs: { drawn: drawnMotif() },
|
|
342
|
+
painters: { ...PAINTERS, ...DRAW_PAINTERS },
|
|
343
|
+
});
|
|
344
|
+
mountPanel(wall, { fileName: 'mine' });
|
|
345
|
+
mountPad(wall, { onEdit: d => history.replaceState(null, '', '?d=' + d) });
|
|
346
|
+
```
|
|
347
|
+
|
|
348
|
+
A tile painted by hand, one eighth of it. Every design is symmetric
|
|
349
|
+
across the diagonal of its square, so a hand only has to draw the
|
|
350
|
+
triangle under that diagonal, from the main corner to the far one. The
|
|
351
|
+
wall is an ordinary wall: the drawing is its motif, so the repeats, the
|
|
352
|
+
groups, the palettes, the brush and any material apply to it.
|
|
353
|
+
[Octavo](https://stepinto.dev/art/octavo.html) is this and nothing else.
|
|
354
|
+
|
|
355
|
+
A drawing is a list of strokes `{ k, c, w, pts }`: the kind (`line`,
|
|
356
|
+
`shape` or `dot`), the colour (0 the wash, 1 to 3 an accent, 4 the ink),
|
|
357
|
+
the weight (1 to 8) and the points in design coordinates.
|
|
358
|
+
**`encodeDrawing(strokes)`** packs it into a short string, two bytes a
|
|
359
|
+
point, base64url; **`decodeDrawing(string)`** reads it back and gives an
|
|
360
|
+
empty drawing for anything it cannot read. The string lives in the
|
|
361
|
+
wall's state (`state.d` unless you name another key), so a preset can
|
|
362
|
+
carry a drawing and so can a query string or a stored value.
|
|
363
|
+
|
|
364
|
+
**`drawnMotif(key)`** is the motif that paints `state[key]`. A motif's
|
|
365
|
+
context now carries `state` for this. **`DRAW_PAINTERS`** has the one
|
|
366
|
+
painter it needs, `stroke`, which paints each stroke on its own side of
|
|
367
|
+
the diagonal and again reflected, with the same drift and the same
|
|
368
|
+
brush, so a petal drawn across the diagonal comes out whole. A shape is
|
|
369
|
+
washed and inked, an ink line is a line, a coloured line is a ribbon. A
|
|
370
|
+
material's `shape`, `line` and `dot` are used when it has them.
|
|
371
|
+
|
|
372
|
+
**`mountPad(wall, { key, onEdit })`** wires the pad. The page provides
|
|
373
|
+
`#pad` holding a canvas `#padCanvas`, buttons `.tool[data-tool]`
|
|
374
|
+
(`line`, `shape`, `dot`), an empty `#swatches`, a range `#weight` with
|
|
375
|
+
`#weightVal`, buttons `#undo` and `#clear`, and `#padHead` with
|
|
376
|
+
`#padToggle`; `azulejeria.css` styles them. The pad shows the square in
|
|
377
|
+
the wall's palette and material with the reflected half dimmed. A
|
|
378
|
+
stroke drawn on the dimmed side is reflected over. The wall repaints
|
|
379
|
+
while the pen moves. Cmd or Ctrl Z undoes. **`settle(stroke)`**,
|
|
380
|
+
**`simplify(pts, eps)`** and **`smooth(pts, closed, times)`** are what
|
|
381
|
+
the pad does to a raw stroke, exported for a page with its own input.
|
|
382
|
+
|
|
383
|
+
## Print
|
|
384
|
+
|
|
385
|
+
**`exportTile(wall, { cm, dpi, bleed })`** paints the wall's tile once
|
|
386
|
+
at print size and resolves to a PNG blob: 15 cm at 300 dpi with a 3 mm
|
|
387
|
+
bleed unless told otherwise (1842 pixels square). The bleed is the tile
|
|
388
|
+
mirrored out past each edge. The file carries its dpi (a `pHYs` chunk;
|
|
389
|
+
**`pngWithDpi(bytes, dpi)`** does that to any PNG), so it opens at the
|
|
390
|
+
right size. `mountPanel` wires it to a `#order` button when the page has
|
|
391
|
+
one (`opts.print` is passed on); with `mountChrome`, pass
|
|
392
|
+
`order: () => exportTile(wall)` in the spec.
|
|
393
|
+
|
|
332
394
|
## Licence
|
|
333
395
|
|
|
334
396
|
MIT.
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "azulejeria",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.6.0",
|
|
4
4
|
"description": "Tin-glazed tiles painted by rule. A seeded canvas engine for Spanish azulejo walls: a diagonal-symmetric design, brushwork that drifts, washes that pool, and four ways to repeat the tile.",
|
|
5
|
-
"keywords": ["canvas", "generative", "wallpaper-groups", "symmetry", "tiles", "azulejo", "mudejar", "sevilla", "pattern", "procedural", "art", "wallpaper", "interlace", "knotwork", "celtic", "mosaic", "voronoi", "trencadis"],
|
|
5
|
+
"keywords": ["canvas", "generative", "wallpaper-groups", "symmetry", "tiles", "azulejo", "mudejar", "sevilla", "pattern", "procedural", "art", "wallpaper", "interlace", "knotwork", "celtic", "mosaic", "voronoi", "trencadis", "drawing", "print"],
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"author": "Andy Cross",
|
|
8
8
|
"homepage": "https://stepinto.dev/art/azulejeria.html",
|
|
@@ -15,11 +15,12 @@
|
|
|
15
15
|
"./knots": "./src/knots.js",
|
|
16
16
|
"./pieces": "./src/pieces.js",
|
|
17
17
|
"./groups": "./src/groups.js",
|
|
18
|
+
"./draw": "./src/draw.js",
|
|
18
19
|
"./azulejeria.css": "./src/azulejeria.css"
|
|
19
20
|
},
|
|
20
21
|
"files": ["src", "test", "README.md", "LICENSE"],
|
|
21
22
|
"sideEffects": false,
|
|
22
23
|
"scripts": {
|
|
23
|
-
"test": "node --check src/azulejeria.js && node --check src/knots.js && node --check src/head.js && node --check src/pieces.js && node --check src/groups.js && node test/groups.mjs"
|
|
24
|
+
"test": "node --check src/azulejeria.js && node --check src/knots.js && node --check src/head.js && node --check src/pieces.js && node --check src/groups.js && node --check src/draw.js && node test/groups.mjs && node test/draw.mjs"
|
|
24
25
|
}
|
|
25
26
|
}
|
package/src/azulejeria.css
CHANGED
|
@@ -136,3 +136,46 @@ input[type="checkbox"] { accent-color: var(--az-accent); }
|
|
|
136
136
|
}
|
|
137
137
|
.btn:active { background: var(--az-card-on); }
|
|
138
138
|
#mood { font-size: 0.62rem; opacity: 0.5; margin-top: 0.45rem; letter-spacing: 0.15em; text-align: center; }
|
|
139
|
+
|
|
140
|
+
/* the drawing pad (azulejeria/draw): bottom left, the square of the
|
|
141
|
+
design with the tools under it */
|
|
142
|
+
#pad {
|
|
143
|
+
position: fixed; left: 1rem; bottom: 1rem; z-index: 20;
|
|
144
|
+
width: 246px;
|
|
145
|
+
font-family: "Courier New", monospace; font-size: 0.72rem;
|
|
146
|
+
color: rgba(242, 234, 214, 0.85);
|
|
147
|
+
background: var(--az-panel);
|
|
148
|
+
border: 1px solid rgba(242, 234, 214, 0.15);
|
|
149
|
+
border-radius: 10px;
|
|
150
|
+
backdrop-filter: blur(8px);
|
|
151
|
+
user-select: none;
|
|
152
|
+
}
|
|
153
|
+
#padHead {
|
|
154
|
+
display: flex; justify-content: space-between; align-items: center;
|
|
155
|
+
padding: 0.55rem 0.8rem; cursor: pointer;
|
|
156
|
+
letter-spacing: 0.18em; text-transform: uppercase; font-size: 0.66rem;
|
|
157
|
+
}
|
|
158
|
+
#padBody { padding: 0 0.8rem 0.8rem; }
|
|
159
|
+
#pad.closed #padBody { display: none; }
|
|
160
|
+
#pad canvas { width: 100%; height: auto; aspect-ratio: 1; border-radius: 6px; cursor: crosshair; }
|
|
161
|
+
#pad canvas:active { cursor: crosshair; }
|
|
162
|
+
.tools { display: flex; gap: 5px; margin-top: 0.55rem; }
|
|
163
|
+
.tools button {
|
|
164
|
+
flex: 1; padding: 0.35rem 0;
|
|
165
|
+
background: var(--az-field); color: rgba(242, 234, 214, 0.7);
|
|
166
|
+
border: 1px solid rgba(242, 234, 214, 0.2); border-radius: 5px;
|
|
167
|
+
font-family: inherit; font-size: 0.62rem; cursor: pointer;
|
|
168
|
+
letter-spacing: 0.12em; text-transform: uppercase;
|
|
169
|
+
}
|
|
170
|
+
.tools button.on { color: #f2ead6; border-color: var(--az-accent-soft); background: var(--az-card-on); }
|
|
171
|
+
.tools button:active { background: var(--az-card-on); }
|
|
172
|
+
#swatches { display: flex; gap: 6px; margin-top: 0.55rem; }
|
|
173
|
+
.sw {
|
|
174
|
+
flex: 1; height: 22px; padding: 0; cursor: pointer;
|
|
175
|
+
border: 1px solid rgba(242, 234, 214, 0.25); border-radius: 5px;
|
|
176
|
+
}
|
|
177
|
+
.sw.on { outline: 2px solid var(--az-accent); outline-offset: 1px; }
|
|
178
|
+
.btn:disabled { opacity: 0.6; cursor: progress; }
|
|
179
|
+
@media (max-width: 520px) {
|
|
180
|
+
#pad { width: 178px; left: 0.6rem; bottom: 0.6rem; }
|
|
181
|
+
}
|
package/src/azulejeria.js
CHANGED
|
@@ -49,8 +49,10 @@ export function hexA(hex, a) {
|
|
|
49
49
|
// elements, each `{ t: 'painterName', ...params }`. The context carries
|
|
50
50
|
// the seeded rng and a few helpers every motif wants: `pick` one of a
|
|
51
51
|
// list, `role` (wash or one of the accents), and `dots` for the
|
|
52
|
-
// scatter that higher densities add.
|
|
53
|
-
|
|
52
|
+
// scatter that higher densities add. `state`, if given, is the wall's
|
|
53
|
+
// state, for a motif that paints something the state carries (a
|
|
54
|
+
// drawing, say) rather than what the seed grows.
|
|
55
|
+
export function makeDesign(seed, density, bands, bold, motif, state) {
|
|
54
56
|
const rng = mulberry32(seed);
|
|
55
57
|
bold = bold || 1; // single tiles carry the motif larger
|
|
56
58
|
const pick = arr => arr[Math.floor(rng() * arr.length)];
|
|
@@ -63,7 +65,7 @@ export function makeDesign(seed, density, bands, bold, motif) {
|
|
|
63
65
|
}
|
|
64
66
|
return { t: 'dots', dots: d };
|
|
65
67
|
};
|
|
66
|
-
return motif({ rng, density, bands, bold, pick, role, dots });
|
|
68
|
+
return motif({ rng, density, bands, bold, pick, role, dots, state });
|
|
67
69
|
}
|
|
68
70
|
|
|
69
71
|
// ---------------------------------------------------------- brushwork ---
|
|
@@ -235,7 +237,7 @@ export function paintDesign(g, els, pal, hand, lw, jseed, painters, material, br
|
|
|
235
237
|
const amp = m.ampOf ? m.ampOf(hand) : 0.012 * hand;
|
|
236
238
|
const Q = Math.PI / 2, D = Q / 2;
|
|
237
239
|
const dc = Math.cos(D), ds = Math.sin(D); // the diagonal
|
|
238
|
-
const b = { g, pal, lw, amp, rng, Q, D, dc, ds, col: pal.wash, hand, brush: brush === undefined ? 1 : brush };
|
|
240
|
+
const b = { g, pal, lw, amp, rng, Q, D, dc, ds, col: pal.wash, hand, brush: brush === undefined ? 1 : brush, material: material || null };
|
|
239
241
|
const shape = m.shape
|
|
240
242
|
? (pts, col) => m.shape(g, pts, col, b)
|
|
241
243
|
: (pts, col) => { wash(g, pts, col, rng); ink(g, pts, lw, pal, rng, true); };
|
|
@@ -334,7 +336,7 @@ const ROT = [0, Math.PI / 2, 3 * Math.PI / 2, Math.PI];
|
|
|
334
336
|
export function tileOpts(cfg, s) {
|
|
335
337
|
const pal = cfg.palettes[s.pal];
|
|
336
338
|
const quarter = s.repeat === 'single' || s.repeat === 'checker';
|
|
337
|
-
const design = makeDesign(s.seed, s.density, s.bands, quarter ? 1.35 : 1, cfg.motifs[s.motif]);
|
|
339
|
+
const design = makeDesign(s.seed, s.density, s.bands, quarter ? 1.35 : 1, cfg.motifs[s.motif], s);
|
|
338
340
|
return { pal, design, quarter, hand: s.hand, brush: s.brush, painters: cfg.painters, material: cfg.material };
|
|
339
341
|
}
|
|
340
342
|
|
|
@@ -468,6 +470,78 @@ export function paintThumb(cfg, p, g, T, k) {
|
|
|
468
470
|
}
|
|
469
471
|
}
|
|
470
472
|
|
|
473
|
+
// -------------------------------------------------------------- print ---
|
|
474
|
+
// exportTile(wall, { cm, dpi, bleed }) paints the wall's tile once at
|
|
475
|
+
// print size, for someone to have it made: 15 cm at 300 dpi by default
|
|
476
|
+
// (1772 pixels), with a bleed of 3 mm all round. The bleed is the tile
|
|
477
|
+
// mirrored out past each edge, which is what its neighbour is in the
|
|
478
|
+
// module and close enough under the other repeats for a cutter's
|
|
479
|
+
// tolerance. It resolves to a PNG blob that says its own dpi, so it
|
|
480
|
+
// opens at the right size. A checker exports its painted tile.
|
|
481
|
+
export function exportTile(wall, opts) {
|
|
482
|
+
opts = opts || {};
|
|
483
|
+
const cm = opts.cm || 15, dpi = opts.dpi || 300, bleedMm = opts.bleed === undefined ? 3 : opts.bleed;
|
|
484
|
+
const px = Math.round(cm / 2.54 * dpi), bl = Math.round(bleedMm / 25.4 * dpi);
|
|
485
|
+
const cfg = { palettes: wall.palettes, motifs: wall.motifs, painters: wall.painters, material: wall.material };
|
|
486
|
+
const tile = makeTile(tileOpts(cfg, wall.state), px, 1, wall.state.seed * 31);
|
|
487
|
+
const c = document.createElement('canvas');
|
|
488
|
+
c.width = c.height = px + 2 * bl;
|
|
489
|
+
const g = c.getContext('2d');
|
|
490
|
+
for (const fy of [-1, 0, 1]) for (const fx of [-1, 0, 1]) {
|
|
491
|
+
if ((fx || fy) && !bl) continue;
|
|
492
|
+
g.save();
|
|
493
|
+
g.translate(bl + px / 2 + fx * px, bl + px / 2 + fy * px);
|
|
494
|
+
g.scale(fx ? -1 : 1, fy ? -1 : 1);
|
|
495
|
+
g.drawImage(tile, -px / 2, -px / 2);
|
|
496
|
+
g.restore();
|
|
497
|
+
}
|
|
498
|
+
return new Promise((resolve, reject) => c.toBlob(blob => {
|
|
499
|
+
if (!blob) { reject(new Error('the tile could not be encoded')); return; }
|
|
500
|
+
blob.arrayBuffer().then(buf => resolve(new Blob([pngWithDpi(new Uint8Array(buf), dpi)], { type: 'image/png' })), reject);
|
|
501
|
+
}, 'image/png'));
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
let CRC_TABLE = null;
|
|
505
|
+
export function crc32(bytes) {
|
|
506
|
+
if (!CRC_TABLE) {
|
|
507
|
+
CRC_TABLE = new Uint32Array(256);
|
|
508
|
+
for (let n = 0; n < 256; n++) {
|
|
509
|
+
let c = n;
|
|
510
|
+
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
|
511
|
+
CRC_TABLE[n] = c >>> 0;
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
let c = 0xffffffff;
|
|
515
|
+
for (let i = 0; i < bytes.length; i++) c = CRC_TABLE[(c ^ bytes[i]) & 255] ^ (c >>> 8);
|
|
516
|
+
return (c ^ 0xffffffff) >>> 0;
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
// a PNG's bytes with a pHYs chunk saying `dpi`, replacing one it has
|
|
520
|
+
export function pngWithDpi(png, dpi) {
|
|
521
|
+
const ppm = Math.round(dpi / 0.0254);
|
|
522
|
+
const chunk = new Uint8Array(21), v = new DataView(chunk.buffer);
|
|
523
|
+
v.setUint32(0, 9);
|
|
524
|
+
chunk.set([112, 72, 89, 115], 4); // pHYs
|
|
525
|
+
v.setUint32(8, ppm); v.setUint32(12, ppm);
|
|
526
|
+
chunk[16] = 1; // per metre
|
|
527
|
+
v.setUint32(17, crc32(chunk.subarray(4, 17)));
|
|
528
|
+
const dv = new DataView(png.buffer, png.byteOffset, png.byteLength);
|
|
529
|
+
let at = 8, after = 33; // the signature, then IHDR
|
|
530
|
+
while (at + 8 <= png.length) {
|
|
531
|
+
const len = dv.getUint32(at), type = String.fromCharCode(...png.subarray(at + 4, at + 8));
|
|
532
|
+
if (type === 'pHYs') {
|
|
533
|
+
const out = new Uint8Array(png.length - (len + 12) + 21);
|
|
534
|
+
out.set(png.subarray(0, at)); out.set(chunk, at); out.set(png.subarray(at + len + 12), at + 21);
|
|
535
|
+
return out;
|
|
536
|
+
}
|
|
537
|
+
if (type === 'IDAT' || type === 'IEND') break;
|
|
538
|
+
at += len + 12;
|
|
539
|
+
}
|
|
540
|
+
const out = new Uint8Array(png.length + 21);
|
|
541
|
+
out.set(png.subarray(0, after)); out.set(chunk, after); out.set(png.subarray(after), after + 21);
|
|
542
|
+
return out;
|
|
543
|
+
}
|
|
544
|
+
|
|
471
545
|
// ------------------------------------------------------------- viewer ---
|
|
472
546
|
// createViewer(canvas, { paint, scale, minZoom, maxZoom, margin }) is
|
|
473
547
|
// a canvas you paint a world into. It fills the window, and handles
|
|
@@ -741,8 +815,10 @@ export function createWall(canvas, cfg) {
|
|
|
741
815
|
// query string sets it; `change(value)` is what to do after. Then
|
|
742
816
|
// `newId` and `onNew` for the button that starts over, `mood(state)`
|
|
743
817
|
// for the line under it, `query(q)` for anything else in the query
|
|
744
|
-
// string, `fileName` and `suffix(state)` for the saved png,
|
|
745
|
-
// `
|
|
818
|
+
// string, `fileName` and `suffix(state)` for the saved png,
|
|
819
|
+
// `order(state)` (a promise of a blob) for the `#order` button that
|
|
820
|
+
// saves one tile at print size, and `ready()` once everything is
|
|
821
|
+
// applied.
|
|
746
822
|
export function mountChrome(viewer, spec) {
|
|
747
823
|
const doc = spec.document || document;
|
|
748
824
|
const $ = id => doc.getElementById(id);
|
|
@@ -804,14 +880,23 @@ export function mountChrome(viewer, spec) {
|
|
|
804
880
|
const on = (id, ev, fn) => { const el = $(id); if (el) el.addEventListener(ev, fn); };
|
|
805
881
|
if (spec.onNew) on(spec.newId || 'newDesign', 'click', () => { spec.onNew(); sync(); });
|
|
806
882
|
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
883
|
+
const download = (blob, tail) => {
|
|
884
|
+
const a = doc.createElement('a');
|
|
885
|
+
a.href = URL.createObjectURL(blob);
|
|
886
|
+
a.download = (spec.fileName || 'wall') + '-' + tail + (spec.suffix ? spec.suffix(state) : state.seed) + '.png';
|
|
887
|
+
a.click();
|
|
888
|
+
setTimeout(() => URL.revokeObjectURL(a.href), 4000);
|
|
889
|
+
};
|
|
890
|
+
on('save', 'click', () => viewer.canvas.toBlob(blob => download(blob, '')));
|
|
891
|
+
if (spec.order) on('order', 'click', () => {
|
|
892
|
+
const btn = $('order'), label = btn.textContent;
|
|
893
|
+
btn.disabled = true; btn.textContent = 'painting the tile…';
|
|
894
|
+
// let the button say so before the paint holds the page
|
|
895
|
+
setTimeout(() => Promise.resolve()
|
|
896
|
+
.then(() => spec.order(state))
|
|
897
|
+
.then(blob => download(blob, 'tile-'))
|
|
898
|
+
.catch(e => console.error(e))
|
|
899
|
+
.finally(() => { btn.disabled = false; btn.textContent = label; }), 30);
|
|
815
900
|
});
|
|
816
901
|
|
|
817
902
|
const panel = $('panel');
|
|
@@ -868,7 +953,8 @@ export function mountChrome(viewer, spec) {
|
|
|
868
953
|
// tile wall's controls: selects `repeat`, `motif` and `palette`; ranges
|
|
869
954
|
// `density`, `hand`, `brush` and `zoom` with `densityVal`, `handVal`,
|
|
870
955
|
// `brushVal` and `zoomVal` beside them; checkboxes `bands`, `grout` and
|
|
871
|
-
// `age`; the `newDesign` button
|
|
956
|
+
// `age`; the `newDesign` button; the `order` button, which saves one
|
|
957
|
+
// tile at print size (`opts.print` is passed to `exportTile`). The query string takes ?preset=,
|
|
872
958
|
// ?seed=, ?repeat=, ?pal=, ?motif=, ?density=, ?hand=, ?zoom=, ?bands=0
|
|
873
959
|
// and ?age=1.
|
|
874
960
|
export function mountPanel(wall, opts) {
|
|
@@ -897,6 +983,7 @@ export function mountPanel(wall, opts) {
|
|
|
897
983
|
mood: s => 'design nº ' + s.seed,
|
|
898
984
|
query: q => { if (q.has('seed')) { state.seed = parseInt(q.get('seed'), 10) || state.seed; wall.preset = ''; } },
|
|
899
985
|
fileName: opts.fileName,
|
|
986
|
+
order: () => exportTile(wall, opts.print),
|
|
900
987
|
ready: tiles,
|
|
901
988
|
});
|
|
902
989
|
}
|
package/src/draw.js
ADDED
|
@@ -0,0 +1,448 @@
|
|
|
1
|
+
// draw: a tile painted by hand, one eighth of it.
|
|
2
|
+
//
|
|
3
|
+
// Every design the engine paints is symmetric across the diagonal of its
|
|
4
|
+
// square, and the repeats do the rest. So a hand only has to draw half
|
|
5
|
+
// of the square, the triangle under the diagonal from the main corner
|
|
6
|
+
// (0, 0) to the far corner (1, 1): an eighth of a quartered tile. This
|
|
7
|
+
// module turns that drawing into a motif. Each stroke is painted once on
|
|
8
|
+
// its own side of the diagonal, clipped there, and again reflected onto
|
|
9
|
+
// the other side with the same drift, so a petal drawn across the
|
|
10
|
+
// diagonal comes out whole and symmetric.
|
|
11
|
+
//
|
|
12
|
+
// A drawing is a list of strokes `{ k, c, w, pts }`: the kind (`line`,
|
|
13
|
+
// `shape` or `dot`), the colour (0 the wash, 1 to 3 an accent, 4 the
|
|
14
|
+
// ink), the weight (1 to 8) and the points in design coordinates. It is
|
|
15
|
+
// carried in a wall's state as a short string (`encodeDrawing`), two
|
|
16
|
+
// bytes a point, so it fits in a query string or a stored value.
|
|
17
|
+
//
|
|
18
|
+
// import { drawnMotif, DRAW_PAINTERS, mountPad } from 'azulejeria/draw';
|
|
19
|
+
// const wall = createWall(canvas, { motifs: { drawn: drawnMotif() },
|
|
20
|
+
// painters: { ...PAINTERS, ...DRAW_PAINTERS }, ... });
|
|
21
|
+
// mountPad(wall);
|
|
22
|
+
|
|
23
|
+
import { mulberry32, wash, ink, makeDesign, paintDesign, hexA } from './azulejeria.js';
|
|
24
|
+
|
|
25
|
+
export const KINDS = ['line', 'shape', 'dot'];
|
|
26
|
+
export const MAX_POINTS = 96; // a stroke is simplified until it has no more than this
|
|
27
|
+
|
|
28
|
+
// ----------------------------------------------------------- encoding ---
|
|
29
|
+
// A version byte, then per stroke a header byte (kind in bits 0-1,
|
|
30
|
+
// colour in 2-4, weight less one in 5-7), a point count and the points,
|
|
31
|
+
// x then y, each a byte over the unit square. Base64url.
|
|
32
|
+
const byte = v => Math.max(0, Math.min(255, Math.round(v * 255)));
|
|
33
|
+
|
|
34
|
+
export function encodeDrawing(strokes) {
|
|
35
|
+
const bytes = [1];
|
|
36
|
+
for (const s of strokes || []) {
|
|
37
|
+
const k = KINDS.indexOf(s.k);
|
|
38
|
+
const pts = (s.pts || []).slice(0, 255);
|
|
39
|
+
if (k < 0 || !pts.length) continue;
|
|
40
|
+
const c = Math.max(0, Math.min(4, s.c | 0)), w = Math.max(1, Math.min(8, s.w | 0));
|
|
41
|
+
bytes.push(k | (c << 2) | ((w - 1) << 5), pts.length);
|
|
42
|
+
for (const [x, y] of pts) bytes.push(byte(x), byte(y));
|
|
43
|
+
}
|
|
44
|
+
if (bytes.length === 1) return '';
|
|
45
|
+
let bin = '';
|
|
46
|
+
for (const b of bytes) bin += String.fromCharCode(b);
|
|
47
|
+
return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// anything it cannot read it drops: a drawing from a bad link is empty
|
|
51
|
+
export function decodeDrawing(str) {
|
|
52
|
+
if (!str || typeof str !== 'string') return [];
|
|
53
|
+
let bin;
|
|
54
|
+
try { bin = atob(str.replace(/-/g, '+').replace(/_/g, '/')); } catch (e) { return []; }
|
|
55
|
+
if (bin.charCodeAt(0) !== 1) return [];
|
|
56
|
+
const out = [];
|
|
57
|
+
let i = 1;
|
|
58
|
+
while (i + 2 <= bin.length) {
|
|
59
|
+
const h = bin.charCodeAt(i++), n = bin.charCodeAt(i++);
|
|
60
|
+
if (!n || i + 2 * n > bin.length) break;
|
|
61
|
+
const pts = [];
|
|
62
|
+
for (let j = 0; j < n; j++) pts.push([bin.charCodeAt(i++) / 255, bin.charCodeAt(i++) / 255]);
|
|
63
|
+
const k = KINDS[h & 3], c = (h >> 2) & 7;
|
|
64
|
+
if (k && c <= 4) out.push({ k, c, w: (h >> 5) + 1, pts });
|
|
65
|
+
}
|
|
66
|
+
return out;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// ------------------------------------------------------------ strokes ---
|
|
70
|
+
// Ramer-Douglas-Peucker: drop the points a line through their
|
|
71
|
+
// neighbours would pass within `eps` of
|
|
72
|
+
export function simplify(pts, eps) {
|
|
73
|
+
if (pts.length < 3) return pts.slice();
|
|
74
|
+
const keep = new Uint8Array(pts.length);
|
|
75
|
+
keep[0] = keep[pts.length - 1] = 1;
|
|
76
|
+
const stack = [[0, pts.length - 1]];
|
|
77
|
+
while (stack.length) {
|
|
78
|
+
const [a, b] = stack.pop();
|
|
79
|
+
const [ax, ay] = pts[a], [bx, by] = pts[b];
|
|
80
|
+
const dx = bx - ax, dy = by - ay, dl = Math.hypot(dx, dy);
|
|
81
|
+
let far = -1, fd = eps;
|
|
82
|
+
for (let i = a + 1; i < b; i++) {
|
|
83
|
+
const [px, py] = pts[i];
|
|
84
|
+
const d = dl ? Math.abs(dy * (px - ax) - dx * (py - ay)) / dl : Math.hypot(px - ax, py - ay);
|
|
85
|
+
if (d > fd) { fd = d; far = i; }
|
|
86
|
+
}
|
|
87
|
+
if (far > 0) { keep[far] = 1; stack.push([a, far], [far, b]); }
|
|
88
|
+
}
|
|
89
|
+
return pts.filter((_, i) => keep[i]);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Chaikin's corners, cut twice: a hand's polyline as a curve
|
|
93
|
+
export function smooth(pts, closed, times) {
|
|
94
|
+
let p = pts;
|
|
95
|
+
for (let t = 0; t < (times === undefined ? 2 : times); t++) {
|
|
96
|
+
if (p.length < 3) return p;
|
|
97
|
+
const q = closed ? [] : [p[0]];
|
|
98
|
+
const n = closed ? p.length : p.length - 1;
|
|
99
|
+
for (let i = 0; i < n; i++) {
|
|
100
|
+
const a = p[i], b = p[(i + 1) % p.length];
|
|
101
|
+
q.push([a[0] * 0.75 + b[0] * 0.25, a[1] * 0.75 + b[1] * 0.25], [a[0] * 0.25 + b[0] * 0.75, a[1] * 0.25 + b[1] * 0.75]);
|
|
102
|
+
}
|
|
103
|
+
if (!closed) q.push(p[p.length - 1]);
|
|
104
|
+
p = q;
|
|
105
|
+
}
|
|
106
|
+
return p;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const swap = pts => pts.map(([x, y]) => [y, x]);
|
|
110
|
+
|
|
111
|
+
// A stroke as it is kept: inside the square, on the drawn side of the
|
|
112
|
+
// diagonal (a stroke drawn mostly on the other side is reflected over),
|
|
113
|
+
// and simplified to no more than MAX_POINTS.
|
|
114
|
+
export function settle(stroke) {
|
|
115
|
+
let pts = stroke.pts.map(([x, y]) => [Math.max(0, Math.min(1, x)), Math.max(0, Math.min(1, y))]);
|
|
116
|
+
if (!pts.length) return null;
|
|
117
|
+
const lean = pts.reduce((s, [x, y]) => s + (y - x), 0);
|
|
118
|
+
if (lean > 0) pts = swap(pts);
|
|
119
|
+
if (stroke.k === 'dot') pts = [pts[0]];
|
|
120
|
+
else {
|
|
121
|
+
let eps = 0.004;
|
|
122
|
+
pts = simplify(pts, eps);
|
|
123
|
+
while (pts.length > MAX_POINTS) pts = simplify(pts, eps *= 1.5);
|
|
124
|
+
if (stroke.k === 'shape' && pts.length < 3) return null;
|
|
125
|
+
if (stroke.k === 'line' && pts.length < 2) return null;
|
|
126
|
+
}
|
|
127
|
+
return { k: stroke.k, c: stroke.c | 0, w: stroke.w | 0 || 1, pts };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// a band either side of a polyline, as a closed outline
|
|
131
|
+
function ribbon(pts, h) {
|
|
132
|
+
const L = [], R = [];
|
|
133
|
+
for (let i = 0; i < pts.length; i++) {
|
|
134
|
+
const a = pts[Math.max(0, i - 1)], c = pts[Math.min(pts.length - 1, i + 1)];
|
|
135
|
+
const dx = c[0] - a[0], dy = c[1] - a[1], d = Math.hypot(dx, dy) || 1;
|
|
136
|
+
const nx = -dy / d * h, ny = dx / d * h;
|
|
137
|
+
L.push([pts[i][0] + nx, pts[i][1] + ny]);
|
|
138
|
+
R.push([pts[i][0] - nx, pts[i][1] - ny]);
|
|
139
|
+
}
|
|
140
|
+
return L.concat(R.reverse());
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// The brush's drift along a whole stroke: two slow sines across its
|
|
144
|
+
// length, pushed along the normal. The engine's `polyPts` drifts each
|
|
145
|
+
// side of a polygon, which suits a shape with a few long sides; a
|
|
146
|
+
// hand's stroke is hundreds of short ones and wants one drift from end
|
|
147
|
+
// to end. A closed stroke takes whole numbers of waves so it closes.
|
|
148
|
+
// Four numbers from the rng, whatever the stroke.
|
|
149
|
+
function drift(pts, closed, amp, rng) {
|
|
150
|
+
const p1 = rng() * 6.283, p2 = rng() * 6.283, a = rng(), b = rng();
|
|
151
|
+
const n = pts.length;
|
|
152
|
+
if (n < 2 || !amp) return pts;
|
|
153
|
+
const len = [0];
|
|
154
|
+
for (let i = 1; i < n; i++) len.push(len[i - 1] + Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1]));
|
|
155
|
+
const total = (len[n - 1] + (closed ? Math.hypot(pts[0][0] - pts[n - 1][0], pts[0][1] - pts[n - 1][1]) : 0)) || 1;
|
|
156
|
+
// so many waves to a tile's side, not to a stroke: a short stroke gets part of one
|
|
157
|
+
const k = Math.max(0.3, Math.min(2.5, total / 0.8));
|
|
158
|
+
const f1 = closed ? Math.max(1, Math.round((2 + a) * k)) : (1.5 + a * 2) * k;
|
|
159
|
+
const f2 = closed ? Math.max(2, Math.round((5 + b * 3) * k)) : (4 + b * 4) * k;
|
|
160
|
+
return pts.map((p, i) => {
|
|
161
|
+
const q = pts[closed ? (i - 1 + n) % n : Math.max(0, i - 1)], r = pts[closed ? (i + 1) % n : Math.min(n - 1, i + 1)];
|
|
162
|
+
const dx = r[0] - q[0], dy = r[1] - q[1], d = Math.hypot(dx, dy) || 1, t = len[i] / total * 6.283;
|
|
163
|
+
const w = (Math.sin(t * f1 + p1) * 0.65 + Math.sin(t * f2 + p2) * 0.35) * amp;
|
|
164
|
+
return [p[0] - dy / d * w, p[1] + dx / d * w];
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// two layers the size of the tile, for the halves of a glazed stroke
|
|
169
|
+
let LAYERS = null;
|
|
170
|
+
function layers(g) {
|
|
171
|
+
const w = g.canvas.width, h = g.canvas.height;
|
|
172
|
+
if (!LAYERS) LAYERS = [0, 1].map(() => { const c = document.createElement('canvas'); return c.getContext('2d'); });
|
|
173
|
+
for (const l of LAYERS) {
|
|
174
|
+
if (l.canvas.width !== w || l.canvas.height !== h) { l.canvas.width = w; l.canvas.height = h; }
|
|
175
|
+
else { l.setTransform(1, 0, 0, 1, 0, 0); l.clearRect(0, 0, w, h); }
|
|
176
|
+
l.setTransform(g.getTransform());
|
|
177
|
+
l.lineCap = 'round'; l.lineJoin = 'round';
|
|
178
|
+
}
|
|
179
|
+
return LAYERS;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// ----------------------------------------------------------- painters ---
|
|
183
|
+
// `stroke` paints one stroke of a drawing and its reflection. The drift
|
|
184
|
+
// is laid once and the brush's random numbers are dealt the same to
|
|
185
|
+
// both halves, so the two meet on the diagonal without a seam in the
|
|
186
|
+
// line. Glaze is translucent, so its halves are painted on a layer
|
|
187
|
+
// each, clipped exactly at the diagonal, and added together: where the
|
|
188
|
+
// two soft edges share a pixel their cover sums to one, and no hairline
|
|
189
|
+
// shows. A material's `shape`, `line` and `dot` are used when it has
|
|
190
|
+
// them, so a drawing comes out in clay or cement as readily as in
|
|
191
|
+
// glaze; those are opaque and paint straight on, the drawn half a hair
|
|
192
|
+
// past the diagonal. A coloured line is a ribbon, which is a shape.
|
|
193
|
+
export const DRAW_PAINTERS = {
|
|
194
|
+
stroke(el, b) {
|
|
195
|
+
const { g, pal } = b;
|
|
196
|
+
const m = b.material || {};
|
|
197
|
+
const seed = Math.floor(b.rng() * 2147483647);
|
|
198
|
+
const col = el.c === 4 ? pal.ink
|
|
199
|
+
: el.c === 0 || !pal.accents.length ? pal.wash
|
|
200
|
+
: pal.accents[(el.c - 1) % pal.accents.length];
|
|
201
|
+
const t = g.getTransform ? g.getTransform() : { a: 100, b: 0 };
|
|
202
|
+
const eps = 0.8 / (Math.hypot(t.a, t.b) || 100);
|
|
203
|
+
const width = b.lw * el.w;
|
|
204
|
+
const r0 = mulberry32(seed);
|
|
205
|
+
|
|
206
|
+
let path = null;
|
|
207
|
+
const fill = el.k === 'shape' || (el.k === 'line' && el.c !== 4);
|
|
208
|
+
if (el.k === 'shape' && el.pts.length >= 3) path = drift(smooth(el.pts, true, 3), true, b.amp, r0);
|
|
209
|
+
else if (el.k === 'line' && el.pts.length >= 2) {
|
|
210
|
+
const line = drift(smooth(el.pts, false, 3), false, b.amp, r0);
|
|
211
|
+
path = el.c === 4 ? line : ribbon(line, width * 0.9);
|
|
212
|
+
} else if (el.k !== 'dot') return;
|
|
213
|
+
const own = m.shape || m.line || m.dot; // the material paints, straight onto the tile
|
|
214
|
+
const L = own ? null : layers(g);
|
|
215
|
+
|
|
216
|
+
const rng0 = b.rng, col0 = b.col, g0 = g;
|
|
217
|
+
for (const half of [0, 1]) {
|
|
218
|
+
const rr = mulberry32(seed + 1);
|
|
219
|
+
const g = L ? L[half] : g0, e = L ? 0 : eps;
|
|
220
|
+
g.save();
|
|
221
|
+
g.beginPath();
|
|
222
|
+
if (half) { g.moveTo(-1, -1); g.lineTo(2, 2); g.lineTo(-1, 2); }
|
|
223
|
+
else { g.moveTo(-1, -1); g.lineTo(-1, -1 + e); g.lineTo(2, 2 + e); g.lineTo(2, -1); }
|
|
224
|
+
g.closePath();
|
|
225
|
+
g.clip();
|
|
226
|
+
b.rng = rr; b.col = col;
|
|
227
|
+
if (el.k === 'dot') {
|
|
228
|
+
for (const [x0, y0] of el.pts) {
|
|
229
|
+
const [x, y] = half ? [y0, x0] : [x0, y0], r = width * 0.8;
|
|
230
|
+
if (m.dot) m.dot(g, x, y, r, col, 0.88, b);
|
|
231
|
+
else { g.beginPath(); g.arc(x, y, r, 0, 6.283); g.fillStyle = col; g.globalAlpha = 0.88; g.fill(); g.globalAlpha = 1; }
|
|
232
|
+
}
|
|
233
|
+
} else {
|
|
234
|
+
const P = half ? swap(path) : path;
|
|
235
|
+
if (fill) {
|
|
236
|
+
if (m.shape) m.shape(g, P, col, b);
|
|
237
|
+
else { wash(g, P, col, rr); ink(g, P, b.lw, pal, rr, true); }
|
|
238
|
+
} else if (m.line) m.line(g, P, width, false, b);
|
|
239
|
+
else ink(g, P, width, pal, rr, false);
|
|
240
|
+
}
|
|
241
|
+
g.restore();
|
|
242
|
+
}
|
|
243
|
+
b.rng = rng0; b.col = col0;
|
|
244
|
+
if (L) {
|
|
245
|
+
L[0].setTransform(1, 0, 0, 1, 0, 0);
|
|
246
|
+
L[0].globalCompositeOperation = 'lighter';
|
|
247
|
+
L[0].drawImage(L[1].canvas, 0, 0);
|
|
248
|
+
L[0].globalCompositeOperation = 'source-over';
|
|
249
|
+
g0.save(); g0.setTransform(1, 0, 0, 1, 0, 0); g0.drawImage(L[0].canvas, 0, 0); g0.restore();
|
|
250
|
+
}
|
|
251
|
+
},
|
|
252
|
+
};
|
|
253
|
+
|
|
254
|
+
// ------------------------------------------------------------- motif ---
|
|
255
|
+
// The motif that paints the drawing in `state[key]` ('d' by default),
|
|
256
|
+
// with the engine's band across the far corner when bands are on.
|
|
257
|
+
export function drawnMotif(key) {
|
|
258
|
+
key = key || 'd';
|
|
259
|
+
return ({ state, bands }) => {
|
|
260
|
+
const els = decodeDrawing(state && state[key]).map(s => ({ t: 'stroke', ...s }));
|
|
261
|
+
if (bands) els.push({ t: 'band', kind: 'circle', w: 0.045, role: 'wash' });
|
|
262
|
+
return els;
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
// --------------------------------------------------------------- pad ---
|
|
267
|
+
// mountPad(wall, opts) wires a drawing pad to a wall whose motif is
|
|
268
|
+
// `drawnMotif`. The page provides, inside `#pad`: a canvas `#padCanvas`;
|
|
269
|
+
// buttons `.tool[data-tool]` (line, shape, dot); an empty `#swatches`
|
|
270
|
+
// the palette's colours are put in; a range `#weight`; buttons `#undo`
|
|
271
|
+
// and `#clear`; and `#padHead` with `#padToggle` to fold it. Anything
|
|
272
|
+
// missing is skipped. The pad shows the square of the design in the
|
|
273
|
+
// wall's own palette, brush and material, with the reflected half
|
|
274
|
+
// dimmed; you draw in the bright half. Every stroke is written to
|
|
275
|
+
// `wall.state[key]` and the wall repaints, while you draw as well as
|
|
276
|
+
// after. `opts.onEdit(d)` hears each change (to put it in the address,
|
|
277
|
+
// say). Cmd or Ctrl Z undoes. Returns `{ render, undo, clear }`.
|
|
278
|
+
export function mountPad(wall, opts) {
|
|
279
|
+
opts = opts || {};
|
|
280
|
+
const doc = opts.document || document;
|
|
281
|
+
const $ = id => doc.getElementById(id);
|
|
282
|
+
const key = opts.key || 'd';
|
|
283
|
+
const canvas = $(opts.canvasId || 'padCanvas');
|
|
284
|
+
const { state } = wall;
|
|
285
|
+
const pen = { tool: 'shape', c: 0, w: 3 };
|
|
286
|
+
const history = [];
|
|
287
|
+
let strokes = decodeDrawing(state[key]), seen = state[key], live = null, liveTimer = 0, queued = false, palSeen = null;
|
|
288
|
+
const M = 10; // the margin round the square, css pixels
|
|
289
|
+
|
|
290
|
+
function write(list) {
|
|
291
|
+
state[key] = encodeDrawing(list);
|
|
292
|
+
seen = state[key];
|
|
293
|
+
wall.preset = '';
|
|
294
|
+
wall.rebuild(true);
|
|
295
|
+
if (opts.onEdit) opts.onEdit(state[key]);
|
|
296
|
+
}
|
|
297
|
+
function commit(next) {
|
|
298
|
+
history.push(strokes);
|
|
299
|
+
if (history.length > 200) history.shift();
|
|
300
|
+
strokes = next;
|
|
301
|
+
write(strokes);
|
|
302
|
+
schedule();
|
|
303
|
+
}
|
|
304
|
+
function undo() { if (history.length) { strokes = history.pop(); write(strokes); schedule(); } }
|
|
305
|
+
function clear() { if (strokes.length) commit([]); }
|
|
306
|
+
|
|
307
|
+
function swatches(pal) {
|
|
308
|
+
const box = $('swatches');
|
|
309
|
+
if (!box) return;
|
|
310
|
+
const cols = [pal.wash, ...pal.accents.slice(0, 3), pal.ink];
|
|
311
|
+
const ids = [0, ...pal.accents.slice(0, 3).map((_, i) => i + 1), 4];
|
|
312
|
+
if (!ids.includes(pen.c)) pen.c = 0;
|
|
313
|
+
box.innerHTML = '';
|
|
314
|
+
ids.forEach((c, i) => {
|
|
315
|
+
const s = doc.createElement('button');
|
|
316
|
+
s.className = 'sw' + (c === pen.c ? ' on' : '');
|
|
317
|
+
s.style.background = cols[i];
|
|
318
|
+
s.title = c === 0 ? 'wash' : c === 4 ? 'ink' : 'accent ' + c;
|
|
319
|
+
s.addEventListener('click', () => { pen.c = c; box.querySelectorAll('.sw').forEach(x => x.classList.toggle('on', x === s)); });
|
|
320
|
+
box.appendChild(s);
|
|
321
|
+
});
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
function render() {
|
|
325
|
+
queued = false;
|
|
326
|
+
if (!canvas) return;
|
|
327
|
+
if (state[key] !== seen) { strokes = decodeDrawing(state[key]); seen = state[key]; history.length = 0; }
|
|
328
|
+
const pal = wall.palettes[state.pal];
|
|
329
|
+
if (pal !== palSeen) { palSeen = pal; swatches(pal); }
|
|
330
|
+
const W = canvas.clientWidth || 200, DPR = Math.min(window.devicePixelRatio || 1, 2);
|
|
331
|
+
if (canvas.width !== Math.round(W * DPR)) { canvas.width = canvas.height = Math.round(W * DPR); }
|
|
332
|
+
const g = canvas.getContext('2d');
|
|
333
|
+
const S = W - 2 * M;
|
|
334
|
+
g.setTransform(DPR, 0, 0, DPR, 0, 0);
|
|
335
|
+
g.fillStyle = pal.grout; g.fillRect(0, 0, W, W);
|
|
336
|
+
g.translate(M, M);
|
|
337
|
+
g.fillStyle = pal.glaze; g.fillRect(0, 0, S, S);
|
|
338
|
+
const m = wall.material || {};
|
|
339
|
+
if (m.surface) m.surface(g, S, pal, mulberry32(state.seed));
|
|
340
|
+
g.lineCap = 'round'; g.lineJoin = 'round';
|
|
341
|
+
g.save(); g.scale(S, S);
|
|
342
|
+
const list = live ? strokes.concat([settle(live) || []]).filter(s => s.pts) : strokes;
|
|
343
|
+
const view = { ...state, [key]: encodeDrawing(list) };
|
|
344
|
+
const design = makeDesign(state.seed, state.density, state.bands, 1, wall.motifs[state.motif], view);
|
|
345
|
+
paintDesign(g, design, pal, state.hand, 0.012 * state.brush, state.seed * 31 + 17, wall.painters, wall.material, state.brush);
|
|
346
|
+
// the reflected half, dimmed, and the diagonal
|
|
347
|
+
g.beginPath(); g.moveTo(0, 0); g.lineTo(1, 1); g.lineTo(0, 1); g.closePath();
|
|
348
|
+
g.fillStyle = hexA(pal.grout, 0.55); g.fill();
|
|
349
|
+
g.restore();
|
|
350
|
+
g.setLineDash([3, 4]); g.strokeStyle = hexA(pal.ink, 0.45); g.lineWidth = 1;
|
|
351
|
+
g.beginPath(); g.moveTo(0, 0); g.lineTo(S, S); g.stroke(); g.setLineDash([]);
|
|
352
|
+
// the main corner, where four tiles (or the four quarters) meet
|
|
353
|
+
g.beginPath(); g.arc(0, 0, 4, 0, 6.283); g.fillStyle = hexA(pal.ink, 0.7); g.fill();
|
|
354
|
+
// the stroke under the pen, as drawn
|
|
355
|
+
if (live && live.pts.length > 1) {
|
|
356
|
+
g.beginPath();
|
|
357
|
+
live.pts.forEach(([x, y], i) => (i ? g.lineTo(x * S, y * S) : g.moveTo(x * S, y * S)));
|
|
358
|
+
if (live.k === 'shape') g.closePath();
|
|
359
|
+
g.strokeStyle = hexA(pal.ink, 0.6); g.lineWidth = 1.2; g.stroke();
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
function schedule() { if (!queued) { queued = true; requestAnimationFrame(render); } }
|
|
363
|
+
|
|
364
|
+
// the wall tells the pad when the palette, brush, preset or seed changes
|
|
365
|
+
const rebuild = wall.rebuild;
|
|
366
|
+
wall.rebuild = t => { rebuild(t); schedule(); };
|
|
367
|
+
const changed = wall.onChange;
|
|
368
|
+
wall.onChange = k => { if (changed) changed(k); schedule(); };
|
|
369
|
+
|
|
370
|
+
if (canvas) {
|
|
371
|
+
const at = e => {
|
|
372
|
+
const r = canvas.getBoundingClientRect(), S = r.width - 2 * M;
|
|
373
|
+
return [(e.clientX - r.left - M) / S, (e.clientY - r.top - M) / S];
|
|
374
|
+
};
|
|
375
|
+
canvas.addEventListener('pointerdown', e => {
|
|
376
|
+
e.preventDefault();
|
|
377
|
+
canvas.setPointerCapture(e.pointerId);
|
|
378
|
+
const p = at(e);
|
|
379
|
+
if (pen.tool === 'dot') {
|
|
380
|
+
const s = settle({ k: 'dot', c: pen.c, w: pen.w, pts: [p] });
|
|
381
|
+
if (s) commit(strokes.concat([s]));
|
|
382
|
+
return;
|
|
383
|
+
}
|
|
384
|
+
live = { k: pen.tool, c: pen.c, w: pen.w, pts: [p] };
|
|
385
|
+
schedule();
|
|
386
|
+
});
|
|
387
|
+
canvas.addEventListener('pointermove', e => {
|
|
388
|
+
if (!live) return;
|
|
389
|
+
const p = at(e), q = live.pts[live.pts.length - 1];
|
|
390
|
+
if (Math.hypot(p[0] - q[0], p[1] - q[1]) < 0.004) return;
|
|
391
|
+
live.pts.push(p);
|
|
392
|
+
schedule();
|
|
393
|
+
// the wall follows the pen, a few times a second
|
|
394
|
+
if (!liveTimer) liveTimer = setTimeout(() => {
|
|
395
|
+
liveTimer = 0;
|
|
396
|
+
if (!live) return;
|
|
397
|
+
const s = settle(live);
|
|
398
|
+
state[key] = encodeDrawing(s ? strokes.concat([s]) : strokes);
|
|
399
|
+
seen = state[key];
|
|
400
|
+
wall.rebuild(true);
|
|
401
|
+
}, 70);
|
|
402
|
+
});
|
|
403
|
+
const end = () => {
|
|
404
|
+
if (!live) return;
|
|
405
|
+
const s = settle(live);
|
|
406
|
+
live = null;
|
|
407
|
+
clearTimeout(liveTimer); liveTimer = 0;
|
|
408
|
+
if (s) commit(strokes.concat([s]));
|
|
409
|
+
else { write(strokes); schedule(); }
|
|
410
|
+
};
|
|
411
|
+
canvas.addEventListener('pointerup', end);
|
|
412
|
+
canvas.addEventListener('pointercancel', end);
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
doc.querySelectorAll('.tool[data-tool]').forEach(btn => {
|
|
416
|
+
btn.classList.toggle('on', btn.dataset.tool === pen.tool);
|
|
417
|
+
btn.addEventListener('click', () => {
|
|
418
|
+
pen.tool = btn.dataset.tool;
|
|
419
|
+
doc.querySelectorAll('.tool[data-tool]').forEach(x => x.classList.toggle('on', x === btn));
|
|
420
|
+
});
|
|
421
|
+
});
|
|
422
|
+
const weight = $('weight');
|
|
423
|
+
if (weight) {
|
|
424
|
+
weight.value = pen.w;
|
|
425
|
+
const val = $('weightVal');
|
|
426
|
+
if (val) val.textContent = pen.w;
|
|
427
|
+
weight.addEventListener('input', () => { pen.w = parseInt(weight.value, 10) || 1; if (val) val.textContent = pen.w; });
|
|
428
|
+
}
|
|
429
|
+
const on = (id, fn) => { const el = $(id); if (el) el.addEventListener('click', fn); };
|
|
430
|
+
on('undo', undo);
|
|
431
|
+
on('clear', clear);
|
|
432
|
+
doc.addEventListener('keydown', e => {
|
|
433
|
+
if ((e.metaKey || e.ctrlKey) && !e.shiftKey && e.key.toLowerCase() === 'z' && !/^(INPUT|SELECT|TEXTAREA)$/.test(e.target.tagName)) {
|
|
434
|
+
e.preventDefault(); undo();
|
|
435
|
+
}
|
|
436
|
+
});
|
|
437
|
+
const box = $('pad');
|
|
438
|
+
on('padHead', () => {
|
|
439
|
+
if (!box) return;
|
|
440
|
+
box.classList.toggle('closed');
|
|
441
|
+
const t = $('padToggle');
|
|
442
|
+
if (t) t.textContent = box.classList.contains('closed') ? '+' : '−';
|
|
443
|
+
schedule();
|
|
444
|
+
});
|
|
445
|
+
window.addEventListener('resize', schedule);
|
|
446
|
+
schedule();
|
|
447
|
+
return { render: schedule, undo, clear };
|
|
448
|
+
}
|
package/test/draw.mjs
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// The drawing's encoding, the stroke settling and the print export's PNG chunk.
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { encodeDrawing, decodeDrawing, settle, simplify, smooth, drawnMotif } from '../src/draw.js';
|
|
4
|
+
import { crc32, pngWithDpi } from '../src/azulejeria.js';
|
|
5
|
+
|
|
6
|
+
const near = (a, b) => Math.abs(a - b) <= 1 / 255;
|
|
7
|
+
const drawing = [
|
|
8
|
+
{ k: 'shape', c: 0, w: 3, pts: [[0.1, 0.05], [0.4, 0.1], [0.3, 0.25]] },
|
|
9
|
+
{ k: 'line', c: 4, w: 1, pts: [[0.5, 0], [0.8, 0.2], [1, 0.5]] },
|
|
10
|
+
{ k: 'line', c: 2, w: 8, pts: [[0.5, 0.1], [0.9, 0.4]] },
|
|
11
|
+
{ k: 'dot', c: 3, w: 5, pts: [[0.7, 0.3]] },
|
|
12
|
+
];
|
|
13
|
+
const back = decodeDrawing(encodeDrawing(drawing));
|
|
14
|
+
assert.equal(back.length, drawing.length);
|
|
15
|
+
back.forEach((s, i) => {
|
|
16
|
+
assert.equal(s.k, drawing[i].k); assert.equal(s.c, drawing[i].c); assert.equal(s.w, drawing[i].w);
|
|
17
|
+
s.pts.forEach((p, j) => assert.ok(near(p[0], drawing[i].pts[j][0]) && near(p[1], drawing[i].pts[j][1])));
|
|
18
|
+
});
|
|
19
|
+
// encoding what was decoded gives the same string: a link is stable
|
|
20
|
+
assert.equal(encodeDrawing(back), encodeDrawing(drawing));
|
|
21
|
+
assert.match(encodeDrawing(drawing), /^[A-Za-z0-9_-]+$/);
|
|
22
|
+
assert.equal(encodeDrawing([]), '');
|
|
23
|
+
for (const bad of ['', null, '!!!', 'AAAA', 'AQ', 'AQEB', 'not a drawing']) assert.deepEqual(decodeDrawing(bad), []);
|
|
24
|
+
|
|
25
|
+
// a stroke drawn on the far side of the diagonal is reflected over
|
|
26
|
+
const s = settle({ k: 'line', c: 0, w: 2, pts: [[0.1, 0.5], [0.2, 0.9], [-0.3, 1.4]] });
|
|
27
|
+
assert.ok(s.pts.every(([x, y]) => y <= x && x >= 0 && x <= 1 && y >= 0 && y <= 1));
|
|
28
|
+
assert.equal(settle({ k: 'shape', c: 0, w: 2, pts: [[0, 0], [1, 0]] }), null);
|
|
29
|
+
assert.equal(settle({ k: 'dot', c: 0, w: 2, pts: [[0.2, 0.1], [0.5, 0.5]] }).pts.length, 1);
|
|
30
|
+
// a long scribble comes down to a stroke that fits
|
|
31
|
+
const scribble = Array.from({ length: 4000 }, (_, i) => [0.5 + 0.4 * Math.cos(i / 9) * (i / 4000), 0.3 + 0.2 * Math.sin(i / 7)]);
|
|
32
|
+
assert.ok(settle({ k: 'line', c: 0, w: 1, pts: scribble }).pts.length <= 96);
|
|
33
|
+
assert.equal(simplify([[0, 0], [0.5, 0.0001], [1, 0]], 0.004).length, 2);
|
|
34
|
+
assert.equal(smooth([[0, 0], [1, 0], [1, 1]], false)[0][0], 0);
|
|
35
|
+
|
|
36
|
+
// the motif reads the drawing from the state it is given
|
|
37
|
+
const els = drawnMotif()({ state: { d: encodeDrawing(drawing) }, bands: true });
|
|
38
|
+
assert.equal(els.length, 5);
|
|
39
|
+
assert.equal(els[0].t, 'stroke'); assert.equal(els[4].t, 'band');
|
|
40
|
+
assert.deepEqual(drawnMotif()({ state: {}, bands: false }), []);
|
|
41
|
+
|
|
42
|
+
// crc32 of "IEND" is the last four bytes of every PNG
|
|
43
|
+
assert.equal(crc32(new TextEncoder().encode('IEND')), 0xae426082);
|
|
44
|
+
// a 1x1 PNG gains a pHYs chunk after IHDR, and keeps one rather than two
|
|
45
|
+
const png = Uint8Array.from(Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==', 'base64'));
|
|
46
|
+
const out = pngWithDpi(png, 300);
|
|
47
|
+
assert.equal(out.length, png.length + 21);
|
|
48
|
+
assert.equal(String.fromCharCode(...out.subarray(37, 41)), 'pHYs');
|
|
49
|
+
assert.equal(new DataView(out.buffer).getUint32(41), 11811);
|
|
50
|
+
const again = pngWithDpi(out, 150);
|
|
51
|
+
assert.equal(again.length, out.length);
|
|
52
|
+
assert.equal(new DataView(again.buffer).getUint32(41), 5906);
|
|
53
|
+
console.log('draw: encoding, settling, motif and the print chunk hold');
|