azulejeria 2.6.0 → 2.8.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,62 @@ 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/knit` | Charted knitting: bands, Fair Isle's two rules, and every stitch as its V | Knit |
30
+ | `azulejeria/azulejeria.css` | The styles for the panel, the cards, the title and the pad | The parts |
31
+
32
+ Each module stands alone except `draw`, which paints with the wall's
33
+ brush. `knots`, `groups`, `pieces`, `shadow`, `loom` and `knit` draw on any
34
+ 2D context.
35
+
36
+ ## Built on it
37
+
38
+ Tile walls (`createWall`):
39
+ [Azulejería](https://stepinto.dev/art/azulejeria.html) (Talavera rosettes and Mudéjar strapwork),
40
+ [Jerez](https://stepinto.dev/art/jerez.html) (vines, horses and sherry),
41
+ [Hidráulico](https://stepinto.dev/art/hidraulico.html) (pigmented cement, pressed and not painted),
42
+ [Delft](https://stepinto.dev/art/delft.html) (a figure in the middle of every tile),
43
+ [Fajalauza](https://stepinto.dev/art/fajalauza.html) (Granada's green and blue on cream),
44
+ [Rosa y Granada](https://stepinto.dev/art/rosaygranada.html) and
45
+ [Encaustic](https://stepinto.dev/art/encaustic.html) (clay inlaid in clay, medieval and Victorian),
46
+ [Papel Pintado](https://stepinto.dev/art/papelpintado.html) (block-printed paper laid by any of the seventeen groups) and
47
+ [Octavo](https://stepinto.dev/art/octavo.html) (you draw one eighth of the tile and the wall paints the rest).
48
+
49
+ Other worlds on the viewer (`createViewer`):
50
+ [Alicatado](https://stepinto.dev/art/alicatado.html) (cut tile set in lime, with the cutter),
51
+ [Trencadís](https://stepinto.dev/art/trencadis.html) (Azulejería's tiles broken and relaid),
52
+ [Sutton Hoo](https://stepinto.dev/art/suttonhoo.html) (garnet cells through the cutter, a buckle in knots),
53
+ [Knotwork](https://stepinto.dev/art/knotwork.html) (insular interlace on vellum),
54
+ [Sebka](https://stepinto.dev/art/sebka.html) (a brick lattice under a sun you can move),
55
+ [Rejería](https://stepinto.dev/art/rejeria.html) (wrought iron and its shadow on whitewash),
56
+ [Jali](https://stepinto.dev/art/jali.html) (a pierced stone screen and the light it lets onto the floor),
57
+ [Tartan](https://stepinto.dev/art/tartan.html) (type a sett, get the cloth),
58
+ [Fair Isle](https://stepinto.dev/art/fairisle.html) (stranded knitting, written as its bands from the top down),
59
+ [Hitomezashi](https://stepinto.dev/art/hitomezashi.html) (two words stitched as rows and columns),
60
+ [Azulejos de letras](https://stepinto.dev/art/letras.html) (a street-sign typeface, with borders that turn the corner),
61
+ [Mantón de Manila](https://stepinto.dev/art/manton.html) (embroidered silk),
62
+ [Hispania](https://stepinto.dev/art/hispania.html) (Roman pavements) and
63
+ [Leonor](https://stepinto.dev/art/leonor.html) (heraldry from a blazon).
64
+
65
+ The designs are written up in the
66
+ [Patterns by Rule](https://stepinto.dev/patterns/) posts, starting
67
+ [here](https://stepinto.dev/posts/tiles-painted-by-rule/) and
28
68
  [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
69
 
32
70
  ```
33
71
  npm install azulejeria
@@ -98,7 +136,8 @@ tile), `panX`, `panY`, `bands`, `grout` and `age`. After changing any of
98
136
  them call `wall.rebuild(true)` to repaint the tiles, or `wall.rebuild(false)`
99
137
  for things the wall draws itself (pan, grout, age). `wall.applyPreset(name)`,
100
138
  `wall.newDesign()` and `wall.zoomAt(x, y, factor)` do what they say. Set
101
- `wall.onChange(kind)` to be told about them.
139
+ `wall.onChange(kind)` to be told about them (`'preset'`, `'design'`,
140
+ `'zoom'`). **`REPEATS`** lists the five classic repeats by name.
102
141
 
103
142
  **A material** changes what the tile is made of without touching what is
104
143
  drawn on it. It is an object of optional hooks, and without one the tile
@@ -118,19 +157,22 @@ centre `cx`, `cy`, so wear can follow the line people walk. `finish(ctx,
118
157
  W, H, state, pal)` is drawn over the whole wall last. None of the hooks
119
158
  read the design's rng, so a material never moves a design.
120
159
 
121
- **`mountPanel(wall, { fileName, defaultPreset })`** wires the standard
160
+ **`mountPanel(wall, { fileName, defaultPreset, print, document })`** wires the standard
122
161
  panel for a wall. It is `mountChrome` (below) with the wall's controls,
123
162
  which are a handful of elements found by id: selects `repeat`,
124
163
  `motif` and `palette`; ranges `density`, `hand`, `brush` and `zoom` with
125
164
  `densityVal`, `handVal`, `brushVal` and `zoomVal` spans beside them;
126
- checkboxes `bands`, `grout` and `age`; buttons `newDesign` and `save`;
165
+ checkboxes `bands`, `grout` and `age`; buttons `newDesign`, `save` and
166
+ `order` (one tile at print size, see Print; `print` is passed to it);
127
167
  a `mood` line for the seed; `.card[data-preset]` cards each holding a
128
168
  canvas for a thumbnail; `.tab[data-tab]` buttons switching `presetsBody`
129
169
  and `panelBody`; `panel` with `panelHead` and `panelToggle`; and a `title`
130
170
  overlay that fades on first touch. Anything missing is skipped. It also
131
171
  reads the query string, so `?preset=talavera` or
132
172
  `?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.
173
+ shareable wall. `document` is where to look for the elements, for a
174
+ panel that lives somewhere other than the page. Copy the markup from
175
+ any of the wall pages above.
134
176
 
135
177
  **`createViewer(canvas, { paint, scale, minZoom, maxZoom, margin })`**
136
178
  is what a wall is built on, and what any other world can be. `paint(g,
@@ -141,7 +183,12 @@ the window, pans on drag, zooms on pinch or wheel, and calls
141
183
  that much larger than the window and only blits while you drag, which is
142
184
  what a slow paint wants. `viewer.state` has `scale`, `panX` and `panY`;
143
185
  add your own fields to it. Call `viewer.repaint()` when the world
144
- changes and `viewer.moved()` when only the pan did.
186
+ changes and `viewer.moved()` when only the pan did. `viewer.zoomAt(x,
187
+ y, factor)` zooms about a point and `viewer.resize()` refits the
188
+ window. Set `onChange(kind)` to hear `'zoom'`, `onInteract()` for the
189
+ first touch and `onZoom()` for the end of a zoom. `viewer.margin` can
190
+ be changed while it runs: a page that animates sets it to 0 so each
191
+ frame paints the window alone.
145
192
 
146
193
  **`mountChrome(viewer, spec)`** wires the same chrome around any viewer:
147
194
  the panel, the tabs, the preset cards, the title that fades, the save
@@ -154,8 +201,13 @@ id by default), `q` its name in the query string (the key by default),
154
201
  when the query string sets it, and `change(value)` is what to do after.
155
202
  Then `newId` and `onNew` for the button that starts over, `mood(state)`
156
203
  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.
204
+ `fileName` and `suffix(state)` for the saved png, `order(state)` (a
205
+ promise of a blob) for an `#order` button, `document` for where the
206
+ elements are, and `ready()` once everything is applied. It returns
207
+ `{ sync, dismissTitle, markPreset }`: call `sync()` after changing the
208
+ state yourself, and `markPreset('')` when something the chrome doesn't
209
+ know about (a text box, say) has left the preset behind. Alicatado is
210
+ the worked example; Tartan and Hitomezashi show a text input beside it.
159
211
 
160
212
  **`azulejeria.css`** styles that markup. Colour it with the custom
161
213
  properties at the top of the file: `--az-bg`, `--az-title`,
@@ -198,8 +250,17 @@ uses it for the frame of a street plaque. `mitreCorner(strip)` is the
198
250
  square alternative: the strip cut on the diagonal and laid both ways,
199
251
  as a run of border tiles is mitred at forty-five degrees.
200
252
 
253
+ **The small things** every page ends up wanting: `mulberry32(seed)`,
254
+ the seeded rng everything here draws from; `hash2(i, j)`, an integer
255
+ from a grid position, for seeding a tile or a stitch by where it is;
256
+ `wobble(rng)`, the brush's slow drift as a function of 0 to 1;
257
+ `hexA(hex, alpha)`, a hex colour as an rgba string; `colourOf(el, pal)`,
258
+ an element's role as a colour; and `ageTile(ctx, rng, s, pal)`, what
259
+ age does to one glazed tile, for a material that wants the default
260
+ under its own.
261
+
201
262
  **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)`,
263
+ bands, bold, motif, state)`, `paintDesign(g, els, pal, hand, lw, seed, painters, material, brush)`,
203
264
  `makeTile(opts, size, pixelRatio, seed)`, `tileOpts(cfg, state)` and
204
265
  `paintThumb(cfg, preset, g, size, pixelRatio)`.
205
266
 
@@ -379,6 +440,8 @@ stroke drawn on the dimmed side is reflected over. The wall repaints
379
440
  while the pen moves. Cmd or Ctrl Z undoes. **`settle(stroke)`**,
380
441
  **`simplify(pts, eps)`** and **`smooth(pts, closed, times)`** are what
381
442
  the pad does to a raw stroke, exported for a page with its own input.
443
+ `KINDS` and `MAX_POINTS` (96, the most points a stroke keeps) are the
444
+ encoding's limits.
382
445
 
383
446
  ## Print
384
447
 
@@ -391,6 +454,124 @@ right size. `mountPanel` wires it to a `#order` button when the page has
391
454
  one (`opts.print` is passed on); with `mountChrome`, pass
392
455
  `order: () => exportTile(wall)` in the spec.
393
456
 
457
+ ## Shadow
458
+
459
+ `azulejeria/shadow` is a sun that goes round and the shadows it casts.
460
+ Nothing is drawn in shadow: a caster's shadow is its own outline, moved
461
+ along the sun's slant by how far it stands off the surface, with what
462
+ must stay lit cut back out, softened and multiplied on in the colour of
463
+ the sky.
464
+
465
+ ```js
466
+ import { sunOf, castShadow, shadowLayer } from 'azulejeria/shadow';
467
+
468
+ const sun = sunOf(9.5); // 6 to 20; the wall faces south
469
+ castShadow(g, {
470
+ w, h, dpr, shade: sun.shade, alpha: 0.8, blur: 2,
471
+ cast: lg => { lg.setTransform(...); drawGrille(lg, sun.slant[0] * d, sun.slant[1] * d); },
472
+ cut: lg => drawGrille(lg, 0, 0),
473
+ });
474
+ ```
475
+
476
+ **`sunOf(hour, { reach })`** gives `slant` (how far along the wall a
477
+ point one unit proud throws its shadow, x right and y down, never
478
+ longer than `reach`), `dir` (the unit vector toward the sun), `light`
479
+ (how squarely it strikes the face), `warm` (1 at the horizon, 0 at the
480
+ top of the day), `sunCol` and `shade` as `[r, g, b]`, and `az` and `e`
481
+ for a page with its own projection. **`castShadow(g, o)`** clears a
482
+ kept layer the size of the window, lets `o.cast(lg)` draw the caster
483
+ where its shadow falls (fill and stroke are already `o.shade`), draws
484
+ `o.cut(lg)` with destination-out if there is one, and multiplies the
485
+ layer onto `g` at `o.alpha`, blurred by `o.blur` device pixels.
486
+ `o.layer` picks which kept layer, for a page that casts more than once.
487
+ **`shadowLayer(n, pw, ph)`** is one of those layers, for a page's own
488
+ compositing.
489
+
490
+ ## Loom
491
+
492
+ `azulejeria/loom` is cloth by rule. A draft is three lists: the shaft
493
+ each warp end is threaded through, the shafts each treadle lifts, and
494
+ the treadle pressed for each pick. Where an end's shaft is lifted the
495
+ warp is on top. A sett is a string of colours and thread counts, and
496
+ the cloth shows a thread's colour wherever that thread is on top.
497
+
498
+ ```js
499
+ import { DRAFTS, parseSett, threadsOf, dyeOf, clothCanvas, threadTile } from 'azulejeria/loom';
500
+
501
+ const threads = threadsOf(parseSett('K4 R24 K24 Y4')).map(c => dyeOf(c, 'modern'));
502
+ const cloth = clothCanvas(400, 300, 0, 0, threads, threads, DRAFTS.twill); // one pixel a crossing
503
+ ```
504
+
505
+ **`DRAFTS`** has `plain`, `twill` (2/2), `drill` (3/1), `herringbone`,
506
+ `diamond` and `basket`; a draft is `{ threading, tieup, treadling }`,
507
+ so write your own. **`lifted(draft, i, j)`** is the rule and
508
+ **`drawdown(draft)`** one repeat of it. **`parseSett(text)`** reads
509
+ colour codes (K R G B Y W N P O T A M C, with L or D in front for light
510
+ and dark, or `#rrggbb`) and counts, slashes at the pivots allowed; the
511
+ sett turns back at both ends unless it has `...` in it.
512
+ **`DRAFT_NAMES`** lists the drafts. **`threadsOf(sett)`** is one repeat, a code per thread, and
513
+ **`writeSett(sett)`** writes it back as a threadcount.
514
+ **`dyeOf(code, dye)`** is the colour in a dye lot (**`DYES`**: `modern`,
515
+ `ancient`, `weathered`, or your own map). **`weavePixels(data, w, h,
516
+ i0, j0, warp, weft, draft, under)`** fills RGBA pixels, one a crossing,
517
+ from end `i0` and pick `j0`, and needs no document;
518
+ **`clothCanvas(...)`** is the same as a canvas to draw scaled up, and
519
+ **`threadTile(draft, t)`** is the threads' own shading, one repeat at
520
+ `t` pixels a thread, to lay over it.
521
+
522
+ ## Knit
523
+
524
+ `azulejeria/knit` is colourwork by rule. A chart is a list of strings,
525
+ a character a stitch: `.` is the ground, `X` the pattern, and any other
526
+ character a further colour. A band is a chart with its colours, and a
527
+ stack is bands from the top down. Fair Isle adds two rules, and the
528
+ module can check both: a row has two colours and no more, and the
529
+ colour not in use may not float more than about seven stitches.
530
+
531
+ ```js
532
+ import { fairIsle, paintKnit, ROW } from 'azulejeria/knit';
533
+
534
+ const cloth = fairIsle('oxo13 zig star11 seed', 'madder', 1); // bands from the top down
535
+ g.setTransform(12, 0, 0, 12, 0, 0); // a stitch is one unit wide, ROW high
536
+ paintKnit(g, cloth, 0, 0, 80, 60, 12); // 80 stitches by 60 rows, 12 px a stitch
537
+ ```
538
+
539
+ **`chartOf(rows, gap)`** makes a chart, and **`byRule(n, fn)`** one
540
+ with the square's symmetries from `fn(a, b)`, the distance from the
541
+ middle each way. **`PEERIES`** are the small bands (`seed`, `dots`,
542
+ `check`, `zig`, `wave`, `cross`, `links`, `lozenge`, `hearts`, `bars`)
543
+ and **`BORDERS`** the large ones, each a function of the half-width
544
+ (`oxo`, `star`, `diamond`, `flake`, `tile`), filled in their corners
545
+ until **`floatsOf(chart)`** reports no float over seven.
546
+ **`ruleMotif(seed, n, limit)`** is a large band nobody charted.
547
+ **`FIGURES`** are the season's (`reindeer`, `tree`, `pudding`,
548
+ `snowman`, `gift`, `cane`, `bauble`, `heart`), in more colours than a
549
+ row should have: `X` is the band's own colour and `k w r g y b` are
550
+ inks the page names. **`textChart(text)`** knits a word in a
551
+ five-by-seven alphabet, and **`knittable(text)`** is what of it can be
552
+ knitted.
553
+
554
+ **`band(chart, colours, opts)`** gives a chart its colours, one for
555
+ each character, each a colour or a list with one for each row
556
+ (**`shadeRows(h, shades)`** makes the list that shades to the middle
557
+ row and back). `opts` are `repeat` (false knits it once), `scale`,
558
+ `phase` and `gap`. **`plain(rows, colour)`** is rows of nothing.
559
+ **`stackOf(bands, base, repeat)`** stacks them, and
560
+ **`stitchAt(stack, i, j)`** is the colour of one stitch.
561
+ **`fairIsle(text, wool, seed, opts)`** is the stack for a cloth
562
+ written as its bands, in one of the **`WOOLS`** (`shetland`, `madder`,
563
+ `sea`, `heather`, `yule`, `stepinto`) or your own; **`parseBands`**,
564
+ **`writeBands`** and **`randomBands(seed)`** read, write and invent the
565
+ text.
566
+
567
+ **`knitPixels(data, w, h, i0, j0, stack)`** fills RGBA pixels, one a
568
+ stitch, and needs no document. **`paintKnit(g, stack, i0, j0, nw, nh,
569
+ px)`** knits into the context's own transform, each stitch drawn as a
570
+ V so that a change of colour has a zigzag edge, with
571
+ **`stitchTile(px)`** laid over for the roundness of the yarn.
572
+ **`paintRib(g, colour, x, y, w, h, px)`** is ribbing for a welt or a
573
+ cuff, and **`fuzzTile(seed, size)`** the halo of the wool.
574
+
394
575
  ## Licence
395
576
 
396
577
  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.8.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, a loom and knitting.",
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", "knitting", "fair-isle"],
6
6
  "license": "MIT",
7
7
  "author": "Andy Cross",
8
8
  "homepage": "https://stepinto.dev/art/azulejeria.html",
@@ -16,11 +16,14 @@
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",
21
+ "./knit": "./src/knit.js",
19
22
  "./azulejeria.css": "./src/azulejeria.css"
20
23
  },
21
24
  "files": ["src", "test", "README.md", "LICENSE"],
22
25
  "sideEffects": false,
23
26
  "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"
27
+ "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 --check src/knit.js && node test/groups.mjs && node test/draw.mjs && node test/loom.mjs && node test/knit.mjs"
25
28
  }
26
29
  }
package/src/draw.js CHANGED
@@ -328,7 +328,9 @@ export function mountPad(wall, opts) {
328
328
  const pal = wall.palettes[state.pal];
329
329
  if (pal !== palSeen) { palSeen = pal; swatches(pal); }
330
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); }
331
+ const px = Math.round(W * DPR);
332
+ // both, because a canvas starts at 300 by 150: a 150px pad at 2x already has the right width
333
+ if (canvas.width !== px || canvas.height !== px) { canvas.width = canvas.height = px; }
332
334
  const g = canvas.getContext('2d');
333
335
  const S = W - 2 * M;
334
336
  g.setTransform(DPR, 0, 0, DPR, 0, 0);
package/src/knit.js ADDED
@@ -0,0 +1,502 @@
1
+ // knit: knitted cloth by rule.
2
+ //
3
+ // Colourwork is drawn on squared paper before it is knitted. A chart
4
+ // is a grid with one square a stitch, and a jumper is a stack of
5
+ // bands, each a chart repeated round the body. Fair Isle adds two
6
+ // rules to that. A row is worked in two colours and no more, because
7
+ // the knitter carries one in each hand; and the colour not in use is
8
+ // stranded across the back, so it may not go more than a few stitches
9
+ // before it is wanted again, or the float catches on fingers. The
10
+ // colours can change from row to row, and they do: a band shades
11
+ // towards its middle row and back.
12
+ //
13
+ // A chart here is a list of strings, a character a stitch. "." is the
14
+ // ground and "X" the pattern; any other character is a further colour,
15
+ // which Fair Isle would not allow in the same row and a Christmas
16
+ // jumper does.
17
+ //
18
+ // Nothing above the last section needs a document, so the rule can be
19
+ // tested without a browser.
20
+
21
+ const mod = (n, m) => ((n % m) + m) % m;
22
+ const rngOf = seed => { let a = seed >>> 0; return () => { a |= 0; a = a + 0x6D2B79F5 | 0; let t = Math.imul(a ^ a >>> 15, 1 | a); t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t; return ((t ^ t >>> 14) >>> 0) / 4294967296; }; };
23
+
24
+ // ------------------------------------------------------------- charts ---
25
+ export function chartOf(rows, gap) {
26
+ const w = Math.max(1, ...rows.map(r => r.length));
27
+ return { w, h: rows.length, rows: rows.map(r => r.padEnd(w, '.')), gap: gap || 0 };
28
+ }
29
+ // A motif with the square's eight symmetries, from a rule on how far a
30
+ // stitch is from the middle each way: `fn(a, b)` for a and b from 0 to n.
31
+ export function byRule(n, fn, gap) {
32
+ const rows = [];
33
+ for (let y = -n; y <= n; y++) {
34
+ let s = '';
35
+ for (let x = -n; x <= n; x++) s += fn(Math.abs(x), Math.abs(y)) ? 'X' : '.';
36
+ rows.push(s);
37
+ }
38
+ return chartOf(rows, gap == null ? 1 : gap);
39
+ }
40
+ // two charts side by side with a stitch between, as an O and an X are
41
+ const beside = (a, b) => chartOf(a.rows.map((r, j) => r + '.' + b.rows[j]), 1);
42
+
43
+ // the longest float in a chart as it repeats, and the most colours in any row
44
+ export function floatsOf(chart) {
45
+ let float = 0, colours = 0;
46
+ for (const row of chart.rows) {
47
+ const line = row + '.'.repeat(chart.gap || 0), n = line.length;
48
+ colours = Math.max(colours, new Set(line).size);
49
+ if (new Set(line).size < 2) continue; // a plain row strands nothing
50
+ let start = 0;
51
+ while (line[mod(start - 1, n)] === line[start]) start++;
52
+ for (let k = 0, run = 0; k < n; k++) {
53
+ const c = line[(start + k) % n];
54
+ run = k && c === line[(start + k - 1) % n] ? run + 1 : 1;
55
+ float = Math.max(float, run);
56
+ }
57
+ }
58
+ return { float, colours };
59
+ }
60
+
61
+ // ------------------------------------------------------------ motifs ---
62
+ // The small bands, peeries, of one to six rows.
63
+ export const PEERIES = {
64
+ seed: chartOf(['X...', '....', '..X.']),
65
+ dots: chartOf(['X.']),
66
+ check: chartOf(['XX..', 'XX..', '..XX', '..XX']),
67
+ zig: chartOf(['..X.', '.X.X', 'X...']),
68
+ wave: chartOf(['XX....', '.XX..X', '...XX.']),
69
+ cross: chartOf(['.X..', 'XXX.', '.X..']),
70
+ links: chartOf(['.XXX..', 'X...X.', '.XXX..']),
71
+ lozenge: chartOf(['..X...', '.X.X..', 'X.X.X.', '.X.X..', '..X...']),
72
+ hearts: chartOf(['.X.X....', 'XXXXX...', 'XXXXX...', '.XXX....', '..X.....']),
73
+ bars: chartOf(['XXX.', 'XXX.']),
74
+ };
75
+
76
+ // The large bands, by rule, at any half-width n (the band is 2n + 1
77
+ // rows). A motif alone on its ground leaves long floats beside it, so
78
+ // each is given what a knitter gives it: small rings of stitches in the
79
+ // corners and at the middle of each side, where four motifs meet, no
80
+ // more of them than it takes to bring every float under the limit.
81
+ const FLOAT = 7;
82
+ function fitted(n, shape) {
83
+ let best = null;
84
+ for (let r = 0; r <= n; r++) for (let e = -1; e <= r; e++) {
85
+ const c = byRule(n, (a, b) => {
86
+ if (shape(a, b)) return true;
87
+ const corner = (n - a) + (n - b), edge = Math.min(a, b) + n - Math.max(a, b);
88
+ return (corner <= r - 1 && corner % 2 === 0) || (edge <= e && edge % 2 === 0);
89
+ });
90
+ const f = floatsOf(c).float;
91
+ if (!best || f < best.f) best = { c, f };
92
+ if (f <= FLOAT) return c;
93
+ }
94
+ return best.c;
95
+ }
96
+ export const BORDERS = {
97
+ // the O and the X: a ring with a seeded middle, then a saltire
98
+ oxo: n => beside(
99
+ fitted(n, (a, b) => { const s = a + b; return (s <= n && s >= n - 1) || (s <= n - 4 && s % 2 === 0); }),
100
+ fitted(n, (a, b) => (Math.abs(a - b) <= 1 && a + b >= 3) || a + b === 0)),
101
+ // eight points: a square laid over a square on its corner, cut into petals along its axes and diagonals
102
+ star: n => fitted(n, (a, b) => {
103
+ const hi = Math.max(a, b), lo = Math.min(a, b), m = Math.round(n * 0.62);
104
+ if (!(hi <= m || a + b <= n)) return false;
105
+ if (hi === 0) return true;
106
+ return !(a === b || (lo === 0 && hi < n) || (hi - lo === 2 && hi < n - 1 && n > 5));
107
+ }),
108
+ // diamonds inside diamonds
109
+ diamond: n => fitted(n, (a, b) => a + b <= n && (n - a - b) % 4 < 2),
110
+ // a snow crystal: six arms would be right, eight is what a square grid gives
111
+ flake: n => fitted(n, (a, b) => {
112
+ const hi = Math.max(a, b), lo = Math.min(a, b);
113
+ if (lo === 0) return hi <= n - 1 && hi % 4 !== 3; // the four arms, with a break in each
114
+ if (a === b) return a <= n - 2; // and the four between
115
+ if (lo === 1 && hi >= 2 && hi <= n - 2 && hi % 2 === 0) return true; // barbs on the arms
116
+ return hi - lo === 1 && hi >= 3 && hi <= n - 2 && hi % 2 === 1;
117
+ }),
118
+ // a lattice of crosses and squares
119
+ tile: n => byRule(n, (a, b) => (a % 4 < 2) !== (b % 4 < 2), 0),
120
+ };
121
+ export const BORDER_NAMES = Object.keys(BORDERS);
122
+ export const PEERIE_NAMES = Object.keys(PEERIES);
123
+
124
+ // A motif nobody charted. A stitch is in the pattern by two short
125
+ // repeats read along the diagonals, one against the other, which is
126
+ // what gives the big Fair Isle bands their lozenges and saltires. Tried
127
+ // again until no float is longer than `limit`.
128
+ export function ruleMotif(seed, n, limit) {
129
+ const rng = rngOf(seed * 2654435761 + n * 97 + 13);
130
+ const bits = len => { let s; do { s = Array.from({ length: len }, () => rng() < 0.5); } while (s.every(v => v === s[0])); return s; };
131
+ let best = null;
132
+ for (let tries = 0; tries < 60; tries++) {
133
+ const A = bits(3 + Math.floor(rng() * 4)), B = bits(2 + Math.floor(rng() * 4)), env = rng() < 0.5;
134
+ const c = byRule(n, (a, b) => (!env || a + b <= n + 2) && A[(a + b) % A.length] !== B[Math.abs(a - b) % B.length]);
135
+ const f = floatsOf(c).float;
136
+ if (!best || f < best.f) best = { c, f };
137
+ if (f <= (limit || 7)) break;
138
+ }
139
+ return best.c;
140
+ }
141
+
142
+ // Figures for the season, in more colours than a row should have. The
143
+ // letters are inks the page names: X the band's own pattern colour,
144
+ // k black, w white, r red, g green, y gold, b brown.
145
+ export const FIGURES = {
146
+ reindeer: chartOf([
147
+ '..b.b.....b.b..', '..b.b.....b.b..', '...bbb...bbb...', '....b.....b....', '....bb...bb....',
148
+ '.XX..XXXXX..XX.', '.XXXXXXXXXXXXX.', '...XXXXXXXXX...', '...XkXXXXXkX...', '...XXXXXXXXX...',
149
+ '....XXXXXXX....', '....XXrrrXX....', '.....XrrrX.....', '.....XXXXX.....', '......XXX......'], 2),
150
+ tree: chartOf([
151
+ '.....y.....', '.....g.....', '....ggg....', '...ggrgg...', '....ggg....', '...ggggg...', '..ggyggrg..',
152
+ '...ggggg...', '..gggggrg..', '.ggrgggggg.', 'ggggggygggg', '....bbb....', '....bbb....'], 2),
153
+ pudding: chartOf([
154
+ '....g.g....', '.....r.....', '...wwwww...', '..wwwwwww..', '.wwbwwwbww.', '.wbbbwbbbw.', '.bbbbbbbbb.',
155
+ '.bbkbbbkbb.', '.bbbbkbbbb.', '..bbbbbbb..', '...bbbbb...'], 2),
156
+ snowman: chartOf([
157
+ '...kkk...', '...kkk...', '..kkkkk..', '...www...', '..wkwkw..', '..wwyww..', '...www...', '.rrrrrrr.',
158
+ '..wwwwwr.', '.wwwkwww.', '.wwwwwww.', '.wwwkwww.', '..wwwww..'], 2),
159
+ gift: chartOf([
160
+ '..rr.rr..', '.r..r..r.', '..rrrrr..', 'XXXXrXXXX', 'XXXXrXXXX', 'rrrrrrrrr', 'XXXXrXXXX', 'XXXXrXXXX', 'XXXXrXXXX'], 3),
161
+ cane: chartOf([
162
+ '..rwr..', '.w...w.', '.r...r.', '.....w.', '.....r.', '.....w.', '.....r.', '.....w.', '.....r.', '.....w.'], 3),
163
+ bauble: chartOf([
164
+ '...y...', '..yyy..', '.XXXXX.', 'XXwXXXX', 'XwXXXXX', 'yyyyyyy', 'XXXXXXX', '.XXXXX.', '..XXX..'], 3),
165
+ heart: chartOf([
166
+ '.rr...rr.', 'rrrr.rrrr', 'rrrrrrrrr', 'rrrrrrrrr', '.rrrrrrr.', '..rrrrr..', '...rrr...', '....r....'], 3),
167
+ };
168
+ export const FIGURE_NAMES = Object.keys(FIGURES);
169
+
170
+ // ------------------------------------------------------------ letters ---
171
+ // Five stitches by seven, the alphabet of every knitted name.
172
+ const FONT = {
173
+ A: '01110100011000111111100011000110001', B: '11110100011000111110100011000111110', C: '01110100011000010000100001000101110',
174
+ D: '11110100011000110001100011000111110', E: '11111100001000011110100001000011111', F: '11111100001000011110100001000010000',
175
+ G: '01110100011000010111100011000101111', H: '10001100011000111111100011000110001', I: '01110001000010000100001000010001110',
176
+ J: '00111000100001000010000101001001100', K: '10001100101010011000101001001010001', L: '10000100001000010000100001000011111',
177
+ M: '10001110111010110101100011000110001', N: '10001110011010110011100011000110001', O: '01110100011000110001100011000101110',
178
+ P: '11110100011000111110100001000010000', Q: '01110100011000110001101011001001101', R: '11110100011000111110101001001010001',
179
+ S: '01111100001000001110000010000111110', T: '11111001000010000100001000010000100', U: '10001100011000110001100011000101110',
180
+ V: '10001100011000110001100010101000100', W: '10001100011000110101101011101110001', X: '10001100010101000100010101000110001',
181
+ Y: '10001100010101000100001000010000100', Z: '11111000010001000100010001000011111',
182
+ 0: '01110100011001110101110011000101110', 1: '00100011000010000100001000010001110', 2: '01110100010000100010001000100011111',
183
+ 3: '11110000010000101110000010000111110', 4: '00010001100101010010111110001000010', 5: '11111100001111000001000011000101110',
184
+ 6: '00110010001000011110100011000101110', 7: '11111000010001000100010000100001000', 8: '01110100011000101110100011000101110',
185
+ 9: '01110100011000101111000010001001100',
186
+ '!': '00100001000010000100001000000000100', '?': '01110100010000100010001000000000100', '.': '00000000000000000000000000110001100',
187
+ ',': '00000000000000000000001100010001000', '-': '00000000000000011111000000000000000', "'": '00100001000100000000000000000000000',
188
+ '&': '01100100101010001000101011001001101', '*': '00000010101111111111011100010000000', '+': '00000001000010011111001000010000000',
189
+ ' ': '00000000000000000000000000000000000',
190
+ };
191
+ export function knittable(text) {
192
+ return String(text || '').normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/[♥❤]/g, '*').toUpperCase().replace(/[^A-Z0-9!?.,\-'&*+ ]/g, '').replace(/\s+/g, ' ').trim();
193
+ }
194
+ // a word as a chart, seven rows high, a stitch between the letters
195
+ export function textChart(text) {
196
+ const t = knittable(text), rows = Array.from({ length: 7 }, () => '');
197
+ for (let k = 0; k < t.length; k++) {
198
+ const gl = FONT[t[k]] || FONT[' '];
199
+ for (let r = 0; r < 7; r++) rows[r] += (k ? '.' : '') + gl.slice(r * 5, r * 5 + 5).replace(/1/g, 'X').replace(/0/g, '.');
200
+ }
201
+ return chartOf(t ? rows : ['.'], 0);
202
+ }
203
+
204
+ // -------------------------------------------------------------- bands ---
205
+ // A band is a chart with its colours. `colours` gives a colour for each
206
+ // character of the chart: one for the whole band, or a list with one
207
+ // for each row of the chart. `repeat` false knits the chart once, at
208
+ // `phase`. `scale` knits every stitch of the chart as that many each way.
209
+ export function band(chart, colours, opts) {
210
+ const o = opts || {};
211
+ return { chart, colours, repeat: o.repeat !== false, scale: Math.max(1, o.scale || 1), phase: o.phase || 0, gap: o.gap == null ? chart.gap || 0 : o.gap, tag: o.tag || '' };
212
+ }
213
+ export const plain = (rows, colour) => band(chartOf(Array.from({ length: Math.max(1, rows) }, () => '.')), { '.': colour });
214
+
215
+ // Bands from the top down, as a stack. `repeat` true begins again at
216
+ // the bottom, as an endless cloth; otherwise everything outside is `base`.
217
+ export function stackOf(bands, base, repeat) {
218
+ let top = 0;
219
+ const out = bands.map(b => { const r = { ...b, top, rows: b.chart.h * b.scale }; top += r.rows; return r; });
220
+ const index = new Int16Array(Math.max(1, top));
221
+ out.forEach((b, k) => index.fill(k, b.top, b.top + b.rows));
222
+ return { bands: out, rows: Math.max(1, top), base: base || '#888888', repeat: !!repeat, index };
223
+ }
224
+
225
+ // the colour of stitch i of row j
226
+ export function stitchAt(stack, i, j) {
227
+ if (!stack.bands.length) return stack.base;
228
+ if (stack.repeat) j = mod(j, stack.rows);
229
+ else if (j < 0 || j >= stack.rows) return stack.base;
230
+ const b = stack.bands[stack.index[j]], c = b.chart;
231
+ const r = Math.floor((j - b.top) / b.scale);
232
+ let x = Math.floor((i - b.phase) / b.scale), ch = '.';
233
+ if (b.repeat) { x = mod(x, c.w + b.gap); if (x < c.w) ch = c.rows[r][x]; }
234
+ else if (x >= 0 && x < c.w) ch = c.rows[r][x];
235
+ const col = b.colours[ch] || b.colours.X || b.colours['.'] || stack.base;
236
+ return typeof col === 'string' ? col : col[Math.min(r, col.length - 1)];
237
+ }
238
+
239
+ // A band's colours shading to its middle row and back: `shades` from
240
+ // the edge inwards, for a chart h rows high.
241
+ export function shadeRows(h, shades) {
242
+ if (typeof shades === 'string') return shades;
243
+ const out = [], half = (h - 1) / 2;
244
+ for (let r = 0; r < h; r++) {
245
+ const t = half ? 1 - Math.abs(r - half) / half : 1;
246
+ out.push(shades[Math.min(shades.length - 1, Math.floor(t * shades.length))]);
247
+ }
248
+ return out;
249
+ }
250
+
251
+ // --------------------------------------------------------------- wool ---
252
+ // Dye lots. Each has a ground for the plain rows, and sets of shades
253
+ // for a band's ground and its pattern, from the edge of a band to its
254
+ // middle. `pop` is the one bright row at the heart of a large band.
255
+ export const WOOLS = {
256
+ shetland: { base: '#e7dcc4', pop: '#b4532a', sets: [
257
+ { g: ['#e7dcc4', '#d8c9a8', '#c9b68e'], p: ['#4a352a', '#6b4a36', '#8a5f40'] },
258
+ { g: ['#d8c9a8', '#e7dcc4', '#f3ecdb'], p: ['#2f2a28', '#55504c', '#7d766e'] },
259
+ { g: ['#c9b68e', '#d8c9a8'], p: ['#3a2c24', '#4a352a'] }] },
260
+ madder: { base: '#efe6d0', pop: '#e0a526', sets: [
261
+ { g: ['#efe6d0', '#e8d7a8', '#e0c070'], p: ['#7c1f1c', '#a52a22', '#c8452c'] },
262
+ { g: ['#efe6d0', '#c9d6dc', '#9fb8c8'], p: ['#1d2f55', '#2a4a7c', '#3f6a9c'] },
263
+ { g: ['#e8d7a8', '#efe6d0'], p: ['#3d5a34', '#57783f'] }] },
264
+ sea: { base: '#dfe6e6', pop: '#f2efe2', sets: [
265
+ { g: ['#1c2e44', '#26405c', '#345878'], p: ['#dfe6e6', '#b9ccd4', '#8fb0c0'] },
266
+ { g: ['#dfe6e6', '#c4d4d8', '#a6c0c8'], p: ['#16263a', '#24405e', '#3a6282'] },
267
+ { g: ['#7f9aa6', '#93aab4'], p: ['#16263a', '#1c2e44'] }] },
268
+ heather: { base: '#3a3344', pop: '#e6c84a', sets: [
269
+ { g: ['#3a3344', '#4a3f5a', '#5c4a70'], p: ['#c7a9d4', '#dcc4e4', '#f0e2f2'] },
270
+ { g: ['#2f4038', '#3d5548', '#4d6a58'], p: ['#d9c9a0', '#e6dab8', '#f2ecd6'] },
271
+ { g: ['#5c4a70', '#4a3f5a'], p: ['#9ab58c', '#b4cca4'] }] },
272
+ yule: { base: '#f1e8d6', pop: '#e0b23a', sets: [
273
+ { g: ['#f1e8d6', '#f1e8d6', '#e8dcc0'], p: ['#9c1b22', '#b3202a', '#c8323a'] },
274
+ { g: ['#f1e8d6', '#e8dcc0'], p: ['#17472f', '#1f5a3a', '#2c7048'] },
275
+ { g: ['#b3202a', '#9c1b22'], p: ['#f1e8d6', '#f8f2e4'] }] },
276
+ stepinto: { base: '#0f1524', pop: '#22d3ee', sets: [
277
+ { g: ['#0f1524', '#152038', '#1e2c4a'], p: ['#38bdf8', '#5ccaf8', '#8adcfb'] },
278
+ { g: ['#152038', '#1e2c4a'], p: ['#8b5cf6', '#a78bfa'] },
279
+ { g: ['#0f1524', '#152038'], p: ['#a7b0c0', '#cbd2de'] }] },
280
+ };
281
+ export const WOOL_NAMES = Object.keys(WOOLS);
282
+
283
+ // ----------------------------------------------------------- fair isle ---
284
+ // A cloth is written as its bands from the top down: "oxo13 zig star11
285
+ // seed". A name from BORDERS takes the rows it is to be knitted over
286
+ // (odd, 7 to 21) after it; a name from PEERIES stands alone; "?" is a
287
+ // large band by rule from the seed, and may take rows too.
288
+ export function parseBands(text) {
289
+ const out = [], re = /(\?|[a-z]+)\s*(\d{0,2})/g;
290
+ let m;
291
+ const t = String(text || '').toLowerCase();
292
+ while ((m = re.exec(t)) && out.length < 40) {
293
+ const name = m[1], rows = m[2] ? Math.max(7, Math.min(21, parseInt(m[2], 10) | 1)) : 13;
294
+ if (name === '?' || BORDERS[name]) out.push({ name, rows });
295
+ else if (PEERIES[name]) out.push({ name, rows: PEERIES[name].h });
296
+ }
297
+ return out;
298
+ }
299
+ export const writeBands = list => list.map(b => (b.name === '?' || BORDERS[b.name]) ? b.name + b.rows : b.name).join(' ');
300
+
301
+ // The stack for a cloth: each large band takes the wool's next set of
302
+ // shades and the bright row at its heart, each peerie the set after,
303
+ // and one plain row lies between any two.
304
+ export function fairIsle(text, wool, seed, opts) {
305
+ const o = opts || {}, lot = typeof wool === 'string' ? WOOLS[wool] || WOOLS.madder : wool;
306
+ const list = parseBands(text), bands = [];
307
+ let big = 0, small = 0;
308
+ list.forEach((item, k) => {
309
+ const isBig = item.name === '?' || !!BORDERS[item.name], n = (item.rows - 1) / 2;
310
+ const chart = item.name === '?' ? ruleMotif((seed || 1) + k * 31, n, 7) : isBig ? BORDERS[item.name](n) : PEERIES[item.name];
311
+ const set = lot.sets[(isBig ? big++ : lot.sets.length - 1 - (small++ % 2)) % lot.sets.length];
312
+ const g = o.shade === false ? set.g[0] : shadeRows(chart.h, set.g);
313
+ let p = o.shade === false ? set.p[0] : shadeRows(chart.h, set.p);
314
+ if (isBig && o.shade !== false && lot.pop && typeof p !== 'string') { p = p.slice(); p[n] = lot.pop; }
315
+ bands.push(band(chart, { '.': g, X: p }, { tag: item.name }));
316
+ bands.push(plain(1, lot.base));
317
+ });
318
+ return stackOf(bands, lot.base, true);
319
+ }
320
+
321
+ // a cloth nobody has knitted: large bands and peeries turn about
322
+ export function randomBands(seed) {
323
+ const rng = rngOf((seed || 1) * 40503 + 7), pick = a => a[Math.floor(rng() * a.length)];
324
+ const out = [], n = 2 + Math.floor(rng() * 3);
325
+ for (let k = 0; k < n; k++) {
326
+ out.push({ name: rng() < 0.4 ? '?' : pick(BORDER_NAMES), rows: pick([9, 11, 13, 13, 15, 17]) });
327
+ out.push({ name: pick(PEERIE_NAMES), rows: 0 });
328
+ if (rng() < 0.35) out.push({ name: pick(PEERIE_NAMES), rows: 0 });
329
+ }
330
+ return writeBands(out);
331
+ }
332
+
333
+ // -------------------------------------------------------------- cloth ---
334
+ // Fills `data` (RGBA, w by h, one pixel a stitch) from stitch i0 of row j0.
335
+ const rgbCache = new Map();
336
+ const rgbOf = hex => { let c = rgbCache.get(hex); if (!c) { const n = parseInt(hex.slice(1), 16); c = [(n >> 16) & 255, (n >> 8) & 255, n & 255]; rgbCache.set(hex, c); } return c; };
337
+ export function knitPixels(data, w, h, i0, j0, stack) {
338
+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
339
+ const c = rgbOf(stitchAt(stack, i0 + x, j0 + y)), o = (y * w + x) * 4;
340
+ data[o] = c[0]; data[o + 1] = c[1]; data[o + 2] = c[2]; data[o + 3] = 255;
341
+ }
342
+ return data;
343
+ }
344
+
345
+ // A knit stitch is a V, and a column of them is a stack of chevrons.
346
+ // ROW is how tall a stitch is against its width, DIP how far the point
347
+ // of the V hangs below its shoulders, as a part of that height.
348
+ export const ROW = 0.8, DIP = 0.6;
349
+
350
+ // The stitch itself: one V, `px` wide, in black and white over
351
+ // nothing, to be laid over the colour. Each leg is a round strand, dark
352
+ // where it meets the next column and where it tucks under the row
353
+ // above, with the twist of the plies across it.
354
+ const tiles = new Map();
355
+ export function stitchTile(px) {
356
+ const W = Math.max(2, Math.round(px)), H = Math.max(2, Math.round(px * ROW));
357
+ const key = W + 'x' + H;
358
+ let c = tiles.get(key);
359
+ if (c) return c;
360
+ if (tiles.size > 24) tiles.clear();
361
+ c = document.createElement('canvas'); c.width = W; c.height = H;
362
+ const g = c.getContext('2d'), D = H * DIP;
363
+ for (const side of [0, 1]) {
364
+ const x0 = side ? W / 2 : 0, x1 = x0 + W / 2;
365
+ // the top of this leg at its outer and inner edge
366
+ const yo = k => k * H + (side ? D : 0), yi = k => k * H + (side ? 0 : D);
367
+ for (let k = -2; k <= 1; k++) {
368
+ g.save();
369
+ g.beginPath(); g.moveTo(x0, yo(k)); g.lineTo(x1, yi(k)); g.lineTo(x1, yi(k) + H); g.lineTo(x0, yo(k) + H); g.closePath(); g.clip();
370
+ // round across its width
371
+ const gr = g.createLinearGradient(x0, 0, x1, 0);
372
+ const stops = [[0, 'rgba(0,0,0,0.30)'], [0.25, 'rgba(0,0,0,0.03)'], [0.5, 'rgba(255,255,255,0.15)'], [0.78, 'rgba(0,0,0,0.05)'], [1, 'rgba(0,0,0,0.26)']];
373
+ for (const [t, col] of stops) gr.addColorStop(side ? 1 - t : t, col);
374
+ g.fillStyle = gr; g.fillRect(x0, k * H - 1, W / 2, H + D + 2);
375
+ // tucked under the stitch above, and lit where it comes forward
376
+ if (W >= 5) {
377
+ g.lineCap = 'butt';
378
+ g.strokeStyle = 'rgba(0,0,0,0.30)'; g.lineWidth = Math.max(1, H * 0.2);
379
+ g.beginPath(); g.moveTo(x0, yo(k)); g.lineTo(x1, yi(k)); g.stroke();
380
+ g.strokeStyle = 'rgba(255,255,255,0.10)'; g.lineWidth = Math.max(1, H * 0.16);
381
+ g.beginPath(); g.moveTo(x0, yo(k) + H * 0.72); g.lineTo(x1, yi(k) + H * 0.72); g.stroke();
382
+ }
383
+ // the plies
384
+ if (W >= 9) {
385
+ g.strokeStyle = 'rgba(0,0,0,0.11)'; g.lineWidth = Math.max(0.6, W * 0.035);
386
+ for (let p = 0; p < 4; p++) {
387
+ const t = (p + 0.5) / 4, ym = (side ? yo(k) + (yi(k) - yo(k)) * 0.5 : yo(k) + (yi(k) - yo(k)) * 0.5) + t * H;
388
+ g.beginPath(); g.moveTo(x0, ym + (side ? -1 : 1) * H * 0.2); g.lineTo(x1, ym + (side ? 1 : -1) * H * 0.2); g.stroke();
389
+ }
390
+ }
391
+ g.restore();
392
+ }
393
+ }
394
+ tiles.set(key, c);
395
+ return c;
396
+ }
397
+
398
+ // Ribbing, for a welt, a cuff or a collar: a column of knit stitches
399
+ // standing forward, a column of purl lying back, turn about.
400
+ export function ribTile(px) {
401
+ const W = Math.max(2, Math.round(px)), H = Math.max(2, Math.round(px * ROW));
402
+ const key = 'rib' + W + 'x' + H;
403
+ let c = tiles.get(key);
404
+ if (c) return c;
405
+ c = document.createElement('canvas'); c.width = W * 2; c.height = H;
406
+ const g = c.getContext('2d');
407
+ g.drawImage(stitchTile(px), 0, 0);
408
+ const gr = g.createLinearGradient(W, 0, W * 2, 0);
409
+ gr.addColorStop(0, 'rgba(0,0,0,0.30)'); gr.addColorStop(0.5, 'rgba(0,0,0,0.46)'); gr.addColorStop(1, 'rgba(0,0,0,0.30)');
410
+ g.fillStyle = gr; g.fillRect(W, 0, W, H);
411
+ // the purl bump
412
+ g.fillStyle = 'rgba(255,255,255,0.10)'; g.fillRect(W + W * 0.2, H * 0.35, W * 0.6, Math.max(1, H * 0.22));
413
+ tiles.set(key, c);
414
+ return c;
415
+ }
416
+
417
+ // The halo: short fibres standing off the yarn, lighter and darker, in
418
+ // every direction. A tile that repeats.
419
+ export function fuzzTile(seed, size) {
420
+ const key = 'fuzz' + seed + '|' + size;
421
+ let c = tiles.get(key);
422
+ if (c) return c;
423
+ c = document.createElement('canvas'); c.width = c.height = size;
424
+ const g = c.getContext('2d'), rng = rngOf(seed * 7 + 11);
425
+ g.lineCap = 'round';
426
+ for (let i = 0; i < size * size / 12; i++) {
427
+ const x = rng() * size, y = rng() * size, a = rng() * Math.PI * 2, l = 1.5 + rng() * 4.5;
428
+ g.strokeStyle = rng() < 0.6 ? `rgba(255,255,255,${0.05 + rng() * 0.13})` : `rgba(0,0,0,${0.05 + rng() * 0.11})`;
429
+ g.lineWidth = 0.5 + rng() * 0.7;
430
+ for (const ox of [-size, 0, size]) for (const oy of [-size, 0, size]) {
431
+ g.beginPath(); g.moveTo(x + ox, y + oy); g.quadraticCurveTo(x + ox + Math.cos(a + 0.6) * l * 0.5, y + oy + Math.sin(a + 0.6) * l * 0.5, x + ox + Math.cos(a) * l, y + oy + Math.sin(a) * l); g.stroke();
432
+ }
433
+ }
434
+ tiles.set(key, c);
435
+ return c;
436
+ }
437
+
438
+ // Knits `stack` over nw stitches by nh rows from stitch i0 of row j0,
439
+ // into whatever transform the context has: a stitch is one unit wide
440
+ // and ROW high, so stitch (i, j) has its shoulders at (i, j * ROW).
441
+ // `px` is the width of a stitch in the canvas's own pixels, which
442
+ // decides how much of the stitch is worth drawing. Clip first if the
443
+ // cloth has an edge.
444
+ let pix = null;
445
+ export function paintKnit(g, stack, i0, j0, nw, nh, px) {
446
+ if (nw <= 0 || nh <= 0) return;
447
+ // the colour, a pixel a stitch: all there is when stitches are small, and what shows in any crack when they are not
448
+ pix = pix || document.createElement('canvas');
449
+ if (pix.width !== nw || pix.height !== nh) { pix.width = nw; pix.height = nh; }
450
+ const pg = pix.getContext('2d'), img = pg.createImageData(nw, nh);
451
+ knitPixels(img.data, nw, nh, i0, j0, stack);
452
+ pg.putImageData(img, 0, 0);
453
+ g.save();
454
+ g.imageSmoothingEnabled = px < 2;
455
+ g.drawImage(pix, i0, j0 * ROW, nw, nh * ROW);
456
+ g.imageSmoothingEnabled = true;
457
+ if (px >= 4 && nw * nh <= 260000) {
458
+ // Every stitch as its V. A run of one colour along a row is one
459
+ // shape, a zigzag above and the same zigzag below, and the shapes
460
+ // are filled a few rows at a time: one path holding a whole cloth
461
+ // is far slower to fill than the same cloth in pieces.
462
+ const d = ROW * DIP, px32 = new Uint32Array(img.data.buffer), paths = new Map();
463
+ const hexOf = v => '#' + ((1 << 24) | ((v & 255) << 16) | (v & 0xff00) | ((v >> 16) & 255)).toString(16).slice(1);
464
+ const run = (v, a, b, j) => {
465
+ let p = paths.get(v);
466
+ if (!p) { p = new Path2D(); paths.set(v, p); }
467
+ const y = j * ROW;
468
+ p.moveTo(a, y);
469
+ for (let i = a; i < b; i++) { p.lineTo(i + 0.5, y + d); p.lineTo(i + 1, y); }
470
+ p.lineTo(b, y + ROW);
471
+ for (let i = b - 1; i >= a; i--) { p.lineTo(i + 0.5, y + ROW + d); p.lineTo(i, y + ROW); }
472
+ p.closePath();
473
+ };
474
+ const flush = () => { for (const [v, p] of paths) { g.fillStyle = hexOf(v); g.fill(p); } paths.clear(); };
475
+ // one row more above, in its own colours, so the top edge is covered
476
+ for (let x = 0; x < nw; x++) { const c = rgbOf(stitchAt(stack, i0 + x, j0 - 1)); run(c[0] | (c[1] << 8) | (c[2] << 16) | 0xff000000, i0 + x, i0 + x + 1, j0 - 1); }
477
+ for (let y = 0; y < nh; y++) {
478
+ let a = 0;
479
+ for (let x = 1; x <= nw; x++) if (x === nw || px32[y * nw + x] !== px32[y * nw + a]) { run(px32[y * nw + a], i0 + a, i0 + x, j0 + y); a = x; }
480
+ if (y % 6 === 5) flush();
481
+ }
482
+ flush();
483
+ }
484
+ if (px >= 2.5) {
485
+ const tile = stitchTile(px), pat = g.createPattern(tile, 'repeat');
486
+ pat.setTransform(new DOMMatrix([1 / tile.width, 0, 0, ROW / tile.height, 0, 0]));
487
+ g.fillStyle = pat; g.fillRect(i0, (j0 - 1) * ROW, nw, (nh + 2) * ROW);
488
+ }
489
+ g.restore();
490
+ }
491
+
492
+ // Ribbing in one colour over a rectangle, in the same units.
493
+ export function paintRib(g, colour, x, y, w, h, px) {
494
+ g.save();
495
+ g.fillStyle = colour; g.fillRect(x, y, w, h);
496
+ if (px >= 2.5) {
497
+ const tile = ribTile(px), pat = g.createPattern(tile, 'repeat');
498
+ pat.setTransform(new DOMMatrix([2 / tile.width, 0, 0, ROW / tile.height, x, y]));
499
+ g.fillStyle = pat; g.fillRect(x, y, w, h);
500
+ }
501
+ g.restore();
502
+ }
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/knit.mjs ADDED
@@ -0,0 +1,70 @@
1
+ // Knitting's rule: charts, bands, the float limit and the stack they make.
2
+ import assert from 'node:assert/strict';
3
+ import { PEERIES, BORDERS, BORDER_NAMES, FIGURES, floatsOf, ruleMotif, chartOf, byRule, textChart, knittable,
4
+ band, plain, stackOf, stitchAt, shadeRows, parseBands, writeBands, fairIsle, randomBands, knitPixels, WOOLS, WOOL_NAMES } from '../src/knit.js';
5
+
6
+ // a chart is square-edged: every row as wide as the widest
7
+ for (const c of [...Object.values(PEERIES), ...Object.values(FIGURES)]) for (const r of c.rows) assert.equal(r.length, c.w);
8
+
9
+ // Fair Isle's two rules, for every band it can be asked for: two colours a row, and no float over seven
10
+ for (const [name, c] of Object.entries(PEERIES)) { const f = floatsOf(c); assert.ok(f.colours <= 2 && f.float <= 7, 'peerie ' + name); }
11
+ for (const name of BORDER_NAMES) for (let n = 3; n <= 10; n++) {
12
+ const c = BORDERS[name](n), f = floatsOf(c);
13
+ assert.equal(c.h, 2 * n + 1, name + ' rows');
14
+ assert.ok(f.colours <= 2 && f.float <= 7, name + ' at ' + (2 * n + 1) + ' rows floats ' + f.float);
15
+ // and it is the same upside down
16
+ assert.deepEqual(c.rows.slice().reverse(), c.rows, name + ' mirrors');
17
+ }
18
+ // a motif by rule keeps the limit too, and the same seed gives the same motif
19
+ for (let seed = 1; seed <= 40; seed++) for (const n of [4, 6, 8]) {
20
+ const c = ruleMotif(seed, n, 7);
21
+ assert.ok(floatsOf(c).float <= 7, 'rule motif ' + seed + ' at ' + n);
22
+ assert.deepEqual(ruleMotif(seed, n, 7).rows, c.rows);
23
+ }
24
+ // the float is counted round the repeat, gap and all
25
+ assert.equal(floatsOf(chartOf(['X....'], 3)).float, 7);
26
+ assert.equal(floatsOf(chartOf(['..X..'], 0)).float, 4);
27
+ assert.equal(floatsOf(chartOf(['XrX.'])).colours, 3);
28
+
29
+ // letters: five by seven, a stitch between, accents dropped
30
+ assert.equal(knittable(' olé, lotte ♥ '), 'OLE, LOTTE *');
31
+ const t = textChart('Hi');
32
+ assert.equal(t.h, 7); assert.equal(t.w, 11);
33
+ assert.equal(t.rows[3], 'XXXXX...X..');
34
+ assert.equal(textChart('').h, 1);
35
+
36
+ // a stack: bands from the top down, each a chart repeated along its rows
37
+ const k = stackOf([band(chartOf(['X.', '.X']), { '.': '#000000', X: '#ffffff' }), plain(2, '#ff0000')], '#00ff00', true);
38
+ assert.equal(k.rows, 4);
39
+ assert.equal(stitchAt(k, 0, 0), '#ffffff'); assert.equal(stitchAt(k, 1, 0), '#000000'); assert.equal(stitchAt(k, 1, 1), '#ffffff');
40
+ assert.equal(stitchAt(k, 5, 2), '#ff0000');
41
+ assert.equal(stitchAt(k, -2, -4), '#ffffff'); // it repeats both ways
42
+ assert.equal(stitchAt({ ...k, repeat: false }, 0, 9), '#00ff00'); // unless it is a garment, which ends
43
+ // a chart knitted once, twice the size, starting where it is told
44
+ const once = stackOf([band(chartOf(['X']), { '.': '#000000', X: '#ffffff' }, { repeat: false, scale: 2, phase: 3 })], '#000000', false);
45
+ assert.deepEqual([2, 3, 4, 5].map(i => stitchAt(once, i, 1)), ['#000000', '#ffffff', '#ffffff', '#000000']);
46
+ // colours by the row
47
+ assert.deepEqual(shadeRows(5, ['a', 'b', 'c']), ['a', 'b', 'c', 'b', 'a']);
48
+ const sh = stackOf([band(chartOf(['X', 'X', 'X']), { '.': '#000000', X: ['#111111', '#222222', '#111111'] })], '#000000', true);
49
+ assert.equal(stitchAt(sh, 0, 1), '#222222');
50
+
51
+ // a cloth is written as its bands
52
+ const list = parseBands('OXO13 zig, star 10 ? nonsense seed');
53
+ assert.deepEqual(list.map(b => b.name), ['oxo', 'zig', 'star', '?', 'seed']);
54
+ assert.equal(list[2].rows, 11); // rows are odd
55
+ assert.equal(writeBands(list), 'oxo13 zig star11 ?13 seed');
56
+ for (const wool of WOOL_NAMES) {
57
+ const cloth = fairIsle('oxo13 zig star11 seed', wool, 7);
58
+ assert.equal(cloth.rows, 13 + 3 + 11 + 3 + 4); // a plain row after each
59
+ // two colours a row, in the wool itself and not only on the chart
60
+ for (let j = 0; j < cloth.rows; j++) { const seen = new Set(); for (let i = 0; i < 60; i++) seen.add(stitchAt(cloth, i, j)); assert.ok(seen.size <= 2, wool + ' row ' + j); }
61
+ assert.ok(WOOLS[wool].sets.length >= 2);
62
+ }
63
+ // a cloth from a seed parses back to itself
64
+ for (let seed = 1; seed <= 20; seed++) { const w = randomBands(seed); assert.equal(writeBands(parseBands(w)), w); assert.equal(randomBands(seed), w); }
65
+
66
+ // one pixel a stitch
67
+ const data = knitPixels(new Uint8ClampedArray(2 * 2 * 4), 2, 2, 0, 0, k);
68
+ assert.deepEqual([...data.slice(0, 8)], [255, 255, 255, 255, 0, 0, 0, 255]);
69
+
70
+ console.log('knit ok');
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');