@ikijs/mcp 0.23.1 → 0.24.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.
@@ -0,0 +1,1250 @@
1
+ "use strict";
2
+ (() => {
3
+ // ../engine/src/math.ts
4
+ function clamp(value, min, max) {
5
+ return Math.max(min, Math.min(max, value));
6
+ }
7
+ function lerp(a, b, t) {
8
+ return a + (b - a) * t;
9
+ }
10
+
11
+ // ../engine/src/parameter-store.ts
12
+ var ParameterStore = class {
13
+ params = /* @__PURE__ */ new Map();
14
+ values = /* @__PURE__ */ new Map();
15
+ /**
16
+ * Resting value per id: the declared default clamped into range, resolved
17
+ * ONCE here so `reset()` is a straight copy and a malformed descriptor is
18
+ * reported once rather than on every reset.
19
+ */
20
+ defaults = /* @__PURE__ */ new Map();
21
+ constructor(parameters) {
22
+ for (const param of parameters) {
23
+ this.params.set(param.id, param);
24
+ if (!Number.isFinite(param.default)) {
25
+ console.error(
26
+ `Iki: parameter "${param.id}" has a non-finite default; resting at the neutral in-range value instead`
27
+ );
28
+ }
29
+ const base = Number.isFinite(param.default) ? param.default : 0;
30
+ this.defaults.set(param.id, clamp(base, param.min, param.max));
31
+ }
32
+ for (const [id, value] of this.defaults) this.values.set(id, value);
33
+ }
34
+ /**
35
+ * Set a parameter's value, clamped to its range. Unknown ids are ignored, as
36
+ * are non-finite values: this is the boundary a host drives with live signals,
37
+ * and `clamp` cannot filter NaN (`Math.max(min, Math.min(max, NaN))` is NaN),
38
+ * so one bad lip-sync/gaze frame would otherwise poison every binding that
39
+ * reads the parameter. A dropped write holds the last good pose.
40
+ */
41
+ set(id, value) {
42
+ const param = this.params.get(id);
43
+ if (!param) return;
44
+ if (!Number.isFinite(value)) return;
45
+ this.values.set(id, clamp(value, param.min, param.max));
46
+ }
47
+ /** Current value, or 0 if the id is unknown. */
48
+ get(id) {
49
+ return this.values.get(id) ?? 0;
50
+ }
51
+ /** Position of a parameter within its range, 0..1. */
52
+ normalized(id) {
53
+ const param = this.params.get(id);
54
+ if (!param || param.max === param.min) return 0;
55
+ return (this.get(id) - param.min) / (param.max - param.min);
56
+ }
57
+ /** Reset every parameter to its resting value (see `defaults`). */
58
+ reset() {
59
+ for (const [id, value] of this.defaults) this.values.set(id, value);
60
+ }
61
+ list() {
62
+ return [...this.params.values()];
63
+ }
64
+ };
65
+
66
+ // ../engine/src/affine.ts
67
+ function translate(tx, ty) {
68
+ return [1, 0, 0, 1, tx, ty];
69
+ }
70
+ function scale(sx, sy) {
71
+ return [sx, 0, 0, sy, 0, 0];
72
+ }
73
+ function rotate(degrees) {
74
+ const r = degrees * Math.PI / 180;
75
+ const c = Math.cos(r);
76
+ const s = Math.sin(r);
77
+ return [c, s, -s, c, 0, 0];
78
+ }
79
+ function multiply(a, b) {
80
+ return [
81
+ a[0] * b[0] + a[2] * b[1],
82
+ a[1] * b[0] + a[3] * b[1],
83
+ a[0] * b[2] + a[2] * b[3],
84
+ a[1] * b[2] + a[3] * b[3],
85
+ a[0] * b[4] + a[2] * b[5] + a[4],
86
+ a[1] * b[4] + a[3] * b[5] + a[5]
87
+ ];
88
+ }
89
+ function toMat3(a) {
90
+ return new Float32Array([a[0], a[1], 0, a[2], a[3], 0, a[4], a[5], 1]);
91
+ }
92
+
93
+ // ../engine/src/warp.ts
94
+ function accumulateKeyformOffsets(keyforms, value, out) {
95
+ const ks = keyforms;
96
+ if (value <= ks[0].value) {
97
+ const { offsets } = ks[0];
98
+ for (let i = 0; i < offsets.length; i++) {
99
+ out[i] += offsets[i];
100
+ }
101
+ } else if (value >= ks[ks.length - 1].value) {
102
+ const { offsets } = ks[ks.length - 1];
103
+ for (let i = 0; i < offsets.length; i++) {
104
+ out[i] += offsets[i];
105
+ }
106
+ } else {
107
+ let lo = ks[0];
108
+ let hi = ks[1];
109
+ for (let k = 1; k < ks.length - 1; k++) {
110
+ if (ks[k].value <= value) {
111
+ lo = ks[k];
112
+ hi = ks[k + 1];
113
+ }
114
+ }
115
+ const t = (value - lo.value) / (hi.value - lo.value);
116
+ const loOff = lo.offsets;
117
+ const hiOff = hi.offsets;
118
+ for (let i = 0; i < loOff.length; i++) {
119
+ out[i] += loOff[i] + (hiOff[i] - loOff[i]) * t;
120
+ }
121
+ }
122
+ }
123
+ function accumulate2DKeyformOffsets(valuesX, valuesY, keyforms2d, vx, vy, out) {
124
+ const lastX = valuesX.length - 1;
125
+ const lastY = valuesY.length - 1;
126
+ let ix;
127
+ let tx;
128
+ if (vx <= valuesX[0]) {
129
+ ix = 0;
130
+ tx = 0;
131
+ } else if (vx >= valuesX[lastX]) {
132
+ ix = lastX - 1;
133
+ tx = 1;
134
+ } else {
135
+ ix = 0;
136
+ for (let k = 0; k < lastX - 1; k++) {
137
+ if (valuesX[k + 1] <= vx) ix = k + 1;
138
+ }
139
+ tx = (vx - valuesX[ix]) / (valuesX[ix + 1] - valuesX[ix]);
140
+ }
141
+ let iy;
142
+ let ty;
143
+ if (vy <= valuesY[0]) {
144
+ iy = 0;
145
+ ty = 0;
146
+ } else if (vy >= valuesY[lastY]) {
147
+ iy = lastY - 1;
148
+ ty = 1;
149
+ } else {
150
+ iy = 0;
151
+ for (let k = 0; k < lastY - 1; k++) {
152
+ if (valuesY[k + 1] <= vy) iy = k + 1;
153
+ }
154
+ ty = (vy - valuesY[iy]) / (valuesY[iy + 1] - valuesY[iy]);
155
+ }
156
+ const W = valuesX.length;
157
+ const c00 = keyforms2d[iy * W + ix];
158
+ const c10 = keyforms2d[iy * W + ix + 1];
159
+ const c01 = keyforms2d[(iy + 1) * W + ix];
160
+ const c11 = keyforms2d[(iy + 1) * W + ix + 1];
161
+ const o00 = c00.offsets;
162
+ const o10 = c10.offsets;
163
+ const o01 = c01.offsets;
164
+ const o11 = c11.offsets;
165
+ for (let n = 0; n < o00.length; n++) {
166
+ const top = o00[n] + (o10[n] - o00[n]) * tx;
167
+ const bot = o01[n] + (o11[n] - o01[n]) * tx;
168
+ out[n] += top + (bot - top) * ty;
169
+ }
170
+ }
171
+ function applyWarps(rest, warps, params, out) {
172
+ out.set(rest);
173
+ if (!warps || warps.length === 0) return;
174
+ for (const warp of warps) {
175
+ accumulateKeyformOffsets(warp.keyforms, params.get(warp.parameter), out);
176
+ }
177
+ }
178
+
179
+ // ../engine/src/warp-grid.ts
180
+ function deformWarpGrid(d, params) {
181
+ const points = Float32Array.from(d.grid.points);
182
+ for (const warp of d.warps ?? []) {
183
+ accumulateKeyformOffsets(warp.keyforms, params.get(warp.parameter), points);
184
+ }
185
+ if (d.warp2d !== void 0) {
186
+ accumulate2DKeyformOffsets(
187
+ d.warp2d.valuesX,
188
+ d.warp2d.valuesY,
189
+ d.warp2d.keyforms2d,
190
+ params.get(d.warp2d.parameter),
191
+ params.get(d.warp2d.parameterY),
192
+ points
193
+ );
194
+ }
195
+ return points;
196
+ }
197
+ function transformGridPoints(points, affine) {
198
+ const out = new Float32Array(points.length);
199
+ for (let i = 0; i < points.length; i += 2) {
200
+ const x = points[i];
201
+ const y = points[i + 1];
202
+ out[i] = affine[0] * x + affine[2] * y + affine[4];
203
+ out[i + 1] = affine[1] * x + affine[3] * y + affine[5];
204
+ }
205
+ return out;
206
+ }
207
+ function bindPointToRestGrid(x, y, restGrid) {
208
+ const { cols, rows, points } = restGrid;
209
+ const stride = cols + 1;
210
+ let col = cols - 1;
211
+ for (let c = 0; c < cols; c++) {
212
+ const xRight2 = points[(c + 1) * 2];
213
+ if (x < xRight2) {
214
+ col = c;
215
+ break;
216
+ }
217
+ }
218
+ const xLeft = points[col * 2];
219
+ const xRight = points[(col + 1) * 2];
220
+ const s = clamp((x - xLeft) / (xRight - xLeft), 0, 1);
221
+ let row = rows - 1;
222
+ for (let r = 0; r < rows; r++) {
223
+ const yBottom2 = points[(r + 1) * stride * 2 + 1];
224
+ if (y > yBottom2) {
225
+ row = r;
226
+ break;
227
+ }
228
+ }
229
+ const yTop = points[row * stride * 2 + 1];
230
+ const yBottom = points[(row + 1) * stride * 2 + 1];
231
+ const t = clamp((yTop - y) / (yTop - yBottom), 0, 1);
232
+ return { cell: row * cols + col, s, t };
233
+ }
234
+ function applyWarpToChild(localVerts, partAffine, restGrid, deformedGrid, out) {
235
+ const n = localVerts.length / 2;
236
+ for (let v = 0; v < n; v++) {
237
+ const lx = localVerts[v * 2];
238
+ const ly = localVerts[v * 2 + 1];
239
+ const mx = partAffine[0] * lx + partAffine[2] * ly + partAffine[4];
240
+ const my = partAffine[1] * lx + partAffine[3] * ly + partAffine[5];
241
+ const binding = bindPointToRestGrid(mx, my, restGrid);
242
+ const [sx, sy] = sampleWarpGrid(deformedGrid, binding);
243
+ out[v * 2] = sx;
244
+ out[v * 2 + 1] = sy;
245
+ }
246
+ }
247
+ function sampleWarpGrid(grid, binding) {
248
+ const { cols, points } = grid;
249
+ const stride = cols + 1;
250
+ const row = Math.floor(binding.cell / cols);
251
+ const col = binding.cell % cols;
252
+ const { s, t } = binding;
253
+ const i00 = (row * stride + col) * 2;
254
+ const i10 = (row * stride + col + 1) * 2;
255
+ const i01 = ((row + 1) * stride + col) * 2;
256
+ const i11 = ((row + 1) * stride + col + 1) * 2;
257
+ const topX = points[i00] + (points[i10] - points[i00]) * s;
258
+ const topY = points[i00 + 1] + (points[i10 + 1] - points[i00 + 1]) * s;
259
+ const botX = points[i01] + (points[i11] - points[i01]) * s;
260
+ const botY = points[i01 + 1] + (points[i11 + 1] - points[i01 + 1]) * s;
261
+ return [topX + (botX - topX) * t, topY + (botY - topY) * t];
262
+ }
263
+ function warpRigidFrame(pivot, restGrid, localPoints) {
264
+ const { cols, rows } = restGrid;
265
+ const binding = bindPointToRestGrid(pivot.x, pivot.y, restGrid);
266
+ const [px, py] = sampleWarpGrid({ cols, rows, points: localPoints }, binding);
267
+ const stride = cols + 1;
268
+ const row = Math.floor(binding.cell / cols);
269
+ const col = binding.cell % cols;
270
+ const { s, t } = binding;
271
+ const i00 = (row * stride + col) * 2;
272
+ const i10 = (row * stride + col + 1) * 2;
273
+ const i01 = ((row + 1) * stride + col) * 2;
274
+ const i11 = ((row + 1) * stride + col + 1) * 2;
275
+ const rest = restGrid.points;
276
+ const cellWidth = rest[(col + 1) * 2] - rest[col * 2];
277
+ const cellHeight = rest[row * stride * 2 + 1] - rest[(row + 1) * stride * 2 + 1];
278
+ const q = localPoints;
279
+ const exX = lerp(q[i10] - q[i00], q[i11] - q[i01], t) / cellWidth;
280
+ const exY = lerp(q[i10 + 1] - q[i00 + 1], q[i11 + 1] - q[i01 + 1], t) / cellWidth;
281
+ const eyX = -lerp(q[i01] - q[i00], q[i11] - q[i10], s) / cellHeight;
282
+ const eyY = -lerp(q[i01 + 1] - q[i00 + 1], q[i11 + 1] - q[i10 + 1], s) / cellHeight;
283
+ const theta = Math.atan2(exY - eyX, exX + eyY);
284
+ const c = Math.cos(theta);
285
+ const sn = Math.sin(theta);
286
+ return [
287
+ c,
288
+ sn,
289
+ -sn,
290
+ c,
291
+ px - (c * pivot.x - sn * pivot.y),
292
+ py - (sn * pivot.x + c * pivot.y)
293
+ ];
294
+ }
295
+
296
+ // ../engine/src/deform.ts
297
+ var IDENTITY_TRANSFORM = {
298
+ x: 0,
299
+ y: 0,
300
+ rotation: 0,
301
+ scaleX: 1,
302
+ scaleY: 1,
303
+ opacity: 1
304
+ };
305
+ function evaluateTransform(transform, bindings, params) {
306
+ const base = transform ?? IDENTITY_TRANSFORM;
307
+ const result = {
308
+ x: base.x,
309
+ y: base.y,
310
+ rotation: base.rotation ?? 0,
311
+ scaleX: base.scaleX ?? 1,
312
+ scaleY: base.scaleY ?? 1,
313
+ opacity: base.opacity ?? 1
314
+ };
315
+ for (const binding of bindings ?? []) {
316
+ const t = params.normalized(binding.parameter);
317
+ const value = binding.from + (binding.to - binding.from) * t;
318
+ switch (binding.channel) {
319
+ case "translateX":
320
+ result.x += value;
321
+ break;
322
+ case "translateY":
323
+ result.y += value;
324
+ break;
325
+ case "rotate":
326
+ result.rotation += value;
327
+ break;
328
+ case "scaleX":
329
+ result.scaleX += value;
330
+ break;
331
+ case "scaleY":
332
+ result.scaleY += value;
333
+ break;
334
+ case "opacity":
335
+ result.opacity *= value;
336
+ break;
337
+ }
338
+ }
339
+ return result;
340
+ }
341
+ function deformerLocalMatrix(d, params) {
342
+ const t = evaluateTransform(d.transform, d.bindings, params);
343
+ const trs = multiply(
344
+ multiply(translate(t.x, t.y), rotate(t.rotation)),
345
+ scale(t.scaleX, t.scaleY)
346
+ );
347
+ return multiply(
348
+ multiply(translate(d.pivot.x, d.pivot.y), trs),
349
+ translate(-d.pivot.x, -d.pivot.y)
350
+ );
351
+ }
352
+ function resolveDeformers(deformers, params) {
353
+ const byId = new Map(deformers.map((d) => [d.id, d]));
354
+ const worlds = /* @__PURE__ */ new Map();
355
+ const grids = /* @__PURE__ */ new Map();
356
+ const localWarps = /* @__PURE__ */ new Map();
357
+ function parentOf(d) {
358
+ if (d.parent === void 0) return void 0;
359
+ const parent = byId.get(d.parent);
360
+ if (!parent) {
361
+ throw new Error(
362
+ `unresolved deformer parent "${d.parent}" \u2014 model not validated?`
363
+ );
364
+ }
365
+ return parent;
366
+ }
367
+ function resolveWorld(d) {
368
+ const cached = worlds.get(d.id);
369
+ if (cached) return cached;
370
+ const local = deformerLocalMatrix(d, params);
371
+ const parent = parentOf(d);
372
+ let world;
373
+ if (parent === void 0) {
374
+ world = local;
375
+ } else if (parent.kind === "warp") {
376
+ const warp = resolveWarp(parent);
377
+ const ridden = multiply(
378
+ warpRigidFrame(d.pivot, parent.grid, warp.localGrid),
379
+ local
380
+ );
381
+ world = warp.parentWorld ? multiply(warp.parentWorld, ridden) : ridden;
382
+ } else {
383
+ world = multiply(resolveWorld(parent), local);
384
+ }
385
+ worlds.set(d.id, world);
386
+ return world;
387
+ }
388
+ function resolveWarp(d) {
389
+ const cached = localWarps.get(d.id);
390
+ if (cached) return cached;
391
+ const parent = parentOf(d);
392
+ if (parent?.kind === "warp") {
393
+ throw new Error(
394
+ `warp deformer "${d.id}" hangs from warp "${parent.id}" \u2014 model not validated?`
395
+ );
396
+ }
397
+ const parentWorld = parent && resolveWorld(parent);
398
+ const localGrid = deformWarpGrid(d, params);
399
+ grids.set(d.id, {
400
+ cols: d.grid.cols,
401
+ rows: d.grid.rows,
402
+ points: parentWorld ? transformGridPoints(localGrid, parentWorld) : localGrid
403
+ });
404
+ const resolved = { localGrid, parentWorld };
405
+ localWarps.set(d.id, resolved);
406
+ return resolved;
407
+ }
408
+ for (const d of deformers) {
409
+ if (d.kind === "warp") resolveWarp(d);
410
+ else resolveWorld(d);
411
+ }
412
+ return { worlds, grids };
413
+ }
414
+
415
+ // ../engine/src/view.ts
416
+ function checkedView(view) {
417
+ const { x, y, width, height } = view;
418
+ if (!Number.isFinite(x) || !Number.isFinite(y)) {
419
+ throw new Error(`Iki: setView() needs a finite x and y, got ${x}, ${y}`);
420
+ }
421
+ if (!(Number.isFinite(width) && width > 0)) {
422
+ throw new Error(
423
+ `Iki: setView() needs a positive finite width, got ${width}`
424
+ );
425
+ }
426
+ if (!(Number.isFinite(height) && height > 0)) {
427
+ throw new Error(
428
+ `Iki: setView() needs a positive finite height, got ${height}`
429
+ );
430
+ }
431
+ return { x, y, width, height };
432
+ }
433
+ function projectView(viewportWidth, viewportHeight, view) {
434
+ const fit = Math.min(
435
+ viewportWidth / view.width,
436
+ viewportHeight / view.height
437
+ );
438
+ return multiply(
439
+ scale(fit * 2 / viewportWidth, fit * 2 / viewportHeight),
440
+ translate(-view.x, -view.y)
441
+ );
442
+ }
443
+
444
+ // ../engine/src/player.ts
445
+ var MASK_ALPHA_CUTOFF = 0.5;
446
+ var IkiPlayer = class {
447
+ constructor(canvas2) {
448
+ this.canvas = canvas2;
449
+ const gl = canvas2.getContext("webgl2", {
450
+ alpha: true,
451
+ // The whole pipeline is premultiplied-alpha: textures are uploaded
452
+ // premultiplied, the fragment shader keeps them so, the blend function
453
+ // is ONE / ONE_MINUS_SRC_ALPHA, and the page compositor reads the
454
+ // framebuffer as premultiplied. Straight-alpha (`premultipliedAlpha: false`) cannot
455
+ // be made consistent with SRC_ALPHA-style blending: semi-transparent
456
+ // pixels over a transparent background come out premultiplied anyway
457
+ // and composite too dark.
458
+ premultipliedAlpha: true,
459
+ // Stencil buffer backs clip masks (a part rendered only inside its masks'
460
+ // coverage). Granted by every modern browser; the load() guard reports if not.
461
+ stencil: true
462
+ });
463
+ if (!gl) throw new Error("WebGL2 is not available in this browser");
464
+ this.gl = gl;
465
+ this.stencilAvailable = gl.getContextAttributes()?.stencil ?? false;
466
+ this.program = createProgram(gl, VERTEX_SHADER, FRAGMENT_SHADER);
467
+ this.uMatrix = getUniform(gl, this.program, "u_matrix");
468
+ this.uColor = getUniform(gl, this.program, "u_color");
469
+ this.uUseTexture = getUniform(gl, this.program, "u_useTexture");
470
+ this.uTex = getUniform(gl, this.program, "u_tex");
471
+ this.uUvOffset = getUniform(gl, this.program, "u_uvOffset");
472
+ this.uUvScale = getUniform(gl, this.program, "u_uvScale");
473
+ this.uUseMeshUv = getUniform(gl, this.program, "u_useMeshUv");
474
+ this.uAlphaCutoff = getUniform(gl, this.program, "u_alphaCutoff");
475
+ this.aPos = gl.getAttribLocation(this.program, "a_pos");
476
+ this.aUv = gl.getAttribLocation(this.program, "a_uv");
477
+ this.quad = createUnitQuad(gl);
478
+ gl.enable(gl.BLEND);
479
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
480
+ }
481
+ canvas;
482
+ gl;
483
+ program;
484
+ quad;
485
+ uMatrix;
486
+ uColor;
487
+ uUseTexture;
488
+ uTex;
489
+ uUvOffset;
490
+ uUvScale;
491
+ uUseMeshUv;
492
+ uAlphaCutoff;
493
+ aPos;
494
+ aUv;
495
+ /** True when the context granted a stencil buffer; clipping needs it. */
496
+ stencilAvailable;
497
+ model;
498
+ view;
499
+ parts = [];
500
+ params = new ParameterStore([]);
501
+ rafId;
502
+ /** Uploaded textures, index-aligned with `model.textures`; `null` = unusable. */
503
+ textures = [];
504
+ /** Bumped by every `load` and by `destroy`; lets a stale async load bail. */
505
+ loadGeneration = 0;
506
+ /** True from the moment `load()` is entered until it resolves or throws. */
507
+ loadPending = false;
508
+ /** Latches the un-awaited-load report, so a repeat caller says it once. */
509
+ warnedLoadUnfinished = false;
510
+ destroyed = false;
511
+ /**
512
+ * Engine-internal mesh buffers, keyed by the part's INDEX in `this.parts`
513
+ * (NOT by part id — duplicate ids must not swap buffers).
514
+ */
515
+ partMeshes = /* @__PURE__ */ new Map();
516
+ /**
517
+ * Clip groups resolved once per `load()`: consumer part index (into `this.parts`)
518
+ * → its mask part indices. A part absent from this map is unclipped.
519
+ */
520
+ partClipGroups = /* @__PURE__ */ new Map();
521
+ /**
522
+ * Load a model and reset parameters to their defaults. All textures are
523
+ * decoded and uploaded before the model is swapped in — the swap is atomic,
524
+ * so you never see a partially-textured frame. `start()` may be called any
525
+ * time, but nothing renders until the first `load()` resolves. For an
526
+ * embedded `data:` atlas this is near-instant.
527
+ *
528
+ * Individual texture decode/upload failures are non-fatal: they are logged
529
+ * via `console.error`, the affected parts are skipped, and `load()` still
530
+ * resolves — the returned {@link IkiLoadResult} lists the indices of any
531
+ * textures that failed, so a host can detect and report a partial load. The
532
+ * model is assumed already validated by `@ikijs/format`.
533
+ *
534
+ * Mesh buffer allocation failure IS fatal (unlike per-texture skip) because
535
+ * textures have an `IkiLoadResult.failedTextures` reporting surface and mesh
536
+ * buffers have none — there is no partial-mesh concept in the format.
537
+ *
538
+ * AWAIT THIS before reading {@link getParameters}. The swap happens after
539
+ * texture decoding, so an un-awaited `load()` leaves the parameter store
540
+ * empty for the rest of the tick; `getParameters` reports that case rather
541
+ * than letting a host conclude the model drives nothing.
542
+ */
543
+ async load(model) {
544
+ this.loadPending = true;
545
+ try {
546
+ return await this.adoptModel(model);
547
+ } finally {
548
+ this.loadPending = false;
549
+ }
550
+ }
551
+ async adoptModel(model) {
552
+ const { gl } = this;
553
+ const generation = ++this.loadGeneration;
554
+ const sources = model.textures ?? [];
555
+ const decoded = await Promise.allSettled(
556
+ sources.map((tex) => decodeTexture(tex.source))
557
+ );
558
+ if (generation !== this.loadGeneration || this.destroyed) {
559
+ for (const result of decoded) {
560
+ if (result.status === "fulfilled" && result.value) result.value.close();
561
+ }
562
+ return { failedTextures: [], superseded: true };
563
+ }
564
+ const maxTextureSizeRaw = gl.getParameter(gl.MAX_TEXTURE_SIZE);
565
+ const maxTextureSize = typeof maxTextureSizeRaw === "number" ? maxTextureSizeRaw : void 0;
566
+ if (maxTextureSize === void 0) {
567
+ console.error("Iki: WebGL context lost during load()");
568
+ }
569
+ drainGlErrors(gl);
570
+ const uploaded = decoded.map((result, i) => {
571
+ if (result.status === "rejected") {
572
+ console.error(`Iki: failed to decode textures[${i}]`, result.reason);
573
+ return null;
574
+ }
575
+ const bitmap = result.value;
576
+ if (!bitmap) return null;
577
+ if (maxTextureSize !== void 0 && (bitmap.width > maxTextureSize || bitmap.height > maxTextureSize)) {
578
+ console.error(
579
+ `Iki: textures[${i}] is ${bitmap.width}x${bitmap.height}, over this device's ${maxTextureSize}px limit`
580
+ );
581
+ bitmap.close();
582
+ return null;
583
+ }
584
+ const texture = gl.createTexture();
585
+ if (!texture) {
586
+ bitmap.close();
587
+ console.error(`Iki: failed to allocate GL texture for textures[${i}]`);
588
+ return null;
589
+ }
590
+ gl.bindTexture(gl.TEXTURE_2D, texture);
591
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
592
+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
593
+ drainGlErrors(gl);
594
+ gl.texImage2D(
595
+ gl.TEXTURE_2D,
596
+ 0,
597
+ gl.RGBA,
598
+ gl.RGBA,
599
+ gl.UNSIGNED_BYTE,
600
+ bitmap
601
+ );
602
+ bitmap.close();
603
+ const uploadError = gl.getError();
604
+ if (uploadError !== gl.NO_ERROR) {
605
+ gl.deleteTexture(texture);
606
+ console.error(
607
+ `Iki: failed to upload textures[${i}] (GL error 0x${uploadError.toString(16)})`
608
+ );
609
+ return null;
610
+ }
611
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
612
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
613
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
614
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
615
+ return texture;
616
+ });
617
+ const nextParts = [...model.parts].sort((a, b) => a.order - b.order);
618
+ const nextPartMeshes = /* @__PURE__ */ new Map();
619
+ for (let i = 0; i < nextParts.length; i++) {
620
+ const part = nextParts[i];
621
+ if (!part.mesh) continue;
622
+ const { mesh } = part;
623
+ const currentPartBuffers = [];
624
+ const positionBuf = gl.createBuffer();
625
+ if (!positionBuf) {
626
+ deletePartMeshBuffers(gl, nextPartMeshes);
627
+ deleteUploadedTextures(gl, uploaded);
628
+ throw new Error("Iki: failed to allocate mesh buffer");
629
+ }
630
+ currentPartBuffers.push(positionBuf);
631
+ const uvBuf = gl.createBuffer();
632
+ if (!uvBuf) {
633
+ for (const b of currentPartBuffers) gl.deleteBuffer(b);
634
+ deletePartMeshBuffers(gl, nextPartMeshes);
635
+ deleteUploadedTextures(gl, uploaded);
636
+ throw new Error("Iki: failed to allocate mesh buffer");
637
+ }
638
+ currentPartBuffers.push(uvBuf);
639
+ const indexBuf = gl.createBuffer();
640
+ if (!indexBuf) {
641
+ for (const b of currentPartBuffers) gl.deleteBuffer(b);
642
+ deletePartMeshBuffers(gl, nextPartMeshes);
643
+ deleteUploadedTextures(gl, uploaded);
644
+ throw new Error("Iki: failed to allocate mesh buffer");
645
+ }
646
+ const rest = new Float32Array(mesh.vertices);
647
+ const warpDeformer = part.deformer !== void 0 ? model.deformers?.find(
648
+ (d) => d.kind === "warp" && d.id === part.deformer
649
+ ) : void 0;
650
+ const isWarpChild = warpDeformer !== void 0;
651
+ const hasWarps = (part.warps?.length ?? 0) > 0;
652
+ const dynamic = hasWarps || isWarpChild;
653
+ const scratch = dynamic ? new Float32Array(mesh.vertices.length) : void 0;
654
+ const local = isWarpChild ? new Float32Array(mesh.vertices.length) : void 0;
655
+ drainGlErrors(gl);
656
+ gl.bindBuffer(gl.ARRAY_BUFFER, positionBuf);
657
+ gl.bufferData(
658
+ gl.ARRAY_BUFFER,
659
+ rest,
660
+ dynamic ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW
661
+ );
662
+ gl.bindBuffer(gl.ARRAY_BUFFER, uvBuf);
663
+ gl.bufferData(
664
+ gl.ARRAY_BUFFER,
665
+ new Float32Array(mesh.uvs),
666
+ gl.STATIC_DRAW
667
+ );
668
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuf);
669
+ gl.bufferData(
670
+ gl.ELEMENT_ARRAY_BUFFER,
671
+ new Uint16Array(mesh.indices),
672
+ gl.STATIC_DRAW
673
+ );
674
+ const meshUploadError = gl.getError();
675
+ if (meshUploadError !== gl.NO_ERROR) {
676
+ for (const b of currentPartBuffers) gl.deleteBuffer(b);
677
+ gl.deleteBuffer(indexBuf);
678
+ deletePartMeshBuffers(gl, nextPartMeshes);
679
+ deleteUploadedTextures(gl, uploaded);
680
+ throw new Error(
681
+ `Iki: failed to upload mesh buffers for part "${part.id}" (GL error 0x${meshUploadError.toString(16)})`
682
+ );
683
+ }
684
+ nextPartMeshes.set(i, {
685
+ position: positionBuf,
686
+ uv: uvBuf,
687
+ index: indexBuf,
688
+ indexCount: mesh.indices.length,
689
+ rest,
690
+ scratch,
691
+ warps: part.warps,
692
+ warpDeformer,
693
+ local
694
+ });
695
+ }
696
+ const nextClipGroups = /* @__PURE__ */ new Map();
697
+ const indexById = /* @__PURE__ */ new Map();
698
+ for (let i = 0; i < nextParts.length; i++) {
699
+ indexById.set(nextParts[i].id, i);
700
+ }
701
+ for (let i = 0; i < nextParts.length; i++) {
702
+ const clip = nextParts[i].clip;
703
+ if (!clip) continue;
704
+ const maskIndices = clip.masks.map((maskId) => indexById.get(maskId)).filter((mi) => mi !== void 0);
705
+ if (maskIndices.length > 0) nextClipGroups.set(i, maskIndices);
706
+ }
707
+ if (nextClipGroups.size > 0 && !this.stencilAvailable) {
708
+ console.error(
709
+ "Iki: model uses clip masks but this WebGL2 context has no stencil buffer; rendering unclipped"
710
+ );
711
+ }
712
+ deletePartMeshBuffers(gl, this.partMeshes);
713
+ for (const texture of this.textures) {
714
+ if (texture) gl.deleteTexture(texture);
715
+ }
716
+ this.model = model;
717
+ this.params = new ParameterStore(model.parameters);
718
+ this.parts = nextParts;
719
+ this.partMeshes = nextPartMeshes;
720
+ this.partClipGroups = nextClipGroups;
721
+ this.textures = uploaded;
722
+ return {
723
+ failedTextures: uploaded.flatMap((t, i) => t === null ? [i] : []),
724
+ superseded: false
725
+ };
726
+ }
727
+ /**
728
+ * Start the render loop. Safe to call more than once, and a no-op after
729
+ * {@link destroy} — the program and buffers the loop draws with are gone, so
730
+ * restarting would only spray GL errors.
731
+ */
732
+ start() {
733
+ if (this.rafId !== void 0 || this.destroyed) return;
734
+ const loop = () => {
735
+ this.renderFrame();
736
+ this.rafId = requestAnimationFrame(loop);
737
+ };
738
+ this.rafId = requestAnimationFrame(loop);
739
+ }
740
+ stop() {
741
+ if (this.rafId === void 0) return;
742
+ cancelAnimationFrame(this.rafId);
743
+ this.rafId = void 0;
744
+ }
745
+ /**
746
+ * Set a parameter value (clamped to its range). Unknown ids and non-finite
747
+ * values are ignored — see {@link ParameterStore.set}.
748
+ */
749
+ setParameter(id, value) {
750
+ this.params.set(id, value);
751
+ }
752
+ /**
753
+ * Frame the canvas on `view` (centre and size in model units) instead of the
754
+ * model's box, which is the default. Pass a wider view for a full body whose
755
+ * raised arms leave the box (how much room is the host's call: a combined
756
+ * pose sets the reach), or a smaller one for a face crop. Parts clip at the
757
+ * canvas's edge, never at the view. The view survives `load()`; `setView()`
758
+ * with no argument restores the default. Throws on a non-finite centre or a
759
+ * non-positive size.
760
+ */
761
+ setView(view) {
762
+ this.view = view ? checkedView(view) : void 0;
763
+ }
764
+ /**
765
+ * Current value of a parameter, or 0 for an unknown id.
766
+ *
767
+ * Hosts need this to avoid shadowing the engine's state: the motion drivers
768
+ * read the live pose to compute the next one, and without a read accessor
769
+ * every host has to keep its own mirror of what it last wrote — and keep that
770
+ * mirror's clamping in step with {@link ParameterStore} by hand.
771
+ */
772
+ getParameter(id) {
773
+ return this.params.get(id);
774
+ }
775
+ /**
776
+ * The model's parameter descriptors, for building UI or host wiring.
777
+ *
778
+ * Empty until the first {@link load} resolves. Reaching it through an
779
+ * un-awaited `load()` is the one mistake in this class that produces no
780
+ * error and no motion: the caller gets `[]`, concludes the model has no
781
+ * parameters, and drives nothing — so that case is reported instead of
782
+ * being indistinguishable from a model that really declares none. A
783
+ * reload is deliberately NOT reported: those parameters are stale rather
784
+ * than absent, and warning there would fire on legitimate concurrent reads.
785
+ */
786
+ getParameters() {
787
+ if (this.loadPending && this.model === void 0 && !this.warnedLoadUnfinished) {
788
+ this.warnedLoadUnfinished = true;
789
+ console.error(
790
+ "Iki: getParameters() ran before load() finished, so it returned an empty list \u2014 await load() before reading parameters."
791
+ );
792
+ }
793
+ return this.params.list();
794
+ }
795
+ destroy() {
796
+ this.stop();
797
+ this.destroyed = true;
798
+ ++this.loadGeneration;
799
+ const { gl } = this;
800
+ for (const texture of this.textures) {
801
+ if (texture) gl.deleteTexture(texture);
802
+ }
803
+ this.textures = [];
804
+ deletePartMeshBuffers(gl, this.partMeshes);
805
+ this.partMeshes = /* @__PURE__ */ new Map();
806
+ gl.deleteBuffer(this.quad);
807
+ gl.deleteProgram(this.program);
808
+ }
809
+ renderFrame() {
810
+ const { gl, canvas: canvas2 } = this;
811
+ const dpr = window.devicePixelRatio || 1;
812
+ const width = Math.max(1, Math.floor(canvas2.clientWidth * dpr));
813
+ const height = Math.max(1, Math.floor(canvas2.clientHeight * dpr));
814
+ if (canvas2.width !== width || canvas2.height !== height) {
815
+ canvas2.width = width;
816
+ canvas2.height = height;
817
+ }
818
+ gl.viewport(0, 0, width, height);
819
+ gl.clearColor(0, 0, 0, 0);
820
+ gl.clear(gl.COLOR_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);
821
+ if (!this.model) return;
822
+ const { width: modelW, height: modelH } = this.model.canvas;
823
+ const project = projectView(
824
+ width,
825
+ height,
826
+ this.view ?? { x: 0, y: 0, width: modelW, height: modelH }
827
+ );
828
+ gl.useProgram(this.program);
829
+ const resolved = this.model.deformers && this.model.deformers.length > 0 ? resolveDeformers(this.model.deformers, this.params) : void 0;
830
+ const deformerWorlds = resolved?.worlds;
831
+ const warpGrids = resolved?.grids;
832
+ gl.uniform1f(this.uAlphaCutoff, 0);
833
+ for (let index = 0; index < this.parts.length; index++) {
834
+ const maskIndices = this.partClipGroups.get(index);
835
+ if (maskIndices && this.stencilAvailable) {
836
+ this.drawClipped(
837
+ index,
838
+ maskIndices,
839
+ project,
840
+ deformerWorlds,
841
+ warpGrids
842
+ );
843
+ } else {
844
+ this.drawPart(index, project, deformerWorlds, warpGrids);
845
+ }
846
+ }
847
+ }
848
+ /**
849
+ * Draw a clipped part: stencil the union of its masks' alpha coverage, then
850
+ * draw the part only where the stencil was written. The mask parts also draw
851
+ * normally in their own `order` slot — this is an EXTRA, color-free pass over
852
+ * the same per-frame deformed geometry. All stencil/colorMask state the pass
853
+ * touches is restored before returning so later parts are unaffected.
854
+ */
855
+ drawClipped(index, maskIndices, project, deformerWorlds, warpGrids) {
856
+ const { gl } = this;
857
+ gl.clear(gl.STENCIL_BUFFER_BIT);
858
+ gl.enable(gl.STENCIL_TEST);
859
+ gl.colorMask(false, false, false, false);
860
+ gl.stencilMask(255);
861
+ gl.stencilFunc(gl.ALWAYS, 1, 255);
862
+ gl.stencilOp(gl.KEEP, gl.KEEP, gl.REPLACE);
863
+ gl.uniform1f(this.uAlphaCutoff, MASK_ALPHA_CUTOFF);
864
+ for (const maskIndex of maskIndices) {
865
+ this.drawPart(maskIndex, project, deformerWorlds, warpGrids);
866
+ }
867
+ gl.uniform1f(this.uAlphaCutoff, 0);
868
+ gl.colorMask(true, true, true, true);
869
+ gl.stencilMask(0);
870
+ gl.stencilFunc(gl.EQUAL, 1, 255);
871
+ gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
872
+ this.drawPart(index, project, deformerWorlds, warpGrids);
873
+ gl.disable(gl.STENCIL_TEST);
874
+ gl.stencilMask(255);
875
+ gl.stencilFunc(gl.ALWAYS, 0, 255);
876
+ gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
877
+ }
878
+ /**
879
+ * Draw a single part with its full per-part material + geometry state. Shared
880
+ * by the normal pass, the stencil mask-write pass, and the masked consumer
881
+ * draw — so every path prepares the SAME complete uniform/texture/VBO state
882
+ * (the caller only sets stencil/colorMask/u_alphaCutoff around it).
883
+ */
884
+ drawPart(index, project, deformerWorlds, warpGrids) {
885
+ const { gl } = this;
886
+ const part = this.parts[index];
887
+ const texture = part.texture ? this.textures[part.texture.index] : void 0;
888
+ if (part.texture && !texture) return;
889
+ const t = this.evaluate(part);
890
+ const warpChild = this.partMeshes.get(index)?.warpDeformer;
891
+ let m;
892
+ if (warpChild) {
893
+ m = project;
894
+ } else if (part.deformer !== void 0) {
895
+ const dWorld = deformerWorlds.get(part.deformer);
896
+ if (!dWorld) {
897
+ throw new Error(
898
+ `part "${part.id}" references unknown deformer "${part.deformer}"`
899
+ );
900
+ }
901
+ m = multiply(multiply(project, dWorld), translate(t.x, t.y));
902
+ m = multiply(m, rotate(t.rotation));
903
+ m = multiply(m, scale(part.width * t.scaleX, part.height * t.scaleY));
904
+ } else {
905
+ m = multiply(project, translate(t.x, t.y));
906
+ m = multiply(m, rotate(t.rotation));
907
+ m = multiply(m, scale(part.width * t.scaleX, part.height * t.scaleY));
908
+ }
909
+ const [r, g, b, a] = part.color;
910
+ gl.uniformMatrix3fv(this.uMatrix, false, toMat3(m));
911
+ gl.uniform4f(this.uColor, r, g, b, a * t.opacity);
912
+ if (part.texture && texture) {
913
+ const { uv } = part.texture;
914
+ gl.uniform1i(this.uUseTexture, 1);
915
+ gl.activeTexture(gl.TEXTURE0);
916
+ gl.bindTexture(gl.TEXTURE_2D, texture);
917
+ gl.uniform1i(this.uTex, 0);
918
+ gl.uniform2f(this.uUvOffset, uv.x, uv.y);
919
+ gl.uniform2f(this.uUvScale, uv.width, uv.height);
920
+ } else {
921
+ gl.uniform1i(this.uUseTexture, 0);
922
+ }
923
+ if (part.mesh) {
924
+ const pm = this.partMeshes.get(index);
925
+ if (!pm) {
926
+ throw new Error(`Iki: mesh buffers missing for part "${part.id}"`);
927
+ }
928
+ gl.uniform1i(this.uUseMeshUv, 1);
929
+ if (pm.warpDeformer) {
930
+ const warpDef = pm.warpDeformer;
931
+ const grid = warpGrids.get(warpDef.id);
932
+ applyWarps(pm.rest, pm.warps, this.params, pm.local);
933
+ const trs = evaluateTransform(
934
+ part.transform,
935
+ part.bindings,
936
+ this.params
937
+ );
938
+ const partAffine = multiply(
939
+ multiply(translate(trs.x, trs.y), rotate(trs.rotation)),
940
+ scale(part.width * trs.scaleX, part.height * trs.scaleY)
941
+ );
942
+ applyWarpToChild(
943
+ pm.local,
944
+ partAffine,
945
+ warpDef.grid,
946
+ grid,
947
+ pm.scratch
948
+ );
949
+ gl.bindBuffer(gl.ARRAY_BUFFER, pm.position);
950
+ gl.bufferSubData(gl.ARRAY_BUFFER, 0, pm.scratch);
951
+ } else if (pm.warps && pm.warps.length > 0) {
952
+ applyWarps(pm.rest, pm.warps, this.params, pm.scratch);
953
+ gl.bindBuffer(gl.ARRAY_BUFFER, pm.position);
954
+ gl.bufferSubData(gl.ARRAY_BUFFER, 0, pm.scratch);
955
+ }
956
+ gl.bindBuffer(gl.ARRAY_BUFFER, pm.position);
957
+ gl.enableVertexAttribArray(this.aPos);
958
+ gl.vertexAttribPointer(this.aPos, 2, gl.FLOAT, false, 0, 0);
959
+ gl.bindBuffer(gl.ARRAY_BUFFER, pm.uv);
960
+ gl.enableVertexAttribArray(this.aUv);
961
+ gl.vertexAttribPointer(this.aUv, 2, gl.FLOAT, false, 0, 0);
962
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, pm.index);
963
+ gl.drawElements(gl.TRIANGLES, pm.indexCount, gl.UNSIGNED_SHORT, 0);
964
+ } else {
965
+ gl.uniform1i(this.uUseMeshUv, 0);
966
+ gl.disableVertexAttribArray(this.aUv);
967
+ gl.bindBuffer(gl.ARRAY_BUFFER, this.quad);
968
+ gl.enableVertexAttribArray(this.aPos);
969
+ gl.vertexAttribPointer(this.aPos, 2, gl.FLOAT, false, 0, 0);
970
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
971
+ }
972
+ }
973
+ /** Resolve a part's effective transform from its base plus active bindings. */
974
+ evaluate(part) {
975
+ return evaluateTransform(part.transform, part.bindings, this.params);
976
+ }
977
+ };
978
+ var VERTEX_SHADER = `#version 300 es
979
+ in vec2 a_pos;
980
+ in vec2 a_uv;
981
+ uniform mat3 u_matrix;
982
+ uniform vec2 u_uvOffset;
983
+ uniform vec2 u_uvScale;
984
+ uniform bool u_useMeshUv;
985
+ // centroid: the context is multisampled (antialias defaults on), and a pixel
986
+ // that a triangle only partly covers is otherwise shaded at its centre even
987
+ // when that lies outside the triangle \u2014 v_uv then extrapolates past the
988
+ // part's inset atlas rect into the neighbouring region's gutter, which holds
989
+ // ANOTHER part's extruded edge. One real model drew a 1 px cream line along
990
+ // its back hair's top edge from the body packed above it. Centroid moves the
991
+ // evaluation inside the covered samples, so v_uv stays inside the rect.
992
+ centroid out vec2 v_uv;
993
+ void main() {
994
+ if (u_useMeshUv) {
995
+ // Mesh path: UVs are already top-left atlas-space; pass straight through,
996
+ // no flip (the only flip in the pipeline lives in the quad branch below).
997
+ v_uv = a_uv;
998
+ } else {
999
+ // Quad path: a_pos corners are +/-0.5; lift to 0..1 (y-up), then map into
1000
+ // the atlas sub-rect with a single V flip so the result is top-left UVs.
1001
+ vec2 uvLocal = a_pos + 0.5;
1002
+ v_uv = vec2(
1003
+ u_uvOffset.x + uvLocal.x * u_uvScale.x,
1004
+ u_uvOffset.y + (1.0 - uvLocal.y) * u_uvScale.y
1005
+ );
1006
+ }
1007
+ vec3 p = u_matrix * vec3(a_pos, 1.0);
1008
+ gl_Position = vec4(p.xy, 0.0, 1.0);
1009
+ }`;
1010
+ var FRAGMENT_SHADER = `#version 300 es
1011
+ precision mediump float;
1012
+ uniform vec4 u_color;
1013
+ uniform bool u_useTexture;
1014
+ uniform sampler2D u_tex;
1015
+ uniform float u_alphaCutoff;
1016
+ centroid in vec2 v_uv;
1017
+ out vec4 outColor;
1018
+ void main() {
1019
+ // Texels are premultiplied (see the upload); the untextured fill is opaque
1020
+ // white, premultiplied or not.
1021
+ vec4 base = u_useTexture ? texture(u_tex, v_uv) : vec4(1.0);
1022
+ vec4 tinted = base * u_color;
1023
+ // 0 for normal draws (no-op); raised during the stencil mask-write pass so
1024
+ // only opaque mask coverage marks the stencil (the transparent fringe is cut).
1025
+ if (tinted.a < u_alphaCutoff) discard;
1026
+ // The blend function and the canvas compositing contract (premultipliedAlpha:
1027
+ // true) both expect rgb already scaled by alpha. base.rgb is; the tint's own
1028
+ // alpha still has to scale it (base.a is already folded into base.rgb).
1029
+ outColor = vec4(tinted.rgb * u_color.a, tinted.a);
1030
+ }`;
1031
+ async function decodeTexture(source) {
1032
+ if (!source.startsWith("data:")) {
1033
+ console.warn(
1034
+ "Iki: external texture sources are unsupported in v1; skipping",
1035
+ source.slice(0, 32)
1036
+ );
1037
+ return null;
1038
+ }
1039
+ const blob = await (await fetch(source)).blob();
1040
+ return createImageBitmap(blob, {
1041
+ imageOrientation: "none",
1042
+ premultiplyAlpha: "premultiply"
1043
+ });
1044
+ }
1045
+ function createUnitQuad(gl) {
1046
+ const buffer = gl.createBuffer();
1047
+ if (!buffer) throw new Error("failed to allocate quad buffer");
1048
+ gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
1049
+ gl.bufferData(
1050
+ gl.ARRAY_BUFFER,
1051
+ new Float32Array([-0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, 0.5]),
1052
+ gl.STATIC_DRAW
1053
+ );
1054
+ return buffer;
1055
+ }
1056
+ function drainGlErrors(gl) {
1057
+ for (let i = 0; i < 32 && gl.getError() !== gl.NO_ERROR; i++) {
1058
+ }
1059
+ }
1060
+ function deletePartMeshBuffers(gl, meshes) {
1061
+ for (const pm of meshes.values()) {
1062
+ gl.deleteBuffer(pm.position);
1063
+ gl.deleteBuffer(pm.uv);
1064
+ gl.deleteBuffer(pm.index);
1065
+ }
1066
+ }
1067
+ function deleteUploadedTextures(gl, textures) {
1068
+ for (const texture of textures) {
1069
+ if (texture) gl.deleteTexture(texture);
1070
+ }
1071
+ }
1072
+ function createProgram(gl, vertexSrc, fragmentSrc) {
1073
+ const program = gl.createProgram();
1074
+ if (!program) throw new Error("failed to allocate WebGL program");
1075
+ gl.attachShader(program, compileShader(gl, gl.VERTEX_SHADER, vertexSrc));
1076
+ gl.attachShader(program, compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc));
1077
+ gl.linkProgram(program);
1078
+ if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
1079
+ const log = gl.getProgramInfoLog(program);
1080
+ gl.deleteProgram(program);
1081
+ throw new Error(`program link failed: ${log}`);
1082
+ }
1083
+ return program;
1084
+ }
1085
+ function compileShader(gl, type, source) {
1086
+ const shader = gl.createShader(type);
1087
+ if (!shader) throw new Error("failed to allocate shader");
1088
+ gl.shaderSource(shader, source);
1089
+ gl.compileShader(shader);
1090
+ if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
1091
+ const log = gl.getShaderInfoLog(shader);
1092
+ gl.deleteShader(shader);
1093
+ throw new Error(`shader compile failed: ${log}`);
1094
+ }
1095
+ return shader;
1096
+ }
1097
+ function getUniform(gl, program, name) {
1098
+ const loc = gl.getUniformLocation(program, name);
1099
+ if (!loc) throw new Error(`uniform not found: ${name}`);
1100
+ return loc;
1101
+ }
1102
+
1103
+ // ../format/src/parameters.ts
1104
+ var StandardParameter = {
1105
+ /** Mouth open amount for lip-sync (0 closed .. 1 open). */
1106
+ MouthOpen: "ParamMouthOpenY",
1107
+ /** Mouth form / smile (-1 .. 1). */
1108
+ MouthForm: "ParamMouthForm",
1109
+ /** Left eye open (0 closed .. 1 open). Drive with the right eye for a blink. */
1110
+ EyeOpenLeft: "ParamEyeLOpen",
1111
+ /** Right eye open (0 closed .. 1 open). */
1112
+ EyeOpenRight: "ParamEyeROpen",
1113
+ /** Eyeball gaze, horizontal (-1 .. 1). */
1114
+ EyeballX: "ParamEyeBallX",
1115
+ /** Eyeball gaze, vertical (-1 .. 1). */
1116
+ EyeballY: "ParamEyeBallY",
1117
+ /** Head angle, horizontal degrees. */
1118
+ AngleX: "ParamAngleX",
1119
+ /** Head angle, vertical degrees. */
1120
+ AngleY: "ParamAngleY",
1121
+ /** Head tilt / roll degrees. Positive tilts the top of the head toward the
1122
+ * viewer's right (clockwise on screen), matching Live2D's ParamAngleZ so a
1123
+ * host's head-tracking maps 1:1; note this is the opposite sense from the
1124
+ * CCW-positive brow angles below. */
1125
+ AngleZ: "ParamAngleZ",
1126
+ /** Body turn, degrees (-10 .. 10). Positive turns the body toward the
1127
+ * viewer's right, as AngleX does the head. */
1128
+ BodyAngleX: "ParamBodyAngleX",
1129
+ /** Body lean, degrees (-10 .. 10). Positive moves the upper body up, negative bows. */
1130
+ BodyAngleY: "ParamBodyAngleY",
1131
+ /** Body tilt, degrees (-10 .. 10). Positive tilts the top toward the viewer's
1132
+ * right (clockwise on screen), as AngleZ does the head. */
1133
+ BodyAngleZ: "ParamBodyAngleZ",
1134
+ /** Idle breath (0 .. 1), cycled by the host. */
1135
+ Breath: "ParamBreath",
1136
+ /** Left brow vertical raise/lower (-1 down .. 1 up). */
1137
+ BrowLeftY: "ParamBrowLY",
1138
+ /** Right brow vertical raise/lower (-1 down .. 1 up). */
1139
+ BrowRightY: "ParamBrowRY",
1140
+ /** Left brow tilt (-1 .. 1, CCW-positive). */
1141
+ BrowLeftAngle: "ParamBrowLAngle",
1142
+ /** Right brow tilt (-1 .. 1, CCW-positive). */
1143
+ BrowRightAngle: "ParamBrowRAngle",
1144
+ /** Cheek blush strength (0 .. 1), raised by an expression. */
1145
+ Cheek: "ParamCheek",
1146
+ /** Horizontal hair sway. Physics OUTPUT — driven by the spring, not set by the host. */
1147
+ HairSwayX: "ParamHairSwayX",
1148
+ /** Hair sway behind a head tilt. Physics OUTPUT — driven by the spring, not set by the host. */
1149
+ HairSwayZ: "ParamHairSwayZ",
1150
+ /** Left shoulder, degrees. Positive raises the arm outward (mirrored on the right). */
1151
+ ArmLeft: "ParamArmL",
1152
+ /** Right shoulder, degrees. Positive raises the arm outward (mirrored on the left). */
1153
+ ArmRight: "ParamArmR",
1154
+ /** Left elbow, degrees. Positive bends the forearm toward the body (the flexion of a hanging arm), negative a little outward (mirrored on the right). */
1155
+ ElbowLeft: "ParamElbowL",
1156
+ /** Right elbow, degrees. Positive bends the forearm toward the body (the flexion of a hanging arm), negative a little outward (mirrored on the left). */
1157
+ ElbowRight: "ParamElbowR",
1158
+ /** Left pose-forearm switch (0 .. 1): 0 the hanging forearm, 1 the drawn pose forearm, between them a crossfade of the two. Declared by auto-rigged models with a pose forearm. */
1159
+ ArmPoseLeft: "ParamArmPoseL",
1160
+ /** Right pose-forearm switch (0 .. 1): 0 the hanging forearm, 1 the drawn pose forearm, between them a crossfade of the two. Declared by auto-rigged models with a pose forearm. */
1161
+ ArmPoseRight: "ParamArmPoseR",
1162
+ /** Left pose forearm's own small rotation about the elbow, degrees. Positive tips the raised hand outward, away from the body (mirrored on the right). */
1163
+ ArmPoseAngleLeft: "ParamArmPoseAngleL",
1164
+ /** Right pose forearm's own small rotation about the elbow, degrees. Positive tips the raised hand outward, away from the body (mirrored on the left). */
1165
+ ArmPoseAngleRight: "ParamArmPoseAngleR"
1166
+ };
1167
+
1168
+ // ../format/src/validate-animations.ts
1169
+ var IDLE_PROCEDURAL = /* @__PURE__ */ new Set([
1170
+ StandardParameter.EyeOpenLeft,
1171
+ StandardParameter.EyeOpenRight,
1172
+ StandardParameter.Breath
1173
+ ]);
1174
+
1175
+ // ../engine/src/frame-clock.ts
1176
+ var FIXED_DT_S = 1 / 60;
1177
+
1178
+ // ../engine/src/idle-motion.ts
1179
+ var BLINK_CLOSE_MS = 60;
1180
+ var BLINK_HOLD_MS = 20;
1181
+ var BLINK_OPEN_MS = 100;
1182
+ var BLINK_DURATION_MS = BLINK_CLOSE_MS + BLINK_HOLD_MS + BLINK_OPEN_MS;
1183
+
1184
+ // ../engine/src/hair-chain-motion.ts
1185
+ var DEG2RAD = Math.PI / 180;
1186
+ var RAD2DEG = 180 / Math.PI;
1187
+
1188
+ // ../engine/src/iki-motion.ts
1189
+ var HEAD_AND_GAZE = /* @__PURE__ */ new Set([
1190
+ StandardParameter.AngleX,
1191
+ StandardParameter.AngleY,
1192
+ StandardParameter.AngleZ,
1193
+ StandardParameter.EyeballX,
1194
+ StandardParameter.EyeballY
1195
+ ]);
1196
+
1197
+ // src/render-page.ts
1198
+ var nextFrame = () => new Promise((resolve) => requestAnimationFrame(() => resolve()));
1199
+ var settle = async () => {
1200
+ await nextFrame();
1201
+ await nextFrame();
1202
+ };
1203
+ var player;
1204
+ var canvas;
1205
+ window.__ikiRender = {
1206
+ async load(model, { canvas: size, view }) {
1207
+ canvas = document.createElement("canvas");
1208
+ canvas.style.width = `${size.width}px`;
1209
+ canvas.style.height = `${size.height}px`;
1210
+ document.body.appendChild(canvas);
1211
+ player = new IkiPlayer(canvas);
1212
+ player.start();
1213
+ const { failedTextures } = await player.load(model);
1214
+ if (view) player.setView(view);
1215
+ await settle();
1216
+ if (canvas.width !== size.width || canvas.height !== size.height) {
1217
+ throw new Error(
1218
+ `canvas is ${canvas.width}x${canvas.height}, expected ${size.width}x${size.height} (device pixel ratio?)`
1219
+ );
1220
+ }
1221
+ return { failedTextures };
1222
+ },
1223
+ async capture(values, crop) {
1224
+ if (!player || !canvas) throw new Error("capture() called before load()");
1225
+ for (const p of player.getParameters()) {
1226
+ player.setParameter(p.id, p.default);
1227
+ }
1228
+ for (const [id, value] of Object.entries(values)) {
1229
+ player.setParameter(id, value);
1230
+ }
1231
+ await settle();
1232
+ if (!crop) return canvas.toDataURL("image/png");
1233
+ const out = document.createElement("canvas");
1234
+ out.width = crop.dw;
1235
+ out.height = crop.dh;
1236
+ out.getContext("2d").drawImage(
1237
+ canvas,
1238
+ crop.sx,
1239
+ crop.sy,
1240
+ crop.sw,
1241
+ crop.sh,
1242
+ 0,
1243
+ 0,
1244
+ crop.dw,
1245
+ crop.dh
1246
+ );
1247
+ return out.toDataURL("image/png");
1248
+ }
1249
+ };
1250
+ })();