motionary 10.6.0 → 10.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (153) hide show
  1. package/AGENTS.md +2 -0
  2. package/CHANGELOG.md +36 -0
  3. package/README.md +77 -4
  4. package/bin/motionary-mcp.mjs +160 -11
  5. package/dist/chunks/{anim-image-DECLkPH4.cjs → anim-image-BzTQa2k3.cjs} +2 -2
  6. package/dist/chunks/{anim-image-DECLkPH4.cjs.map → anim-image-BzTQa2k3.cjs.map} +1 -1
  7. package/dist/chunks/{anim-image-DNghy017.js → anim-image-iD646Q7i.js} +2 -2
  8. package/dist/chunks/{anim-image-DNghy017.js.map → anim-image-iD646Q7i.js.map} +1 -1
  9. package/dist/chunks/{keyframes-F6vp6tZZ.js → keyframes-B4zefz0k.js} +2 -2
  10. package/dist/chunks/{keyframes-F6vp6tZZ.js.map → keyframes-B4zefz0k.js.map} +1 -1
  11. package/dist/chunks/{keyframes-CbUZjD_5.cjs → keyframes-BlOyB1PP.cjs} +2 -2
  12. package/dist/chunks/{keyframes-CbUZjD_5.cjs.map → keyframes-BlOyB1PP.cjs.map} +1 -1
  13. package/dist/chunks/{registry-dr1CPTk1.cjs → registry-BZxDVL3h.cjs} +2 -2
  14. package/dist/chunks/{registry-dr1CPTk1.cjs.map → registry-BZxDVL3h.cjs.map} +1 -1
  15. package/dist/chunks/{registry-D8LAoXI-.js → registry-Bkt3-3ET.js} +3 -3
  16. package/dist/chunks/{registry-D8LAoXI-.js.map → registry-Bkt3-3ET.js.map} +1 -1
  17. package/dist/chunks/runtime-link-CUiZ8lbE.cjs +38 -0
  18. package/dist/chunks/runtime-link-CUiZ8lbE.cjs.map +1 -0
  19. package/dist/chunks/runtime-link-c13gskBZ.js +36 -0
  20. package/dist/chunks/runtime-link-c13gskBZ.js.map +1 -0
  21. package/dist/chunks/{ticker-DaAlEyOd.cjs → ticker-BfxAECfO.cjs} +2 -2
  22. package/dist/chunks/{ticker-DaAlEyOd.cjs.map → ticker-BfxAECfO.cjs.map} +1 -1
  23. package/dist/chunks/{ticker-Do9bGsaV.js → ticker-ZtweD3U4.js} +2 -2
  24. package/dist/chunks/{ticker-Do9bGsaV.js.map → ticker-ZtweD3U4.js.map} +1 -1
  25. package/dist/chunks/{tween-CmkdSyaC.cjs → tween--MD-39y0.cjs} +2 -2
  26. package/dist/chunks/{tween-CmkdSyaC.cjs.map → tween--MD-39y0.cjs.map} +1 -1
  27. package/dist/chunks/{tween-BzCGq_Ba.js → tween-DACdkLyO.js} +2 -2
  28. package/dist/chunks/{tween-BzCGq_Ba.js.map → tween-DACdkLyO.js.map} +1 -1
  29. package/dist/components/ai.cjs +314 -0
  30. package/dist/components/ai.cjs.map +1 -0
  31. package/dist/components/ai.d.cts +58 -0
  32. package/dist/components/ai.d.ts +58 -0
  33. package/dist/components/ai.js +311 -0
  34. package/dist/components/ai.js.map +1 -0
  35. package/dist/components/snap-carousel.cjs +216 -0
  36. package/dist/components/snap-carousel.cjs.map +1 -0
  37. package/dist/components/snap-carousel.d.cts +80 -0
  38. package/dist/components/snap-carousel.d.ts +80 -0
  39. package/dist/components/snap-carousel.js +214 -0
  40. package/dist/components/snap-carousel.js.map +1 -0
  41. package/dist/components/widgets.cjs +626 -268
  42. package/dist/components/widgets.cjs.map +1 -1
  43. package/dist/components/widgets.d.cts +515 -39
  44. package/dist/components/widgets.d.ts +515 -39
  45. package/dist/components/widgets.js +617 -262
  46. package/dist/components/widgets.js.map +1 -1
  47. package/dist/llms-full.txt +191 -6
  48. package/dist/llms.txt +10 -3
  49. package/dist/manifest.json +497 -19
  50. package/dist/runtime/drag-snap.cjs +269 -0
  51. package/dist/runtime/drag-snap.cjs.map +1 -0
  52. package/dist/runtime/drag-snap.d.cts +109 -0
  53. package/dist/runtime/drag-snap.d.ts +109 -0
  54. package/dist/runtime/drag-snap.iife.js +2 -0
  55. package/dist/runtime/drag-snap.iife.js.map +1 -0
  56. package/dist/runtime/drag-snap.js +261 -0
  57. package/dist/runtime/drag-snap.js.map +1 -0
  58. package/dist/runtime/format-apng.cjs +4 -4
  59. package/dist/runtime/format-apng.js +4 -4
  60. package/dist/runtime/format-css.cjs +4 -4
  61. package/dist/runtime/format-css.js +4 -4
  62. package/dist/runtime/format-gif.cjs +4 -4
  63. package/dist/runtime/format-gif.js +4 -4
  64. package/dist/runtime/format-gltf.cjs +37 -18
  65. package/dist/runtime/format-gltf.cjs.map +1 -1
  66. package/dist/runtime/format-gltf.d.cts +18 -2
  67. package/dist/runtime/format-gltf.d.ts +18 -2
  68. package/dist/runtime/format-gltf.iife.js +1 -1
  69. package/dist/runtime/format-gltf.iife.js.map +1 -1
  70. package/dist/runtime/format-gltf.js +37 -18
  71. package/dist/runtime/format-gltf.js.map +1 -1
  72. package/dist/runtime/format-motion.cjs +4 -4
  73. package/dist/runtime/format-motion.js +4 -4
  74. package/dist/runtime/format-obj.cjs +1 -1
  75. package/dist/runtime/format-obj.d.cts +2 -0
  76. package/dist/runtime/format-obj.d.ts +2 -0
  77. package/dist/runtime/format-obj.iife.js.map +1 -1
  78. package/dist/runtime/format-obj.js +1 -1
  79. package/dist/runtime/format-scene.cjs +241 -0
  80. package/dist/runtime/format-scene.cjs.map +1 -0
  81. package/dist/runtime/format-scene.d.cts +349 -0
  82. package/dist/runtime/format-scene.d.ts +349 -0
  83. package/dist/runtime/format-scene.iife.js +2 -0
  84. package/dist/runtime/format-scene.iife.js.map +1 -0
  85. package/dist/runtime/format-scene.js +233 -0
  86. package/dist/runtime/format-scene.js.map +1 -0
  87. package/dist/runtime/format-sprite.cjs +3 -3
  88. package/dist/runtime/format-sprite.js +3 -3
  89. package/dist/runtime/format-svg.cjs +3 -3
  90. package/dist/runtime/format-svg.js +3 -3
  91. package/dist/runtime/format-webp.cjs +4 -4
  92. package/dist/runtime/format-webp.js +4 -4
  93. package/dist/runtime/gl.cjs +17 -4
  94. package/dist/runtime/gl.cjs.map +1 -1
  95. package/dist/runtime/gl.d.cts +2 -0
  96. package/dist/runtime/gl.d.ts +2 -0
  97. package/dist/runtime/gl.iife.js +1 -1
  98. package/dist/runtime/gl.iife.js.map +1 -1
  99. package/dist/runtime/gl.js +17 -4
  100. package/dist/runtime/gl.js.map +1 -1
  101. package/dist/runtime/gltf-anim.cjs +251 -0
  102. package/dist/runtime/gltf-anim.cjs.map +1 -0
  103. package/dist/runtime/gltf-anim.d.cts +216 -0
  104. package/dist/runtime/gltf-anim.d.ts +216 -0
  105. package/dist/runtime/gltf-anim.iife.js +2 -0
  106. package/dist/runtime/gltf-anim.iife.js.map +1 -0
  107. package/dist/runtime/gltf-anim.js +243 -0
  108. package/dist/runtime/gltf-anim.js.map +1 -0
  109. package/dist/runtime/physics.cjs +739 -0
  110. package/dist/runtime/physics.cjs.map +1 -0
  111. package/dist/runtime/physics.d.cts +250 -0
  112. package/dist/runtime/physics.d.ts +250 -0
  113. package/dist/runtime/physics.iife.js +2 -0
  114. package/dist/runtime/physics.iife.js.map +1 -0
  115. package/dist/runtime/physics.js +731 -0
  116. package/dist/runtime/physics.js.map +1 -0
  117. package/dist/runtime/scroll.cjs +2 -2
  118. package/dist/runtime/scroll.js +2 -2
  119. package/dist/runtime/smooth.cjs +1 -1
  120. package/dist/runtime/smooth.js +1 -1
  121. package/dist/runtime/text.cjs +1 -1
  122. package/dist/runtime/text.js +1 -1
  123. package/dist/runtime/vector.cjs +421 -11
  124. package/dist/runtime/vector.cjs.map +1 -1
  125. package/dist/runtime/vector.d.cts +20 -4
  126. package/dist/runtime/vector.d.ts +20 -4
  127. package/dist/runtime/vector.iife.js +1 -1
  128. package/dist/runtime/vector.iife.js.map +1 -1
  129. package/dist/runtime/vector.js +421 -12
  130. package/dist/runtime/vector.js.map +1 -1
  131. package/dist/runtime.cjs +3 -3
  132. package/dist/runtime.d.cts +1 -1
  133. package/dist/runtime.d.ts +1 -1
  134. package/dist/runtime.iife.js +1 -1
  135. package/dist/runtime.iife.js.map +1 -1
  136. package/dist/runtime.js +5 -5
  137. package/dist/widgets.umd.js +1 -1
  138. package/dist/widgets.umd.js.map +1 -1
  139. package/docs/ROADMAP.md +2 -2
  140. package/docs/components/README.md +5 -2
  141. package/docs/components/usa-gl-scene.md +27 -6
  142. package/docs/components/usa-lottie-player.md +18 -0
  143. package/docs/components/usa-motion-prompt.md +32 -0
  144. package/docs/components/usa-physics-playground.md +63 -0
  145. package/docs/components/usa-snap-carousel.md +68 -0
  146. package/docs/components.md +95 -3
  147. package/docs/runtime/drag-snap.md +60 -0
  148. package/docs/runtime/format-gltf.md +3 -2
  149. package/docs/runtime/format-scene.md +59 -0
  150. package/docs/runtime/gltf-anim.md +62 -0
  151. package/docs/runtime/physics.md +61 -0
  152. package/docs/runtime/vector.md +3 -2
  153. package/package.json +61 -1
@@ -0,0 +1,739 @@
1
+ 'use strict';
2
+
3
+ var registry = require('../chunks/registry-BZxDVL3h.cjs');
4
+
5
+ /**
6
+ * `motionary/runtime/physics` (10.7) — a small 2D rigid-body engine written
7
+ * for Motionary (own implementation and API; no Matter.js / Box2D code):
8
+ *
9
+ * - bodies: circles, boxes and convex polygons (static, dynamic or
10
+ * kinematic), density → mass + moment of inertia, restitution, friction,
11
+ * sensors, collision groups / masks, sleeping;
12
+ * - collisions: sort-and-sweep broad phase, separating-axis narrow phase
13
+ * with clipped contact manifolds (up to 2 points), sequential, accumulated and
14
+ * clamped impulses (normal + Coulomb friction) with a Baumgarte position bias;
15
+ * - constraints: `distance` (rigid or a spring with `stiffness` /
16
+ * `damping`), `pin` (a body point to a world point — also the pointer
17
+ * drag constraint) and `weld`-like stiff distance pairs;
18
+ * - a fixed time step (default 1/60 s) with an accumulator, so results are
19
+ * the same at any frame rate; `world.run()` drives it from the shared
20
+ * runtime ticker (pauses while the ticker sleeps).
21
+ *
22
+ * Pure maths — no DOM: safe in SSR and workers. Units are up to you (the
23
+ * defaults assume pixels: gravity 980 px/s²).
24
+ */
25
+ const v = (x = 0, y = 0) => ({ x, y });
26
+ const dot = (a, b) => a.x * b.x + a.y * b.y;
27
+ const cross = (a, b) => a.x * b.y - a.y * b.x;
28
+ const sub = (a, b) => v(a.x - b.x, a.y - b.y);
29
+ const add = (a, b) => v(a.x + b.x, a.y + b.y);
30
+ const mul = (a, s) => v(a.x * s, a.y * s);
31
+ const len = (a) => Math.hypot(a.x, a.y);
32
+ const crossSV = (s, a) => v(-s * a.y, s * a.x);
33
+ const rot = (a, c, s) => v(a.x * c - a.y * s, a.x * s + a.y * c);
34
+ let nextId = 1;
35
+ class Body {
36
+ constructor(o = {}) {
37
+ this.id = nextId++;
38
+ this.force = v();
39
+ this.torque = 0;
40
+ this.radius = 0;
41
+ /** Local convex vertices (counter-clockwise) for boxes / polygons. */
42
+ this.verts = [];
43
+ this.normals = [];
44
+ this.mass = 0;
45
+ this.invMass = 0;
46
+ this.inertia = 0;
47
+ this.invInertia = 0;
48
+ this.sleeping = false;
49
+ this.sleepTime = 0;
50
+ /** Bounding box, refreshed every step. */
51
+ this.aabb = { minX: 0, minY: 0, maxX: 0, maxY: 0 };
52
+ this.wv = [];
53
+ this.wvAngle = NaN;
54
+ this.wvPos = v(NaN, NaN);
55
+ this.shape = o.shape || (o.vertices ? 'polygon' : o.radius != null && o.width == null ? 'circle' : 'box');
56
+ this.type = o.type || 'dynamic';
57
+ this.label = o.label || this.shape;
58
+ this.position = v(o.x || 0, o.y || 0);
59
+ this.velocity = v(o.vx || 0, o.vy || 0);
60
+ this.angle = o.angle || 0;
61
+ this.angularVelocity = o.angularVelocity || 0;
62
+ this.restitution = o.restitution ?? 0.2;
63
+ this.friction = o.friction ?? 0.4;
64
+ this.damping = o.damping ?? 0;
65
+ this.angularDamping = o.angularDamping ?? 0.01;
66
+ this.sensor = !!o.sensor;
67
+ this.category = o.category ?? 1;
68
+ this.mask = o.mask ?? 0xffffffff;
69
+ this.data = o.data;
70
+ const density = o.density ?? 0.001;
71
+ let area = 0, I = 0;
72
+ if (this.shape === 'circle') {
73
+ this.radius = o.radius ?? 20;
74
+ area = Math.PI * this.radius ** 2;
75
+ I = 0.5 * this.radius ** 2; // per unit mass
76
+ }
77
+ else {
78
+ const pts = this.shape === 'box' ? boxVerts(o.width ?? 40, o.height ?? 40) : hull((o.vertices || []).map(([x, y]) => v(x, y)));
79
+ if (pts.length < 3)
80
+ throw new Error('[motionary] physics: a polygon needs at least 3 non-collinear vertices');
81
+ // centre the polygon on its centroid
82
+ const { c, a, i } = polyMass(pts);
83
+ this.verts = pts.map((p) => sub(p, c));
84
+ area = a;
85
+ I = i;
86
+ this.radius = Math.max(...this.verts.map(len));
87
+ this.normals = this.verts.map((p, k) => {
88
+ const q = this.verts[(k + 1) % this.verts.length];
89
+ const e = sub(q, p);
90
+ const n = v(e.y, -e.x);
91
+ return mul(n, 1 / len(n));
92
+ });
93
+ }
94
+ if (this.type === 'dynamic') {
95
+ this.mass = o.mass ?? density * area;
96
+ this.invMass = this.mass > 0 ? 1 / this.mass : 0;
97
+ this.inertia = o.fixedRotation ? Infinity : this.mass * I;
98
+ this.invInertia = o.fixedRotation || !this.inertia ? 0 : 1 / this.inertia;
99
+ }
100
+ }
101
+ get isStatic() {
102
+ return this.type === 'static';
103
+ }
104
+ /** Vertices in world space (cached per pose). */
105
+ worldVerts() {
106
+ if (this.wvAngle !== this.angle || this.wvPos.x !== this.position.x || this.wvPos.y !== this.position.y) {
107
+ const c = Math.cos(this.angle), s = Math.sin(this.angle);
108
+ this.wv = this.verts.map((p) => add(rot(p, c, s), this.position));
109
+ this.wvAngle = this.angle;
110
+ this.wvPos = v(this.position.x, this.position.y);
111
+ }
112
+ return this.wv;
113
+ }
114
+ worldNormal(i) {
115
+ return rot(this.normals[i], Math.cos(this.angle), Math.sin(this.angle));
116
+ }
117
+ updateAabb() {
118
+ if (this.shape === 'circle') {
119
+ const r = this.radius, p = this.position;
120
+ this.aabb = { minX: p.x - r, minY: p.y - r, maxX: p.x + r, maxY: p.y + r };
121
+ return;
122
+ }
123
+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
124
+ for (const p of this.worldVerts()) {
125
+ if (p.x < minX)
126
+ minX = p.x;
127
+ if (p.y < minY)
128
+ minY = p.y;
129
+ if (p.x > maxX)
130
+ maxX = p.x;
131
+ if (p.y > maxY)
132
+ maxY = p.y;
133
+ }
134
+ this.aabb = { minX, minY, maxX, maxY };
135
+ }
136
+ applyImpulse(j, at) {
137
+ if (this.type !== 'dynamic')
138
+ return;
139
+ this.wake();
140
+ this.velocity = add(this.velocity, mul(j, this.invMass));
141
+ if (at)
142
+ this.angularVelocity += cross(sub(at, this.position), j) * this.invInertia;
143
+ }
144
+ applyForce(f, at) {
145
+ if (this.type !== 'dynamic')
146
+ return;
147
+ this.wake();
148
+ this.force = add(this.force, f);
149
+ if (at)
150
+ this.torque += cross(sub(at, this.position), f);
151
+ }
152
+ wake() {
153
+ this.sleeping = false;
154
+ this.sleepTime = 0;
155
+ }
156
+ /** Is the world point inside this body? */
157
+ contains(x, y) {
158
+ const p = v(x, y);
159
+ if (this.shape === 'circle')
160
+ return len(sub(p, this.position)) <= this.radius;
161
+ const w = this.worldVerts();
162
+ for (let i = 0; i < w.length; i++)
163
+ if (dot(this.worldNormal(i), sub(p, w[i])) > 0)
164
+ return false;
165
+ return true;
166
+ }
167
+ }
168
+ function boxVerts(w, h) {
169
+ return [v(-w / 2, -h / 2), v(w / 2, -h / 2), v(w / 2, h / 2), v(-w / 2, h / 2)];
170
+ }
171
+ /** Convex hull (monotone chain), counter-clockwise in a y-down screen space = clockwise maths; we keep "outward normals" consistent. */
172
+ function hull(pts) {
173
+ const p = pts.slice().sort((a, b) => a.x - b.x || a.y - b.y);
174
+ if (p.length < 3)
175
+ return p;
176
+ const lower = [], upper = [];
177
+ const turn = (o, a, b) => cross(sub(a, o), sub(b, o));
178
+ for (const q of p) {
179
+ while (lower.length >= 2 && turn(lower[lower.length - 2], lower[lower.length - 1], q) <= 0)
180
+ lower.pop();
181
+ lower.push(q);
182
+ }
183
+ for (let i = p.length - 1; i >= 0; i--) {
184
+ const q = p[i];
185
+ while (upper.length >= 2 && turn(upper[upper.length - 2], upper[upper.length - 1], q) <= 0)
186
+ upper.pop();
187
+ upper.push(q);
188
+ }
189
+ return lower.slice(0, -1).concat(upper.slice(0, -1));
190
+ }
191
+ /** Area, centroid and polar moment per unit mass of a convex polygon. */
192
+ function polyMass(p) {
193
+ let A = 0, cx = 0, cy = 0, I = 0;
194
+ for (let k = 0; k < p.length; k++) {
195
+ const a = p[k], b = p[(k + 1) % p.length];
196
+ const cr = cross(a, b);
197
+ A += cr;
198
+ cx += (a.x + b.x) * cr;
199
+ cy += (a.y + b.y) * cr;
200
+ I += cr * (dot(a, a) + dot(a, b) + dot(b, b));
201
+ }
202
+ A /= 2;
203
+ const c = v(cx / (6 * A), cy / (6 * A));
204
+ const Io = I / 12; // about the origin, times density
205
+ const iC = Io / A - dot(c, c); // per unit mass, about the centroid
206
+ return { a: Math.abs(A), c, i: Math.abs(iC) };
207
+ }
208
+ // ------------------------------------------------------------------ narrow phase
209
+ const SPECULATIVE = 1;
210
+ /** Squared speed (px²/s², incl. the rim speed of rotation) under which a body may fall asleep. */
211
+ const SLEEP_MOTION = 36;
212
+ /** Inverse mass / inertia as the solver sees them: static, kinematic and sleeping bodies do not move. */
213
+ const iM = (b) => (b.type === 'dynamic' && !b.sleeping ? b.invMass : 0);
214
+ const iI = (b) => (b.type === 'dynamic' && !b.sleeping ? b.invInertia : 0);
215
+ const motion = (b) => dot(b.velocity, b.velocity) + (b.angularVelocity * b.radius) ** 2;
216
+ function circleCircle(a, b) {
217
+ const d = sub(b.position, a.position), dist = len(d), r = a.radius + b.radius;
218
+ if (dist >= r)
219
+ return null;
220
+ const n = dist > 1e-9 ? mul(d, 1 / dist) : v(0, 1);
221
+ return { a, b, normal: n, contacts: [{ point: add(a.position, mul(n, a.radius - (r - dist) / 2)), depth: r - dist }] };
222
+ }
223
+ function polyCircle(p, c) {
224
+ // normal from the polygon to the circle
225
+ const w = p.worldVerts();
226
+ let best = -Infinity, bi = 0;
227
+ for (let i = 0; i < w.length; i++) {
228
+ const s = dot(p.worldNormal(i), sub(c.position, w[i]));
229
+ if (s > c.radius)
230
+ return null;
231
+ if (s > best)
232
+ (best = s), (bi = i);
233
+ }
234
+ if (best < 1e-9) {
235
+ // centre inside the polygon
236
+ const n = p.worldNormal(bi);
237
+ return { a: p, b: c, normal: n, contacts: [{ point: sub(c.position, mul(n, c.radius)), depth: c.radius - best }] };
238
+ }
239
+ // closest point on the polygon outline
240
+ let cp = w[0], cd = Infinity;
241
+ for (let i = 0; i < w.length; i++) {
242
+ const a = w[i], b = w[(i + 1) % w.length], e = sub(b, a);
243
+ const t = Math.max(0, Math.min(1, dot(sub(c.position, a), e) / dot(e, e)));
244
+ const q = add(a, mul(e, t)), d = len(sub(c.position, q));
245
+ if (d < cd)
246
+ (cd = d), (cp = q);
247
+ }
248
+ if (cd >= c.radius)
249
+ return null;
250
+ const n = cd > 1e-9 ? mul(sub(c.position, cp), 1 / cd) : p.worldNormal(bi);
251
+ return { a: p, b: c, normal: n, contacts: [{ point: cp, depth: c.radius - cd }] };
252
+ }
253
+ function maxSeparation(a, b) {
254
+ const wa = a.worldVerts(), wb = b.worldVerts();
255
+ let best = -Infinity, bi = 0;
256
+ for (let i = 0; i < wa.length; i++) {
257
+ const n = a.worldNormal(i);
258
+ let m = Infinity;
259
+ for (const q of wb)
260
+ m = Math.min(m, dot(n, sub(q, wa[i])));
261
+ if (m > best)
262
+ (best = m), (bi = i);
263
+ }
264
+ return { s: best, i: bi };
265
+ }
266
+ function polyPoly(a, b) {
267
+ const A = maxSeparation(a, b);
268
+ if (A.s > 0)
269
+ return null;
270
+ const B = maxSeparation(b, a);
271
+ if (B.s > 0)
272
+ return null;
273
+ let ref = a, inc = b, fi = A.i, flip = false;
274
+ if (B.s > A.s * 0.95 + 0.01)
275
+ (ref = b), (inc = a), (fi = B.i), (flip = true);
276
+ const rw = ref.worldVerts(), iw = inc.worldVerts();
277
+ const n = ref.worldNormal(fi);
278
+ // incident edge: the one whose normal is most anti-parallel to n
279
+ let ii = 0, md = Infinity;
280
+ for (let i = 0; i < iw.length; i++) {
281
+ const d = dot(inc.worldNormal(i), n);
282
+ if (d < md)
283
+ (md = d), (ii = i);
284
+ }
285
+ let pts = [iw[ii], iw[(ii + 1) % iw.length]];
286
+ const r1 = rw[fi], r2 = rw[(fi + 1) % rw.length];
287
+ const t = mul(sub(r2, r1), 1 / len(sub(r2, r1)));
288
+ // clip against the side planes of the reference edge
289
+ const clip = (ps, dir, off) => {
290
+ const out = [];
291
+ const d0 = dot(dir, ps[0]) - off, d1 = dot(dir, ps[1]) - off;
292
+ if (d0 <= 0)
293
+ out.push(ps[0]);
294
+ if (d1 <= 0)
295
+ out.push(ps[1]);
296
+ if (d0 * d1 < 0)
297
+ out.push(add(ps[0], mul(sub(ps[1], ps[0]), d0 / (d0 - d1))));
298
+ return out;
299
+ };
300
+ pts = clip(pts, mul(t, -1), -dot(t, r1));
301
+ if (pts.length < 2)
302
+ return null;
303
+ pts = clip(pts, t, dot(t, r2));
304
+ if (pts.length < 2)
305
+ return null;
306
+ const contacts = [];
307
+ for (const p of pts) {
308
+ const sep = dot(n, sub(p, r1));
309
+ // keep points that are just apart too (speculative): resting stacks keep two contacts instead of rocking on one
310
+ if (sep <= SPECULATIVE)
311
+ contacts.push({ point: p, depth: -sep });
312
+ }
313
+ if (!contacts.some((c) => c.depth >= 0))
314
+ return null;
315
+ return flip ? { a, b, normal: mul(n, -1), contacts } : { a, b, normal: n, contacts };
316
+ }
317
+ /** Contact manifold between two bodies (normal points from a to b), or null. */
318
+ function collide(a, b) {
319
+ if (a.shape === 'circle' && b.shape === 'circle')
320
+ return circleCircle(a, b);
321
+ if (a.shape !== 'circle' && b.shape === 'circle')
322
+ return polyCircle(a, b);
323
+ if (a.shape === 'circle' && b.shape !== 'circle') {
324
+ const m = polyCircle(b, a);
325
+ return m && { a, b, normal: mul(m.normal, -1), contacts: m.contacts };
326
+ }
327
+ return polyPoly(a, b);
328
+ }
329
+ class Constraint {
330
+ constructor(o) {
331
+ this.type = o.type;
332
+ this.a = o.a;
333
+ this.b = o.b || null;
334
+ this.anchorA = v(...(o.anchorA || [0, 0]));
335
+ this.anchorB = v(...(o.anchorB || [0, 0]));
336
+ this.point = v(...(o.point || [o.a.position.x, o.a.position.y]));
337
+ this.stiffness = o.stiffness ?? 1;
338
+ this.damping = o.damping ?? 0.1;
339
+ this.label = o.label || o.type;
340
+ this.length = o.length ?? len(sub(this.worldB(), this.worldA()));
341
+ }
342
+ worldA() {
343
+ return add(this.a.position, rot(this.anchorA, Math.cos(this.a.angle), Math.sin(this.a.angle)));
344
+ }
345
+ worldB() {
346
+ return this.b ? add(this.b.position, rot(this.anchorB, Math.cos(this.b.angle), Math.sin(this.b.angle))) : this.point;
347
+ }
348
+ /** One velocity iteration (impulse along the constraint axis, with a position bias). */
349
+ solve(h) {
350
+ const a = this.a, b = this.b;
351
+ const pa = this.worldA(), pb = this.worldB();
352
+ const d = sub(pb, pa), dist = len(d);
353
+ if (dist < 1e-9 && this.length < 1e-9 && this.type === 'distance')
354
+ return;
355
+ const n = dist > 1e-9 ? mul(d, 1 / dist) : v(1, 0);
356
+ const ra = sub(pa, a.position), rb = b ? sub(pb, b.position) : v();
357
+ const va = add(a.velocity, crossSV(a.angularVelocity, ra));
358
+ const vb = b ? add(b.velocity, crossSV(b.angularVelocity, rb)) : v();
359
+ const vn = dot(sub(vb, va), n);
360
+ const C = dist - this.length;
361
+ const k = a.invMass + (b ? b.invMass : 0) + cross(ra, n) ** 2 * a.invInertia + (b ? cross(rb, n) ** 2 * b.invInertia : 0);
362
+ if (k <= 0)
363
+ return;
364
+ const beta = this.stiffness >= 1 ? 0.2 : this.stiffness * 0.2;
365
+ let lambda = -(vn * (this.stiffness >= 1 ? 1 : this.damping + this.stiffness) + (beta / h) * C) / k;
366
+ if (this.stiffness < 1)
367
+ lambda *= this.stiffness;
368
+ const j = mul(n, lambda);
369
+ a.applyImpulse(mul(j, -1), pa);
370
+ b?.applyImpulse(j, pb);
371
+ }
372
+ }
373
+ class World {
374
+ constructor(o = {}) {
375
+ this.bodies = [];
376
+ this.constraints = [];
377
+ /** Manifolds of the last step (incl. sensor overlaps, which have no response). */
378
+ this.contacts = [];
379
+ this.time = 0;
380
+ this.steps = 0;
381
+ this.acc = 0;
382
+ this.warm = new Map();
383
+ this.listeners = new Set();
384
+ this.stop = null;
385
+ this.gravity = v(...(o.gravity || [0, 980]));
386
+ this.iterations = o.iterations ?? 10;
387
+ this.fixedStep = o.step ?? 1 / 60;
388
+ this.sleeping = o.sleeping ?? true;
389
+ }
390
+ add(...items) {
391
+ for (const it of items)
392
+ it instanceof Body ? this.bodies.push(it) : this.constraints.push(it);
393
+ return items[0];
394
+ }
395
+ body(o) {
396
+ return this.add(new Body(o));
397
+ }
398
+ constraint(o) {
399
+ return this.add(new Constraint(o));
400
+ }
401
+ remove(...items) {
402
+ for (const it of items) {
403
+ if (it instanceof Body) {
404
+ this.bodies = this.bodies.filter((b) => b !== it);
405
+ this.constraints = this.constraints.filter((c) => c.a !== it && c.b !== it);
406
+ }
407
+ else
408
+ this.constraints = this.constraints.filter((c) => c !== it);
409
+ }
410
+ }
411
+ clear() {
412
+ this.bodies = [];
413
+ this.constraints = [];
414
+ this.contacts = [];
415
+ }
416
+ /** Static walls around a w × h box (thickness t outside it). */
417
+ bounds(w, h, t = 50, o = {}) {
418
+ const walls = [
419
+ new Body({ type: 'static', x: w / 2, y: h + t / 2, width: w + 2 * t, height: t, label: 'floor' }),
420
+ new Body({ type: 'static', x: -t / 2, y: h / 2, width: t, height: h + 2 * t, label: 'wall-left' }),
421
+ new Body({ type: 'static', x: w + t / 2, y: h / 2, width: t, height: h + 2 * t, label: 'wall-right' }),
422
+ ];
423
+ if (o.top !== false)
424
+ walls.push(new Body({ type: 'static', x: w / 2, y: -t / 2, width: w + 2 * t, height: t, label: 'ceiling' }));
425
+ for (const b of walls)
426
+ this.add(b);
427
+ return walls;
428
+ }
429
+ onCollision(fn) {
430
+ this.listeners.add(fn);
431
+ return () => this.listeners.delete(fn);
432
+ }
433
+ /** Bodies under a world point (topmost = last added first). */
434
+ query(x, y) {
435
+ return this.bodies.filter((b) => b.contains(x, y)).reverse();
436
+ }
437
+ /** Advance by `seconds` of real time in fixed steps (max 8 steps per call). */
438
+ update(seconds) {
439
+ this.acc = Math.min(this.acc + seconds, this.fixedStep * 8);
440
+ let n = 0;
441
+ while (this.acc >= this.fixedStep) {
442
+ this.step(this.fixedStep);
443
+ this.acc -= this.fixedStep;
444
+ n++;
445
+ }
446
+ return n;
447
+ }
448
+ /** One fixed step of h seconds. */
449
+ step(h = this.fixedStep) {
450
+ const bodies = this.bodies;
451
+ // integrate forces
452
+ for (const b of bodies) {
453
+ if (b.type !== 'dynamic' || b.sleeping)
454
+ continue;
455
+ b.velocity = add(b.velocity, mul(add(this.gravity, mul(b.force, b.invMass)), h));
456
+ b.angularVelocity += b.torque * b.invInertia * h;
457
+ if (b.damping)
458
+ b.velocity = mul(b.velocity, Math.max(0, 1 - b.damping * h));
459
+ if (b.angularDamping)
460
+ b.angularVelocity *= Math.max(0, 1 - b.angularDamping * h);
461
+ }
462
+ // broad phase: sort and sweep on x
463
+ for (const b of bodies)
464
+ b.updateAabb();
465
+ const sorted = bodies.slice().sort((p, q) => p.aabb.minX - q.aabb.minX);
466
+ const manifolds = [];
467
+ for (let i = 0; i < sorted.length; i++) {
468
+ const a = sorted[i];
469
+ for (let j = i + 1; j < sorted.length; j++) {
470
+ const b = sorted[j];
471
+ if (b.aabb.minX > a.aabb.maxX)
472
+ break;
473
+ if (b.aabb.minY > a.aabb.maxY || b.aabb.maxY < a.aabb.minY)
474
+ continue;
475
+ if (a.type !== 'dynamic' && b.type !== 'dynamic')
476
+ continue;
477
+ if (!(a.category & b.mask) || !(b.category & a.mask))
478
+ continue;
479
+ if ((a.sleeping || a.type !== 'dynamic') && (b.sleeping || b.type !== 'dynamic'))
480
+ continue;
481
+ const m = a.id < b.id ? collide(a, b) : collide(b, a);
482
+ if (!m)
483
+ continue;
484
+ manifolds.push(m);
485
+ }
486
+ }
487
+ this.contacts = manifolds;
488
+ const solid = manifolds.filter((m) => !m.a.sensor && !m.b.sensor);
489
+ for (const m of solid) {
490
+ // wake a sleeper hit by a moving body
491
+ // wake a sleeper only when something hits it with some speed (resting neighbours do not keep a pile awake)
492
+ if (m.a.sleeping && !m.b.sleeping && m.b.type === 'dynamic' && motion(m.b) > SLEEP_MOTION * 4)
493
+ m.a.wake();
494
+ if (m.b.sleeping && !m.a.sleeping && m.a.type === 'dynamic' && motion(m.a) > SLEEP_MOTION * 4)
495
+ m.b.wake();
496
+ }
497
+ // velocity iterations
498
+ const key = (m) => m.a.id + ':' + m.b.id;
499
+ for (const m of solid)
500
+ prepare(m, h, this.warm.get(key(m)));
501
+ for (let it = 0; it < this.iterations; it++) {
502
+ for (const m of solid)
503
+ resolve(m);
504
+ for (const c of this.constraints)
505
+ c.solve(h);
506
+ }
507
+ this.warm = new Map(solid.map((m) => [key(m), { pts: m.contacts.map((c) => c.point), pn: m.contacts.map((c) => c.pn), pt: m.contacts.map((c) => c.pt) }]));
508
+ // integrate positions
509
+ for (const b of bodies) {
510
+ if (b.type === 'static' || b.sleeping)
511
+ continue;
512
+ b.position = add(b.position, mul(b.velocity, h));
513
+ b.angle += b.angularVelocity * h;
514
+ b.force = v();
515
+ b.torque = 0;
516
+ }
517
+ // sleeping, per island (bodies linked by contacts / constraints sleep and wake together)
518
+ if (this.sleeping) {
519
+ const parent = new Map();
520
+ const find = (x) => {
521
+ let r = x;
522
+ while (parent.get(r) !== r)
523
+ r = parent.get(r);
524
+ parent.set(x, r);
525
+ return r;
526
+ };
527
+ const dyn = (x) => !!x && x.type === 'dynamic';
528
+ for (const b of bodies)
529
+ if (dyn(b))
530
+ parent.set(b, b);
531
+ const link = (x, y) => {
532
+ if (dyn(x) && dyn(y))
533
+ parent.set(find(x), find(y));
534
+ };
535
+ for (const m of solid)
536
+ link(m.a, m.b);
537
+ for (const c of this.constraints)
538
+ link(c.a, c.b);
539
+ const dragged = new Set(this.constraints.filter((c) => c.label === 'drag').map((c) => c.a));
540
+ for (const b of parent.keys()) {
541
+ if (b.sleeping)
542
+ continue;
543
+ if (motion(b) < SLEEP_MOTION && !dragged.has(b))
544
+ b.sleepTime += h;
545
+ else
546
+ b.sleepTime = 0;
547
+ }
548
+ const islands = new Map();
549
+ for (const b of parent.keys()) {
550
+ const r = find(b);
551
+ islands.set(r, [...(islands.get(r) || []), b]);
552
+ }
553
+ for (const isl of islands.values()) {
554
+ if (isl.some((b) => !b.sleeping && b.sleepTime <= 0.6)) {
555
+ // anything awake and moving keeps (or makes) the whole island awake
556
+ if (isl.some((b) => b.sleeping) && isl.some((b) => !b.sleeping && b.sleepTime === 0))
557
+ for (const b of isl)
558
+ b.wake();
559
+ continue;
560
+ }
561
+ for (const b of isl) {
562
+ b.sleeping = true;
563
+ b.velocity = v();
564
+ b.angularVelocity = 0;
565
+ }
566
+ }
567
+ }
568
+ this.time += h;
569
+ this.steps++;
570
+ if (this.listeners.size)
571
+ for (const m of manifolds)
572
+ for (const fn of this.listeners)
573
+ fn(m);
574
+ }
575
+ /** Drive the world from the shared runtime ticker (needs the core). Returns a stopper. */
576
+ run() {
577
+ if (this.stop)
578
+ return this.stop;
579
+ const off = registry.requireModule('core', 'motionary/runtime/physics').getTicker().add((_, dt) => this.update(Math.min(dt, 100) / 1000));
580
+ this.stop = () => {
581
+ off();
582
+ this.stop = null;
583
+ };
584
+ return this.stop;
585
+ }
586
+ get running() {
587
+ return !!this.stop;
588
+ }
589
+ /** Total kinetic energy (handy for tests / "settled" checks). */
590
+ energy() {
591
+ return this.bodies.reduce((e, b) => e + (b.type === 'dynamic' ? 0.5 * b.mass * dot(b.velocity, b.velocity) + 0.5 * (isFinite(b.inertia) ? b.inertia : 0) * b.angularVelocity ** 2 : 0), 0);
592
+ }
593
+ }
594
+ function prepare(m, h, warm) {
595
+ const { a, b, normal: n } = m;
596
+ const t = v(n.y, -n.x);
597
+ const e = Math.max(a.restitution, b.restitution);
598
+ for (const c of m.contacts) {
599
+ c.ra = sub(c.point, a.position);
600
+ c.rb = sub(c.point, b.position);
601
+ const kn = iM(a) + iM(b) + cross(c.ra, n) ** 2 * iI(a) + cross(c.rb, n) ** 2 * iI(b);
602
+ const kt = iM(a) + iM(b) + cross(c.ra, t) ** 2 * iI(a) + cross(c.rb, t) ** 2 * iI(b);
603
+ c.mn = kn > 0 ? 1 / kn : 0;
604
+ c.mt = kt > 0 ? 1 / kt : 0;
605
+ const rv = sub(add(b.velocity, crossSV(b.angularVelocity, c.rb)), add(a.velocity, crossSV(a.angularVelocity, c.ra)));
606
+ const vn = dot(rv, n);
607
+ // penetrating: push out (Baumgarte); just apart: allow closing the gap this step but not more
608
+ c.bias = c.depth < 0 ? c.depth / h : Math.max((0.2 / h) * Math.max(0, c.depth - 0.25), vn < -150 ? -e * vn : 0);
609
+ c.pn = 0;
610
+ c.pt = 0;
611
+ }
612
+ // warm start: reuse last step's impulses for contacts that stayed put (stacks settle instead of creeping)
613
+ if (warm) {
614
+ m.contacts.forEach((c) => {
615
+ if (c.depth < 0)
616
+ return;
617
+ // match by position (the clipper may list the two points in either order)
618
+ let i = -1, best = 2;
619
+ warm.pts.forEach((q, k) => {
620
+ const d = len(sub(c.point, q));
621
+ if (d < best)
622
+ (best = d), (i = k);
623
+ });
624
+ if (i < 0)
625
+ return;
626
+ c.pn = warm.pn[i];
627
+ c.pt = warm.pt[i];
628
+ applyPair(a, b, add(mul(n, c.pn), mul(t, c.pt)), c.ra, c.rb);
629
+ });
630
+ }
631
+ }
632
+ /** One velocity iteration with accumulated, clamped impulses: friction first (|friction| ≤ μ·normal), then the
633
+ * normal impulses (≥ 0) — two-point manifolds are solved as one 2 × 2 block (a tiny LCP), which keeps boxes resting
634
+ * on boxes from rocking from corner to corner. */
635
+ function resolve(m) {
636
+ const { a, b, normal: n } = m;
637
+ const t = v(n.y, -n.x);
638
+ const mu = Math.sqrt(a.friction * b.friction);
639
+ const cs = m.contacts;
640
+ const rel = (c) => sub(add(b.velocity, crossSV(b.angularVelocity, c.rb)), add(a.velocity, crossSV(a.angularVelocity, c.ra)));
641
+ for (const c of cs) {
642
+ let dt = -c.mt * dot(rel(c), t);
643
+ const t0 = c.pt, max = mu * c.pn;
644
+ c.pt = Math.max(-max, Math.min(max, t0 + dt));
645
+ dt = c.pt - t0;
646
+ applyPair(a, b, mul(t, dt), c.ra, c.rb);
647
+ }
648
+ if (cs.length === 2) {
649
+ const [c1, c2] = cs;
650
+ const im = iM, ii = iI;
651
+ const rn1a = cross(c1.ra, n), rn1b = cross(c1.rb, n), rn2a = cross(c2.ra, n), rn2b = cross(c2.rb, n);
652
+ const k11 = im(a) + im(b) + ii(a) * rn1a * rn1a + ii(b) * rn1b * rn1b;
653
+ const k22 = im(a) + im(b) + ii(a) * rn2a * rn2a + ii(b) * rn2b * rn2b;
654
+ const k12 = im(a) + im(b) + ii(a) * rn1a * rn2a + ii(b) * rn1b * rn2b;
655
+ const det = k11 * k22 - k12 * k12;
656
+ if (k11 * k11 < 1000 * det) {
657
+ const a1 = c1.pn, a2 = c2.pn;
658
+ const b1 = dot(rel(c1), n) - c1.bias - (k11 * a1 + k12 * a2);
659
+ const b2 = dot(rel(c2), n) - c2.bias - (k12 * a1 + k22 * a2);
660
+ let x1 = 0, x2 = 0;
661
+ const sol = () => {
662
+ // 1. both active
663
+ x1 = -(k22 * b1 - k12 * b2) / det;
664
+ x2 = -(k11 * b2 - k12 * b1) / det;
665
+ if (x1 >= 0 && x2 >= 0)
666
+ return true;
667
+ // 2. only the first
668
+ x1 = -b1 / k11;
669
+ x2 = 0;
670
+ if (x1 >= 0 && k12 * x1 + b2 >= 0)
671
+ return true;
672
+ // 3. only the second
673
+ x1 = 0;
674
+ x2 = -b2 / k22;
675
+ if (x2 >= 0 && k12 * x2 + b1 >= 0)
676
+ return true;
677
+ // 4. none
678
+ x1 = x2 = 0;
679
+ return b1 >= 0 && b2 >= 0;
680
+ };
681
+ if (sol()) {
682
+ applyPair(a, b, mul(n, x1 - a1), c1.ra, c1.rb);
683
+ applyPair(a, b, mul(n, x2 - a2), c2.ra, c2.rb);
684
+ c1.pn = x1;
685
+ c2.pn = x2;
686
+ return;
687
+ }
688
+ }
689
+ }
690
+ for (const c of cs) {
691
+ let d = c.mn * (-dot(rel(c), n) + c.bias);
692
+ const p0 = c.pn;
693
+ c.pn = Math.max(p0 + d, 0);
694
+ d = c.pn - p0;
695
+ applyPair(a, b, mul(n, d), c.ra, c.rb);
696
+ }
697
+ }
698
+ function applyPair(a, b, J, ra, rb) {
699
+ if (a.type === 'dynamic' && !a.sleeping) {
700
+ a.velocity = sub(a.velocity, mul(J, a.invMass));
701
+ a.angularVelocity -= cross(ra, J) * a.invInertia;
702
+ }
703
+ if (b.type === 'dynamic' && !b.sleeping) {
704
+ b.velocity = add(b.velocity, mul(J, b.invMass));
705
+ b.angularVelocity += cross(rb, J) * b.invInertia;
706
+ }
707
+ }
708
+ /** A world (also registers nothing — pure). */
709
+ function createWorld(o = {}) {
710
+ return new World(o);
711
+ }
712
+ /** Pointer dragging: a soft pin from a body point to a moving world point. */
713
+ function dragConstraint(world, body, x, y, stiffness = 0.6) {
714
+ const c = body.angle;
715
+ const local = rot(sub(v(x, y), body.position), Math.cos(-c), Math.sin(-c));
716
+ const k = world.constraint({ type: 'pin', a: body, anchorA: [local.x, local.y], point: [x, y], length: 0, stiffness, damping: 0.3, label: 'drag' });
717
+ body.wake();
718
+ return {
719
+ constraint: k,
720
+ move(px, py) {
721
+ k.point = v(px, py);
722
+ body.wake();
723
+ },
724
+ release() {
725
+ world.remove(k);
726
+ },
727
+ };
728
+ }
729
+ /** The module object for `use(physics)`. */
730
+ const physics = { id: 'physics', version: registry.RUNTIME_VERSION, requires: ['core'], api: { createWorld, World, Body, Constraint, collide, dragConstraint } };
731
+
732
+ exports.Body = Body;
733
+ exports.Constraint = Constraint;
734
+ exports.World = World;
735
+ exports.collide = collide;
736
+ exports.createWorld = createWorld;
737
+ exports.dragConstraint = dragConstraint;
738
+ exports.physics = physics;
739
+ //# sourceMappingURL=physics.cjs.map