@margoengine/ragdoll 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,195 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { Mesh } from '@margoengine/core/extension';
3
+ import type { RagdollMotors } from './powered.js';
4
+ import type { Ragdoll, RagdollPart } from './ragdoll.js';
5
+ type Vec3 = [number, number, number];
6
+ /** Options of {@link addRagdollBalance}. */
7
+ export interface RagdollBalanceOptions {
8
+ /** The two foot bones. Each foot's parent bone must be a knee hinge, as `humanoidProfile` builds. */
9
+ feet: readonly [Mesh | RagdollPart, Mesh | RagdollPart];
10
+ /** Seconds a step takes. Default 0.28. */
11
+ stepTime?: number;
12
+ /** How high a foot lifts, as a share of the leg's length. Default 0.15. */
13
+ stepHeight?: number;
14
+ /** How far the capture point may leave the feet before a step, as a share of the leg's length. Default 0.2. */
15
+ stepTrigger?: number;
16
+ /** Hip height held, as a share of the height the character was added at. Default 0.97: knees a little bent. */
17
+ stance?: number;
18
+ /** Share of the upper body's weight an outside force carries, 0 to 1. Default 0: it stands on its own legs. */
19
+ carry?: number;
20
+ /** Frequency in rad/s of the turn that holds the hips upright, answered through the legs by the ground. Default 10. */
21
+ upright?: number;
22
+ /** Largest turn that gives, in rad/s². A harder blow than this can hold knocks the character over. Default 40. */
23
+ maxUpright?: number;
24
+ /** Tilt of the hips in radians past which the character has fallen and every assist stops. Default 0.8. */
25
+ fallTilt?: number;
26
+ /** World gravity along up, in m/s². Default 9.81. */
27
+ gravity?: number;
28
+ }
29
+ /** What a balancing character is doing. */
30
+ export type RagdollBalanceState = 'standing' | 'stepping' | 'fallen';
31
+ /** A character keeping its feet ({@link addRagdollBalance}). */
32
+ export declare class RagdollBalance {
33
+ private readonly ragdoll;
34
+ private readonly motors;
35
+ /** What the character is doing. */
36
+ state: RagdollBalanceState;
37
+ /** Steps started so far. */
38
+ steps: number;
39
+ /** Where a step now would stop the fall, in the world, on the ground. */
40
+ capture: Vec3;
41
+ /** Share of the whole body's weight the `carry` force gave at the last physics step: 0 unless `carry` is set. */
42
+ carried: number;
43
+ private readonly legs;
44
+ private readonly upper;
45
+ private readonly standing;
46
+ private readonly up;
47
+ private readonly forward;
48
+ private readonly total;
49
+ /** Height of a planted ankle. */
50
+ private floor;
51
+ /** From the right ankle to the left at rest. */
52
+ private readonly stanceLine;
53
+ private readonly upperMass;
54
+ /** Each bone's centre of mass in its own frame. */
55
+ private readonly massPoints;
56
+ private readonly upperShare;
57
+ private readonly height;
58
+ private readonly natural;
59
+ private readonly stepTime;
60
+ private readonly lift;
61
+ private readonly trigger;
62
+ private readonly stance;
63
+ private readonly carry;
64
+ private readonly upright;
65
+ private readonly maxUpright;
66
+ private readonly fallTilt;
67
+ private readonly gravity;
68
+ private readonly hipsOverFeet;
69
+ private readonly off;
70
+ private disposed;
71
+ /** How far through {@link SETTLE_TIME}, 0 to 1. */
72
+ private settled;
73
+ private stanceNow;
74
+ /** False until the first step, when added inertia takes effect: see {@link control}. */
75
+ private primed;
76
+ /** Each bone's force and torque for this step, xyz each, and what the bodies hold from the last. */
77
+ private readonly wanted;
78
+ private readonly given;
79
+ /** The feet's colliders as they came, for {@link dispose}. */
80
+ private readonly soles;
81
+ /** Where the hips stood at the last step, and how they moved to get there: see {@link readHips}. */
82
+ private hipsWere;
83
+ private hipsSpeed;
84
+ private hipsSpin;
85
+ /** @internal use {@link addRagdollBalance}. */
86
+ constructor(ragdoll: Ragdoll, motors: RagdollMotors, options: RagdollBalanceOptions);
87
+ /** Radians the hips lean from how they stood. */
88
+ get tilt(): number;
89
+ private step;
90
+ /**
91
+ * How the hips moved over the last step, from where they went. The velocity a body reports at the end of a step holds what
92
+ * the solver's last pass left in it: Seed-san's hips reported 0.02 m/s one way while they moved 0.008 m/s the other, and the
93
+ * height's spring rang on that at half the frame rate.
94
+ */
95
+ private readHips;
96
+ /**
97
+ * Hands the bodies what this step wants as forces. A force goes through every solver pass; an impulse would land before the
98
+ * first, where one pass's share of friction and of the sole's weight must take a whole step's kick, so more passes meant
99
+ * less hold and the feet crept at the same speed on every figure. Only the change is added: a force stays until taken
100
+ * off, and anyone else's stays on the body. A bone that is not dynamic holds its force out of reach, so it is cleared.
101
+ */
102
+ private settle;
103
+ /** Adds to what bone `part` is given this step, N and N m. */
104
+ private give;
105
+ private control;
106
+ /** The centre of mass of the whole body, and its velocity. */
107
+ private massCentre;
108
+ /**
109
+ * A stance knee and ankle have their torques from {@link carryWeight}. A solver motor on a joint the body's weight goes through
110
+ * slides the feet along the floor, a body at rest included, in proportion to its damping and stiffness: RiggedFigure 0.045 m
111
+ * in five seconds through its knees, Knight 0.003 m through its ankles. So a stance knee has only a spring, with no damper
112
+ * and growing with how far it is off its bend, and a stance ankle keeps the rod figure's gains, see
113
+ * {@link RagdollMotors.standing}. Without the spring a thrown leg lands loose and the character stumbles on. A swinging foot
114
+ * gets a motor that keeps it level. The listeners run in the order they were added, so these come after the rod motors'
115
+ * own step and replace it.
116
+ */
117
+ private holdJoints;
118
+ /**
119
+ * The swing foot's motor target, relative to its shin: the sole level, as SIMBICON keeps a swing foot parallel to the ground
120
+ * (K. Yin, K. Loken, M. van de Panne, SIGGRAPH 2007), heading where the hips head now, and inside the ankle's limits as every
121
+ * motor target is. The foot's rest pose in the world was level but kept the heading the character stood with, so once the
122
+ * body turned about the vertical it asked the ankle for more twist than it has: on a joint whose limits hold, the motor and
123
+ * the limit pulled against each other through the shin and turned the leg and the body with them.
124
+ */
125
+ private swingFoot;
126
+ /**
127
+ * A foot level on the ground, heading as `turned` heads now against `from` (the foot's own rest by default, so a planted foot
128
+ * keeps the heading it has), relative to its shin and inside the ankle's limits.
129
+ */
130
+ private levelFoot;
131
+ /** The hinge angle the knee stands at. */
132
+ private kneeAngle;
133
+ /** True for a bone of a stance leg, which {@link carryWeight} holds. */
134
+ private planted;
135
+ /** How far the sole of a foot reaches from the ankle: the points of its collider near its lowest point. */
136
+ private soleOf;
137
+ /**
138
+ * Gives a hull foot a sole of four corners on one plane, the box of what {@link soleOf} found, and keeps the rest of the
139
+ * hull. A hull fitted to a boot has a sole of many points a few millimetres apart in height, and a contact keeps four of
140
+ * them for the solver: which four changes with the slightest turn, so the foot rocked and dropped on a point left out,
141
+ * and the body shook. Four corners are all kept, and they are the sole the ankle torques reckon with.
142
+ */
143
+ private flatten;
144
+ /**
145
+ * Carries the body through the legs: the force and turn the stance legs must give at the hips to hold them at their
146
+ * height, the centre of mass over the feet and the upper body upright, as joint torques by the transpose of the leg's
147
+ * Jacobian (J. Pratt et al., "Virtual Model Control", 1997), each an equal and opposite pair on the two bones of its joint.
148
+ */
149
+ private carryWeight;
150
+ /** The turn this step gives the upper body toward how it stood, about its own centre of mass. */
151
+ private uprightTurn;
152
+ /** The capture point: the centre of mass plus its velocity over the pendulum's natural frequency, on the ground. */
153
+ private capturePoint;
154
+ /** How far the capture point lies from the line between two planted feet, across the ground. */
155
+ private outside;
156
+ private startStep;
157
+ /**
158
+ * How long this step may take. The capture point runs away from the stance foot as e^(omega t) (J. Pratt et al., "Capture
159
+ * Point: A Step toward Humanoid Push Recovery", Humanoids 2006; J. Englsberger et al., "Bipedal walking control based on
160
+ * Capture Point dynamics", IROS 2011), so a step that takes `stepTime` lands where the capture point has gone, and after a
161
+ * hard push that is past where the leg reaches: the stance foot is then dragged off the ground and the body has nothing
162
+ * under it. The step takes no longer than the capture point needs to run from d, its distance from the stance foot now, to the
163
+ * edge of the step's reach, ln(reach / d) / omega, as step timing adaptation chooses it (M. Khadiv, A. Herzog, S. A. A. Moosavian,
164
+ * L. Righetti, "Walking Control Based on Step Timing Adaptation", IEEE T-RO 2020), and no less than half a natural period.
165
+ */
166
+ private stepDuration;
167
+ /** True when a planted foot's ankle stands well above the ground: a push lifted it, and it carries nothing. */
168
+ private lifted;
169
+ /** Where a step of `leg` lands: beside the capture point by half the rest stance, on the foot's own side. */
170
+ private landing;
171
+ /** Sets a leg's motors so its foot reaches the plant or the swing from `hips`, where the hips should be. */
172
+ private driveLeg;
173
+ /** The outside help when `carry` is set: a capped force under the upper body, moved as one rigid body. */
174
+ private assist;
175
+ private fall;
176
+ /** Stands again from where the feet are, after a get-up or a teleport. */
177
+ reset(): this;
178
+ /** Stops balancing and hands the legs back to the animation's pose. Safe to call twice. */
179
+ dispose(): void;
180
+ [Symbol.dispose]: () => void;
181
+ }
182
+ /**
183
+ * Keeps a powered ragdoll on its feet: it stands, and steps to where its momentum says it must when pushed. Add it with the
184
+ * character standing still in the pose to hold, before `activate`. It stands on its own legs: every torque is a pair inside
185
+ * the body, the ground answers within the sole, and a hard enough blow knocks it over. It adds inertia to the feet and shins
186
+ * and solver passes to the character's island and gives a hull foot a flat sole of four corners, and `dispose` takes them away.
187
+ * @example
188
+ * const motors = addRagdollMotors(ragdoll, { frequency: 8 });
189
+ * const balance = addRagdollBalance(ragdoll, motors, { feet: [leftFoot, rightFoot] });
190
+ * ragdoll.activate();
191
+ * motors.hit(chest, [0, 0, -40]); // it stumbles and catches itself; balance.steps counts how
192
+ * @throws TypeError without a ragdoll, motors or two feet, RangeError for a foot with no knee hinge or an option out of range.
193
+ */
194
+ export declare function addRagdollBalance(ragdoll: Ragdoll, motors: RagdollMotors, options: RagdollBalanceOptions): RagdollBalance;
195
+ export {};
@@ -0,0 +1,468 @@
1
+ import { n as e, r as t } from "./limits-CCe6Pdej.js";
2
+ import { MargoError as n } from "@margoengine/math/errors";
3
+ import { conjugateQuaternion as r, multiplyQuaternions as i, rotateByQuaternion as a } from "@margoengine/math/quat";
4
+ //#region src/balance.ts
5
+ var o = (e, t) => [
6
+ e[0] + t[0],
7
+ e[1] + t[1],
8
+ e[2] + t[2]
9
+ ], s = (e, t) => [
10
+ e[0] - t[0],
11
+ e[1] - t[1],
12
+ e[2] - t[2]
13
+ ], c = (e, t) => [
14
+ e[0] * t,
15
+ e[1] * t,
16
+ e[2] * t
17
+ ], l = (e, t) => e[0] * t[0] + e[1] * t[1] + e[2] * t[2], u = (e) => Math.hypot(e[0], e[1], e[2]), d = (e) => c(e, 1 / u(e)), f = (e, t) => [
18
+ e[1] * t[2] - e[2] * t[1],
19
+ e[2] * t[0] - e[0] * t[2],
20
+ e[0] * t[1] - e[1] * t[0]
21
+ ], p = (e, t) => {
22
+ let n = Math.sin(t / 2);
23
+ return [
24
+ e[0] * n,
25
+ e[1] * n,
26
+ e[2] * n,
27
+ Math.cos(t / 2)
28
+ ];
29
+ };
30
+ function m(e, t) {
31
+ let n = f(e, t), r = 1 + l(e, t), i = Math.hypot(n[0], n[1], n[2], r);
32
+ return i < 1e-9 ? [
33
+ 1,
34
+ 0,
35
+ 0,
36
+ 0
37
+ ] : [
38
+ n[0] / i,
39
+ n[1] / i,
40
+ n[2] / i,
41
+ r / i
42
+ ];
43
+ }
44
+ var h = 400, g = 12, _ = 6, v = 30, y = 50, b = .15, x = .9, S = .012, C = 16, w = .25, T = .25, E = .1, D = .8, O = .25, k = .4, A = (e) => e * e * (3 - 2 * e), j = (e, t, n, r, i) => {
45
+ let a = e ?? t;
46
+ if (!(a >= n && a <= r)) throw RangeError(`Ragdoll balance ${i} must be from ${n} to ${r}.`);
47
+ return a;
48
+ }, M = class {
49
+ constructor(e, t, n) {
50
+ this.ragdoll = e, this.motors = t, this.state = "standing", this.steps = 0, this.capture = [
51
+ 0,
52
+ 0,
53
+ 0
54
+ ], this.carried = 0, this.up = [
55
+ 0,
56
+ 1,
57
+ 0
58
+ ], this.disposed = !1, this.settled = 0, this.stanceNow = 1, this.primed = !1, this.soles = [], this.hipsWere = null, this.hipsSpeed = [
59
+ 0,
60
+ 0,
61
+ 0
62
+ ], this.hipsSpin = [
63
+ 0,
64
+ 0,
65
+ 0
66
+ ];
67
+ let r = e.bones, i = r[0], a = (e) => {
68
+ let t = e && "body" in e ? e.node : e, n = r.find((e) => e.node === t);
69
+ if (!n) throw RangeError("That node is not a bone of this ragdoll; pass feet from ragdoll.bones.");
70
+ return n;
71
+ };
72
+ if (!Array.isArray(n?.feet) || n.feet.length !== 2) throw TypeError("addRagdollBalance needs two feet: addRagdollBalance(ragdoll, motors, {feet: [left, right]}).");
73
+ let p = (e) => {
74
+ let t = a(e), n = r[t.parent], o = n && r[n.parent];
75
+ if (!o || o === i || n.spec?.type !== "hinge") throw RangeError("Each foot needs a knee hinge and a thigh above it; build the ragdoll with humanoidProfile.");
76
+ let c = o.body.position, f = n.body.position, p = t.body.position;
77
+ return {
78
+ upper: o,
79
+ lower: n,
80
+ foot: t,
81
+ thigh: u(s(f, c)),
82
+ shin: u(s(p, f)),
83
+ rest: d(s(f, c)),
84
+ upperRest: [...o.body.rotation],
85
+ footRest: [...t.body.rotation],
86
+ hip: s(c, i.body.position),
87
+ kneeCap: 0,
88
+ kneeInertia: 0,
89
+ bend: 0,
90
+ restBend: Math.acos(Math.max(-1, Math.min(1, l(d(s(f, c)), d(s(p, f)))))),
91
+ sole: {
92
+ front: 0,
93
+ back: 0,
94
+ left: 0,
95
+ right: 0
96
+ },
97
+ plant: [
98
+ p[0],
99
+ p[1],
100
+ p[2]
101
+ ],
102
+ swing: null
103
+ };
104
+ };
105
+ this.legs = [p(n.feet[0]), p(n.feet[1])];
106
+ let [m, h] = this.legs, g = new Set(this.legs.flatMap(({ upper: e, lower: t, foot: n }) => [
107
+ e,
108
+ t,
109
+ n
110
+ ]));
111
+ for (let e of r) g.has(r[e.parent]) && g.add(e);
112
+ this.upper = r.filter((e) => !g.has(e)), this.standing = [...i.body.rotation];
113
+ let _ = (m.thigh + m.shin + h.thigh + h.shin) / 2, v = c(o(m.plant, h.plant), .5), y = s(m.plant, h.plant);
114
+ this.hipsOverFeet = s(i.body.position, v), this.floor = l(v, this.up), this.stanceLine = y, this.forward = d(f(d(y), this.up));
115
+ for (let e of this.legs) this.flatten(e);
116
+ this.total = r.reduce((e, t) => e + t.body.mass, 0), this.upperMass = this.upper.reduce((e, t) => e + t.body.mass, 0), this.upperShare = this.upperMass / this.total, this.height = l(this.hipsOverFeet, this.up), this.massPoints = r.map((e) => e.body.centerOfMass);
117
+ let b = l(s(this.massCentre().position, v), this.up);
118
+ this.gravity = j(n.gravity, 9.81, .01, 1e3, "gravity");
119
+ let x = S * this.total * (m.thigh + m.shin) ** 2, w = Math.max(0, C - e.physics.solverIterations);
120
+ for (let e of r) e.body.additionalPgsIterations = w;
121
+ for (let { foot: e, lower: n } of this.legs) for (let r of [e, n]) t.addSteadying(r, x);
122
+ for (let e of this.legs) e.kneeCap = this.total * this.gravity * Math.min(e.thigh, e.shin), e.kneeInertia = t.limbInertia(e.lower);
123
+ this.natural = Math.sqrt(this.gravity / b), this.stepTime = j(n.stepTime, .28, .05, 2, "stepTime"), this.lift = j(n.stepHeight, .15, 0, 1, "stepHeight") * _, this.trigger = j(n.stepTrigger, .2, 0, 2, "stepTrigger") * _, this.stance = j(n.stance, .97, .5, 1, "stance"), this.carry = j(n.carry, 0, 0, 1, "carry"), this.upright = j(n.upright, 10, 0, 1e3, "upright"), this.maxUpright = j(n.maxUpright, 40, 0, 1e6, "maxUpright"), this.fallTilt = j(n.fallTilt, .8, .01, Math.PI, "fallTilt"), this.wanted = new Float64Array(r.length * 6), this.given = new Float64Array(r.length * 6), this.off = e.physics.on("beforestep", (e) => this.step(e));
124
+ }
125
+ get tilt() {
126
+ let e = a(this.up, i(this.ragdoll.bones[0].body.rotation, r(this.standing)));
127
+ return Math.acos(Math.min(1, Math.max(-1, l(e, this.up))));
128
+ }
129
+ step(e) {
130
+ !this.disposed && this.ragdoll.bones[0].body.valid && (this.wanted.fill(0), this.readHips(e), this.control(e), this.settle());
131
+ }
132
+ readHips(e) {
133
+ let t = this.ragdoll.bones[0].body, n = [
134
+ t.position[0],
135
+ t.position[1],
136
+ t.position[2]
137
+ ], a = [...t.rotation], o = this.hipsWere;
138
+ if (o) {
139
+ let t = i(a, r(o.rotation)), l = t[3] < 0 ? -2 / e : 2 / e;
140
+ this.hipsSpeed = c(s(n, o.position), 1 / e), this.hipsSpin = [
141
+ t[0] * l,
142
+ t[1] * l,
143
+ t[2] * l
144
+ ];
145
+ } else this.hipsSpeed = [
146
+ t.linearVelocity[0],
147
+ t.linearVelocity[1],
148
+ t.linearVelocity[2]
149
+ ], this.hipsSpin = [
150
+ t.angularVelocity[0],
151
+ t.angularVelocity[1],
152
+ t.angularVelocity[2]
153
+ ];
154
+ this.hipsWere = {
155
+ position: n,
156
+ rotation: a
157
+ };
158
+ }
159
+ settle() {
160
+ let { wanted: e, given: t } = this;
161
+ this.ragdoll.bones.forEach((n, r) => {
162
+ let i = r * 6, a = n.body;
163
+ if (a.type !== "dynamic") {
164
+ t.subarray(i, i + 6).some((e) => e !== 0) && a.resetForces(!1), t.fill(0, i, i + 6);
165
+ return;
166
+ }
167
+ let o = [
168
+ e[i] - t[i],
169
+ e[i + 1] - t[i + 1],
170
+ e[i + 2] - t[i + 2]
171
+ ], s = [
172
+ e[i + 3] - t[i + 3],
173
+ e[i + 4] - t[i + 4],
174
+ e[i + 5] - t[i + 5]
175
+ ];
176
+ (o[0] || o[1] || o[2]) && a.addForce(o), (s[0] || s[1] || s[2]) && a.addTorque(s), t.set(e.subarray(i, i + 6), i);
177
+ });
178
+ }
179
+ give(e, t, n) {
180
+ let r = this.ragdoll.bones.indexOf(e) * 6;
181
+ for (let e = 0; e < 3; e++) t && (this.wanted[r + e] += t[e]), n && (this.wanted[r + 3 + e] += n[e]);
182
+ }
183
+ control(e) {
184
+ if (this.state === "fallen" || this.ragdoll.bones[0].body.type !== "dynamic") return;
185
+ if (this.tilt > this.fallTilt) {
186
+ this.fall();
187
+ return;
188
+ }
189
+ for (let e of this.legs) if (!e.swing) {
190
+ let t = [
191
+ e.foot.body.position[0],
192
+ e.foot.body.position[1],
193
+ e.foot.body.position[2]
194
+ ];
195
+ e.plant = o(t, c(this.up, this.floor - l(t, this.up)));
196
+ }
197
+ this.capture = this.capturePoint();
198
+ let [t, n] = this.legs, r = c(o(t.plant, n.plant), .5);
199
+ !(t.swing ? t : n.swing && n) && this.outside(t.plant, n.plant, w) > this.trigger && this.startStep();
200
+ let i = t.swing ? t : n.swing ? n : null, a = r;
201
+ if (i) {
202
+ let e = i === t ? n : t, s = A(Math.min(1, i.swing.t)), l = c(o(i.swing.to, e.plant), .5);
203
+ a = o(c(r, 1 - s), c(l, s));
204
+ }
205
+ this.settled = Math.min(1, this.settled + e / x), this.stanceNow = 1 + (this.stance - 1) * A(this.settled) ** 2;
206
+ let u = s(this.hipsOverFeet, c(this.up, this.height)), d = o(o(a, u), c(this.up, this.height * this.stanceNow));
207
+ for (let t of this.legs) this.driveLeg(t, d, e);
208
+ this.state = this.legs.some((e) => e.swing) ? "stepping" : "standing", this.holdJoints(), this.primed && this.carryWeight(e, this.legs.filter((e) => !e.swing), a), this.primed = !0, this.assist(e, r);
209
+ }
210
+ massCentre() {
211
+ let e = [
212
+ 0,
213
+ 0,
214
+ 0
215
+ ], t = [
216
+ 0,
217
+ 0,
218
+ 0
219
+ ];
220
+ return this.ragdoll.bones.forEach((n, r) => {
221
+ let i = n.body, s = o(i.position, a(this.massPoints[r], i.rotation)), c = i.linearVelocity, l = i.mass;
222
+ for (let n = 0; n < 3; n++) e[n] += s[n] * l, t[n] += c[n] * l;
223
+ }), {
224
+ position: c(e, 1 / this.total),
225
+ velocity: c(t, 1 / this.total)
226
+ };
227
+ }
228
+ holdJoints() {
229
+ let e = this.motors.strength;
230
+ for (let t of this.legs) {
231
+ if (this.motors.standing(t.foot, !t.swing), t.swing) {
232
+ let n = this.motors.limbInertia(t.foot);
233
+ t.foot.joint.setRotationMotor(this.swingFoot(t), {
234
+ model: "force",
235
+ stiffness: n * v * v * e,
236
+ damping: 2 * n * v * Math.sqrt(e),
237
+ maxForce: n * h * e
238
+ });
239
+ continue;
240
+ }
241
+ let n = Math.min(1, Math.abs(t.bend - this.kneeAngle(t)) / b) * e;
242
+ n > 0 ? t.lower.joint.setMotor({
243
+ model: "force",
244
+ targetPosition: t.bend,
245
+ targetVelocity: 0,
246
+ stiffness: t.kneeInertia * y * y * n,
247
+ damping: 0,
248
+ maxForce: t.kneeInertia * h * e
249
+ }) : t.lower.joint.clearMotor();
250
+ }
251
+ }
252
+ swingFoot(e) {
253
+ return this.levelFoot(e, this.ragdoll.bones[0].body.rotation, this.standing);
254
+ }
255
+ levelFoot(n, a, o = n.footRest) {
256
+ let s = t(i(a, r(o)), this.up).twist, c = i(p(this.up, s), n.footRest);
257
+ return e(n.foot, i(r(n.lower.body.rotation), c));
258
+ }
259
+ kneeAngle(e) {
260
+ let t = e.lower.spec.axis, n = i(r(e.lower.rest), i(r(e.upper.body.rotation), e.lower.body.rotation));
261
+ return 2 * Math.atan2(l(n, t), n[3]);
262
+ }
263
+ planted(e) {
264
+ return this.legs.some((t) => !t.swing && (e === t.upper || e === t.lower || e === t.foot));
265
+ }
266
+ soleOf(e) {
267
+ let t = e.foot, n = t.shape, r = f(this.up, this.forward), i = {
268
+ front: t.length / 2,
269
+ back: t.length / 2,
270
+ left: t.length / 4,
271
+ right: t.length / 4
272
+ };
273
+ if (n.type !== "hull") return i;
274
+ let o = [];
275
+ for (let e = 0; e + 2 < n.points.length; e += 3) o.push(a([
276
+ n.points[e],
277
+ n.points[e + 1],
278
+ n.points[e + 2]
279
+ ], t.body.rotation));
280
+ let s = Math.min(...o.map((e) => l(e, this.up))), c = o.filter((e) => l(e, this.up) < s + t.length * E), u = c.map((e) => l(e, this.forward)), d = c.map((e) => l(e, r));
281
+ return {
282
+ front: Math.max(...u),
283
+ back: -Math.min(...u),
284
+ left: Math.max(...d),
285
+ right: -Math.min(...d)
286
+ };
287
+ }
288
+ flatten(e) {
289
+ e.sole = this.soleOf(e);
290
+ let t = e.foot, n = t.shape;
291
+ if (n.type !== "hull") return;
292
+ let i = t.body.rotation, s = r(i), u = f(this.up, this.forward), d = [];
293
+ for (let e = 0; e + 2 < n.points.length; e += 3) d.push(a([
294
+ n.points[e],
295
+ n.points[e + 1],
296
+ n.points[e + 2]
297
+ ], i));
298
+ let p = Math.min(...d.map((e) => l(e, this.up))), m = d.filter((e) => l(e, this.up) >= p + t.length * E), { front: h, back: g, left: _, right: v } = e.sole, y = (e, t) => o(o(c(this.forward, e), c(u, t)), c(this.up, p)), b = [
299
+ y(h, _),
300
+ y(h, -v),
301
+ y(-g, _),
302
+ y(-g, -v)
303
+ ];
304
+ this.soles.push({
305
+ part: t,
306
+ shape: n
307
+ }), this.ragdoll.setShape(t, {
308
+ type: "hull",
309
+ points: [...b, ...m].flatMap((e) => [...a(e, s)])
310
+ });
311
+ }
312
+ carryWeight(e, t, n) {
313
+ if (!t.length) return;
314
+ let { position: r, velocity: i } = this.massCentre(), d = this.ragdoll.bones[0].body, p = this.ragdoll.bones, m = t.length, h = this.motors.strength, v = f(this.up, this.forward), y = this.ragdoll.settings.friction, b = (t) => 1 / (1 + 2 * t * e + t * t * e * e), x = l(c(t.reduce((e, t) => o(e, t.plant), [
315
+ 0,
316
+ 0,
317
+ 0
318
+ ]), 1 / m), this.up) + this.height * this.stanceNow, S = b(g) * (144 * (x - l(d.position, this.up)) - 24 * l(this.hipsSpeed, this.up)), C = _, w = c(s(c(s(n, r), 36), c(i, 12)), b(C)), T = s(w, c(this.up, l(w, this.up))), E = this.total * Math.max(0, this.gravity + S) / m, O = u(T) * this.total / m, k = c(T, this.total / m * Math.min(1, D * y * E / Math.max(O, 1e-9))), A = (e) => o(e.body.position, a(this.massPoints[p.indexOf(e)], e.body.rotation)), j = (e) => c(this.up, e.body.mass * this.gravity), M = 0, N = [
319
+ 0,
320
+ 0,
321
+ 0
322
+ ];
323
+ for (let e of p) {
324
+ if (this.planted(e)) continue;
325
+ let t = A(e);
326
+ M += e.body.mass;
327
+ for (let n = 0; n < 3; n++) N[n] += t[n] * e.body.mass;
328
+ }
329
+ let P = c(N, 1 / M), F = M * Math.max(0, this.gravity + S), I = m === 2 ? s(t[1].plant, t[0].plant) : [
330
+ 0,
331
+ 0,
332
+ 0
333
+ ], L = s(I, c(this.up, l(I, this.up))), R = m === 2 ? Math.min(1, Math.max(0, l(s(r, t[0].plant), L) / Math.max(l(L, L), 1e-9))) : 0, z = t.map((e, t) => {
334
+ let n = m === 2 ? t ? R : 1 - R : 1, r = c(this.up, F * n), i = m === 2 ? c(L, t ? R - 1 : R) : [
335
+ 0,
336
+ 0,
337
+ 0
338
+ ], a = e.upper.body.position, l = e.lower.body.position, u = e.foot.body.position, d = A(e.upper), p = A(e.lower);
339
+ return {
340
+ leg: e,
341
+ atKnee: o(o(f(s(P, l), r), f(s(d, l), j(e.upper))), f(s(a, l), k)),
342
+ atAnkle: o(o(o(f(s(s(P, i), u), r), f(s(d, u), j(e.upper))), f(s(p, u), j(e.lower))), f(s(a, u), k)),
343
+ foot: E * m * n
344
+ };
345
+ }), { turn: B, points: V, centre: H } = this.uprightTurn(e), U = [
346
+ 0,
347
+ 0,
348
+ 0
349
+ ];
350
+ this.upper.forEach((e, t) => {
351
+ let n = s(V[t], H);
352
+ U = o(U, f(n, c(f(B, n), e.body.mass)));
353
+ });
354
+ let W = c(U, 1 / (e * m)), G = m === 2, K = 1, q = (e, t, n, r) => Math.abs(t) < 1e-9 ? 1 : Math.max(0, Math.min(1, ((t > 0 ? r : n) - e) / t));
355
+ if (G) for (let { leg: e, atAnkle: t, foot: n } of z) K = Math.min(K, q(l(t, v), l(W, v), -e.sole.front * n, e.sole.back * n)), K = Math.min(K, q(l(t, this.forward), l(W, this.forward), -e.sole.right * n, e.sole.left * n));
356
+ let J = c(W, K), Y = (e, t, n) => G ? Math.max(t, Math.min(n, e)) : e;
357
+ this.upper.forEach((t, n) => this.give(t, c(f(c(B, K), s(V[n], H)), t.body.mass / e), null));
358
+ for (let { leg: e, atKnee: t, atAnkle: n, foot: r } of z) {
359
+ let i = a(e.lower.spec.axis, e.lower.body.rotation), u = l(o(t, J), i), d = c(i, Math.max(-e.kneeCap, Math.min(e.kneeCap, u)) * h), f = o(n, J), p = Y(l(f, v), -e.sole.front * r, e.sole.back * r), m = Y(l(f, this.forward), -e.sole.right * r, e.sole.left * r), g = .5 * y * r * e.sole.left, _ = Y(l(f, this.up), -g, g), b = c(o(o(c(v, p), c(this.forward, m)), c(this.up, _)), h);
360
+ this.give(e.upper, null, s(d, J)), this.give(e.lower, null, s(b, d)), this.give(e.foot, null, c(b, -1));
361
+ }
362
+ }
363
+ uprightTurn(e) {
364
+ let t = this.ragdoll.bones[0].body, n = i(this.standing, r(t.rotation)), s = n[3] < 0 ? -1 : 1, c = Math.hypot(n[0], n[1], n[2]), l = c > 1e-9 ? 2 * Math.atan2(c, n[3] * s) * s / c : 2 * s, d = this.upright, f = 2 * d, p = e / (1 + f * e + d * d * e * e), m = this.hipsSpin, h = [
365
+ 0,
366
+ 1,
367
+ 2
368
+ ].map((e) => p * (d * d * n[e] * l - f * m[e])), g = this.maxUpright * e, _ = u(h);
369
+ if (_ > g) for (let e = 0; e < 3; e++) h[e] *= g / _;
370
+ let v = this.ragdoll.bones, y = this.upper.map((e) => o(e.body.position, a(this.massPoints[v.indexOf(e)], e.body.rotation))), b = [
371
+ 0,
372
+ 0,
373
+ 0
374
+ ];
375
+ return this.upper.forEach((e, t) => {
376
+ for (let n = 0; n < 3; n++) b[n] += y[t][n] * e.body.mass / this.upperMass;
377
+ }), {
378
+ turn: h,
379
+ points: y,
380
+ centre: b
381
+ };
382
+ }
383
+ capturePoint() {
384
+ let { position: e, velocity: t } = this.massCentre(), n = o(e, c(t, 1 / this.natural)), r = Math.min(l(this.legs[0].plant, this.up), l(this.legs[1].plant, this.up));
385
+ return o(n, c(this.up, r - l(n, this.up)));
386
+ }
387
+ outside(e, t, n = 0) {
388
+ let r = s(t, e), i = s(r, c(this.up, l(r, this.up))), a = Math.min(1 - n, Math.max(n, l(s(this.capture, e), i) / Math.max(l(i, i), 1e-9))), d = s(this.capture, o(e, c(i, a)));
389
+ return u(s(d, c(this.up, l(d, this.up))));
390
+ }
391
+ startStep() {
392
+ let [e, t] = this.legs, n = this.landing(e), r = this.landing(t), i = this.outside(n, t.plant), a = this.outside(r, e.plant), o = this.lifted(e), c = o === this.lifted(t) ? Math.abs(i - a) > this.trigger * T ? i < a : u(s(n, e.plant)) >= u(s(r, t.plant)) : o, l = c ? e : t;
393
+ l.swing = {
394
+ from: l.plant,
395
+ to: c ? n : r,
396
+ t: 0,
397
+ time: this.stepDuration(c ? t : e)
398
+ }, this.steps++;
399
+ }
400
+ stepDuration(e) {
401
+ let t = s(this.capture, e.plant), n = u(s(t, c(this.up, l(t, this.up)))), r = this.height * this.stance, i = e.thigh + e.shin, a = Math.sqrt(Math.max(0, i * i * .9 - r * r)) + u(this.stanceLine) / 2, o = k / this.natural;
402
+ return n > 1e-6 ? Math.max(o, Math.min(this.stepTime, Math.log(Math.max(1, a / n)) / this.natural)) : this.stepTime;
403
+ }
404
+ lifted(e) {
405
+ return l(e.foot.body.position, this.up) - this.floor > this.lift * O;
406
+ }
407
+ landing(e) {
408
+ let t = o(this.ragdoll.bones[0].body.position, e.hip), n = this.height * this.stance, r = e === this.legs[0] ? .5 : -.5, i = o(this.capture, c(this.stanceLine, r));
409
+ i = o(i, c(this.up, this.floor - l(i, this.up)));
410
+ let a = Math.sqrt(Math.max(0, (e.thigh + e.shin) ** 2 * .9 - n * n)), d = s(i, t), f = s(d, c(this.up, l(d, this.up))), p = u(f);
411
+ return p > a && (i = o(i, c(f, a / p - 1))), i;
412
+ }
413
+ driveLeg(e, t, n) {
414
+ let l = this.motors, h = this.ragdoll.bones[0].body, g = e.plant;
415
+ if (e.swing) {
416
+ let t = e.swing;
417
+ t.t += n / t.time;
418
+ let r = Math.min(1, t.t), i = A(r);
419
+ g = o(o(c(t.from, 1 - i), c(t.to, i)), c(this.up, this.lift * Math.sin(Math.PI * r))), t.t >= 1 && (e.swing = null);
420
+ }
421
+ let _ = s(g, o(t, e.hip)), { thigh: v, shin: y } = e, b = Math.min(u(_), (v + y) * .999), x = d(_), S = Math.acos(Math.max(-1, Math.min(1, (v * v + y * y - b * b) / (2 * v * y)))), C = Math.acos(Math.max(-1, Math.min(1, (v * v + b * b - y * y) / (2 * v * b)))), w = a(x, p(d(f(x, this.forward)), C)), T = i(m(e.rest, w), e.upperRest), E = e.lower.spec, D = Math.min(E.limits[1], Math.max(E.limits[0], Math.PI - S - e.restBend));
422
+ l.setTarget(e.upper, i(r(h.rotation), T)), l.setTarget(e.lower, i(e.lower.rest, p(E.axis, D))), l.setTarget(e.foot, this.levelFoot(e, e.foot.body.rotation)), e.bend = D;
423
+ }
424
+ assist(e, t) {
425
+ let n = this.ragdoll.bones[0].body, r = e / (1 + 16 * e + 64 * e * e), i = l(t, this.up) + this.height * this.stance, a = l(n.position, this.up), s = this.gravity * e * this.carry, u = Math.max(0, Math.min(r * (64 * (i - a) - 16 * l(n.linearVelocity, this.up)) + s, s * 1.5));
426
+ if (this.carried = u / (this.gravity * e) * this.upperShare, u > 0) for (let e of this.upper) e.body.setLinearVelocity(o(e.body.linearVelocity, c(this.up, u)));
427
+ }
428
+ fall() {
429
+ this.state = "fallen", this.carried = 0;
430
+ for (let e of this.legs) {
431
+ e.swing = null, this.motors.standing(e.foot, !1);
432
+ for (let t of [
433
+ e.upper,
434
+ e.lower,
435
+ e.foot
436
+ ]) this.motors.setTarget(t, null);
437
+ }
438
+ }
439
+ reset() {
440
+ if (this.disposed) throw new n("disposed", "This balance is disposed; call addRagdollBalance again.");
441
+ for (let e of this.legs) {
442
+ let t = e.foot.body.position;
443
+ e.plant = [
444
+ t[0],
445
+ t[1],
446
+ t[2]
447
+ ], e.swing = null;
448
+ }
449
+ return this.floor = l(c(o(this.legs[0].plant, this.legs[1].plant), .5), this.up), this.hipsWere = null, this.state = "standing", this;
450
+ }
451
+ dispose() {
452
+ if (!this.disposed && (this.disposed = !0, this.off(), this.fall(), this.ragdoll.bones[0].body.valid)) {
453
+ this.wanted.fill(0), this.settle();
454
+ for (let { part: e, shape: t } of this.soles) this.ragdoll.setShape(e, t);
455
+ for (let e of this.ragdoll.bones) e.body.additionalPgsIterations = 0;
456
+ for (let { foot: e, lower: t } of this.legs) for (let n of [e, t]) this.motors.addSteadying(n);
457
+ }
458
+ }
459
+ [Symbol.dispose ?? Symbol()]() {
460
+ this.dispose();
461
+ }
462
+ };
463
+ function N(e, t, n) {
464
+ if (!e?.bones || typeof t?.setTarget != "function") throw TypeError("addRagdollBalance needs a Ragdoll and its motors: addRagdollBalance(ragdoll, motors, {feet}).");
465
+ return new M(e, t, n);
466
+ }
467
+ //#endregion
468
+ export { M as RagdollBalance, N as addRagdollBalance };