Framework

Physics

Compile physics assets, query collisions, and simulate rigid bodies.

Physics asset compiler

bedform build --config bedform.config.json --out Intermediate/physics compiles rigid-body assets as behavior/resource-pack overlays and an immutable TypeScript catalog. It does not bundle scripts, create pack manifests, install packs, or simulate bodies. Use bedform/Build for the explicit Node host API (compile, publish, fingerprint, canonical, Config, Registration, SolidError, Limits). The root namespaces CollisionShape, PhysicsModel, and PhysicsRenderer, their matching subpaths, and bedform/keys have no host or Bedrock runtime dependency.

A minimal configuration is:

{
  "schemaVersion": 1,
  "namespace": "example",
  "behaviorPack": "BehaviorPack",
  "resourcePack": "ResourcePack",
  "models": [{
    "name": "crate",
    "representation": "cuboid",
    "geometry": "models/entity/crate.geo.json",
    "geometryIdentifier": "geometry.crate",
    "textures": { "default": "textures/entity/crate" },
    "materials": { "default": "entity_alphatest" },
    "density": 20,
    "collision": { "kind": "complex" }
  }]
}

Pack roots resolve relative to the configuration file. Cuboid geometry and PNG texture paths resolve from the resource pack; texture references omit .png. Texture/material aliases require a default entry; additional material aliases select matching bones and additional textures become controller layers. Authored geometry is copied into the overlay with a unique generated identifier, preserving UVs, locators, hierarchy, fixed transforms and appearance. Mirror flags affect UVs, not physical volume. Cubes use sixteenths of blocks, X-then-Y-then-Z rotations about their cube/bone pivots, inherited bone inflation and cube overrides; coordinates become (x/16,y/16,-z/16) after authored transforms. Deprecated poly_mesh, texture meshes, binding and collision deformation are rejected. Animated visual deformation is outside this rigid compiler.

A particle registration instead supplies representation: "particle", meshSolid and rendererDescriptor paths relative to the configuration. The version-one renderer descriptor contains identifier, geometry, geometryIdentifier, and an assets array enumerating compatible generated assets; geometry/assets resolve from that descriptor. Its anchor geometry may be bone-less. Particle authoring, Blender export and live renderer attachment remain downstream work; this compiler consumes that interchange without importing Blender or ParticleRuntime. Particle owners are invisible and persistent; the renderer owns its separate transient anchor.

PhysicsModel.MeshSolid contains schemaVersion: 1, coordinates: "minecraft" | "blender", positive metresPerUnit, evaluated vertices (x/y/z), oriented triangles (indices and original source.object/source.face), and fingerprint. Compute the fingerprint with fingerprint over every other field. Blender converts (x,y,z) to (x,z,-y) and applies the unit scale exactly once. Weld evaluated topology before export and correct winding after mirrored transforms. Rendering masks, UVs and particle region merging must not alter this source solid. Exterior shells wind outward; enclosed cavities wind inward, alternating for nested islands. Open boundaries, disconnected vertex fans, nonmanifold edges, degeneracy, self-intersections, touching/intersecting shells and ambiguous nesting fail with source diagnostics.

Compilation partitions overlapping cuboids or validated mesh solids by their boundary planes, classifies each convex region against the original solid, and marks internal cell faces for contact suppression. It preserves cavities, through openings and disconnected solids. It never substitutes an enclosing hull for a failed partition. Published sourceGeometry retains converted boundary topology and provenance; sourceCells retain the nonoverlapping convex partition independently of the selected collider. Signed tetrahedron integration derives volume, centroid and all nine inertia components, including cavity subtraction and the parallel-axis adjustment for a COM override.

Geometric tolerance is 1e-9 * max(1, maximumExtent) blocks. The current budgets are 1,024 source triangles, 128 distinct boundary planes, 4,096 arrangement cells, 256 unique vertices per convex cell, 256 vertices per clipped face, four million plane/vertex classification operations, 64 cuboids, 256 bones, 1,024 blocks of model extent and absolute local coordinates at most one million blocks. Input beyond these budgets or a failed geometric predicate is rejected. Plane-arrangement cost can exceed budgets even for a model with few faces; simplify that source instead of relying on approximation. Mesh partition volume must agree with the source integral within 1e-7 relative error. These limits are compilation limits, not runtime performance claims.

Mass and density are mutually exclusive at both the typed and JSON boundaries. Default mass is 1 kg. Optional centerOfMass, restitution (0..1), gravity, linearVelocity (COM blocks/second), and angularVelocity (world radians/second) are model defaults. Restitution and velocities default to zero; omitted gravity defers to the physics world's gravity. Inertia always uses the source solid, regardless of selected collider. Omitted collision selects a fitted model-local box. Fit another enclosing primitive with kind: "sphere" | "ellipsoid" | "capsule" and fit: true. Explicit primitives use halfExtents and an optional pose (position, quaternion rotation); spheres require equal radii, capsules use X/Z radius and Y straight-segment half-length. A compound contains children; complex uses the exact source partition. Primitives and compound descriptions are pure immutable data.

Outputs include behavior_pack, resource_pack, catalog/models.ts, catalog/models.json, and per-model catalog/*.renderer.json attachment metadata. Import Models from the generated TypeScript catalog during the consumer's script build; it reconstructs frozen shared math values, so no host loader is needed at runtime. Fingerprints cover physical inputs, rendering descriptors, compatible asset bytes, configuration and generated visual contracts. The .bedform-physics.json ownership manifest records generated-file hashes. Rebuilds remove only recorded stale files, preserve unrelated files, and refuse to replace or delete edited/unowned files or follow symlinks. Compilation validates every model before output publication; authored sources remain unchanged.

Every representation has one common root at the model origin. An existing identity root at the origin is reused. A new parent preserves a nonidentity authored root or multiple roots, and a bone-less anchor gets one trivial root. All descendant bones and face locators inherit its pose. Generated client_sync integer properties carry committed start/end model-origin poses, sequence/reset, and render-base information; PhysicsRenderer.encode validates and encodes them. PhysicsRenderer.Renderer/Attachment define explicit commit, rebase, pause and idempotent disposal, including restoration, dimension changes and rollback. They do not subscribe to engine events.

The presentation contract uses one linear alpha over 50 ms, component-wise position lerp and shortest-path normalized quaternion lerp. Duplicate/stale packets do not restart its clock; incomplete packets hold the last interval; skipped intervals and reset markers snap to the latest endpoint. Each payload word carries its sequence modulo 128. Runtime transports must retire stale payloads within 127 commits, publish payload/reset before the sequence marker, keep sequence monotonic through resets and recreate the owner before sequence exhaustion (8,388,607). Reset ranges from 0 to 65,535. Local endpoints have 1/4096 block precision within [-8,8) of the render base; rebase or explicitly reset discontinuities outside that range. Quat components have 1/32767 precision and are renormalized per frame. The render base uses signed 32-bit integer block coordinates plus a 1/65535 fractional word. Twenty-five properties stay within exact 23-bit integer payloads. Native owner/anchor rotation must stay neutral. Per-frame root offsets compensate against the rendered entity origin instead of adding a second translation stream.

Compiler acceptance is host-side: analytic boxes/tetrahedra, overlap unions, cavity subtraction, concave manifold openings, disconnected/mirrored/unit-converted solids, malformed topology, deterministic assets, cleanup, packed consumers and generated-expression frame fixtures. Actual engine property timing, native interpolation, helper collision behavior, two-player visuals, runtime physics and sustained performance remain acceptance work in MineCraft-8zu.2 through .5; these compiler checks do not establish those results.

Authoritative collision queries

bedform/Collision (also the root Collision namespace) prepares immutable collider handles and performs distance, contact and continuous queries. prepare(model.collision) copies and validates primitive, compound and exact convex-cell data, preserving source paths and internal-face flags. Prepared handles own a balanced model-local AABB hierarchy; they retain no caller-owned mutable arrays. An Instance supplies the handle and an authoritative model-origin Transform. Rendering intervals, common-root offsets and frame-rate samples are not query inputs.

distance(a,b,options) returns Result<Distance,Diagnostic>, including world-space witnesses, a normal from A toward B, and nonnegative separation. collide(a,b,options) returns frozen exterior manifolds; successful empty output means separated solids. Both support the data-last form distance(b,options)(a) / collide(b,options)(a). Each manifold has at most four spatially spread contact points with paired world-space witnesses, penetration depth and deterministic feature identifiers. Distinct surface normal patches remain separate rather than inventing one global translation for a concave solid. bounds(instance) returns an enclosing world AABB for broad-phase use.

Sphere/capsule pairs use analytic segment distance, including point degeneracy and coincident-axis ties. Other convex pairs use support-mapped GJK distance and EPA penetration on their true support maps: boxes, spheres, capsules, ellipsoids and validated convex hulls are not replaced by bounding proxies. EPA seed sampling constructs an interior polytope only; the final support gap bounds convergence against the original shapes. Repeated support without a certified GJK gap, missing interior EPA seeds and exhausted work are typed failures. Polyhedral contacts clip incident polygons against reference side planes; coplanar triangles are joined into face polygons. Complex models query their actual cells through the hierarchy, recover exterior contacts when a shallow axis points through a partition, suppress internal-only/edge-lip witnesses and merge compatible exterior patches. A pair exposing only unresolved internal witnesses reports a diagnostic rather than a false miss.

Collision.Options defaults to absolute and model-radius-relative tolerance 1e-7 each: the pair tolerance is absoluteTolerance + relativeTolerance * max(radiusA,radiusB). At least one tolerance must be positive. The defaults are 64 GJK iterations, 128 EPA iterations, 128 CCD advances, 16,384 convex leaf pairs and 65,536 model node pairs per query. Iteration limits may be set from 1 to 256; leaf-pair limits up to 65,536 and node-pair limits up to 262,144. EPA has an additional 1,024-facet cap and deterministic seed/simplex bounds. Model preparation permits 4,096 leaves, compound depth eight and at most 256 vertices/faces per cell. Model-local reach must stay within one million blocks, primitive radii/box or ellipsoid half extents must be at least 1e-9 blocks, and authoritative positions must stay within one billion blocks. Capsule straight-segment half length may be zero. Invalid topology, forged handles, nonfinite inputs and unsupported numerical domains fail explicitly. These are numerical/work limits, not sustained runtime performance claims.

Collision.Diagnostic has _tag: "CollisionError", a code (InvalidInput, ComplexityLimit or NonConvergence), a stage (validation, gjk, epa, manifold, bvh or ccd) and a message. The dynamics layer must report the diagnostic and pause the affected island; callers must not interpret a failed Result as separation, delete a body or substitute a hull. Published shapes, witnesses and contact arrays are frozen. Exact-zero/tied normals choose deterministic coordinate/perpendicular directions. Feature identifiers distinguish the selected contact vertices but do not replace persistent body identifiers.

Continuous trajectories

sweep(a,b,duration,options) returns Result<Option<Hit>,Diagnostic>; None certifies a miss over the requested constant-velocity trajectory, while a hit includes seconds, horizon fraction and witnesses within the contact tolerance. The data-last form is sweep(b,duration,options)(a). Horizons must be finite and in (0,60] seconds. Each Motion supplies a prepared shape, a shared RigidTransform state and an optional model-local COM offset. State linear velocity is at the model origin, in blocks/second; angular velocity is world-space radians/second. CCD explicitly computes vCOM = vOrigin + cross(omega, COM-origin), advances the COM linearly, integrates full world angular motion, then derives the model-origin pose from the rotated COM offset. Full turns are supported; endpoint quaternion interpolation does not stand in for the authoritative path.

Advancement uses the current exact-leaf distance divided by a global relative-COM-speed bound plus both angular-speed/reach bounds. The global bound remains conservative when the nearest convex cell changes in a concave, cavity-bearing or disconnected model. Thin obstacles are checked along the path rather than only at discrete endpoints. A stalled or exhausted advance returns a typed CCD failure, never a false miss. sweptBounds(motion,duration) (also sweptBounds(duration)(motion)) encloses the complete COM segment expanded by angular reach, for use in broad-phase candidate generation. Accelerations, forces, response and changing velocities belong to the later fixed-step dynamics layer.

Dynamic broad phase

bedform/CollisionBroadPhase (root CollisionBroadPhase) creates explicit dynamic AABB indexes with make. The frozen handle owns private mutable AVL buffers, surface-area-guided insertion and conservative fat boxes. set(tree,entry) inserts/updates an ID with copied authoritative bounds and dynamic, static or kinematic mode; updates inside the fat box avoid reinsertion. remove is idempotent and reports whether the ID existed. query returns frozen ordered entries whose actual bounds overlap the requested box, and snapshot returns ordered body entries. These binary operations support data-last calls.

pairs(tree,maxPairs?,maxNodes?) traverses paired tree nodes, excludes static/static subtrees, and returns ordered, unique actual-AABB pairs. It also supports pairs(maxPairs?,maxNodes?)(tree). Defaults are 65,536 output pairs and 262,144 node-pair visits, each configurable up to one million. Work exhaustion reports ComplexityLimit. The default fat margin is 0.1 blocks and capacity 16,384 bodies; valid limits are nonnegative margin up to one million blocks and capacity 1..65,536. Body IDs are nonempty strings of at most 256 characters. Old snapshots survive updates/removals unchanged, and the index has no event subscriptions or implicit tick processing. Feed it conservative swept bounds when building CCD candidates.

Collision acceptance includes all 36 ordered primitive/complex/compound shape pairings for rotated separation, overlap and boundary contact; analytic witnesses and four-point box clipping; independent rotated-box SAT fixtures; equivalent cuboid/mesh responses; cavities, openings, disconnected solids and seam crossings; thin-wall, rotation-only, full-turn and offset-COM sweeps; all shape CCD pairings; brute-force broad-phase comparisons after updates/removals; deterministic failures; declaration inference; packed restricted-host consumers; and invariance under differing presentation sampling. This completes the pure collision stage (MineCraft-8zu.2). Impulse response, sleeping/islands, world/runtime integration, engine/client behavior and sustained performance remain in .3 through .5.

Algorithm references: Van den Bergen's GJK distance work and controlled conservative advancement. The implementation uses a conservative global speed bound for changing nearest cells and reports its own bounded convergence failures. Single convex pairs can use the separating-plane closing bound for linear motion; angular reach remains conservative.

Immutable rigid-body dynamics

bedform/PhysicsEntity and bedform/PhysicsWorld (also root namespaces) implement the pure dynamics stage. They import neither Bedrock runtime APIs nor host/build tools, and start no subscriptions. Bodies/worlds and their nested physical data, vectors, intervals, options and events are immutable. Updates return @bedform/effect/Result; lookups distinguish absence with Option. Bodies and worlds implement Equal, Hash, Pipeable and Inspectable with shared prototypes. Equality includes catalog geometry/physical data and complete state; world equality also includes private frozen warm-start data because it affects future steps. Diagnostic JSON is not the later versioned engine persistence format.

Register a compiled model once with PhysicsEntity.define(model), then call make(definition,{id,...}) for each body. make(model,options) also registers directly. IDs are explicit deterministic strings of 1..256 characters. A definition owns prepared collision geometry and copies compiled source-solid mass properties without freezing or retaining a mutable caller model graph. Source-centroid inertia is recovered by subtracting the original parallel-axis contribution, normalized by source mass, then scaled/recentered for requested mass/density/COM. It remains independent of collision approximation or rendering. Invalid, nonfinite, nonpositive, asymmetric or ill-conditioned physical data fails instead of becoming a diagonal proxy. Tensor inversion uses a conditioned Cholesky/inverse check; unsupported inverse-mass domains fail explicitly.

Body options include mode (dynamic, static, kinematic), model-origin pose, mutually exclusive positive mass/density, local centerOfMass, restitution in [0,1], gravity as Option<Vector3>, COM linearVelocity, world angularVelocity and allowSleep. Defaults come from the model, with dynamic mode, identity pose and sleeping permitted. None gravity inherits world gravity; Some(Zero) disables it for that body. gravityFrom(magnitude,direction) validates a nonnegative magnitude and unitizes direction; zero gravity accepts a zero direction. Static bodies reject nonzero velocities. Kinematic velocities are caller-prescribed, contribute contact motion and are unaffected by loads/impulses.

Body operationBehavior
configure(body,properties)Rebuild source-solid mass/inertia, preserve world pose/velocities and wake.
setPose(body,pose)Explicit discontinuity; reset both visual endpoints and increment reset marker.
setLinearVelocity / setAngularVelocityIndependently replace COM/world velocities and update angular momentum.
applyForce(body,force,point?)Accumulate force and world-point torque for the next complete tick; omitted point means COM.
applyTorque(body,torque)Accumulate world torque without adding COM force.
applyImpulse(body,impulse,point?)Immediate COM and full-tensor angular response.
clearForces / wakeClear loads, or wake without automatically resuming a failed body.
pause / resumeHold/retry retained state; pause preserves loads/velocities and is idempotent.
centerOfMass / motionInspect world COM, or shared origin-motion RigidTransform.

Binary updates support data-last calls, such as applyImpulse(impulse,point)(body) and configure(properties)(body). Public linear velocity remains authoritative COM motion. motion(body) computes vOrigin = vCOM + cross(angularVelocity, origin-COM); it never labels COM velocity as origin motion. Paused/sleeping/static bodies report zero effective motion while paused saved velocities remain retained. Pose-preserving mass/COM changes recompute momentum for existing angular velocity. Static/kinematic loads are validated and ignored. Friction is fixed at 0.5 and cannot be overridden.

World updates and stepping

PhysicsWorld.make(options) creates an empty value with gravity (0,-9.81,0). add rejects duplicate IDs, set replaces an existing body, modify(world,id,operation) applies an atomic Result-returning update, get returns Result<Option<PhysicsEntity>>, and remove is idempotent. Receiver operations support direct/curried calls. setGravity wakes world-gravity dependents. Anchor changes wake old contacts and newly overlapping sleepers; removing support wakes the unsupported contact chain. Load/velocity-only updates retain warm starts; pose, physical-data, mode, restitution and pause changes invalidate affected caches. Callback exceptions become typed failures, with no partial update.

step(world) advances exactly 0.05 seconds using four fixed 0.0125-second substeps. There is no elapsed-frame-time input or second render-driven simulation. COM velocities use semi-implicit force/gravity integration. World angular momentum integrates torque and contact impulses; full tensors are transported through shared quaternions. A midpoint angular prediction defines each constant-angular-velocity segment; CCD and actual advancement use that same trajectory, then angular velocity is recovered from momentum and the new orientation. Kinematics retain prescribed velocities. Successful ticks consume force/torque once across all four substeps.

Each regular substep performs ten warm-started sequential-impulse velocity iterations. Normal impulses accumulate/clamp, restitution uses the larger participant coefficient above a 1 block/second closing-speed threshold, and coupled tangent directions clamp to the fixed Coulomb cone. Cached tangents project onto the new tangent plane; local anchors/normals validate reuse. Separate inverse-mass position correction uses 1e-4 block slop, factor 0.2 and at most 0.1 block translation per body/substep, without correction velocity. Contact queries use four times geometric tolerance to keep conservative TOI witnesses/resting patches coherent. Additional localized ten-iteration solves resolve bounded CCD impacts without adding full simulation substeps.

Continuous response advances to the earliest collision, resolves it and continues through the remaining substep using authoritative COM/origin transport and angular reach. Conservative moving contact islands do not connect unrelated bodies through static anchors. If an impact accelerates a body beyond its original motion envelope, the tick restarts transactionally with enlarged bounds and regrouped islands. At most four replans are allowed. Exhaustion pauses/reports retained state instead of missing an impact. A bounded position-correction allowance stays inside the envelopes. This catches subsequent obstacles beyond a light body's initial bounds after a high mass-ratio impact.

World defaults are 4,096 bodies, 65,536 broad-phase pairs and eight CCD impacts per substep. Valid ranges are 1..4,096 bodies, 1..1,000,000 pairs and 1..64 impacts; options.collision supplies collision-stage tolerances/limits. Numerical, effective-mass and work failures never publish NaN or partial state. A failed moving island rolls back its entire tick to original pose, velocities, loads and properties and becomes paused; independent islands continue. A local invalid bound is isolated at its retained pose; a global broad-phase/replan budget failure conservatively holds the moving scene. world.diagnostics records affected IDs and typed collision/numerical/solver causes. Repair inputs and explicitly resume; elapsed held time is not replayed.

Dynamic islands sleep together after 0.5 seconds below 0.03 blocks/second and 0.03 radians/second without outstanding loads. Moving kinematics prevent associated sleeping. Waking updates propagate through the conservative moving contact group, and sleepers retain contact/event discovery. world.events supplies deterministic begin/end transitions ordered by within-tick time and IDs, including transient CCD impacts and removal ends; world.contacts is the committed ordered pair snapshot. Events and diagnostics describe the most recent operation rather than an unbounded log.

Committed bodies publish pose-only interval.start from the previous model origin and interval.end from the four-substep result, with duration 0.05 and monotonic sequence. Explicit discontinuities/first pauses reset endpoints; ordinary load/velocity updates preserve the stream. These Transform values are distinct from COM and motion-bearing RigidTransform. Intervals are unquantized; the later runtime adapter must respect renderer transport/rebase/sequence limits independently. Rendering cannot alter authoritative physics.

Acceptance fixtures cover analytic trajectories, forces/torques, source-solid mass, off-center/full-tensor impulses, gravity, kinematics, elastic momentum/energy, thin-wall and rotation-only response, high mass-ratio replanning, friction/sliding, stacking, sleep/wake/support removal, free rotation, offset-COM paths, rollback/repair, immutable options, events, protocols, overload declarations and packed restricted-host execution. Scalar fixtures use 1e-7 tolerances, elastic response 1e-5, two-second rotation energy 5e-4, isolated large-inertia friction 2e-3 blocks/second, and two-body stacking 0.02/0.04 block height error over two seconds. These host checks establish neither engine visuals nor sustained runtime performance.

This completes pure dynamics (MineCraft-8zu.3). Explicit native contacts, engine owners, persistence and renderer lifecycle are available through PhysicsRuntime. MineCraft-8zu.4 retains its engine/client acceptance boundaries; sustained performance and broader client acceptance remain in .5. Design references include sequential impulses and accumulation/warm starting; this implementation is three-dimensional with the package's fixed physical contracts.

The physics acceptance record contains reproducible host/BDS benchmark commands, measured mesh costs, runtime instrumentation and failed performance gates. The two-client procedure prepares a disposable cuboid fixture for the remaining captures. The ten-minute 128-body benchmark failed the 15 ms p95 target; .5 remains in progress, and client acceptance remains open.

On this page