@daneren2005/shared-memory-physics
2D physics components and systems for
@daneren2005/shared-memory-ecs. Everything
lives in the ECS's shared-memory blocks, so the simulation can run on a worker thread while the main thread
reads positions straight off its entities.
Examples at https://daneren2005.github.io/shared-memory-physics/
The ECS (>=1.10.0) and the shared-memory primitives it is built on are peer dependencies: a game must
register these components against the same copy of the ECS it builds its world with.
npm install @daneren2005/shared-memory-physics @daneren2005/shared-memory-ecs @daneren2005/shared-memory-objects
Components
| Component |
Config |
Serialization |
Block |
dynamics |
- |
accelerationX?, accelerationY?, mass? |
Float32Array - acceleration and inverse mass |
transform |
width, height, angle? / radius |
x, y, angle? |
Float32Array – where, how big, facing |
velocity |
– |
velocityX?, velocityY?, damping? |
Float32Array – world units per second |
body |
shape?, collideCategory?, collideMask?, sensor?, continuousCollisionDetection?, blocksPath? |
– |
Uint32Array – what shape, what collides with |
interpolation |
interpolate |
– |
Float32Array – where to draw it |
navigation |
navigate |
– |
Int32Array – a goal and the path to it (Pathfinding) |
Entity configs are flat and shared across every component, so velocity is keyed as velocityX / velocityY
rather than x / y (which already belong to the transform). Either velocity axis on its own is enough to
load one, and the missing one defaults to 0.
damping is optional linear damping in fraction of speed per second: with it set, a mover started once bleeds
speed off every step and coasts to a stop instead of gliding forever. It is applied implicitly as
velocity / (1 + damping * seconds), so it stays stable at any step size and never reverses direction. It
defaults to 0 (no damping) and must be finite and at least zero. An explicit velocity assignment (a queued
queueVelocity, or writing velocityX directly) is authoritative for that step and bypasses damping until the
entity coasts again.
const shot = world.loadEntity({ x: 0, y: 0, radius: 3, velocityX: 400, damping: 2 });
accelerationX / accelerationY are persistent world units per second squared. Either one (or mass) loads a
dynamics component; missing acceleration axes default to 0 and mass defaults to 1. Physics uses
semi-implicit Euler: it changes velocity by acceleration * seconds first, then moves by that new velocity in
the same fixed step. That puts gravity on the physics backend instead of tying it to render frames:
world.loadEntity({
x: 0, y: 0, width: 20, height: 40,
velocityX: 0, velocityY: 0,
accelerationY: 1600,
});
Mass is stored as inverse mass and round-trips through save; persistent acceleration does not depend on it.
Mass must be finite and greater than zero, and acceleration must be finite. An entity without dynamics has
effective mass 1 when a force or impulse is queued for it.
The transform is split in two. Config is what your entity template says - width and height are
required, angle defaults to 0 - and a size is what loads the component at all: a config with neither a
width nor a height does not get a transform. Serialization is the live state that changes as the world
runs, so save() returns x / y and includes angle only when it is nonzero. An omitted angle defaults
to 0 on load, while a reloaded entity gets its size back from your own template rather than the save.
x / y are the centre of the box, not a corner: the box is rotated about that point and collision
projects out from it in both directions. angle is in radians counter-clockwise from the +x axis, and
the physics never writes it - it is yours to set, usually from the heading, and collision reads it - but it
round-trips through save so a turned entity comes back facing the same way. width /
height are the unrotated size; a box with no area never overlaps anything, not even another box sharing its
exact position.
interpolation is where to draw an entity, which stops being the same thing as where it is the moment
physics runs less often than the screen refreshes. It is opt-in per entity (interpolate: true) and filled in
by InterpolationSystem - see that section for what it costs and what it buys.
The body is what makes an entity collidable, and a size loads one just as it loads a transform - so
everything with a place in the world collides with everything else until you say otherwise. All of it is
defining config out of your own template, which is why save returns nothing for it: a reloaded entity gets
its shape and categories back from the template rather than from the save. See
Body shapes for shape and Collision filtering for the other two.
blocksPath marks a body as something pathfinding should route around - a wall or a building rather than another
mover. The physics never reads it; it is a flag in the same packed word for a game's own navigation to query
(body.blocksPath, or blocksPath(block) off a raw block). It defaults to false, and a body carrying it is
assumed never to move, so a navigation structure can be updated only when such bodies are added or removed.
Body shapes
An entity is one of four shapes. The transform still owns its position, size and angle; a polygon additionally
has a polygon component holding its outline:
shape |
Config |
What it is |
SHAPE_RECTANGLE |
width, height |
a width x height box turned to angle – the default |
SHAPE_CIRCLE |
radius |
a circle of diameter width, which angle does not affect |
SHAPE_CAPSULE |
width, height, shape |
a pill along its longer side, as thick as its shorter side |
SHAPE_POLYGON |
vertices |
a convex 3-16 vertex outline, scaled and turned by its transform |
import { SHAPE_CAPSULE } from '@daneren2005/shared-memory-physics';
world.loadEntity({ x: 0, y: 0, width: 10, height: 4 }); // a rectangle
world.loadEntity({ x: 0, y: 0, radius: 5 }); // a circle
world.loadEntity({ x: 0, y: 0, width: 40, height: 10, shape: SHAPE_CAPSULE }); // a capsule
world.loadEntity({ x: 0, y: 0, vertices: [[-8, -6], [10, 0], [-8, 6]] }); // a triangle
Polygon vertices are local to the entity. They must describe a convex boundary in clockwise or counter-clockwise
order; concave, collinear, non-finite, and out-of-range outlines throw during loading. Their bounding box becomes
the transform's initial width and height, and the stored vertices are normalized around that box's centre.
Changing the transform size therefore scales the polygon, while angle rotates it around that centre. vertices
cannot be given alongside radius.
Give width and height with the vertices when the outline should sit tighter than the box the entity is sized
by - a sprite with the hull drawn inside it, say. The box then stays that size, the vertices are offsets from the
entity's centre rather than from their own bounds, and every one must lie inside the box (the broadphase indexes
the box, so an outline poking out of it would miss contacts):
// A 40x40 sprite whose triangular hull fills only part of it; x/y and the drawn size stay the sprite's.
world.loadEntity({ x: 0, y: 0, width: 40, height: 40, vertices: [[-12, -15], [14, 0], [-12, 15]] });
radius is the same size said differently: it loads as a width and a height of the diameter, so there is
still only one size in the block however the config spelled it. Giving both a radius and a width throws
rather than one quietly winning. A config that says nothing about its shape is read off the size it gave - a
vertices describes a polygon, radius describes a circle, and anything else a rectangle - so only capsules
have to name their shape, and an
unrecognised one throws rather than quietly becoming a rectangle.
A capsule lies along its longer side, caps included: a 40x10 capsule is a 30-long core along the way the entity
faces with a 5 radius cap at each end, the same 10 thick all the way down, and a 10x40 one is that same pill turned
a quarter, running along the entity's height instead - handy for art drawn nose-up. capsuleCoreAngle gives the
angle the core lies at. One as long as it is wide is a circle.
Because a circle is a capsule whose core has no length, the three primitive shapes are an oriented core grown by a
radius - a box with no radius, a point, or a segment - which leaves only three overlap tests rather than one
per primitive pairing: box against box (the separating axis test), core against core, and core against box.
Those fast paths remain unchanged; only a pair involving a polygon enters the polygon separating-axis test. Touching
exactly still counts as not overlapping, whichever pair it is, and a shape with no area never overlaps
anything. Which of the two sizes decides that depends on the shape: a circle with no height is a perfectly
good circle, while a rectangle with no height is nothing at all.
contactNormal answers the other half of a contact: the unit direction one shape is pushed off the other,
written into a { x, y } you pass in, and false when the two are exactly on top of each other and there is no
such direction. It splits the same three ways off the same geometry, so the direction is the face that was
actually hit at the angle the pair is turned to - not the nearest world axis. This is what the native bounce
reflects around; a game reaching for its own response can use it the same way.
shapesOverlap and contactNormal are the allocation-free primitive-shape functions. Their polygon counterparts
are polygonShapesOverlap and polygonContactNormal, which additionally take the polygon component blocks.
shapeHalfWidth / shapeHalfHeight (the axis-aligned box a shape is
indexed under), shapeRadius, shapeIsEmpty, capsuleHalfLength, capsuleCoreAngle, and the distance primitives underneath -
segmentSegmentDistanceSquared, segmentBoxDistanceSquared and pointSegmentDistanceSquared, each of which
takes an optional out vector and fills it with the gap it measured. orientedBoxesOverlap, boundsHalfWidth
and boundsHalfHeight are still there and still rectangle-only.
Registering
Spread physicsRegistry into your own registry so the world allocates the memory pools for these components
alongside your game specific ones. The keys are what the systems query on, so keep them as they are:
import { BaseWorld } from '@daneren2005/shared-memory-ecs';
import { physicsRegistry } from '@daneren2005/shared-memory-physics';
const registry = {
...physicsRegistry,
health: healthDefinition,
};
const world = new BaseWorld(registry);
const entity = world.loadEntity({ x: 0, y: 0, width: 10, height: 5, velocityX: 10, velocityY: 0, maxHealth: 100 });
console.log(entity.components.transform!.x); // 0
PhysicsSystem
PhysicsSystem moves every entity that has both a transform and a velocity, integrating optional acceleration
and queued commands into velocity and then velocity into position once per run - and, once you give it an update built by
createPhysicsUpdate, tells
you which entities have run into each other. It is generic over your full component map, so your world passes
straight in:
import { PhysicsSystem } from '@daneren2005/shared-memory-physics';
world.addSystem(new PhysicsSystem(world));
await world.init();
world.update(1000); // one second: the entity above is now at x = 10
elapsedTime is in milliseconds (what BaseWorld#update is driven with), velocity is in world units per
second, and acceleration is in world units per second squared. A run covering 16ms first adds 16/1000ths
of the acceleration to velocity, then moves 16/1000ths of that updated velocity.
Dynamics commands
Queue forces, impulses, or velocity assignments on the PhysicsSystem that owns the mover. A force acts for the
duration of the next physics run; an impulse changes velocity once without being scaled by that run's duration.
Both are divided by the entity's mass. A velocity assignment replaces only the axes it names, after acceleration,
force, and impulse integration but before movement, so it is exact and independent of mass:
const physics = world.addSystem(new PhysicsSystem(world));
physics.queueForce(entity, 0, 20); // next run: acceleration += force / mass
physics.queueImpulse(entity, 12, -40); // next run: velocity += impulse / mass
physics.queueVelocity(entity, { velocityY: -980 }); // next run: set y without changing x
The methods also accept an entity id. Forces and impulses queued for the same entity before dispatch are summed;
the last velocity assignment for each axis wins. Zero force/impulse vectors and empty velocity assignments are
ignored. Non-finite values throw immediately.
Commands have a strict run boundary. A command queued before dispatch belongs to that run and is consumed once.
A command queued while a worker run is in flight belongs to the following run. A command is still consumed if
its entity is absent from the mover query because it was removed, filtered, scoped out, or in a skipped group;
queue it again when the entity becomes eligible. In a sharded simulation, queue on the system whose mover filter
owns the entity.
The same methods are available on world inside a createPhysicsUpdate collision callback, with entity ids:
onCollision(world, self, other, queries, callbacks, contact) {
world.queueVelocity(self.entityId, {
velocityX: contact.normalX * 480,
velocityY: -720,
});
}
Callback commands always target the next run and survive between runs in either backend. They combine with
commands queued through PhysicsSystem: forces and impulses add together, while a newer main-thread velocity
assignment replaces a callback assignment on each axis it names.
The step
PhysicsSystem runs on a fixed step of 50ms unless you say otherwise (DEFAULT_PHYSICS_STEP_MS). Collision
is by a distance the whole of it, so running it 20 times a second rather than 60 is two thirds less of the frame
spent on it for a simulation that is no less correct - only coarser. What that costs is smoothness, which is
what InterpolationSystem is for.
new PhysicsSystem(world, { deltaBetweenRuns: 0 }); // back to every frame