azulejeria 2.7.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 +57 -2
- package/package.json +5 -4
- package/src/draw.js +3 -1
- package/src/knit.js +502 -0
- package/test/knit.mjs +70 -0
package/README.md
CHANGED
|
@@ -26,11 +26,12 @@ not glazed, a material.
|
|
|
26
26
|
| `azulejeria/draw` | A tile drawn by hand, one eighth of it, carried in a string | Draw |
|
|
27
27
|
| `azulejeria/shadow` | A sun that goes round and the shadows it casts | Shadow |
|
|
28
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 |
|
|
29
30
|
| `azulejeria/azulejeria.css` | The styles for the panel, the cards, the title and the pad | The parts |
|
|
30
31
|
|
|
31
32
|
Each module stands alone except `draw`, which paints with the wall's
|
|
32
|
-
brush. `knots`, `groups`, `pieces`, `shadow` and `
|
|
33
|
-
context.
|
|
33
|
+
brush. `knots`, `groups`, `pieces`, `shadow`, `loom` and `knit` draw on any
|
|
34
|
+
2D context.
|
|
34
35
|
|
|
35
36
|
## Built on it
|
|
36
37
|
|
|
@@ -54,6 +55,7 @@ Other worlds on the viewer (`createViewer`):
|
|
|
54
55
|
[Rejería](https://stepinto.dev/art/rejeria.html) (wrought iron and its shadow on whitewash),
|
|
55
56
|
[Jali](https://stepinto.dev/art/jali.html) (a pierced stone screen and the light it lets onto the floor),
|
|
56
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),
|
|
57
59
|
[Hitomezashi](https://stepinto.dev/art/hitomezashi.html) (two words stitched as rows and columns),
|
|
58
60
|
[Azulejos de letras](https://stepinto.dev/art/letras.html) (a street-sign typeface, with borders that turn the corner),
|
|
59
61
|
[Mantón de Manila](https://stepinto.dev/art/manton.html) (embroidered silk),
|
|
@@ -517,6 +519,59 @@ from end `i0` and pick `j0`, and needs no document;
|
|
|
517
519
|
**`threadTile(draft, t)`** is the threads' own shading, one repeat at
|
|
518
520
|
`t` pixels a thread, to lay over it.
|
|
519
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
|
+
|
|
520
575
|
## Licence
|
|
521
576
|
|
|
522
577
|
MIT.
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "azulejeria",
|
|
3
|
-
"version": "2.
|
|
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
|
|
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"],
|
|
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",
|
|
@@ -18,11 +18,12 @@
|
|
|
18
18
|
"./draw": "./src/draw.js",
|
|
19
19
|
"./shadow": "./src/shadow.js",
|
|
20
20
|
"./loom": "./src/loom.js",
|
|
21
|
+
"./knit": "./src/knit.js",
|
|
21
22
|
"./azulejeria.css": "./src/azulejeria.css"
|
|
22
23
|
},
|
|
23
24
|
"files": ["src", "test", "README.md", "LICENSE"],
|
|
24
25
|
"sideEffects": false,
|
|
25
26
|
"scripts": {
|
|
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"
|
|
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"
|
|
27
28
|
}
|
|
28
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
|
-
|
|
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/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');
|