motlab.js 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +9 -0
- package/README.md +5 -1
- package/llms.txt +794 -794
- package/package.json +107 -107
- package/src/adapters/lottie.js +102 -102
- package/src/adapters/rapier.js +163 -163
- package/src/adapters/rive.js +316 -316
- package/src/addons/deform.js +441 -441
- package/src/addons/physics.js +980 -980
- package/src/core/nodes.js +328 -328
- package/src/core/scene.js +678 -678
- package/src/core/version.js +1 -1
- package/src/renderer/canvas2d.js +950 -950
- package/src/renderer/svg.js +589 -589
- package/src/renderer/webgl2.js +1331 -1331
- package/types/core/version.d.ts +1 -1
package/src/addons/physics.js
CHANGED
|
@@ -1,980 +1,980 @@
|
|
|
1
|
-
// 2D rigid bodies with XPBD (Müller and others, 2020): substeps that move, push apart by position, then fix velocities.
|
|
2
|
-
// A step uses only + - * / and sqrt, so its state hashes the same on every machine and engine.
|
|
3
|
-
import { simulate } from '../core/simulate.js'
|
|
4
|
-
import { STRIDE, instances } from '../core/nodes.js'
|
|
5
|
-
import { at } from '../core/math.js'
|
|
6
|
-
import { hash } from '../core/hash.js'
|
|
7
|
-
import { dmath } from '../core/dmath.js'
|
|
8
|
-
import { mixWord, finish, seedOf } from '../core/rand.js'
|
|
9
|
-
|
|
10
|
-
/**
|
|
11
|
-
* @template T
|
|
12
|
-
* @typedef {import('../core/math.js').Value<T>} Value
|
|
13
|
-
*/
|
|
14
|
-
|
|
15
|
-
/** @typedef {{ kind: 'circle', r: number } | { kind: 'box', w: number, h: number }} Shape */
|
|
16
|
-
|
|
17
|
-
/**
|
|
18
|
-
* @typedef {object} BodySpec
|
|
19
|
-
* @property {string} [id]
|
|
20
|
-
* @property {Shape} shape
|
|
21
|
-
* @property {number} [x]
|
|
22
|
-
* @property {number} [y]
|
|
23
|
-
* @property {number} [angle] Degrees.
|
|
24
|
-
* @property {number} [vx] px per second.
|
|
25
|
-
* @property {number} [vy]
|
|
26
|
-
* @property {number} [spin] Degrees per second.
|
|
27
|
-
* @property {number} [density] Mass per 1000 px² of area, default 1.
|
|
28
|
-
* @property {boolean} [fixed] Never moves; other bodies bounce off it.
|
|
29
|
-
* @property {Value<readonly [number, number, number?]>} [kinematic] Moves along [x, y, angle] in scene time and pushes
|
|
30
|
-
* others without being pushed back.
|
|
31
|
-
* @property {number} [restitution] Bounce, 0..1, default 0.3.
|
|
32
|
-
* @property {number} [friction] Default 0.4.
|
|
33
|
-
* @property {number} [damping] Velocity lost per second, as drag, default 0.
|
|
34
|
-
* @property {number} [group] Bodies sharing a non-zero group pass through each other.
|
|
35
|
-
*/
|
|
36
|
-
|
|
37
|
-
/**
|
|
38
|
-
* @typedef {{ kind: 'pin', body: string | number, at?: readonly [number, number], local?: readonly [number, number],
|
|
39
|
-
* hz?: number, angleHz?: number, breakAt?: number }
|
|
40
|
-
* | { kind: 'link', a: string | number, b: string | number, localA?: readonly [number, number],
|
|
41
|
-
* localB?: readonly [number, number], length?: number, hz?: number }} Joint
|
|
42
|
-
*/
|
|
43
|
-
|
|
44
|
-
/** @typedef {{ point: readonly [number, number], normal: readonly [number, number], restitution?: number, friction?: number }} Plane */
|
|
45
|
-
|
|
46
|
-
/**
|
|
47
|
-
* @typedef {object} WorldState
|
|
48
|
-
* @property {Float64Array} x
|
|
49
|
-
* @property {Float64Array} y
|
|
50
|
-
* @property {Float64Array} c Cosine of each body's angle.
|
|
51
|
-
* @property {Float64Array} s Sine of each body's angle.
|
|
52
|
-
* @property {Float64Array} vx
|
|
53
|
-
* @property {Float64Array} vy
|
|
54
|
-
* @property {Float64Array} w Angular velocity in radians per second.
|
|
55
|
-
* @property {Uint8Array} broken 1 for each joint that has broken.
|
|
56
|
-
*/
|
|
57
|
-
|
|
58
|
-
const DEG = Math.PI / 180
|
|
59
|
-
const TAU = 2 * Math.PI
|
|
60
|
-
/** @param {number} x */
|
|
61
|
-
const sq = x => x * x
|
|
62
|
-
|
|
63
|
-
/** @param {number} r @returns {Shape} */
|
|
64
|
-
export const circle = r => {
|
|
65
|
-
if (!(r > 0)) throw new RangeError(`circle: radius must be above 0, got ${r}`)
|
|
66
|
-
return Object.freeze({ kind: 'circle', r })
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
/** A box centred on its body's position. @param {number} w @param {number} h @returns {Shape} */
|
|
70
|
-
export const box = (w, h) => {
|
|
71
|
-
if (!(w > 0 && h > 0)) throw new RangeError(`box: width and height must be above 0, got ${w} and ${h}`)
|
|
72
|
-
return Object.freeze({ kind: 'box', w, h })
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
/**
|
|
76
|
-
* Ties a body to a point in the world by a spring, like a card pinned to a board. Without hz the pin is rigid.
|
|
77
|
-
* @param {{ body: string | number, at?: readonly [number, number], local?: readonly [number, number], hz?: number,
|
|
78
|
-
* angleHz?: number, breakAt?: number }} options
|
|
79
|
-
* at defaults to where the attachment point starts; local is the offset in body space (default [0, 0]); hz is how
|
|
80
|
-
* fast it springs back, angleHz how fast it turns back to its start angle (omit for a free spin); breakAt (px) lets
|
|
81
|
-
* go for good once stretched that far.
|
|
82
|
-
* @returns {Joint}
|
|
83
|
-
*/
|
|
84
|
-
export const pin = options => Object.freeze({ kind: 'pin', ...options })
|
|
85
|
-
|
|
86
|
-
/**
|
|
87
|
-
* Keeps two bodies' attachment points at a distance, rigidly or as a spring with hz.
|
|
88
|
-
* @param {{ a: string | number, b: string | number, localA?: readonly [number, number],
|
|
89
|
-
* localB?: readonly [number, number], length?: number, hz?: number }} options localA and localB default to [0, 0]
|
|
90
|
-
* (body centres); length defaults to the distance they start at.
|
|
91
|
-
* @returns {Joint}
|
|
92
|
-
*/
|
|
93
|
-
export const link = options => Object.freeze({ kind: 'link', ...options })
|
|
94
|
-
|
|
95
|
-
/**
|
|
96
|
-
* A rigid body world as a simulation: query it at any time, in any order.
|
|
97
|
-
* @param {{ bodies: BodySpec[], joints?: Joint[], planes?: Plane[], gravity?: readonly [number, number],
|
|
98
|
-
* hz?: number, substeps?: number, start?: number, snapshotEvery?: number }} spec gravity defaults to [0, 980] px/s²,
|
|
99
|
-
* hz to 120 and substeps to 4; start is the scene time the world starts moving.
|
|
100
|
-
*/
|
|
101
|
-
export function physics({ bodies, joints = [], planes = [], gravity = [0, 980], hz = 120, substeps = 4, start = 0, snapshotEvery }) {
|
|
102
|
-
if (!Array.isArray(bodies) || bodies.length === 0) throw new TypeError('physics: give at least one body')
|
|
103
|
-
const n = bodies.length
|
|
104
|
-
/** @type {Map<string, number>} */
|
|
105
|
-
const ids = new Map()
|
|
106
|
-
bodies.forEach((b, i) => {
|
|
107
|
-
if (!b?.shape || (b.shape.kind !== 'circle' && b.shape.kind !== 'box')) throw new TypeError(`physics: body ${i} needs a shape from circle() or box()`)
|
|
108
|
-
if (b.id !== undefined) {
|
|
109
|
-
if (ids.has(b.id)) throw new RangeError(`physics: body id "${b.id}" is used twice`)
|
|
110
|
-
ids.set(b.id, i)
|
|
111
|
-
}
|
|
112
|
-
})
|
|
113
|
-
/** @param {string | number} ref @param {string} where */
|
|
114
|
-
const bodyIndex = (ref, where) => {
|
|
115
|
-
const i = typeof ref === 'number' ? ref : ids.get(ref)
|
|
116
|
-
if (i === undefined || !(i >= 0 && i < n)) throw new RangeError(`${where}: no body "${ref}"`)
|
|
117
|
-
return i
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
// Fixed properties, outside the state so snapshots stay small.
|
|
121
|
-
const radius = new Float64Array(n)
|
|
122
|
-
const hw = new Float64Array(n)
|
|
123
|
-
const hh = new Float64Array(n)
|
|
124
|
-
const isBox = new Uint8Array(n)
|
|
125
|
-
const invMass = new Float64Array(n)
|
|
126
|
-
const invInertia = new Float64Array(n)
|
|
127
|
-
const mass = new Float64Array(n)
|
|
128
|
-
const inertia = new Float64Array(n)
|
|
129
|
-
const restitution = new Float64Array(n)
|
|
130
|
-
const friction = new Float64Array(n)
|
|
131
|
-
const damping = new Float64Array(n)
|
|
132
|
-
const group = new Int32Array(n)
|
|
133
|
-
/** @type {(Value<readonly [number, number, number?]> | undefined)[]} */
|
|
134
|
-
const kinematic = bodies.map(b => b.kinematic)
|
|
135
|
-
bodies.forEach((b, i) => {
|
|
136
|
-
const area = b.shape.kind === 'circle' ? Math.PI * b.shape.r * b.shape.r : b.shape.w * b.shape.h
|
|
137
|
-
const m = ((b.density ?? 1) * area) / 1000
|
|
138
|
-
const I = b.shape.kind === 'circle' ? (m * b.shape.r * b.shape.r) / 2 : (m * (b.shape.w * b.shape.w + b.shape.h * b.shape.h)) / 12
|
|
139
|
-
if (b.shape.kind === 'circle') radius[i] = b.shape.r
|
|
140
|
-
else {
|
|
141
|
-
isBox[i] = 1
|
|
142
|
-
hw[i] = b.shape.w / 2
|
|
143
|
-
hh[i] = b.shape.h / 2
|
|
144
|
-
radius[i] = Math.sqrt(hw[i] * hw[i] + hh[i] * hh[i])
|
|
145
|
-
}
|
|
146
|
-
mass[i] = m
|
|
147
|
-
inertia[i] = I
|
|
148
|
-
const moves = !b.fixed && b.kinematic === undefined
|
|
149
|
-
invMass[i] = moves ? 1 / m : 0
|
|
150
|
-
invInertia[i] = moves ? 1 / I : 0
|
|
151
|
-
restitution[i] = b.restitution ?? 0.3
|
|
152
|
-
friction[i] = b.friction ?? 0.4
|
|
153
|
-
damping[i] = b.damping ?? 0
|
|
154
|
-
group[i] = b.group ?? 0
|
|
155
|
-
})
|
|
156
|
-
|
|
157
|
-
const pins = joints.map((j, k) => {
|
|
158
|
-
const where = `physics: joint ${k} (${j.kind})`
|
|
159
|
-
if (j.kind === 'pin') {
|
|
160
|
-
const body = bodyIndex(j.body, where)
|
|
161
|
-
const spec = bodies[body]
|
|
162
|
-
const rest = (spec.angle ?? 0) * DEG
|
|
163
|
-
const rc = dmath.cos(rest)
|
|
164
|
-
const rs = dmath.sin(rest)
|
|
165
|
-
const [lax, lay] = j.local ?? [0, 0]
|
|
166
|
-
const startX = (spec.x ?? 0) + (lax === 0 && lay === 0 ? 0 : rc * lax - rs * lay)
|
|
167
|
-
const startY = (spec.y ?? 0) + (lax === 0 && lay === 0 ? 0 : rs * lax + rc * lay)
|
|
168
|
-
return { kind: 0, a: body, b: -1, lax, lay, lbx: 0, lby: 0, ax: j.at?.[0] ?? startX, ay: j.at?.[1] ?? startY, length: 0,
|
|
169
|
-
hz: j.hz ?? 0, angleHz: j.angleHz ?? 0, rc, rs, breakAt: j.breakAt ?? Infinity }
|
|
170
|
-
}
|
|
171
|
-
if (j.kind === 'link') {
|
|
172
|
-
const a = bodyIndex(j.a, where)
|
|
173
|
-
const b = bodyIndex(j.b, where)
|
|
174
|
-
const [lax, lay] = j.localA ?? [0, 0]
|
|
175
|
-
const [lbx, lby] = j.localB ?? [0, 0]
|
|
176
|
-
const ra = (bodies[a].angle ?? 0) * DEG
|
|
177
|
-
const rb = (bodies[b].angle ?? 0) * DEG
|
|
178
|
-
const pax = (bodies[a].x ?? 0) + (lax === 0 && lay === 0 ? 0 : dmath.cos(ra) * lax - dmath.sin(ra) * lay)
|
|
179
|
-
const pay = (bodies[a].y ?? 0) + (lax === 0 && lay === 0 ? 0 : dmath.sin(ra) * lax + dmath.cos(ra) * lay)
|
|
180
|
-
const pbx = (bodies[b].x ?? 0) + (lbx === 0 && lby === 0 ? 0 : dmath.cos(rb) * lbx - dmath.sin(rb) * lby)
|
|
181
|
-
const pby = (bodies[b].y ?? 0) + (lbx === 0 && lby === 0 ? 0 : dmath.sin(rb) * lbx + dmath.cos(rb) * lby)
|
|
182
|
-
const length = j.length ?? Math.sqrt(sq(pbx - pax) + sq(pby - pay))
|
|
183
|
-
return { kind: 1, a, b, lax, lay, lbx, lby, ax: 0, ay: 0, length, hz: j.hz ?? 0, angleHz: 0, rc: 1, rs: 0, breakAt: Infinity }
|
|
184
|
-
}
|
|
185
|
-
throw new TypeError(`${where}: unknown joint; use pin() or link()`)
|
|
186
|
-
})
|
|
187
|
-
const walls = planes.map((p, k) => {
|
|
188
|
-
const len = Math.sqrt(p.normal[0] * p.normal[0] + p.normal[1] * p.normal[1])
|
|
189
|
-
if (!(len > 0)) throw new RangeError(`physics: plane ${k} needs a normal`)
|
|
190
|
-
const nx = p.normal[0] / len
|
|
191
|
-
const ny = p.normal[1] / len
|
|
192
|
-
return { nx, ny, d: p.point[0] * nx + p.point[1] * ny, restitution: p.restitution ?? 0.3, friction: p.friction ?? 0.4 }
|
|
193
|
-
})
|
|
194
|
-
|
|
195
|
-
const [gx, gy] = gravity
|
|
196
|
-
const h = 1 / hz / substeps
|
|
197
|
-
|
|
198
|
-
/** @returns {WorldState} */
|
|
199
|
-
const init = () => {
|
|
200
|
-
const st = {
|
|
201
|
-
x: new Float64Array(n), y: new Float64Array(n), c: new Float64Array(n), s: new Float64Array(n),
|
|
202
|
-
vx: new Float64Array(n), vy: new Float64Array(n), w: new Float64Array(n), broken: new Uint8Array(pins.length),
|
|
203
|
-
}
|
|
204
|
-
bodies.forEach((b, i) => {
|
|
205
|
-
st.x[i] = b.x ?? 0
|
|
206
|
-
st.y[i] = b.y ?? 0
|
|
207
|
-
const a = (b.angle ?? 0) * DEG
|
|
208
|
-
st.c[i] = dmath.cos(a)
|
|
209
|
-
st.s[i] = dmath.sin(a)
|
|
210
|
-
st.vx[i] = b.vx ?? 0
|
|
211
|
-
st.vy[i] = b.vy ?? 0
|
|
212
|
-
st.w[i] = (b.spin ?? 0) * DEG
|
|
213
|
-
})
|
|
214
|
-
return st
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
// Scratch space for one substep, reused so stepping allocates little.
|
|
218
|
-
const px = new Float64Array(n)
|
|
219
|
-
const py = new Float64Array(n)
|
|
220
|
-
const pc = new Float64Array(n)
|
|
221
|
-
const ps = new Float64Array(n)
|
|
222
|
-
const order = Int32Array.from({ length: n }, (_, i) => i)
|
|
223
|
-
const minX = new Float64Array(n)
|
|
224
|
-
const extentX = new Float64Array(n)
|
|
225
|
-
const extentY = new Float64Array(n)
|
|
226
|
-
|
|
227
|
-
/** Turns body i by a small angle, keeping (c, s) a unit vector. @param {WorldState} st @param {number} i @param {number} da */
|
|
228
|
-
const turn = (st, i, da) => {
|
|
229
|
-
const c = st.c[i] - st.s[i] * da
|
|
230
|
-
const s = st.s[i] + st.c[i] * da
|
|
231
|
-
const len = Math.sqrt(c * c + s * s)
|
|
232
|
-
st.c[i] = c / len
|
|
233
|
-
st.s[i] = s / len
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
/**
|
|
237
|
-
* Moves bodies a and b (b = -1 for the world) apart along normal (nx, ny) at point (qx, qy) by C, softened by
|
|
238
|
-
* compliance. Returns the impulse magnitude applied, for friction.
|
|
239
|
-
* @param {WorldState} st @param {number} a @param {number} b @param {number} nx @param {number} ny
|
|
240
|
-
* @param {number} qx @param {number} qy @param {number} C @param {number} compliance
|
|
241
|
-
*/
|
|
242
|
-
const push = (st, a, b, nx, ny, qx, qy, C, compliance) => {
|
|
243
|
-
const rax = qx - st.x[a]
|
|
244
|
-
const ray = qy - st.y[a]
|
|
245
|
-
const crossA = rax * ny - ray * nx
|
|
246
|
-
let w = invMass[a] + invInertia[a] * crossA * crossA
|
|
247
|
-
let crossB = 0
|
|
248
|
-
if (b >= 0) {
|
|
249
|
-
const rbx = qx - st.x[b]
|
|
250
|
-
const rby = qy - st.y[b]
|
|
251
|
-
crossB = rbx * ny - rby * nx
|
|
252
|
-
w += invMass[b] + invInertia[b] * crossB * crossB
|
|
253
|
-
}
|
|
254
|
-
const alpha = compliance / (h * h)
|
|
255
|
-
if (w + alpha === 0) return 0
|
|
256
|
-
const lambda = C / (w + alpha)
|
|
257
|
-
st.x[a] -= lambda * nx * invMass[a]
|
|
258
|
-
st.y[a] -= lambda * ny * invMass[a]
|
|
259
|
-
turn(st, a, -lambda * crossA * invInertia[a])
|
|
260
|
-
if (b >= 0) {
|
|
261
|
-
st.x[b] += lambda * nx * invMass[b]
|
|
262
|
-
st.y[b] += lambda * ny * invMass[b]
|
|
263
|
-
turn(st, b, lambda * crossB * invInertia[b])
|
|
264
|
-
}
|
|
265
|
-
return lambda
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
/**
|
|
269
|
-
* A contact keeps a witness point on each body in that body's own axes, so its depth can be measured again after
|
|
270
|
-
* other contacts move the bodies. A wall's point (b = -1) stays fixed in the world.
|
|
271
|
-
* @typedef {{ a: number, b: number, nx: number, ny: number, ax: number, ay: number, bx: number, by: number,
|
|
272
|
-
* vn: number, lambda: number, e: number, mu: number }} Contact
|
|
273
|
-
*/
|
|
274
|
-
|
|
275
|
-
/** @param {WorldState} st @param {number} i @param {number} x @param {number} y @returns {[number, number]} */
|
|
276
|
-
const toLocal = (st, i, x, y) => {
|
|
277
|
-
const dx = x - st.x[i]
|
|
278
|
-
const dy = y - st.y[i]
|
|
279
|
-
return [st.c[i] * dx + st.s[i] * dy, -st.s[i] * dx + st.c[i] * dy]
|
|
280
|
-
}
|
|
281
|
-
/** @param {WorldState} st @param {number} i @param {number} lx @param {number} ly @returns {[number, number]} */
|
|
282
|
-
const toWorld = (st, i, lx, ly) => [st.x[i] + st.c[i] * lx - st.s[i] * ly, st.y[i] + st.s[i] * lx + st.c[i] * ly]
|
|
283
|
-
/** Where a body point was at the start of the substep. @param {number} i @param {number} lx @param {number} ly @returns {[number, number]} */
|
|
284
|
-
const toWorldBefore = (i, lx, ly) => [px[i] + pc[i] * lx - ps[i] * ly, py[i] + ps[i] * lx + pc[i] * ly]
|
|
285
|
-
/** @param {WorldState} st @param {Contact} k @returns {[number, number, number, number]} Both witness points now. */
|
|
286
|
-
const witnesses = (st, k) => {
|
|
287
|
-
const [ax, ay] = toWorld(st, k.a, k.ax, k.ay)
|
|
288
|
-
const [bx, by] = k.b >= 0 ? toWorld(st, k.b, k.bx, k.by) : [k.bx, k.by]
|
|
289
|
-
return [ax, ay, bx, by]
|
|
290
|
-
}
|
|
291
|
-
|
|
292
|
-
/** @param {WorldState} st @param {number} a @param {number} b @param {Contact[]} out */
|
|
293
|
-
const collide = (st, a, b, out) => {
|
|
294
|
-
const ba = isBox[a]
|
|
295
|
-
const bb = isBox[b]
|
|
296
|
-
if (!ba && !bb) return circleCircle(st, a, b, out)
|
|
297
|
-
if (!ba && bb) return circleBox(st, a, b, out, false)
|
|
298
|
-
if (ba && !bb) return circleBox(st, b, a, out, true)
|
|
299
|
-
return boxBox(st, a, b, out)
|
|
300
|
-
}
|
|
301
|
-
|
|
302
|
-
/**
|
|
303
|
-
* Records a contact from the point on b that reaches deepest into a; the matching point on a lies depth along the
|
|
304
|
-
* normal, which points from a to b.
|
|
305
|
-
* @param {WorldState} st @param {number} a @param {number} b @param {number} nx @param {number} ny
|
|
306
|
-
* @param {number} sbx @param {number} sby @param {number} depth @param {Contact[]} out
|
|
307
|
-
* @param {number} [e] @param {number} [mu]
|
|
308
|
-
*/
|
|
309
|
-
const addContact = (st, a, b, nx, ny, sbx, sby, depth, out, e, mu) => {
|
|
310
|
-
const sax = sbx + nx * depth
|
|
311
|
-
const say = sby + ny * depth
|
|
312
|
-
const [ax, ay] = toLocal(st, a, sax, say)
|
|
313
|
-
const [bx, by] = b >= 0 ? toLocal(st, b, sbx, sby) : [sbx, sby]
|
|
314
|
-
const vn = relativeNormalVelocity(st, a, b, nx, ny, (sax + sbx) / 2, (say + sby) / 2)
|
|
315
|
-
out.push({
|
|
316
|
-
a, b, nx, ny, ax, ay, bx, by, vn, lambda: 0,
|
|
317
|
-
e: e ?? Math.max(restitution[a], b >= 0 ? restitution[b] : 0),
|
|
318
|
-
mu: mu ?? (b >= 0 ? Math.sqrt(friction[a] * friction[b]) : friction[a]),
|
|
319
|
-
})
|
|
320
|
-
}
|
|
321
|
-
|
|
322
|
-
/**
|
|
323
|
-
* Changes the velocity of b relative to a by J * w along u at point q, w being the pair's inverse mass there.
|
|
324
|
-
* @param {WorldState} st @param {number} a @param {number} b @param {number} ux @param {number} uy
|
|
325
|
-
* @param {number} qx @param {number} qy @param {number} J
|
|
326
|
-
*/
|
|
327
|
-
const impulse = (st, a, b, ux, uy, qx, qy, J) => {
|
|
328
|
-
const ca = (qx - st.x[a]) * uy - (qy - st.y[a]) * ux
|
|
329
|
-
st.vx[a] -= J * ux * invMass[a]
|
|
330
|
-
st.vy[a] -= J * uy * invMass[a]
|
|
331
|
-
st.w[a] -= J * ca * invInertia[a]
|
|
332
|
-
if (b < 0) return
|
|
333
|
-
const cb = (qx - st.x[b]) * uy - (qy - st.y[b]) * ux
|
|
334
|
-
st.vx[b] += J * ux * invMass[b]
|
|
335
|
-
st.vy[b] += J * uy * invMass[b]
|
|
336
|
-
st.w[b] += J * cb * invInertia[b]
|
|
337
|
-
}
|
|
338
|
-
|
|
339
|
-
/** The pair's inverse mass for a push along u at q. @param {WorldState} st @param {number} a @param {number} b @param {number} ux @param {number} uy @param {number} qx @param {number} qy */
|
|
340
|
-
const inverseMass = (st, a, b, ux, uy, qx, qy) => {
|
|
341
|
-
const ca = (qx - st.x[a]) * uy - (qy - st.y[a]) * ux
|
|
342
|
-
let w = invMass[a] + invInertia[a] * ca * ca
|
|
343
|
-
if (b >= 0) {
|
|
344
|
-
const cb = (qx - st.x[b]) * uy - (qy - st.y[b]) * ux
|
|
345
|
-
w += invMass[b] + invInertia[b] * cb * cb
|
|
346
|
-
}
|
|
347
|
-
return w
|
|
348
|
-
}
|
|
349
|
-
|
|
350
|
-
/** @param {WorldState} st @param {number} a @param {number} b @param {number} nx @param {number} ny @param {number} qx @param {number} qy */
|
|
351
|
-
const relativeNormalVelocity = (st, a, b, nx, ny, qx, qy) => {
|
|
352
|
-
const [ax, ay] = pointVelocity(st, a, qx, qy)
|
|
353
|
-
const [bx, by] = b >= 0 ? pointVelocity(st, b, qx, qy) : [0, 0]
|
|
354
|
-
return (bx - ax) * nx + (by - ay) * ny
|
|
355
|
-
}
|
|
356
|
-
|
|
357
|
-
/** @param {WorldState} st @param {number} i @param {number} qx @param {number} qy @returns {[number, number]} */
|
|
358
|
-
const pointVelocity = (st, i, qx, qy) => [st.vx[i] - st.w[i] * (qy - st.y[i]), st.vy[i] + st.w[i] * (qx - st.x[i])]
|
|
359
|
-
|
|
360
|
-
/** @param {WorldState} st @param {number} a @param {number} b @param {Contact[]} out */
|
|
361
|
-
const circleCircle = (st, a, b, out) => {
|
|
362
|
-
const dx = st.x[b] - st.x[a]
|
|
363
|
-
const dy = st.y[b] - st.y[a]
|
|
364
|
-
const r = radius[a] + radius[b]
|
|
365
|
-
const d2 = dx * dx + dy * dy
|
|
366
|
-
if (d2 >= r * r) return
|
|
367
|
-
const d = Math.sqrt(d2)
|
|
368
|
-
const [nx, ny] = d === 0 ? [1, 0] : [dx / d, dy / d]
|
|
369
|
-
addContact(st, a, b, nx, ny, st.x[b] - nx * radius[b], st.y[b] - ny * radius[b], r - d, out)
|
|
370
|
-
}
|
|
371
|
-
|
|
372
|
-
/**
|
|
373
|
-
* Circle a against box b. The contact normal points from the first body given to addContact to the second.
|
|
374
|
-
* @param {WorldState} st @param {number} a @param {number} b @param {Contact[]} out @param {boolean} swap Box first.
|
|
375
|
-
*/
|
|
376
|
-
const circleBox = (st, a, b, out, swap) => {
|
|
377
|
-
const c = st.c[b]
|
|
378
|
-
const s = st.s[b]
|
|
379
|
-
const dx = st.x[a] - st.x[b]
|
|
380
|
-
const dy = st.y[a] - st.y[b]
|
|
381
|
-
// The circle's centre in the box's own axes.
|
|
382
|
-
const lx = c * dx + s * dy
|
|
383
|
-
const ly = -s * dx + c * dy
|
|
384
|
-
const ex = hw[b]
|
|
385
|
-
const ey = hh[b]
|
|
386
|
-
const r = radius[a]
|
|
387
|
-
let nlx
|
|
388
|
-
let nly
|
|
389
|
-
let depth
|
|
390
|
-
if (Math.abs(lx) <= ex && Math.abs(ly) <= ey) {
|
|
391
|
-
const ox = ex - Math.abs(lx)
|
|
392
|
-
const oy = ey - Math.abs(ly)
|
|
393
|
-
if (ox < oy) {
|
|
394
|
-
nlx = lx < 0 ? -1 : 1
|
|
395
|
-
nly = 0
|
|
396
|
-
depth = ox + r
|
|
397
|
-
} else {
|
|
398
|
-
nlx = 0
|
|
399
|
-
nly = ly < 0 ? -1 : 1
|
|
400
|
-
depth = oy + r
|
|
401
|
-
}
|
|
402
|
-
} else {
|
|
403
|
-
const qx = Math.max(-ex, Math.min(ex, lx))
|
|
404
|
-
const qy = Math.max(-ey, Math.min(ey, ly))
|
|
405
|
-
const ddx = lx - qx
|
|
406
|
-
const ddy = ly - qy
|
|
407
|
-
const d2 = ddx * ddx + ddy * ddy
|
|
408
|
-
if (d2 >= r * r) return
|
|
409
|
-
const d = Math.sqrt(d2)
|
|
410
|
-
nlx = ddx / d
|
|
411
|
-
nly = ddy / d
|
|
412
|
-
depth = r - d
|
|
413
|
-
}
|
|
414
|
-
// Normal from the box toward the circle, in world axes.
|
|
415
|
-
const nx = c * nlx - s * nly
|
|
416
|
-
const ny = s * nlx + c * nly
|
|
417
|
-
if (swap) addContact(st, b, a, nx, ny, st.x[a] - nx * r, st.y[a] - ny * r, depth, out)
|
|
418
|
-
else addContact(st, a, b, -nx, -ny, st.x[a] - nx * (r - depth), st.y[a] - ny * (r - depth), depth, out)
|
|
419
|
-
}
|
|
420
|
-
|
|
421
|
-
/** The four corners of box i, counter-clockwise from its +x,+y corner. @param {WorldState} st @param {number} i */
|
|
422
|
-
const corners = (st, i) => {
|
|
423
|
-
const c = st.c[i]
|
|
424
|
-
const s = st.s[i]
|
|
425
|
-
const ux = c * hw[i]
|
|
426
|
-
const uy = s * hw[i]
|
|
427
|
-
const vx = -s * hh[i]
|
|
428
|
-
const vy = c * hh[i]
|
|
429
|
-
const x = st.x[i]
|
|
430
|
-
const y = st.y[i]
|
|
431
|
-
return [x + ux + vx, y + uy + vy, x - ux + vx, y - uy + vy, x - ux - vx, y - uy - vy, x + ux - vx, y + uy - vy]
|
|
432
|
-
}
|
|
433
|
-
|
|
434
|
-
/**
|
|
435
|
-
* Separating axis test on both boxes' axes, then the incident edge clipped to the reference face: up to two
|
|
436
|
-
* contact points along the axis of least overlap.
|
|
437
|
-
* @param {WorldState} st @param {number} a @param {number} b @param {Contact[]} out
|
|
438
|
-
*/
|
|
439
|
-
const boxBox = (st, a, b, out) => {
|
|
440
|
-
const dx = st.x[b] - st.x[a]
|
|
441
|
-
const dy = st.y[b] - st.y[a]
|
|
442
|
-
let best = Infinity
|
|
443
|
-
let bestAxis = 0
|
|
444
|
-
for (let k = 0; k < 4; k++) {
|
|
445
|
-
const owner = k < 2 ? a : b
|
|
446
|
-
const ax = k % 2 === 0 ? st.c[owner] : -st.s[owner]
|
|
447
|
-
const ay = k % 2 === 0 ? st.s[owner] : st.c[owner]
|
|
448
|
-
const ra = hw[a] * Math.abs(ax * st.c[a] + ay * st.s[a]) + hh[a] * Math.abs(-ax * st.s[a] + ay * st.c[a])
|
|
449
|
-
const rb = hw[b] * Math.abs(ax * st.c[b] + ay * st.s[b]) + hh[b] * Math.abs(-ax * st.s[b] + ay * st.c[b])
|
|
450
|
-
const overlap = ra + rb - Math.abs(ax * dx + ay * dy)
|
|
451
|
-
if (overlap <= 0) return
|
|
452
|
-
// A small bias keeps the reference box from flipping between near-equal axes.
|
|
453
|
-
if (overlap < best * 0.98 - 1e-9) {
|
|
454
|
-
best = overlap
|
|
455
|
-
bestAxis = k
|
|
456
|
-
}
|
|
457
|
-
}
|
|
458
|
-
const ref = bestAxis < 2 ? a : b
|
|
459
|
-
const inc = ref === a ? b : a
|
|
460
|
-
let nx = bestAxis % 2 === 0 ? st.c[ref] : -st.s[ref]
|
|
461
|
-
let ny = bestAxis % 2 === 0 ? st.s[ref] : st.c[ref]
|
|
462
|
-
const toward = ref === a ? 1 : -1
|
|
463
|
-
if ((nx * dx + ny * dy) * toward < 0) {
|
|
464
|
-
nx = -nx
|
|
465
|
-
ny = -ny
|
|
466
|
-
}
|
|
467
|
-
// nx, ny now points from the reference box toward the incident one.
|
|
468
|
-
const half = bestAxis % 2 === 0 ? hw[ref] : hh[ref]
|
|
469
|
-
const side = bestAxis % 2 === 0 ? hh[ref] : hw[ref]
|
|
470
|
-
const tx = -ny
|
|
471
|
-
const ty = nx
|
|
472
|
-
const faceX = st.x[ref] + nx * half
|
|
473
|
-
const faceY = st.y[ref] + ny * half
|
|
474
|
-
// The incident box's edge most against the normal.
|
|
475
|
-
const pts = corners(st, inc)
|
|
476
|
-
let edge = 0
|
|
477
|
-
let lowest = Infinity
|
|
478
|
-
for (let k = 0; k < 4; k++) {
|
|
479
|
-
const ex = pts[2 * ((k + 1) % 4)] - pts[2 * k]
|
|
480
|
-
const ey = pts[2 * ((k + 1) % 4) + 1] - pts[2 * k + 1]
|
|
481
|
-
const len = Math.sqrt(ex * ex + ey * ey)
|
|
482
|
-
// Outward normal of a counter-clockwise edge in y-down screen space.
|
|
483
|
-
const d = (ey * nx - ex * ny) / len
|
|
484
|
-
if (d < lowest) {
|
|
485
|
-
lowest = d
|
|
486
|
-
edge = k
|
|
487
|
-
}
|
|
488
|
-
}
|
|
489
|
-
let p1x = pts[2 * edge]
|
|
490
|
-
let p1y = pts[2 * edge + 1]
|
|
491
|
-
let p2x = pts[2 * ((edge + 1) % 4)]
|
|
492
|
-
let p2y = pts[2 * ((edge + 1) % 4) + 1]
|
|
493
|
-
const cx = st.x[ref]
|
|
494
|
-
const cy = st.y[ref]
|
|
495
|
-
// Clip the edge to the reference face's sides.
|
|
496
|
-
for (const dir of [1, -1]) {
|
|
497
|
-
const limit = side
|
|
498
|
-
const d1 = dir * ((p1x - cx) * tx + (p1y - cy) * ty) - limit
|
|
499
|
-
const d2 = dir * ((p2x - cx) * tx + (p2y - cy) * ty) - limit
|
|
500
|
-
if (d1 > 0 && d2 > 0) return
|
|
501
|
-
if (d1 > 0 || d2 > 0) {
|
|
502
|
-
const k = d1 / (d1 - d2)
|
|
503
|
-
const ix = p1x + (p2x - p1x) * k
|
|
504
|
-
const iy = p1y + (p2y - p1y) * k
|
|
505
|
-
if (d1 > 0) {
|
|
506
|
-
p1x = ix
|
|
507
|
-
p1y = iy
|
|
508
|
-
} else {
|
|
509
|
-
p2x = ix
|
|
510
|
-
p2y = iy
|
|
511
|
-
}
|
|
512
|
-
}
|
|
513
|
-
}
|
|
514
|
-
const [first, second] = ref === a ? [a, b] : [b, a]
|
|
515
|
-
for (const [qx, qy] of [[p1x, p1y], [p2x, p2y]]) {
|
|
516
|
-
const depth = -((qx - faceX) * nx + (qy - faceY) * ny)
|
|
517
|
-
if (depth > 0) addContact(st, first, second, nx, ny, qx, qy, depth, out)
|
|
518
|
-
}
|
|
519
|
-
}
|
|
520
|
-
|
|
521
|
-
/** @param {WorldState} st @param {number} i @param {Contact[]} out */
|
|
522
|
-
const collideWalls = (st, i, out) => {
|
|
523
|
-
for (const wall of walls) {
|
|
524
|
-
if (wall.d - (st.x[i] * wall.nx + st.y[i] * wall.ny) < -radius[i]) continue
|
|
525
|
-
const points = isBox[i] ? corners(st, i) : [st.x[i] - wall.nx * radius[i], st.y[i] - wall.ny * radius[i]]
|
|
526
|
-
for (let k = 0; k < points.length; k += 2) {
|
|
527
|
-
const depth = wall.d - (points[k] * wall.nx + points[k + 1] * wall.ny)
|
|
528
|
-
if (depth <= 0) continue
|
|
529
|
-
// The wall is the second body: the normal points into it, and its point is on its surface.
|
|
530
|
-
addContact(st, i, -1, -wall.nx, -wall.ny, points[k] + wall.nx * depth, points[k + 1] + wall.ny * depth, depth, out,
|
|
531
|
-
Math.max(restitution[i], wall.restitution), Math.sqrt(friction[i] * wall.friction))
|
|
532
|
-
}
|
|
533
|
-
}
|
|
534
|
-
}
|
|
535
|
-
|
|
536
|
-
/** @param {WorldState} st @param {number} t Scene time at the end of the substep. @param {number} dt */
|
|
537
|
-
const placeKinematic = (st, t, dt) => {
|
|
538
|
-
for (let i = 0; i < n; i++) {
|
|
539
|
-
const path = kinematic[i]
|
|
540
|
-
if (path === undefined) continue
|
|
541
|
-
const [x, y, angle = 0] = at(path, t)
|
|
542
|
-
const a = angle * DEG
|
|
543
|
-
const c = dmath.cos(a)
|
|
544
|
-
const s = dmath.sin(a)
|
|
545
|
-
st.vx[i] = (x - st.x[i]) / dt
|
|
546
|
-
st.vy[i] = (y - st.y[i]) / dt
|
|
547
|
-
st.w[i] = (st.c[i] * s - st.s[i] * c) / dt
|
|
548
|
-
st.x[i] = x
|
|
549
|
-
st.y[i] = y
|
|
550
|
-
st.c[i] = c
|
|
551
|
-
st.s[i] = s
|
|
552
|
-
}
|
|
553
|
-
}
|
|
554
|
-
|
|
555
|
-
/** @param {WorldState} st @param {undefined} _input @param {number} _dt @param {number} tick */
|
|
556
|
-
const step = (st, _input, _dt, tick) => {
|
|
557
|
-
for (let sub = 0; sub < substeps; sub++) {
|
|
558
|
-
const t = start + (tick + (sub + 1) / substeps) / hz
|
|
559
|
-
for (let i = 0; i < n; i++) {
|
|
560
|
-
px[i] = st.x[i]
|
|
561
|
-
py[i] = st.y[i]
|
|
562
|
-
pc[i] = st.c[i]
|
|
563
|
-
ps[i] = st.s[i]
|
|
564
|
-
if (invMass[i] === 0) continue
|
|
565
|
-
const drag = 1 / (1 + h * damping[i])
|
|
566
|
-
st.vx[i] = (st.vx[i] + h * gx) * drag
|
|
567
|
-
st.vy[i] = (st.vy[i] + h * gy) * drag
|
|
568
|
-
st.w[i] *= drag
|
|
569
|
-
st.x[i] += h * st.vx[i]
|
|
570
|
-
st.y[i] += h * st.vy[i]
|
|
571
|
-
turn(st, i, h * st.w[i])
|
|
572
|
-
}
|
|
573
|
-
placeKinematic(st, t, h)
|
|
574
|
-
|
|
575
|
-
// Broad phase: bounding boxes, sorted by left edge (ties by index), then swept left to right.
|
|
576
|
-
for (let i = 0; i < n; i++) {
|
|
577
|
-
if (isBox[i]) {
|
|
578
|
-
const c = Math.abs(st.c[i])
|
|
579
|
-
const s = Math.abs(st.s[i])
|
|
580
|
-
extentX[i] = c * hw[i] + s * hh[i]
|
|
581
|
-
extentY[i] = s * hw[i] + c * hh[i]
|
|
582
|
-
} else extentX[i] = extentY[i] = radius[i]
|
|
583
|
-
minX[i] = st.x[i] - extentX[i]
|
|
584
|
-
}
|
|
585
|
-
for (let i = 1; i < n; i++) {
|
|
586
|
-
const v = order[i]
|
|
587
|
-
let j = i - 1
|
|
588
|
-
while (j >= 0 && (minX[order[j]] > minX[v] || (minX[order[j]] === minX[v] && order[j] > v))) {
|
|
589
|
-
order[j + 1] = order[j]
|
|
590
|
-
j--
|
|
591
|
-
}
|
|
592
|
-
order[j + 1] = v
|
|
593
|
-
}
|
|
594
|
-
/** @type {Contact[]} */
|
|
595
|
-
const contacts = []
|
|
596
|
-
for (let p = 0; p < n; p++) {
|
|
597
|
-
const a = order[p]
|
|
598
|
-
const right = st.x[a] + extentX[a]
|
|
599
|
-
for (let q = p + 1; q < n; q++) {
|
|
600
|
-
const b = order[q]
|
|
601
|
-
if (minX[b] > right) break
|
|
602
|
-
if (invMass[a] === 0 && invMass[b] === 0) continue
|
|
603
|
-
if (group[a] !== 0 && group[a] === group[b]) continue
|
|
604
|
-
if (Math.abs(st.y[b] - st.y[a]) > extentY[a] + extentY[b]) continue
|
|
605
|
-
const [lo, hi] = a < b ? [a, b] : [b, a]
|
|
606
|
-
collide(st, lo, hi, contacts)
|
|
607
|
-
}
|
|
608
|
-
if (invMass[a] !== 0) collideWalls(st, a, contacts)
|
|
609
|
-
}
|
|
610
|
-
|
|
611
|
-
for (const k of contacts) {
|
|
612
|
-
const { a, b, nx, ny } = k
|
|
613
|
-
const [sax, say, sbx, sby] = witnesses(st, k)
|
|
614
|
-
const depth = (sax - sbx) * nx + (say - sby) * ny
|
|
615
|
-
if (depth <= 0) continue
|
|
616
|
-
k.lambda = push(st, a, b, nx, ny, (sax + sbx) / 2, (say + sby) / 2, depth, 0)
|
|
617
|
-
// Static friction: undo the sideways slip of the two points over this substep while the normal push could
|
|
618
|
-
// have held it, which keeps stacks from creeping.
|
|
619
|
-
const [ax, ay, bx, by] = witnesses(st, k)
|
|
620
|
-
const [a0x, a0y] = toWorldBefore(a, k.ax, k.ay)
|
|
621
|
-
const [b0x, b0y] = b >= 0 ? toWorldBefore(b, k.bx, k.by) : [k.bx, k.by]
|
|
622
|
-
const dx = ax - a0x - (bx - b0x)
|
|
623
|
-
const dy = ay - a0y - (by - b0y)
|
|
624
|
-
const dn = dx * nx + dy * ny
|
|
625
|
-
const tx = dx - dn * nx
|
|
626
|
-
const ty = dy - dn * ny
|
|
627
|
-
const slip = Math.sqrt(tx * tx + ty * ty)
|
|
628
|
-
if (slip === 0) continue
|
|
629
|
-
const qx = (ax + bx) / 2
|
|
630
|
-
const qy = (ay + by) / 2
|
|
631
|
-
const w = inverseMass(st, a, b, tx / slip, ty / slip, qx, qy)
|
|
632
|
-
if (w > 0 && slip / w < k.mu * k.lambda) push(st, a, b, tx / slip, ty / slip, qx, qy, slip, 0)
|
|
633
|
-
}
|
|
634
|
-
pins.forEach((joint, k) => {
|
|
635
|
-
if (st.broken[k]) return
|
|
636
|
-
const a = joint.a
|
|
637
|
-
const [ax, ay] = joint.lax === 0 && joint.lay === 0 ? [st.x[a], st.y[a]] : toWorld(st, a, joint.lax, joint.lay)
|
|
638
|
-
const [bx, by] = joint.b >= 0
|
|
639
|
-
? (joint.lbx === 0 && joint.lby === 0 ? [st.x[joint.b], st.y[joint.b]] : toWorld(st, joint.b, joint.lbx, joint.lby))
|
|
640
|
-
: [joint.ax, joint.ay]
|
|
641
|
-
const dx = bx - ax
|
|
642
|
-
const dy = by - ay
|
|
643
|
-
const dist = Math.sqrt(dx * dx + dy * dy)
|
|
644
|
-
if (dist > joint.breakAt) {
|
|
645
|
-
st.broken[k] = 1
|
|
646
|
-
return
|
|
647
|
-
}
|
|
648
|
-
const stretch = dist - joint.length
|
|
649
|
-
if (dist > 0 && stretch !== 0) {
|
|
650
|
-
// A spring of frequency hz has stiffness m (2 pi hz)^2, and its compliance is the inverse.
|
|
651
|
-
const pull = joint.b >= 0 ? 1 / (invMass[a] + invMass[joint.b] || 1) : mass[a]
|
|
652
|
-
const compliance = joint.hz > 0 ? 1 / (pull * sq(TAU * joint.hz)) : 0
|
|
653
|
-
push(st, a, joint.b, dx / dist, dy / dist, ax, ay, -stretch, compliance)
|
|
654
|
-
}
|
|
655
|
-
if (joint.angleHz > 0 && joint.b < 0) {
|
|
656
|
-
// Turns the body back toward its start angle by the sine of the difference.
|
|
657
|
-
const C = st.s[a] * joint.rc - st.c[a] * joint.rs
|
|
658
|
-
const alpha = 1 / (inertia[a] * sq(TAU * joint.angleHz)) / (h * h)
|
|
659
|
-
turn(st, a, (-C / (invInertia[a] + alpha)) * invInertia[a])
|
|
660
|
-
}
|
|
661
|
-
})
|
|
662
|
-
|
|
663
|
-
for (let i = 0; i < n; i++) {
|
|
664
|
-
if (invMass[i] === 0) continue
|
|
665
|
-
st.vx[i] = (st.x[i] - px[i]) / h
|
|
666
|
-
st.vy[i] = (st.y[i] - py[i]) / h
|
|
667
|
-
st.w[i] = (pc[i] * st.s[i] - ps[i] * st.c[i]) / h
|
|
668
|
-
}
|
|
669
|
-
|
|
670
|
-
// Velocity pass: bounce from the speed before the substep, then sliding friction up to the normal impulse.
|
|
671
|
-
const bounceBelow = 2 * h * Math.sqrt(gx * gx + gy * gy)
|
|
672
|
-
for (const k of contacts) {
|
|
673
|
-
if (k.lambda === 0) continue
|
|
674
|
-
const { a, b, nx, ny } = k
|
|
675
|
-
const [sax, say, sbx, sby] = witnesses(st, k)
|
|
676
|
-
const qx = (sax + sbx) / 2
|
|
677
|
-
const qy = (say + sby) / 2
|
|
678
|
-
const vn = relativeNormalVelocity(st, a, b, nx, ny, qx, qy)
|
|
679
|
-
const target = Math.max(-(Math.abs(k.vn) > bounceBelow ? k.e : 0) * k.vn, 0)
|
|
680
|
-
if (vn < target) {
|
|
681
|
-
const w = inverseMass(st, a, b, nx, ny, qx, qy)
|
|
682
|
-
if (w > 0) impulse(st, a, b, nx, ny, qx, qy, (target - vn) / w)
|
|
683
|
-
}
|
|
684
|
-
const [avx, avy] = pointVelocity(st, a, qx, qy)
|
|
685
|
-
const [bvx, bvy] = b >= 0 ? pointVelocity(st, b, qx, qy) : [0, 0]
|
|
686
|
-
const rvx = bvx - avx
|
|
687
|
-
const rvy = bvy - avy
|
|
688
|
-
const along = rvx * nx + rvy * ny
|
|
689
|
-
const tx = rvx - along * nx
|
|
690
|
-
const ty = rvy - along * ny
|
|
691
|
-
const vt = Math.sqrt(tx * tx + ty * ty)
|
|
692
|
-
if (vt === 0) continue
|
|
693
|
-
const w = inverseMass(st, a, b, tx / vt, ty / vt, qx, qy)
|
|
694
|
-
if (w === 0) continue
|
|
695
|
-
// The normal push moved lambda units of mass times distance in h, an impulse of lambda / h.
|
|
696
|
-
const J = Math.min((k.mu * k.lambda) / h, vt / w)
|
|
697
|
-
impulse(st, a, b, tx / vt, ty / vt, qx, qy, -J)
|
|
698
|
-
}
|
|
699
|
-
}
|
|
700
|
-
}
|
|
701
|
-
|
|
702
|
-
/** @param {WorldState} a @param {WorldState} b @param {number} k @returns {WorldState} */
|
|
703
|
-
const lerp = (a, b, k) => {
|
|
704
|
-
const out = {
|
|
705
|
-
x: a.x.slice(), y: a.y.slice(), c: a.c.slice(), s: a.s.slice(),
|
|
706
|
-
vx: a.vx.slice(), vy: a.vy.slice(), w: a.w.slice(), broken: a.broken.slice(),
|
|
707
|
-
}
|
|
708
|
-
for (let i = 0; i < n; i++) {
|
|
709
|
-
out.x[i] += (b.x[i] - a.x[i]) * k
|
|
710
|
-
out.y[i] += (b.y[i] - a.y[i]) * k
|
|
711
|
-
out.vx[i] += (b.vx[i] - a.vx[i]) * k
|
|
712
|
-
out.vy[i] += (b.vy[i] - a.vy[i]) * k
|
|
713
|
-
out.w[i] += (b.w[i] - a.w[i]) * k
|
|
714
|
-
const c = a.c[i] + (b.c[i] - a.c[i]) * k
|
|
715
|
-
const s = a.s[i] + (b.s[i] - a.s[i]) * k
|
|
716
|
-
const len = Math.sqrt(c * c + s * s) || 1
|
|
717
|
-
out.c[i] = c / len
|
|
718
|
-
out.s[i] = s / len
|
|
719
|
-
}
|
|
720
|
-
return out
|
|
721
|
-
}
|
|
722
|
-
|
|
723
|
-
const sim = simulate({
|
|
724
|
-
init, step, lerp, hz, start, snapshotEvery,
|
|
725
|
-
params: { bodies: bodies.map(b => ({ ...b, kinematic: b.kinematic === undefined ? undefined : String(b.kinematic) })), joints, planes, gravity, substeps },
|
|
726
|
-
})
|
|
727
|
-
|
|
728
|
-
/** @param {string | number} ref */
|
|
729
|
-
const index = ref => bodyIndex(ref, 'physics')
|
|
730
|
-
return Object.freeze({
|
|
731
|
-
sim,
|
|
732
|
-
/** The body specs as given, in order. */
|
|
733
|
-
spec: Object.freeze([...bodies]),
|
|
734
|
-
/** @param {number} t */
|
|
735
|
-
at: t => sim.at(t),
|
|
736
|
-
index,
|
|
737
|
-
...bodyViews(sim, index),
|
|
738
|
-
/** A hash of the exact state at a tick, for checking that two machines agree. @param {number} tick */
|
|
739
|
-
hash: tick => hash(sim.tick(tick)),
|
|
740
|
-
})
|
|
741
|
-
}
|
|
742
|
-
|
|
743
|
-
/**
|
|
744
|
-
* Group props and instances data for the bodies of a world whose state holds x, y, c (cosine) and s (sine) per body.
|
|
745
|
-
* physics() and the Rapier adapter share it.
|
|
746
|
-
* @param {{ at: (t: number) => { x: ArrayLike<number>, y: ArrayLike<number>, c: ArrayLike<number>, s: ArrayLike<number> } }} sim
|
|
747
|
-
* @param {(ref: string | number) => number} index
|
|
748
|
-
*/
|
|
749
|
-
export function bodyViews(sim, index) {
|
|
750
|
-
return {
|
|
751
|
-
/**
|
|
752
|
-
* A body's place as group props.
|
|
753
|
-
* @param {string | number} ref
|
|
754
|
-
*/
|
|
755
|
-
body(ref) {
|
|
756
|
-
const i = index(ref)
|
|
757
|
-
return {
|
|
758
|
-
x: (/** @type {number} */ t) => sim.at(t).x[i],
|
|
759
|
-
y: (/** @type {number} */ t) => sim.at(t).y[i],
|
|
760
|
-
rotation: (/** @type {number} */ t) => {
|
|
761
|
-
const st = sim.at(t)
|
|
762
|
-
return Math.atan2(st.s[i], st.c[i]) / DEG
|
|
763
|
-
},
|
|
764
|
-
}
|
|
765
|
-
},
|
|
766
|
-
/**
|
|
767
|
-
* Instances data for many bodies at once: their positions and angles, with optional per-body scale, opacity and
|
|
768
|
-
* colour index.
|
|
769
|
-
* @param {ReadonlyArray<string | number>} refs
|
|
770
|
-
* @param {{ scale?: (i: number, t: number) => number, opacity?: (i: number, t: number) => number,
|
|
771
|
-
* color?: (i: number, t: number) => number }} [style] i is the position in refs.
|
|
772
|
-
* @returns {(t: number) => Float32Array}
|
|
773
|
-
*/
|
|
774
|
-
instances(refs, { scale, opacity, color } = {}) {
|
|
775
|
-
const list = refs.map(index)
|
|
776
|
-
return t => {
|
|
777
|
-
const st = sim.at(t)
|
|
778
|
-
const out = new Float32Array(list.length * STRIDE)
|
|
779
|
-
list.forEach((i, k) => {
|
|
780
|
-
const o = k * STRIDE
|
|
781
|
-
const size = scale ? scale(k, t) : 1
|
|
782
|
-
out[o] = st.x[i]
|
|
783
|
-
out[o + 1] = st.y[i]
|
|
784
|
-
out[o + 2] = Math.atan2(st.s[i], st.c[i]) / DEG
|
|
785
|
-
out[o + 3] = size
|
|
786
|
-
out[o + 4] = size
|
|
787
|
-
out[o + 5] = opacity ? opacity(k, t) : 1
|
|
788
|
-
out[o + 6] = color ? color(k, t) : -1
|
|
789
|
-
})
|
|
790
|
-
return out
|
|
791
|
-
}
|
|
792
|
-
},
|
|
793
|
-
}
|
|
794
|
-
}
|
|
795
|
-
|
|
796
|
-
const TWO_32 = 4294967296
|
|
797
|
-
|
|
798
|
-
/**
|
|
799
|
-
* Simulated particles that bounce: off planes, and off the bodies of a physics world at the same moment, so sparks
|
|
800
|
-
* skitter across a floor or ricochet off a moving ball. Births follow the same rules as the analytic particles addon
|
|
801
|
-
* (rate, bursts, seeded randomness), and the result is one instances node.
|
|
802
|
-
* @param {import('../core/nodes.js').CommonProps & {
|
|
803
|
-
* base: import('../core/nodes.js').Node, rate?: number, start?: number, end?: number,
|
|
804
|
-
* bursts?: ReadonlyArray<{ at: number, count: number }>, life?: number | readonly [number, number],
|
|
805
|
-
* origin?: Value<readonly [number, number]>, speed?: number | readonly [number, number],
|
|
806
|
-
* angle?: number | readonly [number, number], gravity?: readonly [number, number], drag?: number,
|
|
807
|
-
* restitution?: number, friction?: number, planes?: Plane[], world?: ReturnType<typeof physics>,
|
|
808
|
-
* align?: boolean, scale?: number | readonly [number, number], grow?: (u: number) => number,
|
|
809
|
-
* opacity?: (u: number) => number, colors?: string[], seed?: string | number, hz?: number }} options
|
|
810
|
-
* Times are scene seconds. restitution (default 0.4) is the bounce and friction (default 0.2) the share of sliding
|
|
811
|
-
* speed lost per bounce.
|
|
812
|
-
* @returns {import('../core/nodes.js').Node}
|
|
813
|
-
*/
|
|
814
|
-
export function simParticles({
|
|
815
|
-
base, rate = 0, start = 0, end = Infinity, bursts = [], life = 1, origin = [0, 0], speed = 200, angle = [0, 360],
|
|
816
|
-
gravity = [0, 980], drag = 0, restitution = 0.4, friction = 0.2, planes = [], world, align = false, scale = 1,
|
|
817
|
-
grow, opacity, colors, seed = 0, hz = 120, ...props
|
|
818
|
-
}) {
|
|
819
|
-
const seedWord = seedOf(seed)
|
|
820
|
-
const pick = (/** @type {number | readonly [number, number]} */ range, /** @type {number} */ k) =>
|
|
821
|
-
typeof range === 'number' ? range : range[0] + (range[1] - range[0]) * k
|
|
822
|
-
/** @param {number} source @param {number} index @param {number} channel */
|
|
823
|
-
const random = (source, index, channel) => finish(mixWord(mixWord(mixWord(seedWord, source), index), channel)) / TWO_32
|
|
824
|
-
const walls = planes.map((p, k) => {
|
|
825
|
-
const len = Math.sqrt(p.normal[0] * p.normal[0] + p.normal[1] * p.normal[1])
|
|
826
|
-
if (!(len > 0)) throw new RangeError(`simParticles: plane ${k} needs a normal`)
|
|
827
|
-
return { nx: p.normal[0] / len, ny: p.normal[1] / len, d: (p.point[0] * p.normal[0] + p.point[1] * p.normal[1]) / len }
|
|
828
|
-
})
|
|
829
|
-
const [gx, gy] = gravity
|
|
830
|
-
const shades = colors?.length ?? 0
|
|
831
|
-
// The radius of a circle around each body, to skip the far ones cheaply.
|
|
832
|
-
const bounds = (world?.spec ?? []).map(b => (b.shape.kind === 'circle' ? b.shape.r : Math.sqrt(b.shape.w * b.shape.w + b.shape.h * b.shape.h) / 2))
|
|
833
|
-
|
|
834
|
-
/** Particles born in [from, to), as [source, index, birth time]. @param {number} from @param {number} to */
|
|
835
|
-
const births = (from, to) => {
|
|
836
|
-
/** @type {[number, number, number][]} */
|
|
837
|
-
const out = []
|
|
838
|
-
if (rate > 0) {
|
|
839
|
-
for (let k = Math.max(0, Math.ceil((from - start) * rate - 1e-9)); ; k++) {
|
|
840
|
-
const born = start + k / rate
|
|
841
|
-
if (born >= to - 1e-9 || born >= end) break
|
|
842
|
-
out.push([0, k, born])
|
|
843
|
-
}
|
|
844
|
-
}
|
|
845
|
-
bursts.forEach((b, j) => {
|
|
846
|
-
if (b.at >= from - 1e-9 && b.at < to - 1e-9) for (let m = 0; m < b.count; m++) out.push([j + 1, m, b.at])
|
|
847
|
-
})
|
|
848
|
-
return out
|
|
849
|
-
}
|
|
850
|
-
|
|
851
|
-
/**
|
|
852
|
-
* @typedef {{ source: number[], index: number[], born: number[], x: number[], y: number[], vx: number[], vy: number[] }} Swarm
|
|
853
|
-
*/
|
|
854
|
-
|
|
855
|
-
/** Pushes a particle out of the world's bodies and bounces it off their surfaces. @param {Swarm} s @param {number} k @param {WorldState} w */
|
|
856
|
-
const hitBodies = (s, k, w) => {
|
|
857
|
-
if (!world) return
|
|
858
|
-
for (let i = 0; i < w.x.length; i++) {
|
|
859
|
-
const dx = s.x[k] - w.x[i]
|
|
860
|
-
const dy = s.y[k] - w.y[i]
|
|
861
|
-
const reach = bounds[i]
|
|
862
|
-
if (dx > reach || dx < -reach || dy > reach || dy < -reach) continue
|
|
863
|
-
const shape = /** @type {BodySpec} */ (world.spec[i]).shape
|
|
864
|
-
let nx = 0
|
|
865
|
-
let ny = 0
|
|
866
|
-
let depth = 0
|
|
867
|
-
if (shape.kind === 'circle') {
|
|
868
|
-
const d2 = dx * dx + dy * dy
|
|
869
|
-
if (d2 >= shape.r * shape.r) continue
|
|
870
|
-
const d = Math.sqrt(d2) || 1
|
|
871
|
-
nx = dx / d
|
|
872
|
-
ny = dy / d
|
|
873
|
-
depth = shape.r - d
|
|
874
|
-
} else {
|
|
875
|
-
const c = w.c[i]
|
|
876
|
-
const sn = w.s[i]
|
|
877
|
-
const lx = c * dx + sn * dy
|
|
878
|
-
const ly = -sn * dx + c * dy
|
|
879
|
-
const ox = shape.w / 2 - Math.abs(lx)
|
|
880
|
-
const oy = shape.h / 2 - Math.abs(ly)
|
|
881
|
-
if (ox <= 0 || oy <= 0) continue
|
|
882
|
-
const [lnx, lny] = ox < oy ? [lx < 0 ? -1 : 1, 0] : [0, ly < 0 ? -1 : 1]
|
|
883
|
-
nx = c * lnx - sn * lny
|
|
884
|
-
ny = sn * lnx + c * lny
|
|
885
|
-
depth = Math.min(ox, oy)
|
|
886
|
-
}
|
|
887
|
-
bounce(s, k, nx, ny, depth, w.vx[i], w.vy[i])
|
|
888
|
-
}
|
|
889
|
-
}
|
|
890
|
-
|
|
891
|
-
/** @param {Swarm} s @param {number} k @param {number} nx @param {number} ny @param {number} depth @param {number} bvx @param {number} bvy */
|
|
892
|
-
const bounce = (s, k, nx, ny, depth, bvx, bvy) => {
|
|
893
|
-
s.x[k] += nx * depth
|
|
894
|
-
s.y[k] += ny * depth
|
|
895
|
-
const rvx = s.vx[k] - bvx
|
|
896
|
-
const rvy = s.vy[k] - bvy
|
|
897
|
-
const vn = rvx * nx + rvy * ny
|
|
898
|
-
if (vn >= 0) return
|
|
899
|
-
const tx = rvx - vn * nx
|
|
900
|
-
const ty = rvy - vn * ny
|
|
901
|
-
s.vx[k] = bvx + tx * (1 - friction) - vn * restitution * nx
|
|
902
|
-
s.vy[k] = bvy + ty * (1 - friction) - vn * restitution * ny
|
|
903
|
-
}
|
|
904
|
-
|
|
905
|
-
const sim = simulate({
|
|
906
|
-
hz,
|
|
907
|
-
start,
|
|
908
|
-
lerp: false,
|
|
909
|
-
params: { rate, end, bursts, life, speed, angle, gravity, drag, restitution, friction, planes, seed, origin: String(origin) },
|
|
910
|
-
init: () => ({ source: [], index: [], born: [], x: [], y: [], vx: [], vy: [] }),
|
|
911
|
-
step: (/** @type {Swarm} */ s, _input, dt, tick) => {
|
|
912
|
-
const from = start + tick * dt
|
|
913
|
-
const to = from + dt
|
|
914
|
-
const w = world ? world.at(to) : null
|
|
915
|
-
// Drop the expired, keeping order so the state is the same however the frame was reached.
|
|
916
|
-
let keep = 0
|
|
917
|
-
for (let k = 0; k < s.x.length; k++) {
|
|
918
|
-
if (to - s.born[k] >= pick(life, random(s.source[k], s.index[k], 0))) continue
|
|
919
|
-
for (const key of /** @type {(keyof Swarm)[]} */ (['source', 'index', 'born', 'x', 'y', 'vx', 'vy'])) s[key][keep] = s[key][k]
|
|
920
|
-
keep++
|
|
921
|
-
}
|
|
922
|
-
for (const key of /** @type {(keyof Swarm)[]} */ (['source', 'index', 'born', 'x', 'y', 'vx', 'vy'])) s[key].length = keep
|
|
923
|
-
const keepSpeed = 1 / (1 + dt * drag)
|
|
924
|
-
for (let k = 0; k < s.x.length; k++) {
|
|
925
|
-
s.vx[k] = (s.vx[k] + dt * gx) * keepSpeed
|
|
926
|
-
s.vy[k] = (s.vy[k] + dt * gy) * keepSpeed
|
|
927
|
-
s.x[k] += dt * s.vx[k]
|
|
928
|
-
s.y[k] += dt * s.vy[k]
|
|
929
|
-
for (const wall of walls) {
|
|
930
|
-
const depth = wall.d - (s.x[k] * wall.nx + s.y[k] * wall.ny)
|
|
931
|
-
if (depth > 0) bounce(s, k, wall.nx, wall.ny, depth, 0, 0)
|
|
932
|
-
}
|
|
933
|
-
if (w) hitBodies(s, k, w)
|
|
934
|
-
}
|
|
935
|
-
// Newborns move only for the part of the tick since their birth.
|
|
936
|
-
for (const [source, index, born] of births(from, to)) {
|
|
937
|
-
const [ox, oy] = at(origin, born)
|
|
938
|
-
const direction = pick(angle, random(source, index, 1)) * DEG
|
|
939
|
-
const v = pick(speed, random(source, index, 2))
|
|
940
|
-
const part = to - born
|
|
941
|
-
const vx = v * dmath.cos(direction) + part * gx
|
|
942
|
-
const vy = v * dmath.sin(direction) + part * gy
|
|
943
|
-
s.source.push(source)
|
|
944
|
-
s.index.push(index)
|
|
945
|
-
s.born.push(born)
|
|
946
|
-
s.x.push(ox + part * vx)
|
|
947
|
-
s.y.push(oy + part * vy)
|
|
948
|
-
s.vx.push(vx)
|
|
949
|
-
s.vy.push(vy)
|
|
950
|
-
}
|
|
951
|
-
},
|
|
952
|
-
})
|
|
953
|
-
|
|
954
|
-
/** @param {number} t */
|
|
955
|
-
const data = t => {
|
|
956
|
-
const s = /** @type {Swarm} */ (sim.at(t))
|
|
957
|
-
const out = new Float32Array(s.x.length * STRIDE)
|
|
958
|
-
let n = 0
|
|
959
|
-
for (let k = 0; k < s.x.length; k++) {
|
|
960
|
-
const age = t - s.born[k]
|
|
961
|
-
const span = pick(life, random(s.source[k], s.index[k], 0))
|
|
962
|
-
if (age < 0 || age >= span) continue
|
|
963
|
-
const u = age / span
|
|
964
|
-
const fade = opacity ? opacity(u) : 1
|
|
965
|
-
if (!(fade > 0)) continue
|
|
966
|
-
const size = pick(scale, random(s.source[k], s.index[k], 3)) * (grow ? grow(u) : 1)
|
|
967
|
-
const o = n * STRIDE
|
|
968
|
-
out[o] = s.x[k]
|
|
969
|
-
out[o + 1] = s.y[k]
|
|
970
|
-
out[o + 2] = align ? Math.atan2(s.vy[k], s.vx[k]) / DEG : 0
|
|
971
|
-
out[o + 3] = size
|
|
972
|
-
out[o + 4] = size
|
|
973
|
-
out[o + 5] = Math.min(1, fade)
|
|
974
|
-
out[o + 6] = shades === 0 ? -1 : Math.floor(random(s.source[k], s.index[k], 4) * shades)
|
|
975
|
-
n++
|
|
976
|
-
}
|
|
977
|
-
return out.subarray(0, n * STRIDE)
|
|
978
|
-
}
|
|
979
|
-
return instances({ ...props, base, data, ...(colors ? { colors } : {}) })
|
|
980
|
-
}
|
|
1
|
+
// 2D rigid bodies with XPBD (Müller and others, 2020): substeps that move, push apart by position, then fix velocities.
|
|
2
|
+
// A step uses only + - * / and sqrt, so its state hashes the same on every machine and engine.
|
|
3
|
+
import { simulate } from '../core/simulate.js'
|
|
4
|
+
import { STRIDE, instances } from '../core/nodes.js'
|
|
5
|
+
import { at } from '../core/math.js'
|
|
6
|
+
import { hash } from '../core/hash.js'
|
|
7
|
+
import { dmath } from '../core/dmath.js'
|
|
8
|
+
import { mixWord, finish, seedOf } from '../core/rand.js'
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* @template T
|
|
12
|
+
* @typedef {import('../core/math.js').Value<T>} Value
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
/** @typedef {{ kind: 'circle', r: number } | { kind: 'box', w: number, h: number }} Shape */
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* @typedef {object} BodySpec
|
|
19
|
+
* @property {string} [id]
|
|
20
|
+
* @property {Shape} shape
|
|
21
|
+
* @property {number} [x]
|
|
22
|
+
* @property {number} [y]
|
|
23
|
+
* @property {number} [angle] Degrees.
|
|
24
|
+
* @property {number} [vx] px per second.
|
|
25
|
+
* @property {number} [vy]
|
|
26
|
+
* @property {number} [spin] Degrees per second.
|
|
27
|
+
* @property {number} [density] Mass per 1000 px² of area, default 1.
|
|
28
|
+
* @property {boolean} [fixed] Never moves; other bodies bounce off it.
|
|
29
|
+
* @property {Value<readonly [number, number, number?]>} [kinematic] Moves along [x, y, angle] in scene time and pushes
|
|
30
|
+
* others without being pushed back.
|
|
31
|
+
* @property {number} [restitution] Bounce, 0..1, default 0.3.
|
|
32
|
+
* @property {number} [friction] Default 0.4.
|
|
33
|
+
* @property {number} [damping] Velocity lost per second, as drag, default 0.
|
|
34
|
+
* @property {number} [group] Bodies sharing a non-zero group pass through each other.
|
|
35
|
+
*/
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* @typedef {{ kind: 'pin', body: string | number, at?: readonly [number, number], local?: readonly [number, number],
|
|
39
|
+
* hz?: number, angleHz?: number, breakAt?: number }
|
|
40
|
+
* | { kind: 'link', a: string | number, b: string | number, localA?: readonly [number, number],
|
|
41
|
+
* localB?: readonly [number, number], length?: number, hz?: number }} Joint
|
|
42
|
+
*/
|
|
43
|
+
|
|
44
|
+
/** @typedef {{ point: readonly [number, number], normal: readonly [number, number], restitution?: number, friction?: number }} Plane */
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* @typedef {object} WorldState
|
|
48
|
+
* @property {Float64Array} x
|
|
49
|
+
* @property {Float64Array} y
|
|
50
|
+
* @property {Float64Array} c Cosine of each body's angle.
|
|
51
|
+
* @property {Float64Array} s Sine of each body's angle.
|
|
52
|
+
* @property {Float64Array} vx
|
|
53
|
+
* @property {Float64Array} vy
|
|
54
|
+
* @property {Float64Array} w Angular velocity in radians per second.
|
|
55
|
+
* @property {Uint8Array} broken 1 for each joint that has broken.
|
|
56
|
+
*/
|
|
57
|
+
|
|
58
|
+
const DEG = Math.PI / 180
|
|
59
|
+
const TAU = 2 * Math.PI
|
|
60
|
+
/** @param {number} x */
|
|
61
|
+
const sq = x => x * x
|
|
62
|
+
|
|
63
|
+
/** @param {number} r @returns {Shape} */
|
|
64
|
+
export const circle = r => {
|
|
65
|
+
if (!(r > 0)) throw new RangeError(`circle: radius must be above 0, got ${r}`)
|
|
66
|
+
return Object.freeze({ kind: 'circle', r })
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** A box centred on its body's position. @param {number} w @param {number} h @returns {Shape} */
|
|
70
|
+
export const box = (w, h) => {
|
|
71
|
+
if (!(w > 0 && h > 0)) throw new RangeError(`box: width and height must be above 0, got ${w} and ${h}`)
|
|
72
|
+
return Object.freeze({ kind: 'box', w, h })
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Ties a body to a point in the world by a spring, like a card pinned to a board. Without hz the pin is rigid.
|
|
77
|
+
* @param {{ body: string | number, at?: readonly [number, number], local?: readonly [number, number], hz?: number,
|
|
78
|
+
* angleHz?: number, breakAt?: number }} options
|
|
79
|
+
* at defaults to where the attachment point starts; local is the offset in body space (default [0, 0]); hz is how
|
|
80
|
+
* fast it springs back, angleHz how fast it turns back to its start angle (omit for a free spin); breakAt (px) lets
|
|
81
|
+
* go for good once stretched that far.
|
|
82
|
+
* @returns {Joint}
|
|
83
|
+
*/
|
|
84
|
+
export const pin = options => Object.freeze({ kind: 'pin', ...options })
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Keeps two bodies' attachment points at a distance, rigidly or as a spring with hz.
|
|
88
|
+
* @param {{ a: string | number, b: string | number, localA?: readonly [number, number],
|
|
89
|
+
* localB?: readonly [number, number], length?: number, hz?: number }} options localA and localB default to [0, 0]
|
|
90
|
+
* (body centres); length defaults to the distance they start at.
|
|
91
|
+
* @returns {Joint}
|
|
92
|
+
*/
|
|
93
|
+
export const link = options => Object.freeze({ kind: 'link', ...options })
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* A rigid body world as a simulation: query it at any time, in any order.
|
|
97
|
+
* @param {{ bodies: BodySpec[], joints?: Joint[], planes?: Plane[], gravity?: readonly [number, number],
|
|
98
|
+
* hz?: number, substeps?: number, start?: number, snapshotEvery?: number }} spec gravity defaults to [0, 980] px/s²,
|
|
99
|
+
* hz to 120 and substeps to 4; start is the scene time the world starts moving.
|
|
100
|
+
*/
|
|
101
|
+
export function physics({ bodies, joints = [], planes = [], gravity = [0, 980], hz = 120, substeps = 4, start = 0, snapshotEvery }) {
|
|
102
|
+
if (!Array.isArray(bodies) || bodies.length === 0) throw new TypeError('physics: give at least one body')
|
|
103
|
+
const n = bodies.length
|
|
104
|
+
/** @type {Map<string, number>} */
|
|
105
|
+
const ids = new Map()
|
|
106
|
+
bodies.forEach((b, i) => {
|
|
107
|
+
if (!b?.shape || (b.shape.kind !== 'circle' && b.shape.kind !== 'box')) throw new TypeError(`physics: body ${i} needs a shape from circle() or box()`)
|
|
108
|
+
if (b.id !== undefined) {
|
|
109
|
+
if (ids.has(b.id)) throw new RangeError(`physics: body id "${b.id}" is used twice`)
|
|
110
|
+
ids.set(b.id, i)
|
|
111
|
+
}
|
|
112
|
+
})
|
|
113
|
+
/** @param {string | number} ref @param {string} where */
|
|
114
|
+
const bodyIndex = (ref, where) => {
|
|
115
|
+
const i = typeof ref === 'number' ? ref : ids.get(ref)
|
|
116
|
+
if (i === undefined || !(i >= 0 && i < n)) throw new RangeError(`${where}: no body "${ref}"`)
|
|
117
|
+
return i
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// Fixed properties, outside the state so snapshots stay small.
|
|
121
|
+
const radius = new Float64Array(n)
|
|
122
|
+
const hw = new Float64Array(n)
|
|
123
|
+
const hh = new Float64Array(n)
|
|
124
|
+
const isBox = new Uint8Array(n)
|
|
125
|
+
const invMass = new Float64Array(n)
|
|
126
|
+
const invInertia = new Float64Array(n)
|
|
127
|
+
const mass = new Float64Array(n)
|
|
128
|
+
const inertia = new Float64Array(n)
|
|
129
|
+
const restitution = new Float64Array(n)
|
|
130
|
+
const friction = new Float64Array(n)
|
|
131
|
+
const damping = new Float64Array(n)
|
|
132
|
+
const group = new Int32Array(n)
|
|
133
|
+
/** @type {(Value<readonly [number, number, number?]> | undefined)[]} */
|
|
134
|
+
const kinematic = bodies.map(b => b.kinematic)
|
|
135
|
+
bodies.forEach((b, i) => {
|
|
136
|
+
const area = b.shape.kind === 'circle' ? Math.PI * b.shape.r * b.shape.r : b.shape.w * b.shape.h
|
|
137
|
+
const m = ((b.density ?? 1) * area) / 1000
|
|
138
|
+
const I = b.shape.kind === 'circle' ? (m * b.shape.r * b.shape.r) / 2 : (m * (b.shape.w * b.shape.w + b.shape.h * b.shape.h)) / 12
|
|
139
|
+
if (b.shape.kind === 'circle') radius[i] = b.shape.r
|
|
140
|
+
else {
|
|
141
|
+
isBox[i] = 1
|
|
142
|
+
hw[i] = b.shape.w / 2
|
|
143
|
+
hh[i] = b.shape.h / 2
|
|
144
|
+
radius[i] = Math.sqrt(hw[i] * hw[i] + hh[i] * hh[i])
|
|
145
|
+
}
|
|
146
|
+
mass[i] = m
|
|
147
|
+
inertia[i] = I
|
|
148
|
+
const moves = !b.fixed && b.kinematic === undefined
|
|
149
|
+
invMass[i] = moves ? 1 / m : 0
|
|
150
|
+
invInertia[i] = moves ? 1 / I : 0
|
|
151
|
+
restitution[i] = b.restitution ?? 0.3
|
|
152
|
+
friction[i] = b.friction ?? 0.4
|
|
153
|
+
damping[i] = b.damping ?? 0
|
|
154
|
+
group[i] = b.group ?? 0
|
|
155
|
+
})
|
|
156
|
+
|
|
157
|
+
const pins = joints.map((j, k) => {
|
|
158
|
+
const where = `physics: joint ${k} (${j.kind})`
|
|
159
|
+
if (j.kind === 'pin') {
|
|
160
|
+
const body = bodyIndex(j.body, where)
|
|
161
|
+
const spec = bodies[body]
|
|
162
|
+
const rest = (spec.angle ?? 0) * DEG
|
|
163
|
+
const rc = dmath.cos(rest)
|
|
164
|
+
const rs = dmath.sin(rest)
|
|
165
|
+
const [lax, lay] = j.local ?? [0, 0]
|
|
166
|
+
const startX = (spec.x ?? 0) + (lax === 0 && lay === 0 ? 0 : rc * lax - rs * lay)
|
|
167
|
+
const startY = (spec.y ?? 0) + (lax === 0 && lay === 0 ? 0 : rs * lax + rc * lay)
|
|
168
|
+
return { kind: 0, a: body, b: -1, lax, lay, lbx: 0, lby: 0, ax: j.at?.[0] ?? startX, ay: j.at?.[1] ?? startY, length: 0,
|
|
169
|
+
hz: j.hz ?? 0, angleHz: j.angleHz ?? 0, rc, rs, breakAt: j.breakAt ?? Infinity }
|
|
170
|
+
}
|
|
171
|
+
if (j.kind === 'link') {
|
|
172
|
+
const a = bodyIndex(j.a, where)
|
|
173
|
+
const b = bodyIndex(j.b, where)
|
|
174
|
+
const [lax, lay] = j.localA ?? [0, 0]
|
|
175
|
+
const [lbx, lby] = j.localB ?? [0, 0]
|
|
176
|
+
const ra = (bodies[a].angle ?? 0) * DEG
|
|
177
|
+
const rb = (bodies[b].angle ?? 0) * DEG
|
|
178
|
+
const pax = (bodies[a].x ?? 0) + (lax === 0 && lay === 0 ? 0 : dmath.cos(ra) * lax - dmath.sin(ra) * lay)
|
|
179
|
+
const pay = (bodies[a].y ?? 0) + (lax === 0 && lay === 0 ? 0 : dmath.sin(ra) * lax + dmath.cos(ra) * lay)
|
|
180
|
+
const pbx = (bodies[b].x ?? 0) + (lbx === 0 && lby === 0 ? 0 : dmath.cos(rb) * lbx - dmath.sin(rb) * lby)
|
|
181
|
+
const pby = (bodies[b].y ?? 0) + (lbx === 0 && lby === 0 ? 0 : dmath.sin(rb) * lbx + dmath.cos(rb) * lby)
|
|
182
|
+
const length = j.length ?? Math.sqrt(sq(pbx - pax) + sq(pby - pay))
|
|
183
|
+
return { kind: 1, a, b, lax, lay, lbx, lby, ax: 0, ay: 0, length, hz: j.hz ?? 0, angleHz: 0, rc: 1, rs: 0, breakAt: Infinity }
|
|
184
|
+
}
|
|
185
|
+
throw new TypeError(`${where}: unknown joint; use pin() or link()`)
|
|
186
|
+
})
|
|
187
|
+
const walls = planes.map((p, k) => {
|
|
188
|
+
const len = Math.sqrt(p.normal[0] * p.normal[0] + p.normal[1] * p.normal[1])
|
|
189
|
+
if (!(len > 0)) throw new RangeError(`physics: plane ${k} needs a normal`)
|
|
190
|
+
const nx = p.normal[0] / len
|
|
191
|
+
const ny = p.normal[1] / len
|
|
192
|
+
return { nx, ny, d: p.point[0] * nx + p.point[1] * ny, restitution: p.restitution ?? 0.3, friction: p.friction ?? 0.4 }
|
|
193
|
+
})
|
|
194
|
+
|
|
195
|
+
const [gx, gy] = gravity
|
|
196
|
+
const h = 1 / hz / substeps
|
|
197
|
+
|
|
198
|
+
/** @returns {WorldState} */
|
|
199
|
+
const init = () => {
|
|
200
|
+
const st = {
|
|
201
|
+
x: new Float64Array(n), y: new Float64Array(n), c: new Float64Array(n), s: new Float64Array(n),
|
|
202
|
+
vx: new Float64Array(n), vy: new Float64Array(n), w: new Float64Array(n), broken: new Uint8Array(pins.length),
|
|
203
|
+
}
|
|
204
|
+
bodies.forEach((b, i) => {
|
|
205
|
+
st.x[i] = b.x ?? 0
|
|
206
|
+
st.y[i] = b.y ?? 0
|
|
207
|
+
const a = (b.angle ?? 0) * DEG
|
|
208
|
+
st.c[i] = dmath.cos(a)
|
|
209
|
+
st.s[i] = dmath.sin(a)
|
|
210
|
+
st.vx[i] = b.vx ?? 0
|
|
211
|
+
st.vy[i] = b.vy ?? 0
|
|
212
|
+
st.w[i] = (b.spin ?? 0) * DEG
|
|
213
|
+
})
|
|
214
|
+
return st
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// Scratch space for one substep, reused so stepping allocates little.
|
|
218
|
+
const px = new Float64Array(n)
|
|
219
|
+
const py = new Float64Array(n)
|
|
220
|
+
const pc = new Float64Array(n)
|
|
221
|
+
const ps = new Float64Array(n)
|
|
222
|
+
const order = Int32Array.from({ length: n }, (_, i) => i)
|
|
223
|
+
const minX = new Float64Array(n)
|
|
224
|
+
const extentX = new Float64Array(n)
|
|
225
|
+
const extentY = new Float64Array(n)
|
|
226
|
+
|
|
227
|
+
/** Turns body i by a small angle, keeping (c, s) a unit vector. @param {WorldState} st @param {number} i @param {number} da */
|
|
228
|
+
const turn = (st, i, da) => {
|
|
229
|
+
const c = st.c[i] - st.s[i] * da
|
|
230
|
+
const s = st.s[i] + st.c[i] * da
|
|
231
|
+
const len = Math.sqrt(c * c + s * s)
|
|
232
|
+
st.c[i] = c / len
|
|
233
|
+
st.s[i] = s / len
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Moves bodies a and b (b = -1 for the world) apart along normal (nx, ny) at point (qx, qy) by C, softened by
|
|
238
|
+
* compliance. Returns the impulse magnitude applied, for friction.
|
|
239
|
+
* @param {WorldState} st @param {number} a @param {number} b @param {number} nx @param {number} ny
|
|
240
|
+
* @param {number} qx @param {number} qy @param {number} C @param {number} compliance
|
|
241
|
+
*/
|
|
242
|
+
const push = (st, a, b, nx, ny, qx, qy, C, compliance) => {
|
|
243
|
+
const rax = qx - st.x[a]
|
|
244
|
+
const ray = qy - st.y[a]
|
|
245
|
+
const crossA = rax * ny - ray * nx
|
|
246
|
+
let w = invMass[a] + invInertia[a] * crossA * crossA
|
|
247
|
+
let crossB = 0
|
|
248
|
+
if (b >= 0) {
|
|
249
|
+
const rbx = qx - st.x[b]
|
|
250
|
+
const rby = qy - st.y[b]
|
|
251
|
+
crossB = rbx * ny - rby * nx
|
|
252
|
+
w += invMass[b] + invInertia[b] * crossB * crossB
|
|
253
|
+
}
|
|
254
|
+
const alpha = compliance / (h * h)
|
|
255
|
+
if (w + alpha === 0) return 0
|
|
256
|
+
const lambda = C / (w + alpha)
|
|
257
|
+
st.x[a] -= lambda * nx * invMass[a]
|
|
258
|
+
st.y[a] -= lambda * ny * invMass[a]
|
|
259
|
+
turn(st, a, -lambda * crossA * invInertia[a])
|
|
260
|
+
if (b >= 0) {
|
|
261
|
+
st.x[b] += lambda * nx * invMass[b]
|
|
262
|
+
st.y[b] += lambda * ny * invMass[b]
|
|
263
|
+
turn(st, b, lambda * crossB * invInertia[b])
|
|
264
|
+
}
|
|
265
|
+
return lambda
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* A contact keeps a witness point on each body in that body's own axes, so its depth can be measured again after
|
|
270
|
+
* other contacts move the bodies. A wall's point (b = -1) stays fixed in the world.
|
|
271
|
+
* @typedef {{ a: number, b: number, nx: number, ny: number, ax: number, ay: number, bx: number, by: number,
|
|
272
|
+
* vn: number, lambda: number, e: number, mu: number }} Contact
|
|
273
|
+
*/
|
|
274
|
+
|
|
275
|
+
/** @param {WorldState} st @param {number} i @param {number} x @param {number} y @returns {[number, number]} */
|
|
276
|
+
const toLocal = (st, i, x, y) => {
|
|
277
|
+
const dx = x - st.x[i]
|
|
278
|
+
const dy = y - st.y[i]
|
|
279
|
+
return [st.c[i] * dx + st.s[i] * dy, -st.s[i] * dx + st.c[i] * dy]
|
|
280
|
+
}
|
|
281
|
+
/** @param {WorldState} st @param {number} i @param {number} lx @param {number} ly @returns {[number, number]} */
|
|
282
|
+
const toWorld = (st, i, lx, ly) => [st.x[i] + st.c[i] * lx - st.s[i] * ly, st.y[i] + st.s[i] * lx + st.c[i] * ly]
|
|
283
|
+
/** Where a body point was at the start of the substep. @param {number} i @param {number} lx @param {number} ly @returns {[number, number]} */
|
|
284
|
+
const toWorldBefore = (i, lx, ly) => [px[i] + pc[i] * lx - ps[i] * ly, py[i] + ps[i] * lx + pc[i] * ly]
|
|
285
|
+
/** @param {WorldState} st @param {Contact} k @returns {[number, number, number, number]} Both witness points now. */
|
|
286
|
+
const witnesses = (st, k) => {
|
|
287
|
+
const [ax, ay] = toWorld(st, k.a, k.ax, k.ay)
|
|
288
|
+
const [bx, by] = k.b >= 0 ? toWorld(st, k.b, k.bx, k.by) : [k.bx, k.by]
|
|
289
|
+
return [ax, ay, bx, by]
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/** @param {WorldState} st @param {number} a @param {number} b @param {Contact[]} out */
|
|
293
|
+
const collide = (st, a, b, out) => {
|
|
294
|
+
const ba = isBox[a]
|
|
295
|
+
const bb = isBox[b]
|
|
296
|
+
if (!ba && !bb) return circleCircle(st, a, b, out)
|
|
297
|
+
if (!ba && bb) return circleBox(st, a, b, out, false)
|
|
298
|
+
if (ba && !bb) return circleBox(st, b, a, out, true)
|
|
299
|
+
return boxBox(st, a, b, out)
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* Records a contact from the point on b that reaches deepest into a; the matching point on a lies depth along the
|
|
304
|
+
* normal, which points from a to b.
|
|
305
|
+
* @param {WorldState} st @param {number} a @param {number} b @param {number} nx @param {number} ny
|
|
306
|
+
* @param {number} sbx @param {number} sby @param {number} depth @param {Contact[]} out
|
|
307
|
+
* @param {number} [e] @param {number} [mu]
|
|
308
|
+
*/
|
|
309
|
+
const addContact = (st, a, b, nx, ny, sbx, sby, depth, out, e, mu) => {
|
|
310
|
+
const sax = sbx + nx * depth
|
|
311
|
+
const say = sby + ny * depth
|
|
312
|
+
const [ax, ay] = toLocal(st, a, sax, say)
|
|
313
|
+
const [bx, by] = b >= 0 ? toLocal(st, b, sbx, sby) : [sbx, sby]
|
|
314
|
+
const vn = relativeNormalVelocity(st, a, b, nx, ny, (sax + sbx) / 2, (say + sby) / 2)
|
|
315
|
+
out.push({
|
|
316
|
+
a, b, nx, ny, ax, ay, bx, by, vn, lambda: 0,
|
|
317
|
+
e: e ?? Math.max(restitution[a], b >= 0 ? restitution[b] : 0),
|
|
318
|
+
mu: mu ?? (b >= 0 ? Math.sqrt(friction[a] * friction[b]) : friction[a]),
|
|
319
|
+
})
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* Changes the velocity of b relative to a by J * w along u at point q, w being the pair's inverse mass there.
|
|
324
|
+
* @param {WorldState} st @param {number} a @param {number} b @param {number} ux @param {number} uy
|
|
325
|
+
* @param {number} qx @param {number} qy @param {number} J
|
|
326
|
+
*/
|
|
327
|
+
const impulse = (st, a, b, ux, uy, qx, qy, J) => {
|
|
328
|
+
const ca = (qx - st.x[a]) * uy - (qy - st.y[a]) * ux
|
|
329
|
+
st.vx[a] -= J * ux * invMass[a]
|
|
330
|
+
st.vy[a] -= J * uy * invMass[a]
|
|
331
|
+
st.w[a] -= J * ca * invInertia[a]
|
|
332
|
+
if (b < 0) return
|
|
333
|
+
const cb = (qx - st.x[b]) * uy - (qy - st.y[b]) * ux
|
|
334
|
+
st.vx[b] += J * ux * invMass[b]
|
|
335
|
+
st.vy[b] += J * uy * invMass[b]
|
|
336
|
+
st.w[b] += J * cb * invInertia[b]
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/** The pair's inverse mass for a push along u at q. @param {WorldState} st @param {number} a @param {number} b @param {number} ux @param {number} uy @param {number} qx @param {number} qy */
|
|
340
|
+
const inverseMass = (st, a, b, ux, uy, qx, qy) => {
|
|
341
|
+
const ca = (qx - st.x[a]) * uy - (qy - st.y[a]) * ux
|
|
342
|
+
let w = invMass[a] + invInertia[a] * ca * ca
|
|
343
|
+
if (b >= 0) {
|
|
344
|
+
const cb = (qx - st.x[b]) * uy - (qy - st.y[b]) * ux
|
|
345
|
+
w += invMass[b] + invInertia[b] * cb * cb
|
|
346
|
+
}
|
|
347
|
+
return w
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/** @param {WorldState} st @param {number} a @param {number} b @param {number} nx @param {number} ny @param {number} qx @param {number} qy */
|
|
351
|
+
const relativeNormalVelocity = (st, a, b, nx, ny, qx, qy) => {
|
|
352
|
+
const [ax, ay] = pointVelocity(st, a, qx, qy)
|
|
353
|
+
const [bx, by] = b >= 0 ? pointVelocity(st, b, qx, qy) : [0, 0]
|
|
354
|
+
return (bx - ax) * nx + (by - ay) * ny
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/** @param {WorldState} st @param {number} i @param {number} qx @param {number} qy @returns {[number, number]} */
|
|
358
|
+
const pointVelocity = (st, i, qx, qy) => [st.vx[i] - st.w[i] * (qy - st.y[i]), st.vy[i] + st.w[i] * (qx - st.x[i])]
|
|
359
|
+
|
|
360
|
+
/** @param {WorldState} st @param {number} a @param {number} b @param {Contact[]} out */
|
|
361
|
+
const circleCircle = (st, a, b, out) => {
|
|
362
|
+
const dx = st.x[b] - st.x[a]
|
|
363
|
+
const dy = st.y[b] - st.y[a]
|
|
364
|
+
const r = radius[a] + radius[b]
|
|
365
|
+
const d2 = dx * dx + dy * dy
|
|
366
|
+
if (d2 >= r * r) return
|
|
367
|
+
const d = Math.sqrt(d2)
|
|
368
|
+
const [nx, ny] = d === 0 ? [1, 0] : [dx / d, dy / d]
|
|
369
|
+
addContact(st, a, b, nx, ny, st.x[b] - nx * radius[b], st.y[b] - ny * radius[b], r - d, out)
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/**
|
|
373
|
+
* Circle a against box b. The contact normal points from the first body given to addContact to the second.
|
|
374
|
+
* @param {WorldState} st @param {number} a @param {number} b @param {Contact[]} out @param {boolean} swap Box first.
|
|
375
|
+
*/
|
|
376
|
+
const circleBox = (st, a, b, out, swap) => {
|
|
377
|
+
const c = st.c[b]
|
|
378
|
+
const s = st.s[b]
|
|
379
|
+
const dx = st.x[a] - st.x[b]
|
|
380
|
+
const dy = st.y[a] - st.y[b]
|
|
381
|
+
// The circle's centre in the box's own axes.
|
|
382
|
+
const lx = c * dx + s * dy
|
|
383
|
+
const ly = -s * dx + c * dy
|
|
384
|
+
const ex = hw[b]
|
|
385
|
+
const ey = hh[b]
|
|
386
|
+
const r = radius[a]
|
|
387
|
+
let nlx
|
|
388
|
+
let nly
|
|
389
|
+
let depth
|
|
390
|
+
if (Math.abs(lx) <= ex && Math.abs(ly) <= ey) {
|
|
391
|
+
const ox = ex - Math.abs(lx)
|
|
392
|
+
const oy = ey - Math.abs(ly)
|
|
393
|
+
if (ox < oy) {
|
|
394
|
+
nlx = lx < 0 ? -1 : 1
|
|
395
|
+
nly = 0
|
|
396
|
+
depth = ox + r
|
|
397
|
+
} else {
|
|
398
|
+
nlx = 0
|
|
399
|
+
nly = ly < 0 ? -1 : 1
|
|
400
|
+
depth = oy + r
|
|
401
|
+
}
|
|
402
|
+
} else {
|
|
403
|
+
const qx = Math.max(-ex, Math.min(ex, lx))
|
|
404
|
+
const qy = Math.max(-ey, Math.min(ey, ly))
|
|
405
|
+
const ddx = lx - qx
|
|
406
|
+
const ddy = ly - qy
|
|
407
|
+
const d2 = ddx * ddx + ddy * ddy
|
|
408
|
+
if (d2 >= r * r) return
|
|
409
|
+
const d = Math.sqrt(d2)
|
|
410
|
+
nlx = ddx / d
|
|
411
|
+
nly = ddy / d
|
|
412
|
+
depth = r - d
|
|
413
|
+
}
|
|
414
|
+
// Normal from the box toward the circle, in world axes.
|
|
415
|
+
const nx = c * nlx - s * nly
|
|
416
|
+
const ny = s * nlx + c * nly
|
|
417
|
+
if (swap) addContact(st, b, a, nx, ny, st.x[a] - nx * r, st.y[a] - ny * r, depth, out)
|
|
418
|
+
else addContact(st, a, b, -nx, -ny, st.x[a] - nx * (r - depth), st.y[a] - ny * (r - depth), depth, out)
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/** The four corners of box i, counter-clockwise from its +x,+y corner. @param {WorldState} st @param {number} i */
|
|
422
|
+
const corners = (st, i) => {
|
|
423
|
+
const c = st.c[i]
|
|
424
|
+
const s = st.s[i]
|
|
425
|
+
const ux = c * hw[i]
|
|
426
|
+
const uy = s * hw[i]
|
|
427
|
+
const vx = -s * hh[i]
|
|
428
|
+
const vy = c * hh[i]
|
|
429
|
+
const x = st.x[i]
|
|
430
|
+
const y = st.y[i]
|
|
431
|
+
return [x + ux + vx, y + uy + vy, x - ux + vx, y - uy + vy, x - ux - vx, y - uy - vy, x + ux - vx, y + uy - vy]
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/**
|
|
435
|
+
* Separating axis test on both boxes' axes, then the incident edge clipped to the reference face: up to two
|
|
436
|
+
* contact points along the axis of least overlap.
|
|
437
|
+
* @param {WorldState} st @param {number} a @param {number} b @param {Contact[]} out
|
|
438
|
+
*/
|
|
439
|
+
const boxBox = (st, a, b, out) => {
|
|
440
|
+
const dx = st.x[b] - st.x[a]
|
|
441
|
+
const dy = st.y[b] - st.y[a]
|
|
442
|
+
let best = Infinity
|
|
443
|
+
let bestAxis = 0
|
|
444
|
+
for (let k = 0; k < 4; k++) {
|
|
445
|
+
const owner = k < 2 ? a : b
|
|
446
|
+
const ax = k % 2 === 0 ? st.c[owner] : -st.s[owner]
|
|
447
|
+
const ay = k % 2 === 0 ? st.s[owner] : st.c[owner]
|
|
448
|
+
const ra = hw[a] * Math.abs(ax * st.c[a] + ay * st.s[a]) + hh[a] * Math.abs(-ax * st.s[a] + ay * st.c[a])
|
|
449
|
+
const rb = hw[b] * Math.abs(ax * st.c[b] + ay * st.s[b]) + hh[b] * Math.abs(-ax * st.s[b] + ay * st.c[b])
|
|
450
|
+
const overlap = ra + rb - Math.abs(ax * dx + ay * dy)
|
|
451
|
+
if (overlap <= 0) return
|
|
452
|
+
// A small bias keeps the reference box from flipping between near-equal axes.
|
|
453
|
+
if (overlap < best * 0.98 - 1e-9) {
|
|
454
|
+
best = overlap
|
|
455
|
+
bestAxis = k
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
const ref = bestAxis < 2 ? a : b
|
|
459
|
+
const inc = ref === a ? b : a
|
|
460
|
+
let nx = bestAxis % 2 === 0 ? st.c[ref] : -st.s[ref]
|
|
461
|
+
let ny = bestAxis % 2 === 0 ? st.s[ref] : st.c[ref]
|
|
462
|
+
const toward = ref === a ? 1 : -1
|
|
463
|
+
if ((nx * dx + ny * dy) * toward < 0) {
|
|
464
|
+
nx = -nx
|
|
465
|
+
ny = -ny
|
|
466
|
+
}
|
|
467
|
+
// nx, ny now points from the reference box toward the incident one.
|
|
468
|
+
const half = bestAxis % 2 === 0 ? hw[ref] : hh[ref]
|
|
469
|
+
const side = bestAxis % 2 === 0 ? hh[ref] : hw[ref]
|
|
470
|
+
const tx = -ny
|
|
471
|
+
const ty = nx
|
|
472
|
+
const faceX = st.x[ref] + nx * half
|
|
473
|
+
const faceY = st.y[ref] + ny * half
|
|
474
|
+
// The incident box's edge most against the normal.
|
|
475
|
+
const pts = corners(st, inc)
|
|
476
|
+
let edge = 0
|
|
477
|
+
let lowest = Infinity
|
|
478
|
+
for (let k = 0; k < 4; k++) {
|
|
479
|
+
const ex = pts[2 * ((k + 1) % 4)] - pts[2 * k]
|
|
480
|
+
const ey = pts[2 * ((k + 1) % 4) + 1] - pts[2 * k + 1]
|
|
481
|
+
const len = Math.sqrt(ex * ex + ey * ey)
|
|
482
|
+
// Outward normal of a counter-clockwise edge in y-down screen space.
|
|
483
|
+
const d = (ey * nx - ex * ny) / len
|
|
484
|
+
if (d < lowest) {
|
|
485
|
+
lowest = d
|
|
486
|
+
edge = k
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
let p1x = pts[2 * edge]
|
|
490
|
+
let p1y = pts[2 * edge + 1]
|
|
491
|
+
let p2x = pts[2 * ((edge + 1) % 4)]
|
|
492
|
+
let p2y = pts[2 * ((edge + 1) % 4) + 1]
|
|
493
|
+
const cx = st.x[ref]
|
|
494
|
+
const cy = st.y[ref]
|
|
495
|
+
// Clip the edge to the reference face's sides.
|
|
496
|
+
for (const dir of [1, -1]) {
|
|
497
|
+
const limit = side
|
|
498
|
+
const d1 = dir * ((p1x - cx) * tx + (p1y - cy) * ty) - limit
|
|
499
|
+
const d2 = dir * ((p2x - cx) * tx + (p2y - cy) * ty) - limit
|
|
500
|
+
if (d1 > 0 && d2 > 0) return
|
|
501
|
+
if (d1 > 0 || d2 > 0) {
|
|
502
|
+
const k = d1 / (d1 - d2)
|
|
503
|
+
const ix = p1x + (p2x - p1x) * k
|
|
504
|
+
const iy = p1y + (p2y - p1y) * k
|
|
505
|
+
if (d1 > 0) {
|
|
506
|
+
p1x = ix
|
|
507
|
+
p1y = iy
|
|
508
|
+
} else {
|
|
509
|
+
p2x = ix
|
|
510
|
+
p2y = iy
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
const [first, second] = ref === a ? [a, b] : [b, a]
|
|
515
|
+
for (const [qx, qy] of [[p1x, p1y], [p2x, p2y]]) {
|
|
516
|
+
const depth = -((qx - faceX) * nx + (qy - faceY) * ny)
|
|
517
|
+
if (depth > 0) addContact(st, first, second, nx, ny, qx, qy, depth, out)
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
/** @param {WorldState} st @param {number} i @param {Contact[]} out */
|
|
522
|
+
const collideWalls = (st, i, out) => {
|
|
523
|
+
for (const wall of walls) {
|
|
524
|
+
if (wall.d - (st.x[i] * wall.nx + st.y[i] * wall.ny) < -radius[i]) continue
|
|
525
|
+
const points = isBox[i] ? corners(st, i) : [st.x[i] - wall.nx * radius[i], st.y[i] - wall.ny * radius[i]]
|
|
526
|
+
for (let k = 0; k < points.length; k += 2) {
|
|
527
|
+
const depth = wall.d - (points[k] * wall.nx + points[k + 1] * wall.ny)
|
|
528
|
+
if (depth <= 0) continue
|
|
529
|
+
// The wall is the second body: the normal points into it, and its point is on its surface.
|
|
530
|
+
addContact(st, i, -1, -wall.nx, -wall.ny, points[k] + wall.nx * depth, points[k + 1] + wall.ny * depth, depth, out,
|
|
531
|
+
Math.max(restitution[i], wall.restitution), Math.sqrt(friction[i] * wall.friction))
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
/** @param {WorldState} st @param {number} t Scene time at the end of the substep. @param {number} dt */
|
|
537
|
+
const placeKinematic = (st, t, dt) => {
|
|
538
|
+
for (let i = 0; i < n; i++) {
|
|
539
|
+
const path = kinematic[i]
|
|
540
|
+
if (path === undefined) continue
|
|
541
|
+
const [x, y, angle = 0] = at(path, t)
|
|
542
|
+
const a = angle * DEG
|
|
543
|
+
const c = dmath.cos(a)
|
|
544
|
+
const s = dmath.sin(a)
|
|
545
|
+
st.vx[i] = (x - st.x[i]) / dt
|
|
546
|
+
st.vy[i] = (y - st.y[i]) / dt
|
|
547
|
+
st.w[i] = (st.c[i] * s - st.s[i] * c) / dt
|
|
548
|
+
st.x[i] = x
|
|
549
|
+
st.y[i] = y
|
|
550
|
+
st.c[i] = c
|
|
551
|
+
st.s[i] = s
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
/** @param {WorldState} st @param {undefined} _input @param {number} _dt @param {number} tick */
|
|
556
|
+
const step = (st, _input, _dt, tick) => {
|
|
557
|
+
for (let sub = 0; sub < substeps; sub++) {
|
|
558
|
+
const t = start + (tick + (sub + 1) / substeps) / hz
|
|
559
|
+
for (let i = 0; i < n; i++) {
|
|
560
|
+
px[i] = st.x[i]
|
|
561
|
+
py[i] = st.y[i]
|
|
562
|
+
pc[i] = st.c[i]
|
|
563
|
+
ps[i] = st.s[i]
|
|
564
|
+
if (invMass[i] === 0) continue
|
|
565
|
+
const drag = 1 / (1 + h * damping[i])
|
|
566
|
+
st.vx[i] = (st.vx[i] + h * gx) * drag
|
|
567
|
+
st.vy[i] = (st.vy[i] + h * gy) * drag
|
|
568
|
+
st.w[i] *= drag
|
|
569
|
+
st.x[i] += h * st.vx[i]
|
|
570
|
+
st.y[i] += h * st.vy[i]
|
|
571
|
+
turn(st, i, h * st.w[i])
|
|
572
|
+
}
|
|
573
|
+
placeKinematic(st, t, h)
|
|
574
|
+
|
|
575
|
+
// Broad phase: bounding boxes, sorted by left edge (ties by index), then swept left to right.
|
|
576
|
+
for (let i = 0; i < n; i++) {
|
|
577
|
+
if (isBox[i]) {
|
|
578
|
+
const c = Math.abs(st.c[i])
|
|
579
|
+
const s = Math.abs(st.s[i])
|
|
580
|
+
extentX[i] = c * hw[i] + s * hh[i]
|
|
581
|
+
extentY[i] = s * hw[i] + c * hh[i]
|
|
582
|
+
} else extentX[i] = extentY[i] = radius[i]
|
|
583
|
+
minX[i] = st.x[i] - extentX[i]
|
|
584
|
+
}
|
|
585
|
+
for (let i = 1; i < n; i++) {
|
|
586
|
+
const v = order[i]
|
|
587
|
+
let j = i - 1
|
|
588
|
+
while (j >= 0 && (minX[order[j]] > minX[v] || (minX[order[j]] === minX[v] && order[j] > v))) {
|
|
589
|
+
order[j + 1] = order[j]
|
|
590
|
+
j--
|
|
591
|
+
}
|
|
592
|
+
order[j + 1] = v
|
|
593
|
+
}
|
|
594
|
+
/** @type {Contact[]} */
|
|
595
|
+
const contacts = []
|
|
596
|
+
for (let p = 0; p < n; p++) {
|
|
597
|
+
const a = order[p]
|
|
598
|
+
const right = st.x[a] + extentX[a]
|
|
599
|
+
for (let q = p + 1; q < n; q++) {
|
|
600
|
+
const b = order[q]
|
|
601
|
+
if (minX[b] > right) break
|
|
602
|
+
if (invMass[a] === 0 && invMass[b] === 0) continue
|
|
603
|
+
if (group[a] !== 0 && group[a] === group[b]) continue
|
|
604
|
+
if (Math.abs(st.y[b] - st.y[a]) > extentY[a] + extentY[b]) continue
|
|
605
|
+
const [lo, hi] = a < b ? [a, b] : [b, a]
|
|
606
|
+
collide(st, lo, hi, contacts)
|
|
607
|
+
}
|
|
608
|
+
if (invMass[a] !== 0) collideWalls(st, a, contacts)
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
for (const k of contacts) {
|
|
612
|
+
const { a, b, nx, ny } = k
|
|
613
|
+
const [sax, say, sbx, sby] = witnesses(st, k)
|
|
614
|
+
const depth = (sax - sbx) * nx + (say - sby) * ny
|
|
615
|
+
if (depth <= 0) continue
|
|
616
|
+
k.lambda = push(st, a, b, nx, ny, (sax + sbx) / 2, (say + sby) / 2, depth, 0)
|
|
617
|
+
// Static friction: undo the sideways slip of the two points over this substep while the normal push could
|
|
618
|
+
// have held it, which keeps stacks from creeping.
|
|
619
|
+
const [ax, ay, bx, by] = witnesses(st, k)
|
|
620
|
+
const [a0x, a0y] = toWorldBefore(a, k.ax, k.ay)
|
|
621
|
+
const [b0x, b0y] = b >= 0 ? toWorldBefore(b, k.bx, k.by) : [k.bx, k.by]
|
|
622
|
+
const dx = ax - a0x - (bx - b0x)
|
|
623
|
+
const dy = ay - a0y - (by - b0y)
|
|
624
|
+
const dn = dx * nx + dy * ny
|
|
625
|
+
const tx = dx - dn * nx
|
|
626
|
+
const ty = dy - dn * ny
|
|
627
|
+
const slip = Math.sqrt(tx * tx + ty * ty)
|
|
628
|
+
if (slip === 0) continue
|
|
629
|
+
const qx = (ax + bx) / 2
|
|
630
|
+
const qy = (ay + by) / 2
|
|
631
|
+
const w = inverseMass(st, a, b, tx / slip, ty / slip, qx, qy)
|
|
632
|
+
if (w > 0 && slip / w < k.mu * k.lambda) push(st, a, b, tx / slip, ty / slip, qx, qy, slip, 0)
|
|
633
|
+
}
|
|
634
|
+
pins.forEach((joint, k) => {
|
|
635
|
+
if (st.broken[k]) return
|
|
636
|
+
const a = joint.a
|
|
637
|
+
const [ax, ay] = joint.lax === 0 && joint.lay === 0 ? [st.x[a], st.y[a]] : toWorld(st, a, joint.lax, joint.lay)
|
|
638
|
+
const [bx, by] = joint.b >= 0
|
|
639
|
+
? (joint.lbx === 0 && joint.lby === 0 ? [st.x[joint.b], st.y[joint.b]] : toWorld(st, joint.b, joint.lbx, joint.lby))
|
|
640
|
+
: [joint.ax, joint.ay]
|
|
641
|
+
const dx = bx - ax
|
|
642
|
+
const dy = by - ay
|
|
643
|
+
const dist = Math.sqrt(dx * dx + dy * dy)
|
|
644
|
+
if (dist > joint.breakAt) {
|
|
645
|
+
st.broken[k] = 1
|
|
646
|
+
return
|
|
647
|
+
}
|
|
648
|
+
const stretch = dist - joint.length
|
|
649
|
+
if (dist > 0 && stretch !== 0) {
|
|
650
|
+
// A spring of frequency hz has stiffness m (2 pi hz)^2, and its compliance is the inverse.
|
|
651
|
+
const pull = joint.b >= 0 ? 1 / (invMass[a] + invMass[joint.b] || 1) : mass[a]
|
|
652
|
+
const compliance = joint.hz > 0 ? 1 / (pull * sq(TAU * joint.hz)) : 0
|
|
653
|
+
push(st, a, joint.b, dx / dist, dy / dist, ax, ay, -stretch, compliance)
|
|
654
|
+
}
|
|
655
|
+
if (joint.angleHz > 0 && joint.b < 0) {
|
|
656
|
+
// Turns the body back toward its start angle by the sine of the difference.
|
|
657
|
+
const C = st.s[a] * joint.rc - st.c[a] * joint.rs
|
|
658
|
+
const alpha = 1 / (inertia[a] * sq(TAU * joint.angleHz)) / (h * h)
|
|
659
|
+
turn(st, a, (-C / (invInertia[a] + alpha)) * invInertia[a])
|
|
660
|
+
}
|
|
661
|
+
})
|
|
662
|
+
|
|
663
|
+
for (let i = 0; i < n; i++) {
|
|
664
|
+
if (invMass[i] === 0) continue
|
|
665
|
+
st.vx[i] = (st.x[i] - px[i]) / h
|
|
666
|
+
st.vy[i] = (st.y[i] - py[i]) / h
|
|
667
|
+
st.w[i] = (pc[i] * st.s[i] - ps[i] * st.c[i]) / h
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
// Velocity pass: bounce from the speed before the substep, then sliding friction up to the normal impulse.
|
|
671
|
+
const bounceBelow = 2 * h * Math.sqrt(gx * gx + gy * gy)
|
|
672
|
+
for (const k of contacts) {
|
|
673
|
+
if (k.lambda === 0) continue
|
|
674
|
+
const { a, b, nx, ny } = k
|
|
675
|
+
const [sax, say, sbx, sby] = witnesses(st, k)
|
|
676
|
+
const qx = (sax + sbx) / 2
|
|
677
|
+
const qy = (say + sby) / 2
|
|
678
|
+
const vn = relativeNormalVelocity(st, a, b, nx, ny, qx, qy)
|
|
679
|
+
const target = Math.max(-(Math.abs(k.vn) > bounceBelow ? k.e : 0) * k.vn, 0)
|
|
680
|
+
if (vn < target) {
|
|
681
|
+
const w = inverseMass(st, a, b, nx, ny, qx, qy)
|
|
682
|
+
if (w > 0) impulse(st, a, b, nx, ny, qx, qy, (target - vn) / w)
|
|
683
|
+
}
|
|
684
|
+
const [avx, avy] = pointVelocity(st, a, qx, qy)
|
|
685
|
+
const [bvx, bvy] = b >= 0 ? pointVelocity(st, b, qx, qy) : [0, 0]
|
|
686
|
+
const rvx = bvx - avx
|
|
687
|
+
const rvy = bvy - avy
|
|
688
|
+
const along = rvx * nx + rvy * ny
|
|
689
|
+
const tx = rvx - along * nx
|
|
690
|
+
const ty = rvy - along * ny
|
|
691
|
+
const vt = Math.sqrt(tx * tx + ty * ty)
|
|
692
|
+
if (vt === 0) continue
|
|
693
|
+
const w = inverseMass(st, a, b, tx / vt, ty / vt, qx, qy)
|
|
694
|
+
if (w === 0) continue
|
|
695
|
+
// The normal push moved lambda units of mass times distance in h, an impulse of lambda / h.
|
|
696
|
+
const J = Math.min((k.mu * k.lambda) / h, vt / w)
|
|
697
|
+
impulse(st, a, b, tx / vt, ty / vt, qx, qy, -J)
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
/** @param {WorldState} a @param {WorldState} b @param {number} k @returns {WorldState} */
|
|
703
|
+
const lerp = (a, b, k) => {
|
|
704
|
+
const out = {
|
|
705
|
+
x: a.x.slice(), y: a.y.slice(), c: a.c.slice(), s: a.s.slice(),
|
|
706
|
+
vx: a.vx.slice(), vy: a.vy.slice(), w: a.w.slice(), broken: a.broken.slice(),
|
|
707
|
+
}
|
|
708
|
+
for (let i = 0; i < n; i++) {
|
|
709
|
+
out.x[i] += (b.x[i] - a.x[i]) * k
|
|
710
|
+
out.y[i] += (b.y[i] - a.y[i]) * k
|
|
711
|
+
out.vx[i] += (b.vx[i] - a.vx[i]) * k
|
|
712
|
+
out.vy[i] += (b.vy[i] - a.vy[i]) * k
|
|
713
|
+
out.w[i] += (b.w[i] - a.w[i]) * k
|
|
714
|
+
const c = a.c[i] + (b.c[i] - a.c[i]) * k
|
|
715
|
+
const s = a.s[i] + (b.s[i] - a.s[i]) * k
|
|
716
|
+
const len = Math.sqrt(c * c + s * s) || 1
|
|
717
|
+
out.c[i] = c / len
|
|
718
|
+
out.s[i] = s / len
|
|
719
|
+
}
|
|
720
|
+
return out
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
const sim = simulate({
|
|
724
|
+
init, step, lerp, hz, start, snapshotEvery,
|
|
725
|
+
params: { bodies: bodies.map(b => ({ ...b, kinematic: b.kinematic === undefined ? undefined : String(b.kinematic) })), joints, planes, gravity, substeps },
|
|
726
|
+
})
|
|
727
|
+
|
|
728
|
+
/** @param {string | number} ref */
|
|
729
|
+
const index = ref => bodyIndex(ref, 'physics')
|
|
730
|
+
return Object.freeze({
|
|
731
|
+
sim,
|
|
732
|
+
/** The body specs as given, in order. */
|
|
733
|
+
spec: Object.freeze([...bodies]),
|
|
734
|
+
/** @param {number} t */
|
|
735
|
+
at: t => sim.at(t),
|
|
736
|
+
index,
|
|
737
|
+
...bodyViews(sim, index),
|
|
738
|
+
/** A hash of the exact state at a tick, for checking that two machines agree. @param {number} tick */
|
|
739
|
+
hash: tick => hash(sim.tick(tick)),
|
|
740
|
+
})
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
/**
|
|
744
|
+
* Group props and instances data for the bodies of a world whose state holds x, y, c (cosine) and s (sine) per body.
|
|
745
|
+
* physics() and the Rapier adapter share it.
|
|
746
|
+
* @param {{ at: (t: number) => { x: ArrayLike<number>, y: ArrayLike<number>, c: ArrayLike<number>, s: ArrayLike<number> } }} sim
|
|
747
|
+
* @param {(ref: string | number) => number} index
|
|
748
|
+
*/
|
|
749
|
+
export function bodyViews(sim, index) {
|
|
750
|
+
return {
|
|
751
|
+
/**
|
|
752
|
+
* A body's place as group props.
|
|
753
|
+
* @param {string | number} ref
|
|
754
|
+
*/
|
|
755
|
+
body(ref) {
|
|
756
|
+
const i = index(ref)
|
|
757
|
+
return {
|
|
758
|
+
x: (/** @type {number} */ t) => sim.at(t).x[i],
|
|
759
|
+
y: (/** @type {number} */ t) => sim.at(t).y[i],
|
|
760
|
+
rotation: (/** @type {number} */ t) => {
|
|
761
|
+
const st = sim.at(t)
|
|
762
|
+
return Math.atan2(st.s[i], st.c[i]) / DEG
|
|
763
|
+
},
|
|
764
|
+
}
|
|
765
|
+
},
|
|
766
|
+
/**
|
|
767
|
+
* Instances data for many bodies at once: their positions and angles, with optional per-body scale, opacity and
|
|
768
|
+
* colour index.
|
|
769
|
+
* @param {ReadonlyArray<string | number>} refs
|
|
770
|
+
* @param {{ scale?: (i: number, t: number) => number, opacity?: (i: number, t: number) => number,
|
|
771
|
+
* color?: (i: number, t: number) => number }} [style] i is the position in refs.
|
|
772
|
+
* @returns {(t: number) => Float32Array}
|
|
773
|
+
*/
|
|
774
|
+
instances(refs, { scale, opacity, color } = {}) {
|
|
775
|
+
const list = refs.map(index)
|
|
776
|
+
return t => {
|
|
777
|
+
const st = sim.at(t)
|
|
778
|
+
const out = new Float32Array(list.length * STRIDE)
|
|
779
|
+
list.forEach((i, k) => {
|
|
780
|
+
const o = k * STRIDE
|
|
781
|
+
const size = scale ? scale(k, t) : 1
|
|
782
|
+
out[o] = st.x[i]
|
|
783
|
+
out[o + 1] = st.y[i]
|
|
784
|
+
out[o + 2] = Math.atan2(st.s[i], st.c[i]) / DEG
|
|
785
|
+
out[o + 3] = size
|
|
786
|
+
out[o + 4] = size
|
|
787
|
+
out[o + 5] = opacity ? opacity(k, t) : 1
|
|
788
|
+
out[o + 6] = color ? color(k, t) : -1
|
|
789
|
+
})
|
|
790
|
+
return out
|
|
791
|
+
}
|
|
792
|
+
},
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
const TWO_32 = 4294967296
|
|
797
|
+
|
|
798
|
+
/**
|
|
799
|
+
* Simulated particles that bounce: off planes, and off the bodies of a physics world at the same moment, so sparks
|
|
800
|
+
* skitter across a floor or ricochet off a moving ball. Births follow the same rules as the analytic particles addon
|
|
801
|
+
* (rate, bursts, seeded randomness), and the result is one instances node.
|
|
802
|
+
* @param {import('../core/nodes.js').CommonProps & {
|
|
803
|
+
* base: import('../core/nodes.js').Node, rate?: number, start?: number, end?: number,
|
|
804
|
+
* bursts?: ReadonlyArray<{ at: number, count: number }>, life?: number | readonly [number, number],
|
|
805
|
+
* origin?: Value<readonly [number, number]>, speed?: number | readonly [number, number],
|
|
806
|
+
* angle?: number | readonly [number, number], gravity?: readonly [number, number], drag?: number,
|
|
807
|
+
* restitution?: number, friction?: number, planes?: Plane[], world?: ReturnType<typeof physics>,
|
|
808
|
+
* align?: boolean, scale?: number | readonly [number, number], grow?: (u: number) => number,
|
|
809
|
+
* opacity?: (u: number) => number, colors?: string[], seed?: string | number, hz?: number }} options
|
|
810
|
+
* Times are scene seconds. restitution (default 0.4) is the bounce and friction (default 0.2) the share of sliding
|
|
811
|
+
* speed lost per bounce.
|
|
812
|
+
* @returns {import('../core/nodes.js').Node}
|
|
813
|
+
*/
|
|
814
|
+
export function simParticles({
|
|
815
|
+
base, rate = 0, start = 0, end = Infinity, bursts = [], life = 1, origin = [0, 0], speed = 200, angle = [0, 360],
|
|
816
|
+
gravity = [0, 980], drag = 0, restitution = 0.4, friction = 0.2, planes = [], world, align = false, scale = 1,
|
|
817
|
+
grow, opacity, colors, seed = 0, hz = 120, ...props
|
|
818
|
+
}) {
|
|
819
|
+
const seedWord = seedOf(seed)
|
|
820
|
+
const pick = (/** @type {number | readonly [number, number]} */ range, /** @type {number} */ k) =>
|
|
821
|
+
typeof range === 'number' ? range : range[0] + (range[1] - range[0]) * k
|
|
822
|
+
/** @param {number} source @param {number} index @param {number} channel */
|
|
823
|
+
const random = (source, index, channel) => finish(mixWord(mixWord(mixWord(seedWord, source), index), channel)) / TWO_32
|
|
824
|
+
const walls = planes.map((p, k) => {
|
|
825
|
+
const len = Math.sqrt(p.normal[0] * p.normal[0] + p.normal[1] * p.normal[1])
|
|
826
|
+
if (!(len > 0)) throw new RangeError(`simParticles: plane ${k} needs a normal`)
|
|
827
|
+
return { nx: p.normal[0] / len, ny: p.normal[1] / len, d: (p.point[0] * p.normal[0] + p.point[1] * p.normal[1]) / len }
|
|
828
|
+
})
|
|
829
|
+
const [gx, gy] = gravity
|
|
830
|
+
const shades = colors?.length ?? 0
|
|
831
|
+
// The radius of a circle around each body, to skip the far ones cheaply.
|
|
832
|
+
const bounds = (world?.spec ?? []).map(b => (b.shape.kind === 'circle' ? b.shape.r : Math.sqrt(b.shape.w * b.shape.w + b.shape.h * b.shape.h) / 2))
|
|
833
|
+
|
|
834
|
+
/** Particles born in [from, to), as [source, index, birth time]. @param {number} from @param {number} to */
|
|
835
|
+
const births = (from, to) => {
|
|
836
|
+
/** @type {[number, number, number][]} */
|
|
837
|
+
const out = []
|
|
838
|
+
if (rate > 0) {
|
|
839
|
+
for (let k = Math.max(0, Math.ceil((from - start) * rate - 1e-9)); ; k++) {
|
|
840
|
+
const born = start + k / rate
|
|
841
|
+
if (born >= to - 1e-9 || born >= end) break
|
|
842
|
+
out.push([0, k, born])
|
|
843
|
+
}
|
|
844
|
+
}
|
|
845
|
+
bursts.forEach((b, j) => {
|
|
846
|
+
if (b.at >= from - 1e-9 && b.at < to - 1e-9) for (let m = 0; m < b.count; m++) out.push([j + 1, m, b.at])
|
|
847
|
+
})
|
|
848
|
+
return out
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
/**
|
|
852
|
+
* @typedef {{ source: number[], index: number[], born: number[], x: number[], y: number[], vx: number[], vy: number[] }} Swarm
|
|
853
|
+
*/
|
|
854
|
+
|
|
855
|
+
/** Pushes a particle out of the world's bodies and bounces it off their surfaces. @param {Swarm} s @param {number} k @param {WorldState} w */
|
|
856
|
+
const hitBodies = (s, k, w) => {
|
|
857
|
+
if (!world) return
|
|
858
|
+
for (let i = 0; i < w.x.length; i++) {
|
|
859
|
+
const dx = s.x[k] - w.x[i]
|
|
860
|
+
const dy = s.y[k] - w.y[i]
|
|
861
|
+
const reach = bounds[i]
|
|
862
|
+
if (dx > reach || dx < -reach || dy > reach || dy < -reach) continue
|
|
863
|
+
const shape = /** @type {BodySpec} */ (world.spec[i]).shape
|
|
864
|
+
let nx = 0
|
|
865
|
+
let ny = 0
|
|
866
|
+
let depth = 0
|
|
867
|
+
if (shape.kind === 'circle') {
|
|
868
|
+
const d2 = dx * dx + dy * dy
|
|
869
|
+
if (d2 >= shape.r * shape.r) continue
|
|
870
|
+
const d = Math.sqrt(d2) || 1
|
|
871
|
+
nx = dx / d
|
|
872
|
+
ny = dy / d
|
|
873
|
+
depth = shape.r - d
|
|
874
|
+
} else {
|
|
875
|
+
const c = w.c[i]
|
|
876
|
+
const sn = w.s[i]
|
|
877
|
+
const lx = c * dx + sn * dy
|
|
878
|
+
const ly = -sn * dx + c * dy
|
|
879
|
+
const ox = shape.w / 2 - Math.abs(lx)
|
|
880
|
+
const oy = shape.h / 2 - Math.abs(ly)
|
|
881
|
+
if (ox <= 0 || oy <= 0) continue
|
|
882
|
+
const [lnx, lny] = ox < oy ? [lx < 0 ? -1 : 1, 0] : [0, ly < 0 ? -1 : 1]
|
|
883
|
+
nx = c * lnx - sn * lny
|
|
884
|
+
ny = sn * lnx + c * lny
|
|
885
|
+
depth = Math.min(ox, oy)
|
|
886
|
+
}
|
|
887
|
+
bounce(s, k, nx, ny, depth, w.vx[i], w.vy[i])
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
|
|
891
|
+
/** @param {Swarm} s @param {number} k @param {number} nx @param {number} ny @param {number} depth @param {number} bvx @param {number} bvy */
|
|
892
|
+
const bounce = (s, k, nx, ny, depth, bvx, bvy) => {
|
|
893
|
+
s.x[k] += nx * depth
|
|
894
|
+
s.y[k] += ny * depth
|
|
895
|
+
const rvx = s.vx[k] - bvx
|
|
896
|
+
const rvy = s.vy[k] - bvy
|
|
897
|
+
const vn = rvx * nx + rvy * ny
|
|
898
|
+
if (vn >= 0) return
|
|
899
|
+
const tx = rvx - vn * nx
|
|
900
|
+
const ty = rvy - vn * ny
|
|
901
|
+
s.vx[k] = bvx + tx * (1 - friction) - vn * restitution * nx
|
|
902
|
+
s.vy[k] = bvy + ty * (1 - friction) - vn * restitution * ny
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
const sim = simulate({
|
|
906
|
+
hz,
|
|
907
|
+
start,
|
|
908
|
+
lerp: false,
|
|
909
|
+
params: { rate, end, bursts, life, speed, angle, gravity, drag, restitution, friction, planes, seed, origin: String(origin) },
|
|
910
|
+
init: () => ({ source: [], index: [], born: [], x: [], y: [], vx: [], vy: [] }),
|
|
911
|
+
step: (/** @type {Swarm} */ s, _input, dt, tick) => {
|
|
912
|
+
const from = start + tick * dt
|
|
913
|
+
const to = from + dt
|
|
914
|
+
const w = world ? world.at(to) : null
|
|
915
|
+
// Drop the expired, keeping order so the state is the same however the frame was reached.
|
|
916
|
+
let keep = 0
|
|
917
|
+
for (let k = 0; k < s.x.length; k++) {
|
|
918
|
+
if (to - s.born[k] >= pick(life, random(s.source[k], s.index[k], 0))) continue
|
|
919
|
+
for (const key of /** @type {(keyof Swarm)[]} */ (['source', 'index', 'born', 'x', 'y', 'vx', 'vy'])) s[key][keep] = s[key][k]
|
|
920
|
+
keep++
|
|
921
|
+
}
|
|
922
|
+
for (const key of /** @type {(keyof Swarm)[]} */ (['source', 'index', 'born', 'x', 'y', 'vx', 'vy'])) s[key].length = keep
|
|
923
|
+
const keepSpeed = 1 / (1 + dt * drag)
|
|
924
|
+
for (let k = 0; k < s.x.length; k++) {
|
|
925
|
+
s.vx[k] = (s.vx[k] + dt * gx) * keepSpeed
|
|
926
|
+
s.vy[k] = (s.vy[k] + dt * gy) * keepSpeed
|
|
927
|
+
s.x[k] += dt * s.vx[k]
|
|
928
|
+
s.y[k] += dt * s.vy[k]
|
|
929
|
+
for (const wall of walls) {
|
|
930
|
+
const depth = wall.d - (s.x[k] * wall.nx + s.y[k] * wall.ny)
|
|
931
|
+
if (depth > 0) bounce(s, k, wall.nx, wall.ny, depth, 0, 0)
|
|
932
|
+
}
|
|
933
|
+
if (w) hitBodies(s, k, w)
|
|
934
|
+
}
|
|
935
|
+
// Newborns move only for the part of the tick since their birth.
|
|
936
|
+
for (const [source, index, born] of births(from, to)) {
|
|
937
|
+
const [ox, oy] = at(origin, born)
|
|
938
|
+
const direction = pick(angle, random(source, index, 1)) * DEG
|
|
939
|
+
const v = pick(speed, random(source, index, 2))
|
|
940
|
+
const part = to - born
|
|
941
|
+
const vx = v * dmath.cos(direction) + part * gx
|
|
942
|
+
const vy = v * dmath.sin(direction) + part * gy
|
|
943
|
+
s.source.push(source)
|
|
944
|
+
s.index.push(index)
|
|
945
|
+
s.born.push(born)
|
|
946
|
+
s.x.push(ox + part * vx)
|
|
947
|
+
s.y.push(oy + part * vy)
|
|
948
|
+
s.vx.push(vx)
|
|
949
|
+
s.vy.push(vy)
|
|
950
|
+
}
|
|
951
|
+
},
|
|
952
|
+
})
|
|
953
|
+
|
|
954
|
+
/** @param {number} t */
|
|
955
|
+
const data = t => {
|
|
956
|
+
const s = /** @type {Swarm} */ (sim.at(t))
|
|
957
|
+
const out = new Float32Array(s.x.length * STRIDE)
|
|
958
|
+
let n = 0
|
|
959
|
+
for (let k = 0; k < s.x.length; k++) {
|
|
960
|
+
const age = t - s.born[k]
|
|
961
|
+
const span = pick(life, random(s.source[k], s.index[k], 0))
|
|
962
|
+
if (age < 0 || age >= span) continue
|
|
963
|
+
const u = age / span
|
|
964
|
+
const fade = opacity ? opacity(u) : 1
|
|
965
|
+
if (!(fade > 0)) continue
|
|
966
|
+
const size = pick(scale, random(s.source[k], s.index[k], 3)) * (grow ? grow(u) : 1)
|
|
967
|
+
const o = n * STRIDE
|
|
968
|
+
out[o] = s.x[k]
|
|
969
|
+
out[o + 1] = s.y[k]
|
|
970
|
+
out[o + 2] = align ? Math.atan2(s.vy[k], s.vx[k]) / DEG : 0
|
|
971
|
+
out[o + 3] = size
|
|
972
|
+
out[o + 4] = size
|
|
973
|
+
out[o + 5] = Math.min(1, fade)
|
|
974
|
+
out[o + 6] = shades === 0 ? -1 : Math.floor(random(s.source[k], s.index[k], 4) * shades)
|
|
975
|
+
n++
|
|
976
|
+
}
|
|
977
|
+
return out.subarray(0, n * STRIDE)
|
|
978
|
+
}
|
|
979
|
+
return instances({ ...props, base, data, ...(colors ? { colors } : {}) })
|
|
980
|
+
}
|