Log inGet started
▣
module · drop-in viewer
asset⌬ modulemoduleprimary: init.luau·originates fromworld 07158574-5…●3problems

physics

Convenience wrapper around the `__physics` FFI namespace. Covers raycasting, force / impulse / torque application, velocity reads and writes, body-property mutators (mass, damping, body type, locks), collision groups, joints, constraints, colliders, wheel-collider helpers, and th…

byzero-proxy @ DESKTOP-DB3UJOJ·posted 4mo ago
What it does

physics

Convenience wrapper around the __physics FFI namespace. Covers raycasting, force / impulse / torque application, velocity reads and writes, body-property mutators (mass, damping, body type, locks), collision groups, joints, constraints, colliders, wheel-collider helpers, and the observation reads that report what the solver holds for a body and why it is not moving it, in one consistent surface. Exposed as the Physics global via --!global Physics.

Exports

Queries:

  • Physics.raycast(origin, direction, maxDistance?, exclude?) -> table?
  • Physics.raycastAll(origin, direction, maxDistance?, maxHits?) -> table
  • Physics.overlapSphere(center, radius) -> table
  • Physics.sphereCast(origin, radius, direction, maxDistance?, exclude?) -> table?
  • Physics.capsuleCast(origin, radius, halfHeight, direction, maxDistance?, exclude?) -> table?
  • Physics.boxCast(origin, halfExtents, direction, maxDistance?, exclude?) -> table?
  • Physics.getGravity() -> vec3 / Physics.setGravity(g)
  • Physics.getVelocity(entityId?) -> vec3? / Physics.getAngularVelocity(entityId?) -> vec3?

Forces / impulses (each accepts either (vec3) for the script-context entity or (entityId, vec3); a vec3 may be an {x, y, z} table or three loose numbers):

  • Physics.applyForce / Physics.applyForceAtPoint / Physics.applyTorque: from code that runs inside a step (Physics.onBeforeStep / onAfterStep, a contact listener, fixedUpdate) they act on the next step alone (call once per step); from anywhere else they act over the next frame's simulated time (call once per frame). A continuous force integrates to force times time at any frame rate and tick rate
  • Physics.applyImpulse — one-shot velocity change
  • Physics.setVelocity / Physics.addVelocity / Physics.setAngularVelocity

Step hooks (at the physics tick rate, however many steps a frame runs):

  • Physics.onBeforeStep(fn) -> off: fn(dt, step) at the start of every step, after its force reset; a force written there acts on that step, and a read sees the state it starts from (springs, fields, thrusters, controllers)
  • Physics.onAfterStep(fn) -> off: fn(dt, step) once the step has run, after its contact events and before fixedUpdate; a read sees what that step left
  • One engine call runs every hook of a side, and a hook ends with off() or with the component that registered it

Body properties:

  • Physics.setGravityScale, Physics.setMass, Physics.setLinearDamping, Physics.setAngularDamping, Physics.setCcdEnabled
  • Physics.setBodyType(entityId, "dynamic" | "kinematic" | "static")
  • Physics.setRotationLocks(entityId, x, y, z) / Physics.setTranslationLocks(entityId, x, y, z)

Surfaces (what colliders are made of):

  • Physics.defineSurface(name, { friction?, restitution?, rollingResistance?, spinningResistance?, tags? }) / Physics.removeSurface(name) / Physics.getSurface(name) -> PhysicsSurface? / Physics.surfaces(): a named material a collider takes by naming it in its surface field, and a heightfield per sample through surfaceLayers / surfaceMap (a terrain's painted layers each collide as their own surface)
  • rollingResistance c: a body rolling on the surface slows at c times gravity on level ground, stopping after v^2 / (2 c g), whatever its mass and shape; spinningResistance does the same for a body spinning about the contact normal. Both act through contacts only, so a ball in flight keeps its spin
  • Per contact friction and restitution combine as they always have (the average), and the two sides' rolling and spinning resistances add, so a ball of none on a floor of c rolls against c
  • Ray and shape cast hits carry surface; contacts, contact points, contact events and Physics.contactPeak carry surface and otherSurface; Physics.groundContact(entityId, maxSlope?) -> PhysicsGroundContact? names what a body stands on and the surface under it

Surfaces that act on what touches them (collider fields, read by the physics step itself, no script per contact):

  • oneWay = { x, y, z }: the direction, in the collider's own frame, bodies pass through it along; a body meeting it from that side stands on it (a jump-through platform is { 0, 1, 0 }). Physics.passThrough(entityId, throughId?) drops a standing rigid body through
  • surfaceVelocity = { x, y, z }: the velocity, m/s in the collider's own frame, its surface moves at along itself while the collider stays put; friction carries what rests on it (conveyor belts, treadmills, escalators). Write the field at runtime to change it
  • contactTag = "name" with Physics.setContactFilter(tagA, tagB, "ignore" | "sensor" | "solid") / Physics.contactFilters(): a pair of tags passes through each other ("ignore"), reports contacts and pushes nothing ("sensor"), or collides ("solid", every pair the filter does not name)

Collision groups & filtering:

  • Physics.setCollisionGroups(entityId, membership, filter)
  • Physics.ignoreCollision(entityIdA, entityIdB, ignore?)

Joints / constraints / colliders:

  • Physics.addJoint(a, b, opts?) / Physics.removeJoint(id) / Physics.setJointMotor(id, vel, maxForce): joints with limits (limitMin / limitMax, swingLimit / twistLimit, axisLimits), motors (motorMode "velocity" / "position", capped by motorMaxForce), joint frames (axis, remoteAxis), collideConnected, and a 6-DOF kind = "generic" with lockedAxes
  • Physics.jointState(id): a joint's angle / travel / swing and twist, velocity, whether it is at a limit, and the force its limit and motor applied
  • Physics.jointReaction(id): the load (the stress) a joint carries as signed vectors, read along the member it holds (axial tension positive, compression negative, shear, bending, torsion, a rope's tension) and as load, the share of the break thresholds it is measured against
  • Physics.jointReactions(targets?, opts?) / Physics.listenJointLoads(targets, listen?): many joints' loads in one call as arrays, and the peak each carried between two reads
  • Physics.addConstraint(id, opts?) / Physics.removeConstraint(id, index?)
  • Physics.addCollider(id, config) / Physics.removeCollider(id)
  • Physics.addWheelCollider(id, config?) / Physics.removeWheelCollider(id) / Physics.getWheelState(id) / Physics.vehicleState(chassisId): the wheels under one rigid body make up that body's ray-cast vehicle; the WheelCollider component README covers the fields
  • Physics.detachWheel(id) / Physics.attachWheel(id): a wheel comes off its vehicle as a dynamic body of its own (rolling and bouncing with its spin, the vehicle driving on the wheels it has left) and goes back on its mount; a breakLoad takes it off by itself, a solid wheel is a volume other bodies strike, and vehicleState lists the wheels that came off under detachedWheels

Observation (read off the solver, not off the Physics component):

  • Physics.observe(entityId?, opts?) -> PhysicsObservation? — one read of the world, or of one body; bodies is an array whose entries each name their own entity
  • Physics.worldState() -> PhysicsWorldState — bodies by type, awake / asleep, colliders, soft bodies, joints, contact pairs and points, gravity, timestep, and the last step's cost
  • Physics.softBodyState(entityId, opts?) -> PhysicsSoftBodyState? — a soft body's particle and cell counts, volume against rest, frame, bounds, sleep state and contacts, the solver simulating it (solver: "constraints" or "fem"), its particles' positions with { positions = true }, the cage a shape = "mesh" body was filled with (cage: cell size, whether it came from the cache, build time, parts filled and left out), and where the body stands: status is "built", "pending" (the component stands and the body is built at the start of the next frame, so a read in the call that added it answers this; waitingFor names what the build waits on), "refused" (refusal says why the component was not built) or "none"
  • Physics.debugLines(opts?) -> PhysicsDebugLines?: what the physics world simulates beyond collider surfaces, as world-space lines with the data behind them: a soft body's elements coloured by load (cage), its free, pinned and attached particles (particles), soft-soft contacts (contacts), and each WheelCollider wheel's suspension ray, travel, tyre and ground contact (wheels). capture { pass = "physics" } and the edit-mode collider overlay draw these lines; Physics.softBodyState(id).diagnostics reads a soft body's inverted cells, self-crossings, element loads (maxLoad, loadedElements), pinned and attached particles as numbers
  • Physics.drawnPose(entityId) -> PhysicsDrawnPose?: where an entity is drawn this frame (position, rotation) beside the pose its transform holds (simulatedPosition, simulatedRotation, what entity.position reports). A dynamic body with Physics.interpolation on is drawn blended between its last two physics ticks, and so is everything parented under it: interpolated, interpolatedBy (the body whose blend places it) and alpha (how far into the current tick the frame sits) say so. A camera or anything else that has to stay with a moving body on screen reads this
  • Physics.bodyState(entityId) -> PhysicsBodyState? — the mass, inertia, gravity scale, damping, locks, CCD, collision groups, sleep timers, velocities, queued force and torque, colliders, contacts, joints and transform constraints the solver holds
  • Physics.whyStill(entityId) -> (string?, string?) — the one reason the solver is not advancing a body, and the detail behind it
  • Physics.stillnessReasons() -> {string} — every reason whyStill can answer with
  • Physics.contacts(entityId) -> {PhysicsContact} / Physics.touching(a, b) -> (boolean, number, {PhysicsContactPoint})
  • Physics.catchUp() -> PhysicsCatchUp: how the frame clock kept up with real time: the frames it ran, those that dropped simulated time, owing more than a frame may catch up (boundSeconds, from maxCatchUpSeconds) or with steps past maxSubsteps that fell behind the time they cover (framesBehind), and the simulated seconds they dropped, counted since the engine started
  • Physics.stepCost() -> PhysicsStepCost?: the last step's per-stage cost, with the share attributed to soft bodies (softBodyMs) and each soft body's part of it (softBodies: entity, ms, particles, cells, elements, contacts, substeps, costliest first); a soft body's own read carries its part as lastStepMs
  • Physics.softBodySettings(changes?) -> PhysicsSoftBodySettings: the settings every soft body runs under, each trading quality for cost (maxExtraSubstepRate, contactStiffening, resweepStrain, tangleDetection, overlapConstraints, recoveryPace, and the FEM solver's femTolerance, femMaxIterations, femMaxDenseDofs, read by the bodies whose SoftBody.solver is "fem"); with a table, changes the fields it names, saved as physics.soft_body_* world settings and applied from the next tick, and refuses an unknown field or a value out of range by name
  • Physics.solverSettings(changes?) -> PhysicsSolverSettings: the settings the constraint solver runs every step under (tickRate, maxCatchUpSeconds, maxSubsteps, solverIterations, pgsIterations, stabilizationIterations, warmStartCoefficient, warmStartJoints, lengthUnit, contactFrequency, contactDampingRatio, staticContactFrequency, staticContactDampingRatio, allowedLinearError, maxCorrectiveVelocity, predictionDistance, ccdSubsteps, frictionModel, frictionInBiasPass); with a table, changes the fields it names, saved as physics.* world settings and run by the solver from the next step, and refuses an unknown field or a value out of range by name

High-level helpers:

  • Physics.raycastBetween(fromId, toId, maxDistance?) -> table? (ids or proxies)
  • Physics.hasLineOfSight(fromId, toId) -> boolean (ids or proxies)

Usage

-- `Physics` is auto-injected by the prelude — no require in user code.
local hit = Physics.raycast({x=0,y=2,z=0}, {x=0,y=-1,z=0})
Physics.applyImpulse(entityId, {x=0, y=5, z=0})
Physics.addJoint(a, b, { kind = "fixed" })

Notes

  • Most apply/set helpers are polymorphic on the first argument: they accept either an explicit entityId (with the value as a second arg) or a value directly (using the script-context entity).
  • addJoint accepts both vec3-style anchor tables (localAnchor = {x,y,z}) and pre-split scalar keys (localAnchorX/Y/Z); both forms forward as split keys to the Joint component.
  • setCollisionGroups adds the CollisionGroup component if missing.
  • getWheelState returns nil when the entity has no WheelCollider component, and vehicleState returns nil when no WheelCollider sits under the chassis.
  • The sweeps (sphereCast, capsuleCast, boxCast) report distance as how far the shape's centre travels before its surface meets the geometry, and normal as the outward normal of the surface it met — the same normal a ray hit carries.
  • A ray's or a sweep's direction may have any length: the engine normalises it, so maxDistance and the reported distance are world units whatever the direction's length, and a direction of zero length hits nothing.
  • exclude is applied while searching: the first hit raycast reports, and every hit raycastAll counts toward maxHits, is on an entity outside the list, however many excluded colliders lie in front of it.
  • Every hit table carries startedInside, and it says which surface normal describes. false — the query travelled to the collider and crossed its surface, so distance is how far it went, point is where it met the surface, and normal is that surface's outward normal. true — the query's own start already lay inside that collider, so distance is 0, point is the start itself, and normal is the collider's outward surface normal at the surface point nearest the start: the shortest way out of it. normal is a unit vector either way, and every collider shape answers an inside start the same way, so a slope read like math.acos(hit.normal.y) is meaningful without knowing which shape was hit.
  • raycastBetween and hasLineOfSight cast from the source's world position toward the target's world position, wherever each sits in the hierarchy. Each end takes either an entity id or a proxy, and an end naming no entity raises an error naming the argument (fromId or toId) and the id.
  • Each end's own colliders hold nothing up: those of the body it rides (its own Physics or SoftBody, else the body of its nearest ancestor carrying one) and of every entity riding that body, a child collider composed onto it included. raycastBetween passes over the source's; with nothing between the pair, its first hit is the target's collider.
  • raycastBetween returns nil if the two entities are coincident (< 0.001 units apart).
  • hasLineOfSight returns true even when nothing is hit: line-of-sight only fails if a collider belonging to neither end sits between the pair.
  • The observation reads answer in edit mode as well as play mode. bodyState reports exists = false with stillness = "noBody" for an entity that carries no rigid body, and nil only when nothing in the scene answers to that id.
  • observe(nil, { bodies = false }) builds the world accounting alone; { contactPoints = false } keeps each contact pair's normal, depth, impulse and point count while leaving out the individual points.
  • stepCost figures cover the one step that ran, so they are already per-step costs; it is nil on a frame where the pipeline did not step.

Interface

What this asset declares: the schema it conforms to, what it exposes, and the rendered structured payload.

conforms to

zero/source-extract/v2

global Physics global physics

BoxColliderCollisionGroupJointConstraintWheelCollider

raycast(origin: vec3, direction: vec3, maxDistance: number?, exclude: (string | {string}) →

Cast a ray and return the first hit. Answers from COLLIDERS ALONE: a mesh that renders but carries no collider is not in the physics world, so a ray fired through it reports the same `nil` a ray through open air does. `renderer.raycast` answers the same ray against the geometry the renderer DRAWS, which is what reads the surface of a terrain, a procedurally generated mesh, or any plain `Model`. A trigger (`isTrigger`) holds nothing up, so the ray passes through it. `maxDistance` and `distance` are world units. `startedInside` is `false` for a surface the query crossed on its way there, and `true` when the query's own start already lay inside that collider — where `distance` is 0, `point` is the start itself, and `normal` is the shortest way out of the collider. `normal` is a unit vector either way. `surface` names the surface the collider is made of where the query met it (`Physics.defineSurface`; on a heightfield whose samples name layers, the layer of the sample nearest the point), and is absent for a collider naming none. `softBody` is set when what was hit is a soft body, whose surface the query meets as it is deformed now: a `PhysicsSoftHit` naming the surface triangle, the particles carrying it with the hit's weight on each, the particle nearest the hit, and `region`, the hit as a soft region to hand to `Physics.applyImpulse`, `Physics.pinSoftRegion` or `Physics.softParticles`. `Physics.applyImpulseAtPoint` takes the hit's `point` as it is. A `nil` says the ray met no COLLIDER, which `Physics.colliderCount()` separates from a world that holds none for it to meet.

argtypedescription
originvec3Ray origin in world space.
directionvec3Ray direction, of any length: the engine normalises it, so
maxDistancenumber?Maximum distance along the ray (defaults to 1000).
exclude(string | {string}Optional entity id, or array of entity ids, to exclude from hits.

examples

local hit = Physics.raycast({x=0,y=2,z=0}, {x=0,y=-1,z=0})
local hit = Physics.raycast(origin, dir, 50, { selfId, carriedId })
local hit = Physics.raycast(muzzle, aim, 100); if hit and hit.softBody then Physics.applyImpulseAtPoint(hit.entityId, {x=0, y=0, z=-20}, hit.point, { radius = 0.3 }) end
if Physics.colliderCount() == 0 then hit = renderer.raycast(eye, down, 200) end

colliderCount( ) →

How many colliders the physics world holds. Zero means no ray, cast or overlap fired into this world can hit anything, so it is what separates a query that MISSED from a query fired into a world that holds nothing to hit. Read off the collider set itself, so it costs the same whatever the world holds.

examples

if Physics.colliderCount() == 0 then print("nothing here is solid") end

raycastAll(origin: vec3, direction: vec3, maxDistance: number?, maxHits: number?, exclude: (string | {string}) →

Cast a ray and return every hit up to `maxHits`. Answers from COLLIDERS ALONE, so a rendered mesh with no collider is absent from the result; `renderer.raycastAll` answers the same ray against the geometry the renderer draws. A trigger (`isTrigger`) holds nothing up, so the ray passes through it. `maxDistance` and `distance` are world units. `startedInside` is `false` for a surface the query crossed on its way there, and `true` when the query's own start already lay inside that collider — where `distance` is 0, `point` is the start itself, and `normal` is the shortest way out of the collider. `normal` is a unit vector either way. `surface` names the surface the collider is made of where the query met it (`Physics.defineSurface`; on a heightfield whose samples name layers, the layer of the sample nearest the point), and is absent for a collider naming none. `softBody` is set when what was hit is a soft body, whose surface the query meets as it is deformed now: a `PhysicsSoftHit` naming the surface triangle, the particles carrying it with the hit's weight on each, the particle nearest the hit, and `region`, the hit as a soft region to hand to `Physics.applyImpulse`, `Physics.pinSoftRegion` or `Physics.softParticles`. `Physics.applyImpulseAtPoint` takes the hit's `point` as it is.

argtypedescription
originvec3Ray origin in world space.
directionvec3Ray direction, of any length: the engine normalises it, so
maxDistancenumber?Optional distance limit along the ray.
maxHitsnumber?Optional cap on the number of hits returned.
exclude(string | {string}Optional entity id, or array of entity ids, to exclude from hits.

examples

local hits = Physics.raycastAll(origin, dir, 50, 4)

raycastScreen(sx: number, sy: number, maxDistance: number?, exclude: (string | {string}) →

Cast a ray from a screen pixel into the scene and return the first hit. Unprojects the pixel with `screenToRay`, then casts with `raycast`. `startedInside` is `false` for a surface the query crossed on its way there, and `true` when the query's own start already lay inside that collider — where `distance` is 0, `point` is the start itself, and `normal` is the shortest way out of the collider. `normal` is a unit vector either way. `surface` names the surface the collider is made of where the query met it (`Physics.defineSurface`; on a heightfield whose samples name layers, the layer of the sample nearest the point), and is absent for a collider naming none. `softBody` is set when what was hit is a soft body, whose surface the query meets as it is deformed now: a `PhysicsSoftHit` naming the surface triangle, the particles carrying it with the hit's weight on each, the particle nearest the hit, and `region`, the hit as a soft region to hand to `Physics.applyImpulse`, `Physics.pinSoftRegion` or `Physics.softParticles`. `Physics.applyImpulseAtPoint` takes the hit's `point` as it is.

argtypedescription
sxnumberScreen X in viewport-local pixels (the space of `input.mouse_position` and `screenToRay`).
synumberScreen Y in viewport-local pixels.
maxDistancenumber?Maximum distance along the ray (defaults to 1000, matching `raycast`).
exclude(string | {string}Optional entity id, or array of entity ids, to exclude from hits.

examples

local Zin = require("@builtin::modules.zinput")
local x, y = Zin.state.mousePosition(); local hit = Physics.raycastScreen(x, y)

overlapSphere(center: vec3, radius: number) →

Find every entity id whose colliders overlap a sphere. A trigger (`isTrigger`) holds nothing up, so it is left out.

argtypedescription
centervec3Sphere center in world space.
radiusnumberSphere radius.

examples

local ids = Physics.overlapSphere({x=0,y=0,z=0}, 5)

sphereCast(origin: vec3, radius: number, direction: vec3, maxDistance: number?, exclude: (string | {string}) →

Cast a sphere along a direction and return the first hit. A trigger (`isTrigger`) holds nothing up, so the sweep passes through it. `maxDistance` and `distance` are world units. Applied while sweeping rather than to the answer, so a cast that starts inside an excluded collider reports what is behind it. `startedInside` is `false` for a surface the query crossed on its way there, and `true` when the query's own start already lay inside that collider — where `distance` is 0, `point` is the start itself, and `normal` is the shortest way out of the collider. `normal` is a unit vector either way. `surface` names the surface the collider is made of where the query met it (`Physics.defineSurface`; on a heightfield whose samples name layers, the layer of the sample nearest the point), and is absent for a collider naming none. `softBody` is set when what was hit is a soft body, whose surface the query meets as it is deformed now: a `PhysicsSoftHit` naming the surface triangle, the particles carrying it with the hit's weight on each, the particle nearest the hit, and `region`, the hit as a soft region to hand to `Physics.applyImpulse`, `Physics.pinSoftRegion` or `Physics.softParticles`. `Physics.applyImpulseAtPoint` takes the hit's `point` as it is.

argtypedescription
originvec3Sphere center at the start of the cast.
radiusnumberSphere radius.
directionvec3Cast direction, of any length: the engine normalises it, so
maxDistancenumber?Optional distance limit.
exclude(string | {string}Optional entity id, or array of entity ids, to exclude from hits.

examples

local hit = Physics.sphereCast(o, 0.5, dir, 10)
local hit = Physics.sphereCast(o, 0.5, dir, 10, selfId)

capsuleCast(origin: vec3, radius: number, halfHeight: number, direction: vec3, maxDistance: number?, exclude: (string | {string}) →

Cast an upright capsule along a direction and return the first hit. This is the sweep that answers whether a body of that shape fits through a passage: a capsule of radius `r` reports a hit on anything that leaves it less than `2 * r` of clearance. A trigger (`isTrigger`) holds nothing up, so the sweep passes through it. stands `halfHeight + radius` tall in each direction. `maxDistance` and `distance` are world units. Applied while sweeping rather than to the answer, so a cast that starts inside an excluded collider reports what is behind it. `startedInside` is `false` for a surface the query crossed on its way there, and `true` when the query's own start already lay inside that collider — where `distance` is 0, `point` is the start itself, and `normal` is the shortest way out of the collider. `normal` is a unit vector either way. `surface` names the surface the collider is made of where the query met it (`Physics.defineSurface`; on a heightfield whose samples name layers, the layer of the sample nearest the point), and is absent for a collider naming none. `softBody` is set when what was hit is a soft body, whose surface the query meets as it is deformed now: a `PhysicsSoftHit` naming the surface triangle, the particles carrying it with the hit's weight on each, the particle nearest the hit, and `region`, the hit as a soft region to hand to `Physics.applyImpulse`, `Physics.pinSoftRegion` or `Physics.softParticles`. `Physics.applyImpulseAtPoint` takes the hit's `point` as it is.

argtypedescription
originvec3Capsule centre at the start of the cast.
radiusnumberCapsule radius.
halfHeightnumberDistance from the centre to either cap centre. The capsule
directionvec3Cast direction, of any length: the engine normalises it, so
maxDistancenumber?Optional distance limit.
exclude(string | {string}Optional entity id, or array of entity ids, to exclude from hits.

examples

local hit = Physics.capsuleCast(o, 0.3, 0.6, dir, 0.5)
local hit = Physics.capsuleCast(o, 0.3, 0.6, dir, 0.5, selfId)

boxCast(origin: vec3, halfExtents: vec3, direction: vec3, maxDistance: number?, exclude: (string | {string}) →

Cast a box along a direction and return the first hit. A trigger (`isTrigger`) holds nothing up, so the sweep passes through it. `maxDistance` and `distance` are world units. Applied while sweeping rather than to the answer, so a cast that starts inside an excluded collider reports what is behind it. `startedInside` is `false` for a surface the query crossed on its way there, and `true` when the query's own start already lay inside that collider — where `distance` is 0, `point` is the start itself, and `normal` is the shortest way out of the collider. `normal` is a unit vector either way. `surface` names the surface the collider is made of where the query met it (`Physics.defineSurface`; on a heightfield whose samples name layers, the layer of the sample nearest the point), and is absent for a collider naming none. `softBody` is set when what was hit is a soft body, whose surface the query meets as it is deformed now: a `PhysicsSoftHit` naming the surface triangle, the particles carrying it with the hit's weight on each, the particle nearest the hit, and `region`, the hit as a soft region to hand to `Physics.applyImpulse`, `Physics.pinSoftRegion` or `Physics.softParticles`. `Physics.applyImpulseAtPoint` takes the hit's `point` as it is.

argtypedescription
originvec3Box center at the start of the cast.
halfExtentsvec3Half the size of the box on each axis.
directionvec3Cast direction, of any length: the engine normalises it, so
maxDistancenumber?Optional distance limit.
exclude(string | {string}Optional entity id, or array of entity ids, to exclude from hits.

examples

local hit = Physics.boxCast(o, {x=0.5,y=0.5,z=0.5}, dir, 10)
local hit = Physics.boxCast(o, {x=0.5,y=0.5,z=0.5}, dir, 10, { selfId, carriedId })

colliderShapes(entityId: string | entityRef) →

Read an entity's resolved physics collider shape(s) as the physics engine sees them, including auto-sized colliders. `shapeType` is one of `box`, `sphere`, `capsule`, `convex`, `mesh`, `heightfield`, `compound`, `wire` (a soft body's elements, colliding at its particle radius), `other`: the shape the simulation is running, so a mesh collider reads `mesh`. `params` carries half-extents for a box, radius for a sphere, radius and half-height for a capsule, and the collider's bounding half-extents for the shapes that have no parametric description. A convex collider reports its outline in `linePoints` instead.

argtypedescription
entityIdstring | entityRefTarget entity id.

examples

local shapes = Physics.colliderShapes(id)

colliderManifest( ) →

List every physics collider in the world with what it is and what it takes part in — no geometry, so it is the cheap read to make before deciding what to do with each one. `role` is one of `static`, `dynamic`, `kinematic`, `sensor`. A sensor is a collider the simulation holds as one, reported ahead of the body type behind it, and a collider with no rigid body is static. `exact` says whether `colliderGeometry` would return this collider's true surface or its bounding box. Every collider of one entity shares its `entity`, so this is what to key per-object decisions on. The order is stable across calls over an unchanged world, which is what makes `colliderGeometry`'s positional colours usable.

examples

for _, c in ipairs(Physics.colliderManifest()) do print(c.entity, c.role) end

colliderGeometry(options: table?) →

Read the physics world as drawable triangles: every collider triangulated in world space into one indexed mesh, in GPU buffers ready to draw. Box, sphere, capsule, cylinder, cone, convex, triangle-mesh and heightfield colliders return their real surface, and a compound returns its children folded together; a shape with no triangulation returns its bounding box and reports `exact = false`. `options.colors` is POSITIONAL over `colliderManifest()` — entry `i` colours collider `i` — so you can colour by role, shape, entity or anything else you read there. A position you leave out takes `options.defaultColor`. The returned buffers are yours: destroy them when you replace them. entry of `colliders` is `{ entity, colliderName?, shapeType, role, exact, firstIndex, indexCount }`.

argtypedescription
optionstable?`{ tessellation = "low"|"medium"|"high", colors = { {r,g,b,a}, ... }, defaultColor = {r,g,b,a} }`.

examples

local geo = Physics.colliderGeometry({ tessellation = "high" })

getGravity( ) →

Read the current world gravity vector.

examples

local g = Physics.getGravity()

setGravity(gravity: vec3) → void

Replace the world gravity vector.

argtypedescription
gravityvec3New gravity vector in m/s².

examples

Physics.setGravity({x=0, y=-9.81, z=0})

getVelocity(entityId: (string | entityRef) →

Read the linear velocity of an entity's rigid body, or of its soft body as a whole (its particles' velocities averaged by mass).

argtypedescription
entityId(string | entityRefTarget entity id or proxy; resolves from script context when omitted.

examples

local v = Physics.getVelocity(id)

getAngularVelocity(entityId: (string | entityRef) →

Read the angular velocity of an entity's rigid body.

argtypedescription
entityId(string | entityRefTarget entity id or proxy; resolves from script context when omitted.

examples

local w = Physics.getAngularVelocity(id)

isSleeping(entityId: (string | entityRef) →

Whether an entity's rigid or soft body is currently asleep (at rest and not simulating). A body sleeps once it stops moving, to save simulation cost.

argtypedescription
entityId(string | entityRefTarget entity id or proxy; resolves from script context when omitted.

examples

if Physics.isSleeping(id) then Physics.wakeUp(id) end

wakeUp(entityId: (string | entityRef) → void

Wake an entity's sleeping rigid or soft body so it resumes simulating. The motion setters (`applyImpulse`, `setVelocity`, `setAngularVelocity`) wake the body for you; call this to wake one explicitly.

argtypedescription
entityId(string | entityRefTarget entity id or proxy; resolves from script context when omitted.

examples

Physics.wakeUp(id)

idOf(ref: (string | entityRef) → void

Internal: the stable id of an entity id or proxy.

argtypedescription
ref(string | entityRef

jointOwnerOf(carrierId: string) → void

The entity whose Joint the constraint carried by `carrierId` is, and that Joint's name (nil for the unnamed Joint): a named Joint's constraint is carried by an entity of its own directly under the Joint's entity.

argtypedescription
carrierIdstring

jointCarrier(target: any, name: string?, fname: string) → string

The entity carrying the constraint of the joint `target` names: a `Joint` component (as `component.get("Joint", name)` returns it), or an entity with the Joint named `name` on it (its unnamed Joint when `name` is nil).

argtypedescription
targetany
namestring?
fnamestring

observe(entityId: (string | entityRef, opts: ?) →

Read the solver's own state — the world's accounting, and what it holds for each body plus why it is not moving one. Every value comes off the simulation rather than the `Physics` component, so a write the solver refused or clamped reads back as what it kept. Answers in edit mode as well as play mode. builds the world accounting alone, and `contactPoints = false` keeps each contact pair's normal, depth, impulse and point count while leaving out the individual points. Both default to true. scene. `bodies` is an array, not a table keyed by entity id — each entry names its own entity in `entity`.

argtypedescription
entityId(string | entityRefReport on this one entity. Omit for every body in the world.
opts?`{ bodies: boolean?, contactPoints: boolean? }` — `bodies = false`

examples

local o = Physics.observe(); for _, b in o.bodies do print(b.entity, b.stillness) end
local o = Physics.observe(id); print(o.bodies[1].stillness, o.bodies[1].stillnessDetail)

worldState( ) →

How many bodies, colliders, joints and contacts the simulation holds right now, with world gravity, the timestep, whether the pipeline is stepping at all, what the last step cost, and how many step hooks run around every step (`stepHooks`). Counted off the solver, so a body that failed to build is absent here while its `Physics` component still exists.

examples

local w = Physics.worldState(); print(w.bodies.awake .. "/" .. w.bodies.total .. " awake")
print(Physics.worldState().contacts.touchingPairs .. " pairs touching")

bodyState(entityId: string | entityRef) →

Everything the solver holds for one body — its type, mass, centre of mass, inertia, gravity scale, damping, lock flags, CCD, collision groups, sleep state, velocities, the force and torque queued for the next step, its colliders, contacts, joints and transform constraints, and why it is not moving. carries no rigid body, and `waitingFor` naming what its collider needs while that collider cannot be built), or `nil` when nothing in the scene answers to that id.

argtypedescription
entityIdstring | entityRefEntity id or proxy.

examples

local b = Physics.bodyState(id); print(b.bodyType, b.mass, b.stillness)
local b = Physics.bodyState(id); if not b.exists then print(b.waitingFor or "no body was built") end

planeHold(entityId: string | entityRef) →

Which plane holds a body, and where the hold comes from: the `PlaneHold` covering the body (on its entity or an ancestor, a group hold over its collision groups, or a world hold), as the physics world applied it. A rigid or a soft body answers alike. when no hold holds the body (or nothing in the scene answers to that id).

argtypedescription
entityIdstring | entityRefEntity id or proxy of a body.

examples

local h = Physics.planeHold(crate); if h then print(h.holder, h.covers, h.normal.z) end

forces(entityId: string | entityRef) →

Which forces act on a body from step to step, and their sum: every `Force` component driving it (on its entity or an entity under it, each named by its `source` entity and instance `name`), each evaluated at the pose the body stands at now, in the world frame, as the next step applies it. `applied` reads whether this engine's step applies them: an enabled dynamic body takes them, a static or kinematic one carries them unmoved. Forces written for one step (`applyForce`) are the body state's `queuedForce`. empty `forces` and zero sums for a body carrying none, or nil when nothing in the scene answers to that id with a rigid body.

argtypedescription
entityIdstring | entityRefEntity id or proxy of a body.

examples

local f = Physics.forces(rocket); print(f.force.y, #f.forces)

drawnPose(entityId: string | entityRef) →

Where an entity is drawn this frame, and where its transform puts it. The simulation advances in fixed ticks (`physics.tick_rate`, 30 a second by default) while frames are drawn at the display's rate, so a body with `Physics.interpolation` on is drawn blended between its last two ticks, and everything parented under it is drawn moved with it. `entity.position` reports the simulated pose, which moves only when a tick runs; this read reports the drawn one as well. Read it from a component's `update` to place anything that has to stay with a moving body on screen: a camera following it, a label over it, a measurement of how smoothly it moves. does not blend is drawn at its simulated pose. that id.

argtypedescription
entityIdstring | entityRefEntity id or proxy. Any entity answers; one the simulation

examples

local d = Physics.drawnPose(car); print(d.position.z, d.simulatedPosition.z, d.interpolated)
local d = Physics.drawnPose(tyre); print(d.interpolated, d.interpolatedBy)

whyStill(entityId: string | entityRef) →

Why the solver is not moving a body. Returns `nil` when it IS moving it, and otherwise one of `noBody`, `simulationNotStepping`, `disabled`, `static`, `kinematic`, `infiniteMass`, `translationLocked`, `gravityDisabled`, `asleep`, `outsideIsland`, `resting`, `aboutToMove` — the nearest cause, so the answer names the thing to change. A second return carries the detail: which collider it rests on and how deeply, what its effective gravity works out to, and so on.

argtypedescription
entityIdstring | entityRefEntity id or proxy.

examples

local why, detail = Physics.whyStill(id); if why then print(why, detail) end

stillnessReasons( ) →

Every reason `whyStill` can answer with, in the order the engine considers them. Read from the engine, so the list is the one the answers come from.

examples

for _, reason in Physics.stillnessReasons() do print(reason) end

contacts(entityId: string | entityRef, otherId: (string | entityRef) →

Every contact one body's colliders are in right now, with the other entity, the normal, how deeply the two interpenetrate, the normal and friction impulse the last step applied, how fast the two were closing as that step began, the step, and each contact point: the read behind "is it touching", "is it grounded" and "how hard did that hit land". It describes the last physics step; to detect every collision, hit and impact as an event on the step it happens, use `Physics.onContact`, `Physics.onImpact` or `Physics.contactPeak`. A pair is listed while its surfaces touch: a pair kept apart (`Physics.ignoreCollision`, collision groups) or no longer touching is not. For a soft body these are the contacts of its surface with every other collider, another soft body's surface included. A contact with a soft body on either side names the particles of it that are touching (`particles` for this side, `otherParticles` for the other), so a hit can be answered where it landed. Name `otherId` to read only the contacts with that one entity: a body resting on the ground holds a contact point per surface element that touches it, and a read of one pair costs that pair alone. or when the entity carries neither a rigid body nor a soft body.

argtypedescription
entityIdstring | entityRefEntity id or proxy.
otherId(string | entityRefOptional entity id or proxy: report only the contacts with it.

examples

for _, c in Physics.contacts(id) do print(c.other, c.deepestPenetration) end
for _, c in Physics.contacts(truck, pole) do if c.totalImpulse > 5 then print("dented at", #c.particles, "particles") end end

defineSurface(name: string, surface: PhysicsSurfaceDefinition?) → void

Define a surface: a named material of contact coefficients that a collider takes by naming it in its `surface` field (every collider component carries one), and that a heightfield takes per sample through `surfaceLayers` / `surfaceMap` (how each painted layer of a terrain is its own ground). A surface holds `friction`, `restitution`, `rollingResistance` (a body rolling on it loses speed at this many times gravity on level ground, so a ball rolled at v stops after v^2 / (2 * rollingResistance * 9.81)), `spinningResistance` (the same for a body spinning on it about the contact normal) and free `tags` (what a footstep, a skid mark or an impact sound reads it by). Per contact the two sides' friction and restitution average and their resistances add (a ball of none on a floor of c rolls against c). Contacts, contact events and ray and shape cast hits name the surface each side is made of at the point, and `Physics.groundContact` names what a body stands on. Defining a name again replaces it, and every collider naming it takes the new values from the next physics step; a collider naming a surface no one defined keeps its own coefficients and still reports the name. unstated coefficients take friction 0.5 and 0 for the rest.

argtypedescription
namestringThe surface's name, 1 to 64 bytes.
surfacePhysicsSurfaceDefinition?`{ friction?, restitution?, rollingResistance?, spinningResistance?, tags? }`;

examples

Physics.defineSurface("gravel", { friction = 0.6, rollingResistance = 0.04, tags = { "loose", "crunchy" } })
Physics.defineSurface("ice", { friction = 0.05, rollingResistance = 0.002 })
entity("road").component.add("BoxCollider", { half = { 50, 0.5, 4 }, surface = "gravel" })

removeSurface(name: string) → void

Remove a surface `Physics.defineSurface` defined. Colliders naming it keep the name and collide with their own coefficients from the next step.

argtypedescription
namestringThe surface's name.

examples

Physics.removeSurface("ice")

getSurface(name: string) →

The surface `name` names, as `Physics.defineSurface` defined it.

argtypedescription
namestringThe surface's name.

examples

local s = Physics.getSurface(hit.surface); if s and table.find(s.tags, "loose") then sprayGravel(hit.point) end

surfaces( ) →

Every surface `Physics.defineSurface` defined, by name.

examples

for name, s in Physics.surfaces() do print(name, s.friction, s.rollingResistance) end

groundContact(entityId: string | entityRef, maxSlope: number?) →

What a body stands on now: of its contacts whose normal leans less than `maxSlope` degrees from straight up against gravity, the one the last step pushed hardest, with the surface it is made of under the body. The read a footstep sound, a tyre without a `WheelCollider`, a skid mark or dust takes to know what is underfoot, on a painted terrain as well.

argtypedescription
entityIdstring | entityRefEntity id or proxy carrying a rigid body.
maxSlopenumber?Optional steepest ground counted, in degrees from level (default 60).

examples

local g = Physics.groundContact(player); if g and g.surface == "gravel" then playStep("gravel") end

touching(entityId: string | entityRef, otherId: string | entityRef) →

Whether two entities are touching, and how deeply. in metres and `0` for surfaces that meet without overlapping.

argtypedescription
entityIdstring | entityRefEntity id or proxy.
otherIdstring | entityRefThe other entity id or proxy.

examples

local hit, depth = Physics.touching(a, b); print(hit, depth)

softBodyState(entityId: string | entityRef, opts: table?) →

What the solver holds for one soft body (an entity with a `SoftBody` component): its particle, cell and edge counts, the volume it encloses against its rest volume, its centre of mass and frame, the box around its particles, how fast they move, whether it sleeps, and what it touches, and in `render` how the entity's model is drawn carried by the body. `plastic` is how deep the deformation that stayed is, in metres (a dent past the component's `plasticYield`; `plasticMean` the mean over the particles), 0 for a body that only deformed elastically. `diverged` is true while a step has carried the body into a state no material reaches (its particles spread, or its volume grown, past ten times the shape it is held at, or a particle carried to a value that is not a number), and `divergence` says what was measured; the engine log names the body the step it diverges. `tearStrain` and `tearForce` are the thresholds it tears past (0 tears never), and `piece` names the torn piece a body split off another continues (nil for a body built from its fields). `attachments` lists the regions held to rigid bodies (`attachSoftRegion`) with the force each pulls with, `attachedParticles` counts the particles tied, and `clusters` counts the body's frame plus one per joint end anchored on a region of it. `pins` lists the regions pinned (`pinSoftRegion`) with how many particles each holds, its target and where its particles' centre stands, and `pinnedParticles` counts the particles held kinematic. `diagnostics` is what the physics debug views picture of the body as numbers: inverted cells, self-crossings, element loads (`maxLoad`, `loadedElements`), pinned and attached particles (see `PhysicsSoftBodyDiagnostics`; `Physics.debugLines` draws them). `replication`, on a synced entity in a multiplayer session, says which peer simulates the body (`authority` `"local"` or `"remote"`, `owner`) and what it costs on the wire here (`lastSync` in seconds, `bytesPerSecond`). `stability` compares the body's stiffest elements with the rate the solver runs them at, from the moment it is built, before it steps (see `PhysicsSoftBodyStability`): `holds` is false and `cannotHold` names each part, with its frequency and the substep rate, when the default solver holds it softer than it is stated. `status` says where the body stands: `"built"`, `"pending"` (the component stands and the body is not built yet, `waitingFor` naming what the build waits on), `"refused"` (`refusal` says why the component was not built) or `"none"` (no SoftBody component). A body is built at the start of the frame after its component is added, so a read in the call that added it answers `"pending"`; wait on `status` rather than reading `exists = false` as a refusal. Answers in edit mode as well as play mode. `positions = true` adds every particle's world position; `contactPoints = true` adds each contact's individual points (each contact names its count, normal, depth, impulse and particles either way); `contactsWith` reports only the contacts with that one entity, so a read about one pair costs that pair alone. answers to that id.

argtypedescription
entityIdstring | entityRefEntity id or proxy.
optstable?`{ positions: boolean?, contactPoints: boolean?, contactsWith: (string | entityRef)? }`:

examples

local s = Physics.softBodyState(jelly); print(s.particleCount, s.volumeRatio, s.sleeping)
print(Physics.softBodyState(shell).plastic)   -- metres of dent the shell kept
local s = Physics.softBodyState(shell); if s.diverged then print(s.divergence) end
for _, p in Physics.softBodyState(jelly, { positions = true }).positions do print(p.y) end
local r = Physics.softBodyState(jelly).render; print(r.drawn, r.vertexCount, r.uploadedThisFrame)
local s = Physics.softBodyState(jelly); if s.status == "pending" then print("waiting for", s.waitingFor) end
local st = Physics.softBodyState(beam).stability; if not st.holds then print(st.cannotHold[1]) end

debugLines(opts: table?) →

Draw what the physics world simulates beyond collider surfaces as world-space lines, with what each object's lines picture as data. This is the read the physics debug views draw from: `capture { pass = "physics" }` and the edit-mode collider overlay (debugViz category `colliders`) both show these lines. Layers: `cage` draws a soft body's elements coloured by load: slack blue, yellow half way, red at the load it tears (see `PhysicsSoftBodyDiagnostics` for how a load is read); `particles` draws its particles: free ones as small grey crosses, pinned ones as green octahedra, ones held to a rigid body as magenta octahedra; `contacts` draws the contacts soft surfaces hold against soft surfaces (their own included): the segment joining the two witness points in orange, the normal in cyan; `wheels` draws each `WheelCollider` wheel: its suspension ray as far as it reaches, its whole travel and the tyre's radius below the mount (green on ground, red in the air, as the wheel's `isGrounded` reads), the travel from its mount to the tyre's centre coloured by how much of it is taken up on the same ramp, its tyre circle in white across its steered axle, and its ground point (yellow) and normal (cyan). Answers in edit mode as well as play mode; in edit mode a vehicle stands at rest with its wheels where they are authored. `layers` names the layers to draw (every layer when omitted; an unknown name is an error naming the layers), `entities` keeps to those entities' objects (a wheel is kept by its own entity or its chassis'). no physics world (a worker).

argtypedescription
optstable?`{ layers: {string}?, entities: {(string | entityRef)}? }`:

examples

local d = Physics.debugLines(); print(d.lineCount, #d.objects)
for _, o in Physics.debugLines({ layers = { "particles" } }).objects do print(o.entity, o.pinned, o.attached) end
local w = Physics.debugLines({ layers = { "wheels" }, entities = { truck } }); for _, o in w.objects do print(o.index, o.grounded, o.compression) end

stepCost( ) →

What the last physics step cost, stage by stage — the same figures `worldState().step` carries, for a caller that wants only these. Each covers that one step rather than a window of them, and consecutive steps over the same resting scene vary by tens of percent, so several samples averaged is the honest read of what a step costs. `softBodyMs` is the soft body part of the step and `softBodies` each soft body's part of it. A frame can run several steps; `recent` lists the last 64 with their ordinals (`step`), so a loop reading once a frame counts every step. step — a paused simulation, or a world still bootstrapping.

examples

local c = Physics.stepCost(); if c then print(c.stepMs, c.narrowPhaseMs) end
local c = Physics.stepCost(); if c then for _, b in c.softBodies do print(b.entity, b.ms, b.particles) end end
local seen, total = 0, 0
-- once a frame: every step since the last read, however many a frame ran
local c = Physics.stepCost(); if c then for _, s in c.recent do if s.step > seen then total += s.softBodyMs; seen = s.step end end end

fits(n: ?) → void

argtypedescription
n?

fits(n: ?) → void

argtypedescription
n?

fits(n: ?) → void

argtypedescription
n?

fits(n: ?) → void

argtypedescription
n?

fits(n: ?) → void

argtypedescription
n?

fits(n: ?) → void

argtypedescription
n?

fits(n: ?) → void

argtypedescription
n?

softBodySettingNames( ) → string

softBodySettings(changes: table?) →

The settings every soft body of the world is simulated under, and the way to change them: how many extra substeps a hard hit may run, how stiff soft contacts are, which tangle and overlap recovery runs, and how far the FEM solver (`SoftBody.solver = "fem"`) solves each step. Each one trades simulation quality for cost; `Physics.stepCost().softBodies` shows what each body costs under them. They are world settings (`physics.soft_body_*` in `.world_settings`) saved with the world: a change reads back at once and the solver runs under it from the next physics tick. Written during play, they land on the play shadow like any other `/source` write: the solver runs under them at once, and they are gone when the play edits are discarded. Write them in edit mode (or keep them with `vfs.promotePlayShadow("/zero/source/.world_settings")`) for the world to keep them. left out keep their values. A field the settings do not have, or a value of the wrong type or out of range, is refused by name.

argtypedescription
changestable?Optional `PhysicsSoftBodySettings` fields to change; the fields

examples

print(Physics.softBodySettings().maxExtraSubsteps)
Physics.softBodySettings({ maxExtraSubsteps = 2 })   -- cheaper hard hits
Physics.softBodySettings({ tangleDetection = false, overlapConstraints = false })
Physics.softBodySettings({ femMaxIterations = 60 })   -- FEM bodies converge further each substep

softBodyComponentOf(softId: string, verb: string, level: number) → any

Forces / impulses The SoftBody component of `softId`, refusing an id that names nothing, a rigid body and an entity with no body, each by name. `level` is the stack level the error is raised at, the caller of the verb.

argtypedescription
softIdstring
verbstring
levelnumber

pushedBody(ref: any, verb: string) → string

The id of a body a push is aimed at, refusing an id that names nothing and an entity that carries no body to push.

argtypedescription
refany
verbstring

pushRadius(opts: any, verb: string) → number

The radius a push's options state, checked.

argtypedescription
optsany
verbstring

softPush(ref: any, verb: string, vector: any, what: string, region: any) → void

A push on a region of a soft body: the soft body's id, its region in the engine form, refusing a rigid body by name and a push that states no vector (`what` names it: "force" or "impulse").

argtypedescription
refany
verbstring
vectorany
whatstring
regionany

applyForce(entityIdOrForce: string | entityRef | vec3, force: vec3?, region: PhysicsSoftRegion?) → void

Apply a force to an entity's rigid or soft body, in newtons, for a span of simulated time, whatever the frame rate and the physics tick rate are. Called from code that runs inside a physics step (`Physics.onBeforeStep` / `onAfterStep`, a contact listener, `fixedUpdate`) it acts on the next physics step alone: call it once per step for a continuous force. Called anywhere else (`update`, a task, a tool call) it acts over the simulated time the next frame advances, shared across however many steps that frame runs: call it once per frame for a continuous force. Either way a continuous force integrates to force times elapsed time, so a body pushed up with its own weight floats. A force that depends on where the body is or how fast it moves (a spring, a field, a controller) belongs in `Physics.onBeforeStep`, which reads the state the step starts from; a pull that drives an orbit or an oscillation keeps its energy given there as the momentum it makes over the step, `Physics.applyImpulse(id, force * dt)`. With one argument the script-context entity is targeted; with two args the explicit entity id wins. A soft body takes the force spread over its particles by mass, so it accelerates as a whole the way a rigid body of its mass would; `region` puts it on part of the body instead (`{ box = { min, max } }` or `{ nearest = point }`, as `Physics.softRegion` takes it), which accelerates that part alike and leaves the rest to follow.

argtypedescription
entityIdOrForcestring | entityRef | vec3Entity id (when paired with `force`) OR a force vector for the script-context entity.
forcevec3?Optional force vector when targeting an explicit entity.
regionPhysicsSoftRegion?Part of a soft body to push, as `Physics.softRegion` takes it; omit for the whole body.

examples

Physics.applyForce({x=0, y=10, z=0})
Physics.applyForce(entityId, {x=0, y=10, z=0})
Physics.applyForce(cloth, {x=0, y=0, z=4}, { box = { min = {-0.5, -1, 0.4}, max = {0.5, 1, 0.5} } })

applyForceAtPoint(entityId: string | entityRef, force: vec3, point: vec3, opts: PhysicsPushOptions?) → void

Apply a force at a specific world-space point, over the span `Physics.applyForce` states: from `Physics.onBeforeStep` (or `fixedUpdate`) on the next step alone, from anywhere else over the next frame's simulated time. On a rigid body it generates the matching torque from the lever arm. On a soft body it pushes the particles around the point, weighted from the whole at the point to nothing at `opts.radius` (by default twice the spacing of the body's particles), so the body gives way there first. It always reaches at least the four particles nearest the point, the smallest patch a body can dent, so a radius finer than the particles are spaced spreads over that patch.

argtypedescription
entityIdstring | entityRefTarget entity id.
forcevec3Force vector, in newtons.
pointvec3World-space application point.
optsPhysicsPushOptions?`{ radius: number? }`: how far into a soft body the force reaches, in metres.

examples

Physics.applyForceAtPoint(id, {x=0,y=10,z=0}, {x=1,y=0,z=0})
Physics.applyForceAtPoint(jelly, {x=0,y=-40,z=0}, {x=0,y=1.5,z=0}, { radius = 0.3 })

applyImpulseAtPoint(entityId: string | entityRef, impulse: vec3, point: vec3, opts: PhysicsPushOptions?) → void

Apply an instantaneous impulse at a world-space point: a hit, a kick, a crash. On a rigid body it changes the body's velocity and spin as an impulse at that point of it would. On a soft body it pushes the particles around the point, weighted from the whole at the point to nothing at `opts.radius` (by default twice the spacing of the body's particles), so the body dents there and the rest of it is carried along through its elastic elements. It always reaches at least the four particles nearest the point, the smallest patch a body can dent, so a radius finer than the particles are spaced spreads over that patch; a finer dent takes a finer body (a higher `resolution`). The impulse is the momentum the body gains, in newton-seconds, wherever it lands.

argtypedescription
entityIdstring | entityRefThe body's entity id or proxy.
impulsevec3The impulse, in newton-seconds.
pointvec3Where it lands, in world space: a contact point.
optsPhysicsPushOptions?`{ radius: number? }`: how far into a soft body the impulse reaches, in metres.

examples

Physics.applyImpulseAtPoint(crate, {x=0, y=0, z=-30}, hit.point)
local contact = Physics.contacts(shell)[1]; if contact then Physics.applyImpulseAtPoint(shell, {x=-60, y=0, z=0}, contact.points[1].point, { radius = 0.4 }) end

applyRadialImpulse(entityId: string | entityRef, center: vec3, magnitude: number, opts: PhysicsPushOptions?) → void

Push a body straight away from a world point, like a blast: the push is `magnitude` newton-seconds at the centre, weighted to nothing at `opts.radius` (omitted, it reaches any distance at full strength). A rigid body is pushed by the distance to its centre of mass; a soft body particle by particle, each away from the centre by its own distance, so a blast beside a balloon pushes it off and one inside a body spreads it out. Each moves off at the speed `magnitude` gives a body of its mass.

argtypedescription
entityIdstring | entityRefThe body's entity id or proxy.
centervec3The blast's world position.
magnitudenumberThe impulse at the centre, in newton-seconds.
optsPhysicsPushOptions?`{ radius: number? }`: how far the push reaches, in metres.

examples

Physics.applyRadialImpulse(balloon, {x=0, y=1, z=-1}, 8, { radius = 3 })
for _, id in pile do Physics.applyRadialImpulse(id, blast, 20, { radius = 4 }) end

applyImpulse(entityIdOrImpulse: string | entityRef | vec3, impulse: vec3?, region: PhysicsSoftRegion?) → void

Apply an instantaneous impulse (one-shot velocity change). With one argument the script-context entity is targeted; with two args the explicit entity id wins. A soft body takes the impulse spread over its particles by mass, so it moves off as a whole the way a rigid body of its mass would; `region` puts it on part of the body instead (as `Physics.softRegion` takes it), which sets that part moving and leaves the rest to follow. `applyImpulseAtPoint` aims one at a point.

argtypedescription
entityIdOrImpulsestring | entityRef | vec3Entity id (with `impulse`) OR an impulse vector for the script-context entity.
impulsevec3?Optional impulse vector when targeting an explicit entity.
regionPhysicsSoftRegion?Part of a soft body to push, as `Physics.softRegion` takes it; omit for the whole body.

examples

Physics.applyImpulse({x=0, y=5, z=0})
Physics.applyImpulse(entityId, {x=0, y=5, z=0})
Physics.applyImpulse(jelly, {x=0, y=-2, z=0}, { box = { min = {-0.5, 0.4, -0.5}, max = {0.5, 0.5, 0.5} } })

applyTorque(entityIdOrTorque: string | entityRef | vec3, torque: vec3?) → void

Apply a torque to an entity's rigid body, over the span `Physics.applyForce` states: from `Physics.onBeforeStep` (or `fixedUpdate`) on the next step alone, from anywhere else over the next frame's simulated time. With one argument the script-context entity is targeted; with two args the explicit entity id wins.

argtypedescription
entityIdOrTorquestring | entityRef | vec3Entity id (with `torque`) OR a torque vector for the script-context entity.
torquevec3?Optional torque vector when targeting an explicit entity.

examples

Physics.applyTorque({x=0, y=1, z=0})
Physics.applyTorque(entityId, {x=0, y=1, z=0})

setVelocity(a: string | entityRef | number | vec3, b: (number | vec3, c: ?, d: ?) → void

Set the linear velocity of an entity. Accepts `(x, y, z)` or a `{x, y, z}` vector for the script-context entity, or the same prefixed with an explicit `entityId`.

argtypedescription
astring | entityRef | number | vec3x-component, a `{x, y, z}` vector, or an entity id (explicit target).
b(number | vec3y-component, x-component, or the vector depending on call form.
c?z-component or y-component depending on call form.
d?Optional z-component when targeting an explicit entity.

examples

Physics.setVelocity(0, 10, 0)
Physics.setVelocity(entityId, 0, 10, 0)
Physics.setVelocity(entityId, {x=0, y=10, z=0})

addVelocity(a: string | entityRef | number | vec3, b: (number | vec3, c: ?, d: ?) → void

Add to the linear velocity of an entity. Same call shapes as `setVelocity`.

argtypedescription
astring | entityRef | number | vec3dx, a `{x, y, z}` delta vector, or an entity id (explicit target).
b(number | vec3dy, dx, or the delta vector depending on call form.
c?dz or dy depending on call form.
d?Optional dz when targeting an explicit entity.

examples

Physics.addVelocity(0, 5, 0)
Physics.addVelocity(entityId, 0, 5, 0)
Physics.addVelocity(entityId, {x=0, y=5, z=0})

setAngularVelocity(a: string | entityRef | number | vec3, b: (number | vec3, c: ?, d: ?) → void

Set the angular velocity of an entity (radians/sec). Same call shapes as `setVelocity`.

argtypedescription
astring | entityRef | number | vec3x-component, a `{x, y, z}` vector, or an entity id (explicit target).
b(number | vec3y-component, x-component, or the vector depending on call form.
c?z-component or y-component depending on call form.
d?Optional z-component when targeting an explicit entity.

examples

Physics.setAngularVelocity(0, 0, 1)
Physics.setAngularVelocity(entityId, 0, 0, 1)
Physics.setAngularVelocity(entityId, {x=0, y=0, z=1})

setGravityScale(entityIdOrScale: string | entityRef | number, scale: number?) → void

Set the per-entity gravity scale (1.0 = normal, 0.0 = no gravity). One-arg form targets the script-context entity.

argtypedescription
entityIdOrScalestring | entityRef | numberEntity id (with `scale`) OR scale value (script-context entity).
scalenumber?Optional explicit scale when targeting another entity.

examples

Physics.setGravityScale(0.5)
Physics.setGravityScale(entityId, 0.5)

setMass(entityIdOrMass: string | entityRef | number, mass: number?) → void

Set the mass of an entity's rigid body (kg). One-arg form targets the script-context entity.

argtypedescription
entityIdOrMassstring | entityRef | numberEntity id (with `mass`) OR mass value (script-context entity).
massnumber?Optional explicit mass when targeting another entity.

examples

Physics.setMass(10)
Physics.setMass(entityId, 10)

setLinearDamping(entityIdOrDamping: string | entityRef | number, damping: number?) → void

Set linear damping on an entity's rigid body (0 = no damping). One-arg form targets the script-context entity.

argtypedescription
entityIdOrDampingstring | entityRef | numberEntity id (with `damping`) OR damping value (script-context entity).
dampingnumber?Optional explicit damping when targeting another entity.

examples

Physics.setLinearDamping(0.05)
Physics.setLinearDamping(entityId, 0.05)

setAngularDamping(entityIdOrDamping: string | entityRef | number, damping: number?) → void

Set angular damping on an entity's rigid body. One-arg form targets the script-context entity.

argtypedescription
entityIdOrDampingstring | entityRef | numberEntity id (with `damping`) OR damping value (script-context entity).
dampingnumber?Optional explicit damping when targeting another entity.

examples

Physics.setAngularDamping(0.1)
Physics.setAngularDamping(entityId, 0.1)

setCcdEnabled(entityIdOrEnabled: string | entityRef | boolean, enabled: boolean?) → void

Enable or disable continuous collision detection on an entity's rigid body. One-arg form targets the script-context entity.

argtypedescription
entityIdOrEnabledstring | entityRef | booleanEntity id (with `enabled`) OR boolean (script-context entity).
enabledboolean?Optional explicit boolean when targeting another entity.

examples

Physics.setCcdEnabled(true)
Physics.setCcdEnabled(entityId, true)

setBodyType(entityId: string | entityRef, bodyType: string) → void

Change a rigid body's type at runtime. Mass, colliders, and joints are preserved — only the body's response to forces and position writes changes.

argtypedescription
entityIdstring | entityRefTarget entity id.
bodyTypestringOne of `"dynamic"`, `"kinematic"`, `"static"`.

examples

Physics.setBodyType(entityId, "kinematic")

setRotationLocks(entityId: string | entityRef, x: boolean, y: boolean, z: boolean) → void

Lock or unlock rotation on specific axes.

argtypedescription
entityIdstring | entityRefTarget entity id.
xbooleanLock rotation about the world X axis.
ybooleanLock rotation about the world Y axis.
zbooleanLock rotation about the world Z axis.

examples

Physics.setRotationLocks(id, false, true, false)

setTranslationLocks(entityId: string | entityRef, x: boolean, y: boolean, z: boolean) → void

Lock or unlock translation on specific axes.

argtypedescription
entityIdstring | entityRefTarget entity id.
xbooleanLock translation along the world X axis.
ybooleanLock translation along the world Y axis.
zbooleanLock translation along the world Z axis.

examples

Physics.setTranslationLocks(id, false, false, true)

setCollisionGroups(entityId: string | entityRef, membership: number, filter: number) → void

Set the collision-group membership and filter bitmasks on an entity's colliders. Adds a `CollisionGroup` component if missing; the component holds the groups, so they apply to the colliders of the entity's rigid body or standalone collider by the next physics step, and a body built or rebuilt later takes them as it is built, in edit mode as well as play. A soft body's groups are its `SoftBody` component's `collisionMemberships` and `collisionFilter`.

argtypedescription
entityIdstring | entityRefTarget entity id.
membershipnumberBitmask: which groups this collider belongs to.
filternumberBitmask: which groups this collider can collide with.

examples

Physics.setCollisionGroups(id, 0x0001, 0xFFFF)

ignoreCollision(entityIdA: string | entityRef, entityIdB: string | entityRef, ignore: boolean?) → void

Keep two entities from colliding, or let them collide again. Covers every collider each one owns (its rigid body with the shapes composed onto it, its standalone collider, its ragdoll's bones, its soft body's surface), so it keeps a soft shell off the chassis it is held to as well as two rigid bodies apart. An ignored pair holds no contact: the solver pushes neither one and `Physics.contacts` lists neither to the other. It applies from the next physics step, to bodies already touching as well, and lasts until it is turned off, either entity is despawned, or the mode changes: entering or leaving play starts without it, so make the call where the bodies are set up for play (a component's `onLoad`). It stands beside collision groups: a pair either one excludes does not collide.

argtypedescription
entityIdAstring | entityRefFirst entity id.
entityIdBstring | entityRefSecond entity id.
ignoreboolean?When `true` (default) the pair is kept apart; `false` lets it collide again.

examples

Physics.ignoreCollision(a, b, true)

addJoint(entityIdA: string | entityRef, entityIdB: string | entityRef, opts: table?) → any

Add a Joint component connecting two entities. Accepts either vec3-style anchor inputs (`localAnchor = {x,y,z}`) or pre-split scalar keys (`localAnchorX/Y/Z`); every other key is a `Joint` field. A body takes any number of joints: on an entity that already carries a Joint the new one is added under `name` (or, without one, the first of `joint2`, `joint3`, ... free on it), and each is its own solver joint. An end entity that is no body itself joins the nearest body above it at its own position and orientation, so a marker under a beam's end pins the beam there: a truss is beams joined through end markers. Either end may be a soft body (an entity with a `SoftBody` component): `region` anchors this end on a region of entity A's soft body and `remoteRegion` the other end on a region of B's, each as `Physics.softRegion` takes it (`{ box = { min, max } }` or `{ nearest = point }`); an end with no region is anchored on the soft body as a whole. The anchor of a region end is measured from the centre of its particles. and `Physics.removeJoint` take.

argtypedescription
entityIdAstring | entityRefEntity that hosts the Joint component.
entityIdBstring | entityRefConnected entity.
optstable?Optional joint description: `kind` (fixed, hinge, ball, prismatic, spring, rope, generic), `localAnchor`, `remoteAnchor`, `axis`, `remoteAxis`, `collideConnected`, the limits (`limitMin` / `limitMax` for a hinge in degrees or a prismatic in metres, `swingLimit` / `twistLimit` for a ball joint in degrees, `axisLimits` on any axis), the motor (`motorMode` "velocity" | "position", `motorVelocity`, `motorTarget`, `motorStiffness`, `motorDamping`, `motorMaxForce`, `motorModel`, `axisMotors` on any axis), `lockedAxes` for a generic joint, `stiffness`, `damping`, `restLength`, `maxDistance`, `breakForce`, `breakTorque`, `region`, `remoteRegion`.

examples

Physics.addJoint(a, b, { kind = "fixed" })
Physics.addJoint(a, b, { kind = "hinge", axis = {x=0,y=1,z=0} })
Physics.addJoint(door, frame, { kind = "hinge", axis = {0,1,0}, limitMin = 0, limitMax = 110 })
Physics.addJoint(arm, base, { kind = "hinge", axis = {0,0,1}, motorMode = "position", motorTarget = 90, motorMaxForce = 500 })
Physics.addJoint(forearm, upperArm, { kind = "ball", swingLimit = 45, twistLimit = 20, collideConnected = false })
Physics.addJoint(piston, cylinder, { kind = "prismatic", axis = {0,1,0}, limitMin = 0, limitMax = 0.5 })
Physics.addJoint(seat, rail, { kind = "generic", lockedAxes = {"linY", "linZ", "angX", "angY", "angZ"}, axisLimits = { linX = {-0.2, 0.2} } })
Physics.addJoint(a, b, { kind = "rope", maxDistance = 8 })
Physics.addJoint(a, b, { kind = "fixed", breakForce = 1200, breakTorque = 800 })
Physics.addJoint(bag, hook, { kind = "ball", region = { nearest = {0, 0.5, 0} } })
Physics.addJoint(jellyA, jellyB, { kind = "fixed", region = { box = { min = {0.4, -0.5, -0.5}, max = {0.5, 0.5, 0.5} } }, remoteRegion = { box = { min = {-0.5, -0.5, -0.5}, max = {-0.4, 0.5, 0.5} } } })
local grab = Physics.addJoint(hand, crate, { kind = "fixed", breakForce = 2000 }); Physics.removeJoint(grab)

split(prefix: string) → void

A vec3 given as a table becomes the three split keys; a vector given neither way keeps the Joint's own default.

argtypedescription
prefixstring

removeJoint(entityId: string | entityRef | table, name: string?) → void

Remove one joint, leaving every other joint on its bodies standing: the `Joint` an entity carries (its unnamed one, or the one `name` names), or the `Joint` component given itself, as `Physics.addJoint` returns it.

argtypedescription
entityIdstring | entityRef | tableTarget entity id, or a `Joint` component.
namestring?The Joint's name on that entity; omit for its unnamed Joint.

examples

Physics.removeJoint(id)
Physics.removeJoint(beam, "right")
local grab = Physics.addJoint(hand, crate); Physics.removeJoint(grab)

jointCarrierOf(id: string) → string

The entity carrying the joint `id` is the connected end of, or nil when no joint connects to it.

argtypedescription
idstring

setJointMotor(entityId: string | entityRef | table, targetVelocity: number, maxForce: number, name: string?) → void

Drive an entity's joint motor at `targetVelocity` with at most `maxForce`. The joint is the one `entityId` carries, or, when it carries none, the joint it is the connected end of. Writes the joint's own motor fields (`motorMode = "velocity"`, `motorVelocity`, `motorMaxForce`), so the motor is component data that syncs and reads back. A hinge turns at radians per second under newton-metres, a prismatic slides at metres per second under newtons, a ball joint drives each of its angles (velocity 0 holds it still: joint friction up to `maxForce`), a generic joint every free axis. For a target angle or travel set `motorMode = "position"` and `motorTarget` on the Joint; for single axes, its `axisMotors`.

argtypedescription
entityIdstring | entityRef | tableEntity carrying the Joint component, or the body it connects to, or a `Joint` component.
targetVelocitynumberVelocity the motor holds: rad/s for an angle, m/s for a travel.
maxForcenumberThe most force or torque the motor applies; 0 leaves it uncapped.
namestring?The Joint's name on that entity, for one of several joints; omit for its unnamed Joint.

examples

Physics.setJointMotor(wheel, 10, 50)
Physics.setJointMotor(piston, 0.5, 2000)
Physics.setJointMotor(arm, 2, 300, "elbow")

softVec(v: any, what: string) → void

Soft bodies held to rigid bodies, pinned, and soft body joint ends

argtypedescription
vany
whatstring

softRegion(region: PhysicsSoftRegion?) →

The engine form of a soft body region: the record the `SoftBody` component's attachments and a `Joint`'s soft body ends carry. A region names part of a soft body by where its particles stand: `{ box = { min, max } }` is every particle between the two corners, `{ nearest = point }` the one particle nearest the point, and `nil` (or `{}`) the whole body. Coordinates are in the soft body entity's local space, the unit box it is built in (-0.5 to 0.5 on each axis, before its scale; for a `custom` body, the space its particles are listed in), so a region stays the same part of the body wherever the body is; `space = "world"` reads them in world space instead. A box counts a particle whose contact skin reaches into it: a generated body's outer particles stand that skin inside the unit box, so a box flat on one of its faces (`min = {-0.5, -1, -1}, max = {-0.5, 1, 1}`) holds that face's particles. Errors naming the key that is wrong.

argtypedescription
regionPhysicsSoftRegion?`{ box = { min = v, max = v } | { v, v }, nearest = v, space = "local" | "world" }`, or nil for the whole body.

examples

Physics.softRegion({ box = { min = {-0.5, 0.45, -0.5}, max = {0.5, 0.5, 0.5} } })
Physics.softRegion({ nearest = {0, 0.5, 0} })

softBodyComponent(softId: string, verb: string) → any

argtypedescription
softIdstring
verbstring

attachSoftRegion(softId: string | entityRef, targetId: string | entityRef, region: PhysicsSoftRegion?) →

Hold a region of a soft body to a rigid body, two-way: the region follows the rigid body wherever it goes, and the rigid body carries the region's weight and pull. Each particle in the region is tied to the point of the rigid body it stands at when the attachment is made. The attachment is an entry of the soft body's `SoftBody` component (`attachments`), so it is saved with the scene, reaches every peer, and is made again on a rebuilt body; it is released when either side is removed. Its load reads back from `Physics.softBodyState(softId).attachments`. A cloth's edge on a flagpole, a soft panel on a car's chassis, a jelly glued to a moving platform. Where the rigid body's colliders touch the soft body (a shell resting on its chassis), the contact and the hold push on each other: keep them clear, or `Physics.ignoreCollision(softId, targetId)`.

argtypedescription
softIdstring | entityRefThe soft body's entity (it carries a `SoftBody` component).
targetIdstring | entityRefThe rigid body's entity (it carries `Physics`), by id, name or proxy.
regionPhysicsSoftRegion?Which particles to hold, as `Physics.softRegion` takes it: `{ box = { min, max } }`, `{ nearest = point }`, with `space = "world"` for world coordinates; nil holds the whole body.

examples

Physics.attachSoftRegion(flag, pole, { box = { min = {-0.5, -1, -1}, max = {-0.45, 1, 1} } })
Physics.attachSoftRegion(shell, chassis, { box = { min = {-0.5, -0.5, -0.5}, max = {0.5, -0.4, 0.5} } })

repairSoftBody(softId: string | entityRef) → number

Restore the shape a soft body was built in: every permanent dent, crumple and crease it took past its `plasticYield` is undone, and the body is put back in that shape where it stands, keeping its motion as a whole. The repair is the `SoftBody` component's `repairs` count raised by one, so it reaches every peer. `Physics.softBodyState(softId).plastic` reads 0 once it is applied (at the start of the next frame), and a `Physics.setSoftParticles` made before then is put back in the built shape with the rest of the body.

argtypedescription
softIdstring | entityRefThe soft body's entity (it carries a `SoftBody` component).

examples

Physics.repairSoftBody(shell)

detachSoftRegion(softId: string | entityRef, targetId: (string | entityRef) →

Release regions of a soft body held with `attachSoftRegion` (or authored in its `SoftBody` component's `attachments`).

argtypedescription
softIdstring | entityRefThe soft body's entity.
targetId(string | entityRefRelease only the regions held to this rigid body; omit to release every one.

examples

Physics.detachSoftRegion(flag, pole)
Physics.detachSoftRegion(shell)

pinSoftRegion(softId: string | entityRef, region: PhysicsSoftRegion?, opts: { name: string?, target: vec3? }?) →

Pin a region of a soft body: its particles are held kinematic, where they stand now, and the rest of the body hangs from them, rests on them or swings about them through its elastic elements. A cloth pinned by two corners hangs; a jelly pinned along its base stays put while its top wobbles. Give the pin a `target` (or set one later with `Physics.setPinTarget`) and the pinned particles move together so their centre stands there, dragging the body after them: a hand grabbing a corner, a press driven down into a block. The pin is an entry of the soft body's `SoftBody` component (`pins`), so it is saved with the scene, reaches every peer and is made again on a rebuilt body; it reads back from `Physics.softBodyState(softId).pins`.

argtypedescription
softIdstring | entityRefThe soft body's entity (it carries a `SoftBody` component).
regionPhysicsSoftRegion?Which particles to pin, as `Physics.softRegion` takes it: `{ box = { min, max } }` or `{ nearest = point }` in the entity's unit box (-0.5 to 0.5 on each axis), `space = "world"` for world coordinates; nil pins the whole body.
opts{ name: string?, target: vec3? }?`{ name: string?, target: vec3? }`: the name the pin is addressed by (by default `pin1`, `pin2`, ...), and a world position to move the pinned particles' centre to.

examples

local corner = Physics.pinSoftRegion(cloth, { nearest = {-0.5, 0, 0.5} })
Physics.pinSoftRegion(cloth, { box = { min = {-0.5, -1, 0.45}, max = {0.5, 1, 0.5} } }, { name = "top" })
local grab = Physics.pinSoftRegion(jelly, { nearest = hit.point, space = "world" }, { target = hit.point })

setPinTarget(softId: string | entityRef, name: string, position: vec3?) → void

Drive a pin of a soft body to a world position: its particles move together over the next step so the centre they had when the pin was made stands at `position`, with the velocity that carries them there, and the rest of the body follows. Set it every frame to drag the region along a path. `nil` stops driving it and holds it where it stands. The target is the pin's entry in the `SoftBody` component's `pins`, so it reaches every peer.

argtypedescription
softIdstring | entityRefThe soft body's entity.
namestringThe pin's name, as `pinSoftRegion` returned it.
positionvec3?The world position for the pinned particles' centre; nil holds them where they stand.

examples

Physics.setPinTarget(cloth, corner, {x=2, y=3, z=0})

releasePin(softId: string | entityRef, name: string?) →

Release a pin of a soft body, or every pin: its particles take their mass back, keep the velocity they had, and move with the body again.

argtypedescription
softIdstring | entityRefThe soft body's entity.
namestring?The pin to release; omit to release every one.

examples

Physics.releasePin(cloth, corner)
Physics.releasePin(cloth)

softParticles(softId: string | entityRef, region: PhysicsSoftRegion?) →

Read the particles of a soft body that a region selects: where each stands, how fast it moves, where it stands in the body's rest shape and whether it is pinned, with the selection's centre of mass and mean velocity. `Physics.setSoftParticles` writes a read back as it is. The way to see a dent where a hit landed, how far a pinned corner was dragged, or how a region moves. `indices` name the particles for comparing two reads of the same body. The region is resolved at each call against where the particles stand then (a local-space region in the body's frame as it stands now), so a read after the body moved can select other particles than an earlier read of the same region; a pin's own particles read back through `Physics.softBodyState(softId).pins` (`center`) and the `pinned` flags.

argtypedescription
softIdstring | entityRefThe soft body's entity.
regionPhysicsSoftRegion?Which particles to read, as `Physics.softRegion` takes it; nil reads the whole body.

examples

local top = Physics.softParticles(jelly, { box = { min = {-0.5, 0.4, -0.5}, max = {0.5, 0.5, 0.5} } }); print(top.count, top.center.y)
local near = Physics.softParticles(shell, { box = { min = {1.6, 0, -0.3}, max = {2.2, 1, 0.3} }, space = "world" })

setSoftParticles(softId: string | entityRef, particles: PhysicsSoftParticlesWrite) →

Write a soft body's particles: where each stands, how fast it moves, and where it stands in the body's rest shape, the shape it springs back to. The body simulates on from the written state, so a shape read once can be put back: a replay or a rewind, a saved game holding a damaged object, a level that starts with something already bent, a correction from the network, a repair that pushes one dent out. The write is applied at once on the peer that simulates the body: a read straight after sees it, and the next physics step starts from it. Written from `Physics.onBeforeStep`, it is the state that step starts from, ahead of the step's drives, tears and solve. `positions` and `velocities` move the particles and leave the rest shape as it was, so the body springs back from a written shape toward its rest shape (a dent past its `plasticYield` can then set); `restPositions` changes the rest shape itself, the permanent part of the shape, which stays once the body settles, the way a dent past the yield stays (`Physics.softBodyState(id) .plastic` reads it, and `Physics.repairSoftBody` undoes it). A read's `restPositions` are where each particle rests, which a crumple's elements pull the body away from, so to keep the shape a body stands in after a crash, write its `positions` as `restPositions`. Positions are written first and the body's frame fitted to them, then the rest places are measured through that frame, and each element of the body takes the rest shape its particles' places give it, which can differ from the one a crumple's elements flowed to: a body whose flow left its elements pulling against one another (a deep crumple) keeps the written dent and settles a little way from the written shape, into it or out of it. Rest places that state the shape the body was built in (a read taken before its first dent) put that shape back exactly, the way `Physics.repairSoftBody` does, so a rewind to a moment before a crash replays it the same way each time. A write that places every particle (a whole read written back) is the whole state the body steps on from, so two rewinds to one read fall the same way, and the frame after a write draws the body where it was written, paused or not. A rewind starts from the read alone, while the run the read came from carried on with what the solver had built up, so the two can part by rounding where a hit amplifies it; writing the read back the moment it is taken (from `Physics.onBeforeStep`) makes that run a replay of it too. A read's rest places say where each particle rests, while each element of a crumple keeps a flow of its own: written back over the body while it still holds the read's dent, a read leaves those elements as they are, and written over any other state it gives each element the rest its particles' places give, so a body read with a deep crumple steps on from the two a little apart (about 1.5 cm over 20 steps where a 3 m slab's crumple pulls hardest). A repair (`Physics.repairSoftBody`) applies at the start of the next frame and puts the body back in its built shape over a write made before it; a written `restPositions` in the built shape is the same repair, at once. A pinned particle stands where it is written and its pin holds it there, whatever velocity is written to it (a read before the next step reads that velocity; the step keeps the particle in place). A `Physics.softParticles` read is a write of this shape, so `Physics.setSoftParticles(id, read)` puts back the particles it read, their rest places included.

argtypedescription
softIdstring | entityRefThe soft body's entity (it carries a `SoftBody` component).
particlesPhysicsSoftParticlesWrite`PhysicsSoftParticlesWrite`: `indices` (zero-based, as `Physics.softParticles` reads them; omit to write every particle in order) and any of `positions`, `velocities` and `restPositions`, one value per named particle, in world space.

examples

local saved = Physics.softParticles(shell); if saved then Physics.setSoftParticles(shell, saved) end   -- later: put the shell back as it was
local bent = Physics.softParticles(bar); if bent then Physics.setSoftParticles(bar, { restPositions = bent.positions }) end   -- the shape it stands in becomes its rest shape
Physics.setSoftParticles(jelly, { indices = { 0, 7 }, velocities = { {x=0, y=3, z=0}, {x=0, y=3, z=0} } })

softElements(softId: string | entityRef) →

Read every element of a soft body in one call: the force each carries (newtons, positive pulling, negative pushing), its strain, length, rest length, permanent set, its load against its break limit, whether it broke, and where its two ends stand in world space (`endA`, `endB`; a broken element's are where its particles went), as arrays indexed by element. A `custom` body's authored `elements` read by their number in the component's list, wherever a tear left them, the same read from the body's entity and from each piece's; any other body's edges read in its own order with `a` / `b` naming their particles. The way to colour a structure by stress, draw its members, find its most loaded member or watch a span carry a load, at the cost of one call per frame.

argtypedescription
softIdstring | entityRefThe soft body's entity.

examples

local s = Physics.softElements(bridge); for i = 1, s.count do if s.load[i] > 0.8 then print("member", i, "near breaking", s.force[i]) end end
local s = Physics.softElements(bridge); for i = 1, s.count do if not s.broken[i] then print("member", i, "from", s.endA[i], "to", s.endB[i]) end end

softBodyEnergy(softId: string | entityRef, opts: { mark: boolean? }?) →

Read a soft body's energy ledger, to tune a deformable by numbers: the kinetic and elastic energy it holds now, and since the mark the work gravity did on it, the work plastic flow absorbed, the energy tears and cuts took out of it, what pieces split off carried away and what it lost otherwise (damping, friction, contacts, less what whatever holds or pushes it gave it), each by region too, with the peak acceleration of its centre of mass. `opts.mark = true` sets the mark first and starts the ledger again; a body never marked reads its kinetic and elastic energy only (`accounted` is false), and costs nothing per step. A marked body is accounted after every step that moves it, so a crash read straight after it reads the whole crash: mark before, read after.

argtypedescription
softIdstring | entityRefThe soft body's entity.
opts{ mark: boolean? }?`{ mark: boolean? }`.

examples

Physics.softBodyEnergy(shell, { mark = true })   -- before the crash
local e = Physics.softBodyEnergy(shell); print(e.absorbed, e.elastic, e.dissipated)   -- after it: joules
for _, r in Physics.softBodyEnergy(shell).regions do print(r.name, r.absorbed) end

measureSoftBody(softId: string | entityRef, test: { [string]: any }) →

Measure how a soft body responds to a stated load, without building a rig: a copy of it, built from its component as authored, is pressed between two plates, sent at a speed into a post or a wall, or dropped onto a floor, in a world of its own at the tick and solver iterations the world's settings state (in edit mode as in play), and every step is sampled: force against displacement, its energy and what it absorbed. The live body is untouched. A press answers its initial `stiffness` (N/m), `peakForce`, the `work` under the loading curve and the `permanentSet`; an impact the `crush`, `peakForce`, `peakDeceleration`, `rebound` and the share of its energy it absorbed (`absorbedShare`); a drop the same against the height. Tune a material toward "takes X kJ over Y m" with it, then build the body.

argtypedescription
softIdstring | entityRefThe soft body's entity.
test{ [string]: any }One load: `{ press = { depth, axis?, speed?, hold?, settle?, friction? } }` (axis "x", "y" or "z" in the body's own frame, default "y"; speed default depth / 2 s; frictionless plates unless `friction` says otherwise), `{ impact = { speed, direction?, radius?, offset?, carried?, duration?, friction? } }` (direction default "-z", a post of `radius` metres or a wall when it is left out, `carried` kilograms on a rigid block held to its trailing face) or `{ drop = { height, duration?, friction? } }`.

examples

local m = Physics.measureSoftBody(block, { press = { depth = 0.05 } }); print(m.stiffness, m.work, m.absorbed)
local m = Physics.measureSoftBody(nose, { impact = { speed = 15, radius = 0.1, carried = 700 } }); print(m.crush, m.rebound, m.absorbedShare, m.peakDeceleration / 9.81)
local m = Physics.measureSoftBody(crate, { drop = { height = 2 } }); print(m.absorbed, m.elastic, m.dissipated, m.gravityWork)

driveSoftElements(softId: string | entityRef, targets: { [number]: number }, opts: { speed: number? }?) → void

Drive the length of authored elements of a `custom` soft body: each named element's rest length moves toward its target at `opts.speed` (metres per second; 0 or omitted sets it at once), pushing and pulling with no more than the element's own `maxForce`, so a blocked ram stalls instead of tearing the body. A hydraulic ram, a muscle, a crane's luffing cylinder. The drive holds until the element's fields are written again (an element of kind "actuator" is driven to its `targetLength` from its fields). Takes effect from the next physics step, on the peer that simulates the body.

argtypedescription
softIdstring | entityRefThe soft body's entity.
targets{ [number]: number }Element number (as listed in the component's `elements`) to the length in metres it is driven to.
opts{ speed: number? }?`{ speed: number? }`: how fast the lengths move, in metres per second.

examples

Physics.driveSoftElements(crane, { [7] = 2.5, [8] = 2.5 }, { speed = 0.4 })

entitiesForPieces(record: any) → void

Make the entity of every piece a tear record names: a copy of the entity the piece came from, without its children, that is play state (left out of every save), stands at the root of the scene, so it flies free of whatever the torn entity hangs from, and whose SoftBody adopts the piece's body.

argtypedescription
recordany

pumpSoftBodyTears( ) → void

pumpSoftBodyTears( ) → void

Give every piece the soft bodies tore off since the last call its entity, and deliver each tear to the `onSoftBodyTear` listeners. Every `SoftBody` component calls this each frame, so tears are handled on their own; the work is done once per frame however many call it.

examples

Physics.pumpSoftBodyTears()

onSoftBodyTear(fn: (PhysicsSoftBodyTear) →

Call `fn` for every tear of a soft body from now on: a body loaded past its `tearStrain` or `tearForce` (fields of its `SoftBody` component), cut by `Physics.cutSoftBody` or torn by `Physics.tearSoftBody`. The torn entity keeps the largest piece; every piece split off is an entity of its own by the time `fn` runs, standing at the root of the scene and carrying a `SoftBody` with the torn body's fields, its share of the model and the material, the velocity, dents and pins that fell on its side. Its body joins it on the next frame, and an impulse applied to it in `fn` reaches the body then. A piece is play state: it is left out of every save, and leaving play takes it away and gives the torn entity back its whole body.

argtypedescription
fn(PhysicsSoftBodyTearReceives one `PhysicsSoftBodyTear` per tear: `{ entity, pieces, position, kind, particles }`.

examples

local off = Physics.onSoftBodyTear(function(e) print(e.entity, #e.pieces, e.position) end)
Physics.onSoftBodyTear(function(e) for _, id in e.pieces do Physics.applyImpulse(id, { x = 0, y = 2, z = 0 }) end end)

softBodyTears( ) →

Every soft body tear since the last call to this function, oldest first, with the entities of the pieces each split off: the same records `onSoftBodyTear` delivers. The 256 most recent are kept.

examples

for _, t in Physics.softBodyTears() do print(t.kind, t.entity, #t.pieces) end

refuseBreakInEdit(verb: string) → void

Refuse a cut or a tear asked in edit mode: nothing simulates there, so it would wait for a physics step that only play mode takes, on a body play mode builds anew.

argtypedescription
verbstring

cutSoftBody(softId: string | entityRef, blade: { vec3 } | { point: vec3, normal: vec3 }) → void

Cut a soft body along a blade, every element of the body the blade meets opening along it: `{ point = p, normal = n }` cuts along the whole plane through `p` facing `n`, splitting the body in two wherever it lies on both sides; `{ a, b, c }` cuts along that world-space triangle, which cuts only as far as the triangle reaches. Applied straight after the next physics step; a piece the cut separates becomes an entity of its own (see `onSoftBodyTear`), and the cut reports as a tear of kind "cut". A plane is measured against the body where that step leaves it, so it cuts a moving body wherever it has gone; a cut that opens nothing is reported in the log. Raises when the entity carries no `SoftBody`, and in edit mode, where nothing simulates.

argtypedescription
softIdstring | entityRefThe soft body's entity.
blade{ vec3 } | { point: vec3, normal: vec3 }`{ point = vec3, normal = vec3 }` for a plane, or the triangle's three world-space corners `{ a, b, c }`.

examples

Physics.cutSoftBody(jelly, { point = vector.create(0, 1, 0), normal = vector.create(1, 0, 0) })   -- in two along x = 0
Physics.cutSoftBody(jelly, { vector.create(0, -5, -5), vector.create(0, 5, -5), vector.create(0, 0, 10) })
-- slice off the part of a body 0.2 m above its centre
local c = Physics.softBodyState(jelly).centerOfMass
Physics.cutSoftBody(jelly, { point = vector.create(c.x, c.y + 0.2, c.z), normal = vector.create(0, 1, 0) })

tearSoftBody(softId: string | entityRef, region: PhysicsSoftRegion) → void

Tear a soft body at a region: every edge and cell holding a particle of the region comes apart there, opening a hole or, when the region runs across the body, splitting it. Applied straight after the next physics step; a piece the tear separates becomes an entity of its own (see `onSoftBodyTear`), and it reports as a tear of kind "tear". Raises when the entity carries no `SoftBody`, for a region naming no box and no point (the whole body), and in edit mode, where nothing simulates.

argtypedescription
softIdstring | entityRefThe soft body's entity.
regionPhysicsSoftRegionWhich particles to tear through, as `Physics.softRegion` takes it: `{ box = { min, max } }` or `{ nearest = point }` in the entity's unit box (-0.5 to 0.5 on each axis), `space = "world"` for world coordinates.

examples

Physics.tearSoftBody(cloth, { nearest = hit.point, space = "world" })
Physics.tearSoftBody(sheet, { box = { min = {-0.02, -1, -0.5}, max = {0.02, 1, 0.5} } })

pumpJointBreaks( ) → void

The engine hands each break over exactly once, so every record this reads is the only copy there will ever be: buffer the whole batch before any listener runs, and run each listener under pcall, so one handler that raises costs its own delivery and nothing else's.

pumpJointBreaks( ) → void

Deliver every joint break the simulation has recorded to the registered listeners. The engine calls this after every physics step that broke a joint, before that step's `fixedUpdate`, so listeners hear each break at the physics rate whichever way the joint was made.

examples

Physics.pumpJointBreaks()

jointReaction(entityId: string | entityRef | table, name: string?) →

The load (the stress) an entity's joint is carrying right now, as the constraint solver resolved it on the last physics step: the force and the moment it applies to the body carrying it, as vectors and read along the member it holds, so tension tells from compression, axial load from shear and bending from twist. This is the same quantity a break threshold is measured against, and `load` is the share of `breakForce` / `breakTorque` it stands at. A joint with a soft body at either end reads the same way. `Physics.jointReactions` reads many joints in one call. its constraint is not built yet. `axial` is the force along the member at this body's end, positive pulling it outward (tension) and negative pushing it inward (compression): a member hanging 10 kg reads +98.1, one propping it -98.1. `direction` is that line, from the body's centre of mass out to its anchor; `connectedAxial` reads the connected body as a member the same way. `tension` is the pull along the line between the two anchors (a rope's or a spring's), 0 while they stand together. `shear` is the force across the member, `bending` the moment across it, `torsion` the moment about it. `worldForce` / `worldTorque` are the force and the moment about the anchor the joint applies to this body (N, N·m), `localForce` / `localTorque` the same along the joint frame's axes, and `force` / `torque` their sizes. `load` is the larger of force / breakForce and torque / breakTorque, 1 breaking the joint, 0 with no threshold. A joint `Physics.listenJointLoads` listens to carries `peak`, the largest load any step put on it since the last read, which reading takes.

argtypedescription
entityIdstring | entityRef | tableEntity carrying the Joint component, or a `Joint` component.
namestring?The Joint's name on that entity, for one of several joints; omit for its unnamed Joint.

examples

local r = Physics.jointReaction(id); print(r and r.axial)
local r = Physics.jointReaction(beam, "right"); if r and r.axial < 0 then print("compressed", -r.axial) end

jointCarriers(targets: any, fname: string) → void

The entities carrying the constraints of the joints `targets` names: a `Joint` component, an entity (every joint its body is in), or an array of Joint components and entities (each entity's unnamed Joint).

argtypedescription
targetsany
fnamestring

jointReactions(targets: any?, opts: { vectors: boolean?, fields: { string }? }?) →

The load (the stress) of many joints in one call, as arrays of one value per joint, each read the way `Physics.jointReaction` reads one: a whole bridge or machine coloured by load in one read a frame. `targets` is an array of `Joint` components and entities (each entity's unnamed Joint), in the order the arrays answer; one entity, for every joint its body is in; or nil for every joint in the world. Each joint is named by `entityId` (whose Joint), `joint` (its name, empty for the unnamed one), `jointEntityId` and `connectedEntityId`, and by `bodyEntityId` and `connectedBodyEntityId`, the entities of the two bodies it holds: the members to sum a structure's loads on. A joint `Physics.listenJointLoads` listens to gives the peak it carried since its last read in `peakLoad`, `peakMaxAxial` and `peakMinAxial`, which reading takes; every other joint gives its current reading there. (any listed in the return, the vectors and names included), the cheapest read of a large structure; `{ vectors = true }` adds the arrays `worldForce`, `worldTorque`, `localForce`, `localTorque`, `direction` and `position` of {x, y, z}. Reading the same joints every frame, pass their `joint:jointEntityId()` ids, taken once, in place of the Joints. while a joint's constraint is not built, its values 0), `axial`, `connectedAxial`, `tension`, `shear`, `bending`, `torsion`, `force`, `torque`, `impulse`, `load`, `listened`, `peakLoad`, `peakMaxAxial`, `peakMinAxial`.

argtypedescription
targetsany?An array of Joints and entities, one entity, or nil for every joint.
opts{ vectors: boolean?, fields: { string }? }?`{ fields = { "axial", "load" } }` builds only the arrays it names

examples

local r = Physics.jointReactions(); for i = 1, r.count do print(r.entityId[i], r.axial[i], r.load[i]) end
local r = Physics.jointReactions(members); for i = 1, r.count do if r.load[i] > 0.8 then print(i, "near breaking") end end
local r = Physics.jointReactions(ids, { fields = { "axial", "load" } }); print(r.axial[1], r.load[1])

listenJointLoads(targets: any, listen: boolean?) → void

Keep the peak load of joints between reads: from the next physics step on, every step offers its load to each joint's peak, and `Physics.jointReaction(..).peak` and the `peak*` arrays of `Physics.jointReactions` take it, so a load that crossed a threshold for one step and fell back is still read however many steps ran between two reads. Only listened joints (and breakable ones) are measured every step. Listening ends when `listen` is false or the joint's entity is gone.

argtypedescription
targetsanyA `Joint`, an entity (every joint its body is in), or an array of Joints and entities.
listenboolean?True (the default) to keep the peak, false to stop.

examples

Physics.listenJointLoads(bridgeJoints)
local r = Physics.jointReaction(cable); if r and r.peak and r.peak.load > 1 then print("overloaded at step", r.peak.step) end

jointState(entityId: string | entityRef | table, name: string?) →

Where an entity's joint stands as of the last physics step: the angle of a hinge, the travel of a prismatic, the swing and twist of a ball joint, whether it is at a limit, and the force its limit and motor applied. `axes` holds the same for each axis of the joint's frame (the frame's X along the joint's `axis`). Angles are degrees, angular velocities radians per second, travels metres.

argtypedescription
entityIdstring | entityRef | tableEntity carrying the Joint component, or a `Joint` component.
namestring?The Joint's name on that entity, for one of several joints; omit for its unnamed Joint.

examples

local s = Physics.jointState(door); print(s.angle, s.atLimit)
if Physics.jointState(elbow).atLimit then playSound("creak") end

jointBreaks( ) →

Every joint that has broken since the last call to this function. A joint breaks when the reaction it carries exceeds the `breakForce` (newtons of force on the body carrying it) or `breakTorque` (newton-metres of moment about its anchor) its joint was given; each joint reports once and its constraint is already released when the record arrives. The 256 most recent are kept: a structure that comes apart while nothing reads them drops the oldest beyond that, as the engine's own queue does beyond 1024.

examples

for _, e in ipairs(Physics.jointBreaks()) do print(e.entityId, e.force) end

onJointBreak(fn: (table) →

Call `fn` for every joint that breaks from now on, with the same record `jointBreaks` returns.

argtypedescription
fn(tableReceives one break record per broken joint.

examples

local off = Physics.onJointBreak(function(e) print(e.kind, e.force, e.position) end)

contactEventFrom(record: any, flipped: boolean) → PhysicsContactEvent

A record as `entity` sees it: the record unchanged when `entity` is its first side, else its two sides exchanged and its normals reversed.

argtypedescription
recordany
flippedboolean

contactSideOf(record: any, target: string) → boolean

How a record reaches a target: as is when the target is its first side, reversed when it is the second, nil when it is neither. The empty target (every contact) takes every record as is.

argtypedescription
recordany
targetstring

contactWanted(listener: any, event: PhysicsContactEvent) → boolean

Whether a listener wants an event. An impact is the listener's when the impulse rose past its own `minImpulse` on that step, whichever threshold of another listener's the engine recorded it for.

argtypedescription
listenerany
eventPhysicsContactEvent

pumpContactEvents( ) → void

Take what the engine recorded and hand each record to every listener and buffer whose target it concerns.

view(flipped: boolean) → PhysicsContactEvent

argtypedescription
flippedboolean

syncContactInterest(target: string) → void

Tell the engine what to record for `target`: the union of what its listeners and buffers ask, or nothing once none is left.

argtypedescription
targetstring

ask(entry: any) → void

argtypedescription
entryany

contactAsk(fname: string, opts: PhysicsContactOptions?, defaults: { string }) → any

What a listener or buffer asks for, from its options, raising on a kind the engine does not record.

argtypedescription
fnamestring
optsPhysicsContactOptions?
defaults{ string }

contactTarget(fname: string, target: (string | entityRef) → void

argtypedescription
fnamestring
target(string | entityRef

addContactListener(fname: string, target: (string | entityRef) → void

argtypedescription
fnamestring
target(string | entityRef

_onDisconnect( ) → void

The connection ends when `off` runs, or when the component that made it is removed or its entity destroyed; either way the listener goes and the engine stops recording what nobody hears any more.

onContact(target: (string | entityRef, fn: ?, opts: ?) →

Call `fn` for each collision and contact event of an entity's colliders from now on: on collision begin, while the two stay in contact, on collision end, on an impact (a hit, by how hard it lands), and on a trigger's enter and exit. Events are recorded by the physics step itself and `fn` runs once per step, before that step's `fixedUpdate`, so an impact that lasts one step is heard even when a frame runs several steps. The listener ends when the returned function is called, or when the component that registered it is removed or its entity destroyed. Only the colliders somebody listens to cost the step anything. Use it to detect a hit, a landing, two things touching or parting, or a body in a zone. built from), a collider's own entity, a trigger, a soft body. `nil` hears every contact in the world. `{ kind, step, entity, other, collider, otherCollider, trigger, normal, closingSpeed, impulse, tangentImpulse, peakImpulse, totalImpulse, steps, pointCount, points }`. `kinds` defaults to begin, end, enter and exit, plus impact when `minImpulse` is given; add "persist" for an event on every step of a contact.

argtypedescription
target(string | entityRefThe entity whose contacts to hear: a body (every collider it is
fn?Receives one `PhysicsContactEvent` per event, seen from `target`:
opts?`PhysicsContactOptions`: `{ kinds?, minImpulse?, minSpeed? }`.

examples

local off = Physics.onContact(ball, function(e) if e.kind == "begin" then print("hit", e.other, e.closingSpeed) end end)
Physics.onContact(nil, function(e) print(e.kind, e.entity, e.other) end, { kinds = { "begin", "end" } })
Physics.onContact(public.entityId, function(e) log.info(`{e.kind} with {e.other}`) end)

onImpact(target: (string | entityRef, fn: ?, opts: ?) →

Call `fn` for every impact (a collision hit) on an entity from now on: the physics step on which the normal impulse between it and something it touches rises past `minImpulse` newton-seconds. Each impact is heard once, on the step it lands, with the impulse of that step (`impulse`, N s; a rigid stop of mass m from speed v is m * v), how fast the two were closing as they met (`closingSpeed`, m/s) and where (`points`); the impulse divided by the step's time is the mean impact force over it. Use it to detect a hit and answer it: damage, impact sounds, fall damage, scoring, breaking things. Runs once per physics step, before that step's `fixedUpdate`. (default 0, the step a pair first takes any load) and the closing speed it must reach.

argtypedescription
target(string | entityRefThe entity to hear impacts on, or `nil` for every impact in the world.
fn?Receives one `PhysicsContactEvent` (kind "impact") per impact.
opts?`{ minImpulse?, minSpeed? }`: the impulse an impact must reach

examples

Physics.onImpact(box, function(e) print("hit by", e.other, e.impulse, "N s at", e.closingSpeed, "m/s") end, { minImpulse = 50 })
Physics.onImpact(player, function(e) if e.closingSpeed > 12 then takeFallDamage(e.closingSpeed) end end)

onTrigger(target: (string | entityRef, fn: ?) →

Call `fn` when a body enters or leaves a trigger from now on (on trigger enter, on trigger exit). A trigger is a collider with `isTrigger` set: it holds nothing up and reports what overlaps it, whether it stands alone or rides a body, and it detects dynamic and kinematic bodies alike. A fixed trigger leaves out the fixed geometry it stands in, such as the floor under a zone. hear; `nil` hears every trigger in the world. ("exit"), seen from `target`, with `other` the entity that entered or left.

argtypedescription
target(string | entityRefThe trigger's entity, or the entity whose trigger overlaps to
fn?Receives one `PhysicsContactEvent` per enter ("enter") and exit

examples

Physics.onTrigger(zone, function(e) if e.kind == "enter" then print(e.other, "entered") end end)

listenContacts(target: (string | entityRef, opts: ?) →

Start keeping an entity's collision and contact events for polling: from now on every event of the kinds `opts` names is kept for `Physics.contactEvents(target)` to read, and the hardest hit it takes for `Physics.contactPeak(target)`, however many physics steps run between two reads. Keeps the most recent 1024 events per target. Calling it again for the same target replaces the options. The events stop being kept when the returned function runs, or when the component that called it is removed or its entity destroyed.

argtypedescription
target(string | entityRefThe entity whose events to keep, or `nil` for every contact in the world.
opts?`PhysicsContactOptions`, as `onContact` takes it.

examples

local stop = Physics.listenContacts(body, { minImpulse = 100 })
for _, e in Physics.contactEvents(body) do if e.kind == "impact" then print(e.other, e.impulse) end end

_onDisconnect( ) → void

contactEvents(target: (string | entityRef) →

Every collision and contact event kept for `target` since the last call for it, oldest first, each from its own physics step: begin, persist, end, impact, trigger enter and exit, as `Physics.listenContacts` started keeping them. Reading empties the list. nothing is kept for `target`.

argtypedescription
target(string | entityRefThe entity `listenContacts` named, or `nil` for every contact.

examples

for _, e in Physics.contactEvents(ball) do print(e.kind, e.other, e.step) end

contactPeak(target: string | entityRef) →

The hardest hit `target` took since the last call for it: the largest normal impulse one physics step put between it and anything it touched, with who, on which step, how fast the two were closing as that step began, and the surfaces each side is made of where the hit landed. Every step counts, so an impact that began and ended between two reads is still the peak it was. The engine keeps it while anything listens to `target` (`Physics.listenContacts`, `onContact`, `onImpact`, `onTrigger`). Reading starts the next peak afresh. or nil when nothing pushed on it since the last read.

argtypedescription
targetstring | entityRefA listened entity.

examples

Physics.listenContacts(body); local peak = Physics.contactPeak(body); if peak then print(peak.impulse, peak.closingSpeed) end

pumpContactEvents( ) → void

Deliver every collision and contact event the physics steps recorded since the last delivery to the `onContact`, `onImpact` and `onTrigger` listeners and the lists `listenContacts` keeps. The engine calls this after every physics step that recorded any, before that step's `fixedUpdate`, so listeners hear each step's events at the physics rate.

examples

Physics.pumpContactEvents()

contactEventsDropped( ) →

How many contact events the engine let go before anything read them: its queue keeps 4096 between two deliveries, and each target `listenContacts` keeps 1024. Zero when nothing was lost. lists `listenContacts` keeps, since the world started.

examples

local lost = Physics.contactEventsDropped(); if lost.engine > 0 then log.warn("contact events dropped") end

vectorOf(v: any) → vector

argtypedescription
vany

motionSampleFrom(record: any) → PhysicsMotionSample

argtypedescription
recordany

motionKey(id: string, name: string) → string

argtypedescription
idstring
namestring

motionTarget(fname: string, target: string | entityRef, name: string?) → void

argtypedescription
fnamestring
targetstring | entityRef
namestring?

trimMotion(probe: any) → void

Keep the probe's `capacity` newest samples, counting the ones let go.

argtypedescription
probeany

pullMotion(probe: any) → void

Take what the engine recorded for one probe into the probe's own list, which keeps its `capacity` newest samples.

argtypedescription
probeany

probeMotion(target: string | entityRef, opts: PhysicsMotionProbeOptions?) →

Place a motion probe: a measuring point on a body (an accelerometer, a g-force sensor) whose velocity, acceleration, angular velocity and angular acceleration the physics step samples, for `Physics.motionSamples` and `Physics.motionPeak` to read. On a rigid body it measures a point of the body, the rotation terms (centripetal and tangential acceleration) included, at every solver substep: the rate the solver actually steps the body, which rises when the body's island runs extra substeps. A step the solver does not move the body in (asleep, settled) takes one sample. On a soft body it measures a region's particles, their velocity averaged by mass, at the same rate: a hit soft body's extra substeps are each sampled. Each sample also reads the proper acceleration, what a rider or sensor at the point feels (0 g in free fall, 1 g at rest), and its size in g. Use it for g-force readouts, impact severity, crash and hit strength, controller haptics, flight and roller-coaster feel, and telemetry. A body with no probe costs nothing. The probe follows the entity id across a mode switch or a respawn, and each new body it measures (play starting, a respawn) starts its record afresh: the samples, the peak and the clock. It ends when the returned function runs or the component that placed it is removed or its entity destroyed. Placing it again with the same `name` replaces its options and keeps what it recorded. `opts.region` a soft body.

argtypedescription
targetstring | entityRefThe entity whose body to measure: a rigid body, or with
optsPhysicsMotionProbeOptions?`PhysicsMotionProbeOptions`: `{ point?, region?, name?, capacity?, substeps? }`.

examples

local stop = Physics.probeMotion(car, { point = {0, 0.6, -0.3}, name = "seat" })
Physics.probeMotion(ball)
Physics.probeMotion(dummy, { region = { nearest = {0, 0.4, 0} }, name = "head" })

_onDisconnect( ) → void

motionSamples(target: string | entityRef, name: string?) →

Every sample a motion probe took since the last call for it, oldest first, each from the solver substep (or physics step) it was taken in, however many steps ran between two calls: read it once a frame, or from `fixedUpdate`, and nothing is missed. A sample carries the point's velocity, acceleration, proper acceleration (what is felt), g-force, angular velocity and angular acceleration, and its step, time and length. Reading empties the list. `Physics.motionProbe` states the rate the samples are taken at and how many were let go. since the last read or no probe has that target and name.

argtypedescription
targetstring | entityRefThe probed entity.
namestring?The probe's name, when `Physics.probeMotion` gave it one.

examples

for _, s in Physics.motionSamples(car, "seat") do if s.g > 4 then print("hard hit", s.g, s.step) end end
local samples = Physics.motionSamples(ball); local last = samples[#samples]; if last then print(last.acceleration, last.g) end

motionPeak(target: string | entityRef, name: string?) →

The sample with the largest g-force (proper acceleration) a motion probe took since the last call for it: the hardest moment of a crash, a hit or a turn. Every sample counts, whether or not `Physics.motionSamples` read it. Reading starts the next peak afresh. last read or no probe has that target and name.

argtypedescription
targetstring | entityRefThe probed entity.
namestring?The probe's name, when `Physics.probeMotion` gave it one.

examples

local peak = Physics.motionPeak(car, "seat"); if peak and peak.g > 20 then print("severe impact", peak.g) end

motionProbe(target: string | entityRef, name: string?) →

What a motion probe is doing: the rate it samples at (samples per second), the length of its latest sample, how many samples the latest physics step took, how many it keeps and how many wait to be read, how many it let go since it was placed, and whether it is bound to a body (with the reason when it is not: no entity carries the id, or the entity holds no body the probe can measure).

argtypedescription
targetstring | entityRefThe probed entity.
namestring?The probe's name, when `Physics.probeMotion` gave it one.

examples

local info = Physics.motionProbe(car, "seat"); print(info.rate, "samples/s", info.dropped, "dropped")

syncStepListening( ) → void

Step hooks: code that runs with every physics step Tell the engine which sides of the step have a hook to run.

addStepHook(fname: string, signal: any, fn: (number, number) → void

argtypedescription
fnamestring
signalany
fn(number, number

_onDisconnect( ) → void

The hook ends when `off` runs, or when the component that made it is removed or its entity destroyed (a hot reload of the component ends it before the reloaded copy starts).

onBeforeStep(fn: (number, number) →

Call `fn` at the start of every physics step from now on, at the physics tick rate (`physics.tick_rate`), however many steps a frame runs. It runs after the step's force reset and before the step integrates, so a force, torque, impulse or velocity written here acts on this very step, and a read here (a position, a velocity, a raycast) sees the state the step starts from. This is the place for a force that depends on where a body is or how fast it moves: gravity toward a planet, a spring, a thruster holding altitude, buoyancy, a PID controller, an active ragdoll's balance. `applyForce` holds a force over the whole step the way gravity is held; a pull that stands in for gravity (an orbit) or drives an oscillation keeps its energy when it is given as the momentum it makes over the step instead: `Physics.applyImpulse(id, force * dt)`. One engine call runs every hook, so one hook looping over many bodies costs about what the loop costs. Runs while the gameplay clock runs, on every engine that steps the world: under multiplayer push only the bodies this peer simulates. The hook ends when the returned function is called, or when the component that registered it is removed, its entity destroyed or its code reloaded. A hook must not wait (`task.wait`); spawn a task from it for work that does. The engine runs the hooks of the engine thread's VM, so a worker job's call (a `jobs.dispatch` entry) raises, naming the refusal. the `step` the contact events of this step carry.

argtypedescription
fn(number, numberReceives `(dt, step)`: the step's length in seconds and its number,

examples

local off = Physics.onBeforeStep(function(dt) Physics.applyForce(ship, { 0, 9.81 * 500, 0 }) end)
Physics.onBeforeStep(function(dt) local p = entity(moon).position; local r = math.sqrt(p.x * p.x + p.y * p.y + p.z * p.z); local k = -GM * mass * dt / (r * r * r); Physics.applyImpulse(moon, { p.x * k, p.y * k, p.z * k }) end)

onAfterStep(fn: (number, number) →

Call `fn` at the end of every physics step from now on, at the physics tick rate, however many steps a frame runs. It runs once the step has integrated, after that step's collision events reached their listeners (`Physics.onContact`, `onImpact`, `onTrigger`) and before `fixedUpdate`, so a read here sees what this step left: positions, velocities, `Physics.jointReaction`, `Physics.contactPeak`. Use it to sample a trajectory step by step, measure energy, record a replay, or react to a step's result. A force written here acts on the next step. One engine call runs every hook. The hook ends the way an `onBeforeStep` hook ends, and must not wait either.

argtypedescription
fn(number, numberReceives `(dt, step)`: the step's length in seconds and its number.

examples

local samples = {}; local off = Physics.onAfterStep(function(dt, step) table.insert(samples, entity(ball).position.y) end)

runStepHooks(phase: string, dt: number, step: number) → void

Run the step hooks registered for one side of a physics step. The engine calls this with `"before"` at the start of every step and with `"after"` at its end while `Physics.onBeforeStep` or `Physics.onAfterStep` hooks are registered.

argtypedescription
phasestring`"before"` or `"after"`.
dtnumberThe step's length in seconds.
stepnumberThe step's number.

examples

Physics.runStepHooks("before", 1 / 30, 1)

addConstraint(entityId: string | entityRef, opts: table?) → void

Add a transform constraint to an entity.

argtypedescription
entityIdstring | entityRefTarget entity id.
optstable?Optional constraint description (targetEntityId, position, rotation, scale, lookAt, targetPosition, axes, weight).

examples

Physics.addConstraint(id, { targetEntityId = parent, position = true })

removeConstraint(entityId: string | entityRef, index: number?) → void

Remove transform constraints from an entity (if any are present).

argtypedescription
entityIdstring | entityRefTarget entity id.
indexnumber?Optional constraint index (currently ignored — the whole component is removed).

examples

Physics.removeConstraint(id)

colliderOn(entityId: string | entityRef) → string

Which collider component an entity carries, or nil when it carries none.

argtypedescription
entityIdstring | entityRefTarget entity id.

examples

local which = Physics.colliderOn(id)

addCollider(entityId: string | entityRef, component: string, config: table?) → void

Add a collider component to an entity, naming the shape you want.

argtypedescription
entityIdstring | entityRefTarget entity id.
componentstringOne of `Physics.COLLIDER_COMPONENTS`.
configtable?The component's own fields, e.g. `{ radius = 0.5 }` for a sphere.

examples

Physics.addCollider(id, "SphereCollider", { radius = 0.5 })

removeCollider(entityId: string | entityRef) → string

Remove whichever collider component an entity carries.

argtypedescription
entityIdstring | entityRefTarget entity id.

examples

Physics.removeCollider(id)

addWheelCollider(entityId: string | entityRef, config: table?) → void

Add a WheelCollider to an entity. The entity must be a child (or descendant) of a rigid body — the system walks up the hierarchy to find the Physics component. Every wheel under one body is a wheel of that body's ray-cast vehicle.

argtypedescription
entityIdstring | entityRefTarget entity id.
configtable?Optional wheel configuration (`radius?`, `suspensionDistance?`, `springRate?`, `damperRate?`, `targetPosition?`, `maxSuspensionForce?`, `bumpStopRecovery?`, `bumpStopSpeed?`, `groundAngle?`, `motorTorque?`, `brakeTorque?`, `steerAngle?`, `forwardFriction?`, `sidewaysFriction?`, `frictionSlip?`, `sideFrictionStiffness?`, `corneringStiffness?`, `forwardFrictionStiffness?`, `slideGrip?`, `slideSlip?`, `loadSensitivity?`, `referenceLoad?`, `inertia?`, `rollingResistance?`, `width?`, `is2D?`, `visual?`, `solid?`, `mass?`, `breakLoad?`, `attached?`). A `solid` wheel is a volume other bodies strike; a `breakLoad` above 0 lets it come off as a body of its own (`Physics.detachWheel` takes it off on command). An `inertia` above 0 makes the wheel spin on its own (wheelspin, lock-up, drift); the tyre grip curve fields shape its grip over slip and load (`Physics.tyreCurve` measures it, `@builtin::modules.tyres` holds presets).

examples

Physics.addWheelCollider(id, { radius = 0.35, motorTorque = 500 })

removeWheelCollider(entityId: string | entityRef) → void

Remove the WheelCollider component from an entity (if present).

argtypedescription
entityIdstring | entityRefTarget entity id.

examples

Physics.removeWheelCollider(id)

setWheelAttached(entityId: string | entityRef, attached: boolean) → boolean

Write a wheel's `attached`, through its WheelCollider component when it has one, so the change reaches every peer.

argtypedescription
entityIdstring | entityRef
attachedboolean

detachWheel(entityId: string | entityRef) → boolean

Take a wheel off its vehicle: it leaves as a dynamic body of its own from where it stands, moving as it moved and spinning as it spun, with its volume (`solid`) as its collider and its `mass`, and the vehicle drives on the wheels it has left. The wheel entity stays under the chassis in the hierarchy; `Physics.getVelocity`, `applyImpulse` and the contact listeners reach it as any body. A wheel also comes off by itself when its `reaction` passes its `breakLoad`. On a shared world the peer that may write the wheel takes it off for every peer.

argtypedescription
entityIdstring | entityRefThe wheel entity (it carries the WheelCollider).

examples

Physics.detachWheel(wheel.id); print(Physics.getWheelState(wheel.id).detachReason) -- "command"

attachWheel(entityId: string | entityRef) → boolean

Put a wheel that came off back on its vehicle, at its mount: its own body goes, and the vehicle drives on it again from the next physics tick.

argtypedescription
entityIdstring | entityRefThe wheel entity (it carries the WheelCollider).

examples

Physics.attachWheel(wheel.id)

vec3Of(v: any) → vec3

argtypedescription
vany

wheelStateOf(v: any) → table

argtypedescription
vany

getWheelState(entityId: string | entityRef) →

Read a wheel collider's runtime state. Reads the native component the wheel system writes after each physics step.

argtypedescription
entityIdstring | entityRefTarget entity id (must carry a WheelCollider component).

examples

local state = Physics.getWheelState(id)

tyreCurve(entityId: string | entityRef, opts: table?) →

Measure a wheel's tyre grip curve: the force its tyre pushes with at a steady slip, swept over slip ratio (along the road), slip angle (across it) and load, as the wheel's WheelCollider fields state its grip and as its solve settles on at that slip. Tune a tyre by numbers: its peak, where it peaks, how far it falls past the peak, and how its grip per newton falls with load.

argtypedescription
entityIdstring | entityRefThe wheel entity (it carries the WheelCollider).
optstable?Optional `{ loads = { N... }?, slipRatios = { ... }?, slipAngles = { degrees... }?, at = { { slipRatio, slipAngle }... }? }`: the loads to sweep (default the load the wheel carries now, or its `referenceLoad`), the slip ratios (default 0 to 1 by 0.025), the slip angles (default 0 to 30 degrees by 1), and pairs of slips to answer together.

examples

local curve = Physics.tyreCurve(wheel.id); print(curve.loads[1].side.peak.slipAngle, curve.loads[1].side.peak.perLoad)

vehicleState(chassisId: string | entityRef) →

Read a vehicle: the chassis body's forward speed and the state of every wheel under it (the wheels whose nearest rigid-body ancestor is this chassis), and the wheels that came off it.

argtypedescription
chassisIdstring | entityRefThe chassis entity (the rigid body the wheels sit under).

examples

local car = Physics.vehicleState(carId); print(car.speed, car.groundedWheels)

walk(e: any) → void

argtypedescription
eany

shaftNetworkState(entityId: string | entityRef) →

Read a ShaftNetwork (a drivetrain, gearbox, differential, clutch, gear train, winch or other network of rotating parts on shafts) as of the last physics tick: every part's speed and torques and every link's torque, slip and lock, by name. The same reading as the component's `state()`.

argtypedescription
entityIdstring | entityRefThe entity carrying the ShaftNetwork.

examples

local s = Physics.shaftNetworkState(car.id); print(s.parts.engine.rpm, s.links.clutch.slipping)

raycastBetween(fromId: string, toId: string, maxDistance: number?) →

Cast a ray from one entity toward another and return the first hit.

argtypedescription
fromIdstringOrigin entity id.
toIdstringTarget entity id.
maxDistancenumber?Optional distance cap (default 1000).

examples

local hit = Physics.raycastBetween(a, b)

hasLineOfSight(fromId: string, toId: string) →

Check whether two entities have line-of-sight between their origins.

argtypedescription
fromIdstringViewer entity id.
toIdstringTarget entity id.

examples

if Physics.hasLineOfSight(a, b) then ... end
⌬ Types
PhysicsLocks = {PhysicsSleepState = {PhysicsColliderState = {PhysicsContactPoint = {PhysicsContact = {PhysicsJointMotor = {PhysicsJointState = {PhysicsJointLoadPeak = {PhysicsJointReaction = {PhysicsJointReactions = {PhysicsTransformConstraintState = {PhysicsPlaneHold = {PhysicsHeldForce = {PhysicsBodyForces = {PhysicsBodyState = {PhysicsMovingThreshold = {PhysicsStepCost = {PhysicsStepSummary = {PhysicsSoftBodyCost = {PhysicsSoftBodySettings = {PhysicsWorldState = {PhysicsSoftBodyState = {PhysicsSoftBodyStability = {PhysicsSoftStabilityPart = {PhysicsSoftBodyEnergy = {PhysicsSoftMeasureSamples = {PhysicsSoftMeasurement = {PhysicsSoftRegionState = {PhysicsSoftElements = {PhysicsSoftBodyReplication = {PhysicsSoftBodyDiagnostics = {PhysicsDebugObject = {PhysicsDebugLines = {PhysicsSoftPin = {PhysicsSoftParticles = {PhysicsSoftParticlesWrite = {PhysicsPushOptions = {PhysicsSoftAttachment = {PhysicsSoftHit = {PhysicsSoftRegion = {PhysicsSoftBodyCage = {PhysicsSoftBodyRender = {PhysicsDrawnPose = {PhysicsObservation = {PhysicsSurface = {PhysicsSurfaceDefinition = {PhysicsGroundContact = {PhysicsSoftBodyTear = {PhysicsSoftElementBreak = {PhysicsContactEventPoint = {PhysicsContactEvent = {PhysicsContactOptions = {PhysicsContactPeak = {PhysicsMotionSample = {PhysicsMotionProbeOptions = {PhysicsMotionProbeInfo = {

Sub-parts

Everything contained inside this part. Assets are composite children (clickable cards). Files are leaf payloads. Expand any row to view its source.

Showing up to 3 levels deep. Open a part to see what it holds further down.

63+items
·
assettype · born here
❒asset
# Module (asset type) A module is a reusable, stateless (or globally-stateful) Luau library that other code pulls in with `require()`. Modules are the unit of factored-out logic in a world: helpers, math libraries, format parsers, registries, shared algorithms. ## When to use one - You have logic you want to share across multiple components, services, scenes, or tools. - You have a registry, lookup table, or shared cache that callers all read from / write to. - You want a stable API surface (`M.fn`) other code can depend on. If the logic is bound to one entity, use a `.component`. If you want a named UI of fields rather than functions, use a `.preset`. ## Where it lives - Source: `/zero/source/.../<name>.module/` - Identity: the source path with `/` written as `.` and each segment's type suffix dropped — `/zero/source/demo/beats.module` is `demo.beats`, and `/zero/source/kit.package/beats.module` is `kit.beats`, the container's name kept and its `.package` suffix gone. `asset.create` returns this string, `asset.resolve(...).identity` reads it back, and the `require` forms below write it as `<identity>`. - Folder shape: - `init.luau` (or `init.lua`) — module body. **Required.** Returns a table (conventionally named `M`). - `README.md` — instance-level documentation. **Required.** - `.metadata` — agent-editable tags + free-form fields. **Required.** ## How to create one ```luau asset.create("module", "<name>") -- Creates: /zero/source/<name>.module/ -- init.luau (canonical `local M = {} … return M`) -- README.md (instance README template) -- `folder` places it in a subfolder of /source, and that subfolder -- leads the identity: `{ folder = "lib" }` produces `lib.<name>`. -- `into` authors it inside a resolved container (a package, a toolbox), -- whose own identity leads the same way: asset.create("module", "<name>", { folder = "lib" }) asset.create("module", "<name>", { into = asset.resolve("myPkg.package") }) ``` ## How it operates 1. **Registration.** Writing `init.luau` into a `.module/` folder indexes the asset and registers the module path with the resolver. 2. **Loading.** The first `require("<identity>")` runs the file's body and caches the returned table. Subsequent requires from anywhere return the **same table** — this is the shared-state lever for "module-local" registries. The body runs in an environment of the module's own: a name it declares without `local` is readable by the module's own functions and by no other script, so an export reaches its callers through the returned table and nothing else. Requiring a component's folder runs its chunk the same way, once, and its `update`, `start` and `public` stay in that environment; a component runs on an entity through `entity(id).component.add(name)`. 3. **Hot reload.** Editing the file re-runs the module body and folds what it returns into the table already loaded, so that table keeps its identity: a caller that captured it with `require` reads the new source's functions and values through the reference it already holds, and a later `require` returns that same table. A key the new source drops goes away; a key something set at runtime stays. The body's own `local`s start again from their initial values, so state that must outlive an edit lives in `modules.state()` (`guides { path: "core/scripting-and-tasks" }`). 4. **Identity resolution.** A module is reached by its `<identity>`, and where the caller lives decides which spelling of it resolves. For a module in a **world**, from a caller in that same world — another module, a component, a scene entrypoint, or an `execute` chunk: - `require("<identity>")` — the identity on its own, resolved against the caller's own root. It carries every folder segment, so a module created with `{ folder = "demo" }` is `require("demo.beats")`. - `require("@root::<identity>")` — the same root-relative resolution, written out. - `require(".sibling")` — a module in the same folder, by its bare name; `..name` steps up one folder, `...name` two. Logs, stack traces and hot-reload notices name that same module `@local.source.<identity>` — its key under the world source root. The `<identity>` tail of that key is the form above, so a trace reading `@local.source.demo.beats` is `require("demo.beats")`. For a module in a **library** — content under `/zero/source/libs/@<lib>/` — `@<lib>::` addresses that library's root from anywhere: `require("@builtin::modules.transform")`. Mounting a world as a library moves its files under such a root and flips the caller root to `@<lib>::`, which is what keeps the root-relative forms above resolving across the move. ## Discovery - `asset.list("module")` — every registered module. - `asset.inspect("<name>")` — public functions, source path, this type README. - `ls /zero/source/<name>.module` lists the files the folder holds. ## Authoring conventions - Return a single `M` table from `init.luau`. Top-level statements with side effects run on first require — useful for one-time initialization, dangerous if they touch the engine before it's ready. - Write exported functions as `typed function`, not `function`: the argument types are enforced at the call and the checker knows the signature, so a caller's mistake is reported where they made it. - Annotate exported functions with `--!desc` / `--!arg` / `--!return` / `--!example` so the LSP, `tools.list`, and `asset.inspect` surface them. A function with no `--!desc` is reachable only by someone already reading this file. - Declare a VALUE with `Field.<kind>(default, mode, description)`, and a table whose members are reached through a metatable with `--!members <TypeName>` — the latter gives the surface its accepted member set, its type, and its documentation from one table. See `guides { path: "core/authoring" }` for all four rules and `modules/api/engine/entity.module/members.module` for a worked member table. - Keep module state in module-local upvalues or in `modules.state()`. A name the body declares without `local` lives in the module's environment, which every run of the module shares: a function the previous run left in place reads what the reload assigned. Module-locals start again from their initial values with each hot reload; the table `modules.state()` returns is the same table on both sides of every reload. - Prefer focused modules over kitchen-sink modules. If two halves of a module have no shared state, split them. ## Common pitfalls - **Cyclic requires.** A `require` chain that loops will return the partial table (the half built before the cycle was detected). Design for one-way dependencies. - **Engine-time side effects.** Don't `entity.spawn` at module top-level — the engine may not be ready. Expose an `M.init` and call it from a scene entrypoint. - **Hot-reload + module-local cache.** A module that caches expensive computation in upvalues loses that cache on reload — fine for dev, but be aware in performance work. - **`init.lua` vs `init.luau`.** Either works, `.luau` is canonical. - **Writing one while play runs.** A `/source` write made while play is running lands on the play shadow, and a guarded play-exit discards it unless it is kept. One `.module` write shadows `init.luau`, the `README.md` and the `.metadata` together. `vfs.write(path, bytes, { durable = true })` skips the shadow, and `vfs.promotePlayShadow` keeps what is already on it — the `core/vfs` guide has the model and what each route costs. ## Related types - `.component` — for entity-bound state + lifecycle hooks. - `.service` — generates content you don't have yet (a mesh, sound, texture, …) via a metered provider. - `.tool` — for a single agent-callable function with a YAML schema. - `.package` — to group several modules + components + scenes into one shippable folder. ## In the Inspector Exports: what the module exports (name, kind, signature), parsed from its source without running it, with **Check** (the LSP's diagnostics for its entry file) and **Open**.
▲ 0↑ born
▣
module · born here
❒asset
# engine_records The engine's own records: the tables a subsystem keeps as its account of what stands in the running engine, and the classes whose every instance is one. The input maps activated, a signal's handlers and connections, the entity and asset event registries and the renderer's registry of live features are records; each follows whoever holds the thing it records. `declare(t)` makes a table a record, `declareClass(mt)` makes every table carrying that metatable one, and `holds(v)` answers whether a value is a record. `engine.snapshotModuleState` carries a record by reference without walking it, and `engine.restoreModuleState` leaves it as it stands, so what went away since a reading stays away and what arrived stays in place. A leaf with no requires, so a module that loads before the `engine` global exists declares its records as it loads.
▲ 0↑ born
◇
component · born here
❒asset
# Latch A latch point: a place on a body where it latches to a matching point on another body that comes within reach. A trailer hitch takes the coupler of a trailer backed onto it, two train cars couple on contact, a ship docks at a port lined up within an angle, a door catches as it swings shut, a magnet clicks onto a plate, a part snaps into a socket. Public fields: `tag`, `accepts`, `offset`, `radius`, `maxAngle`, `maxSpeed`, `armed`, `lock`, `joint`, `partner` (written by the simulation). Methods: `:release()`, `:onLatch(fn)`, `:onRelease(fn)`, `:latchJoint()`, `:state()`. ## When two points latch The point is a frame: the entity's own frame, moved by `offset`. Put the Latch on the body itself, or on an entity under the body (a marker at the hitch ball, at a coupler, at a port), whose body the point rides on. After every physics step, two points latch when all of these hold: - each `accepts` the other's `tag` (an empty `accepts` latches to points of its own tag, so two train couplers tagged `coupler` latch to each other); - they ride on different bodies, both points are `armed`, and neither is latched; - they stand within the larger of their two `radius` (metres); - the turn that takes one frame onto the other is within the smaller of their two `maxAngle` (degrees; 180 latches turned any way); - they close no faster than the smaller of their positive `maxSpeed` (m/s; 0 latches at any speed). A point near several takes the nearest. The step that makes a latch joins the two with a Joint and the next step holds it. ## The joint a latch makes The Joint is named `latch`, on the entity of the point that makes it, and holds the two frames together: point on point and turned alike. So lay out each point where, and turned as, its partner will stand once joined: a coupler marker on a trailer turned as the hitch marker on the truck is when the trailer stands straight behind it. Its fields come from `joint` (the making point's, else its partner's, else a fixed joint; the making point is the one `onLatch` names as `host`, so state `joint` on one point of a pair): any Joint kind and any Joint field but the anchors and ends the latch states, so a ball leaves the trailer free to swing, a hinge about `axis` leaves one turn free, a fixed joint docks, and `breakForce` / `breakTorque` make a catch that bursts open. It reads like any joint: `:latchJoint()` returns it, and `Physics.jointReaction`, `Physics.jointState` and `Physics.bodyState(id).joints` take it. ## Releasing, breaking, latching again - `:release()` (or `Physics.releaseLatch(id)`) takes the joint off and frees both points. `lock = "permanent"` on either point refuses it: the latch holds until its joint breaks or a point is removed. - Taking the latch's Joint off by hand (`Physics.removeJoint(latch:latchJoint())`) releases the latch too, with reason "release". - A latch joint past its `breakForce` / `breakTorque` frees both points. - Removing a Latch, or its entity, frees its partner on the next step. A freed point latches again once it has stood clear of every point it latches to, so pulling a trailer away and backing it in again hitches it again. `:onLatch(fn)` and `:onRelease(fn)` hear each latch and each release (`reason` "release", "break", "removed" or "refused"); `Physics.onLatch` and `Physics.onUnlatch` hear every latch in the world. ## Refused A Latch refuses, naming the field: an empty `tag`, an `accepts` entry that is not a tag, a negative `radius`, a `maxAngle` outside 0 to 180, a negative `maxSpeed`, a `joint.kind` that is not a name, a `joint` stating `connected`, `target`, `name`, `localAnchor` or `remoteAnchor`, and a second, named Latch on one entity. Added with one of these it does not start; written live, the field keeps the value it held and `:errors()` names why. `:state().problem` names a point with no body at or above it, or on a soft body. A latch whose `joint` the Joint refuses (a kind no Joint has, a rope with no `maxDistance`) is not made: both points are freed and `onRelease` hears reason "refused" with the Joint's `error`. ## Cost, determinism, multiplayer Each step places every latch point on its body and sorts them into a grid of cells as wide as the widest reach, comparing each point with the points of the 27 cells around it: the cost per point per step is one placement, one grid insertion and a comparison with each point within three cells of it, the same however many points stand further away, and a world with no Latch does no work. The widest reach sets the cell for every point, so keep a point's `radius` to the reach it latches at. The pairs are taken nearest first, ties in the order the points' entities were made, so two engines running the same scene latch the same pairs on the same step. The latch is made on the peer that simulates both bodies; its Joint and `partner` reach every peer. A point on a body another peer simulates is that peer's to latch, so two points whose bodies two different peers simulate do not latch. ```luau -- a truck's ball hitch and a trailer's coupler: back the trailer in and it hitches local hitch = entity.spawn("hitch", { parent = truck.id, position = { 0, 0.5, -2.6 } }) hitch.component.add("Latch", { tag = "hitch", accepts = { "coupler" }, radius = 0.15, joint = { kind = "ball" } }) local coupler = entity.spawn("coupler", { parent = trailer.id, position = { 0, 0.5, 2.1 } }) coupler.component.add("Latch", { tag = "coupler", accepts = { "hitch" } }) coupler.component.get("Latch"):onLatch(function(e) print("hitched", e.distance) end) -- release, drive away, back in again: it hitches again coupler.component.get("Latch"):release() -- a door catch that bursts open past 4000 N catch.component.add("Latch", { tag = "catch", radius = 0.05, maxAngle = 5, joint = { kind = "fixed", breakForce = 4000 } }) ```
▲ 0↑ born
◇
component · born here
❒asset
# Physics Adds rigid body dynamics to an entity. Body kind is `"dynamic"` (affected by forces), `"static"` (immovable), `"kinematic"` (placed by script at the pose its transform holds) or `"kinematicVelocity"` (carried by the solver at the velocity script gives it with `Physics.setVelocity`). Both kinematic kinds push dynamic bodies and are not pushed back. Public fields: `kind`, `gravityScale`, `mass`, `linearDamping`, `angularDamping`, `ccd`, `interpolation`, `lockRotationX/Y/Z`, `lockTranslationX/Y/Z`, `dominance`, `canSleep`, `sleepLinearThreshold`, `sleepAngularThreshold`, `centerOfMass`, `inertia`, `softCcd`, `extraSolverIterations`, `extraPgsIterations`. Every field reaches the solver on the next step when written, and `Physics.bodyState(id)` reads each back as the solver holds it. A value outside what a field takes is refused with an error naming the field. `dominance` (-127 to 127) decides who pushes whom between dynamic bodies: a body in a higher group pushes one in a lower group and is not pushed back, the way a player character shoves crates without slowing. Bodies in one group push each other as usual. `canSleep = false` keeps the body simulated every step however slowly it moves (a probe coasting in zero gravity, a vehicle idling at rest); `sleepLinearThreshold` (m/s at the body's farthest point, default 0.05) and `sleepAngularThreshold` (rad/s, default 0.5, for a body with no colliders) set how still it must stay for half a second before it sleeps. `Physics.sleep(id)` puts a body to sleep at once. `centerOfMass` (local, metres) and `inertia` (principal moments, kg·m²) replace the values the colliders give the body; leave them unset to derive them. A car body with `centerOfMass = { 0, -0.5, 0 }` resists the roll that tips it with the derived centre. `softCcd` (metres) predicts contacts that far ahead of the body each step, which catches a fast body before it passes through a thin wall at a fraction of the cost of `ccd`. Set it to about the distance the body travels in one step (speed / tick rate). `extraSolverIterations` and `extraPgsIterations` (0 to 16 each) stiffen one structure without raising the solver world-wide: the island the body is part of (everything jointed to it or touching it) runs the world's `solverIterations` plus the largest extra substeps any of its bodies asks for, and the world's `pgsIterations` plus the largest extra passes. A body held under a heavy load by impulse joints (a light link of a chain holding a heavy block) also asks its island for substeps short enough to hold it stable, which `Physics.bodyState(id).solvedSubsteps` reads. Put the same values on every member of a bridge, a chain or a ragdoll; the island's step costs about that many more substeps, and the rest of the world costs what it did. `ccd` (continuous collision detection) sweeps the body along its motion so it cannot pass through thin geometry between two steps. It is off by default: the sweep runs on every body that travels further than its own thickness in one step — most of a collapsing structure or a debris burst — and it dominates the physics budget when a scene has many such bodies. Turn it on for the individual bodies that would visibly tunnel: bullets, thrown props, a wrecking ball. ```luau entity(id).component.add("Physics", { kind = "dynamic", ccd = true }) ``` A body on an entity under a parent lives in world space. It starts where its entity stands in the world, with the parent's position, rotation and scale applied, and a write to the entity's `position`, `localPosition`, `rotation` or `localRotation` places the body where that write puts the entity, in the same call: a ray cast right after the write meets it there. The one exception is a `kinematic` body while the clock runs: the write aims it, and the next step sweeps it there, carrying the dynamic bodies in its path. While the clock runs, the solver moves a `dynamic` or `kinematicVelocity` body and its parent does not carry it: moving or turning the parent leaves the body where the solver has it, and each step writes the entity's local transform from the body's pose, so the entity stays on the body. A `static` or `kinematic` body goes where its entity goes, its parent's moves included. With the clock held (edit mode, a paused session), every body goes where its entity goes. A change of parent that keeps the entity's local pose (`setParent` or `unparent` with `keepWorldTransform = false`) is a write of that kind: the entity's local pose read under its new parent (or as world, for `unparent`) places its body, every kind of body, whether the clock runs or is held, as a write to its `localPosition` does. The placement stops a `dynamic` body and leaves a `kinematicVelocity` body the velocity it was given; a `kinematic` body while the clock runs is aimed there, as for any write. `keepWorldTransform = true` leaves the entity where it stands in the world, and its body where it is, at the velocity it has. Colliders on the entity's children go with its body. `mass` is the body's total mass in kilograms. At its default of 0 the mass comes from the space the body's solid colliders fill, at 1 kg per cubic metre, so a bigger collider makes a heavier body; a value greater than zero sets the total mass exactly. Either way the mass is spread evenly over that space: where two colliders overlap, the space they share is counted once, so a ball inside a box weighs what the box weighs, and a trigger (`isTrigger = true`) fills no space and adds no mass, inertia or shift of the centre of mass. A body's colliders are the ones on its entity and on every entity beneath it that carries no `Physics` of its own, whatever order the components were added in: a collider added to a child before its parent got `Physics`, or a child moved under the body later, joins the body, and a child moved out from under it, or whose body's `Physics` is removed, stands alone as static geometry. The body's mass, centre of mass and inertia come from the shapes, poses and sizes of those colliders (a `mass` above zero is spread over them), so a car built from a chassis and child parts rolls and pitches the way its parts are laid out. `Physics.bodyState(id).colliders` lists them. A body whose entity holds no collider is given a stand-in box: one fitted to the entity's model, or a 1 m box (half extents 0.5) when it renders none. It collides with everything and `Physics.bodyState(id).colliders` lists it. A collider component added to the entity replaces it, and the first solid collider (one that is no trigger) on an entity beneath the body takes its place as it joins the body, in the same frame when both are added together. A body whose colliders beneath it are still waiting for their mesh, or sit on an inactive entity, rests on the stand-in until one of them is built. The stand-in is given as the body is built: a built body whose last collider is removed or deactivated, or moves out from under it, holds no collider until another one joins it. Methods: `:applyForce(x, y, z)`, `:applyImpulse(x, y, z)`, `:applyTorque(x, y, z)`, `:setVelocity(x, y, z)`, `:addVelocity(dx, dy, dz)`. ```luau entity(id).component.add("Physics", { kind = "dynamic" }) entity(id).component.get("Physics"):applyImpulse(5, 0, 0) ```
▲ 0↑ born
◇
component · born here
❒asset
# Joint Connects two bodies with a joint constraint: the hinges, pins, ropes, springs and sliders that mechanisms and structures are made of, from a door, a chain or a ragdoll to a bridge, a truss or a tower that bends, shows its stress and breaks under load. Each end is a rigid body (an entity with `Physics`) or a soft body (an entity with `SoftBody`). The engine solves joints inside its physics step, measures the load each one carries (tension or compression along a member, shear, bending; `Physics.jointReaction` / `Physics.jointReactions` read it) and breaks one when that load passes its `breakForce` / `breakTorque` (`Physics.onJointBreak` reports it), so a structure of members pinned at shared nodes bends, reports where it is overloaded and collapses inside the engine's own step. Joint kinds: `"fixed"`, `"hinge"`, `"ball"`, `"prismatic"`, `"spring"`, `"rope"`, `"generic"`, `"rail"`. Two bodies that join on their own when matching points come within reach (a trailer hitch, train couplers, a docking port, a door catch) take a `Latch` on each point: the step makes the Joint the Latch states and frees it on a release or a break. Public fields: `kind`, `connected`, `localAnchorX/Y/Z`, `remoteAnchorX/Y/Z`, `axisX/Y/Z`, `remoteAxisX/Y/Z` (`remoteAxis`), `collideConnected`, `limited`, `limitMin`, `limitMax` (`minAngle`, `maxAngle`), `swingLimit`, `twistLimit`, `motorMode`, `motorTarget`, `motorVelocity`, `motorStiffness`, `motorDamping`, `motorMaxForce`, `motorModel`, `lockedAxes`, `axisLimits`, `axisMotors`, `stiffness`, `damping`, `restLength`, `maxDistance`, `yieldForce`, `yieldTorque`, `reelSpeed`, `breakForce`, `breakTorque`, `region`, `remoteRegion`, and a rail's `path`, `closed`, `ends`, `curve`, `tolerance`, `friction`. `connected` is the other body: write the entity or its id, and it reads back as the entity; a name written into it is kept as written and found when the joint is built. It is an entity reference, so a Joint a scene's `build.luau` writes between two entities the build spawns (`connected = post` or `connected = post.id`) names the entity the build placed, through every rebuild, save, load and play. ```luau -- scenes/main.scene/build.luau: a plank bridge, each plank hinged to the one before function content() local prev = entity.spawn("bank", { position = { 0, 2, 0 } }) prev.component.add("Physics", { kind = "static" }) prev.component.add("BoxCollider", { half = { 0.5, 0.25, 1 } }) for i = 1, 10 do local plank = entity.spawn("plank" .. i, { position = { i, 2, 0 } }) plank.component.add("Physics", { mass = 2 }) plank.component.add("BoxCollider", { half = { 0.45, 0.05, 1 } }) plank.component.add("Joint", { connected = prev, kind = "hinge", axisZ = 1, axisY = 0, localAnchorX = -0.5, remoteAnchorX = 0.5 }) prev = plank end end ``` Methods: `:setMotor(targetVelocity, maxForce)`, `:onBreak(fn)`, `:isBroken()`, `:breakEvent()`, `:reattach()`, `:state()`, `:reaction()`, `:jointEntityId()`. ## Several joints on one body (trusses, hands, two-handed holds) A body takes any number of joints. The first `Joint` on an entity has no name; add each further one under a `name` of its own, or with `Physics.addJoint`, which names it (`joint2`, `joint3`, ...) and returns it. Each is its own solver joint: its own kind, anchors, limits, motor, break thresholds, reaction, state, break record and removal. A `Joint` on an entity that is no body itself (a marker parented under a beam's end, a hand under an arm) joins the nearest body above it, at that entity's position and orientation, with its anchor and axis measured in the entity's own frame. `connected` may name such an entity too, so two beams are pinned end to end through a marker on each. A joint that cannot be built says why in `:errors()`: an end with no body at or above it (a collider with no `Physics` is static geometry: give it `Physics { kind = "static" }` to join a joint to it), a `connected` id no entity carries, or both ends on one body. ```luau -- a beam pinned at both ends beam.component.add("Joint", { connected = leftPost.id, kind = "hinge", axisZ = 1, axisY = 0, localAnchorX = -2 }) beam.component.add("Joint", { name = "right", connected = rightPost.id, kind = "hinge", axisZ = 1, axisY = 0, localAnchorX = 2 }) -- a hand holding a crate on top of the arm joint the hand already carries local grab = Physics.addJoint(hand, crate, { kind = "fixed", breakForce = 2000 }) Physics.jointReaction(grab) -- this joint's load alone Physics.removeJoint(grab) -- let go; the arm joint stays ``` `Physics.jointState`, `Physics.jointReaction`, `Physics.setJointMotor` and `Physics.removeJoint` take the Joint itself, or an entity and the Joint's name. A break record's `entityId` and `joint` name the entity and the Joint that broke, and `Physics.bodyState(id).joints` lists each joint a body is in the same way. `:reaction()` reads the joint's load (its stress) the way a structure is read: `axial` along the member at this body's end (tension positive, compression negative), `connectedAxial` at the other body's, `shear`, `bending`, `torsion`, a rope's or spring's `tension`, and `load`, the share of `breakForce` / `breakTorque` it stands at. `Physics.jointReactions(joints)` reads a whole structure's joints in one call, and `Physics.listenJointLoads(joints)` keeps each joint's peak between two reads; the physics guide's "Reading a joint's load" covers both, with a stress-colouring recipe. ## Joint frames, limits and motors (doors, ragdoll joints, sliders, 6DOF) Each body carries a joint frame at its anchor, its X axis along `axis` (this body) or `remoteAxis` (the connected body; zero takes `axis`). `linX` / `linY` / `linZ` are travel along the frame's axes and `angX` / `angY` / `angZ` turns about them; zero is where the two frames coincide. The frame's Y and Z are the body's own carried by the shortest turn taking its X onto `axis` (`axis = {0, 1, 0}` puts the frame's Y along the body's -X). An axis reads positive as this body travels along it or turns right-handed about it, relative to the connected body. - **Hinge range**: `limitMin` / `limitMax` in degrees (a prismatic's travel in metres). Writing either turns `limited` on. - **Ball cone**: `swingLimit` is the half-angle in degrees the axis swings inside, `twistLimit` how far it twists either way; negative (the default) leaves each free. - **Any axis**: `axisLimits = { angZ = {-30, 30}, linY = { min = 0, max = 0.5 } }`. - **Motor**: `motorMode = "velocity"` holds `motorVelocity` (rad/s or m/s); `motorMode = "position"` pulls toward `motorTarget` (degrees or metres) with `motorStiffness` / `motorDamping`; neither applies more than `motorMaxForce` (0 uncapped). It drives a hinge's angle, a prismatic's travel, each angle of a ball joint and every free axis of a generic joint; `axisMotors = { angX = { mode = "velocity", velocity = 2, maxForce = 50 } }` drives single axes. `:setMotor(v, maxForce)` and `Physics.setJointMotor` set the same fields. - **Contacts**: `collideConnected = false` stops the two bodies colliding with each other (limbs, links, parts overlapping at the joint). - **Generic**: `kind = "generic"` holds the axes `lockedAxes` names (`{ "linX", "linZ", "angX", "angY", "angZ" }` leaves a slider along `linY`). Every field is live: write it on the running joint and the next step uses it. `Physics.jointState(id)` reads the angle, travel, swing and twist, velocity, `atLimit`, and the force the limit and motor applied. ```luau -- a door that opens 0 to 110 degrees, closed by a capped motor door.component.add("Joint", { connected = frame.id, kind = "hinge", axis = {0, 1, 0}, limitMin = 0, limitMax = 110 }) local joint = door.component.get("Joint") joint.motorMode = "position"; joint.motorTarget = 0; joint.motorMaxForce = 50 -- a shoulder on a cone that does not collide with the torso arm.component.add("Joint", { connected = torso.id, kind = "ball", swingLimit = 70, twistLimit = 30, collideConnected = false }) ``` ```luau entity(id).component.add("Joint", { connected = frameEntityId, kind = "hinge", axis = {0, 1, 0}, }) ``` ## Springs: `stiffness`, `damping`, `restLength` A `"spring"` joint pulls its two anchors toward `restLength` metres apart with `stiffness` (newtons per metre of stretch) and resists the speed its length changes at with `damping`. Left out (the fields read `-1`, the kind's own), `stiffness` is 100 and `damping` 10, and `restLength` is the distance the anchors stood at when the joint was built. Writing `restLength` on the live joint moves where it settles, and writing a negative one keeps the length it rests at. A hinge, ball, prismatic or generic joint moves freely about its axes unless a limit or a motor holds it: its `stiffness` and `damping` default to none (the fields read `-1`, the kind's own). Set on one with no `motorMode`, they are a spring pulling each of its axes (a hinge's angle, a prismatic's travel, each angle of a ball joint, every free axis of a generic joint) back to where its frames align, read per unit of acceleration. A `motorMode = "position"` motor with `motorTarget` pulls toward any other position. ```luau -- a bungee: two bodies held 5 m apart by a soft spring a.component.add("Joint", { connected = b.id, kind = "spring", restLength = 5, stiffness = 200, damping = 20 }) -- a self-closing door: a hinge with a spring back to its closed angle door.component.add("Joint", { connected = frame.id, kind = "hinge", axis = {0, 1, 0}, stiffness = 20, damping = 4 }) ``` A `"rope"` joint is a maximum-distance limit solved inside the physics step: the bodies move freely while the anchors are closer than `maxDistance` (slack rope) and are held from separating beyond it (taut rope). It requires `maxDistance > 0`, and `maxDistance` is live: writing it on the running joint retunes the limit in place. Without a `yieldForce` the rope holds at any force: lengthening it lets the load drop, and shortening it reels any load in at the solver's correction speed (3 m/s), however heavy. A rope given a `yieldForce` winds in at its `reelSpeed`, pulling with at most that force. ## Giving way and holding again: `yieldForce`, `yieldTorque` `yieldForce` (newtons) is the most force a joint holds its travel with, and `yieldTorque` (newton-metres) its angles. While the load needs more, the joint gives way at exactly that force or torque; once the load falls below it, the joint holds again wherever it then stands. It keeps working throughout: only `breakForce` / `breakTorque` break a joint. 0 (the default) holds without bound. - **Rope** (`yieldForce`): pays out. `maxDistance` grows to the length the rope gave way to and reads back as it stands, so the rope holds the load from there once it is light enough. Writing a shorter `maxDistance` winds the load in at `reelSpeed` (metres per second, 1 by default), slowing to arrive, pulling with at most `yieldForce` (a winch with a slip clutch, a tow rope taken up): it gains the full shortening when its load is below the yield, and pays out instead, holding from where it went, when the load is above it. A shock load (a body falling onto the rope) pays out as it brakes. - **Prismatic** (`yieldForce`), **hinge** (`yieldTorque`), **ball** (`yieldTorque`), **generic** (`yieldForce` on its free travels, `yieldTorque` on its free angles): the axes hold still below the yield and slide or turn at it above (a friction slider, a breakaway barrier, a slip clutch on a drum, a stiff hinge). The axes take one of a yield, a motor or a `stiffness` spring; a motor capped by `motorMaxForce` is the yield that drives somewhere. `:state()` (`Physics.jointState`) reads `slipping`, true while the joint gave way over the last step, and a rope's `length`; `:reaction()` reads the force it carries, which stands at the yield while it slips. A rope's payout is stated on its carrying entity as the `joint.length` named value too. A negative yield, or a `reelSpeed` of 0 or less, is refused naming the field: `Physics.addJoint` raises it, and a live write keeps the value the joint holds and reports it in `:errors()`. ```luau -- a winch rope that holds 3000 N: a heavier load pays it out, a lighter one is reeled in local rope = Physics.addJoint(hook, load, { kind = "rope", maxDistance = 4, yieldForce = 3000 }) rope.maxDistance = Physics.jointState(rope).length - 1 -- reel in a metre print(Physics.jointState(rope).slipping, Physics.jointReaction(rope).tension) -- a crash barrier that holds a 20 kN push and slides at it above Physics.addJoint(barrier, post, { kind = "prismatic", axis = {1, 0, 0}, yieldForce = 20000 }) ``` ```luau entity(ballId).component.add("Joint", { connected = hookEntityId, kind = "rope", maxDistance = 8, }) ``` A soft body end is anchored on the body as a whole (its frame, the rigid motion that best fits its particles), or on a region of its particles: `region` for this entity, `remoteRegion` for the connected one, each `{ box = { min, max } }` (every particle between the corners) or `{ nearest = point }` (the one particle nearest the point), in the entity's unit box (-0.5 to 0.5 on each axis) unless `space = "world"`. A region end's anchor is measured from the centre of its particles. Motors, `breakForce` / `breakTorque` and `Physics.jointReaction` work the same at either kind of end, and the joint is removed with either body. ```luau -- a soft punching bag hung by its top particle from a fixed hook bag.component.add("Joint", { connected = hook.id, kind = "ball", region = { nearest = { 0, 0.5, 0 } } }) -- two jellies held face to face, breaking under 200 N a.component.add("Joint", { connected = b.id, kind = "fixed", breakForce = 200, region = { box = { min = { 0.4, -0.5, -0.5 }, max = { 0.5, 0.5, 0.5 } } }, remoteRegion = { box = { min = { -0.5, -0.5, -0.5 }, max = { -0.4, 0.5, 0.5 } } }, }) ``` A hinge's turn can be a part of a `ShaftNetwork`: `{ name = "drum", joint = drumEntity }` couples it to motors, gears, clutches, brakes and other hinges (a winch, a crane's slew, a geared contraption, a propeller on a shaft), the network's torque acting on the joint's body about its axis and, opposite, on the connected body. The `ShaftNetwork` component README has the fields. ## Rails: a point held to a path (tracks, coasters, zip lines, sliding doors) `kind = "rail"` holds the point at this body's anchor (`localAnchor`) to `path` on the connected body: free to move along the path under gravity, contacts, forces and its motor, held across it. A rollercoaster car on its track, a train on its line, a trolley on a zip line, a door on a curved track, a bead on a wire, a camera dolly. - **The path**: `path` is the points it runs through, `{ {x, y, z}, ... }` in the connected entity's local space, so a path on a moving body moves with it (at least 2 points; 3 for a loop). A spline from `modules.spline` is taken as it is, its `closed` with it. `curve = "smooth"` (the default) runs a smooth curve through the points; `"linear"` straight runs between them. - **Ends**: `closed = true` makes the path a loop. An open path's ends are `ends = "capped"` (the default: the point stops at them) or `"open"` (the point runs off, the rail lets go of it, and `state().onPath` reads false with `left` naming the end). `:reattach()` takes a point that ran off back onto the path's nearest point: move the body back to the path first. - **Held**: the point stands on the path to within the solver's precision, through bends and loops at speed; a point found more than `tolerance` metres (default 0.01) off it when a step begins is put back on it. A frictionless rail does no work: a cart keeps its energy round a loop. A soft body (`SoftBody`) is held by the particles `region` names (`{ nearest = point }` for one), through the body's own give: under load they stand off the path by as much as the body stretches there. - **Driven**: `motorMode = "velocity"` holds `motorVelocity` m/s along the path (positive toward its end), `motorMode = "position"` brings the point to `motorTarget` metres along it with `motorStiffness` / `motorDamping`; neither pushes harder than `motorMaxForce` newtons (0 uncapped). `:setMotor(speed, maxForce)` sets a velocity motor. `friction` is a coefficient on the force holding the point to the path. - **Refused**: a path that cannot be held (fewer points than the path needs, two consecutive points together, a point that is no position), a `tolerance` of 0 or less, a negative `friction`, or a field another kind takes (`stiffness`, `damping`, `restLength`, `maxDistance`, `limitMin` / `limitMax`, `swingLimit` / `twistLimit`, `lockedAxes`, `axisLimits`, `axisMotors`, `yieldForce`, `yieldTorque`) is refused by name, as for every joint kind: `Physics.addJoint` raises the reason and takes the Joint off the entity, and a Joint added as a component stands down with `lifecycle` "failed" and the reason as its `disabledReason`. - **Read**: `:state()` (`Physics.jointState`) reads `progress` (metres from the path's start), `speed`, `length`, `closed`, `laps` (times round a loop), `onPath`, `left`, `atEnd` ("start" / "end" while a capped end holds the point), `offset` (metres off the path), `railMotorForce`, `frictionForce`, `tangent`, `normal` and `curvature`. `:reaction()` reads the force holding the point, with `localForce` along the path (x), toward the bend's centre (y) and across (z). `breakForce` releases the rail above that force, with the break event every joint sends. ```luau -- a coaster car on a looping track car.component.add("Joint", { connected = track.id, kind = "rail", path = trackPoints, closed = true, collideConnected = false }) local s = car.component.get("Joint"):state() print(s.progress, s.speed, s.laps) -- a zip line: the trolley's point 1 m above its centre, stopped at the far end Physics.addJoint(trolley, cable, { kind = "rail", path = { {0, 12, 0}, {15, 6, 0}, {30, 3, 0} }, localAnchor = {0, 1, 0}, friction = 0.02 }) -- a sliding door on a curved track, driven open by a capped motor Physics.addJoint(door, frame, { kind = "rail", path = arcPoints, motorMode = "position", motorTarget = 1.2, motorMaxForce = 300 }) ```
▲ 0↑ born
▣
module · born here
❒asset
# signal Event primitive. A producer holds a `Signal`; consumers attach handlers with `:Connect` and the producer invokes them with `:Fire(...)`. ```lua local Signal = require("@builtin::modules.signal") local hit = Signal.new() local conn = hit:Connect(function(dmg) print("hit for", dmg) end) hit:Fire(10) -- runs every handler with (10) conn:Disconnect() -- detach this handler ``` ## API - `Signal.new() -> Signal` - `signal:Connect(fn) -> Connection` — attach a handler; runs on each `:Fire` in attachment order. - `signal:Once(fn) -> Connection` — fire at most once, then self-disconnect. - `signal:Wait() -> ...` — yield the calling coroutine until the next `:Fire`, returning its arguments. Call from inside a coroutine (e.g. a `task.spawn` body). - `signal:Fire(...)` — invoke every handler with the arguments. A handler that raises is caught and logged; the rest still run. - `signal:DisconnectAll()` — detach every handler. - `connection:Disconnect()` — detach one handler (idempotent). - `connection.Connected` — boolean, false once disconnected. Handlers run synchronously and must not yield. The connection list is snapshotted before a fire, so a handler may disconnect itself or others mid-fire without skipping a handler. ## Auto-cleanup A connection made while a script component is on the call stack is tagged with that component instance and its entity, and it ends with whichever goes first: - Removing the component from its entity (`component.remove`), or hot-reloading it, disconnects every connection the instance made. - Destroying the entity disconnects every connection it sourced, after the entity's `onDestroyed` fires, so a component's handler on its own entity's `onDestroyed` still runs after the component's `onDestroy` (driven by the entity-destroy dispatch in `entity_signals.module`). A component never has to track and tear down its own connections.
▲ 0↑ born
◇
component · born here
❒asset
# CollisionGroup Sets collision group membership and filter masks on an entity's physics colliders using a bitmask. Two colliders collide only when `(a.membership & b.filter) ~= 0` AND `(b.membership & a.filter) ~= 0`. Public fields: `membership` (default `0xFFFFFFFF`), `filter` (default `0xFFFFFFFF`). Methods: `setGroups(membership, filter)`, `ignoreEntity(entityId, ignore?)`. ```luau entity(id).component.add("CollisionGroup", { membership = 1, filter = 3 }) ```
▲ 0↑ born
◇
component · born here
❒asset
# SoftBody Makes an entity a deformable body: a jelly, a cushion, a balloon, a cloth, a soft version of the entity's own model, or a shell that crumples and keeps the dent, like a car body after a crash. The body is a set of particles held together by elastic elements, simulated in the same step as rigid bodies, so it rests on and pushes rigid bodies, rigid bodies rest on, bounce off and dent it, and soft bodies collide with each other. A soft body is its own body and its own collision surface: it goes on an entity with no `Physics` and no collider component, and whichever is added second is refused with an error naming the conflict (logged, and readable as the refused component's `disabledReason`). The body fills the entity's unit box (-0.5 to 0.5 on each axis) times its world scale, so it sits where a default cube or sphere primitive of that scale would. `shape = "mesh"` instead fills every closed part of the entity's model with tetrahedra of `cellSize`, and the model is drawn carried by them; a model with no closed part, or a cell size past the 60000-cell cap, is refused with the reason and the fields that change it. While the simulation runs, the entity's position and rotation follow the body as a whole, and a `Model` on the entity moves with it; the deformed surface is drawn by the physics view (`capture` with `pass = "physics"`) with the body's elements over it coloured by load and its pinned and attached particles marked, the same lines `Physics.debugLines` returns and the edit-mode collider overlay draws, and read by `Physics.softBodyState` (its `diagnostics` count inverted cells, self-crossings, loaded elements, pinned and attached particles). Public fields: `shape` (`"box"`, `"sphere"`, `"balloon"`, `"cloth"`, `"mesh"`, `"custom"`, `"rope"`), `cellSize` (for `mesh`: the cells' edge in metres, 0 takes the model's longest extent divided by `resolution`), `collideWith` (for `mesh`: `"cage"`, the cells' boundary, or `"surface"`, the model's own surface), `resolution` (particles along the longest edge, 2 to 24), `mass` (kg; the default 0 weighs it at 1 kg per cubic metre of its shape, like a rigid body), `stiffness` (Young's modulus in pascals for a box or sphere, default 300; spring stiffness for a balloon or cloth), `damping` (0 rings on, 1 settles without overshoot), `model` (a solid's cells: `"corotational"`, the default, `"neoHookean"` or the cheap `"volume"`), `solver` (`"constraints"`, the default, or `"fem"` for stiff materials, below), `poisson` (Poisson's ratio, 0 up to 0.5), `plasticYield` (the strain past which a dent stays; 0, the default, is fully elastic), `plasticCreep` (how fast per second the strain past the yield sets, default 10), `plasticMax` (the most permanent strain a part takes, default 0.5), `inflation` (the share of its built volume a closed shape is held at), `shapeMatching` (hertz of the pull back toward the body's rest shape as a whole, 0 for none), `selfContact` (whether the surface collides with itself), `repairs`, `preserveVolume`, `friction`, `restitution`, `collisionMemberships`, `collisionFilter`, `canSleep`, `attachments`, `pins`, the tear fields `tearStrain`, `tearForce`, `tearSmoothing`, `interiorToughness`, `maxTearsPerStep`, `minPiece` and `piece`, for a `custom` body `particles`, `elements`, `cells`, `triangles` and `particleRadius` (below), for a `rope` `from`, `to`, `length`, `segments`, `thickness`, `stretchStiffness`, `bendStiffness` and `breakForce` (below), and for any body `regions` and `plane` (below). The material (`stiffness`, `damping`, `poisson`, the plastic fields, `inflation`, `shapeMatching`, `preserveVolume`, `friction`, `restitution`, the collision groups), the `solver` and `repairs` take effect on the running body, waking it. Writing `shape`, `resolution`, `cellSize`, `collideWith`, `mass`, `model`, `selfContact` or `canSleep` rebuilds the body; in play mode a rebuild of the same particles (a new `model`, `mass` or `selfContact`, or the entity moved while the clock is paused) keeps the deformation that stayed, and one while the simulation runs keeps every particle where it is and how it moves. A reload of this component's code keeps the body as it stands: the reloaded component takes it over, dents, motion and pins included. **Permanent deformation.** With `plasticYield` above 0, a part of the body strained further than the yield flows toward the shape it is held in, so a dent, a crumple or a crease stays once the load is gone: a car shell that keeps its crash, clay that keeps a print, a sheet that keeps a fold. `Physics.softBodyState(id).plastic` reads how deep it is, in metres; `:repair()` (or `Physics.repairSoftBody(id)`) restores the shape the body was built in, the body put back in it where it stands and moving on as it moved. Leaving play for edit mode puts the body back in that shape too. **Writing particles.** `Physics.softParticles(id, region?)` reads a body's particles (`indices` from 0, world `positions`, `velocities` and `restPositions`, where each stands in the rest shape) and `Physics.setSoftParticles(id, particles)` writes them, the read taken back as it is: a rewind, a replay, a saved damaged object, a level that starts with something bent, a network correction, one dent pushed out. `positions` and `velocities` move the particles and the body springs back toward its rest shape from there; `restPositions` changes the rest shape, the permanent part of it (a read's `restPositions` are where each particle rests, which a crumple's elements pull away from, so to keep the shape a body stands in after a crash write its `positions` as `restPositions`), which stays once the body settles the way a dent past `plasticYield` stays (`plastic` reads it, `:repair()` undoes it). `indices` names the particles written, every particle in order without it. The write applies at once: a read straight after sees it, the next step simulates from it, and from `Physics.onBeforeStep` it is the state that step starts from. Positions are written before the rest places, which are measured through the frame the written positions give; each element takes the rest shape its particles' places give it, which can differ from the one a crumple's elements flowed to, so a deep crumple written back keeps its dent and settles a little way from the written shape, into it or out of it. Rest places that state the shape the body was built in (a read taken before its first dent) put that shape back exactly, the way `:repair()` does, so a rewind to before a crash replays it the same way every time. A write that places every particle (a whole read written back) is the whole state the body steps on from, so two rewinds to one read fall the same way, and the frame after any write draws the body where it was written, paused or not. A pinned particle stands where it is written, held there by its pin whatever velocity is written to it. A rewind starts from the read alone, while the run the read was taken from carried on with what the solver had built up, so the two can part by rounding where a hit amplifies it (a box balancing on an edge); writing the read back the moment it is taken (from `Physics.onBeforeStep`) makes that run a replay of it too. Each element of a crumple keeps a flow of its own that a read's rest places do not carry: written back over the body while it still holds the read's dent, a read leaves those elements as they are, and over any other state it gives each element the rest its particles' places give, so a body read with a deep crumple steps on from the two a little apart. **Stiff materials.** The default solver (`solver = "constraints"`) sweeps the body's elements with its contacts a few times a substep, which leaves a stiff body (`stiffness` 1e6 and up: a beam, a chassis rail, a stiff panel) with more give than its material has, and past a point flying apart. `solver = "fem"` solves the whole body's elasticity at once each substep, so a 2 m beam of `stiffness` 1e8 held by one end stands out within 3 cm of straight on it where it swings from its pin on the default solver. Contacts, `attachments`, `pins`, plasticity, tearing and cutting all work on it, a `Joint` on one of its regions is answered through the whole body, and `Physics.softBodyState(id).solver` reads which solver the body runs on. It costs more per step, most for a body resting on many contacts (a resolution-6 box on the ground about 5 to 6 ms on native against 1 to 1.5 ms), so keep it for the parts that need it. The physics guide's "Stiff materials: the FEM solver" has the measured costs and the world settings that tune it (`Physics.softBodySettings`: `femMaxDenseDofs`, `femMaxIterations`, `femTolerance`). **Tearing and cutting.** With `tearStrain` (a stretch, as a share of an element's rest length) or `tearForce` (a pull in newtons) above 0, the body tears where it is loaded past it: a cloth rips, a net gives under a heavy ball, a panel comes off a car that hits a wall. `Physics.cutSoftBody(id, { point = p, normal = n })` cuts it along a plane (or `{ a, b, c }`, a world-space blade triangle), and `Physics.tearSoftBody(id, region)` tears it at a region, both in play mode. The torn entity keeps the largest piece, and every piece split off becomes an entity of its own, a copy of the torn one without its children, standing at the root of the scene so it flies free of whatever the torn one hangs from, carrying this component with the same fields, its share of the model, the material, and the velocity, dents and pins that fell on its side; its `piece` field names the piece its body is. `Physics.onSoftBodyTear(fn)` hears each tear with the torn entity, the pieces' entities, where and why. A piece is play state: left out of every save, and leaving play takes it away and gives the torn entity back its whole body. `tearSmoothing` averages the load over time before the test, `interiorToughness` makes the inside of the body harder to tear than its surface, `maxTearsPerStep` bounds how many edges tear in one step, and `minPiece` is the smallest piece a tear splits off. The tear fields take effect on the running body. **A body authored particle by particle (`shape = "custom"`).** A truss, a bridge deck, a crane, a cable net, a soft robot, a car frame of nodes and beams: list the particles and link them with elements of their own. `particles` is a list of `{ position = { x, y, z }, mass = kg }` (or just positions) in the entity's local space, metres before its scale; `elements` a list of `{ a, b, kind = ..., ... }` linking particles `a` and `b` by their number in that list (from 1). An element's `kind` is `"rod"` (the default: it holds its length against a pull and a push), `"cable"` (a pull only: it goes slack when its ends close in), `"strut"` (a push only), `"spring"` or `"actuator"` (a rod whose length is driven). Each takes its own law in SI units, 0 meaning none: `stiffness` (newtons per metre; 0 holds the element as stiff as the solver holds anything), `damping` (newton-seconds per metre, damping its own spring, so it needs a `stiffness`), `maxForce` (it gives way at this force and springs back once the load drops), `yieldForce` (past this force it stays bent: it carries the yield force while its length flows to where the load puts it, up to `plasticMax` of its length squeezed and `plasticMaxStretch` stretched, then holds again where it stands (a hit fast enough to carry it past that bound within one physics substep can leave it set a little past it); it gives way as fast as the load moves its ends, and `plasticCreep` does not pace it; a load it cannot carry takes its ends to that bound, where it stops with a jolt its `breakForce` has to carry as well as the standing load: a member held rigid stops within one substep, at several times that load), `breakForce` (it breaks under this pull or push), `breakStrain` (it breaks stretched past this share of its length), `group` (a name `regions` select it by and its breaks report), `breakGroup` (when one element of the group breaks, every element of it breaks in the same step), `collide` (rigid and soft bodies hit it as a segment of `particleRadius` and push its two particles; true by default) and, for an actuator, `targetLength` and `speed` (metres, metres per second). `cells` (tetrahedra, `{ a, b, c, d }`) give it solid material of the body's `stiffness` and `poisson`, and `triangles` (`{ a, b, c }`) a surface other bodies collide with: a deck a wheel drives on. Pins and attachments hold its particles as they hold any body's, `{ nearest = point }` naming one particle; `plane = { normal, point }` puts the whole body on a plane and keeps it there, the way a side-on bridge stays flat (a body built flat in the plane: a solid held to one is pressed flat into it). A structure carrying a load heavy against its particles (a vehicle on a bridge) holds its shape on `solver = "fem"`; the default solver carries such a load along a chain of members only slowly, and the structure sags (the physics guide's "Structures from particles and elements" has the numbers). `Physics.softElements(id)` (or `:elementStates()`) reads every element's force (newtons, positive pulling and negative pushing), strain, length, rest length, permanent set, load against its break limit, whether it broke and where its two ends stand (`endA`, `endB`, world space), all in one call; `Physics.driveSoftElements(id, { [n] = length }, { speed })` (or `:drive`) drives element lengths, a ram or a muscle. A break removes the element whole, its particles staying; a part it disconnects becomes a piece of its own, and `Physics.onSoftBodyTear` hears each break with the broken elements in `elements` (`index`, `group`, `breakGroup`, `force`, `load`; the element whose own load broke it first) and the physics `step` it broke in. The element laws apply to the running body; the particles and the list of links rebuild it. A model on the entity is carried by the cells or the surface triangles; a body of links alone has neither, and is drawn as its elements: each element a round tube of its `thickness` (0 takes twice `particleRadius`) with the entity's material, a ball where three or more meet, carried by the particles every frame. An element listed `hidden = true` is left out of the drawing (a brace or a bending spring that is not seen), and an element that breaks stops being drawn. `Physics.softBodyState(id).render` reads `drawnAs = "elements"` and how many `elements` it draws. After a break, the read of the body's entity and the read of each piece's are the same, every element wherever the break left it, so one read covers the whole structure. A piece a break splits off is a copy of the entity, its other components included, so a component that drives the structure runs once by checking that the `SoftBody`'s `piece` is empty. **A rope or a cable (`shape = "rope"`).** A tow line, a climbing rope, a power line, a grapple rope, a bridge's cable stays: `from` and `to` are its ends in the entity's local space, `length` its length (0 takes the distance between them, a rope built taut; a longer one is built hanging between them in a catenary), `segments` the elements along it (it has one particle more), `thickness` its diameter (what it collides through and the tube it is drawn as) and `mass` its weight (1 kg a metre when 0). It is built from those as a chain of particles and elements and stepped on the FEM solver: it hangs, drapes and wraps over what it touches, its segments colliding with rigid bodies, terrain and soft bodies. Its segments hold their length both ways, like a chain's links, and bend freely at the particles; `stretchStiffness` is its axial stiffness E A in newtons (default 1e6, a centimetre-thick polyester rope; 0 as stiff as the solver holds anything), `bendStiffness` its flexural rigidity E I (0 hangs limp), `damping` damps its stretch and `breakForce` snaps a segment past that pull. `pins` hold its particles in the world and `attachments` tie them to rigid bodies, `{ nearest = from }` and `{ nearest = to }` naming its ends. `Physics.softElements(id).force[k]` is the pull in segment k counted from `from`. It is drawn as a round tube of its thickness with the entity's material. The physics guide's "Ropes and cables" has the measured loads, sags, swings and costs. **Regions with a material of their own.** `regions` gives parts of any soft body their own material: a crumple zone that gives way while the cabin holds, a soft tip on a stiff tool, a padded skin over a hard frame, the weak members of a structure. Each entry is `{ name, region = { box = { min, max } } | { nearest = point }, stiffness, damping, poisson, plasticYield, plasticCreep, plasticMax, tearStrain, tearForce, tearSmoothing, density }`: `region` selects particles the way `attachments` and `pins` do (in the shape the body was built in, in the entity's unit box, for a `mesh` body the model's own local coordinates and for a `custom` body those of its `particles`; a `space = "world"` region where the body stood in the world when it was built), and an element (a cell, an edge) takes the material when all its particles are inside; on a `custom` body `group = "name"` selects the elements of that group instead. On a `custom` body `stiffness` and `poisson` are those of its `cells`, so a region of links (a `group`, or a body with no cells) states neither, and is refused naming the field when it does: its links take the `stiffness` of their own elements. A value an entry leaves out is the body's own, and later entries win over earlier ones. `density` (kilograms per cubic metre of the region's cells) weighs its particles when the body is built; everything else applies to the running body in place. `Physics.softBodyState(id).regions` reads each back: its values, the `elements` and `cells` that took them, the `particles` it covers, and `plastic`, the largest permanent strain of its elements (0 where it stayed elastic). `:setRegion(name, values)` changes one on the running body. `attachments` holds regions of the body to rigid bodies, two-way: a list of `{ target, region }`, `target` the entity id of a body with `Physics`, `region` `{ box = { min, max } }` (every particle between the corners) or `{ nearest = point }` (the one particle nearest the point) in the entity's unit box, `space = "world"` for world coordinates, empty for the whole body. Each region follows its rigid body and the rigid body carries its weight and pull. Changing the list re-ties only the entries that changed; a rebuilt body is tied again, and removing either side releases the hold. `Physics.softBodyState(id).attachments` reads each entry back with the force it pulls with, or why it holds nothing. To join soft bodies to each other, or to anchor a joint on a soft body, use a `Joint`, whose ends each take a region. Methods: `:state(opts?)` returns the same report as `Physics.softBodyState(entityId, opts)`. `:elementStates()` reads every element at once (`Physics.softElements`), `:drive(targets, opts?)` drives element lengths (`Physics.driveSoftElements`), and `:setRegion(name, values)` changes a region on the running body and returns its entry. `:repair()` restores the shape the body was built in and returns the new `repairs` count. `:attach(target, region?)` adds an attachment and returns its index (the same as `Physics.attachSoftRegion`); `:detach(target?)` releases the regions held to `target`, or all of them, and returns how many it removed. The body is built at the start of the frame after the component is added. Until then `Physics.softBodyState(id).status` is `"pending"` (with `exists = false`, and `waitingFor` naming what the build waits on); once built it is `"built"`, and a component that was not built reads `"refused"` with the reason in `refusal`. `Physics.softBodyState(id).cage` reports a `mesh` body's fill: `cellSize`, `cached` (taken from the cage cache, as a second instance of a model is), `buildMs`, `generateMs`, `filledParts`, `strayParts`, `openParts`, `seams` (springs sewing touching parts together), `pieces`, `enclosedVolume` and `digest`. ```luau local jelly = entity.spawn("jelly") jelly.position = { 0, 2, 0 } jelly.component.add("SoftBody", { shape = "box", resolution = 6 }) print(Physics.softBodyState(jelly).status) -- "pending" in the call that added it -- on a later frame: local s = Physics.softBodyState(jelly) print(s.status, s.particleCount, s.volumeRatio, s.sleeping) -- "built", 216, ... ``` ```luau -- a cloth whose left edge hangs from a pole flag.component.add("SoftBody", { shape = "cloth" }) flag.component.get("SoftBody"):attach(pole, { box = { min = { -0.5, -1, -0.5 }, max = { -0.45, 1, 0.5 } } }) print(Physics.softBodyState(flag).attachments[1].forceMagnitude) -- on a later frame ``` ```luau -- a cloth that rips when pulled past 1.4 times its length sheet.component.add("SoftBody", { shape = "cloth", resolution = 12, tearStrain = 0.4 }) Physics.onSoftBodyTear(function(e) print(e.entity, "tore", e.kind, "at", e.position, "into", #e.pieces + 1, "pieces") end) -- a jelly cut in two along the plane x = 0 Physics.cutSoftBody(jelly, { point = vector.create(0, 0, 0), normal = vector.create(1, 0, 0) }) ``` ```luau -- a stiff beam held by one end, on the FEM solver beam.localScale = { 2, 0.2, 0.2 } beam.component.add("SoftBody", { shape = "box", resolution = 16, stiffness = 1e8, mass = 8, solver = "fem", pins = { { name = "root", region = { box = { min = { -0.5, -1, -1 }, max = { -0.45, 1, 1 } } } } } }) print(Physics.softBodyState(beam).solver) -- "fem" ``` ```luau -- a slab of clay that keeps the print of whatever lands on it clay.component.add("SoftBody", { shape = "box", stiffness = 3000, plasticYield = 0.02 }) -- on a later frame, after something landed on it and left: print(Physics.softBodyState(clay).plastic) -- metres of dent that stayed clay.component.get("SoftBody"):repair() -- and gone again ``` ```luau -- a side-on bridge of eight one-metre panels: a top chord that yields past -- 4 kN, breaks past 9 kN and drops as one, over a stronger deck and web local particles, elements = {}, {} for i = 0, 8 do table.insert(particles, { position = { i, 0, 0 }, mass = 20 }) end for i = 0, 7 do table.insert(particles, { position = { i + 0.5, 1, 0 }, mass = 20 }) end for i = 1, 8 do table.insert(elements, { i, i + 1, group = "deck" }) end for i = 1, 7 do table.insert(elements, { 9 + i, 10 + i, yieldForce = 4000, plasticMax = 0.03, breakForce = 9000, group = "chord", breakGroup = "chord" }) end for i = 1, 8 do table.insert(elements, { i, 9 + i, group = "web" }) table.insert(elements, { 9 + i, i + 1, group = "web" }) end bridge.component.add("SoftBody", { shape = "custom", particles = particles, elements = elements, solver = "fem", pins = { { name = "left", region = { nearest = { 0, 0, 0 } } }, { name = "right", region = { nearest = { 8, 0, 0 } } } }, plane = { normal = { 0, 0, 1 }, point = bridge.position }, }) -- each frame: colour the members by load local e = Physics.softElements(bridge) for i = 1, e.count do print(i, e.force[i], e.load[i]) end -- newtons (+ pull, - push), share of break force Physics.onSoftBodyTear(function(t) for _, b in t.elements do print("member", b.index, b.group, "broke at", b.force, "N, step", t.step) end end) ``` ```luau -- a car shell whose front crumples while the cabin holds shell.component.add("SoftBody", { shape = "box", resolution = 10, stiffness = 2e5, solver = "fem", regions = { { name = "crumple", region = { box = { min = { -0.5, -0.5, 0.3 }, max = { 0.5, 0.5, 0.5 } } }, stiffness = 1e4, plasticYield = 0.01 }, } }) print(Physics.softBodyState(shell).regions[1].plastic) -- the crumple zone's permanent strain shell.component.get("SoftBody"):setRegion("crumple", { stiffness = 2e4 }) ```
▲ 0↑ born
◇
component · born here
❒asset
# WheelCollider A wheel of a ray-cast vehicle (Unity-style). Add it to a child entity of a rigid body: every wheel under one body is one wheel of that body's vehicle, simulated by rapier's ray-cast vehicle controller (`DynamicRayCastVehicleController`). The system finds the nearest ancestor with a `Physics` component and drives it. Each physics tick a wheel casts its suspension ray straight down the chassis' local **-Y** from its own position, which is the suspension **mount**. The ray passes through triggers and through the chassis' own colliders, so a chassis `BoxCollider` around the mounts is fine. The wheel stands on the nearest surface along the ray whose normal faces back along it within `groundAngle` (45 degrees by default); the ray reads past a steeper face, such as the side of a crate, a kerb's face or a wall, to the ground beyond it, so a wheel meets a box on the road on its top. The controller then applies the suspension, drive, brake and tyre grip to the chassis as impulses, and the opposite of each, at the tyre's contact, to the dynamic body the wheel stands on: a car parked on a deck, a seesaw, a soft body or another car weighs on it as the same chassis resting on it directly does, and a car that drives or brakes on a floating deck pushes the deck the other way, the two sharing one momentum. The push into that body reaches it whole where its contacts hold it up, as a deck or a crate lying on the floor is held, and where it would throw a light body out from under the tyre, or tip it about the edge it stands on, it reaches the body only as far as the tyre can follow it, the spring's compression over a tick, and the body pushes the chassis back no harder than that. Along the ground, the drive, brake and grip push the body as far as its own movement was counted when they were sized: a car on its own wheels or a deck on ice takes the whole push and moves under it, while a crate the floor's friction holds passes it on to the floor. The fixed world carries whatever the body does not take. Drive conventions: positive `motorTorque` drives toward the parent body's local **-Z** (the engine's forward); positive `steerAngle` steers right. ## Fields | Field | Meaning | |---|---| | `suspensionDistance` | Suspension travel (m): the wheel hangs at most this far below the mount, and the spring compresses by at most this much from its rest, where the bump stop holds the wheel. | | `targetPosition` | Where the spring rests, as a share of `suspensionDistance` below the mount. The spring's rest length is `suspensionDistance * targetPosition`, and the wheel reaches the ground within that length plus its radius. 1 rests at full extension. The spring compresses from its rest by up to `suspensionDistance`, where the bump stop is. | | `springRate`, `damperRate` | Spring stiffness (N/m) and damping (N·s/m) per wheel. | | `maxSuspensionForce` | The most force (N) one wheel's suspension pushes with (default 6000). Raise it for a vehicle heavier than about 2 t on four wheels. | | `bumpStopRecovery`, `bumpStopSpeed` | How the bump stop pushes a chassis standing past it back out: by `bumpStopRecovery` of the depth each physics tick (default 0.2), and no faster than `bumpStopSpeed` (m/s, default 1). | | `groundAngle` | The steepest surface the wheel stands on (degrees, default 45): the widest angle between a surface's normal and the suspension, pointing back up it. The ray reads past a steeper face to the ground beyond it. A wheel at 60 climbs a 50 degree face that a default wheel reads past (a rock crawler, a kart riding kerbs, a bogie on a ramp); one at 30 stands only on gentle ground. | | `radius`, `width` | Wheel size (m). An unset radius comes from the wheel entity's model bounds, or else from its visual's. The ray is cast from the centre of the tread, so a chassis leaning over flat ground meets it at the same points at any lean. It is cast from a shoulder instead when the ground under that shoulder stands more than 1 mm above the ground under the centre, so a kerb or a plank under one shoulder holds the wheel up, or when the centre finds no ground. | | `motorTorque` | Drive torque (N·m). A wheel with no `inertia` drives with `motorTorque / radius` newtons, up to `forwardFriction` times the load it carries; a wheel that spins on its own takes it on its axle (see Spin below). | | `maxDriveSpeed` | The tread speed (m/s, default 0) up to which `motorTorque` drives a wheel that spins on its own: below it the wheel takes the whole torque, and from it on only what holds its tread there, on the ground and in the air, the way a rev limit holds an engine. A reverse drive is held to it backward. 0 drives the wheel at any speed. It bounds what the drive does: a gripping tyre turns its wheel at the speed the road passes under it, so a car rolling faster than the top (down a hill, or its rear end lifting over a crest) turns its wheels faster than it while its drive puts nothing on them. A wheel with no `inertia` rolls at the road speed and its drive is held by its grip alone. | | `brakeTorque` | Brake torque (N·m). A wheel with no `inertia` brakes with up to `forwardFriction` times the load, while `motorTorque` is 0, and so does `rollingResistance`; a wheel that spins on its own takes it on its axle, beside the drive. A braked car stands still on any slope its brakes' grip holds, gravity included. | | `steerAngle` | Steering angle (degrees), positive steers right. At light throttle the car turns on the radius its geometry gives, the wheelbase over `tan(steerAngle)`, as long as the turn asks less of its tyres than their sideways grip (`sidewaysFriction`); driving the steered wheels hard tightens the turn and driving only the others widens it. | | `frictionSlip` | The tyre's combined grip limit (default 10.5): the drive, brake and side grip together reach at most the suspension load times this before the tyre slides sideways. Lower it (1 or less) for ice, a drift car or skids. | | `sideFrictionStiffness` | The tyre's cornering stiffness (default 1): how hard it pushes back across its contact for each radian its contact slips off the line it rolls along, as a share of `corneringStiffness` times the load it carries. A standing tyre holds its contact still across the ground, so a chassis leaning on its springs or tipping over turns about its tyres' contacts; a rolling one answers a steady push across it with a steady slip angle, about 6 degrees at its sideways grip at the defaults. | | `corneringStiffness` | The base cornering stiffness (default 10): the sideways force, per newton of load, per radian of slip angle, that `sideFrictionStiffness` scales. At 10 and a `sidewaysFriction` of 1 the tyre's grip across the road peaks at about 6 degrees of slip angle; at 25 at about 2.3 degrees (a stiff race tyre), at 5 at about 11 (a soft, balloon or off-road tyre). | | `forwardFriction` | Longitudinal grip coefficient (default 1): drive and brake force are held to this times the load the wheel carries. | | `inertia` | The wheel's moment of inertia about its axle (kg·m², default 0). Above 0 the wheel spins on its own (see Spin below); about half the wheel's mass times its radius squared, 1 to 2 for a car wheel. 0 rolls it at the road speed. | | `forwardFrictionStiffness` | Slip-ratio stiffness of a wheel that spins on its own (default 1): how hard its tyre pushes along the road per unit of slip ratio, as a share of 10 times the load it carries. At the defaults its force reaches its load at a slip ratio of 0.1. | | `slideGrip` | The share of its grip a tyre of a wheel that spins on its own keeps once it slides (default 0.75): up to its peak slip it grips with all of `forwardFriction` and `sidewaysFriction`, and from `slideSlip` times that slip on with this share of them. | | `slideSlip` | Where a tyre's grip curve has fallen off, for a wheel that spins on its own (default 2): the slip, as a multiple of its peak slip, at which its grip has fallen in a straight line from its peak to `slideGrip` of it. 1 lets go at once past the peak (a peaky tyre); 3 to 5 falls off gently and holds a slide. See Grip curve below. | | `loadSensitivity`, `referenceLoad` | Tyre load sensitivity (default 0): every grip coefficient and stiffness of the tyre is scaled by `(load / referenceLoad) ^ -loadSensitivity`, so its grip per newton falls as its load rises, and at `referenceLoad` (N, default 4000) it grips with its coefficients as stated. 0 grips in proportion to load; 0.1 to 0.3 is a road tyre. Held to 0..0.9. See Grip curve below. | | `sidewaysFriction` | Sideways grip coefficient (default 1): the force the tyre pushes back with as the chassis moves across its contact, in a turn or under a push from the side, reaches at most this times the load it carries, less what its drive or brake spends of it. A car turning harder than that slides wide: steered 10 degrees, a 2 t truck turns on the 19 m its steering gives at 5 m/s and slides wide on its wheels at 20 m/s. Gravity's pull across a slope is held by the tyre's combined grip, `frictionSlip`, so a truck standing across a slope stays where it stands until it tips. | | `rollingResistance` | Drag on a freely rolling wheel, times the load it carries. The ground under the tyre adds its own `rollingResistance` (see Ground below). | | `surfaceGrip` | How this tyre grips particular ground: `{ { surface = "ice", grip = 0.35 }, { surface = "loose", grip = 0.8 } }`. On a surface an entry names, by its name or one of its tags, the tyre grips with `grip` of its stated grip in place of the surface's `friction`: a studded tyre on ice, an off-road tread on gravel. The surface's own name is matched first, then its tags in their order. Empty by default. | | `is2D` | The wheel applies no sideways grip. | | `visual` | The wheel's visual: an entity, or its id (see below). | | `solid` | The wheel is a volume other bodies strike (default false): see Solid wheels below. | | `mass` | The wheel's mass (kg, default 20) as a body of its own once it comes off. | | `breakLoad` | The force (N) above which the wheel comes off its vehicle (default 0, never): see Wheels that come off below. | | `attached` | Whether the wheel is on its vehicle (default true). Set false to take it off, true to put it back on its mount. | | `detachReason` | Why the wheel came off: `"load"` or `"command"`; empty while it is on. | The suspension ends at a **bump stop**: once the spring has compressed by `suspensionDistance` from its rest, the wheel holds the chassis off the ground there like a solid contact. It stops the chassis closing on the ground within the tick, so a landing faster than the springs can take, or a chassis heavier than its springs carry, ends on the stops with the tyre on the ground rather than in it, and the chassis is not thrown back up. A chassis that stands past its stops (put there by a script, say) is eased back out by `bumpStopRecovery` of the depth each tick, at no more than `bumpStopSpeed` (1 m/s by default). The spring is applied as an impulse worked out from the state at the start of each tick. So that it cannot feed on itself, its rate is held, per tick, to what the chassis' mass **and its rotational inertia** integrate stably: a light chassis, or one whose pitch or roll inertia is small next to its wheelbase, gets less of a very stiff spring than authored. The damper is applied to the velocity the chassis ends the tick with, which is stable at any rate, so the authored `damperRate` always acts whole. A damper pulls a wheel down no harder than its spring pushes it. ## Ground A tyre's grip coefficients (`forwardFriction`, `sidewaysFriction`, `frictionSlip`) are stated for ground of friction 1. On a surface content defined (`Physics.defineSurface`), named by the collider under the tyre or painted on a `Terrain` under it, every one of them is scaled by the surface's `friction`, or by the tyre's own `surfaceGrip` entry for that surface; its stiffnesses are not, so on slippery ground the tyre reaches its lower peak at a smaller slip. The ground's `rollingResistance` adds to the tyre's own: the surface's, or the collider's own on a collider naming none. So one car on tarmac, gravel, grass and ice brakes, accelerates and corners differently with no script, wheel by wheel: a car with its left wheels on ice and its right on tarmac pulls right under the brake. Ground naming no defined surface leaves the tyre's grip coefficients as stated, whatever the collider's own `friction`. A surface defined without a `friction` takes 0.5, so a tyre grips it with half its stated grip: state `friction = 1` for ground a tyre grips as stated (dry tarmac), and lower for looser ground, for example `Physics.defineSurface("tarmac", { friction = 1.0, rollingResistance = 0.01 })`, `"gravel"` 0.6, `"grass"` 0.45, `"ice"` 0.1. `surface` and `ground` in the runtime state name what each tyre stands on, and `Physics.tyreCurve(wheelId, { surface = "gravel" })` measures the curve on a given surface. ## Runtime state Read-only, updated every physics tick, and readable through `Physics.getWheelState(wheelId)`: - `isGrounded`: the tyre touches the ground anywhere within the suspension's full travel, `suspensionDistance` below the mount. Past the spring's rest it carries no load. - `compression` (0 with the spring at or past its rest length, up to `suspensionDistance`, where the bump stop is). - `angularVelocity` (rad/s) and `rotation` (rad): the wheel's spin and its angle about the axle, both growing as it rolls forward. A wheel with no `inertia` turns by the distance rolled over the radius; one that spins on its own turns at its own spin. - `skid` (m/s): how fast the tyre slides while its grip is used up; 0 while the tyre holds. Sideways for a wheel with no `inertia`; along the road too for one that spins on its own, so a locked or spinning tyre reads its slide. - `slipRatio`: the tread's speed less the road's under it, both positive rolling forward, as a share of the road speed (taken as at least 0.5 m/s), so its sign is the way the tyre pushes the car along the road. Rolling forward it reads 0 rolling, above 0 in wheelspin (1 at twice the road speed) and -1 locked; rolling backward the signs turn over, a wheel spinning backward past the road reading below 0 and a locked one 1. 0 for a wheel with no `inertia`. - `slipAngle` (degrees): the angle between the line the tyre rolls along and the way its contact moves over the ground, positive as the contact moves toward the wheel's right: how far into a drift the tyre is. - `roadSpeed` (m/s): how fast the ground passes under the tyre along the line it rolls along, positive rolling forward. `load` (N): the force the tyre presses the ground with, which its grip is sized by. - `sideImpulse`, `forwardImpulse` (N·s): what the tyre applied to the chassis this tick, and `sideForce`, `forwardForce` (N) the same over the tick. `suspensionForce` (N). `stopImpulse` (N·s): what the bump stop applied this tick, the part of a landing or a load the suspension could not take. - `center`, `hitPoint`, `hitNormal`: the wheel centre and the ground contact, in world space. A wheel with no ground within its travel hangs at full travel. - `surface`: the surface the tyre touches (`Physics.defineSurface`), the one the collider under it names there or, on a painted `Terrain`, the layer under the contact; absent on ground naming none. `ground`: the entity id of what it touches. Both are also on the component (`wheel.component.get("WheelCollider").surface`). - `reaction` (N): the force the ground and whatever struck the wheel's volume put on the wheel in the last tick: the suspension's push, the bump stop's, the tyre's along and across the road, and the contacts on its volume, their push and their friction, added as vectors. What `breakLoad` is measured against. `detachLoad` (N): the `reaction` the wheel came off at, 0 for one taken off by command. - `vehicleOrder`: the wheel's place among the wheels of its vehicle, from 1: the order the vehicle steps them in, which is the order they arrived in the world, and the order `Physics.vehicleState` lists them in. A wheel that came off keeps the place it last held; one that has not stepped on a vehicle reads 0. **Drivetrains.** An engine, a clutch, a gearbox and a differential driving the wheels are a `ShaftNetwork` (on the chassis, say) whose parts name the wheels: `{ name = "rearLeft", wheel = rl }`. A wheel a network drives spins on its own (with its own `inertia`, or the part's when it states none), its `motorTorque` (up to `maxDriveSpeed`) and `brakeTorque` still acting on its axle, and the network's links (a shaft, a gear ratio, a clutch, an open, locked or limited-slip differential) are solved with the tyres and the chassis in one step: one wheel on ice spins behind an open differential while the other stands, and a locked one drives both. The `ShaftNetwork` component README has the fields, and the physics guide (`topics/physics`) a car recipe. A driver for the wheels is built in: `VehicleController` on the chassis reads the vehicle input map, or the intent code gives it through `setIntent` (an AI driver, a replay, a test), and writes `motorTorque`, `brakeTorque` and `steerAngle`. `Physics.vehicleState(chassisId)` reads the whole vehicle: the chassis' forward speed (m/s, negative in reverse), how many wheels are grounded, and each wheel's state, in the order the vehicle steps its wheels. That order is the order the wheels arrived in the world (the first spawned first), and each wheel's place in it is its `vehicleOrder` (from 1). The vehicle steps its wheels in that order on every run and every engine, whatever entity slots the wheels were given, so a car stepped the same steps from the same state reads the same `Physics.stateDigest`. ## Spin: wheelspin, lock-up and drifts A wheel with an `inertia` above 0 spins on its own. Its spin is integrated each tick from the torques on its axle: `motorTorque` drives it, `brakeTorque` (with `rollingResistance` times its load) holds it toward still, and its tyre pushes back. The tyre pushes the chassis along the road in proportion to the slip between its tread and the road (the slip ratio, `forwardFrictionStiffness`), up to `forwardFriction` times its load; the wheel and the chassis are solved together, so it is stable at the engine's 30 Hz and 60 Hz ticks with a wheel however light. So: - **Wheelspin.** A drive torque past what the tyre puts down spins the wheel up faster than the road (`slipRatio` above 0), and the car gains speed only as fast as its grip pushes it: 250 N·m on each wheel of a 600 kg car (`inertia = 1.2`, radius 0.35) spins its wheels to more than twice the road speed on ice (`forwardFriction = 0.15`) and the car gains 2.2 m/s in 2 s, while on asphalt it pulls away with a slip ratio under 0.09 and reaches 8.6 m/s. The drive spins the wheel up to `maxDriveSpeed` at its tread and holds it there, the way a rev limit holds an engine: the same car with `maxDriveSpeed = 25` and 1500 N·m on each rear wheel spins its rear treads to 25 m/s from rest on asphalt and in the air and no faster, and still spins them past twice the road speed pulling away on `forwardFriction = 0.15`. `VehicleController` sets it from its `topSpeed`. With `maxDriveSpeed` 0 `motorTorque` acts whatever the wheel's spin, so a wheel driven past its grip keeps spinning up until the drive eases. `VehicleController`'s `tractionControl` eases it: it holds each driven wheel's drive to what its tyre pushes back with just short of the slip its grip peaks at, read from `Physics.tyreCurve`; a driver of your own does the same by cutting `motorTorque` while `slipRatio` stands past a target (0.1 to 0.5) the way the drive turns the wheel. - **Lock-up.** A brake torque past what the tyre holds stops the wheel (`angularVelocity` 0, `slipRatio` -1) while the chassis slides on, and a sliding tyre grips with `slideGrip` of its grip. The same car braked from 20 m/s stops in 26.9 m with every wheel locked (20000 N·m), and in 22.5 m with each brake held at 0.95 of what its tyre holds at the `load` it reads. A locked tyre holds only `slideGrip` of its grip, so a brake held at the peak keeps it locked: anti-lock braking is a driver that eases `brakeTorque` off while `slipRatio` stands past about 0.15 against the way the car rolls (below -0.15 rolling forward), letting the wheel roll again. - **Drift.** A tyre's grip along the road and across it is one grip: a tyre slid past its peak, spinning or locked, pushes against its slip in both directions with `slideGrip` of it, so the rear wheels of a car locked on the handbrake, or spun up under power, let go across the road and the car rotates into a drift (`slipAngle` on the rear tyres). Throttle and counter-steer hold it: from 15 m/s, the rear pair locked on 6000 N·m with the front steered 20 degrees for 0.7 s turns the car 32 degrees across its path, and 450 N·m on the rear with the front steered along the way the car moves holds it past 10 degrees for 1.6 s; a rear-driven car kicked into a slide at 10 m/s holds it past 10 degrees for 2.6 s with its throttle cut while the rear slip ratio stands above 0.5. Holding the throttle with the rear wheels spinning far past that leaves them next to no grip across the road, and the car spins. `VehicleController`'s `counterSteer` gives a car that counter-steer from the controller: it steers the front wheels along the way the car moves as it slides, so a car driven from keys that steer full lock or none holds a drift on the throttle and the steering keys (the `VehicleController` README, "Holding a slide"). A wheel in the air keeps its spin, turned by its drive up to `maxDriveSpeed` and slowed by its brake. A chassis lying still with its wheels spinning in the air (on its roof, say) falls asleep like any other body, and its wheels spin on from where they were when it wakes. A wheel with no `inertia` (the default) rolls at the road speed. ## Grip curve: peak, fall-off and load sensitivity A tyre's grip is a curve over its slip (a tyre or tire curve, or grip curve). Along the road its force rises with the slip ratio at `forwardFrictionStiffness` times 10 per newton of load, and across it with the slip angle (its tangent) at `sideFrictionStiffness` times `corneringStiffness` per newton, each up to its peak: `forwardFriction` and `sidewaysFriction` times the load. The two directions share one grip, an ellipse their two peaks span, so a tyre braking or driving hard has less left for cornering. On a wheel that spins on its own, past the peak the grip falls in a straight line to `slideGrip` of it at `slideSlip` times the peak slip and stays there, the tyre pushing against its slip; a wheel with no `inertia` grips up to its peak across the road and holds it there. A `loadSensitivity` above 0 makes the tyre grip with less per newton the more it carries, every grip and stiffness scaled by `(load / referenceLoad) ^ -loadSensitivity`: a heavy vehicle grips with less per kilogram than a light one on the same tyres, and a wheel loaded by weight transfer (the outside wheels in a corner, the front ones under braking) gains less grip than the load it takes, so a car's balance moves with its load. The whole force is held to `frictionSlip` times the load as well. So a tyre is stated by its peak (`forwardFriction`, `sidewaysFriction`), where it peaks (the stiffnesses), how it falls off (`slideGrip`, `slideSlip`) and how it takes load (`loadSensitivity`, `referenceLoad`): a peaky sim tyre, a forgiving drift tyre, a kart's, a truck's, a tyre on ice or on gravel. `@builtin::modules.tyres` holds presets of these fields (`road`, `grippy`, `peaky`, `drift`, `loose`, `ice`, `heavy`), as content, and any curve the fields state is one the engine takes: ```luau local Tyres = require("@builtin::modules.tyres") wheel.component.add("WheelCollider", Tyres.with("drift", { radius = 0.35, inertia = 1.2 })) ``` `Physics.tyreCurve(wheelId, opts?)` (the `phys.tyreCurve` tool) measures the curve a wheel states: its force against slip angle and, for a wheel that spins on its own, against slip ratio, at each load asked for, with each sweep's `peak` and `slide` and `gripScale`, the share of its stated grip it has per newton at that load. It is the force the wheel's solve settles on at that slip, so a tune can be checked by numbers before it is driven. Measured on a 600 kg car on four wheels that spin on their own (`inertia = 1.2`, radius 0.35), at the engine's 30 Hz and 60 Hz ticks. A grippy curve (peak 1.2, falling to 0.9 of it by 3 peaks) corners at 11.0 to 11.1 m/s² on a skidpad, reaches 17.5 m/s after 2 s of 600 N·m on each wheel and stops from 20 m/s in 18 to 18.5 m with every wheel locked; the default curve (1, falling to 0.75 by 2) corners at 8.2 to 8.6 m/s², reaches 14.7 m/s and stops in 26.2 to 26.7 m; a peaky curve (1.2, falling to 0.5 by 1.2) corners at 7.5 to 8.5 m/s², reaches 12.0 m/s and stops in 32.5 to 33.3 m, and a handbrake turn from 15 m/s swings it 32 degrees across its path before counter-steer straightens it out; a slidey curve (0.8, falling to 0.4 by 1.5) corners at 5.1 to 5.6 m/s², reaches 6.4 m/s, is still sliding 6 s into the stop, and ends the same handbrake turn still 12 degrees across its path. With a `loadSensitivity` of 0.3 the car at 1200 kg (springs, dampers and `maxSuspensionForce` doubled) corners at 0.82 of the 600 kg car's peak, against the stated `2 ^ -0.3` = 0.81, and at 0 at the same one; with 0.5 and `referenceLoad` at its wheels' static load, weight transfer onto the outside wheels lowers its skidpad peak by 2.3 to 2.6%. ## Solid wheels A wheel's suspension is a ray, so on its own a wheel has no volume: a post, a wall or another car meets the chassis' collider and passes through the tyre. A `solid` wheel carries a volume as well, riding with the wheel centre as the suspension travels and steering with it: the wheel entity's own collider when it has one that is not a trigger (a `SphereCollider`, or a `MeshCollider` hull of a tyre model on the wheel entity), else a cylinder of the wheel's `radius` and `width` about its axle. Walls, posts and other bodies strike it on its tread and on its faces, the contact holds the chassis back as a contact on the chassis' own collider does, and contact events name the wheel entity (`otherCollider`). Its contacts low on its tread, in the cap under the wheel centre that `groundAngle` spans (below the centre by the radius times the cosine of the angle), are the suspension's: the ground, a ramp, a kerb or a plank met there is mounted by the suspension as a ray-only wheel mounts it, and a car on solid wheels settles and drives as the same car on ray-only wheels does. With the default 45 degrees a wheel of radius 0.35 m mounts a kerb up to 10 cm high and strikes anything taller. The cylinder adds no mass to the chassis and takes the collision groups of the chassis' colliders; a collider of the wheel's own keeps its own. A trigger on the wheel entity stays a trigger beside the volume, standing where the wheel entity stands on the chassis. ## Wheels that come off A wheel comes off its vehicle when its `reaction` passes its `breakLoad`, or when `attached` is set false (`Physics.detachWheel(wheel)`). It leaves as a dynamic body of its own, on the wheel entity, with its `mass` and with the wheel entity's own collider as its collider, whenever it is taken off and whether or not it is `solid`: that collider leaves the chassis with it, and the chassis' mass, centre of mass and inertia are worked out again over the colliders it keeps. A wheel with no collider of its own, or whose own collider is a trigger, leaves on a cylinder of its `radius` and `width`, and a trigger of its own leaves the chassis with it on its body and goes back to its mount with it. It rolls, bounces and lies down like any body, and `Physics.getVelocity`, `Physics.applyImpulse` and the contact listeners reach it. The wheel entity stays under the chassis in the hierarchy, standing where its own body is, and its visual follows that body. The vehicle drives on the wheels it has left, the others keeping their suspension, spin and tyre state, and a `ShaftNetwork` part naming the wheel turns on its own (its `problem` says the wheel came off) until it goes back on. The mount is a fuse: a wheel torn off by its `breakLoad` passes its chassis no more than that over the tick it breaks in, of the blow's push and of the turn it gives the car alike. The wheel leaves moving as the blow left it, and the chassis keeps the rest of its momentum, so a car whose front wheel strikes a post carries on past it on its other wheels while the wheel stays at the post. Carrying on along its line, the car brings the wheel behind the torn one to the same post: a `breakLoad` that wheel's glancing blow stays under keeps it on, and a lower one sheds it too. A wheel taken off by command leaves moving as its chassis moved where it stood, spinning as it spun. `reaction` is a force over one physics tick. A 600 kg car on four wheels reads about 1.5 to 2 kN per wheel at rest and about 1.9 kN rolling over an 8 cm kerb at 15 m/s; striking a post at 15 m/s with one solid wheel reads about 285 kN at a 30 Hz tick and 570 kN at 60 Hz (the same blow over half the time). A `breakLoad` of a few tens of kN keeps wheels on through kerbs, jumps and landings and loses them to a crash. Set `attached` true again (`Physics.attachWheel(wheel)`) and the wheel goes back on its mount: its own body goes, and the vehicle drives on it from the next physics tick. `Physics.vehicleState(chassis)` lists the wheels on the vehicle under `wheels` and those that came off under `detachedWheels`, each with its `detachReason` and `detachLoad`. `attached` and `detachReason` are synced fields: on a shared world the peer simulating the vehicle breaks its wheels, every peer takes the wheel off, and the wheel's body moves on every other peer as the simulating peer moves it. ## Seeing the suspension `capture { pass = "physics" }` and the edit-mode collider overlay draw every wheel over the colliders: its suspension ray over its whole reach, `suspensionDistance` and the radius below the mount (green on ground, red in the air, as `isGrounded` reads), the travel from the mount to the tyre's centre coloured by how much of it is taken up (blue extended, yellow half way, red bottomed out), the tyre's radius as a white circle across its steered axle, and where the tyre meets the ground (yellow) with the ground's normal (cyan). `Physics.debugLines({ layers = { "wheels" }, entities = { chassis } })` returns those lines with each wheel's `grounded` and `compression` (the same values as `isGrounded` and `compression` here), `travel`, `suspensionLength`, `restLength`, `radius`, `mount` and `contactPoint` / `contactNormal`. In edit mode the vehicle stands at rest, so its wheels draw where they are mounted and follow their authored fields as they change. ## Visuals The wheel entity's transform is the suspension mount, so it stays where it is authored. Put the tyre mesh on another entity under the chassis (a child of the wheel is the usual place) and name it in `visual`, as the entity or its id (a prefab or player clone of the car points it at its own copy of the tyre): every tick the wheel places that entity at the wheel centre, turns it by the steering angle and spins it about the axle, starting from the rotation it had when the wheel first posed it. Methods: `setMotor(torque)`, `setBrake(torque)`, `setSteer(angle)`. ```luau local car = entity.spawn("car") car.position = { 0, 1, 0 } car.component.add("Physics", { kind = "dynamic", mass = 600 }) car.component.add("BoxCollider", { half = { 0.9, 0.3, 2.0 } }) for _, at in { { -0.85, -1.3 }, { 0.85, -1.3 }, { -0.85, 1.3 }, { 0.85, 1.3 } } do local wheel = entity.spawn("wheel", { parent = car.id }) wheel.localPosition = { at[1], -0.3, at[2] } local tyre = entity.spawn("tyre", { parent = wheel.id }) tyre.component.add("Model", { model = "cylinder" }) tyre.localRotation = { 0, 0, 0.7071068, 0.7071068 } -- the cylinder's axis along X tyre.localScale = { 0.7, 0.25, 0.7 } wheel.component.add("WheelCollider", { suspensionDistance = 0.3, springRate = 20000, damperRate = 2000, visual = tyre, }) end ```
▲ 0↑ born
·
assettype · born here
❒asset
# assetType (asset type) An asset type says what a kind of asset is: the files an asset of the kind is made of, the code that gives it behaviour, the interface a person uses to work with it, and how it is found, pictured and checked. A `<typename>.assetType/` folder declares a type called `<typename>`, and every `<name>.<typename>/` folder is an asset of it. `assetType` is itself a type, so a type is an asset like any other: it is created, versioned, installed and contributed the same way. ## Making a type `asset.create("assetType", "<typename>")` scaffolds a type. The type registers the moment its folder is written, anywhere under `/zero/source/`, and from then on `<name>.<typename>/` folders are its assets. An asset of a type that is not registered yet is not an asset, so make the type first. A type folder is a root: `~.x` in any file inside it names the type's own `x`, wherever the type is installed. Keep the type's whole implementation inside its folder and reach it that way. What a type folder must hold is set by this type's own `type.yaml`, the same way every type's `type.yaml` sets what its assets hold. `asset.validate` on a type reports anything missing, and the scaffold produces a folder that passes. ## What sets your type's schema (`type.yaml`) `type.yaml` is the structural contract every asset of the type is checked against. The keys below are the ones the engine reads; a key not listed here is ignored. | Key | What it controls | |---|---| | `suffix` | The folder suffix of the type's assets. Defaults to `.<typename>`. | | `primary` | The file or files that are the asset's content: what the asset resolves to when it is used. | | `entry_files`, `primary_aliases` | Further files that load as the asset or share its identity. | | `is_container` | Whether the suffix stays in the identities of what the asset holds. | | `is_opaque_walker` | Whether a walk of the tree stops at the asset and registers only its primary. | | `plural_dir`, `classify_exts` | Loose files in a folder of this name, or with these extensions, are assets of the type. | | `is_text_default` | Whether the asset's files are text unless stated otherwise. | | `broadcasts_subassets` | Whether assets nested inside an asset of the type are found by their own short name. | | `root` | `true` makes every asset of the type a root, so `~.x` inside one names that asset's own `x`. | | `contract_ref: { field, category }` | A key of the primary file that names another asset the asset is built on. | | `files: { required, optional }` | The files an asset holds (below). | | `allow_unlisted` | `false` reports every file the type does not declare. | | `aliases_from: [{ file, key }]` | Further names an asset answers to, read from its own files. | | `settings:` | Typed per-asset settings (below). | | `inspector:` | The interface people use for the type and its assets (below). | | `preview:` | How an asset is pictured (below). | | `references:` | Names of other assets the type's files carry (below). | | `indexing:` | What search reads for each asset (below). | | `describe:` | How a missing description is generated (below). | ### The files an asset holds Each entry under `files.required` or `files.optional` is `{ path, kind: file | folder, one_of_group?, content? }`. `*` in a path matches within one segment. Entries that share a `one_of_group` are satisfied by any one of them. `content` lists checks on the file's bytes: | Check | Passes when | |---|---| | `non_empty` | the file has content | | `json_field { key, type?, non_empty?, accept? }` | the JSON holds the key (a dotted path) with that shape | | `yaml_field { key, type?, non_empty?, accept? }` | the same for YAML | | `described { keys?, headings?, message? }` | the file says what the asset is (see "Ask your assets to say what they are") | Each check takes a `message`, which is what the author is told when it fails. ### Settings `settings: { values, schema: { type | instance, export? } }` gives every asset typed settings. `values` names the file an asset's values live in; `schema.type` declares one schema for the whole type, and `schema.instance` names a file each asset declares its own in. `asset.create` writes the resolved values, and a write to the values file reaches `onChange` with what changed. ## The human side (`inspector.luau`) A type is used by people through its Inspector, and without one the type is usable only from code. The Inspector is the type's interface for a person: for a procedural graph it is the graph editor, for a kit it is the tracking view of what the kit holds and what is still missing. Writing it is part of writing the type. `inspector: { type, instance? }` in `type.yaml` names the files. `type` is the interface for the type itself and for its assets; `instance` names a file an asset may ship to add its own. Each returns: ```luau return { sections = { { id = "graph", title = "Graph", build = function(ctx) ... end } }, replace = { contents = { ... } }, -- replace a default section by id order = { "graph", "contents" }, -- section order } ``` `build(ctx)` receives the asset and builds the section. A section's `title`, and the text its rows carry, is a string or an `i18n.text` value read from a catalog (`i18n.text("inspectors.mesh.title")`), which follows the editor's language. `asset.create("assetType", ...)` scaffolds a working `inspector.luau` to start from. `asset.validate` on a type that names no inspector, or names one that does not load, reports it. ## Say what your type is for (`about.yaml`) Every type carries an `about.yaml` that says what the type is for, in three plain-language texts: ```yaml intent: "Sets the typeface of the text in your game: UI, labels, signs and 3D lettering." function: "A font, from a TTF, OTF or WOFF file, made available to all of Zero's text, including 3D text." usage: "You choose it by name for your UI or your text, and the text appears in that typeface." ``` - **`intent`** is what the type is for in someone's game, in the words a game maker uses. Up to 800 bytes. - **`function`** is how it works today: what an asset of it is made of and what the engine does with it. Up to 1500 bytes. - **`usage`** is what a person or an agent does with one. Up to 1200 bytes. Write about the type as a whole, not one asset of it, and say what it does now. Agents read these texts to learn when to reach for the type and how; people searching find the type by them. The scaffold starts each text with `[[describe]]` and a note on what to write; a text that still starts that way counts as not written. `services describe` can write them. They show up in `asset.inspect` as `detail.about`, in `assetTypeRef:getAbout()`, at the end of the type's `types/<typename>` guide, and at the top of the type's Inspector. ## Ask your assets to say what they are A type can require each asset to carry a description: a file, written by the author or generated, saying what the asset is and what it is for. Declare it with a `described` check: ```yaml files: required: - path: "README.md" kind: "file" content: - { check: "described", message: "Say what this widget is for and where it goes." } ``` A file that is missing, empty or still has a line starting with `[[describe]]` fails the check, and so does a YAML file whose named `keys` are missing or over their `max_bytes`, or a Markdown file missing a named heading. `asset.validate` names the asset, and a push that carries it is refused with `message`. `services describe` finds such assets and writes their descriptions. `describe:` steers what is generated: ```yaml describe: guidance: "Say what the widget shows, what input it reacts to, and where it fits in a UI." examples: - "<identity of an asset of this type whose description reads well>" ``` An example is an asset of your type whose description is a true, written one, never a placeholder and never the asset being described; with none, leave `examples` empty. A type whose assets the model cannot perceive (a sound, a motion) says so in `guidance`, and the description is drawn only from what the asset's own files state. Start the file unwritten in your `template/`: a heading and one line starting with `[[describe]]`, never example content, which every new asset would carry verbatim. A type whose assets say what they are through their own content (a mesh, a texture) declares no check. ## The type's code (`behavior.luau`) `behavior.luau` returns one table. These are the keys the engine reads from it; anything else on the table is the type's own. ### What the type's assets can do | Key | Shape | What the engine does with it | |---|---|---| | `ref` | `{ [name] = function(self, ...) }` | Every function becomes a method on every asset of the type: `ref:name(...)`. | | `modules` | `{ [name] = require(".x") }` | Code the type's assets reach with `asset.containing(__FILE__).modules.<name>`. | | `events` | an events schema | Events an asset fires. Readers subscribe through `ref.events.<name>:connect(...)`; the type fires them. | | `refShapes` | `{ [method] = function(self) -> (typeExpr, source?) }` | The result type of a `ref` method for one particular asset (below). | | `namePattern` | a Lua pattern | The names `asset.create` accepts for the type's assets. Default `^[A-Za-z][A-Za-z0-9_]*$`. | | `derive` | `{ output, module, compute, fingerprint, matches?, required?, timeout? }` | A file computed from the asset when it is committed; a `required` one holds the commit until it lands. | Some `ref` names mean the same for every type, and the engine calls them: - **`instantiate(self, target?, opts?) -> (root, idMap)`**: puts the asset in a scene. Defining it is what makes the type scene-instantiable. Its return is a contract (below). - **`inspect(self) -> detail`**: what `asset.inspect` reports for the asset beyond the common record (below). - **`preview(self, opts)`**: renders the asset's picture; it wins over the type's `preview:` recipe. - **`previewMaterial(self) -> { material }`**: the material a `surface` preview paints. - **`saveDefinition(self)`**: writes the asset's in-memory edits back to its files in edit mode. Some names are answered for every asset before the type is asked, so a `ref` entry of the same name is never reached: `getSource`, `getBytes`, `getText`, `exists`, `deps`, `canInstantiate`, `canPreview`, `preview` (which calls yours when you define one), `meta`, `runtime`, `events`, `typeRef`, `modules`, and the residency flags `has_backing_asset`, `has_runtime_changes`, `cpu_resident`, `gpu_resident`. ### When the engine calls the type | Hook | Signature | When it runs | |---|---|---| | `onCreate` | `(name, opts) -> { [path] = contents }` | On `asset.create`. Returns the files of the new asset, laid over the type's `template/`. Annotate `opts`: its type is the schema `asset.create` checks the caller's arguments against. A `""` key writes a single loose file. | | `onReplace` | `(dest, files) -> files` | On an `asset.create` over an asset already at `dest`, after `onCreate`, so what the author added can be carried into the replacement. | | `onRegister` | `(self)` | Once per asset, when it first registers: when the world loads, on a live `asset.create`, and when an asset arrives later (installed, pulled, synced). This is what makes an asset take effect the moment it is written. | | `onChange` | `(ref, change)` | On every write to a file inside an asset of the type. `change` is `{ path, asset, type, kind, origin }`, plus `settings` and `settingsChanged` for a write to the settings values file; `kind` is `edited` or `seeded`, `origin` is `local` or `remote`. Filter on `change.path`. Writes to one asset arrive in order, each after the hook for the one before has finished, and the hook may wait on what it reads. A write the hook makes inside its own asset arrives later like any other, so keep the hook convergent. | | `onDependencyChange` | `(ref, change)` | When a module the asset's code requires is re-run, or a name the asset carries starts resolving. `change.kind` is `dependency`. | | `onDelete` | `(ref)` | When an asset of the type leaves the world: deleted, or the world it is in is swapped away. | | `validate` | `(ref) -> { { code, message, severity?, path? } }` | On `asset.validate`, after the `type.yaml` checks, for the type's own rules. `severity` defaults to `error`. Runs on every push, so a type's rules hold at publish. A hook that fails reports `validate.hook_failed`. | ### Settings hooks | Hook | When it runs | |---|---| | `settingsDefaults(name, opts, asked) -> table` | Once per `asset.create`, for values the schema's defaults do not give. | | `settingsCorrections(values, name, opts) -> (corrections?, reasons?)` | On every settings write. A correction to a field the writer named refuses the write, giving the reason. | | `settingsDerivedDefaults(values, explicit, changed)` | On a settings write, for fields derived from others. | | `normalizeSettings(values, stored?)` | On every read and write, to map an earlier spelling of a field to the current one. | | `settingsHealed(values, stored)` | On a read, to repair stored values. | | `settingsSchemaProblem(schema, ref) -> string?` | When an asset's own schema is read; a returned string refuses the schema. | `creationInputs` (`{ [opt] = true | selectorOpt }`) names `asset.create` options that are inputs to the type rather than settings. ### Reloading An edit to `behavior.luau` reaches existing assets with no restart. ## How an asset is pictured (`preview:`) | `kind` | The picture is | The type provides | |---|---|---| | `instantiate` | the asset placed in the preview studio through its `instantiate` | `ref.instantiate` | | `image` | a file the asset holds, fitted to the frame | `source: { files }`, the candidate files in order | | `surface` | the asset painted on a mesh | `mesh`, and `ref.previewMaterial` | | `custom` | whatever `ref.preview` returns | `ref.preview` | ```yaml preview: kind: surface mesh: sphere ``` `angle: [yaw, pitch]` turns the camera. The studio owns the light, the backdrop and the framing, so an asset pictures the same in every world. A type with no `preview:` that defines `instantiate` still answers `ref:preview()`. A picture is rendered when something asks to view it (the editor showing the asset, `ref:preview()`), when previews are generated on request (`assets.generatePreviews`), and when the asset is staged. An edit alone renders nothing. The picture records what it was made from, so a stale one is told from a current one. ## The names your type's assets hold (`references:`) Where your type's own format or API carries the name of another asset, declare it here: ```yaml references: keys: # a top-level key of the type's files that holds a name, or a table of them - { key: "shader", type: "shader" } args: # an argument of a call, counting from 1 - { call: "g:node", position: 2, type: "procNode" } fields: # a field of the options table a call takes - { call: "fx.beam", field: "material", type: "material" } ``` `type` is the category the name resolves in. `asset.declareReferenceKey`, `asset.declareReferenceArg` and `asset.declareReferenceField` declare the same from a script. ## What search reads (`indexing:`) `indexing:` is how assets are found. Search reaches an asset only through what its type's `indexing:` names, and adds nothing of its own. That includes you: an asset indexed badly is one you cannot find later, when you are making something else and need it. A type whose assets are never looked for says `indexing: none`. ```yaml indexing: data: # text, read from the asset's files - role: identity extractor: verbatim source: { file: "README.md" } - role: interface extractor: symbols source: { files: ["init.luau"] } - role: implementation extractor: verbatim source: { files: ["init.luau"] } content: # the picture - role: identity modality: image source: { file: "preview.png" } facets: # what a query filters and re-ranks by file: ".metadata" rigged: { type: bool, from: { components: { contains: SkinnedModel } } } roughness: { type: number, filter: range, from: { file: "mat.yaml", field: "floats.roughness" } } ``` **Roles.** Each `data` and `content` entry has a `role`, and a query matches in two slots: - **`identity`**: what an asset is. For anything you look at, the picture; for anything else, the text that says what it is. - **`capability`**: what it does and how it is made. `interface` (the signatures or shape a caller uses) and `implementation` (the body) both count as capability, and a type with code usually declares both. Ask what a person would recognise an asset of the type by, and what it does, and point each role at the file that says it. For text, that is the asset's description: the file your template starts with a `[[describe]]` block, which the author writes or `services describe` fills in (see "Ask your assets to say what they are"). **`data`.** `extractor: verbatim` embeds a file's text as it is; `symbols` embeds the declared signatures of code. `source` is `{ file }` or `{ files: [...] }`. Never index a file name (`source: { field: name }`): one or two words carry nothing to match. **`content`.** `modality: image` embeds the picture itself, so a text query matches what the asset looks like. A type whose assets are looked at makes the picture its identity. **`facets`.** What a query narrows and re-ranks the matches by. `file` is embedded whole, so keys nobody declared in it are still found. Each further key is computed for every asset and states a value for every one, including `false`: a file can imply "not rigged" but never say it, and a query separates rigged from unrigged only because the unrigged ones say `rigged: false`. A key is `{ type: bool | number | enum, filter?: range, from }`, where `from` is `{ file, field }` (a field of one of the asset's files, dotted for nesting), `{ metadata: key }`, or `{ components: { contains | any_outside } }` (what the asset's entities carry). ## What blocks a push A push checks every asset it carries against its type. These refuse it: - a required file that is missing, a `content` check that fails, a `described` file not written yet; - an error from the type's `validate`. Unlisted files and warnings do not. A `described` file blocks only a push that changes the asset. When a push is refused, the message names each asset and what it lacks. `world.publishBlockers()` and `zm status` read the same list without pushing. ## Typing a result from the asset (`refShapes`) A `ref` method whose result depends on the asset (one entry per child folder, per row of a config, per control a map declares) can only be annotated as `{ [string]: Thing }`, which accepts any key. `refShapes` states the result for each asset instead: a function returning a Luau type expression for that asset, and the module whose types the expression uses. Read the asset; never run it. ```lua -- inputMap.assetType/behavior.luau M.refShapes = { activate = function(self): (string, string) local names = {} for _, control in ipairs(M.ref.controls(self)) do table.insert(names, control.name .. ": Handle") end if #names == 0 then return "", "" end return "{ " .. table.concat(names, ", ") .. " }", "@builtin::modules.zinput.scheme" end, } ``` With it, `map.jump:onPressed(fn)` is checked and `map.noexisting` is reported. A per-asset type applies where the call site names which asset: a component field whose default names it, or an annotation `AssetRef<"inputMap", "<identity>">`. `asset.resolve(name, category)` carries only the category, and a name computed at runtime carries nothing, so calls on those keep the declared return. The type belongs to the call's result: index it there, or bind what you need from it there, and the names stay checked. `require("@builtin::assetTypes.assetType.shared.refShapes").published()` shows what was published: `categories` (each type's method surface) and `returns` (per-asset results by identity, then method). An identity missing from `returns` was never published. Results are recomputed when an asset is written; at most 64 assets of one type are read. ## Putting an asset in a scene (`ref.instantiate`) A caller writes one piece of code against every instantiable type, so what `instantiate` returns is fixed: ```lua local Instantiable = require("@builtin::assetTypes.assetType.shared.instantiable") M.ref = { instantiate = function(self, target, opts) local root = Instantiable.root(self, target, opts) -- compose the asset under `root`, now return Instantiable.result(self, root, idMap) end, } ``` **In.** `target` is the entity the asset lands under, or onto for a hierarchy type; with none, the type spawns a new root. `position`, `rotation` (three numbers in degrees, or a quaternion), `scale`, `name` and `temporary` mean the same for every type: `Instantiable.root` applies them to a root you make, `Instantiable.place` to one you adopt. Document any options of your own in the hook's `--!arg` docs. **Out.** `(root, idMap)`. `root` is the composed root, live when you return: build synchronously, never defer to a component's `awake`. `idMap` maps each original id to the spawned one, so a component that composes the asset again on every load can pass it back in and keep references into the composition. Every call goes through `Instantiable.result`, which refuses a root that is not live and turns a missing `idMap` into `{}`. ## Inspecting an asset (`ref.inspect`) `asset.inspect(ref)` builds a record every asset shares (`identity`, `name`, `guid`, `source`, `typeName`, `typeDefinitionPath`, `scope`, `origin`, `description`, `tags`), then calls `ref.inspect(self)` for the type's own `detail`: ```lua M.ref = { inspect = function(self) -- read the asset's own files, never runtime state: inspect works on an asset -- that has not been compiled, uploaded or registered return { --[[ what makes this asset what it is ]] } end, } ``` Without it, the record is the shared part alone, and an agent inspecting the asset learns nothing of what it is. A hook that raises leaves `detail` empty and sets `record.warning`. ## Discovery - `asset.list("assetType")`: every registered type. - `asset.inspect("<typename>")`: the type, its README and its `about.yaml` texts. - `asset.resolve("<typename>", "assetType")`: the type itself.
▲ 0↑ born
·
assettype · born here
❒asset
# Component (asset type) A component is a reusable behavior + data unit attached to an entity. The component file declares public fields, methods, and lifecycle callbacks; the engine instantiates one per attachment and drives its hooks every frame. Components are the primary unit of gameplay code — movement, AI, animations, UI panels, network sync, and per-entity state all live here. ## When to use one - You need per-entity state that survives across frames. - You need per-entity behavior driven by engine lifecycle hooks (`start`, `update`, `onDestroy`). - You want to expose configurable fields to designers / `entity.spawn` callers / scenes without code changes. If you need a stateless pure-function library, use a `.module`. If you need to generate content declaratively, use a `.service`; compute work belongs in a `.computeShader`. ## Where it lives - Source: `/zero/source/.../<Name>.component/` - Identity: `<Name>` (the `.component` suffix strips from the identity, but the folder retains the suffix on disk). - Folder shape: - `init.luau` (or `init.lua`) — declares the component. **Required.** - `README.md` — instance-level documentation. **Required.** - `.metadata` — agent-editable tags + free-form fields. **Required.** The structural contract is enforced by `asset.validate` against this type's `type.yaml`. ## How to create one Always start with the scaffold — it guarantees the folder shape matches `type.yaml` from the moment it's on disk: ```luau asset.create("component", "<Name>") -- Creates: /zero/source/<Name>.component/ -- init.luau (canonical declare + public block + hooks stubbed) -- README.md (instance README template) ``` After scaffolding, edit `init.luau` to fill in the actual fields and behaviour. The component registers as soon as the file is written — hot-reload is automatic; no engine restart required. ## How it operates 1. **Registration.** Writing `init.luau` into a `.component/` folder indexes the asset, mints a guid (in the `.meta` sidecar), and surfaces the type to the engine's component registry. Same-frame visible to `entity.component.add`. 2. **Attachment.** `entity(id).component.add(name, data)` (or the batch form `tools.use("entityOps", "addComponents", targets, { [name] = data })`) attaches an instance. The `data` table's fields override the component's declared defaults; omitted fields take the declared default. The `data` values are copied into `public.*` BEFORE `awake()` runs. 3. **Lifecycle.** The hooks run in this order: - `awake()` — same frame as attach, immediately after the data copy. Initialise state, set up native bridges, register with other systems. Other components on the same entity may not have awoken yet. - `start()` — the next frame. Every component on the entity has completed `awake()` by then, so cross-component setup is safe here. - `update(dt)` — same frame as `start()`, then every frame after, for as long as the gameplay clock is running. `fixedUpdate(dt)` runs once per physics step, straight after it, with the step's `dt`, so a frame can run it several times or not at all; `editorUpdate(dt)` runs while the clock is held. Which of them ticks is decided by `engine.mode` AND `engine.paused` together — see **Per-frame hooks and the two axes** below, and `man modes`. - `onDestroy()` — when the component is removed via `component.remove` or when the owning entity is despawned. Release resources, drop native ECS components. For the full list (`onEnable`, `onDisable`, `fixedUpdate`, `editorUpdate`, `onPropertyChanged`, `onAssetReload`, `onModuleReload`, `onBeforeSave`, …) and the timing details, **read `man components` — that is the canonical lifecycle reference. Generic component patterns (declare blocks, public fields, sync, ECS bindings, typed methods) all live there.** 4. **Public surface.** Fields declared in `public` are inspectable, editable in the inspector, and persist with the entity. Methods are declared on that same table with a colon — `typed function public:method(args)` — and every one of them takes the component ref as `self`, so a caller invokes it with a colon too: `entity(id).component.get(name):method(args)`. That is the one calling convention a component ref answers to: the reflection methods `ref:fields()` / `ref:getField(name)` / `ref:setField(name, value)` take the same spelling. A function the chunk declares at file scope (`function helper()`) is the component's own, reachable from its hooks under its bare name; `public` is what the ref carries. 5. **Settings and the Inspector card.** `type.yaml` names the component's settings schema as `settings: { schema: { instance: "init.luau", export: "public" } }`: the `public` table IS the schema, and its values live on each entity the component is on, so `asset.schema(componentRef)` answers the Field descriptors and no values file exists. On an entity the Inspector shows the component as a card whose generic `settings` section edits those fields as typed controls, each edit checked against the schema and written to the live component as one undoable operation. `type.yaml` also names `inspector: { instance: "inspector.luau" }`: a component that ships an `inspector.luau` beside its `init.luau` shapes its card — the file returns `{ sections, replace, order }` (see `assetTypes/README.md`, "`inspector:`"), each section's `build(ctx)` reading `ctx.component` (the live component) and `ctx.selection.id` (the entity). `SceneModule.component/inspector.luau` replaces `settings` with the bound module's declared inputs. 6. **Events.** An `events` block declares typed moments the component fires from inside — `events = { onHit = Event({ dmg = Field.number(0, NoSync) }) }`. The owner fires with `events.onHit:fire({ dmg = 10 })`; outside code subscribes through the proxy's subscribe-only facade, `entity(id).component.get(name).events.onHit:connect(fn)` (`:once` / `:wait` too). Pass `Sync` as the event's second argument to replicate a fire to other peers. Events let one component react to another's moments without polling. Full reference: **`man components`**, Events section. 7. **Hot reload.** Editing `init.luau` reloads the component definition; live instances are reconciled with the new declaration in-place, and each crosses one lifecycle boundary: `onDestroy()` ends the running life, then `awake()` and `start()` construct the one that replaces it, and `update()` resumes on the next frame. `public` and `private` values carry across; module-level `local`s belong to the chunk, so the new life starts with them at their initial values and its `awake`/`start` are what fill them in. Whatever the old life handed elsewhere — a subscription, a shared registration, a spawned entity — is released in `onDestroy`, the call that pairs with the construction about to run. An edit that leaves the source byte-identical crosses no boundary at all. A field carries its value across when something stated it: a key of the `data` table the instance was attached with (a scene record's data is that table), or a write made since. Every other field takes the edited source's declared default, so changing a default reaches every instance that left the field to it. An instance that states its own value for a field whose default the edit changed keeps that value, and the reload logs a `[HotReload]` warning naming the field, the entity, the value kept and both defaults. ## Discovery - `asset.list("component")` — every registered component (engine + world + libraries). - `asset.inspect("<name>")` — identity, scope, public fields, lifecycle methods, source path, and this type README. `detail` carries the component's declared `fields`, `methods`, and `events`, parsed from its source — `tools.use("assets","describe", "<name>")` renders it as markdown, so a component's events are visible without opening its source. - `ls /zero/source/<Name>.component` lists the files the folder holds. - `entity(id).component.list()` — components attached to an entity. ## Per-frame hooks and the two axes `engine.mode` (`"edit"` / `"play"`) and `engine.paused` (the gameplay clock) are independent, and the per-frame hooks read them separately: - `update(dt)` / `fixedUpdate(dt)` tick while **the gameplay clock is running** — whichever mode the engine is in. - `editorUpdate(dt)` ticks while **the clock is held** — because the mode is `edit`, or because play is paused — and also alongside `update` whenever edit is running. Which gives four states, and this table is the contract: | `engine.mode` | `engine.paused` | hooks that tick | |---|---|---| | `edit` | `true` | `editorUpdate` | | `edit` | `false` | `update`, `fixedUpdate`, `editorUpdate` | | `play` | `false` | `update`, `fixedUpdate` | | `play` | `true` | `editorUpdate` | Entering edit sets `paused = true` and entering play sets it back to `false`, so a session that never writes `engine.paused` only ever sees rows 1 and 3 — which is where the shorthand "`update` is the play tick, `editorUpdate` is the edit tick" comes from. It is the two default rows of a four-row table, not the rule. **Row 2 is the one that surprises.** With `engine.paused = false` in edit — set by hand, or by a tool that advances the gameplay clock to sample it, such as a `capture.collage` given a `duration` — `update` and `editorUpdate` both fire, once each, every frame. A component that declares both and routes them to one body therefore runs that body **twice per frame**: ```luau local function drive(dt) ... end function update(dt) drive(dt) end function editorUpdate(dt) drive(dt) end -- twice per frame in row 2 ``` Nothing reports the doubling; it reads as an animation running at twice its intended speed. To get exactly one tick per frame in every row, ask which axis you meant and answer it in the body: ```luau function update(dt) drive(dt) end function editorUpdate(dt) if engine.paused then drive(dt) end end ``` A scene `entrypoint.luau` declaring the same two hook names is dispatched by the scene loader, not by this table: there `update` needs play AND running, `editorUpdate` needs edit, and play-paused ticks neither. Read `man scenes` before carrying a component's rule to an entrypoint. ## Authoring conventions - Annotate public fields with `--!desc` so the inspector + LSP show documentation alongside the field name. - Declare lifecycle hooks (`start`, `update`, `onDestroy`) explicitly rather than relying on engine defaults — readers can see at a glance what runs when. - Keep `update(dt)` cheap — it runs every frame per instance. Move heavy work to `start`, to a `.computeShader`, or behind a job (`man jobs`). - For multi-entity batching, prefer `tools.use("entityOps", "addComponents", targets, components)` over a loop of `entity(id).component.add` — it takes many targets and many components in one call. ## Common pitfalls - **Naming.** The component identity is the folder stem with `.component` stripped (e.g. `<Spinner>.component/` → identity `Spinner`). Don't repeat the suffix in the identity passed to `component.add`. - **`init.lua` vs `init.luau`.** Either is accepted (it's a `one_of_group: "entrypoint"`), but `.luau` is canonical. Mixing both in one folder is invalid. - **`update` in edit mode.** It runs whenever the gameplay clock is running, and entering edit stops that clock — so `update` is idle in a freshly-entered edit session and ticks again the moment anything sets `engine.paused = false`. Use `tools.use("wld", "play")` to test update logic under the mode it ships in; `tools.use("wld", "edit")` to return. See **Per-frame hooks and the two axes** above. - **Renaming.** Renaming the folder changes the identity. References to the component are recorded against the component itself, so renaming or moving it does not break them. ## Related types - `.module` — pure-function library, no per-entity state. - `.service`: a declarative content generator, no per-entity state. - `.preset` — a captured component configuration, replayable into `component.add` without re-typing fields. - `.bundle` — entity hierarchies that may carry component attachments as part of the bundle. ## In the Inspector Fields: its execution order, hooks, and how many methods and events it declares, then the fields its `public` table declares as read-only typed controls holding their defaults, with **Check** and **Open** for its entry file. Instances: a link to every entity carrying it. What its card shows on an entity comes from the component's own `inspector.luau`.
▲ 0↑ born
▣
module · born here
❒asset
# luau_introspect (module) Parses Luau/asset source TEXT into structured declarations. Pure string/pattern parsing (`string.find` / `string.match` / `string.gmatch`) over the literal source — no compiling, no VM spawn, no runtime state, no engine FFI. Given source text, it extracts what is written in the file. This is the shared parser every per-assetType `M.ref.inspect` hook uses to turn a component/module/tool's own source into the structured record `asset.inspect` returns. ## Exports - `docstrings(src) -> DocMap` — scans `--!desc` / `--!arg` / `--!return` / `--!example` comment runs and binds each run to the name of the declaration on the next non-comment line (the identifier after `function`, `public:`, `local function`, or `M.`). - `publicFields(src) -> { FieldEntry }` — parses `public = { name = Field.<kind>(default, mode), ... }` table-literal entries and module-scope `public.<name> = Field.<kind>(...)` assignments. - `events(src) -> { EventEntry }` — parses `events = { name = Event(payloadSchema?, syncMode?), ... }` table-literal entries. - `methods(src) -> { MethodEntry }` — parses `function public:<name>(...)` / `typed function public:<name>(...)` declarations (params + optional return type). - `lifecycleHooks(src, catalog) -> { string }` — top-level `function <name>(` declarations whose name is in the caller-supplied `catalog` array. - `moduleExports(src) -> { ExportEntry }` — parses `M.<name> = function` assignments, `function M.<name>(...)` declarations, and a trailing `return { foo = foo, ... }` export table. - `forSource(src, computeFn) -> any` — memoises `computeFn(src)` keyed on `src` itself in a module-local table. The same source text returns the cached result without re-running `computeFn`; different source text recomputes. Keyed on the source content (not an asset checksum) because composite/container assets (component folders, scene folders, etc.) all hash to the empty-string checksum — a checksum-keyed cache collapses every such asset's detail onto whichever one was inspected first. ## Usage ```luau local Introspect = require("modules.luau_introspect") local src = self:getInitScript() local detail = Introspect.forSource(src, function(s) return { fields = Introspect.publicFields(s), events = Introspect.events(s), methods = Introspect.methods(s), hooks = Introspect.lifecycleHooks(s, lifecycleCatalog), } end) ``` ## Notes - Every function is a pure string→table transform: same source text in, same structured table out, every time. No reads of live component state, no entity/world queries. - Structural scanning runs over a comment- and string-aware **mask** of the source (a same-length copy where comment bodies and string-literal contents are blanked to spaces, delimiters and newlines preserved). Pattern matches and brace/paren balancing run on the mask — so a brace, `Field.`, `Event(`, or a whole entry that appears inside a comment or a string literal never registers — while captured values are sliced from the original source at the same (aligned) indices. This makes the parser robust to apostrophes in comments, commented-out entries, string defaults containing `}` / `Field.` / `Event(`, and `[[ ]]` long strings. - `default` / `category` are raw trimmed source-text slices (with any trailing comment stripped), not evaluated values. - For a **ref constructor** (`Field.assetRef` / `dataRef` / `resource` / `componentRef`) the FIRST positional argument is the category / contract / componentType selector, captured under `category`; the SECOND argument is captured under `default`. - For every **other** Field kind the first argument is the `default` and `category` is nil. - A trailing `Sync` / `NoSync` identifier is captured as `sync`, tolerating a trailing comma or a trailing comment after the last argument. - Field/Event entries whose key is a computed or indirect expression (`[expr] = Field.number(...)`) are omitted — only literal identifier keys are recognised. - `methods` captures a `...` variadic parameter (as `name = "..."`), with its `: <type>` annotation when present. - A `--!desc` written above a field/event declaration (`<name> = Field.<kind>(...)` / `<name> = Event(...)`) or a `public.<name> =` assignment binds to that name in `docstrings`, and is folded into the corresponding `publicFields` / `events` entry's `desc`. - `lifecycleHooks` never hardcodes the lifecycle-callback catalog; the caller passes the list of names to match against. - `forSource`'s memo is bounded (oldest-key eviction) so a long session touching many distinct asset versions can't grow it without limit.
▲ 0↑ born
▣
module · born here
❒asset
# assetType.shared.ref Builds the metatable every `AssetRef` (the `{ __ref, type, name, guid, identity, path }` envelope returned by `asset.resolve` / `asset.ref`) carries. Replaces the per-call C metatable that used to live in `crates/zero_scripting/src/ffi/bindings/asset.rs::attach_asset_ref_metatable`. ## Public API ```lua local assetRef = require("@builtin::assetTypes.assetType.shared.ref") -- Called by the Rust factory (push_asset_ref_handle) via -- _G.__build_asset_ref_proxy after the envelope fields are set. assetRef.build(envelope) -- attaches AssetRefMT, returns the table ``` The module exposes no invalidation surface — discovery is registry-driven and hot-reload is transparent (see "Discovery and hot-reload" below). ## Method dispatch order `ref.foo` is resolved in this order: 1. **Default methods** — `getSource` / `getBytes` / `getText` / `exists` / `inspect` and the lazy `meta` property. Per-type definitions cannot override these (engine contract from gh#1889). 2. **Per-type `ref` table** — discovered through `asset.resolve(<typename>, "assetType")` + `require(<identity>.behavior)`. The lookup resolves to whichever `<typename>.assetType/` folder is currently registered for the typename (built-in, user, or library-vendored) and pulls its `ref` methods. 3. **Nil** — unknown key, same shape as the original C metatable. ## Adding methods for a new asset type Drop a `behavior.luau` into the type folder: ``` src/lua/lib/assetTypes/<typename>.assetType/ ├── type.yaml -- structural spec (existing) ├── behavior.luau -- ref + global behaviour (new) └── template/ -- placeholder body (existing) ``` `behavior.luau` returns: ```lua return { ref = { --!desc Per-instance method on every `<typename>` AssetRef. myMethod = function(self, ...) ... end, }, global = { -- Reserved for the asset.<typename>.* surface — not consumed -- yet; included so the contract from gh#1889 lands cleanly. }, } ``` Within `ref` methods, `self` is the AssetRef envelope: `self.path`, `self.identity`, `self.guid`, `self.type`, `self.name` are available. Engine-required fields (`guid`, `path`, `identity`, `type`) must not be redefined. ## Discovery and hot-reload Type discovery uses the asset registry, so it doesn't matter where a `<typename>.assetType/` folder lives — engine built-ins under `@builtin::assetTypes.<X>`, user types dropped under `/zero/source/<X>.assetType/`, or types vendored inside an imported library all resolve identically. The dispatcher walks `asset.resolve(<typename>, "assetType")` → canonical identity → `require <identity>.behavior` on every miss; the asset registry is the cache for the resolve half and Luau's `_LOADED` is the cache for the require half. Hot-reload is transparent. When a `<typename>.assetType/behavior.luau` is rewritten through VFS, the engine's `invalidate_require_cache_for_state` re-runs the module and mutates the cached `_LOADED[<identity>.behavior]` table in place. Dispatch reads `mod.ref` on every access (rather than caching a sub-pointer), so existing AssetRefs see the new methods on the very next access — no Rust-side hook into this module is needed, and no invalidation API is exposed for callers to call. The same registry-driven path also handles type **registration** correctness: dropping a new `<typename>.assetType/behavior.luau` updates the asset registry, the next `asset.resolve(<typename>, "assetType")` returns the new ref, and AssetRefs of that type immediately gain the new methods. ## Why Luau, not Rust The asset surface needed per-category behaviour (`material:getProperties()`, `bundle:instantiate(entityId)`, `tool:run(args)`) and the old shape couldn't grow without an FFI change per method. Owning the proxy in Luau means: - Type-specific methods ship as content (the `<typename>.assetType/` folder), not engine code. - Adding a new asset type drops in a new folder; no Rust rebuild. - Methods can call any other Luau global (`vfs`, `asset`, `Material`, `entity`, etc.) directly, instead of going through narrow FFI primitives. ## Consumers - `crates/zero_scripting/src/ffi/bindings/asset.rs::attach_asset_ref_metatable` — the Rust factory that pushes envelopes invokes `_G.__build_asset_ref_proxy` once per push. - Every Luau call site of `asset.resolve` / `asset.ref` / `entity(id).component.X.material` / any binding declared `AssetRef<...>` — they all receive envelopes built through this module.
▲ 0↑ born
▣
module · born here
❒asset
# yaml.module YAML decode + encode for authored engine content. Pure Luau, no engine dependencies — a general parsing library, not data-system plumbing. ```luau local Yaml = require("@builtin::modules.yaml") local doc = Yaml.decode(vfs.read(path)) vfs.write(path, Yaml.encode(doc)) ``` ## Supported subset - Block mappings (`key: value`) and block sequences (`- item`), nested to any depth. - Compact sequence-of-mapping entries (`- path: x` / ` kind: y`). - Flow collections — `{ a: 1, b: 2 }` and `[1, 2, 3]` — single line. - Plain scalars with type inference: `~` / `null` → nil, `true` / `false` → boolean, numeric literals → number, everything else → string. - Single- and double-quoted strings (`''` escapes a literal quote inside a single-quoted string; `\n` `\t` `\r` `\\` `\"` inside a double-quoted one). A quote opens a quoted scalar where a scalar begins — after `key:`, after a `- ` entry marker, or inside a flow collection — so a plain scalar carries an apostrophe as data (`note: the world's rules`). Quoted keys are read in flow mappings. - `#` comments — honored outside quotes, so a `#` inside a quoted string is kept as data. - Literal (`|`) and folded (`>`) block scalars, with a chomping indicator (`-` strips the final newline, `+` keeps every trailing blank line, none keeps one newline) and an indentation indicator (`1`-`9`: the content's indent past the parent's), in either order (`|-`, `>+`, `|2`, `>1-`). A block scalar's content is literal text: quotes (balanced or not), `#`, `key: value` and `---` inside it are data. - An optional leading `---` document marker. ## Loud-error contract Constructs outside the subset above raise instead of misparsing: anchors/aliases (`&`, `*`), tags (`!`), directives (`%`), multi-document streams (a second `---`), a block-scalar header it cannot read (`|x`, `|-+`, `|0`), tab indentation, and inconsistent indentation (both block structure and block-scalar bodies). Every error carries the offending line number (`yaml: line N: ...`), so a bad config points straight at the line to fix. Tab indentation is rejected everywhere — including block-scalar body lines whose leading whitespace contains a tab. A tab after the first non-space character of a line is content and passes through. ## API - `Yaml.decode(text: string): any` — decode a YAML document into a Luau value (table, scalar, or nil for an empty document). Raises on malformed input or an unsupported construct. - `Yaml.decodeWithComments(text: string): (any, boolean)` — decode as `decode` does, and report whether the text carries a comment by the decoder's own rule: a `#` at a line's start or after whitespace, outside a quoted scalar and outside a block scalar. Re-encoding the value drops such comments, so an editor that writes a document back reads this first. - `Yaml.encode(value: table): string` — encode a Luau table as YAML (block style, two-space indent, alphabetically sorted keys). Raises on values YAML can't represent (functions, userdata, non-string mapping keys). A top-level empty table encodes to an empty document, which decodes back to `nil` (the YAML empty-document ambiguity).
▲ 0↑ born
▣
module · born here
❒asset
# json JSON encode/decode library for Luau. Encodes Lua values to JSON strings and decodes JSON strings back to Lua values. Used for communication with the Rust side of the engine, the VFS read/write bridge, and any wire-format that needs JSON. Pure Luau, no engine dependencies. Compact and pretty-printed encoders, plus a hand-rolled decoder that streams the input by position so it works under WASM as well as native. ## Exports - `Json.encode(value: any, indent?: string, currentIndent?: string) -> string` — compact encode. Functions / unknown types and NaN/Inf encode as `null`. - `Json.encodePretty(value: any, indentStr?: string) -> string` — pretty-printed encode with sorted object keys (diff-friendly). - `Json.encodeArgs(...: any) -> string` — encode varargs as a JSON array. - `Json.decode(str: string) -> any` — decode a JSON string. Returns the decoded value, or `nil` + error message on failure. ## Usage ```luau local Json = require("@builtin::modules.json") local widget = { type = "button", text = "Click Me" } local compact = Json.encode(widget) -- '{"text":"Click Me","type":"button"}' local pretty = Json.encodePretty(widget, " ") local decoded = Json.decode(compact) local v, err = Json.decode("oops") -- v = nil, err = error message ``` ## Notes - Object keys are sorted alphabetically in both encoders for consistent output across runs. - Numeric keys on objects are stringified at encode time (JSON has no numeric keys). Pure-integer key sets get detected as arrays via `isArray` and encoded with brackets. - NaN, +Inf, -Inf encode as `null` — JSON has no representation. Round trips through `decode` recover `null` (Lua `nil`), so they don't preserve. - Unicode `\uXXXX` escapes decode to UTF-8 by hand to stay WASM-safe. Only the BMP is covered; supplementary planes via surrogate pairs are not. - Functions encode as `null`. - Decode is character-streamed — no regex, no `string.match` patterns on the whole input — so the line-and-column information needs to be reconstructed from the position offset.
▲ 0↑ born
▣
module · born here
❒asset
# assetType runtime The machinery that reads a `<typename>.assetType/behavior.luau` and turns its declarations into live behaviour. A `behavior.luau` is a table of declarations — `ref` methods, `modules` shared code, an `events` schema, a `namePattern`, `refShapes`, and the `onCreate` / `onRegister` / `onChange` / `onDelete` / `validate` / `settingsDefaults` / `settingsCorrections` hooks. None of it runs itself. This is the code that runs it, and it lives here because reading a type's declarations is the **assetType type's own behaviour** — the same way `material.assetType` owns what a `.material` does. ## Sub-modules | Module | Reads | Responsibility | |---|---|---| | `ref.module` | `ref`, `modules` | Builds every `AssetRef` envelope, attaches the shared metatable, and dispatches per-type methods and shared modules onto it. Also owns edit-mode write-behind persistence. | | `create.module` | `onCreate`, `namePattern`, `validate` | Backs `asset.create`: resolves the type, checks the name against its pattern, runs `onCreate` (or clones `template/`), and writes the instance. `validate.module` beside it checks a creation `opts` table against the type's `createSchema`. Before running `onCreate`, resolves the type's settings chain (below) and hands the result to the hook as `opts.settings`. | | `settings.module` | `settings`, `settingsDefaults`, `settingsCorrections` | A type's declared settings schema and where its values live (`type.yaml`'s `settings:` block). `Settings.resolveForCreate` layers the schema's own defaults, the type's own `settingsDefaults(name, opts, asked)` hook (a DEFAULT the schema can't express — a name-derived convention, a fact read off a payload the caller handed it, a value following a field `asked` shows a higher layer naming; any later layer overrides it), the Preset Manager, an importer's settings, the caller's `settings` table, then the type's own `settingsCorrections(values, name, opts)` hook (a CROSS-FIELD CONSTRAINT the schema can't express, applied last over the fully merged values). A correction over a default/preset/importer value lands silently; a correction that would override what the caller's own `settings` table explicitly asked for refuses the creation instead, naming the field and why. Neither hook is ever handed a table to mutate; each returns what it wants changed (`settingsCorrections` may also return a `{ [field]: reason }` table for that refusal message). `Settings.cloneValues` deep-copies a values table — `create.module` hands `onCreate` a copy, never the table it stamps. `Settings.valuesOf` / `writeValues` read and write an asset's own values file. | | `typeYaml.module` | `type.yaml` | The folder a type lives in and its parsed `type.yaml`, decoded once per content version of the file. `settings.module` and `inspector.module` read their blocks through it. `about` / `aboutAt` read a type's `about.yaml` (`intent`, `function`, `usage`), leaving out any key that is empty or still starts with `[[describe]]`; `aboutRows` and `aboutMarkdown` lay the texts out for the Inspector and the `types/<name>` guide. | | `inspector.module` | `type.yaml`'s `inspector:` block | Which inspector a type declares for its assets (`inspector: { type: ... }` or `{ instance: ... }`), and the declaration that file returns — the sections it adds, the generic ones it replaces, and their order — or the problem that kept it from loading. | | `onRegister.module` | `onRegister` | Fires an instance's once-only registration hook — on arrival, on world load, and for `@builtin` library instances. | | `changeDispatch.module` | `onChange`, `onDelete`, `refShapes` | Routes a VFS source write or a folder delete to the enclosing typed asset's type hooks. | | `refShapes.module` | `refShapes`, `ref` | Publishes what every `AssetRef<category>` answers to, so a member read on an asset-typed value is checked against that category's real surface. | | `events.module` | `events` | The per-asset event runtime behind `ref.events`. | | `instantiable.module` | `ref.instantiate` | The instantiation contract an asset type opts into: `root` stands the root entity, `place` applies the base placement opts to one the type adopted, and `result` shapes the `(root, idMap)` every `instantiate` returns. Also registers the `sceneInstantiable` field-constraint validator. | | `declaration.module` | `type.yaml` | The type's decoded declaration, read once and held until a write inside an `.assetType` folder; what every question about a type as a whole reads. | | `previewRecipe.module` | `type.yaml` `preview:` | How an instance's `preview.png` is produced: which of the four recipes (`instantiate`, `image`, `surface`, `custom`) the type declares, and what that recipe needs. | ## Reaching it ```luau local rt = require("@builtin::assetTypes.assetType.shared") rt.ref.loadTypeBehavior("material") ``` Fields resolve lazily. The prelude requires the sub-modules directly, in dependency order (`ref`, then `changeDispatch`, `onRegister.install()`, `refShapes.install()`) — a table that required all six on load would take that ordering away from it.
▲ 0↑ born
backing path · modules/api/engine/physics.module

Problems

Everything affecting this asset right now: its own problems, anything wrong inside it, and problems on its direct dependencies.

These counts cover only the parts this page shows. Problems on the parts it leaves out are not counted here.

3+problems

Inside

3 problems across 1 item
●
dep.unresolved · L7402
could not resolve `Constraint`
●
dep.unresolved · L7420
could not resolve `Constraint`
●
dep.unresolved · L7421
could not resolve `Constraint`
⌬ZeroMind agent review · awaiting first pass
Findings
Reviewer findings (handle · model · tag · quoted note) appear here once the per-pass review log lands. Today only the rolled-up agent_score is exposed.
usability—
did it work as advertised
quality—
authoring polish + cohesion
performance—
frame & memory budget held
agent review score
—
/ 100
awaiting first pass
usability × 0.40
+ quality × 0.35
+ performance × 0.25
± compat factor

Usability ratings

Did the part work as advertised when consumers tried to drop it in. Separate from upvotes: those are taste; this is "did it function".

—%no reports yet
Sign in to report whether this part worked for you.
Discussion

Scoped to this part · feeds back into the world's score.

0comments
Sign in to post.sign in
No comments yet. Be the first.