azulejeria 2.6.0 → 2.7.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 CHANGED
@@ -10,24 +10,60 @@ a polyline with a slow wobble along its normal, the way a loaded brush
10
10
  drifts. Washes are laid thin twice so the glaze pools. Each tile gets its
11
11
  own mottled glaze, a slight turn, a slight shift, and a few of them craze.
12
12
 
13
- This package is the engine. You bring the motifs, the palettes and the
14
- presets, and, if the tile is not glazed, a material. Three walls built on
15
- it: [Azulejería](https://stepinto.dev/art/azulejeria.html) (Talavera
16
- rosettes and Mudéjar strapwork), [Jerez](https://stepinto.dev/art/jerez.html)
17
- (vines, horses and sherry) and [Hidráulico](https://stepinto.dev/art/hidraulico.html)
18
- (pigmented cement, pressed rather than painted). Underneath the wall is a
19
- viewer, a canvas you paint any world into, with the drag, the pinch, the
20
- wheel and the page chrome; [Alicatado](https://stepinto.dev/art/alicatado.html)
21
- (cut tile set in lime) is the viewer with the cutter below,
22
- [Papel Pintado](https://stepinto.dev/art/papelpintado.html) is the wall laid
23
- by any of the seventeen wallpaper groups,
24
- [Trencadís](https://stepinto.dev/art/trencadis.html) is the viewer breaking
25
- Azulejería's tiles with it, and
26
- [Knotwork](https://stepinto.dev/art/knotwork.html) is the viewer with the knots. The design is
27
- written up [here](https://stepinto.dev/posts/tiles-painted-by-rule/) and
13
+ This package is the engine. It started as that one wall and is now a
14
+ small kit for pattern made by rule and painted to look like a material.
15
+ You bring the motifs, the palettes and the presets, and, if the tile is
16
+ not glazed, a material.
17
+
18
+ ## What is in it
19
+
20
+ | Import | What it is | Section |
21
+ |---|---|---|
22
+ | `azulejeria` | The tile wall, the viewer it is built on, the panel and page chrome, the brush and its geometry, corner tiles for borders, one tile at print size | A wall in forty lines, The parts, Print |
23
+ | `azulejeria/pieces` | The cutter: a polygon inset, shifted, turned and bevelled, and a Voronoi for things that are broken | Pieces |
24
+ | `azulejeria/groups` | The seventeen wallpaper groups as a way to lay any tile | Groups |
25
+ | `azulejeria/knots` | Interlace on a grid: over and under by parity, breaks, cuts and beasts | Knots |
26
+ | `azulejeria/draw` | A tile drawn by hand, one eighth of it, carried in a string | Draw |
27
+ | `azulejeria/shadow` | A sun that goes round and the shadows it casts | Shadow |
28
+ | `azulejeria/loom` | Weaving drafts, setts and the cloth they make | Loom |
29
+ | `azulejeria/azulejeria.css` | The styles for the panel, the cards, the title and the pad | The parts |
30
+
31
+ Each module stands alone except `draw`, which paints with the wall's
32
+ brush. `knots`, `groups`, `pieces`, `shadow` and `loom` draw on any 2D
33
+ context.
34
+
35
+ ## Built on it
36
+
37
+ Tile walls (`createWall`):
38
+ [Azulejería](https://stepinto.dev/art/azulejeria.html) (Talavera rosettes and Mudéjar strapwork),
39
+ [Jerez](https://stepinto.dev/art/jerez.html) (vines, horses and sherry),
40
+ [Hidráulico](https://stepinto.dev/art/hidraulico.html) (pigmented cement, pressed and not painted),
41
+ [Delft](https://stepinto.dev/art/delft.html) (a figure in the middle of every tile),
42
+ [Fajalauza](https://stepinto.dev/art/fajalauza.html) (Granada's green and blue on cream),
43
+ [Rosa y Granada](https://stepinto.dev/art/rosaygranada.html) and
44
+ [Encaustic](https://stepinto.dev/art/encaustic.html) (clay inlaid in clay, medieval and Victorian),
45
+ [Papel Pintado](https://stepinto.dev/art/papelpintado.html) (block-printed paper laid by any of the seventeen groups) and
46
+ [Octavo](https://stepinto.dev/art/octavo.html) (you draw one eighth of the tile and the wall paints the rest).
47
+
48
+ Other worlds on the viewer (`createViewer`):
49
+ [Alicatado](https://stepinto.dev/art/alicatado.html) (cut tile set in lime, with the cutter),
50
+ [Trencadís](https://stepinto.dev/art/trencadis.html) (Azulejería's tiles broken and relaid),
51
+ [Sutton Hoo](https://stepinto.dev/art/suttonhoo.html) (garnet cells through the cutter, a buckle in knots),
52
+ [Knotwork](https://stepinto.dev/art/knotwork.html) (insular interlace on vellum),
53
+ [Sebka](https://stepinto.dev/art/sebka.html) (a brick lattice under a sun you can move),
54
+ [Rejería](https://stepinto.dev/art/rejeria.html) (wrought iron and its shadow on whitewash),
55
+ [Jali](https://stepinto.dev/art/jali.html) (a pierced stone screen and the light it lets onto the floor),
56
+ [Tartan](https://stepinto.dev/art/tartan.html) (type a sett, get the cloth),
57
+ [Hitomezashi](https://stepinto.dev/art/hitomezashi.html) (two words stitched as rows and columns),
58
+ [Azulejos de letras](https://stepinto.dev/art/letras.html) (a street-sign typeface, with borders that turn the corner),
59
+ [Mantón de Manila](https://stepinto.dev/art/manton.html) (embroidered silk),
60
+ [Hispania](https://stepinto.dev/art/hispania.html) (Roman pavements) and
61
+ [Leonor](https://stepinto.dev/art/leonor.html) (heraldry from a blazon).
62
+
63
+ The designs are written up in the
64
+ [Patterns by Rule](https://stepinto.dev/patterns/) posts, starting
65
+ [here](https://stepinto.dev/posts/tiles-painted-by-rule/) and
28
66
  [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).
31
67
 
32
68
  ```
33
69
  npm install azulejeria
@@ -98,7 +134,8 @@ tile), `panX`, `panY`, `bands`, `grout` and `age`. After changing any of
98
134
  them call `wall.rebuild(true)` to repaint the tiles, or `wall.rebuild(false)`
99
135
  for things the wall draws itself (pan, grout, age). `wall.applyPreset(name)`,
100
136
  `wall.newDesign()` and `wall.zoomAt(x, y, factor)` do what they say. Set
101
- `wall.onChange(kind)` to be told about them.
137
+ `wall.onChange(kind)` to be told about them (`'preset'`, `'design'`,
138
+ `'zoom'`). **`REPEATS`** lists the five classic repeats by name.
102
139
 
103
140
  **A material** changes what the tile is made of without touching what is
104
141
  drawn on it. It is an object of optional hooks, and without one the tile
@@ -118,19 +155,22 @@ centre `cx`, `cy`, so wear can follow the line people walk. `finish(ctx,
118
155
  W, H, state, pal)` is drawn over the whole wall last. None of the hooks
119
156
  read the design's rng, so a material never moves a design.
120
157
 
121
- **`mountPanel(wall, { fileName, defaultPreset })`** wires the standard
158
+ **`mountPanel(wall, { fileName, defaultPreset, print, document })`** wires the standard
122
159
  panel for a wall. It is `mountChrome` (below) with the wall's controls,
123
160
  which are a handful of elements found by id: selects `repeat`,
124
161
  `motif` and `palette`; ranges `density`, `hand`, `brush` and `zoom` with
125
162
  `densityVal`, `handVal`, `brushVal` and `zoomVal` spans beside them;
126
- checkboxes `bands`, `grout` and `age`; buttons `newDesign` and `save`;
163
+ checkboxes `bands`, `grout` and `age`; buttons `newDesign`, `save` and
164
+ `order` (one tile at print size, see Print; `print` is passed to it);
127
165
  a `mood` line for the seed; `.card[data-preset]` cards each holding a
128
166
  canvas for a thumbnail; `.tab[data-tab]` buttons switching `presetsBody`
129
167
  and `panelBody`; `panel` with `panelHead` and `panelToggle`; and a `title`
130
168
  overlay that fades on first touch. Anything missing is skipped. It also
131
169
  reads the query string, so `?preset=talavera` or
132
170
  `?seed=4242&repeat=rotate&pal=talavera&motif=rosette&density=5&age=1` is a
133
- shareable wall. Copy the markup from either of the two pages above.
171
+ shareable wall. `document` is where to look for the elements, for a
172
+ panel that lives somewhere other than the page. Copy the markup from
173
+ any of the wall pages above.
134
174
 
135
175
  **`createViewer(canvas, { paint, scale, minZoom, maxZoom, margin })`**
136
176
  is what a wall is built on, and what any other world can be. `paint(g,
@@ -141,7 +181,12 @@ the window, pans on drag, zooms on pinch or wheel, and calls
141
181
  that much larger than the window and only blits while you drag, which is
142
182
  what a slow paint wants. `viewer.state` has `scale`, `panX` and `panY`;
143
183
  add your own fields to it. Call `viewer.repaint()` when the world
144
- changes and `viewer.moved()` when only the pan did.
184
+ changes and `viewer.moved()` when only the pan did. `viewer.zoomAt(x,
185
+ y, factor)` zooms about a point and `viewer.resize()` refits the
186
+ window. Set `onChange(kind)` to hear `'zoom'`, `onInteract()` for the
187
+ first touch and `onZoom()` for the end of a zoom. `viewer.margin` can
188
+ be changed while it runs: a page that animates sets it to 0 so each
189
+ frame paints the window alone.
145
190
 
146
191
  **`mountChrome(viewer, spec)`** wires the same chrome around any viewer:
147
192
  the panel, the tabs, the preset cards, the title that fades, the save
@@ -154,8 +199,13 @@ id by default), `q` its name in the query string (the key by default),
154
199
  when the query string sets it, and `change(value)` is what to do after.
155
200
  Then `newId` and `onNew` for the button that starts over, `mood(state)`
156
201
  for the line under it, `query(q)` for anything else in the query string,
157
- `fileName` and `suffix(state)` for the saved png, and `ready()` once
158
- everything is applied. Alicatado is the worked example.
202
+ `fileName` and `suffix(state)` for the saved png, `order(state)` (a
203
+ promise of a blob) for an `#order` button, `document` for where the
204
+ elements are, and `ready()` once everything is applied. It returns
205
+ `{ sync, dismissTitle, markPreset }`: call `sync()` after changing the
206
+ state yourself, and `markPreset('')` when something the chrome doesn't
207
+ know about (a text box, say) has left the preset behind. Alicatado is
208
+ the worked example; Tartan and Hitomezashi show a text input beside it.
159
209
 
160
210
  **`azulejeria.css`** styles that markup. Colour it with the custom
161
211
  properties at the top of the file: `--az-bg`, `--az-title`,
@@ -198,8 +248,17 @@ uses it for the frame of a street plaque. `mitreCorner(strip)` is the
198
248
  square alternative: the strip cut on the diagonal and laid both ways,
199
249
  as a run of border tiles is mitred at forty-five degrees.
200
250
 
251
+ **The small things** every page ends up wanting: `mulberry32(seed)`,
252
+ the seeded rng everything here draws from; `hash2(i, j)`, an integer
253
+ from a grid position, for seeding a tile or a stitch by where it is;
254
+ `wobble(rng)`, the brush's slow drift as a function of 0 to 1;
255
+ `hexA(hex, alpha)`, a hex colour as an rgba string; `colourOf(el, pal)`,
256
+ an element's role as a colour; and `ageTile(ctx, rng, s, pal)`, what
257
+ age does to one glazed tile, for a material that wants the default
258
+ under its own.
259
+
201
260
  **The lower level** is there if you want it: `makeDesign(seed, density,
202
- bands, bold, motif)`, `paintDesign(g, els, pal, hand, lw, seed, painters, material, brush)`,
261
+ bands, bold, motif, state)`, `paintDesign(g, els, pal, hand, lw, seed, painters, material, brush)`,
203
262
  `makeTile(opts, size, pixelRatio, seed)`, `tileOpts(cfg, state)` and
204
263
  `paintThumb(cfg, preset, g, size, pixelRatio)`.
205
264
 
@@ -379,6 +438,8 @@ stroke drawn on the dimmed side is reflected over. The wall repaints
379
438
  while the pen moves. Cmd or Ctrl Z undoes. **`settle(stroke)`**,
380
439
  **`simplify(pts, eps)`** and **`smooth(pts, closed, times)`** are what
381
440
  the pad does to a raw stroke, exported for a page with its own input.
441
+ `KINDS` and `MAX_POINTS` (96, the most points a stroke keeps) are the
442
+ encoding's limits.
382
443
 
383
444
  ## Print
384
445
 
@@ -391,6 +452,71 @@ right size. `mountPanel` wires it to a `#order` button when the page has
391
452
  one (`opts.print` is passed on); with `mountChrome`, pass
392
453
  `order: () => exportTile(wall)` in the spec.
393
454
 
455
+ ## Shadow
456
+
457
+ `azulejeria/shadow` is a sun that goes round and the shadows it casts.
458
+ Nothing is drawn in shadow: a caster's shadow is its own outline, moved
459
+ along the sun's slant by how far it stands off the surface, with what
460
+ must stay lit cut back out, softened and multiplied on in the colour of
461
+ the sky.
462
+
463
+ ```js
464
+ import { sunOf, castShadow, shadowLayer } from 'azulejeria/shadow';
465
+
466
+ const sun = sunOf(9.5); // 6 to 20; the wall faces south
467
+ castShadow(g, {
468
+ w, h, dpr, shade: sun.shade, alpha: 0.8, blur: 2,
469
+ cast: lg => { lg.setTransform(...); drawGrille(lg, sun.slant[0] * d, sun.slant[1] * d); },
470
+ cut: lg => drawGrille(lg, 0, 0),
471
+ });
472
+ ```
473
+
474
+ **`sunOf(hour, { reach })`** gives `slant` (how far along the wall a
475
+ point one unit proud throws its shadow, x right and y down, never
476
+ longer than `reach`), `dir` (the unit vector toward the sun), `light`
477
+ (how squarely it strikes the face), `warm` (1 at the horizon, 0 at the
478
+ top of the day), `sunCol` and `shade` as `[r, g, b]`, and `az` and `e`
479
+ for a page with its own projection. **`castShadow(g, o)`** clears a
480
+ kept layer the size of the window, lets `o.cast(lg)` draw the caster
481
+ where its shadow falls (fill and stroke are already `o.shade`), draws
482
+ `o.cut(lg)` with destination-out if there is one, and multiplies the
483
+ layer onto `g` at `o.alpha`, blurred by `o.blur` device pixels.
484
+ `o.layer` picks which kept layer, for a page that casts more than once.
485
+ **`shadowLayer(n, pw, ph)`** is one of those layers, for a page's own
486
+ compositing.
487
+
488
+ ## Loom
489
+
490
+ `azulejeria/loom` is cloth by rule. A draft is three lists: the shaft
491
+ each warp end is threaded through, the shafts each treadle lifts, and
492
+ the treadle pressed for each pick. Where an end's shaft is lifted the
493
+ warp is on top. A sett is a string of colours and thread counts, and
494
+ the cloth shows a thread's colour wherever that thread is on top.
495
+
496
+ ```js
497
+ import { DRAFTS, parseSett, threadsOf, dyeOf, clothCanvas, threadTile } from 'azulejeria/loom';
498
+
499
+ const threads = threadsOf(parseSett('K4 R24 K24 Y4')).map(c => dyeOf(c, 'modern'));
500
+ const cloth = clothCanvas(400, 300, 0, 0, threads, threads, DRAFTS.twill); // one pixel a crossing
501
+ ```
502
+
503
+ **`DRAFTS`** has `plain`, `twill` (2/2), `drill` (3/1), `herringbone`,
504
+ `diamond` and `basket`; a draft is `{ threading, tieup, treadling }`,
505
+ so write your own. **`lifted(draft, i, j)`** is the rule and
506
+ **`drawdown(draft)`** one repeat of it. **`parseSett(text)`** reads
507
+ colour codes (K R G B Y W N P O T A M C, with L or D in front for light
508
+ and dark, or `#rrggbb`) and counts, slashes at the pivots allowed; the
509
+ sett turns back at both ends unless it has `...` in it.
510
+ **`DRAFT_NAMES`** lists the drafts. **`threadsOf(sett)`** is one repeat, a code per thread, and
511
+ **`writeSett(sett)`** writes it back as a threadcount.
512
+ **`dyeOf(code, dye)`** is the colour in a dye lot (**`DYES`**: `modern`,
513
+ `ancient`, `weathered`, or your own map). **`weavePixels(data, w, h,
514
+ i0, j0, warp, weft, draft, under)`** fills RGBA pixels, one a crossing,
515
+ from end `i0` and pick `j0`, and needs no document;
516
+ **`clothCanvas(...)`** is the same as a canvas to draw scaled up, and
517
+ **`threadTile(draft, t)`** is the threads' own shading, one repeat at
518
+ `t` pixels a thread, to lay over it.
519
+
394
520
  ## Licence
395
521
 
396
522
  MIT.
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "azulejeria",
3
- "version": "2.6.0",
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", "drawing", "print"],
3
+ "version": "2.7.0",
4
+ "description": "Pattern by rule, painted to look like a material. A seeded canvas engine that began with Spanish azulejo walls: tiles with a drifting brush, the seventeen wallpaper groups, a tile cutter, interlace, a hand-drawn tile, cast shadows and a loom.",
5
+ "keywords": ["canvas", "generative", "wallpaper-groups", "symmetry", "tiles", "azulejo", "mudejar", "sevilla", "pattern", "procedural", "art", "wallpaper", "interlace", "knotwork", "celtic", "mosaic", "voronoi", "trencadis", "drawing", "print", "shadow", "weaving", "tartan", "loom"],
6
6
  "license": "MIT",
7
7
  "author": "Andy Cross",
8
8
  "homepage": "https://stepinto.dev/art/azulejeria.html",
@@ -16,11 +16,13 @@
16
16
  "./pieces": "./src/pieces.js",
17
17
  "./groups": "./src/groups.js",
18
18
  "./draw": "./src/draw.js",
19
+ "./shadow": "./src/shadow.js",
20
+ "./loom": "./src/loom.js",
19
21
  "./azulejeria.css": "./src/azulejeria.css"
20
22
  },
21
23
  "files": ["src", "test", "README.md", "LICENSE"],
22
24
  "sideEffects": false,
23
25
  "scripts": {
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"
26
+ "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 --check src/shadow.js && node --check src/loom.js && node test/groups.mjs && node test/draw.mjs && node test/loom.mjs"
25
27
  }
26
28
  }
package/src/loom.js ADDED
@@ -0,0 +1,175 @@
1
+ // loom: cloth by rule.
2
+ //
3
+ // A weaving draft is a small program. The threading says which shaft
4
+ // each warp end is drawn through, the tie-up says which shafts each
5
+ // treadle lifts, and the treadling says which treadle is pressed for
6
+ // each pick of the weft. Where an end's shaft is lifted the warp lies
7
+ // over the weft; everywhere else the weft lies over the warp. That is
8
+ // the whole of the structure, and `lifted` is the whole of the rule.
9
+ //
10
+ // The colour is a second program laid over the first. A sett is a
11
+ // string of colours and thread counts, "K4 R24 K24 Y4", and the cloth
12
+ // shows a thread's colour wherever that thread is on top.
13
+ //
14
+ // Nothing above the last section needs a document, so the rule can be
15
+ // tested without a browser.
16
+
17
+ const mod = (n, m) => ((n % m) + m) % m;
18
+
19
+ // ------------------------------------------------------------- drafts ---
20
+ // threading: a shaft for each end, repeating. tieup: for each treadle,
21
+ // the shafts it lifts. treadling: a treadle for each pick, repeating.
22
+ const TWILL_TIE = [[0, 1], [1, 2], [2, 3], [3, 0]];
23
+ export const DRAFTS = {
24
+ // over one, under one
25
+ plain: { threading: [0, 1], tieup: [[0], [1]], treadling: [0, 1] },
26
+ // 2/2 twill: over two, under two, stepping one along each pick. The cloth of tartan
27
+ twill: { threading: [0, 1, 2, 3], tieup: TWILL_TIE, treadling: [0, 1, 2, 3] },
28
+ // 3/1 twill: the warp shows on the face. Denim
29
+ drill: { threading: [0, 1, 2, 3], tieup: [[0, 1, 2], [1, 2, 3], [2, 3, 0], [3, 0, 1]], treadling: [0, 1, 2, 3] },
30
+ // the twill turned back on itself every eight ends, with a break at the turn
31
+ herringbone: { threading: [0, 1, 2, 3, 0, 1, 2, 3, 1, 0, 3, 2, 1, 0, 3, 2], tieup: TWILL_TIE, treadling: [0, 1, 2, 3] },
32
+ // the twill turned back in the weft as well: diamonds
33
+ diamond: { threading: [0, 1, 2, 3, 0, 1, 2, 3, 2, 1, 0, 3, 2, 1], tieup: TWILL_TIE, treadling: [0, 1, 2, 3, 0, 1, 2, 3, 2, 1, 0, 3, 2, 1] },
34
+ // plain weave with every thread doubled
35
+ basket: { threading: [0, 0, 1, 1], tieup: [[0], [1]], treadling: [0, 0, 1, 1] },
36
+ };
37
+ export const DRAFT_NAMES = Object.keys(DRAFTS);
38
+
39
+ // is warp end i over the weft at pick j?
40
+ export function lifted(draft, i, j) {
41
+ const shaft = draft.threading[mod(i, draft.threading.length)];
42
+ return draft.tieup[draft.treadling[mod(j, draft.treadling.length)]].includes(shaft);
43
+ }
44
+
45
+ // the drawdown of one repeat: w ends by h picks, 1 where the warp is up
46
+ export function drawdown(draft) {
47
+ const w = draft.threading.length, h = draft.treadling.length, m = new Uint8Array(w * h);
48
+ for (let j = 0; j < h; j++) for (let i = 0; i < w; i++) m[j * w + i] = lifted(draft, i, j) ? 1 : 0;
49
+ return { w, h, m };
50
+ }
51
+
52
+ // --------------------------------------------------------------- setts ---
53
+ // A sett is written as the weavers write it: a colour code and a
54
+ // count, over and over. "K4 R24 K24 Y4" is four black, twenty-four
55
+ // red, twenty-four black, four yellow. A colour is one or two letters
56
+ // (K black, R red, G green, B blue, Y yellow, W white, N grey, P
57
+ // purple, O orange, T brown, A azure, with L or D in front for light
58
+ // and dark) or a hex colour, #c8102e. A slash may sit between the
59
+ // colour and the count, as it does at the pivots of a registered
60
+ // threadcount ("B/24 K4 ... B/4"), and is ignored: a sett is taken to
61
+ // turn back at both ends, the first and last stripes being the pivots
62
+ // and counted once, unless it is written with "..." in it, which
63
+ // says it simply repeats.
64
+ export function parseSett(text) {
65
+ const t = String(text || '');
66
+ const stripes = [];
67
+ const re = /(#[0-9a-fA-F]{6}|[A-Za-z]{1,2})\s*\/?\s*(\d{1,3})/g;
68
+ let m;
69
+ while ((m = re.exec(t)) && stripes.length < 64) {
70
+ const n = Math.min(400, parseInt(m[2], 10));
71
+ if (n > 0) stripes.push({ code: m[1][0] === '#' ? m[1].toLowerCase() : m[1].toUpperCase(), n });
72
+ }
73
+ return { stripes, mirror: !t.includes('...') };
74
+ }
75
+
76
+ // one repeat of the sett, a colour code for each thread
77
+ export function threadsOf(sett) {
78
+ const s = sett.stripes;
79
+ if (!s.length) return ['N'];
80
+ const order = sett.mirror && s.length > 2 ? s.concat(s.slice(1, -1).reverse()) : s;
81
+ const out = [];
82
+ for (const { code, n } of order) for (let k = 0; k < n; k++) out.push(code);
83
+ return out;
84
+ }
85
+
86
+ // the sett written back out, as the register would have it
87
+ export function writeSett(sett) {
88
+ const s = sett.stripes;
89
+ if (!sett.mirror) return s.map(x => x.code + x.n).join(' ') + ' ...';
90
+ return s.map((x, i) => x.code + (i === 0 || i === s.length - 1 ? '/' : '') + x.n).join(' ');
91
+ }
92
+
93
+ // --------------------------------------------------------------- dyes ---
94
+ // The same sett in three dye lots. Modern is the aniline dye of the
95
+ // mills, ancient the paler shades the vegetable dyes are supposed to
96
+ // have given, weathered what a plaid looks like after a century in a
97
+ // peat bog.
98
+ export const DYES = {
99
+ modern: { K: '#101010', R: '#c80000', G: '#006818', B: '#2c2c80', Y: '#e8c000', W: '#e0e0e0', N: '#808080', P: '#780078', O: '#d87c00', T: '#604000', A: '#5c8cd0', M: '#901c38', C: '#b01030' },
100
+ ancient: { K: '#2a2a2a', R: '#d4542c', G: '#4f8a4a', B: '#5a86b8', Y: '#e6cc5c', W: '#f0ebdd', N: '#9a9a94', P: '#9a5a9a', O: '#e89a3c', T: '#8a6a3a', A: '#8cb4dc', M: '#b0506a', C: '#c8485a' },
101
+ weathered: { K: '#4c4a48', R: '#a2553f', G: '#6f7046', B: '#5a6c80', Y: '#c2a85e', W: '#d9d0bd', N: '#8f8a80', P: '#7d6478', O: '#b9814a', T: '#75603f', A: '#8a9cab', M: '#8f5a5c', C: '#9c5450' },
102
+ };
103
+ const rgbOf = hex => { const n = parseInt(hex.slice(1), 16); return [(n >> 16) & 255, (n >> 8) & 255, n & 255]; };
104
+ // a code as [r, g, b] in a dye lot: a letter, a letter with L or D
105
+ // before it, or a hex colour as it stands
106
+ export function dyeOf(code, dye) {
107
+ const lot = typeof dye === 'string' ? DYES[dye] || DYES.modern : dye;
108
+ if (code[0] === '#') return rgbOf(code);
109
+ if (lot[code]) return rgbOf(lot[code]);
110
+ if (code.length === 2 && (code[0] === 'L' || code[0] === 'D') && lot[code[1]]) {
111
+ const c = rgbOf(lot[code[1]]), to = code[0] === 'L' ? 255 : 0, t = code[0] === 'L' ? 0.4 : 0.35;
112
+ return c.map(v => Math.round(v + (to - v) * t));
113
+ }
114
+ return rgbOf(lot.N);
115
+ }
116
+
117
+ // -------------------------------------------------------------- cloth ---
118
+ // Fills `data` (RGBA, w by h, one pixel a crossing) with the cloth from
119
+ // end i0 and pick j0: at each crossing the colour of whichever thread
120
+ // is on top. `warp` and `weft` are one repeat of colours, [r, g, b]
121
+ // each. The thread underneath shows a little at the edges of the one
122
+ // above, so `under` (0 to 1) lets that much of it through.
123
+ export function weavePixels(data, w, h, i0, j0, warp, weft, draft, under) {
124
+ const dd = drawdown(draft), u = under || 0, nw = warp.length, nf = weft.length;
125
+ for (let y = 0; y < h; y++) {
126
+ const j = j0 + y, f = weft[mod(j, nf)], row = mod(j, dd.h) * dd.w;
127
+ for (let x = 0; x < w; x++) {
128
+ const i = i0 + x, p = warp[mod(i, nw)], up = dd.m[row + mod(i, dd.w)];
129
+ const a = up ? p : f, b = up ? f : p, o = (y * w + x) * 4;
130
+ data[o] = a[0] + (b[0] - a[0]) * u; data[o + 1] = a[1] + (b[1] - a[1]) * u; data[o + 2] = a[2] + (b[2] - a[2]) * u; data[o + 3] = 255;
131
+ }
132
+ }
133
+ return data;
134
+ }
135
+
136
+ // The same as a canvas, one pixel a crossing, to be drawn scaled up
137
+ // with smoothing off. Pass `into` to reuse a canvas.
138
+ export function clothCanvas(w, h, i0, j0, warp, weft, draft, under, into) {
139
+ const c = into || document.createElement('canvas');
140
+ if (c.width !== w || c.height !== h) { c.width = w; c.height = h; }
141
+ const g = c.getContext('2d'), img = g.createImageData(w, h);
142
+ weavePixels(img.data, w, h, i0, j0, warp, weft, draft, under);
143
+ g.putImageData(img, 0, 0);
144
+ return c;
145
+ }
146
+
147
+ // The threads themselves: one repeat of the draft with each crossing
148
+ // `t` pixels square, in black and white over nothing, to be laid over
149
+ // the colour. The thread on top is round (dark at its edges, light
150
+ // down its middle) and goes under where the other system comes up.
151
+ const tiles = new Map();
152
+ export function threadTile(draft, t) {
153
+ const key = JSON.stringify(draft) + '|' + t;
154
+ let c = tiles.get(key);
155
+ if (c) return c;
156
+ if (tiles.size > 24) tiles.clear();
157
+ const dd = drawdown(draft);
158
+ c = document.createElement('canvas'); c.width = dd.w * t; c.height = dd.h * t;
159
+ const g = c.getContext('2d');
160
+ const up = (i, j) => dd.m[mod(j, dd.h) * dd.w + mod(i, dd.w)];
161
+ for (let j = 0; j < dd.h; j++) for (let i = 0; i < dd.w; i++) {
162
+ const x = i * t, y = j * t, warp = up(i, j);
163
+ const gr = warp ? g.createLinearGradient(x, 0, x + t, 0) : g.createLinearGradient(0, y, 0, y + t);
164
+ gr.addColorStop(0, 'rgba(0,0,0,0.34)'); gr.addColorStop(0.22, 'rgba(0,0,0,0.04)');
165
+ gr.addColorStop(0.45, 'rgba(255,255,255,0.16)'); gr.addColorStop(0.78, 'rgba(0,0,0,0.05)'); gr.addColorStop(1, 'rgba(0,0,0,0.38)');
166
+ g.fillStyle = gr; g.fillRect(x, y, t, t);
167
+ // where it dives under its neighbour along its own length
168
+ const e = Math.max(1, t * 0.16);
169
+ g.fillStyle = 'rgba(0,0,0,0.26)';
170
+ if (warp) { if (!up(i, j - 1)) g.fillRect(x, y, t, e); if (!up(i, j + 1)) g.fillRect(x, y + t - e, t, e); }
171
+ else { if (up(i - 1, j)) g.fillRect(x, y, e, t); if (up(i + 1, j)) g.fillRect(x + t - e, y, e, t); }
172
+ }
173
+ tiles.set(key, c);
174
+ return c;
175
+ }
package/src/shadow.js ADDED
@@ -0,0 +1,83 @@
1
+ // shadow: a sun that goes round, and the shadows it casts.
2
+ //
3
+ // Nothing here is drawn in shadow; the shadows are cast. A caster is
4
+ // whatever stands off the surface behind it: a course of brick proud of
5
+ // a wall, an iron grille a hand's width in front of whitewash, a stone
6
+ // screen with a floor below it. Its shadow is its own outline, moved
7
+ // along the sun's slant by how far it stands off, with anything that
8
+ // must stay lit cut back out, softened at the edge and multiplied onto
9
+ // the surface in the colour of the sky.
10
+ //
11
+ // Sebka needed it first, Rejería second and Jali third, which is when
12
+ // it moved here.
13
+
14
+ // The wall faces south. At six the sun is on the horizon to the left;
15
+ // at one it is high and in front; at eight it sets on the right. A
16
+ // point standing h proud of the wall throws its shadow h times `slant`
17
+ // along the wall (x to the right, y down); `light` is how squarely the
18
+ // sun hits the face. `reach` is the longest slant allowed, so dawn and
19
+ // dusk don't throw shadows off the page. `az` and `e` are the sun's
20
+ // angle along the wall and its height, for a page that needs its own
21
+ // projection; `warm` is 1 at the horizon and 0 at the top of the day.
22
+ const EMAX = 64 * Math.PI / 180;
23
+ export function sunOf(hour, opts) {
24
+ const reach = (opts && opts.reach) || 9;
25
+ const t = Math.min(0.995, Math.max(0.005, (hour - 6) / 14));
26
+ const az = Math.PI * t;
27
+ const e = EMAX * Math.sin(az);
28
+ let sx = Math.cos(az) / Math.sin(az), sy = Math.tan(e) / Math.sin(az);
29
+ const len = Math.hypot(sx, sy);
30
+ if (len > reach) { sx *= reach / len; sy *= reach / len; }
31
+ const light = Math.cos(e) * Math.sin(az);
32
+ // the light itself: white at height, orange at the horizon. What the
33
+ // sun doesn't reach is lit by the sky, so the shade is blue, and
34
+ // bluer against a warm sun
35
+ const warm = 1 - e / EMAX;
36
+ const w2 = warm * warm;
37
+ const sunCol = [255, Math.round(248 - 70 * w2), Math.round(232 - 125 * w2)];
38
+ const shade = [Math.round(112 - 22 * warm), Math.round(118 - 18 * warm), Math.round(162 + 8 * warm)];
39
+ const dl = Math.hypot(sx, sy) || 1;
40
+ return { slant: [sx, sy], light, warm, e, az, sunCol, shade, dir: [-sx / dl, -sy / dl] };
41
+ }
42
+
43
+ // offscreen layers, kept by number and resized as the window is
44
+ const layers = [];
45
+ export function shadowLayer(n, pw, ph) {
46
+ let c = layers[n];
47
+ if (!c) c = layers[n] = document.createElement('canvas');
48
+ if (c.width !== pw || c.height !== ph) { c.width = pw; c.height = ph; }
49
+ return c;
50
+ }
51
+
52
+ // castShadow(g, { w, h, dpr, shade, alpha, blur, layer, cast, cut })
53
+ // lays one shadow over what is already on g. `cast(lg)` draws the
54
+ // caster where its shadow falls, on a clear layer the size of the
55
+ // window whose fill and stroke are already the shade colour; it sets
56
+ // its own transform, and may composite as it likes. `cut(lg)`, if
57
+ // given, is then drawn with destination-out: whatever it paints is
58
+ // taken out of the shadow (the caster itself, or a level the shadow
59
+ // can't reach). The layer is multiplied onto g at `alpha`, softened by
60
+ // `blur` device pixels (none while something is moving: the blur is
61
+ // most of a frame). `shade` is an [r, g, b] or a css colour; `layer`
62
+ // picks which kept layer to use, for a page that casts more than once
63
+ // and wants each kept.
64
+ export function castShadow(g, o) {
65
+ const pw = Math.ceil(o.w * o.dpr), ph = Math.ceil(o.h * o.dpr);
66
+ const lc = shadowLayer(o.layer || 0, pw, ph);
67
+ const lg = lc.getContext('2d');
68
+ lg.setTransform(1, 0, 0, 1, 0, 0);
69
+ lg.globalCompositeOperation = 'source-over';
70
+ lg.globalAlpha = 1;
71
+ lg.clearRect(0, 0, pw, ph);
72
+ lg.fillStyle = lg.strokeStyle = Array.isArray(o.shade) ? `rgb(${o.shade})` : o.shade;
73
+ o.cast(lg);
74
+ if (o.cut) { lg.globalCompositeOperation = 'destination-out'; o.cut(lg); }
75
+ g.save();
76
+ g.setTransform(1, 0, 0, 1, 0, 0);
77
+ g.globalCompositeOperation = 'multiply';
78
+ g.globalAlpha = o.alpha == null ? 1 : o.alpha;
79
+ if (o.blur) g.filter = `blur(${o.blur.toFixed(2)}px)`;
80
+ g.drawImage(lc, 0, 0);
81
+ g.restore();
82
+ return lc;
83
+ }
package/test/loom.mjs ADDED
@@ -0,0 +1,52 @@
1
+ // The loom's rule: the drafts, the sett and the cloth they make.
2
+ import assert from 'node:assert/strict';
3
+ import { DRAFTS, DRAFT_NAMES, lifted, drawdown, parseSett, threadsOf, writeSett, dyeOf, weavePixels } from '../src/loom.js';
4
+
5
+ // plain weave is a chequer; 2/2 twill is over two, under two, stepping one a pick
6
+ for (let j = -3; j < 5; j++) for (let i = -3; i < 5; i++) {
7
+ assert.equal(lifted(DRAFTS.plain, i, j), (((i - j) % 2) + 2) % 2 === 0);
8
+ assert.equal(lifted(DRAFTS.twill, i, j), (((i - j) % 4) + 4) % 4 < 2);
9
+ }
10
+ // every draft is balanced enough to be a cloth: no end and no pick floats the whole repeat
11
+ for (const name of DRAFT_NAMES) {
12
+ const d = drawdown(DRAFTS[name]);
13
+ for (let j = 0; j < d.h; j++) { const s = d.m.slice(j * d.w, (j + 1) * d.w).reduce((a, b) => a + b, 0); assert.ok(s > 0 && s < d.w, name + ' pick ' + j); }
14
+ for (let i = 0; i < d.w; i++) { let s = 0; for (let j = 0; j < d.h; j++) s += d.m[j * d.w + i]; assert.ok(s > 0 && s < d.h, name + ' end ' + i); }
15
+ }
16
+ // in a 2/2 twill half of every repeat is warp; in drill three quarters
17
+ assert.equal(drawdown(DRAFTS.twill).m.reduce((a, b) => a + b, 0), 8);
18
+ assert.equal(drawdown(DRAFTS.drill).m.reduce((a, b) => a + b, 0), 12);
19
+
20
+ // a sett turns back at its pivots, which are counted once
21
+ const s = parseSett('K4 R24 K24 Y4');
22
+ assert.deepEqual(s.stripes, [{ code: 'K', n: 4 }, { code: 'R', n: 24 }, { code: 'K', n: 24 }, { code: 'Y', n: 4 }]);
23
+ assert.equal(s.mirror, true);
24
+ assert.equal(threadsOf(s).length, 4 + 24 + 24 + 4 + 24 + 24);
25
+ assert.equal(threadsOf(s).join('').replace(/(.)\1*/g, '$1'), 'KRKYKR');
26
+ assert.equal(writeSett(s), 'K/4 R24 K24 Y/4');
27
+ // the register's slashes are read; Royal Stewart is 190 threads
28
+ assert.equal(threadsOf(parseSett('R/72 B8 K12 Y2 K2 W2 K2 G16 R8 K2 R4 W/2')).length, 190);
29
+ // "..." says it repeats without turning
30
+ const h = parseSett('k4 w4 ...');
31
+ assert.equal(h.mirror, false);
32
+ assert.equal(threadsOf(h).join(''), 'KKKKWWWW');
33
+ // two stripes have nothing between the pivots to turn back through
34
+ assert.equal(threadsOf(parseSett('R/8 K/8')).length, 16);
35
+ // hex colours, light and dark, nonsense
36
+ assert.deepEqual(parseSett('#C8102E 6 LB 2').stripes, [{ code: '#c8102e', n: 6 }, { code: 'LB', n: 2 }]);
37
+ assert.deepEqual(dyeOf('#c8102e', 'modern'), [200, 16, 46]);
38
+ assert.deepEqual(dyeOf('K', 'modern'), [16, 16, 16]);
39
+ assert.ok(dyeOf('LB', 'modern')[2] > dyeOf('B', 'modern')[2] && dyeOf('DB', 'modern')[2] < dyeOf('B', 'modern')[2]);
40
+ assert.deepEqual(dyeOf('ZZ', 'modern'), dyeOf('N', 'modern'));
41
+ assert.deepEqual(threadsOf(parseSett('')), ['N']);
42
+ assert.deepEqual(parseSett('hello world').stripes, []);
43
+
44
+ // the cloth: red warp, white weft, plain weave is a chequer of the two
45
+ const px = weavePixels(new Uint8ClampedArray(4 * 4 * 4), 4, 4, 0, 0, [[200, 0, 0]], [[255, 255, 255]], DRAFTS.plain, 0);
46
+ assert.deepEqual([...px.slice(0, 8)], [200, 0, 0, 255, 255, 255, 255, 255]);
47
+ assert.deepEqual([...px.slice(16, 24)], [255, 255, 255, 255, 200, 0, 0, 255]);
48
+ // and it is the same cloth wherever the window starts
49
+ const a = weavePixels(new Uint8ClampedArray(8 * 8 * 4), 8, 8, -5, 3, [[1, 2, 3], [9, 9, 9], [50, 60, 70]], [[7, 7, 7], [100, 0, 0]], DRAFTS.herringbone, 0.2);
50
+ const b = weavePixels(new Uint8ClampedArray(9 * 9 * 4), 9, 9, -6, 2, [[1, 2, 3], [9, 9, 9], [50, 60, 70]], [[7, 7, 7], [100, 0, 0]], DRAFTS.herringbone, 0.2);
51
+ for (let y = 0; y < 8; y++) for (let x = 0; x < 8; x++) for (let k = 0; k < 4; k++) assert.equal(a[(y * 8 + x) * 4 + k], b[((y + 1) * 9 + x + 1) * 4 + k]);
52
+ console.log('loom ok');