motlab.js 0.1.0 → 0.1.1

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.
@@ -1,441 +1,441 @@
1
- // Shape deformers for vector art: keyforms that interpolate shapes over params as Live2D does, blend shapes, lattice
2
- // warps, and skinning that bends paths with rig bones. Paths move by their points, so they stay sharp at any size.
3
- import { at } from '../core/math.js'
4
- import { Path, MOVE, LINE, CUBIC, CLOSE, ARGS } from '../core/path.js'
5
- import { toCurves } from './path.js'
6
-
7
- /**
8
- * @template T
9
- * @typedef {import('../core/math.js').Value<T>} Value
10
- */
11
-
12
- /**
13
- * What keyforms, blend shapes and the shape track type interpolate: numbers, arrays of numbers, paths with the same
14
- * commands in the same order, or plain objects of these.
15
- * @typedef {number | readonly number[] | Path | { [key: string]: Shape }} Shape
16
- */
17
-
18
- /**
19
- * Sums shapes scaled by weights. Weights here always add up to 1, so path opcodes are copied, not summed.
20
- * @param {readonly any[]} values
21
- * @param {readonly number[]} weights
22
- * @param {string} where
23
- * @returns {any}
24
- */
25
- function combine(values, weights, where) {
26
- const first = values[0]
27
- if (typeof first === 'number') {
28
- let sum = 0
29
- for (let i = 0; i < values.length; i++) sum += weights[i] * values[i]
30
- return sum
31
- }
32
- if (first instanceof Path) {
33
- const d0 = first.data
34
- for (const v of values) {
35
- if (!(v instanceof Path) || v.data.length !== d0.length) {
36
- throw new TypeError(`${where}: paths must have the same commands in the same order to blend`)
37
- }
38
- }
39
- const data = new Array(d0.length)
40
- for (let j = 0; j < d0.length; j += 1 + ARGS[d0[j]]) {
41
- data[j] = d0[j]
42
- for (const v of values) if (v.data[j] !== d0[j]) throw new TypeError(`${where}: paths must have the same commands in the same order to blend`)
43
- for (let a = j + 1; a <= j + ARGS[d0[j]]; a++) {
44
- let sum = 0
45
- for (let i = 0; i < values.length; i++) sum += weights[i] * values[i].data[a]
46
- data[a] = sum
47
- }
48
- }
49
- const out = new Path()
50
- out.data = data
51
- return out
52
- }
53
- if (Array.isArray(first) || ArrayBuffer.isView(first)) {
54
- const n = /** @type {ArrayLike<number>} */ (first).length
55
- for (const v of values) if (v.length !== n) throw new TypeError(`${where}: arrays of length ${n} and ${v.length} cannot blend`)
56
- const out = new Array(n)
57
- for (let j = 0; j < n; j++) {
58
- let sum = 0
59
- for (let i = 0; i < values.length; i++) sum += weights[i] * values[i][j]
60
- out[j] = sum
61
- }
62
- return out
63
- }
64
- if (first !== null && typeof first === 'object') {
65
- /** @type {Record<string, any>} */
66
- const out = {}
67
- for (const key of Object.keys(first)) {
68
- out[key] = combine(values.map(v => {
69
- if (v === null || typeof v !== 'object' || !(key in v)) throw new TypeError(`${where}: every shape must have "${key}"`)
70
- return v[key]
71
- }), weights, where)
72
- }
73
- return out
74
- }
75
- throw new TypeError(`${where}: can only blend numbers, arrays of numbers, paths and objects of these, got ${typeof first}`)
76
- }
77
-
78
- /**
79
- * Keeps the last result, for Values that several props read at the same time.
80
- * @template T
81
- * @param {(t: number) => T} fn
82
- * @returns {(t: number) => T}
83
- */
84
- function memo(fn) {
85
- let lastT = NaN
86
- /** @type {T} */
87
- let last
88
- return t => {
89
- if (t !== lastT) {
90
- last = fn(t)
91
- lastT = t
92
- }
93
- return last
94
- }
95
- }
96
-
97
- /**
98
- * A track type for shapes: track(keys, { type: shapeType }) tweens paths point by point, or whole objects of numbers
99
- * and paths, so a shape can morph between drawings with the same commands.
100
- * @type {import('../core/track.js').ValueType<any>}
101
- */
102
- export const shapeType = Object.freeze({
103
- mix: (/** @type {any} */ a, /** @type {any} */ b, /** @type {number} */ k) => combine([a, b], [1 - k, k], 'shapeType'),
104
- })
105
-
106
- /**
107
- * A keyform: shapes stored at key values of one or more inputs, such as Live2D's AngleX and AngleY params, blended
108
- * linearly across the grid of keys for the inputs' current values. Inputs past the outer keys hold the edge shape.
109
- * @param {Value<number> | ReadonlyArray<Value<number>>} inputs One input, or one per grid axis.
110
- * @param {ReadonlyArray<[number | readonly number[], any]>} keys [key value, shape] pairs, with one key value per
111
- * input. With several inputs every combination of key values must be given.
112
- * @returns {(t: number) => any}
113
- */
114
- export function keyform(inputs, keys) {
115
- const axes = Array.isArray(inputs) ? inputs : [inputs]
116
- const d = axes.length
117
- if (!Array.isArray(keys) || keys.length === 0) throw new TypeError('keyform: give a list of [key value, shape] pairs')
118
- const entries = keys.map(([coords, value], i) => {
119
- const c = typeof coords === 'number' ? [coords] : [...coords]
120
- if (c.length !== d || !c.every(Number.isFinite)) throw new TypeError(`keyform: key ${i} needs ${d} key value${d === 1 ? '' : 's'}, one per input`)
121
- return { c, value }
122
- })
123
- const axisValues = Array.from({ length: d }, (_, k) => [...new Set(entries.map(e => e.c[k]))].sort((p, q) => p - q))
124
- const strides = new Array(d)
125
- let size = 1
126
- for (let k = d - 1; k >= 0; k--) {
127
- strides[k] = size
128
- size *= axisValues[k].length
129
- }
130
- const grid = new Array(size)
131
- for (const { c, value } of entries) {
132
- const slot = c.reduce((sum, v, k) => sum + axisValues[k].indexOf(v) * strides[k], 0)
133
- if (grid[slot] !== undefined) throw new RangeError(`keyform: key ${c.join(', ')} is given twice`)
134
- grid[slot] = value
135
- }
136
- const missing = grid.length - entries.length
137
- if (missing > 0) throw new RangeError(`keyform: ${missing} key combination${missing === 1 ? ' is' : 's are'} missing; give a shape for every combination of key values`)
138
-
139
- return memo(t => {
140
- /** @type {number[]} */
141
- const cell = new Array(d)
142
- /** @type {number[]} */
143
- const frac = new Array(d)
144
- for (let k = 0; k < d; k++) {
145
- const values = axisValues[k]
146
- const x = at(axes[k], t)
147
- const last = values.length - 1
148
- if (last === 0 || x <= values[0]) [cell[k], frac[k]] = [0, 0]
149
- else if (x >= values[last]) [cell[k], frac[k]] = [last - 1, 1]
150
- else {
151
- let i = 0
152
- while (values[i + 1] <= x) i++
153
- cell[k] = i
154
- frac[k] = (x - values[i]) / (values[i + 1] - values[i])
155
- }
156
- }
157
- const shapes = []
158
- const weights = []
159
- for (let corner = 0; corner < 1 << d; corner++) {
160
- let w = 1
161
- let slot = 0
162
- for (let k = 0; k < d; k++) {
163
- const up = (corner >> k) & 1
164
- w *= up ? frac[k] : 1 - frac[k]
165
- slot += (cell[k] + up) * strides[k]
166
- }
167
- if (w === 0) continue
168
- shapes.push(grid[slot])
169
- weights.push(w)
170
- }
171
- return shapes.length === 1 ? shapes[0] : combine(shapes, weights, 'keyform')
172
- })
173
- }
174
-
175
- /**
176
- * Blend shapes, or morph targets: the base plus each target's difference from it times its weight. Weights may go
177
- * past 1 or below 0 to exaggerate.
178
- * @param {Value<any>} base
179
- * @param {ReadonlyArray<[Value<any>, Value<number>]>} targets [shape, weight] pairs.
180
- * @returns {(t: number) => any}
181
- */
182
- export function blendShapes(base, targets) {
183
- return memo(t => {
184
- const shapes = [at(base, t)]
185
- const weights = [1]
186
- for (const [target, weight] of targets) {
187
- const w = at(weight, t)
188
- if (w === 0) continue
189
- shapes.push(at(target, t))
190
- weights.push(w)
191
- weights[0] -= w
192
- }
193
- return shapes.length === 1 ? shapes[0] : combine(shapes, weights, 'blendShapes')
194
- })
195
- }
196
-
197
- /** @type {WeakMap<Path, { size: number, curves: Path, slots: Int32Array }>} */
198
- const curveCache = new WeakMap()
199
-
200
- /**
201
- * The path as moves, lines and cubics, with the index of every point's x in its data.
202
- * @param {Path} path
203
- */
204
- function pointsOf(path) {
205
- const hit = curveCache.get(path)
206
- if (hit && hit.size === path.data.length) return hit
207
- const curves = toCurves(path)
208
- /** @type {number[]} */
209
- const slots = []
210
- const d = curves.data
211
- for (let i = 0; i < d.length; i += 1 + ARGS[d[i]]) {
212
- if (d[i] === MOVE || d[i] === LINE) slots.push(i + 1)
213
- else if (d[i] === CUBIC) slots.push(i + 1, i + 3, i + 5)
214
- else if (d[i] !== CLOSE) throw new TypeError('deform: toCurves left a command that is not a move, line, cubic or close')
215
- }
216
- const result = { size: path.data.length, curves, slots: Int32Array.from(slots) }
217
- curveCache.set(path, result)
218
- return result
219
- }
220
-
221
- /**
222
- * Moves every point of a path, or of a flat [x0, y0, x1, y1, ...] list, through fn.
223
- * @param {Path | readonly number[]} source
224
- * @param {(x: number, y: number, k: number) => readonly number[]} fn k counts points from 0.
225
- * @returns {Path | number[]}
226
- */
227
- function movePoints(source, fn) {
228
- if (source instanceof Path) {
229
- const { curves, slots } = pointsOf(source)
230
- const data = curves.data.slice()
231
- for (let k = 0; k < slots.length; k++) {
232
- const j = slots[k]
233
- const [x, y] = fn(data[j], data[j + 1], k)
234
- data[j] = x
235
- data[j + 1] = y
236
- }
237
- const out = new Path()
238
- out.data = data
239
- return out
240
- }
241
- if (!Array.isArray(source) && !ArrayBuffer.isView(source)) throw new TypeError('deform: the shape must be a path or a flat list of x, y numbers')
242
- const out = new Array(source.length)
243
- for (let j = 0, k = 0; j < source.length; j += 2, k++) {
244
- const [x, y] = fn(source[j], source[j + 1], k)
245
- out[j] = x
246
- out[j + 1] = y
247
- }
248
- return out
249
- }
250
-
251
- /**
252
- * @typedef {object} Lattice
253
- * @property {readonly [number, number, number, number]} box x, y, w, h of the area the lattice covers at rest.
254
- * @property {number} columns Cells across.
255
- * @property {number} rows Cells down.
256
- * @property {readonly number[]} rest The (columns + 1) * (rows + 1) points at rest, row by row, as x, y pairs.
257
- * @property {(fn: (x: number, y: number, u: number, v: number) => readonly number[]) => number[]} map A moved copy of
258
- * the rest points; u and v run 0..1 across and down the box.
259
- */
260
-
261
- /**
262
- * A lattice for warp(): a grid of points over a box, like a Live2D warp deformer or a free-form deformer.
263
- * @param {{ box: readonly [number, number, number, number], columns?: number, rows?: number }} options columns and
264
- * rows (cells, default 2) set how finely the warp can bend.
265
- * @returns {Lattice}
266
- */
267
- export function lattice({ box, columns = 2, rows = 2 }) {
268
- if (!Array.isArray(box) || box.length !== 4 || !(box[2] > 0) || !(box[3] > 0)) throw new TypeError('lattice: box must be [x, y, w, h] with w and h above 0')
269
- if (!(Number.isInteger(columns) && columns > 0 && Number.isInteger(rows) && rows > 0)) throw new RangeError('lattice: columns and rows must be whole numbers above 0')
270
- const [bx, by, bw, bh] = box
271
- /** @type {number[]} */
272
- const rest = []
273
- for (let j = 0; j <= rows; j++) for (let i = 0; i <= columns; i++) rest.push(bx + (bw * i) / columns, by + (bh * j) / rows)
274
- return Object.freeze({
275
- box: /** @type {readonly [number, number, number, number]} */ (Object.freeze([bx, by, bw, bh])),
276
- columns,
277
- rows,
278
- rest: Object.freeze(rest),
279
- map(fn) {
280
- /** @type {number[]} */
281
- const out = []
282
- for (let j = 0; j <= rows; j++) {
283
- for (let i = 0; i <= columns; i++) {
284
- const [x, y] = fn(rest[2 * (j * (columns + 1) + i)], rest[2 * (j * (columns + 1) + i) + 1], i / columns, j / rows)
285
- out.push(x, y)
286
- }
287
- }
288
- return out
289
- },
290
- })
291
- }
292
-
293
- /**
294
- * A grid of triangles over a box, for a mesh node: the points to move, the image places they show, and the
295
- * triangles. points is a plain [x, y, ...] list, so warp() and skin() bend it like any shape.
296
- * @param {{ box: readonly [number, number, number, number], columns?: number, rows?: number,
297
- * crop?: readonly [number, number, number, number] }} options box is x, y, w, h in node space; columns and rows are
298
- * cells (default 8 each); crop is the part of the image shown, in image px, and defaults to the box itself, which
299
- * suits an image drawn at its own size from the node's origin.
300
- */
301
- export function gridMesh({ box, columns = 8, rows = 8, crop = box }) {
302
- if (!Array.isArray(box) || box.length !== 4 || !(box[2] > 0) || !(box[3] > 0)) throw new TypeError('gridMesh: box must be [x, y, w, h] with w and h above 0')
303
- if (!Array.isArray(crop) || crop.length !== 4) throw new TypeError('gridMesh: crop must be [x, y, w, h] in image px')
304
- if (!(Number.isInteger(columns) && columns > 0 && Number.isInteger(rows) && rows > 0)) throw new RangeError('gridMesh: columns and rows must be whole numbers above 0')
305
- const [bx, by, bw, bh] = box
306
- const [cx, cy, cw, ch] = crop
307
- /** @type {number[]} */
308
- const points = []
309
- /** @type {number[]} */
310
- const uvs = []
311
- for (let j = 0; j <= rows; j++) {
312
- for (let i = 0; i <= columns; i++) {
313
- points.push(bx + (bw * i) / columns, by + (bh * j) / rows)
314
- uvs.push(cx + (cw * i) / columns, cy + (ch * j) / rows)
315
- }
316
- }
317
- /** @type {number[]} */
318
- const triangles = []
319
- for (let j = 0; j < rows; j++) {
320
- for (let i = 0; i < columns; i++) {
321
- const a = j * (columns + 1) + i
322
- const c = a + columns + 1
323
- // Diagonals alternate like a checkerboard, so the mesh bends the same way to the left and to the right.
324
- if ((i + j) % 2 === 0) triangles.push(a, a + 1, c + 1, a, c + 1, c)
325
- else triangles.push(a, a + 1, c, a + 1, c + 1, c)
326
- }
327
- }
328
- return Object.freeze({ points: Object.freeze(points), uvs: Object.freeze(uvs), triangles: Object.freeze(triangles) })
329
- }
330
-
331
- /**
332
- * Warps a shape through a lattice: each point keeps its place within its cell while the cell's corners move to
333
- * `points`. Points outside the box follow the nearest edge cells.
334
- * @param {Value<Path | readonly number[]>} source
335
- * @param {Lattice} grid
336
- * @param {Value<readonly number[]>} points The lattice's points now, as from grid.map() or a keyform of such lists.
337
- * @returns {(t: number) => any}
338
- */
339
- export function warp(source, grid, points) {
340
- const { columns, rows } = grid
341
- const [bx, by, bw, bh] = grid.box
342
- const across = columns + 1
343
- return memo(t => {
344
- const p = at(points, t)
345
- if (p.length !== grid.rest.length) throw new RangeError(`warp: the lattice has ${grid.rest.length / 2} points, got ${p.length / 2}`)
346
- return movePoints(at(source, t), (x, y) => {
347
- const u = ((x - bx) / bw) * columns
348
- const v = ((y - by) / bh) * rows
349
- const i = Math.min(Math.max(Math.floor(u), 0), columns - 1)
350
- const j = Math.min(Math.max(Math.floor(v), 0), rows - 1)
351
- const fu = u - i
352
- const fv = v - j
353
- const a = 2 * (j * across + i)
354
- const b = a + 2
355
- const c = a + 2 * across
356
- const d = c + 2
357
- const w00 = (1 - fu) * (1 - fv)
358
- const w10 = fu * (1 - fv)
359
- const w01 = (1 - fu) * fv
360
- const w11 = fu * fv
361
- return [w00 * p[a] + w10 * p[b] + w01 * p[c] + w11 * p[d], w00 * p[a + 1] + w10 * p[b + 1] + w01 * p[c + 1] + w11 * p[d + 1]]
362
- })
363
- })
364
- }
365
-
366
- /**
367
- * Skinning: bends a shape drawn in the rig's rest pose with the rig's bones. Each point follows the bones near it,
368
- * weighted by distance to each bone's segment at `bindAt`, so joints bend smoothly instead of breaking.
369
- * @param {Path | readonly number[]} source The shape in rig space, as it sits in the pose at `bindAt`.
370
- * @param {import('./rig.js').Rig} r
371
- * @param {{ bones?: readonly string[], bindAt?: number, falloff?: number }} [options] bones defaults to every bone,
372
- * bindAt to 0, and falloff (px) sets how far a bone's pull reaches before its neighbours take over (default 30).
373
- * @returns {(t: number) => any}
374
- */
375
- export function skin(source, r, { bones = r.bones, bindAt = 0, falloff = 30 } = {}) {
376
- if (!(falloff > 0)) throw new RangeError(`skin: falloff must be above 0, got ${falloff}`)
377
- const matrices = bones.map(name => r.matrix(name))
378
- /** @type {{ inverse: number[][], weights: { bone: number, w: number }[][] } | null} */
379
- let bound = null
380
-
381
- const bind = () => {
382
- const inverse = matrices.map(m => invert(m(bindAt)))
383
- const segments = bones.map(name => [...r.point(name)(bindAt), ...r.tip(name)(bindAt)])
384
- /** @type {{ bone: number, w: number }[][]} */
385
- const weights = []
386
- movePoints(source, (x, y) => {
387
- const distances = segments.map(([x0, y0, x1, y1]) => segmentDistance(x, y, x0, y0, x1, y1))
388
- let list = distances.map((dist, bone) => ({ bone, w: Math.exp(-((dist / falloff) ** 2)) })).filter(e => e.w > 1e-4)
389
- if (list.length === 0) list = [{ bone: distances.indexOf(Math.min(...distances)), w: 1 }]
390
- const total = list.reduce((sum, e) => sum + e.w, 0)
391
- weights.push(list.map(e => ({ bone: e.bone, w: e.w / total })))
392
- return [x, y]
393
- })
394
- return { inverse, weights }
395
- }
396
-
397
- return memo(t => {
398
- bound ??= bind()
399
- const { inverse, weights } = bound
400
- const moves = matrices.map((m, i) => multiply(m(t), inverse[i]))
401
- return movePoints(source, (x, y, k) => {
402
- let nx = 0
403
- let ny = 0
404
- for (const { bone, w } of weights[k]) {
405
- const M = moves[bone]
406
- nx += w * (M[0] * x + M[2] * y + M[4])
407
- ny += w * (M[1] * x + M[3] * y + M[5])
408
- }
409
- return [nx, ny]
410
- })
411
- })
412
- }
413
-
414
- /** @param {number} px @param {number} py @param {number} x0 @param {number} y0 @param {number} x1 @param {number} y1 */
415
- function segmentDistance(px, py, x0, y0, x1, y1) {
416
- const dx = x1 - x0
417
- const dy = y1 - y0
418
- const length2 = dx * dx + dy * dy
419
- const k = length2 === 0 ? 0 : Math.min(1, Math.max(0, ((px - x0) * dx + (py - y0) * dy) / length2))
420
- return Math.hypot(px - (x0 + k * dx), py - (y0 + k * dy))
421
- }
422
-
423
- /** @param {readonly number[]} m @returns {number[]} */
424
- function invert(m) {
425
- const [a, b, c, d, e, f] = m
426
- const det = a * d - b * c
427
- if (det === 0) throw new RangeError('skin: a bone is scaled to nothing in the bind pose, so points cannot be bound to it')
428
- return [d / det, -b / det, -c / det, a / det, (c * f - d * e) / det, (b * e - a * f) / det]
429
- }
430
-
431
- /** @param {readonly number[]} p @param {readonly number[]} q @returns {number[]} */
432
- function multiply(p, q) {
433
- return [
434
- p[0] * q[0] + p[2] * q[1],
435
- p[1] * q[0] + p[3] * q[1],
436
- p[0] * q[2] + p[2] * q[3],
437
- p[1] * q[2] + p[3] * q[3],
438
- p[0] * q[4] + p[2] * q[5] + p[4],
439
- p[1] * q[4] + p[3] * q[5] + p[5],
440
- ]
441
- }
1
+ // Shape deformers for vector art: keyforms that interpolate shapes over params as Live2D does, blend shapes, lattice
2
+ // warps, and skinning that bends paths with rig bones. Paths move by their points, so they stay sharp at any size.
3
+ import { at } from '../core/math.js'
4
+ import { Path, MOVE, LINE, CUBIC, CLOSE, ARGS } from '../core/path.js'
5
+ import { toCurves } from './path.js'
6
+
7
+ /**
8
+ * @template T
9
+ * @typedef {import('../core/math.js').Value<T>} Value
10
+ */
11
+
12
+ /**
13
+ * What keyforms, blend shapes and the shape track type interpolate: numbers, arrays of numbers, paths with the same
14
+ * commands in the same order, or plain objects of these.
15
+ * @typedef {number | readonly number[] | Path | { [key: string]: Shape }} Shape
16
+ */
17
+
18
+ /**
19
+ * Sums shapes scaled by weights. Weights here always add up to 1, so path opcodes are copied, not summed.
20
+ * @param {readonly any[]} values
21
+ * @param {readonly number[]} weights
22
+ * @param {string} where
23
+ * @returns {any}
24
+ */
25
+ function combine(values, weights, where) {
26
+ const first = values[0]
27
+ if (typeof first === 'number') {
28
+ let sum = 0
29
+ for (let i = 0; i < values.length; i++) sum += weights[i] * values[i]
30
+ return sum
31
+ }
32
+ if (first instanceof Path) {
33
+ const d0 = first.data
34
+ for (const v of values) {
35
+ if (!(v instanceof Path) || v.data.length !== d0.length) {
36
+ throw new TypeError(`${where}: paths must have the same commands in the same order to blend`)
37
+ }
38
+ }
39
+ const data = new Array(d0.length)
40
+ for (let j = 0; j < d0.length; j += 1 + ARGS[d0[j]]) {
41
+ data[j] = d0[j]
42
+ for (const v of values) if (v.data[j] !== d0[j]) throw new TypeError(`${where}: paths must have the same commands in the same order to blend`)
43
+ for (let a = j + 1; a <= j + ARGS[d0[j]]; a++) {
44
+ let sum = 0
45
+ for (let i = 0; i < values.length; i++) sum += weights[i] * values[i].data[a]
46
+ data[a] = sum
47
+ }
48
+ }
49
+ const out = new Path()
50
+ out.data = data
51
+ return out
52
+ }
53
+ if (Array.isArray(first) || ArrayBuffer.isView(first)) {
54
+ const n = /** @type {ArrayLike<number>} */ (first).length
55
+ for (const v of values) if (v.length !== n) throw new TypeError(`${where}: arrays of length ${n} and ${v.length} cannot blend`)
56
+ const out = new Array(n)
57
+ for (let j = 0; j < n; j++) {
58
+ let sum = 0
59
+ for (let i = 0; i < values.length; i++) sum += weights[i] * values[i][j]
60
+ out[j] = sum
61
+ }
62
+ return out
63
+ }
64
+ if (first !== null && typeof first === 'object') {
65
+ /** @type {Record<string, any>} */
66
+ const out = {}
67
+ for (const key of Object.keys(first)) {
68
+ out[key] = combine(values.map(v => {
69
+ if (v === null || typeof v !== 'object' || !(key in v)) throw new TypeError(`${where}: every shape must have "${key}"`)
70
+ return v[key]
71
+ }), weights, where)
72
+ }
73
+ return out
74
+ }
75
+ throw new TypeError(`${where}: can only blend numbers, arrays of numbers, paths and objects of these, got ${typeof first}`)
76
+ }
77
+
78
+ /**
79
+ * Keeps the last result, for Values that several props read at the same time.
80
+ * @template T
81
+ * @param {(t: number) => T} fn
82
+ * @returns {(t: number) => T}
83
+ */
84
+ function memo(fn) {
85
+ let lastT = NaN
86
+ /** @type {T} */
87
+ let last
88
+ return t => {
89
+ if (t !== lastT) {
90
+ last = fn(t)
91
+ lastT = t
92
+ }
93
+ return last
94
+ }
95
+ }
96
+
97
+ /**
98
+ * A track type for shapes: track(keys, { type: shapeType }) tweens paths point by point, or whole objects of numbers
99
+ * and paths, so a shape can morph between drawings with the same commands.
100
+ * @type {import('../core/track.js').ValueType<any>}
101
+ */
102
+ export const shapeType = Object.freeze({
103
+ mix: (/** @type {any} */ a, /** @type {any} */ b, /** @type {number} */ k) => combine([a, b], [1 - k, k], 'shapeType'),
104
+ })
105
+
106
+ /**
107
+ * A keyform: shapes stored at key values of one or more inputs, such as Live2D's AngleX and AngleY params, blended
108
+ * linearly across the grid of keys for the inputs' current values. Inputs past the outer keys hold the edge shape.
109
+ * @param {Value<number> | ReadonlyArray<Value<number>>} inputs One input, or one per grid axis.
110
+ * @param {ReadonlyArray<[number | readonly number[], any]>} keys [key value, shape] pairs, with one key value per
111
+ * input. With several inputs every combination of key values must be given.
112
+ * @returns {(t: number) => any}
113
+ */
114
+ export function keyform(inputs, keys) {
115
+ const axes = Array.isArray(inputs) ? inputs : [inputs]
116
+ const d = axes.length
117
+ if (!Array.isArray(keys) || keys.length === 0) throw new TypeError('keyform: give a list of [key value, shape] pairs')
118
+ const entries = keys.map(([coords, value], i) => {
119
+ const c = typeof coords === 'number' ? [coords] : [...coords]
120
+ if (c.length !== d || !c.every(Number.isFinite)) throw new TypeError(`keyform: key ${i} needs ${d} key value${d === 1 ? '' : 's'}, one per input`)
121
+ return { c, value }
122
+ })
123
+ const axisValues = Array.from({ length: d }, (_, k) => [...new Set(entries.map(e => e.c[k]))].sort((p, q) => p - q))
124
+ const strides = new Array(d)
125
+ let size = 1
126
+ for (let k = d - 1; k >= 0; k--) {
127
+ strides[k] = size
128
+ size *= axisValues[k].length
129
+ }
130
+ const grid = new Array(size)
131
+ for (const { c, value } of entries) {
132
+ const slot = c.reduce((sum, v, k) => sum + axisValues[k].indexOf(v) * strides[k], 0)
133
+ if (grid[slot] !== undefined) throw new RangeError(`keyform: key ${c.join(', ')} is given twice`)
134
+ grid[slot] = value
135
+ }
136
+ const missing = grid.length - entries.length
137
+ if (missing > 0) throw new RangeError(`keyform: ${missing} key combination${missing === 1 ? ' is' : 's are'} missing; give a shape for every combination of key values`)
138
+
139
+ return memo(t => {
140
+ /** @type {number[]} */
141
+ const cell = new Array(d)
142
+ /** @type {number[]} */
143
+ const frac = new Array(d)
144
+ for (let k = 0; k < d; k++) {
145
+ const values = axisValues[k]
146
+ const x = at(axes[k], t)
147
+ const last = values.length - 1
148
+ if (last === 0 || x <= values[0]) [cell[k], frac[k]] = [0, 0]
149
+ else if (x >= values[last]) [cell[k], frac[k]] = [last - 1, 1]
150
+ else {
151
+ let i = 0
152
+ while (values[i + 1] <= x) i++
153
+ cell[k] = i
154
+ frac[k] = (x - values[i]) / (values[i + 1] - values[i])
155
+ }
156
+ }
157
+ const shapes = []
158
+ const weights = []
159
+ for (let corner = 0; corner < 1 << d; corner++) {
160
+ let w = 1
161
+ let slot = 0
162
+ for (let k = 0; k < d; k++) {
163
+ const up = (corner >> k) & 1
164
+ w *= up ? frac[k] : 1 - frac[k]
165
+ slot += (cell[k] + up) * strides[k]
166
+ }
167
+ if (w === 0) continue
168
+ shapes.push(grid[slot])
169
+ weights.push(w)
170
+ }
171
+ return shapes.length === 1 ? shapes[0] : combine(shapes, weights, 'keyform')
172
+ })
173
+ }
174
+
175
+ /**
176
+ * Blend shapes, or morph targets: the base plus each target's difference from it times its weight. Weights may go
177
+ * past 1 or below 0 to exaggerate.
178
+ * @param {Value<any>} base
179
+ * @param {ReadonlyArray<[Value<any>, Value<number>]>} targets [shape, weight] pairs.
180
+ * @returns {(t: number) => any}
181
+ */
182
+ export function blendShapes(base, targets) {
183
+ return memo(t => {
184
+ const shapes = [at(base, t)]
185
+ const weights = [1]
186
+ for (const [target, weight] of targets) {
187
+ const w = at(weight, t)
188
+ if (w === 0) continue
189
+ shapes.push(at(target, t))
190
+ weights.push(w)
191
+ weights[0] -= w
192
+ }
193
+ return shapes.length === 1 ? shapes[0] : combine(shapes, weights, 'blendShapes')
194
+ })
195
+ }
196
+
197
+ /** @type {WeakMap<Path, { size: number, curves: Path, slots: Int32Array }>} */
198
+ const curveCache = new WeakMap()
199
+
200
+ /**
201
+ * The path as moves, lines and cubics, with the index of every point's x in its data.
202
+ * @param {Path} path
203
+ */
204
+ function pointsOf(path) {
205
+ const hit = curveCache.get(path)
206
+ if (hit && hit.size === path.data.length) return hit
207
+ const curves = toCurves(path)
208
+ /** @type {number[]} */
209
+ const slots = []
210
+ const d = curves.data
211
+ for (let i = 0; i < d.length; i += 1 + ARGS[d[i]]) {
212
+ if (d[i] === MOVE || d[i] === LINE) slots.push(i + 1)
213
+ else if (d[i] === CUBIC) slots.push(i + 1, i + 3, i + 5)
214
+ else if (d[i] !== CLOSE) throw new TypeError('deform: toCurves left a command that is not a move, line, cubic or close')
215
+ }
216
+ const result = { size: path.data.length, curves, slots: Int32Array.from(slots) }
217
+ curveCache.set(path, result)
218
+ return result
219
+ }
220
+
221
+ /**
222
+ * Moves every point of a path, or of a flat [x0, y0, x1, y1, ...] list, through fn.
223
+ * @param {Path | readonly number[]} source
224
+ * @param {(x: number, y: number, k: number) => readonly number[]} fn k counts points from 0.
225
+ * @returns {Path | number[]}
226
+ */
227
+ function movePoints(source, fn) {
228
+ if (source instanceof Path) {
229
+ const { curves, slots } = pointsOf(source)
230
+ const data = curves.data.slice()
231
+ for (let k = 0; k < slots.length; k++) {
232
+ const j = slots[k]
233
+ const [x, y] = fn(data[j], data[j + 1], k)
234
+ data[j] = x
235
+ data[j + 1] = y
236
+ }
237
+ const out = new Path()
238
+ out.data = data
239
+ return out
240
+ }
241
+ if (!Array.isArray(source) && !ArrayBuffer.isView(source)) throw new TypeError('deform: the shape must be a path or a flat list of x, y numbers')
242
+ const out = new Array(source.length)
243
+ for (let j = 0, k = 0; j < source.length; j += 2, k++) {
244
+ const [x, y] = fn(source[j], source[j + 1], k)
245
+ out[j] = x
246
+ out[j + 1] = y
247
+ }
248
+ return out
249
+ }
250
+
251
+ /**
252
+ * @typedef {object} Lattice
253
+ * @property {readonly [number, number, number, number]} box x, y, w, h of the area the lattice covers at rest.
254
+ * @property {number} columns Cells across.
255
+ * @property {number} rows Cells down.
256
+ * @property {readonly number[]} rest The (columns + 1) * (rows + 1) points at rest, row by row, as x, y pairs.
257
+ * @property {(fn: (x: number, y: number, u: number, v: number) => readonly number[]) => number[]} map A moved copy of
258
+ * the rest points; u and v run 0..1 across and down the box.
259
+ */
260
+
261
+ /**
262
+ * A lattice for warp(): a grid of points over a box, like a Live2D warp deformer or a free-form deformer.
263
+ * @param {{ box: readonly [number, number, number, number], columns?: number, rows?: number }} options columns and
264
+ * rows (cells, default 2) set how finely the warp can bend.
265
+ * @returns {Lattice}
266
+ */
267
+ export function lattice({ box, columns = 2, rows = 2 }) {
268
+ if (!Array.isArray(box) || box.length !== 4 || !(box[2] > 0) || !(box[3] > 0)) throw new TypeError('lattice: box must be [x, y, w, h] with w and h above 0')
269
+ if (!(Number.isInteger(columns) && columns > 0 && Number.isInteger(rows) && rows > 0)) throw new RangeError('lattice: columns and rows must be whole numbers above 0')
270
+ const [bx, by, bw, bh] = box
271
+ /** @type {number[]} */
272
+ const rest = []
273
+ for (let j = 0; j <= rows; j++) for (let i = 0; i <= columns; i++) rest.push(bx + (bw * i) / columns, by + (bh * j) / rows)
274
+ return Object.freeze({
275
+ box: /** @type {readonly [number, number, number, number]} */ (Object.freeze([bx, by, bw, bh])),
276
+ columns,
277
+ rows,
278
+ rest: Object.freeze(rest),
279
+ map(fn) {
280
+ /** @type {number[]} */
281
+ const out = []
282
+ for (let j = 0; j <= rows; j++) {
283
+ for (let i = 0; i <= columns; i++) {
284
+ const [x, y] = fn(rest[2 * (j * (columns + 1) + i)], rest[2 * (j * (columns + 1) + i) + 1], i / columns, j / rows)
285
+ out.push(x, y)
286
+ }
287
+ }
288
+ return out
289
+ },
290
+ })
291
+ }
292
+
293
+ /**
294
+ * A grid of triangles over a box, for a mesh node: the points to move, the image places they show, and the
295
+ * triangles. points is a plain [x, y, ...] list, so warp() and skin() bend it like any shape.
296
+ * @param {{ box: readonly [number, number, number, number], columns?: number, rows?: number,
297
+ * crop?: readonly [number, number, number, number] }} options box is x, y, w, h in node space; columns and rows are
298
+ * cells (default 8 each); crop is the part of the image shown, in image px, and defaults to the box itself, which
299
+ * suits an image drawn at its own size from the node's origin.
300
+ */
301
+ export function gridMesh({ box, columns = 8, rows = 8, crop = box }) {
302
+ if (!Array.isArray(box) || box.length !== 4 || !(box[2] > 0) || !(box[3] > 0)) throw new TypeError('gridMesh: box must be [x, y, w, h] with w and h above 0')
303
+ if (!Array.isArray(crop) || crop.length !== 4) throw new TypeError('gridMesh: crop must be [x, y, w, h] in image px')
304
+ if (!(Number.isInteger(columns) && columns > 0 && Number.isInteger(rows) && rows > 0)) throw new RangeError('gridMesh: columns and rows must be whole numbers above 0')
305
+ const [bx, by, bw, bh] = box
306
+ const [cx, cy, cw, ch] = crop
307
+ /** @type {number[]} */
308
+ const points = []
309
+ /** @type {number[]} */
310
+ const uvs = []
311
+ for (let j = 0; j <= rows; j++) {
312
+ for (let i = 0; i <= columns; i++) {
313
+ points.push(bx + (bw * i) / columns, by + (bh * j) / rows)
314
+ uvs.push(cx + (cw * i) / columns, cy + (ch * j) / rows)
315
+ }
316
+ }
317
+ /** @type {number[]} */
318
+ const triangles = []
319
+ for (let j = 0; j < rows; j++) {
320
+ for (let i = 0; i < columns; i++) {
321
+ const a = j * (columns + 1) + i
322
+ const c = a + columns + 1
323
+ // Diagonals alternate like a checkerboard, so the mesh bends the same way to the left and to the right.
324
+ if ((i + j) % 2 === 0) triangles.push(a, a + 1, c + 1, a, c + 1, c)
325
+ else triangles.push(a, a + 1, c, a + 1, c + 1, c)
326
+ }
327
+ }
328
+ return Object.freeze({ points: Object.freeze(points), uvs: Object.freeze(uvs), triangles: Object.freeze(triangles) })
329
+ }
330
+
331
+ /**
332
+ * Warps a shape through a lattice: each point keeps its place within its cell while the cell's corners move to
333
+ * `points`. Points outside the box follow the nearest edge cells.
334
+ * @param {Value<Path | readonly number[]>} source
335
+ * @param {Lattice} grid
336
+ * @param {Value<readonly number[]>} points The lattice's points now, as from grid.map() or a keyform of such lists.
337
+ * @returns {(t: number) => any}
338
+ */
339
+ export function warp(source, grid, points) {
340
+ const { columns, rows } = grid
341
+ const [bx, by, bw, bh] = grid.box
342
+ const across = columns + 1
343
+ return memo(t => {
344
+ const p = at(points, t)
345
+ if (p.length !== grid.rest.length) throw new RangeError(`warp: the lattice has ${grid.rest.length / 2} points, got ${p.length / 2}`)
346
+ return movePoints(at(source, t), (x, y) => {
347
+ const u = ((x - bx) / bw) * columns
348
+ const v = ((y - by) / bh) * rows
349
+ const i = Math.min(Math.max(Math.floor(u), 0), columns - 1)
350
+ const j = Math.min(Math.max(Math.floor(v), 0), rows - 1)
351
+ const fu = u - i
352
+ const fv = v - j
353
+ const a = 2 * (j * across + i)
354
+ const b = a + 2
355
+ const c = a + 2 * across
356
+ const d = c + 2
357
+ const w00 = (1 - fu) * (1 - fv)
358
+ const w10 = fu * (1 - fv)
359
+ const w01 = (1 - fu) * fv
360
+ const w11 = fu * fv
361
+ return [w00 * p[a] + w10 * p[b] + w01 * p[c] + w11 * p[d], w00 * p[a + 1] + w10 * p[b + 1] + w01 * p[c + 1] + w11 * p[d + 1]]
362
+ })
363
+ })
364
+ }
365
+
366
+ /**
367
+ * Skinning: bends a shape drawn in the rig's rest pose with the rig's bones. Each point follows the bones near it,
368
+ * weighted by distance to each bone's segment at `bindAt`, so joints bend smoothly instead of breaking.
369
+ * @param {Path | readonly number[]} source The shape in rig space, as it sits in the pose at `bindAt`.
370
+ * @param {import('./rig.js').Rig} r
371
+ * @param {{ bones?: readonly string[], bindAt?: number, falloff?: number }} [options] bones defaults to every bone,
372
+ * bindAt to 0, and falloff (px) sets how far a bone's pull reaches before its neighbours take over (default 30).
373
+ * @returns {(t: number) => any}
374
+ */
375
+ export function skin(source, r, { bones = r.bones, bindAt = 0, falloff = 30 } = {}) {
376
+ if (!(falloff > 0)) throw new RangeError(`skin: falloff must be above 0, got ${falloff}`)
377
+ const matrices = bones.map(name => r.matrix(name))
378
+ /** @type {{ inverse: number[][], weights: { bone: number, w: number }[][] } | null} */
379
+ let bound = null
380
+
381
+ const bind = () => {
382
+ const inverse = matrices.map(m => invert(m(bindAt)))
383
+ const segments = bones.map(name => [...r.point(name)(bindAt), ...r.tip(name)(bindAt)])
384
+ /** @type {{ bone: number, w: number }[][]} */
385
+ const weights = []
386
+ movePoints(source, (x, y) => {
387
+ const distances = segments.map(([x0, y0, x1, y1]) => segmentDistance(x, y, x0, y0, x1, y1))
388
+ let list = distances.map((dist, bone) => ({ bone, w: Math.exp(-((dist / falloff) ** 2)) })).filter(e => e.w > 1e-4)
389
+ if (list.length === 0) list = [{ bone: distances.indexOf(Math.min(...distances)), w: 1 }]
390
+ const total = list.reduce((sum, e) => sum + e.w, 0)
391
+ weights.push(list.map(e => ({ bone: e.bone, w: e.w / total })))
392
+ return [x, y]
393
+ })
394
+ return { inverse, weights }
395
+ }
396
+
397
+ return memo(t => {
398
+ bound ??= bind()
399
+ const { inverse, weights } = bound
400
+ const moves = matrices.map((m, i) => multiply(m(t), inverse[i]))
401
+ return movePoints(source, (x, y, k) => {
402
+ let nx = 0
403
+ let ny = 0
404
+ for (const { bone, w } of weights[k]) {
405
+ const M = moves[bone]
406
+ nx += w * (M[0] * x + M[2] * y + M[4])
407
+ ny += w * (M[1] * x + M[3] * y + M[5])
408
+ }
409
+ return [nx, ny]
410
+ })
411
+ })
412
+ }
413
+
414
+ /** @param {number} px @param {number} py @param {number} x0 @param {number} y0 @param {number} x1 @param {number} y1 */
415
+ function segmentDistance(px, py, x0, y0, x1, y1) {
416
+ const dx = x1 - x0
417
+ const dy = y1 - y0
418
+ const length2 = dx * dx + dy * dy
419
+ const k = length2 === 0 ? 0 : Math.min(1, Math.max(0, ((px - x0) * dx + (py - y0) * dy) / length2))
420
+ return Math.hypot(px - (x0 + k * dx), py - (y0 + k * dy))
421
+ }
422
+
423
+ /** @param {readonly number[]} m @returns {number[]} */
424
+ function invert(m) {
425
+ const [a, b, c, d, e, f] = m
426
+ const det = a * d - b * c
427
+ if (det === 0) throw new RangeError('skin: a bone is scaled to nothing in the bind pose, so points cannot be bound to it')
428
+ return [d / det, -b / det, -c / det, a / det, (c * f - d * e) / det, (b * e - a * f) / det]
429
+ }
430
+
431
+ /** @param {readonly number[]} p @param {readonly number[]} q @returns {number[]} */
432
+ function multiply(p, q) {
433
+ return [
434
+ p[0] * q[0] + p[2] * q[1],
435
+ p[1] * q[0] + p[3] * q[1],
436
+ p[0] * q[2] + p[2] * q[3],
437
+ p[1] * q[2] + p[3] * q[3],
438
+ p[0] * q[4] + p[2] * q[5] + p[4],
439
+ p[1] * q[4] + p[3] * q[5] + p[5],
440
+ ]
441
+ }