@margoengine/rigging 0.0.0-stage → 1.0.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.
Files changed (84) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +1443 -2
  4. package/dist/anatomy-data-ansur2.d.ts +63 -0
  5. package/dist/anatomy-data-cdc.d.ts +16 -0
  6. package/dist/anatomy-data-deleva.d.ts +86 -0
  7. package/dist/anatomy-human.d.ts +67 -0
  8. package/dist/anatomy-human.js +2229 -0
  9. package/dist/anatomy.d.ts +638 -0
  10. package/dist/anatomy.js +1112 -0
  11. package/dist/autorig.d.ts +50 -0
  12. package/dist/autorig.js +663 -0
  13. package/dist/bar-grip.d.ts +7 -0
  14. package/dist/body-volumes-DTym0RVY.js +56 -0
  15. package/dist/body-volumes.d.ts +19 -0
  16. package/dist/checks.d.ts +50 -0
  17. package/dist/contact.d.ts +186 -0
  18. package/dist/contact.js +746 -0
  19. package/dist/correctives.d.ts +92 -0
  20. package/dist/correctives.js +162 -0
  21. package/dist/coupling.d.ts +57 -0
  22. package/dist/coupling.js +330 -0
  23. package/dist/errors-D8rc8kzg.js +7 -0
  24. package/dist/face.d.ts +93 -0
  25. package/dist/face.js +144 -0
  26. package/dist/hands.d.ts +209 -0
  27. package/dist/hands.js +510 -0
  28. package/dist/heat.d.ts +38 -0
  29. package/dist/hinged-contact.d.ts +7 -0
  30. package/dist/hulls.d.ts +54 -0
  31. package/dist/hulls.js +134 -0
  32. package/dist/ik.d.ts +162 -0
  33. package/dist/ik.js +561 -0
  34. package/dist/index.d.ts +6 -0
  35. package/dist/index.js +390 -0
  36. package/dist/joint-limits.d.ts +44 -0
  37. package/dist/joint-limits.js +74 -0
  38. package/dist/limb-collision.d.ts +99 -0
  39. package/dist/loading-CZaYr1N7.js +67 -0
  40. package/dist/mesh-CyvLHNp0.js +142 -0
  41. package/dist/mesh.d.ts +47 -0
  42. package/dist/mtoon-data.d.ts +118 -0
  43. package/dist/mtoon-legacy.d.ts +17 -0
  44. package/dist/mtoon-shader.d.ts +4 -0
  45. package/dist/mtoon.d.ts +84 -0
  46. package/dist/mtoon.js +990 -0
  47. package/dist/paint.d.ts +82 -0
  48. package/dist/pose-tracking.d.ts +117 -0
  49. package/dist/pose-tracking.js +488 -0
  50. package/dist/retarget.d.ts +78 -0
  51. package/dist/retarget.js +375 -0
  52. package/dist/rig-BawZ5OLb.js +127 -0
  53. package/dist/rig.d.ts +65 -0
  54. package/dist/shared/gltf.d.ts +257 -0
  55. package/dist/shared/layers.d.ts +16 -0
  56. package/dist/springs.d.ts +180 -0
  57. package/dist/springs.js +458 -0
  58. package/dist/strand-springs.d.ts +46 -0
  59. package/dist/strand-springs.js +168 -0
  60. package/dist/swim.d.ts +55 -0
  61. package/dist/swim.js +167 -0
  62. package/dist/transfer.d.ts +41 -0
  63. package/dist/transfer.js +136 -0
  64. package/dist/validate.d.ts +188 -0
  65. package/dist/validate.js +440 -0
  66. package/dist/voxel-weights-48ok-Dax.js +255 -0
  67. package/dist/voxel-weights.d.ts +42 -0
  68. package/dist/voxel-weights.js +1 -0
  69. package/dist/voxels.d.ts +36 -0
  70. package/dist/vrm-constraints.d.ts +60 -0
  71. package/dist/vrm-constraints.js +261 -0
  72. package/dist/vrm-first-person.d.ts +115 -0
  73. package/dist/vrm-first-person.js +618 -0
  74. package/dist/vrm-presets-CU4V4yq6.js +47 -0
  75. package/dist/vrm-presets.d.ts +1 -0
  76. package/dist/vrm.d.ts +303 -0
  77. package/dist/vrm.js +574 -0
  78. package/dist/vrm0.d.ts +134 -0
  79. package/dist/vrm0.js +377 -0
  80. package/dist/vrma.d.ts +90 -0
  81. package/dist/vrma.js +315 -0
  82. package/dist/weight-map-D8cAONQQ.js +92 -0
  83. package/dist/weight-map.d.ts +58 -0
  84. package/package.json +189 -4
package/dist/index.js ADDED
@@ -0,0 +1,390 @@
1
+ import { n as e, r as t, t as n } from "./weight-map-D8cAONQQ.js";
2
+ import { a as r, i, n as a, o, t as s } from "./rig-BawZ5OLb.js";
3
+ import { i as c, n as l, r as u, t as d } from "./mesh-CyvLHNp0.js";
4
+ import { MargoError as f } from "@margoengine/math/errors";
5
+ //#region src/heat.ts
6
+ async function p(e, t, r = {}) {
7
+ a(t);
8
+ let { skip: o = [], visibility: u = !0, heat: d = 1, tolerance: f = 1e-6, maxIterations: p = 2e3, threshold: _ = 1e-4, signal: y } = r;
9
+ if (!(d > 0 && d < Infinity)) throw RangeError(`Bone heat ${d} must be finite and above 0`);
10
+ if (!(f > 0 && f < 1)) throw RangeError("Bone heat tolerance must be above 0 and below 1");
11
+ if (!Number.isInteger(p) || p < 1) throw RangeError("Bone heat maxIterations must be a positive integer");
12
+ if (!(_ >= 0 && _ < .5)) throw RangeError("Bone heat threshold must be from 0 to below 0.5");
13
+ if (typeof u != "boolean" && typeof u != "function") throw TypeError("Bone heat visibility must be true, false or a function(from, to)");
14
+ y?.throwIfAborted();
15
+ let b = new Set(i(t, o, "Bone heat skip"));
16
+ if (b.size === t.length) throw RangeError("Bone heat skips every joint; leave at least one to move");
17
+ let x = c(e, r.weld), S = s(t, (e) => !b.has(e)), C = typeof u == "function" ? u : u ? await m(x) : null;
18
+ y?.throwIfAborted();
19
+ let { nearest: w, heatDiagonal: T } = h(x, t.length, S, C, d), { matrix: E, area: D } = l(x), O = D.length, k = new Float64Array(O);
20
+ for (let e = 0; e < O; e++) k[e] = D[e] * T[e];
21
+ for (let e = 0; e < O; e++) E.diagonal[e] + k[e] > 0 || (k[e] = 1);
22
+ let A = new n(x.vertexCount, t.length), j = new Float64Array(O * t.length), M = [...new Set(w.owners)].sort((e, t) => e - t), N = new Float64Array(O), P = new Float64Array(O), F = g(O), I = performance.now();
23
+ for (let e of M) {
24
+ for (let t = 0; t < O; t++) {
25
+ let n = w.share(t, e);
26
+ N[t] = k[t] * n, P[t] = n;
27
+ }
28
+ await v(E, k, N, P, F, f, p, async () => {
29
+ performance.now() - I > 30 && (await new Promise((e) => setTimeout(e, 0)), I = performance.now()), y?.throwIfAborted();
30
+ });
31
+ for (let n = 0; n < O; n++) j[n * t.length + e] = P[n];
32
+ }
33
+ let L = t.length;
34
+ for (let e = 0; e < O; e++) {
35
+ let t = 0;
36
+ for (let n = 0; n < L; n++) {
37
+ let r = j[e * L + n];
38
+ j[e * L + n] = r > 0 ? r : 0, t += j[e * L + n];
39
+ }
40
+ for (let n = 0; n < L; n++) j[e * L + n] < _ * t && (j[e * L + n] = 0);
41
+ t = 0;
42
+ for (let n = 0; n < L; n++) t += j[e * L + n];
43
+ if (t > 0) for (let n = 0; n < L; n++) j[e * L + n] /= t;
44
+ else j[e * L + w.first[e]] = 1;
45
+ }
46
+ for (let e = 0; e < x.vertexCount; e++) A.values.set(j.subarray(x.point[e] * L, x.point[e] * L + L), e * L);
47
+ return A;
48
+ }
49
+ async function m(e) {
50
+ if (!e.triangles.length) return () => !0;
51
+ let t;
52
+ try {
53
+ t = await import("@margoengine/bvh");
54
+ } catch (e) {
55
+ throw new f("unsupported", `Bone heat visibility needs @margoengine/bvh (${String(e)}); install it, or pass visibility: false`);
56
+ }
57
+ let n = t.MeshBVH.build({
58
+ positions: e.positions,
59
+ indices: e.triangles
60
+ }), r = [
61
+ 0,
62
+ 0,
63
+ 0
64
+ ];
65
+ return (e, t) => {
66
+ for (let n = 0; n < 3; n++) r[n] = e[n] + (t[n] - e[n]) * .001;
67
+ return r[0] === t[0] && r[1] === t[1] && r[2] === t[2] || !n.intersectsSegment(r, t);
68
+ };
69
+ }
70
+ function h(e, t, n, r, i) {
71
+ let a = e.positions, s = a.length / 3, c = n.owners.length, l = new Float64Array(s), u = new Int32Array(s), f = new Int32Array(s * 4).fill(-1), p = new Int32Array(c), m = new Float64Array(c), h = /* @__PURE__ */ new Float64Array(3), g = [
72
+ 0,
73
+ 0,
74
+ 0
75
+ ], _ = [
76
+ 0,
77
+ 0,
78
+ 0
79
+ ], v = (.001 * e.size) ** 2, y = d(e), b = /* @__PURE__ */ new Set(), x = (e, t) => {
80
+ let s = a[e * 3], d = a[e * 3 + 1], y = a[e * 3 + 2];
81
+ for (let e = 0; e < c; e++) p[e] = e, m[e] = o(n.points, e, s, d, y);
82
+ p.sort((e, t) => m[e] - m[t]);
83
+ let b = -1;
84
+ for (let e = 0; e < c; e++) {
85
+ let i = p[e];
86
+ if (!(t && r && (o(n.points, i, s, d, y, h), g[0] = s, g[1] = d, g[2] = y, _[0] = h[0], _[1] = h[1], _[2] = h[2], !r(g, _)))) {
87
+ b = i;
88
+ break;
89
+ }
90
+ }
91
+ if (b < 0) return !1;
92
+ let x = Math.max(m[b], v);
93
+ l[e] = i / x, u[e] = n.owners[b];
94
+ let S = 0;
95
+ for (let i = 0; i < c && S < 4; i++) {
96
+ let a = p[i];
97
+ if (m[a] > m[b] * 1.002 + v) break;
98
+ let c = n.owners[a], l = !1;
99
+ for (let t = 0; t < S; t++) f[e * 4 + t] === c && (l = !0);
100
+ l || t && r && a !== b && (o(n.points, a, s, d, y, h), _[0] = h[0], _[1] = h[1], _[2] = h[2], !r(g, _)) || (f[e * 4 + S++] = c);
101
+ }
102
+ return !0;
103
+ };
104
+ for (let e = 0; e < s; e++) x(e, !0) && b.add(y[e]);
105
+ for (let e = 0; e < s; e++) b.has(y[e]) || x(e, !1);
106
+ let S = [];
107
+ for (let e = 0; e < f.length; e++) f[e] >= 0 && S.push(f[e]);
108
+ return {
109
+ heatDiagonal: l,
110
+ nearest: {
111
+ owners: S,
112
+ first: u,
113
+ share(e, t) {
114
+ if (!l[e]) return 0;
115
+ let n = 0, r = !1;
116
+ for (let i = 0; i < 4; i++) {
117
+ let a = f[e * 4 + i];
118
+ if (a < 0) break;
119
+ n++, a === t && (r = !0);
120
+ }
121
+ return r ? 1 / n : 0;
122
+ }
123
+ },
124
+ jointCount: t
125
+ };
126
+ }
127
+ function g(e) {
128
+ return {
129
+ r: new Float64Array(e),
130
+ z: new Float64Array(e),
131
+ p: new Float64Array(e),
132
+ q: new Float64Array(e),
133
+ inverse: new Float64Array(e)
134
+ };
135
+ }
136
+ function _(e, t, n, r) {
137
+ let { offsets: i, columns: a, values: o, diagonal: s } = e;
138
+ for (let e = 0; e < n.length; e++) {
139
+ let c = (s[e] + t[e]) * n[e];
140
+ for (let t = i[e]; t < i[e + 1]; t++) c += o[t] * n[a[t]];
141
+ r[e] = c;
142
+ }
143
+ }
144
+ async function v(e, t, n, r, i, a, o, s) {
145
+ let { r: c, z: l, p: u, q: d, inverse: p } = i, m = r.length;
146
+ for (let n = 0; n < m; n++) p[n] = 1 / (e.diagonal[n] + t[n]);
147
+ _(e, t, r, d);
148
+ let h = 0, g = 0;
149
+ for (let e = 0; e < m; e++) c[e] = n[e] - d[e], l[e] = c[e] * p[e], u[e] = l[e], g += c[e] * l[e], h += n[e] * n[e];
150
+ if (h = Math.sqrt(h), !(h > 0)) r.fill(0);
151
+ else {
152
+ for (let n = 0; n < o; n++) {
153
+ let i = 0;
154
+ for (let e = 0; e < m; e++) i = Math.max(i, Math.abs(l[e]));
155
+ if (i <= a) return;
156
+ n % 32 == 31 && await s(), _(e, t, u, d);
157
+ let o = 0;
158
+ for (let e = 0; e < m; e++) o += u[e] * d[e];
159
+ if (!(o > 0)) return;
160
+ let f = g / o, h = 0;
161
+ for (let e = 0; e < m; e++) r[e] += f * u[e], c[e] -= f * d[e], l[e] = c[e] * p[e], h += c[e] * l[e];
162
+ let v = h / g;
163
+ g = h;
164
+ for (let e = 0; e < m; e++) u[e] = l[e] + v * u[e];
165
+ }
166
+ throw new f("failed", `Bone heat did not converge in ${o} iterations; raise maxIterations or tolerance, or remesh slivers`);
167
+ }
168
+ }
169
+ //#endregion
170
+ //#region src/paint.ts
171
+ var y = class {
172
+ constructor(t, n, r = {}) {
173
+ this.weights = t;
174
+ let i = c(n, r.weld);
175
+ if (i.vertexCount !== t?.vertexCount) throw RangeError(`WeightPainter mesh has ${i.vertexCount} vertices but the weights ${t?.vertexCount}; pair them`);
176
+ if (r.parents !== void 0) {
177
+ if (!Array.isArray(r.parents) || r.parents.length !== t.boneCount) throw RangeError(`WeightPainter parents needs one entry per bone (${t.boneCount})`);
178
+ this.parents = r.parents;
179
+ }
180
+ this.locked = r.locked ?? [], e(t.boneCount, this.locked), this.point = i.point, this.positions = i.positions, {offsets: this.offsets, columns: this.columns} = u(i);
181
+ let a = i.positions.length / 3, o = new Int32Array(a + 1);
182
+ for (let e = 0; e < i.point.length; e++) o[i.point[e] + 1]++;
183
+ for (let e = 0; e < a; e++) o[e + 1] += o[e];
184
+ this.memberOffsets = o.slice(), this.members = new Int32Array(i.point.length);
185
+ for (let e = 0; e < i.point.length; e++) this.members[o[i.point[e]]++] = e;
186
+ }
187
+ stroke(n) {
188
+ let { mode: r, center: i, radius: a } = n ?? {}, o = n.strength ?? .5, s = n.falloff ?? "smooth", c = n.value ?? 1, l = this.weights.boneCount;
189
+ if (![
190
+ "add",
191
+ "subtract",
192
+ "replace",
193
+ "smooth"
194
+ ].includes(r)) throw RangeError(`Brush mode ${String(r)} must be add, subtract, replace or smooth`);
195
+ if (!i || i.length !== 3 || !i.every(Number.isFinite)) throw RangeError("Brush center must be three finite numbers");
196
+ if (!(a > 0 && a < Infinity)) throw RangeError("Brush radius must be finite and above 0");
197
+ if (!(o >= 0 && o <= 1)) throw RangeError("Brush strength must be from 0 to 1");
198
+ if (!(c >= 0 && c <= 1)) throw RangeError("Brush value must be from 0 to 1");
199
+ if (![
200
+ "smooth",
201
+ "linear",
202
+ "constant"
203
+ ].includes(s)) throw RangeError("Brush falloff must be smooth, linear or constant");
204
+ let u = n.bone ?? -1;
205
+ if (r !== "smooth" && !(Number.isInteger(u) && u >= 0 && u < l)) throw RangeError(`Brush bone ${n.bone} must be one of the ${l} bones`);
206
+ let d = e(l, this.locked);
207
+ if (r !== "smooth" && d[u]) throw RangeError(`Bone ${u} is locked; unlock it to paint it`);
208
+ let f = this.positions, p = [], m = [];
209
+ for (let e = 0; e < f.length / 3; e++) {
210
+ let t = Math.hypot(f[e * 3] - i[0], f[e * 3 + 1] - i[1], f[e * 3 + 2] - i[2]) / a;
211
+ if (t >= 1) continue;
212
+ let n = s === "constant" ? 1 : s === "linear" ? 1 - t : 1 - t * t * (3 - 2 * t);
213
+ n * o > 0 && (p.push(e), m.push(n * o));
214
+ }
215
+ let h = this.weights.values, g = new Float32Array(p.length * l), _ = (e) => this.members[this.memberOffsets[e]] * l;
216
+ p.forEach((e, t) => g.set(h.subarray(_(e), _(e) + l), t * l));
217
+ let v = new Float32Array(g);
218
+ p.forEach((e, n) => {
219
+ let i = n * l, a = m[n];
220
+ if (r === "smooth") {
221
+ let n = this.offsets[e], r = this.offsets[e + 1];
222
+ if (r === n) return;
223
+ for (let e = 0; e < l; e++) {
224
+ if (d[e]) continue;
225
+ let t = 0;
226
+ for (let i = n; i < r; i++) t += h[_(this.columns[i]) + e];
227
+ t /= r - n, v[i + e] += (t - v[i + e]) * a;
228
+ }
229
+ t(v, i, l, d);
230
+ return;
231
+ }
232
+ let o = v[i + u], s = r === "add" ? o + a : r === "subtract" ? o - a : o + (c - o) * a, f = 0, p = 0;
233
+ for (let e = 0; e < l; e++) e !== u && (d[e] ? f += v[i + e] : p += v[i + e]);
234
+ s = Math.min(Math.max(s, 0), Math.max(0, 1 - f));
235
+ let g = Math.max(0, 1 - f - s);
236
+ if (p > 0) for (let e = 0; e < l; e++) e !== u && !d[e] && (v[i + e] *= g / p);
237
+ else if (g > 0) {
238
+ let e = this.parents?.[u] ?? -1;
239
+ e >= 0 && e !== u && !d[e] ? v[i + e] = g : s = Math.max(0, 1 - f);
240
+ }
241
+ v[i + u] = s;
242
+ });
243
+ let y = [];
244
+ p.forEach((e, t) => {
245
+ for (let n = this.memberOffsets[e]; n < this.memberOffsets[e + 1]; n++) {
246
+ let e = this.members[n];
247
+ h.set(v.subarray(t * l, t * l + l), e * l), y.push(e);
248
+ }
249
+ });
250
+ let b = Uint32Array.from(y), x = new Float32Array(b.length * l), S = 0;
251
+ return p.forEach((e, t) => {
252
+ for (let n = this.memberOffsets[e]; n < this.memberOffsets[e + 1]; n++) x.set(g.subarray(t * l, t * l + l), S++ * l);
253
+ }), {
254
+ vertices: b,
255
+ undo: () => {
256
+ b.forEach((e, t) => h.set(x.subarray(t * l, t * l + l), e * l));
257
+ }
258
+ };
259
+ }
260
+ smoothAll({ iterations: n = 1, strength: r = .5 } = {}) {
261
+ if (!Number.isInteger(n) || n < 1 || n > 1e3) throw RangeError("Smooth iterations must be an integer from 1 to 1,000");
262
+ if (!(r >= 0 && r <= 1)) throw RangeError("Smooth strength must be from 0 to 1");
263
+ let i = this.weights.boneCount, a = this.weights.values, o = a.slice(), s = e(i, this.locked), c = this.positions.length / 3, l = (e) => this.members[this.memberOffsets[e]] * i, u = new Float32Array(c * i);
264
+ for (let e = 0; e < n; e++) {
265
+ for (let e = 0; e < c; e++) {
266
+ let n = e * i, o = this.offsets[e], c = this.offsets[e + 1];
267
+ if (u.set(a.subarray(l(e), l(e) + i), n), c !== o) {
268
+ for (let e = 0; e < i; e++) {
269
+ if (s[e]) continue;
270
+ let t = 0;
271
+ for (let n = o; n < c; n++) t += a[l(this.columns[n]) + e];
272
+ u[n + e] += (t / (c - o) - u[n + e]) * r;
273
+ }
274
+ t(u, n, i, s);
275
+ }
276
+ }
277
+ for (let e = 0; e < c; e++) for (let t = this.memberOffsets[e]; t < this.memberOffsets[e + 1]; t++) a.set(u.subarray(e * i, e * i + i), this.members[t] * i);
278
+ }
279
+ return {
280
+ vertices: Uint32Array.from({ length: this.weights.vertexCount }, (e, t) => t),
281
+ undo: () => a.set(o)
282
+ };
283
+ }
284
+ normalize() {
285
+ return this.weights.normalize({ locked: this.locked }), this;
286
+ }
287
+ pointOf(e) {
288
+ return this.point[e];
289
+ }
290
+ }, b = 16, x = {
291
+ unweighted: "have no weight; paint them or run boneHeatWeights",
292
+ "too-many-influences": "have more nonzero weights than allowed; export with toInfluences(4)",
293
+ "not-normalized": "have weights that don't sum to 1; call normalize()",
294
+ "negative-weight": "have negative weights; set them to 0 and call normalize()",
295
+ "non-finite": "have NaN or infinite weights; repaint or recompute them",
296
+ "invalid-joint": "name joints outside the skin; fix the joint indices or pass jointCount",
297
+ "duplicate-joint": "list one joint twice with nonzero weights; add the weights into one slot",
298
+ "degenerate-bone": "are degenerate (zero length, or a non-invertible bind matrix); move the joint or fix its scale"
299
+ };
300
+ function S(e) {
301
+ let { weights: t, maxInfluences: r = 4, tolerance: i = .001 } = e ?? {};
302
+ if (!Number.isInteger(r) || r < 1) throw RangeError("checkSkin maxInfluences must be a positive integer");
303
+ if (!(i >= 0 && i < 1)) throw RangeError("checkSkin tolerance must be from 0 to below 1");
304
+ let o, s, c, l;
305
+ if (t instanceof n) o = t.boneCount, s = null, c = t.values, l = e.jointCount ?? t.boneCount;
306
+ else {
307
+ if (o = t?.influences ?? 4, s = t?.joints, c = t?.weights, !Number.isInteger(o) || o < 1 || s?.length !== c?.length || s.length % o) throw TypeError(`checkSkin weights need equal-length joints and weights, ${o} per vertex`);
308
+ let n = 0;
309
+ for (let e = 0; e < s.length; e++) s[e] > n && (n = s[e]);
310
+ l = e.jointCount ?? n + 1;
311
+ }
312
+ if (!Number.isInteger(l) || l < 1) throw RangeError("checkSkin jointCount must be at least 1");
313
+ let u = c.length / o, d = /* @__PURE__ */ new Map(), f = (e, t, n = -1) => {
314
+ let r = d.get(e);
315
+ r || d.set(e, r = {
316
+ count: 0,
317
+ last: -1,
318
+ vertices: [],
319
+ bones: /* @__PURE__ */ new Set(),
320
+ counted: /* @__PURE__ */ new Set()
321
+ }), t >= 0 ? r.last !== t && (r.last = t, r.count++, r.vertices.length < b && r.vertices.push(t)) : r.counted.has(n) || (r.counted.add(n), r.count++), n >= 0 && r.bones.size < b && r.bones.add(n);
322
+ };
323
+ for (let e = 0; e < u; e++) {
324
+ let t = 0, n = 0, a = !1;
325
+ for (let r = 0; r < o; r++) {
326
+ let i = c[e * o + r];
327
+ if (s) {
328
+ let t = s[e * o + r];
329
+ if (!Number.isInteger(t) || t < 0 || t >= l) f("invalid-joint", e, t);
330
+ else if (i !== 0 && Number.isFinite(i)) for (let n = 0; n < r; n++) {
331
+ let r = c[e * o + n];
332
+ if (s[e * o + n] === t && r !== 0 && Number.isFinite(r)) {
333
+ f("duplicate-joint", e, t);
334
+ break;
335
+ }
336
+ }
337
+ }
338
+ Number.isFinite(i) ? (i < 0 && f("negative-weight", e), i !== 0 && n++, t += i) : (f("non-finite", e), a = !0);
339
+ }
340
+ a || (n === 0 ? f("unweighted", e) : Math.abs(t - 1) > i && f("not-normalized", e), n > r && f("too-many-influences", e));
341
+ }
342
+ if (e.joints !== void 0) {
343
+ a(e.joints);
344
+ let t = e.joints, n = [
345
+ Infinity,
346
+ Infinity,
347
+ Infinity
348
+ ], r = [
349
+ -Infinity,
350
+ -Infinity,
351
+ -Infinity
352
+ ];
353
+ for (let { position: e } of t) for (let t = 0; t < 3; t++) n[t] = Math.min(n[t], e[t]), r[t] = Math.max(r[t], e[t]);
354
+ let i = Math.hypot(r[0] - n[0], r[1] - n[1], r[2] - n[2]);
355
+ t.forEach((e, n) => {
356
+ if (e.parent < 0) return;
357
+ let r = t[e.parent].position, a = e.position;
358
+ Math.hypot(a[0] - r[0], a[1] - r[1], a[2] - r[2]) <= 1e-6 * i && f("degenerate-bone", -1, n);
359
+ });
360
+ }
361
+ let p = e.inverseBindMatrices;
362
+ if (p !== void 0) {
363
+ if (p?.length % 16 || !p.length) throw TypeError("checkSkin inverseBindMatrices need 16 per joint");
364
+ for (let e = 0; e < p.length / 16; e++) {
365
+ let t = Array.from({ length: 16 }, (t, n) => p[e * 16 + n]), n = t[0] * (t[5] * t[10] - t[9] * t[6]) - t[4] * (t[1] * t[10] - t[9] * t[2]) + t[8] * (t[1] * t[6] - t[5] * t[2]);
366
+ (!t.every(Number.isFinite) || Math.abs(n) < 1e-12) && f("degenerate-bone", -1, e);
367
+ }
368
+ }
369
+ let m = [...d].map(([e, t]) => {
370
+ let n = [...t.bones].sort((e, t) => e - t), r = e === "degenerate-bone" ? `${t.count} bone(s) (${n.join(", ")})` : `${t.count} vertex(es)`;
371
+ return {
372
+ code: e,
373
+ count: t.count,
374
+ vertices: t.vertices,
375
+ bones: n,
376
+ message: `${r} ${x[e]}`
377
+ };
378
+ });
379
+ return {
380
+ ok: m.length === 0,
381
+ vertexCount: u,
382
+ issues: m
383
+ };
384
+ }
385
+ function C(e) {
386
+ let t = S(e);
387
+ if (!t.ok) throw RangeError(`Skin is not ready to export: ${t.issues.map((e) => e.message).join("; ")}; fix them, then call assertSkin again`);
388
+ }
389
+ //#endregion
390
+ export { n as WeightMap, y as WeightPainter, C as assertSkin, p as boneHeatWeights, a as checkRig, S as checkSkin, r as rigJoints };
@@ -0,0 +1,44 @@
1
+ // @ts-ignore optional peer: its types apply when it is installed
2
+ import type { Animator } from '@margoengine/animator';
3
+ // @ts-ignore optional peer: its types apply when it is installed
4
+ import { type CCDJointLimit } from '@margoengine/animator/ccd';
5
+ type Quaternion = readonly [number, number, number, number];
6
+ /** One calibrated local rotation constraint, applied to an animation or to an IK chain. */
7
+ export interface PoseJointLimit {
8
+ /** Index in the pose or glTF model. */
9
+ readonly joint: number;
10
+ /** The neutral local rotation, [x, y, z, w], in the joint's authored axes. */
11
+ readonly neutral: Quaternion;
12
+ /** Limits relative to neutral. A cone must specify its local bone axis for a standalone pose. */
13
+ readonly limit: CCDJointLimit;
14
+ }
15
+ /**
16
+ * Projects the authored joints of a sampled pose into their calibrated ranges. Uses the same hinge, cone and Euler
17
+ * limits as the contact solver, so ordinary animation and contact obey the same anatomy. The layout is reusable and
18
+ * supports dense rigs without packing an entire skeleton into one IK chain.
19
+ */
20
+ export declare class PoseJointLimits {
21
+ readonly jointCount: number;
22
+ private readonly groups;
23
+ /**
24
+ * Compiles the joint limits once for a pose with `jointCount` bones.
25
+ * @throws RangeError for an invalid bone index, duplicate joint, rotation or joint count.
26
+ */
27
+ constructor(jointCount: number, limits: readonly PoseJointLimit[]);
28
+ /** Edits only the limited rotations in a local pose, with 10 values per joint (translation, rotation and scale). */
29
+ apply(local: Float64Array): void;
30
+ }
31
+ /**
32
+ * Applies one calibrated limit profile to an Animator after the pose and earlier solvers. Register after contact or
33
+ * look-at solvers if they must also obey these limits. Returns the remover.
34
+ */
35
+ export declare function addPoseJointLimits(animator: Animator, limits: readonly PoseJointLimit[]): () => void;
36
+ /**
37
+ * Moves excess axial twist from a joint into its direct parent while preserving the child's world rotation and origin.
38
+ * Used for a hand attached to an authored forearm: the forearm can pronate and the wrist's local twist stays within
39
+ * `[min,max]` radians around `neutral`. The parent must have a positive uniform scale. A zero-length offset is invalid.
40
+ * Returns the signed number of radians moved into the parent. Neighbouring child branches follow the parent as usual.
41
+ * @throws RangeError for invalid joint indices, rotations, scales, axis or range.
42
+ */
43
+ export declare function redistributeJointTwist(local: Float64Array, parents: readonly number[], joint: number, neutral: Quaternion, range: readonly [number, number]): number;
44
+ export {};
@@ -0,0 +1,74 @@
1
+ import { axisAngleToQuaternion as e, conjugateQuaternion as t, multiplyQuaternions as n, normalizeQuaternion as r, rotateByQuaternion as i } from "@margoengine/math/quat";
2
+ import { CCDSolver as a } from "@margoengine/animator/ccd";
3
+ import { dot as o, length as s, normalize as c } from "@margoengine/math/vec3";
4
+ //#region src/joint-limits.ts
5
+ function l(e, t) {
6
+ if (!(e?.length === 4 && Array.from(e).every(Number.isFinite) && Math.hypot(...Array.from(e)) > 0)) throw RangeError(`${t} needs a finite, nonzero quaternion`);
7
+ return r(e);
8
+ }
9
+ var u = class {
10
+ constructor(e, t) {
11
+ if (this.jointCount = e, this.groups = [], !Number.isInteger(e) || e < 1 || e > 65536) throw RangeError("Pose joint count must be an integer from 1 to 65,536");
12
+ let n = /* @__PURE__ */ new Set();
13
+ for (let r = 0; r < t.length; r += 256) {
14
+ let i = t.slice(r, r + 256), o = new a(i.map(() => [
15
+ 0,
16
+ 0,
17
+ 0
18
+ ])), s = i.map(({ joint: t, neutral: r, limit: i }, a) => {
19
+ if (!Number.isInteger(t) || t < 0 || t >= e || n.has(t)) throw RangeError("Pose limits must name distinct joint indices in the pose");
20
+ if (i.type === "cone" && !i.axis) throw RangeError("Pose cone limits need an explicit local axis");
21
+ return n.add(t), o.rest.set(l(r, "Pose limit neutral rotation"), a * 4), o.setLimit(a, i), t * 10 + 3;
22
+ });
23
+ this.groups.push({
24
+ offsets: s,
25
+ solver: o
26
+ });
27
+ }
28
+ }
29
+ apply(e) {
30
+ if (!(e instanceof Float64Array) || e.length !== this.jointCount * 10) throw TypeError("Pose joint limits need a Float64Array with 10 values per joint");
31
+ for (let { offsets: t, solver: n } of this.groups) t.forEach((t, r) => n.rotations.set(l(e.subarray(t, t + 4), "Sampled pose rotation"), r * 4)), n.projectRotations();
32
+ for (let { offsets: t, solver: n } of this.groups) t.forEach((t, r) => e.set(n.rotations.subarray(r * 4, r * 4 + 4), t));
33
+ }
34
+ };
35
+ function d(e, t) {
36
+ let n = e.animation.model.nodes, r = new u(n.length, t), i = e.animation.model.root.engine.store, a = i.transforms, o = new Float64Array(n.length * 10), s = [
37
+ 0,
38
+ 0,
39
+ 0,
40
+ 1
41
+ ], c = t.map(({ joint: e }) => ({
42
+ node: n[e],
43
+ at: e * 10 + 3
44
+ }));
45
+ return e.addSolver(() => {
46
+ for (let { node: e, at: t } of c) {
47
+ let { id: n } = e;
48
+ o[t] = a.qx[n], o[t + 1] = a.qy[n], o[t + 2] = a.qz[n], o[t + 3] = a.qw[n];
49
+ }
50
+ r.apply(o);
51
+ for (let { node: t, at: n } of c) {
52
+ for (let e = 0; e < 4; e++) s[e] = o[n + e];
53
+ e.writeNodeRotation(t, s);
54
+ }
55
+ i.tick(!1);
56
+ });
57
+ }
58
+ function f(a, u, d, f, p) {
59
+ if (!(a instanceof Float64Array) || a.length !== u.length * 10 || !Number.isInteger(d) || d < 0 || d >= u.length) throw RangeError("Twist redistribution needs a valid joint in a local pose");
60
+ let m = u[d];
61
+ if (!Number.isInteger(m) || m < 0 || m >= u.length || m === d) throw RangeError("Twist redistribution needs a valid direct parent");
62
+ let [h, g] = p;
63
+ if (!(h >= -Math.PI && g <= Math.PI && h <= g)) throw RangeError("Twist range must be ordered within [-π, π]");
64
+ let _ = d * 10, v = m * 10, y = a[v + 7];
65
+ if (!(y > 0 && Number.isFinite(y) && a[v + 8] === y && a[v + 9] === y)) throw RangeError("Twist redistribution needs a finite positive uniform parent scale");
66
+ let b = a.subarray(_, _ + 3), x = s(b);
67
+ if (!(x > 1e-9 && Number.isFinite(x))) throw RangeError("Twist redistribution needs a nonzero child offset");
68
+ let S = c(b), C = l(f, "Neutral rotation"), w = l(a.subarray(v + 3, v + 7), "Parent rotation"), T = l(a.subarray(_ + 3, _ + 7), "Child rotation"), E = t(C), D = n(E, T), O = i(S, E), k = o(D, O), A = Math.hypot(k, D[3]) < 1e-9 ? 0 : 2 * Math.atan2(k, D[3]), j = Math.atan2(Math.sin(A), Math.cos(A)), M = j - Math.max(h, Math.min(g, j));
69
+ if (Math.abs(M) <= 1e-12) return 0;
70
+ let N = e(S, M);
71
+ return a.set(r(n(w, N)), v + 3), a.set(r(n(t(N), T)), _ + 3), M;
72
+ }
73
+ //#endregion
74
+ export { u as PoseJointLimits, d as addPoseJointLimits, f as redistributeJointTwist };
@@ -0,0 +1,99 @@
1
+ import type { Vec3 } from '@margoengine/math';
2
+ /** An anatomical landmark carried by a bone. */
3
+ export interface CollisionLandmark {
4
+ /** Bone index in the skeleton. */
5
+ readonly joint: number;
6
+ /** Offset in the bone's local frame, default the joint origin. */
7
+ readonly offset?: Vec3;
8
+ }
9
+ /** A capsule or sphere carried by the body of a human or animal. */
10
+ export interface BodyCollisionVolume {
11
+ /** First landmark of the body volume, typically on the chest, pelvis, head or another limb. */
12
+ readonly start: CollisionLandmark;
13
+ /** Second landmark. Omit for a sphere. */
14
+ readonly end?: CollisionLandmark;
15
+ /** Radius in skeleton space. Use multiple overlapping volumes for a tapered silhouette. */
16
+ readonly radius: number;
17
+ }
18
+ /** A capsule around one limb link. Its slots index the packed candidate positions, not the skeleton. */
19
+ export interface LimbCollisionLink {
20
+ /** First joint slot, starting from zero. */
21
+ readonly start: number;
22
+ /** Second joint slot, starting from zero. The same slot gives a sphere. */
23
+ readonly end: number;
24
+ /** Radius of the limb, including clothing or fur, in skeleton units. */
25
+ readonly radius: number;
26
+ /** Optional fraction range of the segment to check. Use the proximal trim for the shared shoulder or hip. Default [0, 1]. */
27
+ readonly range?: readonly [number, number];
28
+ }
29
+ /** Bounds a joint direction against a body-relative axis, for example shoulder extension behind the chest. */
30
+ export interface LimbDirectionLimit {
31
+ /** Origin slot in the proposed chain. */
32
+ readonly start: number;
33
+ /** Direction slot in the proposed chain, distinct from start. */
34
+ readonly end: number;
35
+ /** Bone that carries the forward axis, for example the upper chest or pelvis. */
36
+ readonly reference: number;
37
+ /** Direction in the reference bone's local rest axes. */
38
+ readonly forward: Vec3;
39
+ /** Maximum angle behind the plane normal to forward. In radians from 0 to π/2, default 0.75. */
40
+ readonly maxBackwards?: number;
41
+ }
42
+ /** One collision sample for a swept check. Obtain it from {@link LimbCollisionRig.snapshot}. */
43
+ export interface LimbCollisionSample {
44
+ /** Capsule endpoints of the posed body in skeleton space, six numbers per volume. */
45
+ readonly body: Float64Array;
46
+ /** Capsule endpoints of the candidate limb in skeleton space, six numbers per link. */
47
+ readonly limb: Float64Array;
48
+ /** Direction vector and body axis per limit, six numbers each. Older samples may omit this channel. */
49
+ readonly directions?: Float64Array;
50
+ }
51
+ /** Precision and work limits for a check between two collision samples. */
52
+ export interface LimbSweepOptions {
53
+ /** Gap that counts as a touch, in skeleton units. Default 0.0001. */
54
+ readonly tolerance?: number;
55
+ /** Positive checks budget, 1 to 4096. Default 128. */
56
+ readonly maxSteps?: number;
57
+ }
58
+ /** Result of advancing the moving proxies and joint directions toward contact. */
59
+ export interface LimbSweepResult {
60
+ /** True when all motion along the supplied proxy paths was clear. */
61
+ readonly clear: boolean;
62
+ /** Time fraction at the first conservative hit, the work limit, or 1 when clear. */
63
+ readonly time: number;
64
+ /** Smallest signed capsule separation or direction margin measured so far, in skeleton units. */
65
+ readonly clearance: number;
66
+ /** True when certification needs more steps or a sample resolving an opposed pair of axes. */
67
+ readonly exhausted: boolean;
68
+ }
69
+ /**
70
+ * Self-collision for a soft-bodied rig using authored anatomical landmarks and link thickness.
71
+ * Body volumes follow their joints. The collision function can be used as a deterministic IK constraint.
72
+ */
73
+ export declare class LimbCollisionRig {
74
+ private readonly parents;
75
+ private readonly order;
76
+ private readonly volumes;
77
+ private readonly links;
78
+ private readonly limits;
79
+ private readonly slots;
80
+ private readonly body;
81
+ private readonly candidate;
82
+ private axes;
83
+ private posed;
84
+ /** Configures the volumes and link ranges once, for a human, quadruped or other skeleton. */
85
+ constructor(parents: readonly number[], volumes: readonly BodyCollisionVolume[], links: readonly LimbCollisionLink[], limits?: readonly LimbDirectionLimit[]);
86
+ /** Poses the body volumes from the current skeleton before checking a limb. */
87
+ setBodyPose(local: ArrayLike<number>): void;
88
+ /** Minimum signed gap for the proposed pose. Negative rejects a collision or an anatomical direction violation. */
89
+ readonly clearance: (positions: ArrayLike<number>) => number;
90
+ /** Captures the current obstacle shape and a candidate limb for between-frame checks. */
91
+ snapshot(positions: ArrayLike<number>): LimbCollisionSample;
92
+ /**
93
+ * Tests linearly moving capsule endpoints and joint vectors. Body axes follow their shortest spherical arcs.
94
+ * Include an intermediate pose for opposite axes or curved limb paths. Two legacy samples check capsules alone.
95
+ */
96
+ sweep(from: LimbCollisionSample, to: LimbCollisionSample, { tolerance, maxSteps }?: LimbSweepOptions): LimbSweepResult;
97
+ private packLimb;
98
+ private measure;
99
+ }
@@ -0,0 +1,67 @@
1
+ import { n as e } from "./errors-D8rc8kzg.js";
2
+ //#region ../shared/cleanup.js
3
+ var t = class {
4
+ constructor(...e) {
5
+ this.failed = e.length > 0, this.error = e[0];
6
+ }
7
+ run(e) {
8
+ try {
9
+ e();
10
+ } catch (e) {
11
+ this.failed || (this.error = e), this.failed = !0;
12
+ }
13
+ return this;
14
+ }
15
+ finish() {
16
+ if (this.failed) throw this.error;
17
+ }
18
+ };
19
+ //#endregion
20
+ //#region ../shared/loading.js
21
+ async function n(e, { maxBytes: n, signal: r, label: i = "Asset", output: a = null, expected: o = 0 }) {
22
+ if (!Number.isSafeInteger(n) || n < 0 || a !== null && (!(a instanceof Uint8Array) || a.length !== n)) throw RangeError("Invalid asset byte budget; pass maxBytes as an integer");
23
+ if (r?.throwIfAborted(), !e) throw TypeError(`Empty ${i} response; check the URL`);
24
+ let s = e.getReader(), c = [], l = 0, u = a, d = new t(), f = (e) => {
25
+ try {
26
+ Promise.resolve(s.cancel(e)).catch(() => {});
27
+ } catch {}
28
+ }, p = () => f(r.reason);
29
+ r?.addEventListener("abort", p, { once: !0 });
30
+ try {
31
+ for (!a && Number.isSafeInteger(o) && o > 0 && o <= n && (u = new Uint8Array(o));;) {
32
+ r?.throwIfAborted();
33
+ let { done: e, value: t } = await s.read();
34
+ if (r?.throwIfAborted(), e) break;
35
+ if (!(t instanceof Uint8Array)) throw TypeError(`${i} stream requires byte chunks`);
36
+ if (t.byteLength > n - l) throw RangeError(`${i} byte budget exceeded; raise maxBytes`);
37
+ u && t.length <= u.length - l ? u.set(t, l) : (u && c.push(u.subarray(0, l)), u = null, c.push(t.length < t.buffer.byteLength || !(t.buffer instanceof ArrayBuffer) ? t.slice() : t)), l += t.byteLength;
38
+ }
39
+ } catch (e) {
40
+ f(e), d = new t(e);
41
+ }
42
+ if (d.run(() => r?.removeEventListener("abort", p)).run(() => s.releaseLock()).finish(), a) return a.subarray(0, l);
43
+ if (u) return l < u.length ? u.slice(0, l) : u;
44
+ let m = new Uint8Array(l), h = 0;
45
+ for (let e of c) m.set(e, h), h += e.length;
46
+ return m;
47
+ }
48
+ async function r(t, r) {
49
+ try {
50
+ if (r.signal?.throwIfAborted(), !t.ok) throw e("failed", `${r.label ?? "Asset"} request failed: HTTP ${t.status}; check the URL and that the server serves it`);
51
+ let n = Number(t.headers.get("content-length"));
52
+ if (Number.isFinite(n) && n > r.maxBytes) throw RangeError(`${r.label ?? "Asset"} byte budget exceeded; raise maxBytes`);
53
+ let i = t.headers.get("content-encoding");
54
+ (!i || i === "identity") && (r = {
55
+ ...r,
56
+ expected: n
57
+ });
58
+ } catch (e) {
59
+ try {
60
+ Promise.resolve(t.body?.cancel(e)).catch(() => {});
61
+ } catch {}
62
+ throw e;
63
+ }
64
+ return n(t.body, r);
65
+ }
66
+ //#endregion
67
+ export { r as t };