@margoengine/physics2d 0.1.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/body.d.ts CHANGED
@@ -59,6 +59,7 @@ export interface BodyOwner2D {
59
59
  readonly scale: number;
60
60
  addCollider(body: Body2D, options: ColliderOptions2D): Collider2D;
61
61
  removeCollider(collider: Collider2D): void;
62
+ replaceColliderShapes(collider: Collider2D, shape: ShapeOptions2D, parts: Described[]): void;
62
63
  removeBody(body: Body2D): void;
63
64
  lockTranslation(body: Body2D, x: boolean, y: boolean): void;
64
65
  retype(body: Body2D, type: BodyType2D): void;
@@ -75,6 +76,8 @@ export declare class Collider2D {
75
76
  private turn;
76
77
  /** The kernel shapes this collider is made of. @internal */
77
78
  readonly shapes: number[];
79
+ /** Stable identifier for collider-pair tracking across multi-shape swaps. @internal */
80
+ readonly uid: number;
78
81
  /** The shape as the kernel was given it, for the queries a character controller makes. @internal */
79
82
  described: Described | null;
80
83
  /** The options it was made with (its shape and settings), to describe it again where it moves. @internal */
@@ -82,8 +85,13 @@ export declare class Collider2D {
82
85
  private removed;
83
86
  private enabled;
84
87
  private savedGroups;
88
+ private explicitMass;
85
89
  /** @internal */
86
- constructor(owner: BodyOwner2D, body: Body2D, shapes: number[], settings: Uint32Array, offset: readonly [number, number], turn: number);
90
+ constructor(owner: BodyOwner2D, body: Body2D, shapes: number[], settings: Uint32Array, offset: readonly [number, number], turn: number, uid?: number);
91
+ /** @internal Current settings words shared across all kernel shapes of this collider. */
92
+ get rawSettings(): Uint32Array;
93
+ /** @internal Re-applies explicit mass or mass properties after kernel shapes are replaced. */
94
+ reapplyMass(): void;
87
95
  /** The kernel's handle of its first shape: unique among live colliders. */
88
96
  get handle(): number;
89
97
  /** The body this collider is on. */
@@ -93,12 +101,12 @@ export declare class Collider2D {
93
101
  markRemoved(): void;
94
102
  private push;
95
103
  /**
96
- * Changes the collider's outline after it is made (Rapier's `setShape`): any one convex outline a collider takes
97
- * (`circle`, `box`, `capsule`, `segment`, `triangle`, a convex `polygon`), placed at the collider's own offset and
98
- * turn. Its material, density, filtering and flags stay; the body's mass follows the new area, and the next step builds
99
- * its contacts from the new outline (a pair already touching stays one: no collision event from the change alone).
100
- * @throws RangeError for an outline of several kernel shapes (a concave polygon, polyline, trimesh, heightfield, compound
101
- * or voxels) or a collider made of several; MargoError (state) once the collider was removed.
104
+ * Changes the collider's outline after it is made (Rapier's `setShape`): any shape a collider takes
105
+ * (`circle`, `box`, `capsule`, `segment`, `triangle`, convex or concave `polygon`, `polyline`, `trimesh`,
106
+ * `heightfield`, `compound`, `voxels` or `halfspace`), placed at the collider's own offset and turn.
107
+ * Its material, density, mass mode, filtering and flags stay; the body's mass follows the new outline, and
108
+ * pairs already touching are carried across the swap without raising a duplicate start event.
109
+ * @throws RangeError for an invalid shape description; MargoError (state) once the collider was removed.
102
110
  */
103
111
  setShape(shape: ShapeOptions2D): void;
104
112
  isSensor(): boolean;
@@ -112,6 +120,10 @@ export declare class Collider2D {
112
120
  /** The questions the hooks are asked about this collider's pairs, as {@link Collider2D.setActiveHooks} sets them. */
113
121
  get activeHooks(): Required<ActiveHooks2D>;
114
122
  setFriction(value: number): void;
123
+ /** Sets the coefficient of rolling resistance (see `ColliderSettings2D.rollingResistance`). */
124
+ setRollingResistance(value: number): void;
125
+ /** The coefficient of rolling resistance. */
126
+ rollingResistance(): number;
115
127
  setRestitution(value: number): void;
116
128
  /** How a contact combines this collider's friction with the other's (Rapier's `setFrictionCombineRule`). */
117
129
  setFrictionCombineRule(rule: CoefficientCombineRule2D): void;
@@ -0,0 +1,161 @@
1
+ import type { Body2D, BodyOptions2D } from './body.js';
2
+ import type { Joint2D, JointOptions2D } from './joint.js';
3
+ import type { Physics2D } from './physics.js';
4
+ import type { Vec2D } from './shapes.js';
5
+ /** A group of bodies and joints made together (Matter.js's Composite): moved, turned and removed as one. */
6
+ export declare class Composite2D implements Disposable {
7
+ private readonly physics;
8
+ /** The bodies, in the order they were made (a grid's row by row). */
9
+ readonly bodies: Body2D[];
10
+ /** The joints between them. */
11
+ readonly joints: Joint2D[];
12
+ /** A grid's columns and rows (a stack, a soft body), for `mesh`; 0 for any other group. */
13
+ readonly columns: number;
14
+ readonly rows: number;
15
+ /** @internal */
16
+ constructor(physics: Physics2D,
17
+ /** The bodies, in the order they were made (a grid's row by row). */
18
+ bodies: Body2D[],
19
+ /** The joints between them. */
20
+ joints: Joint2D[],
21
+ /** A grid's columns and rows (a stack, a soft body), for `mesh`; 0 for any other group. */
22
+ columns?: number, rows?: number);
23
+ /** Moves every body by `offset` (world units), keeping their velocities. */
24
+ translate(offset: Vec2D): this;
25
+ /** Turns every body by `angle` (radians) about `about` (world units, default the bodies' mean position). */
26
+ rotate(angle: number, about?: Vec2D): this;
27
+ /** Removes the bodies and so every joint on them. */
28
+ remove(): void;
29
+ [Symbol.dispose](): void;
30
+ private live;
31
+ }
32
+ /** The body a grid cell gets: its options, or null to leave the cell empty. `position` is filled in. */
33
+ export type CellBody2D = (position: [number, number], column: number, row: number) => BodyOptions2D | null;
34
+ export interface StackOptions2D {
35
+ /** The centre of the first cell (column 0, row 0), world units. */
36
+ position: Vec2D;
37
+ columns: number;
38
+ rows: number;
39
+ /** A cell's width and height, world units. */
40
+ cell: Vec2D;
41
+ /** Space between cells, world units (default [0, 0]). */
42
+ gap?: Vec2D;
43
+ /** Makes each cell's body. */
44
+ body: CellBody2D;
45
+ }
46
+ /**
47
+ * A grid of bodies (Matter.js's `Composites.stack`): columns along +x, rows along +y (down the screen), each cell's
48
+ * body from `body`. Returns them row by row with the grid's size, ready for `mesh`.
49
+ */
50
+ export declare function stack(physics: Physics2D, options: StackOptions2D): Composite2D;
51
+ export interface PyramidOptions2D {
52
+ /** The middle of the base row's bottom edge, world units: where the pyramid stands. */
53
+ position: Vec2D;
54
+ /** Bodies in the base row; each row up holds one fewer, set half a cell in. */
55
+ base: number;
56
+ /** A cell's width and height, world units. */
57
+ cell: Vec2D;
58
+ /** Space between cells, world units (default [0, 0]). */
59
+ gap?: Vec2D;
60
+ body: CellBody2D;
61
+ }
62
+ /**
63
+ * A pyramid (Matter.js's `Composites.pyramid`, Box2D's pyramid): `base` bodies in the bottom row and one fewer in each
64
+ * row up, each row set half a cell in, standing on `position` with up as -y (up the screen).
65
+ */
66
+ export declare function pyramid(physics: Physics2D, options: PyramidOptions2D): Composite2D;
67
+ /** A joint between two neighbours: any joint's options but its anchors. A spring's `restLength` defaults to the gap now. */
68
+ export type LinkOptions2D = Exclude<JointOptions2D, {
69
+ type: 'spring' | 'gear';
70
+ }> | (Omit<Extract<JointOptions2D, {
71
+ type: 'spring';
72
+ }>, 'restLength'> & {
73
+ restLength?: number;
74
+ });
75
+ export interface ChainOptions2D {
76
+ /** Where each body holds the link to the next, in its own frame (world units). */
77
+ anchorA: Vec2D;
78
+ /** Where each body holds the link from the one before. */
79
+ anchorB: Vec2D;
80
+ /** The link (default a revolute joint). */
81
+ link?: LinkOptions2D;
82
+ }
83
+ /**
84
+ * Joins each body to the next (Matter.js's `Composites.chain`): body i's `anchorA` to body i + 1's `anchorB`, by
85
+ * `link`. Returns a group of the same bodies with the new joints.
86
+ */
87
+ export declare function chain(physics: Physics2D, group: Composite2D | readonly Body2D[], options: ChainOptions2D): Composite2D;
88
+ export interface MeshOptions2D {
89
+ /** Also join each cell to its diagonal neighbours (default false). */
90
+ crossBrace?: boolean;
91
+ /** The link between neighbours' centres (default a spring at the gap now, stiffness 1000 N/m, damping 10 N s/m). */
92
+ link?: LinkOptions2D;
93
+ }
94
+ /**
95
+ * Joins a full grid's neighbours (Matter.js's `Composites.mesh`): each body to the one right of it and the one below,
96
+ * and to both below-diagonals with `crossBrace`, centre to centre. `grid` is a `stack` with no empty cells.
97
+ */
98
+ export declare function mesh(physics: Physics2D, grid: Composite2D, options?: MeshOptions2D): Composite2D;
99
+ export interface NewtonsCradleOptions2D {
100
+ /** The first ball's pivot, world units: the pivots run along +x, the balls hang below (+y). */
101
+ position: Vec2D;
102
+ /** Balls (default 5). */
103
+ count?: number;
104
+ /** A ball's radius, world units. */
105
+ radius: number;
106
+ /** Pivot to ball centre, world units. */
107
+ length: number;
108
+ /**
109
+ * Space between neighbouring balls, world units (default 3 cm): wider than the 2 cm within which two shapes get a
110
+ * contact, so each collision is one ball striking the next, as in an ideal cradle. Touching balls are solved together
111
+ * in one step and share the blow among them (as in Box2D and Rapier).
112
+ */
113
+ gap?: number;
114
+ }
115
+ /**
116
+ * A Newton's cradle (Matter.js's `Composites.newtonsCradle`): `count` balls of steel's density in a row `gap` apart,
117
+ * each on a rigid arm from a fixed pivot, bouncing with restitution 1 and no friction. Swing the first out (turn it with
118
+ * its arm: `teleport(position, angle)`) and let it go: the last flies out at the first's speed.
119
+ */
120
+ export declare function newtonsCradle(physics: Physics2D, options: NewtonsCradleOptions2D): Composite2D;
121
+ export interface CarOptions2D {
122
+ /** The body's centre, world units. */
123
+ position: Vec2D;
124
+ /** The body's width and height, world units. */
125
+ width: number;
126
+ height: number;
127
+ /** The wheels' radius, world units. */
128
+ wheelRadius: number;
129
+ /** The suspension's frequency (default 4 Hz) and damping ratio (default 0.7). */
130
+ hertz?: number;
131
+ damping?: number;
132
+ }
133
+ /**
134
+ * A car (Matter.js's `Composites.car`, Box2D's car): a box body on two wheels, each on a wheel joint with a suspension
135
+ * spring, the wheels at the body's corners and below its bottom. Bodies: the body, the rear wheel, the front wheel.
136
+ * Drive it with `joints[i].setMotor`.
137
+ */
138
+ export declare function car(physics: Physics2D, options: CarOptions2D): Composite2D;
139
+ export interface SoftBodyOptions2D {
140
+ /** The first particle's centre, world units. */
141
+ position: Vec2D;
142
+ columns: number;
143
+ rows: number;
144
+ /** A particle's radius, world units. */
145
+ radius: number;
146
+ /** Space between particles, world units (default 0). */
147
+ gap?: number;
148
+ /** Join the diagonals too (default true): it holds its shape. */
149
+ crossBrace?: boolean;
150
+ /** Particles' density (default 1000 kg per square metre) and friction (default 0.4). */
151
+ density?: number;
152
+ friction?: number;
153
+ /** The springs' frequency on a particle (default 8 Hz) and damping ratio (default 0.3). */
154
+ hertz?: number;
155
+ damping?: number;
156
+ }
157
+ /**
158
+ * A soft body (Matter.js's `Composites.softBody`): a grid of circle particles joined to their neighbours by springs of
159
+ * `hertz` on a particle's mass, cross-braced by default. Bodies row by row.
160
+ */
161
+ export declare function softBody(physics: Physics2D, options: SoftBodyOptions2D): Composite2D;
@@ -0,0 +1,183 @@
1
+ //#region src/composites.ts
2
+ var e = class {
3
+ constructor(e, t, n, r = 0, i = 0) {
4
+ this.physics = e, this.bodies = t, this.joints = n, this.columns = r, this.rows = i;
5
+ }
6
+ translate(e) {
7
+ for (let t of this.live()) {
8
+ let [n, r] = t.position;
9
+ t.teleport([n + e[0], r + e[1]]);
10
+ }
11
+ return this;
12
+ }
13
+ rotate(e, n) {
14
+ let r = this.live(), [i, a] = n ?? t(r), [o, s] = [Math.cos(e), Math.sin(e)];
15
+ for (let t of r) {
16
+ let [n, r] = t.position, [c, l] = [n - i, r - a];
17
+ t.teleport([i + o * c - s * l, a + s * c + o * l], t.rotation + e);
18
+ }
19
+ return this;
20
+ }
21
+ remove() {
22
+ for (let e of this.live()) this.physics.removeBody(e);
23
+ }
24
+ [Symbol.dispose]() {
25
+ this.remove();
26
+ }
27
+ live() {
28
+ return this.bodies.filter((e) => !e.isRemoved);
29
+ }
30
+ }, t = (e) => {
31
+ let t = 0, n = 0;
32
+ for (let r of e) [t, n] = [t + r.position[0], n + r.position[1]];
33
+ return e.length ? [t / e.length, n / e.length] : [0, 0];
34
+ }, n = (e, t) => {
35
+ if (!Number.isInteger(e) || e < 1) throw RangeError(`${t} is a whole number of 1 or more; got ${e}.`);
36
+ return e;
37
+ }, r = (e, t, n = 0) => {
38
+ if (!(e > n && e < Infinity)) throw RangeError(`${t} is a finite number above ${n}; got ${e}.`);
39
+ return e;
40
+ };
41
+ function i(t, i) {
42
+ let a = n(i.columns, "columns"), o = n(i.rows, "rows"), [s, c] = [r(i.cell[0], "cell width"), r(i.cell[1], "cell height")], [l, u] = i.gap ?? [0, 0], d = [];
43
+ for (let e = 0; e < o; e++) for (let n = 0; n < a; n++) {
44
+ let r = [i.position[0] + n * (s + l), i.position[1] + e * (c + u)], a = i.body(r, n, e);
45
+ a && d.push(t.addBody(null, {
46
+ ...a,
47
+ position: r
48
+ }));
49
+ }
50
+ return new e(t, d, [], a, o);
51
+ }
52
+ function a(t, i) {
53
+ let a = n(i.base, "base"), [o, s] = [r(i.cell[0], "cell width"), r(i.cell[1], "cell height")], [c, l] = i.gap ?? [0, 0], u = [];
54
+ for (let e = 0; e < a; e++) {
55
+ let n = a - e, r = i.position[0] - (n - 1) * (o + c) / 2, d = i.position[1] - s / 2 - e * (s + l);
56
+ for (let a = 0; a < n; a++) {
57
+ let n = [r + a * (o + c), d], s = i.body(n, a, e);
58
+ s && u.push(t.addBody(null, {
59
+ ...s,
60
+ position: n
61
+ }));
62
+ }
63
+ }
64
+ return new e(t, u, []);
65
+ }
66
+ function o(e, t, n, r, i, a) {
67
+ if (r.type === "spring" && r.restLength === void 0) {
68
+ let [o, c] = [s(t, i), s(n, a)];
69
+ return e.addJoint(t, n, {
70
+ ...r,
71
+ anchorA: i,
72
+ anchorB: a,
73
+ restLength: Math.hypot(c[0] - o[0], c[1] - o[1])
74
+ });
75
+ }
76
+ return e.addJoint(t, n, {
77
+ ...r,
78
+ anchorA: i,
79
+ anchorB: a
80
+ });
81
+ }
82
+ var s = (e, [t, n]) => {
83
+ let [r, i] = e.position, a = e.rotation;
84
+ return [r + Math.cos(a) * t - Math.sin(a) * n, i + Math.sin(a) * t + Math.cos(a) * n];
85
+ };
86
+ function c(t, n, r) {
87
+ let i = [...n instanceof e ? n.bodies : n], a = r.link ?? { type: "revolute" }, s = [];
88
+ for (let e = 0; e + 1 < i.length; e++) s.push(o(t, i[e], i[e + 1], a, r.anchorA, r.anchorB));
89
+ return new e(t, i, s);
90
+ }
91
+ function l(t, n, r = {}) {
92
+ let { columns: i, rows: a, bodies: s } = n;
93
+ if (i * a !== s.length || i === 0) throw TypeError("mesh joins a full grid: a stack with a body in every cell.");
94
+ let c = r.link ?? {
95
+ type: "spring",
96
+ stiffness: 1e3,
97
+ damping: 10
98
+ }, l = (e, t) => s[t * i + e], u = [], d = [0, 0], f = (e, n) => u.push(o(t, e, n, c, d, d));
99
+ for (let e = 0; e < a; e++) for (let t = 0; t < i; t++) t + 1 < i && f(l(t, e), l(t + 1, e)), e + 1 < a && f(l(t, e), l(t, e + 1)), r.crossBrace && e + 1 < a && (t + 1 < i && f(l(t, e), l(t + 1, e + 1)), t > 0 && f(l(t, e), l(t - 1, e + 1)));
100
+ return new e(t, s, [...n.joints, ...u], i, a);
101
+ }
102
+ function u(t, i) {
103
+ let a = n(i.count ?? 5, "count"), o = r(i.radius, "radius"), s = r(i.length, "length"), c = 2 * o + (i.gap ?? .03 / t.scale), l = t.addBody(null, {
104
+ type: "fixed",
105
+ position: [i.position[0], i.position[1]],
106
+ colliders: []
107
+ }), u = [], d = [];
108
+ for (let e = 0; e < a; e++) {
109
+ let n = i.position[0] + c * e, r = t.addBody(null, {
110
+ position: [n, i.position[1] + s],
111
+ colliders: {
112
+ shape: "circle",
113
+ radius: o,
114
+ density: 7850,
115
+ restitution: 1,
116
+ friction: 0
117
+ }
118
+ });
119
+ d.push(t.addJoint(l, r, {
120
+ type: "revolute",
121
+ anchorA: [c * e, 0],
122
+ anchorB: [0, -s]
123
+ })), u.push(r);
124
+ }
125
+ return new e(t, [l, ...u], d);
126
+ }
127
+ function d(t, n) {
128
+ let i = r(n.width, "width"), a = r(n.height, "height"), o = r(n.wheelRadius, "wheelRadius"), [s, c] = n.position, l = t.addBody(null, {
129
+ position: [s, c],
130
+ colliders: {
131
+ shape: "box",
132
+ width: i,
133
+ height: a,
134
+ density: 400,
135
+ collisionGroups: 131070
136
+ }
137
+ }), u = [l], d = [];
138
+ for (let e of [-1, 1]) {
139
+ let r = [e * (i - 2 * o) / 2, a / 2 + o * .5], f = t.addBody(null, {
140
+ position: [s + r[0], c + r[1]],
141
+ colliders: {
142
+ shape: "circle",
143
+ radius: o,
144
+ density: 1e3,
145
+ friction: .9,
146
+ collisionGroups: 131070
147
+ }
148
+ });
149
+ d.push(t.addJoint(l, f, {
150
+ type: "wheel",
151
+ anchorA: r,
152
+ axis: [0, 1],
153
+ hertz: n.hertz ?? 4,
154
+ damping: n.damping ?? .7
155
+ })), u.push(f);
156
+ }
157
+ return new e(t, u, d);
158
+ }
159
+ function f(e, t) {
160
+ let n = r(t.radius, "radius"), a = t.gap ?? 0, o = i(e, {
161
+ position: t.position,
162
+ columns: t.columns,
163
+ rows: t.rows,
164
+ cell: [2 * n, 2 * n],
165
+ gap: [a, a],
166
+ body: () => ({ colliders: {
167
+ shape: "circle",
168
+ radius: n,
169
+ density: t.density ?? 1e3,
170
+ friction: t.friction ?? .4
171
+ } })
172
+ }), s = o.bodies[0].mass, c = 2 * Math.PI * (t.hertz ?? 8);
173
+ return l(e, o, {
174
+ crossBrace: t.crossBrace ?? !0,
175
+ link: {
176
+ type: "spring",
177
+ stiffness: s * c * c,
178
+ damping: 2 * (t.damping ?? .3) * s * c
179
+ }
180
+ });
181
+ }
182
+ //#endregion
183
+ export { e as Composite2D, d as car, c as chain, l as mesh, u as newtonsCradle, a as pyramid, f as softBody, i as stack };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export { Physics2D } from './physics.js';
2
- export type { Physics2DOptions, Physics2DSolverOptions, Physics2DLoadOptions, KernelWasmSource, ContactForceEvent2D, DebugColour2D, DebugLines2D, DebugStyle2D, Physics2DHooks, ProjectedPoint2D, ContactPair2D, ContactChange2D, Physics2DEventMap, CollisionEvent2D, CollisionEventType2D, QueryFilter2D, RaycastOptions2D, Hit2D, CastHit2D, ShapeCastHit2D, ShapeCastOptions2D, } from './physics.js';
2
+ export type { Explosion2D, SleepEvent2D, JointBreakEvent2D, Physics2DOptions, Physics2DSolverOptions, Physics2DLoadOptions, KernelWasmSource, ContactForceEvent2D, DebugColour2D, DebugLines2D, DebugStyle2D, Physics2DHooks, ProjectedPoint2D, ContactPair2D, ContactChange2D, Physics2DEventMap, CollisionEvent2D, CollisionEventType2D, QueryFilter2D, RaycastOptions2D, Hit2D, CastHit2D, ShapeCastHit2D, ShapeCastOptions2D, } from './physics.js';
3
3
  export { Body2D, Collider2D } from './body.js';
4
4
  export type { BodyOptions2D, BodyType2D, SpriteLike } from './body.js';
5
5
  export { Joint2D } from './joint.js';