GitHubLoslegen

Die API-Referenz stammt aus den Go-Doc-Kommentaren im Quellcode und ist auf Englisch verfasst.

package physics3d

import "github.com/nsgo-dev/game/pkg/physics3d"

Übersicht

Package physics3d provides compact, deterministic 3D collision detection, raycasting, rigid-body dynamics, and a kinematic character controller in pure Go.

Architecture

physics3d is implemented purely with the Go standard library and no cgo or third-party physics engine bindings (Epic #180, option a). Avoiding cgo keeps builds reproducible and portable across every NSGo target — macOS, Windows, Linux, iOS, Android, and WebAssembly — without C/C++ toolchains, per-platform native libraries, or FFI marshaling overhead.

The simulation trades full articulated meshes for a focused set of primitives (boxes, spheres, capsules, convex hulls built from point clouds or meshes, cylinders, and compound shapes assembled from child colliders with local offsets, rotations, combined parallel-axis inertia tensors, and optional per-child triggers and collision layers), exact overlap and raycast queries, rigid bodies with iterative impulse and positional resolution, and a capsule character controller that handles slopes, stairs, and wall sliding. Pairs that involve a convex hull or a cylinder are tested with GJK and EPA and give the solver up to four contact points over the touching area.

Coordinate Convention

physics3d uses a right-handed, Y-up coordinate system: +X is right, +Y is up, and +Z points toward the viewer. Default gravity in NewWorld is (0, -9.81, 0).

Determinism

Stepping a World with fixed durations (such as from game.Loop.Update) runs collision detection, impulse solving, and positional correction in a fixed body and contact order with no map-order iteration or wall-clock input, so identical initial states produce bit-identical trajectories across runs.

Index

Konstanten

const (
	// DefaultHullVertices is the vertex limit NewConvexHull uses when given a limit of 0 or less.
	DefaultHullVertices = 64
	// MaxHullVertices is the largest vertex limit NewConvexHull accepts; larger limits are lowered to it.
	MaxHullVertices = 256
)
const (
	// DefaultSoftSubsteps is the default number of XPBD substeps per SoftWorld.Step.
	DefaultSoftSubsteps = 8
	// DefaultSoftIterations is the default number of constraint solver iterations per substep.
	DefaultSoftIterations = 6
)
const SnapshotVersion = 1

SnapshotVersion is the schema version stored in WorldSnapshot.

Variablen

var ErrDegenerateHull = errors.New("physics3d: points do not span a convex volume")

ErrDegenerateHull is returned by NewConvexHull and ConvexHullFromMesh when the points do not span a volume: fewer than four of them, all on one plane, line or point, or not finite.

Funktionen

func BoxEdges(b Box) [12][2]Vec3

BoxEdges returns the 12 wireframe line segments of b in deterministic order (4 on the min-Z face, 4 on the max-Z face, and 4 connecting Z edges).

func CanCollide(a, b *Body) bool

CanCollide reports whether bodies a and b are permitted to collide or overlap based on their Layer and Mask bitmasks. Zero Layer or Mask fields default to LayerAll for backwards compatibility.

func CapsuleEdges(c Capsule, segments int) [][2]Vec3

CapsuleEdges returns wireframe line segments for capsule c aligned with its axis (B - A): two end-cap rings at A and B, four longitudinal rails, and four hemisphere arcs capping both ends. Degenerate capsules (A == B) fall back to SphereEdges. Non-positive radii return nil; non-positive segments default to 24 (minimum 4).

func ConvexHullEdges(h ConvexHull, rot Quat) [][2]Vec3

ConvexHullEdges returns the world-space wireframe segments of h turned by rot about its Center, one per hull edge in the order of Edges.

func CylinderEdges(c Cylinder, segments int) [][2]Vec3

CylinderEdges returns wireframe line segments for cylinder c: a ring around each cap and four lines along its side. Non-positive radii and zero-length axes return nil; non-positive segments default to 24 (minimum 4).

func DrawBody(d *core.Drawing, viewProj Mat4, viewport core.Bounds, b *Body, style DebugStyle)

DrawBody draws the world-space collider wireframe of b onto d.

func DrawCharacter(d *core.Drawing, viewProj Mat4, viewport core.Bounds, c *CharacterController, style DebugStyle)

DrawCharacter draws the kinematic capsule wireframe of c onto d, along with its ground normal when grounded.

func DrawContact(d *core.Drawing, viewProj Mat4, viewport core.Bounds, c Contact, style DebugStyle)

DrawContact draws a contact point marker and its surface normal arrow onto d. Non-hitting contacts are ignored.

func DrawLine3D(d *core.Drawing, viewProj Mat4, viewport core.Bounds, a, b Vec3, col core.Color, lineWidth float32)

DrawLine3D projects and strokes a 3D line segment [a, b] onto d using viewProj and viewport, clipping cleanly against the camera frustum and near plane. It leaves d's graphics state unchanged.

The near plane is clip z >= -w, right for a [-1, 1] depth projection such as Mat4Perspective or Mat4Ortho. Use DrawLine3DZO for a [0, 1] projection such as math3d.Perspective or math3d.Ortho.

func DrawLine3DZO(d *core.Drawing, viewProj Mat4, viewport core.Bounds, a, b Vec3, col core.Color, lineWidth float32)

DrawLine3DZO is DrawLine3D for a [0, 1] depth projection such as math3d.Perspective, math3d.Ortho or a render3d camera: it clips at clip z >= 0, as render3d.ProjectSegment does. DrawLine3D used with a [0, 1] orthographic projection would draw segments behind the camera, because w is 1 there everywhere (#546).

func DrawRaycast(d *core.Drawing, viewProj Mat4, viewport core.Bounds, ray Ray, hit RaycastHit, hitOK bool, style DebugStyle)

DrawRaycast draws a 3D ray segment onto d. When hitOK is true, the ray is drawn from ray.Origin to hit.Point and the hit point and outward normal are drawn as a contact; otherwise the full ray up to ray.MaxDist is drawn.

func DrawShape(d *core.Drawing, viewProj Mat4, viewport core.Bounds, s Shape, style DebugStyle)

DrawShape draws a 3D wireframe of s projected into viewport onto d.

func DrawSoftWorld(d *core.Drawing, viewProj Mat4, viewport core.Bounds, sw *SoftWorld, style DebugStyle)

DrawSoftWorld projects and draws XPBD structural constraint wireframes, rigid attachments, and pinned particle markers from sw onto d using viewProj, viewport, and style (respecting style.DepthZO). Release builds compile this to a no-op.

func DrawWorld(d *core.Drawing, viewProj Mat4, viewport core.Bounds, w *World, style DebugStyle)

DrawWorld draws the wireframes of every body in w in deterministic order, followed by contact markers and normals for any currently overlapping pairs.

func GenerateCoverPointsFromBodies(bodies []*Body, opts CoverOptions) []ai.CoverPoint

GenerateCoverPointsFromBodies generates deterministic XZ-plane cover points from the given 3D bodies: axis-aligned or oriented boxes, spheres, vertical capsules, and cylinders standing on an end (their axis within about 25 degrees of vertical). Convex hulls and cylinders lying on their side generate no cover.

func OrientedBoxEdges(b Box, rot Quat) [12][2]Vec3

OrientedBoxEdges returns the 12 world-space edges of b rotated by rot about its Center.

func Project(viewProj Mat4, viewport core.Bounds, p Vec3) (core.Point, float32, bool)

Project transforms world-space point p by viewProj and maps normalized device coordinates to viewport screen coordinates (X left-to-right in [viewport.Origin.X, viewport.Origin.X+viewport.Size.Width], Y top-down in [viewport.Origin.Y, viewport.Origin.Y+viewport.Size.Height]).

It returns the screen point, the normalized depth ndcZ, and ok == true when clip w > 0 and ndcZ is within [-1, 1], the depth range of this package's Mat4Perspective and Mat4Ortho. For a [0, 1] depth projection (math3d.Perspective, math3d.Ortho, a render3d camera) the caller must also require ndcZ >= 0: an orthographic [0, 1] camera has w = 1 everywhere, so a point behind it gets ndcZ in [-1, 0) and is still reported ok, as DebugStyle.DepthZO does for DrawContact.

func SphereEdges(s Sphere, segments int) [][2]Vec3

SphereEdges returns wireframe line segments for three orthogonal great circles (XY, XZ, and YZ planes) of sphere s. Non-positive radii return nil; non-positive segments default to 24 (minimum 3).

Typen

type ActiveContactSnapshot struct {
	KeyA        int     `json:"keyA"`
	KeyB        int     `json:"keyB"`
	KeyChildA   int     `json:"keyChildA"`
	KeyChildB   int     `json:"keyChildB"`
	BodyAID     int     `json:"bodyAID"`
	BodyBID     int     `json:"bodyBID"`
	ChildIndexA int     `json:"childIndexA"`
	ChildIndexB int     `json:"childIndexB"`
	Point       Vec3    `json:"point"`
	Normal      Vec3    `json:"normal"`
	Depth       float32 `json:"depth"`
	IsTrigger   bool    `json:"isTrigger,omitempty"`
}

ActiveContactSnapshot captures one active contact or trigger overlap record.

func (a *ActiveContactSnapshot) UnmarshalJSON(data []byte) error

UnmarshalJSON defaults child indices to -1 when omitted in pre-compound v1 snapshots.

type AreaEffect struct {
	Gravity           Vec3
	LinearDamping     float32
	AngularDamping    float32
	HasLinearDamping  bool
	HasAngularDamping bool
	SubmergedFraction float32
	BuoyancyAccel     Vec3
	FluidLinearDrag   float32
	FluidAngularDrag  float32
	FluidVelocity     Vec3
}

AreaEffect holds the resolved gravity, damping, and fluid state at a point or shape from all overlapping active trigger bodies.

type AreaOverrideMode uint8

AreaOverrideMode controls how a trigger Body's AreaSettings combines its gravity or damping value with overlapping areas and the world or body default.

const (
	// AreaOverrideNone leaves the world or body default unchanged (zero value).
	AreaOverrideNone AreaOverrideMode = iota
	// AreaOverrideCombine sums this area's value with other equal-priority
	// Combine or Add areas (plus any higher-priority Add areas) and replaces
	// lower-priority areas and the world/body default.
	AreaOverrideCombine
	// AreaOverrideReplace replaces lower- and equal-priority areas and the
	// world/body default with this area's value. Higher-priority Add areas
	// still add on top.
	AreaOverrideReplace
	// AreaOverrideAdd adds this area's value on top of lower-priority areas
	// and the world/body default.
	AreaOverrideAdd
)
type AreaSettings struct {
	// Priority orders overlapping areas: higher Priority takes precedence.
	// Equal priorities break ties deterministically by World body insertion order.
	Priority int

	// GravityMode controls whether and how this area overrides gravity.
	GravityMode AreaOverrideMode
	// Gravity is the directional gravity acceleration (units/s^2) used when
	// PointGravity is false.
	Gravity Vec3

	// PointGravity switches gravity from directional Gravity to a radial field
	// centered at GravityPoint.
	PointGravity bool
	// GravityPoint is the world-space point-gravity center.
	GravityPoint Vec3
	// GravityStrength is the acceleration magnitude (units/s^2) toward
	// GravityPoint (negative values repel).
	GravityStrength float32
	// GravityFalloff selects distance attenuation for PointGravity.
	GravityFalloff GravityFalloff
	// GravityUnitDistance is the reference distance for GravityFalloffInverse
	// and GravityFalloffInverseSquare (defaults to 1 when <= 0), or the cutoff
	// radius for GravityFalloffLinear (defaults to the trigger's outer radius
	// when <= 0).
	GravityUnitDistance float32

	// LinearDampingMode controls whether and how LinearDamping overrides a body's damping.
	LinearDampingMode AreaOverrideMode
	// LinearDamping is the linear damping coefficient (1/s) applied according to LinearDampingMode.
	LinearDamping float32

	// AngularDampingMode controls whether and how AngularDamping overrides a body's damping.
	AngularDampingMode AreaOverrideMode
	// AngularDamping is the angular damping coefficient (1/s) applied according to AngularDampingMode.
	AngularDamping float32

	// FluidDensity enables Archimedes buoyancy when > 0 (mass per unit volume, kg/m^3).
	// A body with implicit density Mass/Volume settles at submerged fraction
	// (Mass / Volume) / FluidDensity.
	FluidDensity float32
	// FluidLinearDrag is the linear fluid drag coefficient (1/s), scaled by the
	// submerged fraction of the body's bounds.
	FluidLinearDrag float32
	// FluidAngularDrag is the angular fluid drag coefficient (1/s), scaled by the
	// submerged fraction of the body's bounds.
	FluidAngularDrag float32
	// FluidVelocity is the fluid flow velocity (units/s) relative to which
	// FluidLinearDrag acts.
	FluidVelocity Vec3
}

AreaSettings configures gravity, damping, and buoyancy/fluid drag overrides for a 3D trigger Body (IsTrigger == true). The zero value has no physical effect.

func (a AreaSettings) Active() bool

Active reports whether a enables any gravity, damping, or fluid effect.

type AxisConfig struct {
	Mode      AxisMode
	Min       float32 // lower limit (meters or radians) when Mode == AxisLimited
	Max       float32 // upper limit (meters or radians) when Mode == AxisLimited
	Drive     DriveMode
	Stiffness float32 // spring stiffness (N/m for linear, N*m/rad for angular)
	Damping   float32 // damping coefficient (N*s/m for linear, N*m*s/rad for angular)
	TargetPos float32 // target position (meters) or angle (radians)
	TargetVel float32 // target velocity (m/s) or angular velocity (rad/s)
	MaxForce  float32 // max drive force (N) or torque (N*m); <= 0 means unlimited
}

AxisConfig configures one linear (X, Y, Z) or angular (X, Y, Z) degree of freedom of a SixDOFJoint.

type AxisMode int

AxisMode controls whether one linear or angular degree of freedom on a SixDOFJoint is free, locked at 0, or clamped to [Min, Max].

const (
	// AxisFree leaves the axis unconstrained (optional springs and drives still apply).
	AxisFree AxisMode = iota
	// AxisLocked rigidly locks the axis at 0.
	AxisLocked
	// AxisLimited clamps the axis to [Min, Max].
	AxisLimited
)
type BallJoint struct {
	BodyA, BodyB     *Body
	LocalAnchorA     Vec3
	LocalAnchorB     Vec3
	ConeLimit        float32 // maximum half-angle in radians (> 0 enables cone limit)
	LocalAxisA       Vec3    // cone reference axis in A's local space (defaults to +Y)
	LocalAxisB       Vec3    // bone/body axis in B's local space (defaults to +Y)
	BreakForce       float32 // max reaction force in N before breaking (<= 0 disables)
	BreakTorque      float32 // max reaction torque in N*m before breaking (<= 0 disables)
	CollideConnected bool
	// contains filtered or unexported fields
}

BallJoint is a 3D ball-and-socket point constraint with an optional symmetric cone swing limit.

func NewBallJoint(a, b *Body, localAnchorA, localAnchorB Vec3) *BallJoint

NewBallJoint creates a BallJoint locking LocalAnchorA on a to LocalAnchorB on b.

func (j *BallJoint) Bodies() (*Body, *Body)

Bodies returns the connected bodies.

func (r *BallJoint) Broken() bool

Broken reports whether the joint has exceeded its break threshold and been removed.

func (j *BallJoint) Prepare(dt float32)

Prepare resets per-step accumulated limit impulses.

func (r *BallJoint) ReactionForce() Vec3

ReactionForce returns the world-space constraint force (in Newtons) applied to BodyB during the most recent World.Step.

func (r *BallJoint) ReactionTorque() Vec3

ReactionTorque returns the world-space constraint torque (in N*m) applied to BodyB during the most recent World.Step.

func (j *BallJoint) SolvePosition(dt float32)

SolvePosition corrects socket anchor drift and optional cone swing violations.

func (j *BallJoint) SolveVelocity(dt float32)

SolveVelocity solves the 3D socket point constraint and optional cone swing limit.

type BendingConstraint struct {
	A, B, C, D int
	RestAngle  float32
	Compliance float32
	// contains filtered or unexported fields
}

BendingConstraint constrains the signed dihedral angle between triangles (A, B, C) and (B, A, D) sharing edge (A, B) toward RestAngle (in radians; 0 is coplanar/flat).

type Body struct {
	// ID uniquely identifies the body inside its World. AddBody assigns one
	// sequentially when ID is 0.
	ID int
	// Tag is an optional user label for identifying bodies in query results.
	Tag string
	// Shape is the body's collision primitive in local coordinates relative to Pos.
	Shape Shape
	// Pos is the body's world-space position.
	Pos Vec3
	// Vel is the body's linear velocity in units per second.
	Vel Vec3
	// Rot is the body's world-space orientation quaternion. A zero quaternion is
	// normalized to identity by AddBody and treated as identity by helpers.
	Rot Quat
	// AngVel is the body's angular velocity in radians per second.
	AngVel Vec3
	// Mass is the body's mass in kilograms. Zero mass marks a static body.
	Mass float32
	// InvMass is 1/Mass for dynamic bodies and 0 for static bodies.
	InvMass float32
	// InvInertia is the body's scalar inverse rotational inertia fallback.
	// AddBody computes both InvInertiaTensor and InvInertia from Shape and Mass
	// unless LockRotation is set or an explicit inertia override is provided.
	InvInertia float32
	// CenterOfMass is the body's center of mass in local coordinates relative to Pos.
	// For dynamic compound bodies, AddBody computes it from all solid children
	// unless already set or overridden with SetCenterOfMass.
	CenterOfMass Vec3
	// InvInertiaTensor is the 3x3 symmetric inverse inertia tensor in local
	// body space about CenterOfMass. AddBody computes it from Shape and Mass
	// (diagonal for axis-aligned boxes, spheres, and axis-aligned capsules or
	// cylinders; full symmetric for rotated, offset, convex-hull, and compound
	// shapes) unless LockRotation is set or an explicit override is provided via
	// InvInertiaTensor, SetInertia, SetInertiaTensor, or scalar InvInertia.
	InvInertiaTensor SymMat3
	// LockRotation keeps a dynamic body from rotating: InvInertia becomes 0
	// and angular impulses are ignored, which InvInertia == 0 alone could not
	// express while 0 also meant "compute a default" (#546).
	LockRotation bool
	// Restitution is the bounciness in [0, 1]. Overridden when Material is non-nil.
	Restitution float32
	// Friction is the Coulomb friction coefficient (>= 0). Overridden when Material is non-nil.
	Friction float32
	// LinearDamping reduces velocity smoothly over time (1 / (1 + LinearDamping*dt)). Overridden when Material is non-nil.
	LinearDamping float32
	// AngularDamping reduces angular velocity smoothly over time (1 / (1 + AngularDamping*dt)). Overridden when Material is non-nil.
	AngularDamping float32
	// Material optionally overrides Friction, Restitution, LinearDamping, and
	// AngularDamping with a shared PhysicsMaterial.
	Material *PhysicsMaterial
	// GravityScale multiplies the effective gravity applied to this body during
	// World.Step. NewDynamicBody initializes it to 1; on a zero-initialized Body
	// literal it defaults to 1 unless SetGravityScale(0) is called or GravityScale
	// is modified after AddBody.
	GravityScale float32
	// Static marks an immovable body with infinite mass (InvMass == 0).
	Static bool
	// Kinematic marks a body driven directly by user/animation code (infinite
	// mass to the solver and unaffected by gravity, while retaining Mass/InvMass
	// so it can transition cleanly to dynamic simulation).
	Kinematic bool
	// Sleeping marks a dynamic body currently at rest; the solver skips
	// integrating it until woken by Wake, ApplyImpulse, or an active collision.
	Sleeping bool
	// Layer is the collision layer bitmask this body belongs to (0 defaults to LayerAll).
	Layer LayerMask
	// Mask is the collision layer bitmask this body collides with (0 defaults to LayerAll).
	Mask LayerMask
	// IsTrigger marks a sensor volume that emits trigger ContactEvents without
	// applying impulse or positional resolution.
	IsTrigger bool
	// Area configures optional gravity, damping, and buoyancy/fluid drag overrides
	// applied to overlapping dynamic bodies when IsTrigger is true.
	Area AreaSettings
	// contains filtered or unexported fields
}

Body is a rigid body, kinematic body, static collider, or trigger volume in a World.

func NewDynamicBody(shape Shape, pos Vec3, mass float32) Body

NewDynamicBody returns a dynamic Body placed at pos with the given mass and default friction (0.5), linear damping (0.01), and angular damping (0.05). For a ShapeCompound with mass <= 0, if solid children specify Mass or Density, their combined mass is used. Otherwise mass <= 0 returns a static body.

func NewStaticBody(shape Shape, pos Vec3) Body

NewStaticBody returns a static Body placed at pos with default friction.

func (b *Body) ApplyAngularImpulse(impulse Vec3)

ApplyAngularImpulse adds the angular velocity delta produced by impulse to a dynamic body (using InvInertiaTensor when set, otherwise scalar InvInertia) and wakes it.

func (b *Body) ApplyImpulse(impulse Vec3)

ApplyImpulse adds impulse / Mass to a dynamic body's velocity and wakes it.

func (b *Body) ApplyImpulseAtPoint(impulse, worldPoint Vec3)

ApplyImpulseAtPoint applies linear impulse at worldPoint, imparting both linear velocity and torque about WorldCenterOfMass, and wakes b.

func (b *Body) ApplyMaterial(m PhysicsMaterial)

ApplyMaterial copies m's surface and damping properties onto b, clamping them to valid ranges, and clears b.Material so the copied values take effect directly.

func (b *Body) EffectiveGravityScale() float32

EffectiveGravityScale returns b's active gravity multiplier. For a zero-initialized Body literal whose GravityScale has not been set, this defaults to 1.

func (b *Body) RecomputeMassProperties()

RecomputeMassProperties recomputes Mass, InvMass, CenterOfMass, InvInertia, and InvInertiaTensor from b.Shape for a dynamic body. For compound bodies, solid children determine the combined center of mass and parallel-axis inertia tensor; trigger children are ignored.

func (b *Body) SetCenterOfMass(com Vec3)

SetCenterOfMass overrides b's local center of mass (relative to b.Pos). For dynamic bodies without an explicit inertia override, SetCenterOfMass recomputes InvInertiaTensor about the new center of mass via the parallel-axis theorem. Calling SetCenterOfMass(Vec3{}) on a compound body pins its center of mass to the local origin even when AddBody would otherwise derive it from child shapes.

func (b *Body) SetGravityScale(scale float32)

SetGravityScale sets the per-body gravity multiplier on b, including 0 for weightless bodies. Non-finite values are ignored.

func (b *Body) SetInertia(diag Vec3)

SetInertia overrides b's body-space diagonal inertia tensor (Ix, Iy, Iz) about CenterOfMass. Each positive finite component sets the inverse inertia along that local axis to 1/I; non-positive, non-finite, or overflowing components lock rotation about that local axis (inverse inertia 0).

func (b *Body) SetInertiaTensor(inertia SymMat3)

SetInertiaTensor overrides b's body-space 3x3 symmetric inertia tensor about CenterOfMass. Full inversion requires a symmetric positive-definite tensor; if inertia is singular or not positive-definite, positive finite diagonal entries are inverted per axis.

func (b *Body) Wake()

Wake clears b's sleeping state so it participates in subsequent steps.

func (b *Body) WorldCenterOfMass() Vec3

WorldCenterOfMass returns b's center of mass in world coordinates. For bodies with zero local CenterOfMass, this equals b.Pos.

func (b *Body) WorldInvInertiaTensor() SymMat3

WorldInvInertiaTensor returns b's world-space 3x3 inverse inertia tensor R * InvInertiaTensor * R^T, or the zero matrix when b is nil, static, kinematic, or has LockRotation set. When InvInertiaTensor is zero and scalar InvInertia > 0, it returns an isotropic diagonal tensor.

func (b *Body) WorldShape() Shape

WorldShape returns the body's collision shape transformed by Pos and Rot.

type BodySnapshot struct {
	ID                 int              `json:"id"`
	Tag                string           `json:"tag,omitempty"`
	Shape              Shape            `json:"shape"`
	Pos                Vec3             `json:"pos"`
	Vel                Vec3             `json:"vel"`
	Rot                Quat             `json:"rot"`
	AngVel             Vec3             `json:"angVel"`
	Mass               float32          `json:"mass"`
	InvMass            float32          `json:"invMass"`
	InvInertia         float32          `json:"invInertia"`
	CenterOfMass       Vec3             `json:"centerOfMass"`
	InvInertiaTensor   SymMat3          `json:"invInertiaTensor"`
	CustomCenterOfMass bool             `json:"customCenterOfMass,omitempty"`
	CustomInertia      bool             `json:"customInertia,omitempty"`
	LockRotation       bool             `json:"lockRotation,omitempty"`
	Restitution        float32          `json:"restitution"`
	Friction           float32          `json:"friction"`
	LinearDamping      float32          `json:"linearDamping"`
	AngularDamping     float32          `json:"angularDamping"`
	Material           *PhysicsMaterial `json:"material,omitempty"`
	GravityScale       float32          `json:"gravityScale"`
	GravityScaleSet    bool             `json:"gravityScaleSet,omitempty"`
	Static             bool             `json:"static,omitempty"`
	Kinematic          bool             `json:"kinematic,omitempty"`
	Sleeping           bool             `json:"sleeping,omitempty"`
	Layer              LayerMask        `json:"layer"`
	Mask               LayerMask        `json:"mask"`
	IsTrigger          bool             `json:"isTrigger,omitempty"`
	Area               AreaSettings     `json:"area"`

	SleepTimer     float32 `json:"sleepTimer,omitempty"`
	ResidualDepth  float32 `json:"residualDepth,omitempty"`
	LastPos        Vec3    `json:"lastPos"`
	LastRot        Quat    `json:"lastRot"`
	HavePose       bool    `json:"havePose,omitempty"`
	RestingOnVoxel bool    `json:"restingOnVoxel,omitempty"`
}

BodySnapshot captures the complete public and private simulation state of a physics3d.Body.

type Box struct {
	Center      Vec3
	HalfExtents Vec3
}

Box is an axis-aligned bounding box defined by its center and half-extents.

func BoxFromMinMax(min, max Vec3) Box

BoxFromMinMax returns the axis-aligned Box spanning [min, max].

func MergeBoxes(boxes []Box, eps float32) []Box

MergeBoxes greedily merges adjacent axis-aligned boxes along X, then Z, then Y whenever their perpendicular faces align within eps (defaults to 1e-4 when <= 0). Degenerate boxes with non-positive extent on any axis are dropped.

The point-set union of the returned boxes equals the union of the valid input boxes, and the result order is deterministic regardless of input slice order.

func (b Box) Max() Vec3

Max returns the maximum corner of b.

func (b Box) Min() Vec3

Min returns the minimum corner of b.

func (b Box) Translated(offset Vec3) Box

Translated returns a copy of b shifted by offset.

type CachedImpulseSnapshot struct {
	BodyAID        int                   `json:"bodyAID"`
	BodyBID        int                   `json:"bodyBID"`
	ChildA         int                   `json:"childA"`
	ChildB         int                   `json:"childB"`
	Normal         Vec3                  `json:"normal"`
	NormalImpulse  float32               `json:"normalImpulse,omitempty"`
	TangentImpulse Vec3                  `json:"tangentImpulse"`
	Points         []CachedPointSnapshot `json:"points,omitempty"`
}

CachedImpulseSnapshot captures one warm-start contact manifold cache entry.

func (c *CachedImpulseSnapshot) UnmarshalJSON(data []byte) error

UnmarshalJSON defaults ChildA and ChildB to -1 when omitted in pre-compound v1 snapshots.

type CachedPointSnapshot struct {
	LocalA         Vec3    `json:"localA"`
	LocalB         Vec3    `json:"localB"`
	FeatureID      uint32  `json:"featureID,omitempty"`
	NormalImpulse  float32 `json:"normalImpulse"`
	TangentImpulse Vec3    `json:"tangentImpulse"`
}

CachedPointSnapshot captures one warm-start contact point inside a manifold.

type Capsule struct {
	A, B   Vec3
	Radius float32
}

Capsule is a line segment from A to B swept by Radius.

func VerticalCapsule(center Vec3, radius, height float32) Capsule

VerticalCapsule returns a Y-aligned capsule centered at center with the given radius and total height. If height is less than 2*radius, the capsule degenerates to a sphere of the given radius at center.

func (c Capsule) Translated(offset Vec3) Capsule

Translated returns a copy of c shifted by offset.

type CharacterController struct {
	// Pos is the world-space position of the bottom of the capsule (feet).
	Pos Vec3
	// Radius is the capsule radius.
	Radius float32
	// Height is the total height of the capsule (clamped to at least 2*Radius).
	Height float32
	// StepHeight is the maximum vertical step height climbed automatically.
	StepHeight float32
	// MaxSlopeAngle is the steepest walkable floor angle from horizontal, in
	// radians. Values <= 0 default to 45 degrees (pi/4).
	MaxSlopeAngle float32
	// Vel is the controller's velocity in units per second.
	Vel Vec3
	// Yaw is the character's facing angle in radians around the +Y axis.
	// When ApplyPlatformYaw is true, Move adds GroundYawDelta to Yaw while
	// carried by a rotating ground body.
	Yaw float32
	// ApplyPlatformYaw controls whether Move adds a rotating ground body's
	// per-step yaw delta to Yaw. NewCharacterController initializes it to true.
	// Position carry around a rotating ground body always applies regardless of
	// this setting.
	ApplyPlatformYaw bool
	// PlatformOnLeave controls how the controller inherits GroundVelocity when
	// jumping or walking off a moving ground body.
	PlatformOnLeave PlatformOnLeave
	// Grounded reports whether the controller ended the last Move on walkable ground.
	Grounded bool
	// GroundNormal is the outward surface normal of the ground when Grounded is true.
	GroundNormal Vec3
	// GroundBody is the Body supporting the character when Grounded is true, or
	// nil when airborne or standing on a static collider without a Body
	// (TriMeshCollider, HeightfieldCollider, or VoxelCollider).
	GroundBody *Body
	// GroundVelocity is the world-space velocity of GroundBody at the contact
	// point during the last Move, or zero when airborne or on static geometry.
	GroundVelocity Vec3
	// GroundYawDelta is the yaw rotation in radians around +Y imparted by the
	// ground body during the last Move.
	GroundYawDelta float32
	// OnWall reports whether a non-walkable wall or steep slope was contacted.
	OnWall bool
	// OnCeiling reports whether a ceiling surface was contacted.
	OnCeiling bool
	// Crushed reports whether the capsule remained squeezed between opposing
	// surfaces with no valid depenetration during the last Move.
	Crushed bool
	// IgnoreBodyID optionally ignores a body with this ID during movement queries.
	IgnoreBodyID int
	// Mask filters which body and static collider layers block the character
	// (0 defaults to LayerAll).
	Mask LayerMask
	// PushForce is the horizontal force in newtons the character applies to a dynamic body it walks into, so crates and barrels give way instead of acting as walls. 0 leaves dynamic bodies blocking the character like static ones.
	//
	// The controller is not a body in the World, so dynamic bodies do not collide with it on their own; to let them, add a kinematic body that follows Pos and set IgnoreBodyID to its ID (#546).
	PushForce float32
	// GravityScale multiplies the effective gravity applied during Move.
	// NewCharacterController initializes it to 1; on a zero-initialized
	// CharacterController literal it defaults to 1 unless SetGravityScale(0) is called.
	GravityScale float32
	// contains filtered or unexported fields
}

CharacterController is a kinematic capsule collider that moves through a World with walkable slope sliding, automatic stair stepping, headroom checks, tangential wall sliding, moving-platform carry, and kinematic push/crush resolution.

Pos is the world-space position of the bottom of the capsule (the character's feet).

func NewCharacterController(pos Vec3, radius, height float32) *CharacterController

NewCharacterController returns a CharacterController at pos with the given capsule radius and height, a default StepHeight of 0.35, a 45-degree MaxSlopeAngle, and ApplyPlatformYaw enabled.

func (c *CharacterController) Capsule() Capsule

Capsule returns the controller's world-space capsule at Pos.

func (c *CharacterController) EffectiveGravity(world *World) Vec3

EffectiveGravity returns the scaled gravity acceleration acting on c in world, combining world.Gravity with any overlapping active trigger areas.

func (c *CharacterController) EffectiveGravityScale() float32

EffectiveGravityScale returns c's active gravity multiplier, defaulting to 1 when unset on a zero-initialized CharacterController.

func (c *CharacterController) Move(world *World, wishMove Vec3, dt time.Duration) MoveResult

Move advances the character through world for dt.

wishMove is the desired velocity in units per second: X and Z drive horizontal movement, while a non-zero Y sets Vel.Y directly (such as for a jump) and Y == 0 lets world.Gravity govern vertical motion.

func (c *CharacterController) SetGravityScale(scale float32)

SetGravityScale sets the per-character gravity multiplier on c, including 0 for weightless characters. Non-finite values are ignored.

func (c *CharacterController) Shape() Shape

Shape returns the controller's world-space Shape at Pos.

type ClothConfig struct {
	Origin            Vec3
	AxisU             Vec3    // direction along columns; zero defaults to +X
	AxisV             Vec3    // direction along rows; zero defaults to +Z
	Width, Height     float32 // physical extent along AxisU and AxisV
	Cols, Rows        int     // number of quads (>= 1); creates (Cols+1)*(Rows+1) particles
	TotalMass         float32 // <= 0 defaults to 1.0
	ParticleRadius    float32 // <= 0 defaults to 0.04
	StretchCompliance float32 // structural and shear compliance
	BendCompliance    float32 // dihedral bending compliance (0 defaults to 0.01 unless DisableBending)
	DisableBending    bool
	PinTopLeft        bool // pin (col=0, row=0)
	PinTopRight       bool // pin (col=Cols, row=0)
	PinBottomLeft     bool // pin (col=0, row=Rows)
	PinBottomRight    bool // pin (col=Cols, row=Rows)
	Layer             LayerMask
	Mask              LayerMask
	Friction          float32
}

ClothConfig configures a rectangular 3D cloth grid constructed by SoftWorld.AddCloth.

type ClothGrid struct {
	Particles []int
	Cols      int
	Rows      int
}

ClothGrid holds the particle layout created by SoftWorld.AddCloth.

func (g ClothGrid) Index(col, row int) int

Index returns the particle index in SoftWorld.Particles at grid vertex (col, row), or -1 when out of range.

type CompoundChild struct {
	// Shape is the child collider primitive (Box, Sphere, Capsule, ConvexHull,
	// Cylinder, or nested ShapeCompound).
	Shape Shape `json:"shape"`
	// Offset is the child's local translation relative to the compound origin.
	Offset Vec3 `json:"offset"`
	// Rot is the child's local orientation quaternion. A zero quaternion is
	// treated as identity.
	Rot Quat `json:"rot"`
	// Mass is an optional explicit mass in kilograms for this child.
	// When Mass <= 0 and Density > 0, mass is computed as Density * volume(Shape).
	// Trigger children do not contribute to body mass, center of mass, or inertia.
	Mass float32 `json:"mass,omitempty"`
	// Density is an optional mass per unit volume (kg/m^3) used when Mass <= 0.
	Density float32 `json:"density,omitempty"`
	// Trigger marks this child as a sensor volume that emits trigger ContactEvents
	// without applying collision impulses or contributing to body mass/inertia.
	Trigger bool `json:"trigger,omitempty"`
	// Layer is an optional collision layer bitmask for this child.
	// Zero inherits the parent Body.Layer (which defaults to LayerAll when zero).
	Layer LayerMask `json:"layer,omitempty"`
	// Mask is an optional collision mask bitmask for this child.
	// Zero inherits the parent Body.Mask (which defaults to LayerAll when zero).
	Mask LayerMask `json:"mask,omitempty"`
}

CompoundChild is one child collider inside a compound Shape, positioned in the parent's local coordinate frame by Offset and Rot.

func (c CompoundChild) EffectiveLayer(parentLayer LayerMask) LayerMask

EffectiveLayer returns c's collision layer, inheriting parentLayer when c.Layer is zero (and defaulting to LayerAll when both are zero).

func (c CompoundChild) EffectiveMask(parentMask LayerMask) LayerMask

EffectiveMask returns c's collision mask, inheriting parentMask when c.Mask is zero (and defaulting to LayerAll when both are zero).

func (c CompoundChild) LocalShape() Shape

LocalShape returns c.Shape transformed into the parent's local frame by c.Offset and c.Rot.

func (c CompoundChild) WorldShape(parentPos Vec3, parentRot Quat) Shape

WorldShape returns c.Shape transformed into world space by applying c's local Offset and Rot first and then the parent's pos and rot.

type CompoundMassProperties struct {
	// Mass is the total mass of all solid children in kilograms.
	Mass float32
	// CenterOfMass is the combined center of mass in the compound's local frame.
	CenterOfMass Vec3
	// Inertia is the 3x3 symmetric inertia tensor about CenterOfMass in local space.
	Inertia SymMat3
	// InvInertia is the inverse of Inertia in local space.
	InvInertia SymMat3
	// ScalarInvI is the isotropic mean inverse inertia 3 / (Ixx + Iyy + Izz).
	ScalarInvI float32
}

CompoundMassProperties holds the combined mass, local center of mass, and local inertia tensor (about CenterOfMass) computed from a compound shape's solid children using the parallel-axis theorem.

func ComputeCompoundMassProperties(children []CompoundChild, totalMass float32) CompoundMassProperties

ComputeCompoundMassProperties computes the combined mass, local center of mass, and 3x3 symmetric inertia tensor (using the parallel-axis theorem) from all non-trigger children.

When totalMass > 0, the returned Mass matches totalMass (distributing mass across unspecified children by volume or scaling explicit child masses to preserve relative ratios). When totalMass <= 0, Mass is the sum of explicit child masses and densities (0 if no child specifies Mass or Density).

type Contact struct {
	Hit    bool
	Normal Vec3
	Depth  float32
	Point  Vec3
}

Contact describes an overlap between two shapes A and B.

When Hit is true, Normal is a unit vector pointing from B toward A (the direction to translate A by Depth to separate it from B), Depth is the positive penetration depth, and Point is a representative contact point in world space.

func TestBoxBox(a, b Box) Contact

TestBoxBox tests two axis-aligned boxes for overlap.

func TestBoxCapsule(a Box, b Capsule) Contact

TestBoxCapsule tests an axis-aligned box a against a capsule b. The returned Contact normal points from b toward a. When the capsule's segment passes through the box, the normal and depth come from the separating axis theorem over the box faces and the edges crossed with the segment, so moving a by Normal*Depth separates the whole capsule rather than one sphere on it.

func TestBoxSphere(a Box, b Sphere) Contact

TestBoxSphere tests an axis-aligned box a against a sphere b. The returned Contact normal points from b toward a.

func TestBoxTriangle(b Box, tri Triangle) Contact

TestBoxTriangle tests axis-aligned box b against triangle tri using the 13-axis Separating Axis Theorem. The returned Contact normal points from tri toward b.

func TestCapsuleCapsule(a, b Capsule) Contact

TestCapsuleCapsule tests two capsules for overlap. When the two segments cross, the normal is perpendicular to both of them rather than an arbitrary axis.

func TestCapsuleTriangle(cap Capsule, tri Triangle) Contact

TestCapsuleTriangle tests capsule cap against triangle tri. The returned Contact normal points from tri toward cap.

func TestOrientedBoxBox(a Box, rotA Quat, b Box, rotB Quat) Contact

TestOrientedBoxBox tests two boxes, each rotated by its rotation about its own Center, with the separating axis theorem over the 15 face and edge axes. The returned Contact normal points from b toward a; Point is the average of the corners of either box that lie inside the other, so a box resting flat on another gets a point under its center and a tilted one gets its penetrating corner.

func TestShapeTriangle(s Shape, tri Triangle) Contact

TestShapeTriangle tests any Shape against a Triangle. The returned Contact normal points from tri toward s.

func TestShapes(a, b Shape) Contact

TestShapes tests two shapes for overlap. The returned Contact normal points from b toward a. Boxes oriented by Shape.Rot are tested exactly: two boxes with the separating axis theorem, and a box against a sphere or capsule in the box's own frame. Any pair with a convex hull or a cylinder is tested with GJK and EPA, and its Point is the middle of the area where the two shapes touch.

func TestSphereCapsule(a Sphere, b Capsule) Contact

TestSphereCapsule tests a sphere a against a capsule b. The returned Contact normal points from b toward a. A sphere centered on the capsule's segment is pushed out perpendicular to the segment.

func TestSphereSphere(a, b Sphere) Contact

TestSphereSphere tests two spheres for overlap.

func TestSphereTriangle(s Sphere, tri Triangle) Contact

TestSphereTriangle tests sphere s against triangle tri. The returned Contact normal points from tri toward s.

type ContactEvent struct {
	Kind        ContactEventKind
	BodyA       *Body
	BodyB       *Body
	ChildIndexA int
	ChildIndexB int
	Point       Vec3
	Normal      Vec3
	Depth       float32
	IsTrigger   bool
}

ContactEvent describes a deterministic contact or trigger transition between BodyA and BodyB (canonicalized so BodyA.ID <= BodyB.ID).

Normal points from BodyB toward BodyA (matching TestShapes(BodyA, BodyB)). ChildIndexA and ChildIndexB report the zero-based compound child indices on BodyA and BodyB, or -1 for non-compound bodies.

type ContactEventKind int

ContactEventKind identifies the lifecycle transition of a contact or trigger pair.

const (
	// ContactEnter fires once on the first step two bodies begin overlapping.
	ContactEnter ContactEventKind = iota
	// ContactStay fires on each subsequent step the two bodies remain overlapping.
	ContactStay
	// ContactExit fires once when two previously overlapping bodies separate or
	// either body is removed from the World.
	ContactExit
)
type ContactEventSnapshot struct {
	Kind        ContactEventKind `json:"kind"`
	BodyAID     int              `json:"bodyAID"`
	BodyBID     int              `json:"bodyBID"`
	ChildIndexA int              `json:"childIndexA"`
	ChildIndexB int              `json:"childIndexB"`
	Point       Vec3             `json:"point"`
	Normal      Vec3             `json:"normal"`
	Depth       float32          `json:"depth"`
	IsTrigger   bool             `json:"isTrigger,omitempty"`
}

ContactEventSnapshot captures one ContactEvent produced by the last Step.

func (e *ContactEventSnapshot) UnmarshalJSON(data []byte) error

UnmarshalJSON defaults ChildIndexA and ChildIndexB to -1 when omitted in pre-compound v1 snapshots.

type ConvexHull struct {
	// Center is where the hull's local origin sits.
	Center Vec3
	// contains filtered or unexported fields
}

ConvexHull is a convex polyhedron for collision. Build one with NewConvexHull or ConvexHullFromMesh; the zero value is empty and collides with nothing.

The hull's vertices are fixed when it is built and are relative to Center, which Translated and Shape.Transformed move. A Shape that wraps a hull may also set Rot, which turns the hull about Center, as it does for a Box.

func ConvexHullFromMesh(positions []math3d.Vec3, indices []uint32, maxVertices int) (ConvexHull, error)

ConvexHullFromMesh returns the convex hull of a triangle mesh's vertices, such as a glTF primitive's Positions and Indices or a render3d.Mesh's. When indices is not empty only the vertices it references are used; otherwise every position is. maxVertices is as for NewConvexHull.

func NewConvexHull(points []Vec3, maxVertices int) (ConvexHull, error)

NewConvexHull returns the convex hull of points, keeping at most maxVertices of them as its vertices (DefaultHullVertices when maxVertices <= 0, and never more than MaxHullVertices). A limit of 1 to 3 is raised to 4, the fewest vertices a hull with volume has.

The hull is built by quickhull, which adds the point furthest outside the hull so far until none is left or the limit is reached. When the limit stops it early, the hull is the hull of the points kept: it lies inside the full hull and keeps its most prominent corners. Points within a small tolerance of a face are dropped, and coplanar triangles are merged into polygon faces. The result depends only on the points and their order, never on map order or the platform's scheduling, so the same input always gives the same hull.

It returns ErrDegenerateHull when the points do not span a volume.

func (h ConvexHull) Centroid() Vec3

Centroid returns h's center of mass for uniform density, Center plus the centroid of its vertices' volume.

func (h ConvexHull) Edges() [][2]int

Edges returns a copy of h's edges, each a pair of indices into Vertices with the smaller first, in a fixed order.

func (h ConvexHull) FaceNormals() []Vec3

FaceNormals returns the outward unit normal of each face, in the order of Faces.

func (h ConvexHull) Faces() [][]int

Faces returns a copy of h's faces, each a list of indices into Vertices in counter-clockwise order seen from outside the hull.

func (h ConvexHull) InertiaTensor(mass float32) [3]Vec3

InertiaTensor returns the inertia tensor of h with the given mass and uniform density, about its centroid, in its local axes, as rows.

func (h ConvexHull) IsEmpty() bool

IsEmpty reports whether h has no geometry, as the zero ConvexHull has.

func (h ConvexHull) MarshalJSON() ([]byte, error)

MarshalJSON encodes h with its full geometry, so that WorldSnapshot round-trips bodies with convex hull shapes losslessly.

func (h ConvexHull) NumVertices() int

NumVertices returns how many vertices h has.

func (h ConvexHull) Recentered() ConvexHull

Recentered returns h with its vertices moved so that its centroid is at the local origin and Center moved by the same amount, so it covers the same space. A body built from a recentered hull at the hull's position rotates about its center of mass.

func (h ConvexHull) Translated(offset Vec3) ConvexHull

Translated returns a copy of h shifted by offset.

func (h *ConvexHull) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes a hull written by MarshalJSON. It refuses unknown fields and geometry whose indices are out of range or whose numbers are not finite.

func (h ConvexHull) Vertices() []Vec3

Vertices returns a copy of h's vertices relative to Center.

func (h ConvexHull) Volume() float32

Volume returns h's volume.

type CoverOptions struct {
	// Spacing is the horizontal distance between cover samples along each collider face (defaults to 1.0 when <= 0).
	Spacing float32
	// Standoff offsets each cover point outward from the collider face into open space (defaults to 0.5 when <= 0).
	Standoff float32
	// EdgeInset is the margin from face corners (defaults to Spacing * 0.5 when <= 0).
	EdgeInset float32
	// MinEdgeLength skips horizontal faces shorter than this length (<= 0 allows any positive face).
	MinEdgeLength float32
	// HalfCoverMinHeight is the minimum obstacle vertical height for CoverHalf (defaults to 0.7 when <= 0).
	// Shorter obstacles (such as floor slabs) do not generate cover.
	HalfCoverMinHeight float32
	// FullCoverMinHeight is the minimum obstacle vertical height for CoverFull (defaults to 1.6 when <= 0).
	FullCoverMinHeight float32
	// LayerMask filters bodies considered as cover obstacles (0 defaults to LayerAll).
	LayerMask LayerMask
	// IncludeDynamic includes non-static bodies when true; by default only static level geometry generates cover.
	IncludeDynamic bool
	// StartID is the first CoverPoint.ID assigned (defaults to 1 when 0).
	StartID uint64
}

CoverOptions configures 3D collider-edge cover point generation projected onto the XZ ground plane.

Generated ai.CoverPoint values store (X, Z) in Pos, the obstacle's floor Y in Elevation, and the horizontal XZ unit direction into the obstacle in Facing.

type Cylinder struct {
	A, B   Vec3
	Radius float32
}

Cylinder is a solid round cylinder whose axis runs from the center of its A cap to the center of its B cap, with flat caps of the given Radius (#808). A cylinder whose A and B coincide or whose Radius is not positive has no volume: collisions, raycasts and areas ignore it.

func VerticalCylinder(center Vec3, radius, height float32) Cylinder

VerticalCylinder returns a Y-aligned cylinder centered at center with the given radius and total height, such as a barrel standing on its end.

func (c Cylinder) Center() Vec3

Center returns the midpoint of c's axis.

func (c Cylinder) Height() float32

Height returns the length of c's axis.

func (c Cylinder) Translated(offset Vec3) Cylinder

Translated returns a copy of c shifted by offset.

type DebugStyle struct {
	BoxColor     core.Color
	SphereColor  core.Color
	CapsuleColor core.Color
	// HullColor draws convex hulls.
	HullColor core.Color
	// CylinderColor draws cylinders.
	CylinderColor  core.Color
	ContactColor   core.Color
	NormalColor    core.Color
	RayColor       core.Color
	LineWidth      float32
	SphereSegments int
	NormalLength   float32
	// DepthZO clips at the near plane of a [0, 1] depth projection (clip z >= 0), such as math3d.Perspective, math3d.Ortho and the render3d cameras, as render3d.ProjectSegment does. By default lines clip at clip z >= -w, the near plane of this package's [-1, 1] Mat4Perspective and Mat4Ortho; with a [0, 1] orthographic projection, where w is 1 everywhere, that keeps geometry behind the camera (#546).
	DepthZO bool
}

DebugStyle configures the colors, stroke width, and tessellation used by physics3d debug drawing functions. Zero-valued fields fall back to DefaultDebugStyle().

func DefaultDebugStyle() DebugStyle

DefaultDebugStyle returns a high-contrast DebugStyle suitable for overlaying 3D collider wireframes on a game scene.

type DistanceConstraint struct {
	A, B       int
	RestLength float32
	Compliance float32
	MaxOnly    bool
	// contains filtered or unexported fields
}

DistanceConstraint constrains the Euclidean distance between particles A and B. When MaxOnly is true, the constraint acts as a unilateral tether that only pulls particles together when their separation exceeds RestLength.

type DistanceJoint struct {
	BodyA, BodyB     *Body
	LocalAnchorA     Vec3
	LocalAnchorB     Vec3
	MinDistance      float32
	MaxDistance      float32
	Stiffness        float32 // 0 = rigid constraint; > 0 = soft spring stiffness
	Damping          float32 // >= 0 damping coefficient
	BreakForce       float32 // max reaction force in N before breaking (<= 0 disables)
	BreakTorque      float32 // max reaction torque in N*m before breaking (<= 0 disables)
	CollideConnected bool
	// contains filtered or unexported fields
}

DistanceJoint constrains the distance between anchor points on BodyA and BodyB within [MinDistance, MaxDistance] with optional spring stiffness and damping.

The joint is slack while the distance is inside the range: Stiffness and Damping soften the limits rather than pull toward a rest length. For a spring with a rest length L, set MinDistance and MaxDistance both to L; for a soft rope, set MinDistance to 0.

func NewDistanceJoint(a, b *Body, localAnchorA, localAnchorB Vec3, minDist, maxDist float32) *DistanceJoint

NewDistanceJoint creates a DistanceJoint between a and b. If maxDist < minDist, maxDist is set equal to minDist (a fixed-length rod).

func (j *DistanceJoint) Bodies() (*Body, *Body)

Bodies returns the connected bodies.

func (r *DistanceJoint) Broken() bool

Broken reports whether the joint has exceeded its break threshold and been removed.

func (j *DistanceJoint) Prepare(dt float32)

Prepare computes the active distance mode and spring ERP/CFM parameters for dt.

func (r *DistanceJoint) ReactionForce() Vec3

ReactionForce returns the world-space constraint force (in Newtons) applied to BodyB during the most recent World.Step.

func (r *DistanceJoint) ReactionTorque() Vec3

ReactionTorque returns the world-space constraint torque (in N*m) applied to BodyB during the most recent World.Step.

func (j *DistanceJoint) SolvePosition(dt float32)

SolvePosition corrects distance drift for rigid (Stiffness <= 0) DistanceJoints.

func (j *DistanceJoint) SolveVelocity(dt float32)

SolveVelocity applies one velocity iteration along the anchor axis.

type DriveMode int

DriveMode selects how a SixDOFJoint axis drive operates.

const (
	// DriveNone disables explicit motor driving (Stiffness > 0 or Damping > 0
	// still acts as a passive spring-damper toward TargetPos).
	DriveNone DriveMode = iota
	// DrivePosition drives the axis toward TargetPos using Stiffness and Damping
	// (or a direct velocity servo when both are 0), clamped by MaxForce when > 0.
	DrivePosition
	// DriveVelocity drives the axis toward TargetVel, clamped by MaxForce when > 0.
	DriveVelocity
)
type FixedJoint struct {
	BodyA, BodyB     *Body
	LocalAnchorA     Vec3
	LocalAnchorB     Vec3
	RefRelRot        Quat
	BreakForce       float32 // max reaction force in N before breaking (<= 0 disables)
	BreakTorque      float32 // max reaction torque in N*m before breaking (<= 0 disables)
	CollideConnected bool
	// contains filtered or unexported fields
}

FixedJoint rigidly locks both relative position and relative orientation between BodyA and BodyB.

func NewFixedJoint(a, b *Body, localAnchorA, localAnchorB Vec3) *FixedJoint

NewFixedJoint creates a FixedJoint locking a and b at their current relative orientation and specified local anchor points.

func (j *FixedJoint) Bodies() (*Body, *Body)

Bodies returns the connected bodies.

func (r *FixedJoint) Broken() bool

Broken reports whether the joint has exceeded its break threshold and been removed.

func (j *FixedJoint) Prepare(dt float32)

Prepare captures the reference relative orientation if not already set.

func (r *FixedJoint) ReactionForce() Vec3

ReactionForce returns the world-space constraint force (in Newtons) applied to BodyB during the most recent World.Step.

func (r *FixedJoint) ReactionTorque() Vec3

ReactionTorque returns the world-space constraint torque (in N*m) applied to BodyB during the most recent World.Step.

func (j *FixedJoint) SolvePosition(dt float32)

SolvePosition corrects linear and angular drift from the locked relative pose.

func (j *FixedJoint) SolveVelocity(dt float32)

SolveVelocity solves the 6-DOF linear and angular lock.

type GLTFColliderOptions struct {
	// UseScene selects doc.Scenes[Scene] when true. When false, the document's
	// default scene (doc.Scene, falling back to scene 0 or all nodes) is used.
	UseScene bool
	// Scene is the scene index inspected when UseScene is true.
	Scene int

	// IncludeUnmarked builds static TriMeshColliders for ordinary mesh nodes
	// that carry neither a collider name suffix nor extras.collider metadata.
	// When false (default), only annotated collider nodes produce colliders.
	IncludeUnmarked bool

	// Friction is the default Coulomb friction coefficient for generated
	// colliders when not overridden by extras.collider (<= 0 defaults to 0.5).
	Friction float32
	// Restitution is the default bounciness in [0, 1] when not overridden.
	Restitution float32
	// Layer is the default collision layer mask when not overridden (0 -> LayerAll).
	Layer LayerMask
	// Mask is the default collision filter mask when not overridden (0 -> LayerAll).
	Mask LayerMask
	// TagPrefix is optionally prepended to generated collider tags.
	TagPrefix string
}

GLTFColliderOptions configures how colliders are built from a glTF document.

type GLTFColliders struct {
	Bodies    []*Body
	TriMeshes []*TriMeshCollider
}

GLTFColliders holds the static primitive bodies and triangle-mesh colliders extracted from a glTF document.

func BuildGLTFColliders(doc *gltf.Document, opts GLTFColliderOptions) (*GLTFColliders, error)

BuildGLTFColliders extracts static collider bodies and TriMeshColliders from doc according to glTF collider naming conventions (-col, -colonly, -boxcol, -boxcolonly, -spherecol, -spherecolonly, -capsulecol, -capsulecolonly, -convcol, -convcolonly) and node extras.collider metadata.

Node transforms are read from Node.WorldMatrix (computed automatically by gltf.Load / gltf.LoadFS and refreshed by doc.ComputeWorldMatrices).

func (c *GLTFColliders) AddToWorld(w *World)

AddToWorld registers every body and triangle-mesh collider in c into w, updating c.Bodies to reference the stored *Body pointers returned by w.AddBody.

func (c *GLTFColliders) RemoveFromWorld(w *World)

RemoveFromWorld removes every registered body and triangle-mesh collider in c from w.

type GravityFalloff uint8

GravityFalloff controls how point-gravity acceleration varies with distance from GravityPoint.

const (
	// GravityFalloffNone applies constant GravityStrength regardless of distance (zero value).
	GravityFalloffNone GravityFalloff = iota
	// GravityFalloffLinear decreases acceleration linearly from GravityStrength at
	// distance 0 to 0 at GravityUnitDistance (or the trigger shape's outer radius
	// when GravityUnitDistance <= 0).
	GravityFalloffLinear
	// GravityFalloffInverse scales acceleration as GravityStrength * (unitDist / dist).
	GravityFalloffInverse
	// GravityFalloffInverseSquare scales acceleration as GravityStrength * (unitDist / dist)^2.
	GravityFalloffInverseSquare
)
type HeightfieldCollider struct {
	ID          int
	Tag         string
	Layer       LayerMask
	Mask        LayerMask
	Friction    float32
	Restitution float32
	Cols        int
	Rows        int
	CellSize    float32
	Origin      Vec3
	Heights     []float32
	Bounds      Box
}

HeightfieldCollider is a static terrain heightfield collider on a regular XZ grid with exact barycentric surface interpolation, DDA raycasting, and sphere/capsule/box collision.

Vertex (cx, cz) sits at world position:

(Origin.X + cx*CellSize, Origin.Y + Heights[cz*Cols + cx], Origin.Z + cz*CellSize)
func NewHeightfieldCollider(cols, rows int, cellSize float32, origin Vec3, heights []float32) *HeightfieldCollider

NewHeightfieldCollider constructs a HeightfieldCollider matching world3d.Heightmap grid conventions (row-major heights[cz*cols + cx]).

func NewHeightfieldFromImage(img image.Image, opts HeightfieldImageOptions) (*HeightfieldCollider, error)

NewHeightfieldFromImage builds a static HeightfieldCollider from any standard Go image.Image (grayscale 8-bit, 16-bit Gray16, RGBA, NRGBA, RGBA64, etc.).

func (hf *HeightfieldCollider) CollectContacts(s Shape, dst []Contact) []Contact

CollectContacts appends all overlapping heightfield triangle contacts for s to dst.

func (hf *HeightfieldCollider) HeightAt(x, z float32) (float32, bool)

HeightAt returns the exact barycentric terrain elevation at world (x, z) and whether (x, z) lies within the heightfield's XZ footprint.

func (hf *HeightfieldCollider) NormalAt(x, z float32) Vec3

NormalAt returns the outward unit surface normal of the terrain at world (x, z). Coordinates outside the footprint are clamped to the nearest boundary cell.

func (hf *HeightfieldCollider) QueryTriangles(bounds Box, visit func(tri Triangle))

QueryTriangles visits every terrain triangle overlapping the XZ footprint of bounds.

func (hf *HeightfieldCollider) Raycast(ray Ray) (RaycastHit, bool)

Raycast intersects ray with the heightfield using clipped 2D DDA grid traversal over only the cells crossed by the ray.

func (hf *HeightfieldCollider) ShapeCast(shape Shape, delta Vec3) (RaycastHit, bool)

ShapeCast sweeps shape along displacement delta against hf and returns the earliest hit.

func (hf *HeightfieldCollider) TestShape(s Shape) Contact

TestShape returns the deepest Contact between s and hf (normal pointing from terrain upward toward s).

type HeightfieldImageOptions struct {
	// CellSize sets the horizontal spacing between adjacent grid vertices in
	// world units. If WorldWidth > 0, CellSize is derived as
	// WorldWidth / float32(cols-1) instead. Defaults to 1.0 when both are <= 0.
	CellSize float32
	// WorldWidth optionally sets the total X span of the heightfield in world
	// units (overriding CellSize).
	WorldWidth float32
	// WorldDepth optionally sets the total Z span of the heightfield in world
	// units. When WorldDepth > 0 and Rows == 0, Rows is derived from
	// round(WorldDepth/CellSize)+1 (at least 2) so the terrain spans WorldDepth
	// using HeightfieldCollider's square CellSize.
	WorldDepth float32
	// Cols and Rows optionally resample the image to a target vertex grid
	// resolution (0 keeps the image's width/height; when set, must be >= 2).
	Cols int
	Rows int
	// Bilinear enables bilinear filtering when sampling the image at fractional
	// pixel coordinates (used when Cols/Rows differ from the source image
	// dimensions). When false, nearest-neighbor sampling is used.
	Bilinear bool
	// MinHeight and MaxHeight map normalized pixel values [0, 1] linearly to
	// [MinHeight, MaxHeight]. When both are 0, MaxHeight defaults to 1.0.
	MinHeight float32
	MaxHeight float32
	// Origin is the world-space position of vertex (0, 0) at height 0.
	Origin Vec3
	// Channel selects how pixel colors map to normalized height (defaults to
	// HeightmapLuminance).
	Channel HeightmapChannel
	// FlipZ reverses the image Y -> world Z row order when true.
	FlipZ bool
	// Tag, Friction, Restitution, Layer, and Mask populate the corresponding
	// HeightfieldCollider fields. Friction <= 0 defaults to 0.5.
	Tag         string
	Friction    float32
	Restitution float32
	Layer       LayerMask
	Mask        LayerMask
}

HeightfieldImageOptions configures NewHeightfieldFromImage.

type HeightfieldSnapshot struct {
	ID          int       `json:"id"`
	Tag         string    `json:"tag,omitempty"`
	Layer       LayerMask `json:"layer"`
	Mask        LayerMask `json:"mask"`
	Friction    float32   `json:"friction"`
	Restitution float32   `json:"restitution"`
	Cols        int       `json:"cols"`
	Rows        int       `json:"rows"`
	CellSize    float32   `json:"cellSize"`
	Origin      Vec3      `json:"origin"`
	Heights     []float32 `json:"heights,omitempty"`
}

HeightfieldSnapshot captures a static HeightfieldCollider.

type HeightmapChannel int

HeightmapChannel selects which color channel of an image.Image supplies normalized height samples in [0, 1] for NewHeightfieldFromImage.

const (
	// HeightmapLuminance converts each pixel to 16-bit luminance (matching
	// color.Gray16Model and preserving exact 16-bit grayscale values).
	HeightmapLuminance HeightmapChannel = iota
	// HeightmapRed reads the red channel.
	HeightmapRed
	// HeightmapGreen reads the green channel.
	HeightmapGreen
	// HeightmapBlue reads the blue channel.
	HeightmapBlue
	// HeightmapAlpha reads the alpha channel.
	HeightmapAlpha
)
type HingeJoint struct {
	BodyA, BodyB     *Body
	LocalAnchorA     Vec3
	LocalAnchorB     Vec3
	LocalAxisA       Vec3 // hinge axis in A's local space (defaults to +Y)
	LocalAxisB       Vec3 // hinge axis in B's local space (defaults to LocalAxisA)
	EnableLimits     bool
	MinAngle         float32 // radians
	MaxAngle         float32 // radians
	MotorTargetVel   float32 // desired angular velocity around hinge axis (rad/s)
	MotorMaxTorque   float32 // max motor torque (N*m); motor active when > 0
	DriveTargetAngle float32 // target angle in radians for spring/position drive
	DriveStiffness   float32 // spring stiffness in N*m/rad (> 0 enables position spring)
	DriveDamping     float32 // angular damping in N*m*s/rad (>= 0)
	DriveMaxTorque   float32 // max drive torque in N*m (<= 0 means unlimited)
	BreakForce       float32 // max reaction force in N before breaking (<= 0 disables)
	BreakTorque      float32 // max reaction torque in N*m before breaking (<= 0 disables)
	CollideConnected bool
	// contains filtered or unexported fields
}

HingeJoint constrains two bodies to rotate around a single shared axis at an anchor point, with optional angular limits, velocity motor, spring/position drive, and break thresholds.

func NewHingeJoint(a, b *Body, localAnchorA, localAnchorB, localAxis Vec3) *HingeJoint

NewHingeJoint creates a HingeJoint between a and b around localAxis.

func (j *HingeJoint) Angle() float32

Angle returns the signed hinge rotation in radians around the hinge axis from the initial relative orientation.

The angle is tracked across steps, so a hinge that keeps turning reports 3*pi/2 rather than -pi/2 and limits beyond ±pi, such as a valve with MaxAngle 4*pi, work. It assumes the hinge turns less than pi per step.

func (j *HingeJoint) Bodies() (*Body, *Body)

Bodies returns the connected bodies.

func (r *HingeJoint) Broken() bool

Broken reports whether the joint has exceeded its break threshold and been removed.

func (j *HingeJoint) Prepare(dt float32)

Prepare initializes the reference frame, wakes motorized or spring-driven bodies, and checks limits.

func (r *HingeJoint) ReactionForce() Vec3

ReactionForce returns the world-space constraint force (in Newtons) applied to BodyB during the most recent World.Step.

func (r *HingeJoint) ReactionTorque() Vec3

ReactionTorque returns the world-space constraint torque (in N*m) applied to BodyB during the most recent World.Step.

func (j *HingeJoint) SolvePosition(dt float32)

SolvePosition corrects hinge anchor, axis alignment, and angular limit violations.

func (j *HingeJoint) SolveVelocity(dt float32)

SolveVelocity solves the hinge anchor, axis alignment, motor, spring/position drive, and angular limits.

type Joint3D interface {
	// Bodies returns the pair of bodies connected by the joint.
	Bodies() (*Body, *Body)
	// Prepare updates per-step cached values before velocity iterations.
	Prepare(dt float32)
	// SolveVelocity applies one sequential-impulse velocity iteration.
	SolveVelocity(dt float32)
	// SolvePosition applies one non-linear Gauss-Seidel positional and angular
	// correction iteration.
	SolvePosition(dt float32)
}

Joint3D constrains the relative motion of one or two bodies inside a World. Either body may be nil to anchor the constraint directly to the world frame.

type JointBreakEvent struct {
	Joint  Joint3D
	BodyA  *Body
	BodyB  *Body
	Force  Vec3
	Torque Vec3
}

JointBreakEvent reports a joint that broke during World.Step because its reaction force or torque exceeded its BreakForce or BreakTorque threshold.

type JointBreakEventSnapshot struct {
	Joint   *JointSnapshot `json:"joint,omitempty"`
	BodyAID int            `json:"bodyAID"`
	BodyBID int            `json:"bodyBID"`
	Force   Vec3           `json:"force"`
	Torque  Vec3           `json:"torque"`
}

JointBreakEventSnapshot captures one JointBreakEvent from the last Step.

type JointReactionSnapshot struct {
	StepLinearImpulse  Vec3    `json:"stepLinearImpulse"`
	StepAngularImpulse Vec3    `json:"stepAngularImpulse"`
	LastDt             float32 `json:"lastDt,omitempty"`
	Broken             bool    `json:"broken,omitempty"`
}

JointReactionSnapshot captures the per-step reaction accumulator shared by built-in joints.

type JointSnapshot struct {
	Kind             string                `json:"kind"` // "distance", "ball", "hinge", "slider", "fixed", "swingtwist", "sixdof"
	BodyAID          int                   `json:"bodyAID"`
	BodyBID          int                   `json:"bodyBID"`
	LocalAnchorA     Vec3                  `json:"localAnchorA"`
	LocalAnchorB     Vec3                  `json:"localAnchorB"`
	BreakForce       float32               `json:"breakForce,omitempty"`
	BreakTorque      float32               `json:"breakTorque,omitempty"`
	CollideConnected bool                  `json:"collideConnected,omitempty"`
	Reaction         JointReactionSnapshot `json:"reaction"`

	// DistanceJoint fields
	MinDistance float32 `json:"minDistance,omitempty"`
	MaxDistance float32 `json:"maxDistance,omitempty"`
	Stiffness   float32 `json:"stiffness,omitempty"`
	Damping     float32 `json:"damping,omitempty"`
	AccImpulse  float32 `json:"accImpulse,omitempty"`
	Mode        int     `json:"mode,omitempty"`
	TargetDist  float32 `json:"targetDist,omitempty"`
	Gamma       float32 `json:"gamma,omitempty"`
	Bias        float32 `json:"bias,omitempty"`

	// BallJoint / HingeJoint / SliderJoint fields
	ConeLimit        float32 `json:"coneLimit,omitempty"`
	LocalAxisA       Vec3    `json:"localAxisA"`
	LocalAxisB       Vec3    `json:"localAxisB"`
	EnableLimits     bool    `json:"enableLimits,omitempty"`
	MinAngle         float32 `json:"minAngle,omitempty"`
	MaxAngle         float32 `json:"maxAngle,omitempty"`
	MinTranslation   float32 `json:"minTranslation,omitempty"`
	MaxTranslation   float32 `json:"maxTranslation,omitempty"`
	MotorTargetVel   float32 `json:"motorTargetVel,omitempty"`
	MotorMaxTorque   float32 `json:"motorMaxTorque,omitempty"`
	MotorMaxForce    float32 `json:"motorMaxForce,omitempty"`
	DriveTargetAngle float32 `json:"driveTargetAngle,omitempty"`
	DriveTargetPos   float32 `json:"driveTargetPos,omitempty"`
	DriveStiffness   float32 `json:"driveStiffness,omitempty"`
	DriveDamping     float32 `json:"driveDamping,omitempty"`
	DriveMaxTorque   float32 `json:"driveMaxTorque,omitempty"`
	DriveMaxForce    float32 `json:"driveMaxForce,omitempty"`

	// Shared private reference/impulse state
	RefInitialized bool    `json:"refInitialized,omitempty"`
	RefPerpA       Vec3    `json:"refPerpA"`
	RefPerpB       Vec3    `json:"refPerpB"`
	RefRelRot      Quat    `json:"refRelRot"`
	MotorImpulse   float32 `json:"motorImpulse,omitempty"`
	DriveImpulse   float32 `json:"driveImpulse,omitempty"`
	DriveGamma     float32 `json:"driveGamma,omitempty"`
	DriveBias      float32 `json:"driveBias,omitempty"`
	DriveActive    bool    `json:"driveActive,omitempty"`
	LimitImpulse   float32 `json:"limitImpulse,omitempty"`
	LimitState     int     `json:"limitState,omitempty"`
	Angle          float32 `json:"angle,omitempty"`
	SwingImpulse   float32 `json:"swingImpulse,omitempty"`

	// SwingTwistJoint fields
	TwistAxisA        Vec3    `json:"twistAxisA"`
	TwistAxisB        Vec3    `json:"twistAxisB"`
	PlaneAxisA        Vec3    `json:"planeAxisA"`
	PlaneAxisB        Vec3    `json:"planeAxisB"`
	EnableSwingLimits bool    `json:"enableSwingLimits,omitempty"`
	SwingMin1         float32 `json:"swingMin1,omitempty"`
	SwingMax1         float32 `json:"swingMax1,omitempty"`
	SwingMin2         float32 `json:"swingMin2,omitempty"`
	SwingMax2         float32 `json:"swingMax2,omitempty"`
	EnableTwistLimits bool    `json:"enableTwistLimits,omitempty"`
	MinTwist          float32 `json:"minTwist,omitempty"`
	MaxTwist          float32 `json:"maxTwist,omitempty"`
	TwistImpulse      float32 `json:"twistImpulse,omitempty"`
	TwistLimitState   int     `json:"twistLimitState,omitempty"`

	// SixDOFJoint fields
	LocalFrameA     Quat                       `json:"localFrameA"`
	LocalFrameB     Quat                       `json:"localFrameB"`
	Linear          [3]AxisConfig              `json:"linear"`
	Angular         [3]AxisConfig              `json:"angular"`
	LinState        [3]SixDOFAxisStateSnapshot `json:"linState"`
	AngState        [3]SixDOFAxisStateSnapshot `json:"angState"`
	SingleAxisAngle float32                    `json:"singleAxisAngle,omitempty"`
	SingleAxisIdx   int                        `json:"singleAxisIdx,omitempty"`
}

JointSnapshot captures the complete public and private solver state of any built-in Joint3D.

type LayerMask uint32

LayerMask is a 32-bit collision layer bitmask.

const LayerAll LayerMask = ^LayerMask(0)

LayerAll matches every collision layer.

func LayerBit(i uint) LayerMask

LayerBit returns a LayerMask with only bit i set (0 <= i < 32). Values >= 32 return 0.

type Mat4 [16]float32

Mat4 is a 4x4 matrix stored in column-major order, matching OpenGL, WebGPU, and glTF conventions. Element (row, col) is stored at index col*4 + row, so the translation column occupies indices 12, 13, and 14.

func Mat4Identity() Mat4

Mat4Identity returns the 4x4 identity matrix.

func Mat4LookAt(eye, target, up Vec3) Mat4

Mat4LookAt returns a right-handed view matrix placing the camera at eye, looking toward target, with world up direction up.

func Mat4Mul(a, b Mat4) Mat4

Mat4Mul returns the matrix product a * b (column-major).

func Mat4Ortho(left, right, bottom, top, near, far float32) Mat4

Mat4Ortho returns a right-handed orthographic projection matrix mapping [left, right] x [bottom, top] x [-near, -far] to normalized device coordinates [-1, 1]^3. Degenerate planes return Mat4Identity().

func Mat4Perspective(fovYRad, aspect, near, far float32) Mat4

Mat4Perspective returns a right-handed perspective projection matrix mapping view-space Z in [-near, -far] to normalized device coordinates Z in [-1, 1]. fovYRad is the vertical field of view in radians, aspect is width/height, and near and far are positive distances to the clipping planes (0 < near < far). Degenerate parameters return Mat4Identity().

type MoveResult struct {
	Pos            Vec3
	Grounded       bool
	GroundNormal   Vec3
	GroundBody     *Body
	GroundVelocity Vec3
	GroundYawDelta float32
	OnWall         bool
	OnCeiling      bool
	SteppedUp      bool
	Crushed        bool
}

MoveResult summarizes the outcome of a CharacterController.Move call.

type OverlapHit struct {
	Body        *Body
	ChildIndex  int
	TriMesh     *TriMeshCollider
	Heightfield *HeightfieldCollider
	Voxel       *VoxelCollider
	Contact     Contact
}

OverlapHit reports a body or static collider overlapped by World.QueryOverlap or World.OverlapLayer. Contact.Normal points from the collider toward the query shape.

type PairKeySnapshot struct {
	A int `json:"a"`
	B int `json:"b"`
}

PairKeySnapshot is a JSON-serializable body ID pair.

type Particle struct {
	Pos         Vec3
	PrevPos     Vec3
	Vel         Vec3
	InvMass     float32
	Radius      float32
	Friction    float32
	Restitution float32
	Pinned      bool
	Layer       LayerMask
	Mask        LayerMask
	// contains filtered or unexported fields
}

Particle is a 3D point mass simulated by SoftWorld using Extended Position-Based Dynamics (XPBD). Set Pinned to true or InvMass to 0 to fix a particle in place. Zero Layer or Mask values default to LayerAll.

func (p *Particle) ApplyForce(f Vec3)

ApplyForce accumulates a world-space force applied to p during the next SoftWorld.Step.

func (p *Particle) IsPinned() bool

IsPinned reports whether p has infinite mass (Pinned is true or InvMass <= 0).

func (p *Particle) SetMass(mass float32)

SetMass sets p's inverse mass to 1/mass when mass > 0, or 0 when mass <= 0.

type PhysicsMaterial struct {
	// Friction is the Coulomb friction coefficient (>= 0).
	Friction float32 `json:"friction"`
	// Restitution is the bounciness in [0, 1].
	Restitution float32 `json:"restitution"`
	// LinearDamping reduces linear velocity smoothly over time (>= 0).
	LinearDamping float32 `json:"linearDamping"`
	// AngularDamping reduces angular velocity smoothly over time (>= 0).
	AngularDamping float32 `json:"angularDamping"`
}

PhysicsMaterial holds surface and damping properties for 3D physics bodies. Assign a *PhysicsMaterial to Body.Material to share properties across bodies, or copy it onto one body with Body.ApplyMaterial.

type PlatformOnLeave int

PlatformOnLeave controls how a CharacterController inherits the moving ground body's velocity when leaving it (by jumping or walking off).

const (
	// PlatformLeaveAddVelocity adds the full ground velocity at the contact
	// point to the character's velocity when leaving a moving ground body.
	// This is the default zero value.
	PlatformLeaveAddVelocity PlatformOnLeave = iota
	// PlatformLeaveAddUpwardVelocity adds the ground velocity when leaving a
	// moving ground body, clamping any downward (negative Y) component to zero
	// so jumping or stepping off a descending platform is not pulled downward.
	PlatformLeaveAddUpwardVelocity
	// PlatformLeaveDoNothing drops the platform's velocity upon leaving.
	PlatformLeaveDoNothing
)
type Quat struct {
	X, Y, Z, W float32
}

Quat is a unit quaternion representing a 3D rotation (X, Y, Z imaginary; W real). The zero value Quat{} is treated as the identity rotation by Body and Quat helpers.

func IntegrateQuat(q Quat, angVel Vec3, dt float32) Quat

IntegrateQuat integrates world-space angular velocity angVel over dt seconds onto q using the exact exponential map.

func QuatFromAxisAngle(axis Vec3, angle float32) Quat

QuatFromAxisAngle returns the unit quaternion representing a right-handed rotation of angle radians around axis. If axis is zero, QuatIdentity is returned.

func QuatFromTo(from, to Vec3) Quat

QuatFromTo returns the shortest-arc unit quaternion rotating direction from to to.

func QuatIdentity() Quat

QuatIdentity returns the identity rotation quaternion.

func (q Quat) AngleTo(b Quat) float32

AngleTo returns the shortest angular distance in radians between q and b in [0, pi].

func (q Quat) Conjugate() Quat

Conjugate returns the quaternion conjugate (inverse for unit quaternions).

func (q Quat) Dot(b Quat) float32

Dot returns the 4D dot product of q and b.

func (q Quat) IsIdentity() bool

IsIdentity reports whether q represents no rotation (including the zero Quat{}).

func (q Quat) LenSq() float32

LenSq returns the squared quaternion norm.

func (q Quat) Mul(b Quat) Quat

Mul returns the Hamilton product q * b (applying b then q).

func (q Quat) Norm() Quat

Norm returns the normalized unit quaternion, or QuatIdentity if q is zero.

func (q Quat) RotateVec(v Vec3) Vec3

RotateVec rotates v by the unit quaternion q.

func (q Quat) Slerp(b Quat, t float32) Quat

Slerp performs shortest-arc spherical linear interpolation from q to b by t in [0, 1].

func (q Quat) ToAxisAngle() (Vec3, float32)

ToAxisAngle decomposes q into a unit axis and an angle in [0, pi].

type Ragdoll struct {
	World       *World
	Skeleton    []SkeletonJoint
	Bodies      []*Body
	Joints      []Joint3D
	Mode        RagdollMode
	BlendWeight float32 // [0, 1]: 0 = animated pose, 1 = full physics (used in RagdollBlended)
	// contains filtered or unexported fields
}

Ragdoll manages the rigid bodies and joint constraints generated from a skeletal hierarchy, supporting kinematic animation following, dynamic ragdoll simulation, and smooth animation-to-ragdoll blending.

func BuildRagdoll(world *World, joints []SkeletonJoint, rootPos Vec3, rootRot Quat) *Ragdoll

BuildRagdoll spawns per-bone capsule/box bodies and connecting SwingTwistJoint / HingeJoint constraints in world matching the skeleton hierarchy rooted at (rootPos, rootRot).

The returned Ragdoll starts in RagdollDynamic mode with BlendWeight = 1.

func (r *Ragdoll) Destroy()

Destroy removes all ragdoll joints and bone bodies from r.World.

func (r *Ragdoll) SetMode(mode RagdollMode)

SetMode switches the ragdoll between RagdollKinematic, RagdollDynamic, and RagdollBlended modes.

func (r *Ragdoll) SyncFromPose(worldPositions []Vec3, worldRotations []Quat)

SyncFromPose updates bone bodies from an animated world-space pose.

In RagdollKinematic mode, bones snap directly to the animated pose. In RagdollBlended mode, bones smoothly blend between the animated pose and their simulated physics pose according to BlendWeight in [0, 1] (0 = pure animation, 1 = pure physics). In RagdollDynamic mode, the animated pose is recorded without overriding physics bodies.

func (r *Ragdoll) WritePose() ([]Vec3, []Quat)

WritePose reads back the current world-space joint positions and rotations from the ragdoll's bodies for driving skinned-mesh rendering.

type RagdollMode int

RagdollMode controls how a Ragdoll's bodies respond to animation vs physics.

const (
	// RagdollKinematic drives every bone body directly from SyncFromPose,
	// bypassing gravity and physics impulses while remaining collidable.
	RagdollKinematic RagdollMode = iota
	// RagdollDynamic simulates all bone bodies under full rigid-body dynamics
	// and skeleton joint constraints.
	RagdollDynamic
	// RagdollBlended blends between the animated pose provided to SyncFromPose
	// and the physics simulation using BlendWeight in [0, 1]
	// (0 = pure animation, 1 = pure physics).
	RagdollBlended
)
type Ray struct {
	Origin  Vec3
	Dir     Vec3
	MaxDist float32
}

Ray is a directed ray starting at Origin, pointing along Dir, up to MaxDist units long. Dir need not be unit length; raycast functions normalize it. Rays with zero Dir or non-positive MaxDist report no hits.

type RaycastHit struct {
	// Body is the hit body for World raycasts, or nil for standalone shape,
	// triangle-mesh, or heightfield hits.
	Body *Body
	// ChildIndex is the zero-based index of the struck child when Body or the
	// tested Shape is a ShapeCompound, or -1 for non-compound shapes and static
	// colliders.
	ChildIndex int
	// TriMesh is the hit triangle-mesh collider when the ray struck a static mesh.
	TriMesh *TriMeshCollider
	// Heightfield is the hit heightfield collider when the ray struck terrain.
	Heightfield *HeightfieldCollider
	// Voxel is the hit voxel collider when the ray struck voxel terrain.
	Voxel *VoxelCollider
	// T is the normalized hit fraction in [0, 1] along the ray's MaxDist
	// (or along the segment from -> to for World.Raycast).
	T float32
	// Distance is the Euclidean distance from the ray origin to Point.
	Distance float32
	// Point is the world-space intersection point.
	Point Vec3
	// Normal is the outward unit surface normal at Point. A ray that starts inside a box, sphere, capsule, convex hull or cylinder hits at T 0 with Point at the origin and Normal facing back along the ray (-Dir), since no surface was crossed.
	Normal Vec3
}

RaycastHit describes where a ray intersects a shape, body, or static collider.

func RaycastBox(ray Ray, b Box) (RaycastHit, bool)

RaycastBox tests ray against an axis-aligned box b.

func RaycastCapsule(ray Ray, c Capsule) (RaycastHit, bool)

RaycastCapsule tests ray against a capsule c.

func RaycastConvexHull(ray Ray, h ConvexHull, rot Quat) (RaycastHit, bool)

RaycastConvexHull tests ray against hull h turned by rot about its Center. A ray that starts inside h hits at T 0 with Normal facing back along the ray, as for the other shapes.

func RaycastCylinder(ray Ray, c Cylinder) (RaycastHit, bool)

RaycastCylinder tests ray against cylinder c, its side and both caps. A ray that starts inside c hits at T 0 with Normal facing back along the ray, as for the other shapes.

func RaycastShape(ray Ray, s Shape) (RaycastHit, bool)

RaycastShape tests ray against s.

func RaycastSphere(ray Ray, s Sphere) (RaycastHit, bool)

RaycastSphere tests ray against a sphere s.

func RaycastTriangle(ray Ray, tri Triangle) (RaycastHit, bool)

RaycastTriangle tests ray against triangle tri using the Möller–Trumbore algorithm. It handles both front- and back-facing hits and orients the returned Normal to oppose the ray direction.

func ShapeCastShape(moving Shape, delta Vec3, target Shape) (RaycastHit, bool)

ShapeCastShape sweeps moving along displacement delta against stationary target and returns the exact time of impact, contact point, and outward unit normal pointing from target toward moving. Initial overlaps report T == 0 and Distance == 0 with the overlap contact from TestShapes.

type RigidAttachment struct {
	Particle    int
	Body        *Body
	LocalAnchor Vec3
	Compliance  float32
	// contains filtered or unexported fields
}

RigidAttachment couples particle Particle to rigid Body at LocalAnchor. Compliance == 0 acts as a rigid two-way attachment; positive Compliance acts as a compliant elastic attachment while still transferring reaction impulses to Body.

type RopeConfig struct {
	Start, End     Vec3
	Segments       int
	TotalMass      float32
	ParticleRadius float32
	Compliance     float32
	PinStart       bool
	PinEnd         bool
	Layer          LayerMask
	Mask           LayerMask
	Friction       float32
}

RopeConfig configures a 3D rope constructed by SoftWorld.AddRope.

type Shape struct {
	Kind    ShapeKind
	Box     Box
	Sphere  Sphere
	Capsule Capsule
	// Hull is the convex hull of a ShapeConvexHull shape.
	Hull ConvexHull
	// Cylinder is the cylinder of a ShapeCylinder shape.
	Cylinder Cylinder
	// Rot orients a Box or a ConvexHull about its Center, making the box an oriented box. The zero value and identity leave them unrotated; spheres, capsules and cylinders ignore it.
	Rot Quat
	// Children holds the child colliders when Kind == ShapeCompound.
	Children []CompoundChild `json:"Children,omitempty"`
}

Shape is a tagged wrapper holding one 3D collision primitive or a compound assembly of child shapes.

func BoxShape(b Box) Shape

BoxShape wraps b in a Shape.

func CapsuleShape(c Capsule) Shape

CapsuleShape wraps c in a Shape.

func CompoundShape(children ...CompoundChild) Shape

CompoundShape wraps children in a tagged Shape of kind ShapeCompound, copying the slice so later mutations to the caller's slice do not alias.

func ConvexHullShape(h ConvexHull) Shape

ConvexHullShape wraps h in a Shape.

func CylinderShape(c Cylinder) Shape

CylinderShape wraps c in a Shape.

func SphereShape(s Sphere) Shape

SphereShape wraps s in a Shape.

func (s Shape) Bounds() Box

Bounds returns a tight axis-aligned bounding Box enclosing s.

func (s Shape) Transformed(pos Vec3, rot Quat) Shape

Transformed returns a copy of s rotated by rot around the local origin and translated by pos. For identity rotations, it is identical to Translated(pos). A Box or ConvexHull keeps its geometry and gains the rotation in Shape.Rot, so the result is exact rather than the AABB enclosing it; Bounds returns that AABB.

func (s Shape) Translated(offset Vec3) Shape

Translated returns a copy of s shifted by offset.

type ShapeCastOptions struct {
	// LayerMask filters bodies and static colliders by their Layer bitmask.
	// Zero defaults to LayerAll.
	LayerMask LayerMask
	// IgnoreBody optionally excludes one body from the cast.
	IgnoreBody *Body
	// IgnoreBodyID optionally excludes the body with this ID (matching CharacterController.IgnoreBodyID).
	IgnoreBodyID int
	// IgnoreTriggers excludes bodies with IsTrigger == true when set.
	IgnoreTriggers bool
}

ShapeCastOptions configures filtering for World.ShapeCastWith and World.ShapeCastAllWith.

type ShapeKind int

ShapeKind identifies the active primitive inside a Shape.

const (
	// ShapeBox selects Shape.Box.
	ShapeBox ShapeKind = iota
	// ShapeSphere selects Shape.Sphere.
	ShapeSphere
	// ShapeCapsule selects Shape.Capsule.
	ShapeCapsule
	// ShapeConvexHull selects Shape.Hull.
	ShapeConvexHull
	// ShapeCylinder selects Shape.Cylinder.
	ShapeCylinder
	// ShapeCompound selects Shape.Children.
	ShapeCompound
)
type SixDOFAxisStateSnapshot struct {
	LimitState   int     `json:"limitState,omitempty"`
	LimitImpulse float32 `json:"limitImpulse,omitempty"`
	DriveImpulse float32 `json:"driveImpulse,omitempty"`
	DriveGamma   float32 `json:"driveGamma,omitempty"`
	DriveBias    float32 `json:"driveBias,omitempty"`
	DriveMode    int     `json:"driveMode,omitempty"`
	DriveVel     float32 `json:"driveVel,omitempty"`
}

SixDOFAxisStateSnapshot captures private per-axis solver state of a SixDOFJoint.

type SixDOFJoint struct {
	BodyA, BodyB *Body
	LocalAnchorA Vec3
	LocalAnchorB Vec3
	// LocalFrameA and LocalFrameB orient the constraint's (X, Y, Z) frame in A's
	// and B's local spaces. Zero quaternions default to identity for A and
	// world-aligned with A on initialization for B.
	LocalFrameA Quat
	LocalFrameB Quat

	Linear  [3]AxisConfig // linear X, Y, Z (indices 0, 1, 2)
	Angular [3]AxisConfig // angular X, Y, Z (indices 0, 1, 2)

	BreakForce       float32 // max reaction force in N before breaking (<= 0 disables)
	BreakTorque      float32 // max reaction torque in N*m before breaking (<= 0 disables)
	CollideConnected bool
	// contains filtered or unexported fields
}

SixDOFJoint is a generic 6-degree-of-freedom constraint between BodyA and BodyB with independent linear (X, Y, Z) and angular (X, Y, Z) axis modes, limits, spring stiffness/damping, velocity or position drives, reaction readouts, and optional break thresholds.

func NewSixDOFJoint(a, b *Body, localAnchorA, localAnchorB Vec3) *SixDOFJoint

NewSixDOFJoint creates a SixDOFJoint between a and b at the specified local anchor points, aligning LocalFrameB to match LocalFrameA (identity) in world space so all six relative coordinates start at zero. All axes default to AxisFree.

func (j *SixDOFJoint) AngularPosition() Vec3

AngularPosition returns the current relative rotation (X, Y, Z) in radians in the constraint frame. When exactly one angular axis is unlocked, its component is tracked continuously past ±pi.

func (j *SixDOFJoint) Bodies() (*Body, *Body)

Bodies returns the connected bodies.

func (r *SixDOFJoint) Broken() bool

Broken reports whether the joint has exceeded its break threshold and been removed.

func (j *SixDOFJoint) LinearPosition() Vec3

LinearPosition returns the current relative anchor displacement along the constraint frame's (X, Y, Z) axes in meters.

func (j *SixDOFJoint) Prepare(dt float32)

Prepare initializes the constraint frames, wakes driven bodies, and caches per-axis spring, drive, and limit states for dt.

func (r *SixDOFJoint) ReactionForce() Vec3

ReactionForce returns the world-space constraint force (in Newtons) applied to BodyB during the most recent World.Step.

func (r *SixDOFJoint) ReactionTorque() Vec3

ReactionTorque returns the world-space constraint torque (in N*m) applied to BodyB during the most recent World.Step.

func (j *SixDOFJoint) SolvePosition(dt float32)

SolvePosition corrects locked and limited linear and angular drift.

func (j *SixDOFJoint) SolveVelocity(dt float32)

SolveVelocity solves all 6 linear and angular constraint, spring, drive, and limit rows.

type SkeletonJoint struct {
	Name       string
	Parent     int     // parent joint index, or < 0 for root
	LocalPos   Vec3    // joint offset in parent space
	LocalRot   Quat    // joint orientation in parent space (zero => identity)
	Radius     float32 // capsule radius (defaults to 0.08 when <= 0)
	Length     float32 // bone length (defaults to 0.25 when <= 0)
	Mass       float32 // bone mass in kg (defaults to 1.0 when <= 0)
	SwingLimit float32 // optional symmetric cone/hinge swing limit in radians (> 0 enables)
	HingeAxis  Vec3    // optional explicit hinge axis (non-zero selects HingeJoint)
	// Optional asymmetric swing limits in radians for SwingTwistJoint.
	// When any of these four fields is non-zero, they override symmetric SwingLimit
	// on their respective axis (or all four when both axes are specified).
	SwingMin1  float32
	SwingMax1  float32
	SwingMin2  float32
	SwingMax2  float32
	TwistLimit float32 // optional symmetric twist half-angle in radians (> 0 sets [-TwistLimit, +TwistLimit])
	MinTwist   float32 // optional asymmetric lower twist limit in radians
	MaxTwist   float32 // optional asymmetric upper twist limit in radians
}

SkeletonJoint describes one bone in a skeletal hierarchy used by BuildRagdoll.

type SliderJoint struct {
	BodyA, BodyB     *Body
	LocalAnchorA     Vec3
	LocalAnchorB     Vec3
	LocalAxisA       Vec3 // slide axis in A's local space (defaults to +X)
	EnableLimits     bool
	MinTranslation   float32
	MaxTranslation   float32
	MotorTargetVel   float32 // desired linear speed along slide axis (units/s)
	MotorMaxForce    float32 // max linear motor force (N); active when > 0
	DriveTargetPos   float32 // target translation along slide axis for spring/position drive
	DriveStiffness   float32 // linear spring stiffness in N/m (> 0 enables position spring)
	DriveDamping     float32 // linear damping in N*s/m (>= 0)
	DriveMaxForce    float32 // max drive force in N (<= 0 means unlimited)
	BreakForce       float32 // max reaction force in N before breaking (<= 0 disables)
	BreakTorque      float32 // max reaction torque in N*m before breaking (<= 0 disables)
	CollideConnected bool
	// contains filtered or unexported fields
}

SliderJoint constrains two bodies to translate along a single shared axis without relative rotation, with optional linear limits, velocity motor, spring/position drive, and break thresholds.

func NewSliderJoint(a, b *Body, localAnchorA, localAnchorB, localAxis Vec3) *SliderJoint

NewSliderJoint creates a SliderJoint sliding along localAxis.

func (j *SliderJoint) Bodies() (*Body, *Body)

Bodies returns the connected bodies.

func (r *SliderJoint) Broken() bool

Broken reports whether the joint has exceeded its break threshold and been removed.

func (j *SliderJoint) Prepare(dt float32)

Prepare initializes the reference rotation, wakes motorized or spring-driven bodies, and checks linear limits.

func (r *SliderJoint) ReactionForce() Vec3

ReactionForce returns the world-space constraint force (in Newtons) applied to BodyB during the most recent World.Step.

func (r *SliderJoint) ReactionTorque() Vec3

ReactionTorque returns the world-space constraint torque (in N*m) applied to BodyB during the most recent World.Step.

func (j *SliderJoint) SolvePosition(dt float32)

SolvePosition corrects orientation, perpendicular drift, and linear limit violations.

func (j *SliderJoint) SolveVelocity(dt float32)

SolveVelocity solves orientation lock, perpendicular linear lock, linear motor, spring/position drive, and limits.

func (j *SliderJoint) Translation() float32

Translation returns the current signed displacement of BodyB's anchor relative to BodyA's anchor along the world slide axis.

type SoftBoxConfig struct {
	Center           Vec3
	HalfExtents      Vec3
	TotalMass        float32
	ParticleRadius   float32
	EdgeCompliance   float32
	VolumeCompliance float32
	Layer            LayerMask
	Mask             LayerMask
	Friction         float32
	Restitution      float32
}

SoftBoxConfig configures an 8-vertex, 5-tetrahedron 3D soft box constructed by SoftWorld.AddSoftBox.

type SoftWorld struct {
	Particles   []Particle
	Distances   []DistanceConstraint
	Bendings    []BendingConstraint
	Volumes     []VolumeConstraint
	Attachments []RigidAttachment

	// World provides optional 3D bodies, triangle meshes, and heightfields to collide against.
	World *World
	// Gravity is the constant acceleration applied to unpinned particles. NewSoftWorld sets (0, -9.81, 0).
	Gravity Vec3
	// Wind is an optional constant external acceleration applied to unpinned particles.
	Wind Vec3
	// Damping is linear velocity damping per second (e.g. 0.02).
	Damping    float32
	Substeps   int
	Iterations int
	// contains filtered or unexported fields
}

SoftWorld simulates 3D XPBD particles, constraints (distance, dihedral bending, tetrahedral volume), two-way rigid-body attachments, and collisions against World bodies, triangle meshes, and heightfields in deterministic order.

func NewSoftWorld() *SoftWorld

NewSoftWorld returns a SoftWorld with standard Y-up gravity (0, -9.81, 0), 8 substeps, 6 solver iterations, and mild linear damping.

func (sw *SoftWorld) AddBending(a, b, c, d int, compliance float32) int

AddBending adds a dihedral bending constraint across shared edge (a, b) between triangles (a, b, c) and (b, a, d), capturing the current dihedral angle as RestAngle.

func (sw *SoftWorld) AddCloth(cfg ClothConfig) ClothGrid

AddCloth builds a triangulated (Cols+1) x (Rows+1) cloth mesh with structural, shear, and dihedral bending constraints.

func (sw *SoftWorld) AddDistance(a, b int, restLength, compliance float32) int

AddDistance adds a bilateral distance constraint between particles a and b. If restLength < 0, the current Euclidean distance between a and b is used.

func (sw *SoftWorld) AddParticle(p Particle) int

AddParticle appends p to sw.Particles, initializes PrevPos to p.Pos, and returns its index.

func (sw *SoftWorld) AddRope(cfg RopeConfig) []int

AddRope constructs a 3D chain of Segments+1 particles from Start to End with distance constraints (plus unilateral tethers when Compliance == 0 so heavy attached bodies cannot over-stretch the rope).

func (sw *SoftWorld) AddSoftBox(cfg SoftBoxConfig) []int

AddSoftBox constructs a deformable 3D box made of 8 corner particles, 18 distance constraints (12 outer edges + 6 face diagonals), and 5 tetrahedral volume constraints.

func (sw *SoftWorld) AddTether(a, b int, maxLength, compliance float32) int

AddTether adds a unilateral maximum-distance constraint between particles a and b that activates only when their separation exceeds maxLength.

func (sw *SoftWorld) AddVolume(a, b, c, d int, compliance float32) int

AddVolume adds a tetrahedral volume preservation constraint for particles (a, b, c, d), capturing their current signed volume as RestVolume.

func (sw *SoftWorld) AttachBody(particleIdx int, body *Body, localAnchor Vec3, compliance float32) int

AttachBody couples particleIdx to body at localAnchor with two-way reaction impulses. Set compliance to 0 for a rigid pin attachment or > 0 for an elastic attachment.

func (sw *SoftWorld) Edges() [][2]Vec3

Edges returns wireframe segments for all structural (non-MaxOnly) distance constraints in sw.

func (sw *SoftWorld) PinParticle(idx int)

PinParticle marks particle idx as pinned (immovable).

func (sw *SoftWorld) RopeLength(particles []int) float32

RopeLength returns the total Euclidean polyline length along the ordered particle indices.

func (sw *SoftWorld) Step(dt time.Duration)

Step advances the 3D XPBD particle and constraint simulation by dt deterministically. Call this on the fixed game loop after World.Step(dt) so two-way rigid attachments stay synchronized without over-stretching.

func (sw *SoftWorld) UnpinParticle(idx int)

UnpinParticle clears particle idx's Pinned flag.

type Sphere struct {
	Center Vec3
	Radius float32
}

Sphere is a ball defined by its center and radius.

func (s Sphere) Translated(offset Vec3) Sphere

Translated returns a copy of s shifted by offset.

type SweepHit struct {
	// T is the normalized hit fraction in [0, 1] along the sweep displacement.
	T float32
	// Distance is the Euclidean distance traveled along the sweep before contact.
	Distance float32
	// Point is the world-space contact point on the struck surface.
	Point Vec3
	// Normal is the outward unit surface normal pointing toward the swept shape.
	Normal Vec3
	// Depth is the penetration depth when the shape starts already overlapping (T == 0).
	Depth float32
	// Voxel is the struck VoxelCollider.
	Voxel *VoxelCollider
	// BlockX, BlockY, BlockZ identify the integer voxel coordinate struck.
	BlockX, BlockY, BlockZ int
}

SweepHit describes the first contact encountered when sweeping a Shape along a displacement vector against a VoxelCollider.

type SwingTwistJoint struct {
	BodyA, BodyB *Body
	LocalAnchorA Vec3
	LocalAnchorB Vec3
	TwistAxisA   Vec3 // bone/twist axis in A's local space (defaults to +Y)
	TwistAxisB   Vec3 // bone/twist axis in B's local space (defaults to world-aligned TwistAxisA)
	PlaneAxisA   Vec3 // reference axis perpendicular to TwistAxisA (auto-completed if zero)
	PlaneAxisB   Vec3 // reference axis perpendicular to TwistAxisB (auto-aligned if zero)

	EnableSwingLimits bool
	SwingMin1         float32 // negative/lower swing limit around PlaneAxisA in radians
	SwingMax1         float32 // positive/upper swing limit around PlaneAxisA in radians
	SwingMin2         float32 // negative/lower swing limit around Plane2A in radians
	SwingMax2         float32 // positive/upper swing limit around Plane2A in radians

	EnableTwistLimits bool
	MinTwist          float32 // lower twist limit in radians (in [-pi, pi])
	MaxTwist          float32 // upper twist limit in radians (in [-pi, pi])

	BreakForce       float32 // max reaction force in N before breaking (<= 0 disables)
	BreakTorque      float32 // max reaction torque in N*m before breaking (<= 0 disables)
	CollideConnected bool
	// contains filtered or unexported fields
}

SwingTwistJoint is a 3D ball-and-socket constraint with an asymmetric four-quadrant elliptic swing cone and an independent twist range [MinTwist, MaxTwist].

Each body carries an orthonormal frame (TwistAxis, PlaneAxis, TwistAxis x PlaneAxis). Swing1 rotates around PlaneAxisA (clamped to [SwingMin1, SwingMax1]), Swing2 rotates around TwistAxisA x PlaneAxisA (clamped to [SwingMin2, SwingMax2]), and Twist rotates around TwistAxisB (clamped to [MinTwist, MaxTwist]).

func NewSwingTwistJoint(a, b *Body, localAnchorA, localAnchorB, twistAxis Vec3) *SwingTwistJoint

NewSwingTwistJoint creates a SwingTwistJoint locking LocalAnchorA on a to LocalAnchorB on b with twistAxis specified in a's local space (defaulting to +Y). TwistAxisB and PlaneAxisB are aligned to match A's frame in world space so the initial swing and twist angles start at zero.

func (j *SwingTwistJoint) Bodies() (*Body, *Body)

Bodies returns the connected bodies.

func (r *SwingTwistJoint) Broken() bool

Broken reports whether the joint has exceeded its break threshold and been removed.

func (j *SwingTwistJoint) Prepare(dt float32)

Prepare resets per-step impulses and evaluates active twist limit states.

func (r *SwingTwistJoint) ReactionForce() Vec3

ReactionForce returns the world-space constraint force (in Newtons) applied to BodyB during the most recent World.Step.

func (r *SwingTwistJoint) ReactionTorque() Vec3

ReactionTorque returns the world-space constraint torque (in N*m) applied to BodyB during the most recent World.Step.

func (j *SwingTwistJoint) SolvePosition(dt float32)

SolvePosition corrects socket anchor drift, asymmetric swing violations, and twist violations.

func (j *SwingTwistJoint) SolveVelocity(dt float32)

SolveVelocity solves the 3D socket anchor, asymmetric swing cone, and twist limits.

func (j *SwingTwistJoint) SwingAngles() (swing1, swing2 float32)

SwingAngles returns the current decomposed swing angles (swing1, swing2) in radians around PlaneAxisA and TwistAxisA x PlaneAxisA.

func (j *SwingTwistJoint) TwistAngle() float32

TwistAngle returns the current decomposed twist angle in radians in [-pi, pi] around the joint's twist axis.

type SymMat3 struct {
	XX, YY, ZZ float32
	XY, XZ, YZ float32
}

SymMat3 is a symmetric 3x3 matrix stored by its six unique entries:

[ XX  XY  XZ ]
[ XY  YY  YZ ]
[ XZ  YZ  ZZ ]

All arithmetic avoids fused multiply-add contraction for cross-architecture determinism.

func DiagSymMat3(diag Vec3) SymMat3

DiagSymMat3 returns a diagonal symmetric 3x3 matrix with entries diag.X, diag.Y, diag.Z.

func (m SymMat3) Add(b SymMat3) SymMat3

Add returns the component-wise sum m + b.

func (m SymMat3) Inverse() (SymMat3, bool)

Inverse returns the inverse of m computed in float64 without FMA contraction, or (SymMat3{}, false) if m is singular or non-finite.

func (m SymMat3) IsZero() bool

IsZero reports whether all entries of m are zero.

func (m SymMat3) MulVec(v Vec3) Vec3

MulVec returns m * v without FMA contraction.

func (m SymMat3) QuadForm(v Vec3) float32

QuadForm returns v^T * m * v.

func (m SymMat3) Rotated(q Quat) SymMat3

Rotated returns R * m * R^T where R is the 3x3 rotation matrix of unit quaternion q, computed without FMA contraction.

func (m SymMat3) Solve(rhs Vec3) Vec3

Solve solves the symmetric linear system m * x = rhs in float64 without FMA contraction, returning the zero vector when m is singular or non-finite.

type TriMeshCollider struct {
	ID          int
	Tag         string
	Layer       LayerMask
	Mask        LayerMask
	Friction    float32
	Restitution float32
	Triangles   []Triangle
	Bounds      Box
	// contains filtered or unexported fields
}

TriMeshCollider is a static triangle-mesh collider accelerated by a pure-Go AABB Bounding Volume Hierarchy (BVH).

func NewTriMeshCollider(vertices []Vec3, indices []uint32) *TriMeshCollider

NewTriMeshCollider builds a TriMeshCollider and its AABB BVH from indexed triangle soup (directly compatible with glTF mesh positions and indices).

func NewTriMeshFromGLTFMesh(mesh gltf.Mesh, worldTransform math3d.Mat4) *TriMeshCollider

NewTriMeshFromGLTFMesh builds a single static TriMeshCollider combining all triangle primitives of mesh, transformed by worldTransform (an all-zero matrix is treated as identity).

func NewTriMeshFromGLTFNode(doc *gltf.Document, nodeIndex int) *TriMeshCollider

NewTriMeshFromGLTFNode builds a static TriMeshCollider from doc.Nodes[nodeIndex] using the node's full WorldMatrix transform. Returns nil if doc is nil, nodeIndex is out of range, or the node references no valid mesh.

func NewTriMeshFromGLTFPrimitive(prim gltf.Primitive, worldTransform math3d.Mat4) *TriMeshCollider

NewTriMeshFromGLTFPrimitive builds a static TriMeshCollider from a single glTF primitive (indexed or non-indexed, supporting Triangles, TriangleStrip, and TriangleFan modes), transforming vertices by worldTransform (an all-zero matrix is treated as identity).

func (tm *TriMeshCollider) CollectContacts(s Shape, dst []Contact) []Contact

CollectContacts appends all overlapping triangle contacts for s to dst.

func (tm *TriMeshCollider) QueryTriangles(bounds Box, visit func(tri Triangle))

QueryTriangles visits every triangle in tm whose leaf BVH node overlaps bounds.

func (tm *TriMeshCollider) Raycast(ray Ray) (RaycastHit, bool)

Raycast traverses the BVH to find the closest intersection between ray and tm.

func (tm *TriMeshCollider) ShapeCast(shape Shape, delta Vec3) (RaycastHit, bool)

ShapeCast sweeps shape along displacement delta against tm using its BVH and returns the earliest hit.

func (tm *TriMeshCollider) TestShape(s Shape) Contact

TestShape returns the deepest Contact between s and tm (normal pointing from tm toward s).

type TriMeshSnapshot struct {
	ID          int        `json:"id"`
	Tag         string     `json:"tag,omitempty"`
	Layer       LayerMask  `json:"layer"`
	Mask        LayerMask  `json:"mask"`
	Friction    float32    `json:"friction"`
	Restitution float32    `json:"restitution"`
	Triangles   []Triangle `json:"triangles,omitempty"`
}

TriMeshSnapshot captures a static TriMeshCollider.

type Triangle struct {
	A, B, C Vec3
}

Triangle is a 3D triangle defined by vertices A, B, C (counter-clockwise winding defines the outward Normal).

func (t Triangle) Bounds() Box

Bounds returns the tight axis-aligned bounding Box enclosing t.

func (t Triangle) Centroid() Vec3

Centroid returns the geometric center of t.

func (t Triangle) Normal() Vec3

Normal returns the unit surface normal of t using counter-clockwise winding.

type Vec3 struct {
	X, Y, Z float32
}

Vec3 is a 3D vector in a right-handed, Y-up coordinate system.

func (v Vec3) Add(b Vec3) Vec3

Add returns v + b.

func (v Vec3) Cross(b Vec3) Vec3

Cross returns the right-handed cross product v x b.

func (v Vec3) Dist(b Vec3) float32

Dist returns the Euclidean distance between v and b.

func (v Vec3) DistSq(b Vec3) float32

DistSq returns the squared Euclidean distance between v and b.

func (v Vec3) Dot(b Vec3) float32

Dot returns the dot product of v and b.

func (v Vec3) Len() float32

Len returns the Euclidean length of v.

func (v Vec3) LenSq() float32

LenSq returns the squared Euclidean length of v.

func (v Vec3) Neg() Vec3

Neg returns -v.

func (v Vec3) Norm() Vec3

Norm returns the unit vector in the direction of v, or the zero vector when v has zero length.

func (v Vec3) Scale(s float32) Vec3

Scale returns v multiplied by s.

func (v Vec3) Sub(b Vec3) Vec3

Sub returns v - b.

type VolumeConstraint struct {
	A, B, C, D int
	RestVolume float32
	Compliance float32
	// contains filtered or unexported fields
}

VolumeConstraint preserves the signed volume of tetrahedron (A, B, C, D).

type VoxelBoundsGrid interface {
	VoxelGrid
	// VoxelBounds returns the inclusive world-space AABB enclosing all solid
	// voxels in the grid's local coordinates (before adding VoxelCollider.Origin),
	// and false when no solid voxels exist.
	VoxelBounds() (min, max Vec3, ok bool)
}

VoxelBoundsGrid is an optional interface a VoxelGrid may implement so VoxelCollider.Raycast can reject rays outside the populated world in O(1) and clip long rays to the active voxel region.

type VoxelCollider struct {
	ID          int
	Tag         string
	Layer       LayerMask
	Mask        LayerMask
	Friction    float32
	Restitution float32
	Origin      Vec3
	Grid        VoxelGrid
	// contains filtered or unexported fields
}

VoxelCollider collides bodies, characters, rays, overlaps, and shape sweeps directly against a VoxelGrid without building a triangle mesh. Edits to the underlying VoxelGrid take effect immediately with zero rebuild.

func NewVoxelCollider(grid VoxelGrid) *VoxelCollider

NewVoxelCollider constructs a VoxelCollider backed by grid with default friction (0.5).

func (vc *VoxelCollider) CollectContacts(s Shape, dst []Contact) []Contact

CollectContacts appends all overlapping exposed solid-voxel contacts for s to dst in deterministic (y, z, x) order.

func (vc *VoxelCollider) NotifyBlockChanged(x, y, z int)

NotifyBlockChanged wakes sleeping dynamic bodies near voxel (x, y, z) in every World to which vc is attached. VoxelGrid implementations that also implement VoxelEditNotifier invoke this automatically on block edits.

func (vc *VoxelCollider) NotifyReset()

NotifyReset wakes all dynamic bodies in every World to which vc is attached.

func (vc *VoxelCollider) QueryBlocks(bounds Box, visit func(x, y, z int, blockBox Box))

QueryBlocks visits every solid voxel overlapping bounds in deterministic ascending (y, z, x) order, passing its integer coordinate and world-space Box.

func (vc *VoxelCollider) Raycast(ray Ray) (RaycastHit, bool)

Raycast intersects ray directly with solid blocks in vc using 3D DDA (Amanatides & Woo) without building a triangle mesh.

func (vc *VoxelCollider) Sweep(shape Shape, delta Vec3) (SweepHit, bool)

Sweep translates shape along delta against solid blocks in vc and returns the earliest opposing contact. Axis-aligned boxes use an exact analytical swept-AABB slab test with internal-face filtering; spheres, capsules, and oriented boxes use sub-stepped narrowphase with binary-search TOI refinement.

func (vc *VoxelCollider) TestShape(s Shape) Contact

TestShape returns the deepest Contact between s and solid blocks in vc (normal pointing from the voxel terrain toward s).

type VoxelColliderSnapshot struct {
	ID          int       `json:"id"`
	Tag         string    `json:"tag,omitempty"`
	Layer       LayerMask `json:"layer"`
	Mask        LayerMask `json:"mask"`
	Friction    float32   `json:"friction"`
	Restitution float32   `json:"restitution"`
	Origin      Vec3      `json:"origin"`
}

VoxelColliderSnapshot captures the metadata of a VoxelCollider (its backing VoxelGrid interface is matched by ID on Restore).

type VoxelEditNotifier interface {
	VoxelGrid
	// WatchVoxelEdits registers callbacks invoked whenever a voxel changes
	// solidity (onBlock) or the grid is reset (onReset). Calling the returned
	// cancel function unregisters the callbacks.
	WatchVoxelEdits(onBlock func(x, y, z int), onReset func()) (cancel func())
}

VoxelEditNotifier is an optional interface a VoxelGrid may implement so VoxelCollider automatically wakes sleeping dynamic bodies in attached Worlds whenever a block changes solidity or the grid is cleared.

type VoxelGrid interface {
	// VoxelSize returns the positive world-space edge length of one voxel.
	VoxelSize() float32
	// IsSolid reports whether the voxel at integer coordinate (x, y, z) is solid.
	IsSolid(x, y, z int) bool
}

VoxelGrid supplies direct solid-block occupancy queries for a VoxelCollider. Voxel (x, y, z) occupies the world-space cube from Origin + (x, y, z)*VoxelSize to Origin + (x+1, y+1, z+1)*VoxelSize.

type World struct {
	// Gravity is the constant acceleration applied to dynamic bodies each step.
	// NewWorld initializes it to (0, -9.81, 0).
	Gravity Vec3
	// SolverIterations is the number of velocity and positional solver passes
	// per Step; values <= 0 default to 8.
	SolverIterations int
	// OnContact is invoked deterministically for non-trigger ContactEvents
	// (ContactEnter, ContactStay, ContactExit).
	OnContact func(ContactEvent)
	// OnTrigger is invoked deterministically for trigger ContactEvents
	// (ContactEnter, ContactStay, ContactExit).
	OnTrigger func(ContactEvent)
	// OnJointBreak is invoked deterministically for each joint broken during
	// World.Step in joint insertion order.
	OnJointBreak func(JointBreakEvent)
	// contains filtered or unexported fields
}

World holds static, kinematic, and dynamic bodies, static triangle meshes, heightfields, voxel colliders, and 3D joints, stepping them forward deterministically.

func NewWorld() *World

NewWorld returns a World with standard Y-up gravity (0, -9.81, 0) and 8 solver iterations.

func (w *World) AddBody(b Body) *Body

AddBody copies b into w, normalizes its ID, reassigning an explicit ID that is already taken,, orientation, mass, and inertia fields, and returns a pointer to the stored body.

func (w *World) AddGLTFColliders(doc *gltf.Document, opts GLTFColliderOptions) (*GLTFColliders, error)

AddGLTFColliders builds static colliders from doc and adds them to w.

func (w *World) AddHeightfield(hf *HeightfieldCollider) *HeightfieldCollider

AddHeightfield registers a static HeightfieldCollider in w and returns it.

func (w *World) AddJoint(j Joint3D) Joint3D

AddJoint registers j in w so it is solved during World.Step and returns j.

func (w *World) AddTriMesh(tm *TriMeshCollider) *TriMeshCollider

AddTriMesh registers a static TriMeshCollider in w and returns it.

func (w *World) AddVoxelCollider(vc *VoxelCollider) *VoxelCollider

AddVoxelCollider registers a static VoxelCollider in w and returns it. If vc.Grid implements VoxelEditNotifier, edits to the grid automatically wake sleeping bodies near changed blocks.

func (w *World) AllowCollision(a, b *Body)

AllowCollision re-enables collision and trigger detection between bodies a and b if previously disabled with IgnoreCollision.

func (w *World) AreaEffectAtShape(shape Shape, layer, mask LayerMask) AreaEffect

AreaEffectAtShape resolves all active trigger areas in w overlapping shape (filtered by layer and mask) using w.Gravity as the base gravity.

func (w *World) Bodies() []*Body

Bodies returns the bodies currently in w in deterministic insertion order.

func (w *World) Checksum() uint64

Checksum returns a deterministic 64-bit FNV-1a hash of w's complete state, including private solver caches, sleep timers, previous poses, active contacts, joints, and colliders.

func (w *World) ContactEvents() []ContactEvent

ContactEvents returns the deterministic slice of ContactEvents produced by the most recent World.Step (and any subsequent RemoveBody exit events).

func (w *World) GenerateCoverPoints(opts CoverOptions) []ai.CoverPoint

GenerateCoverPoints generates deterministic XZ-plane cover points along the vertical faces of matching colliders in w, discarding points that overlap any other matching collider.

func (w *World) GravityAt(p Vec3) Vec3

GravityAt returns the effective gravity acceleration at world point p in w, combining w.Gravity with any overlapping active trigger areas.

func (w *World) Heightfields() []*HeightfieldCollider

Heightfields returns all static HeightfieldColliders registered in w.

func (w *World) IgnoreCollision(a, b *Body)

IgnoreCollision disables collision and trigger detection between bodies a and b.

func (w *World) JointBreakEvents() []JointBreakEvent

JointBreakEvents returns the deterministic slice of JointBreakEvents produced by the most recent World.Step, in joint insertion order.

func (w *World) Joints() []Joint3D

Joints returns all joints currently registered in w in insertion order.

func (w *World) OverlapLayer(shape Shape, mask LayerMask) []OverlapHit

OverlapLayer returns every body, triangle mesh, heightfield, and voxel collider in w whose Layer matches mask and overlaps shape, in deterministic insertion order. Each hit's Contact.Normal points from the collider toward shape. For compound bodies, every overlapping child matching mask is reported in ascending child-index order with its zero-based ChildIndex.

func (w *World) QueryOverlap(shape Shape) []OverlapHit

QueryOverlap returns every body and static collider in w overlapping shape, in deterministic insertion order. Each hit's Contact.Normal points from the collider toward shape.

func (w *World) Raycast(from, to Vec3) []RaycastHit

Raycast casts a segment from from to to against all bodies and static colliders in w and returns all hits sorted by ascending T in [0, 1].

func (w *World) RaycastFirst(from, to Vec3) (RaycastHit, bool)

RaycastFirst casts a segment from from to to against all bodies and static colliders in w and returns the closest hit, if any.

func (w *World) RaycastFirstLayer(from, to Vec3, mask LayerMask) (RaycastHit, bool)

RaycastFirstLayer casts a segment from from to to against all bodies, triangle meshes, heightfields, and voxel colliders whose Layer matches mask, returning the closest hit. For compound bodies, ChildIndex reports the struck child.

func (w *World) RaycastLayer(from, to Vec3, mask LayerMask) []RaycastHit

RaycastLayer casts a segment from from to to against all bodies, triangle meshes, heightfields, and voxel colliders whose Layer matches mask, returning hits sorted by ascending T in [0, 1] with deterministic tie-breaking. For compound bodies, every child matching mask is tested and reported with its zero-based ChildIndex.

func (w *World) RemoveBody(id int) bool

RemoveBody removes the body with the given ID, preserving deterministic order of the remaining bodies, emitting ContactExit events for any active overlaps, removing joints attached to the body, and waking dynamic bodies so supported stacks react.

func (w *World) RemoveHeightfield(id int) bool

RemoveHeightfield removes the heightfield collider with the given ID from w.

func (w *World) RemoveJoint(j Joint3D) bool

RemoveJoint removes j from w.

func (w *World) RemoveTriMesh(id int) bool

RemoveTriMesh removes the triangle-mesh collider with the given ID from w.

func (w *World) RemoveVoxelCollider(id int) bool

RemoveVoxelCollider removes the VoxelCollider with the given ID from w and wakes dynamic bodies so supported objects react.

func (w *World) Restore(snap WorldSnapshot) error

Restore replaces w's state from snap. Existing *Body, Joint3D, and collider pointers are reused in place by ID/slot when possible so external handles (such as vehicle chassis pointers) and World callbacks stay valid across rollback restores.

func (w *World) Save() WorldSnapshot

Save captures a deep, deterministic, JSON-serializable snapshot of w, including all private solver state (warm-start impulse cache, sleep timers, previous poses, active contact/trigger pairs, joint state, and colliders).

func (w *World) ShapeCast(shape Shape, origin Vec3, rot Quat, delta Vec3) (RaycastHit, bool)

ShapeCast sweeps shape placed at (origin, rot) along displacement delta against all bodies, triangle meshes, heightfields, and voxel colliders in w, returning the earliest hit. Ties break deterministically in the same order as RaycastFirst (Body, TriMesh, Heightfield, Voxel, then ascending ID).

func (w *World) ShapeCastAll(shape Shape, origin Vec3, rot Quat, delta Vec3) []RaycastHit

ShapeCastAll sweeps shape placed at (origin, rot) along displacement delta against all bodies, triangle meshes, heightfields, and voxel colliders in w, returning all hits (at most one earliest hit per body or collider, or per matching child of a compound body with its zero-based ChildIndex) sorted by ascending T with deterministic tie-breaking.

func (w *World) ShapeCastAllLayer(shape Shape, origin Vec3, rot Quat, delta Vec3, mask LayerMask, ignore *Body) []RaycastHit

ShapeCastAllLayer sweeps shape placed at (origin, rot) along displacement delta against bodies and static colliders whose Layer matches mask, optionally ignoring ignore, and returns all hits sorted by ascending T with deterministic tie-breaking. Passing mask == 0 returns nil.

func (w *World) ShapeCastAllWith(shape Shape, origin Vec3, rot Quat, delta Vec3, opts ShapeCastOptions) []RaycastHit

ShapeCastAllWith sweeps shape placed at (origin, rot) along displacement delta with filtering configured by opts, returning all hits sorted by ascending T. A zero opts.LayerMask defaults to LayerAll.

func (w *World) ShapeCastLayer(shape Shape, origin Vec3, rot Quat, delta Vec3, mask LayerMask, ignore *Body) (RaycastHit, bool)

ShapeCastLayer sweeps shape placed at (origin, rot) along displacement delta against bodies and static colliders whose Layer matches mask, optionally ignoring ignore, and returns the earliest hit. Passing mask == 0 matches no colliders (matching RaycastFirstLayer).

func (w *World) ShapeCastWith(shape Shape, origin Vec3, rot Quat, delta Vec3, opts ShapeCastOptions) (RaycastHit, bool)

ShapeCastWith sweeps shape placed at (origin, rot) along displacement delta with filtering configured by opts, returning the earliest hit. A zero opts.LayerMask defaults to LayerAll.

func (w *World) Step(dt time.Duration)

Step advances the rigid-body simulation by dt using symplectic Euler integration, deterministic collision detection, warm-started iterative impulse resolution with Coulomb friction, 3D joint solving, positional correction, and deterministic contact/trigger event dispatch.

func (w *World) SyncBroadphase()

SyncBroadphase refreshes the broadphase acceleration structure for any bodies whose Pos, Rot, Shape, Static, or IsTrigger fields were mutated directly since the last World.Step. AddBody, RemoveBody, AddTriMesh, RemoveTriMesh, AddHeightfield, RemoveHeightfield, Restore, and Step maintain the broadphase automatically.

func (w *World) TriMeshes() []*TriMeshCollider

TriMeshes returns all static TriMeshColliders registered in w.

func (w *World) VoxelColliders() []*VoxelCollider

VoxelColliders returns all static VoxelColliders registered in w.

func (w *World) WakeInBox(bounds Box)

WakeInBox wakes every sleeping dynamic body whose world bounds overlap bounds, and transitively wakes any sleeping dynamic bodies currently resting on them via active contacts.

type WorldSnapshot struct {
	Version          int                       `json:"version"`
	Gravity          Vec3                      `json:"gravity"`
	SolverIterations int                       `json:"solverIterations"`
	NextID           int                       `json:"nextID"`
	NextColliderID   int                       `json:"nextColliderID"`
	Bodies           []BodySnapshot            `json:"bodies,omitempty"`
	WarmStartCache   []CachedImpulseSnapshot   `json:"warmStartCache,omitempty"`
	ActiveContacts   []ActiveContactSnapshot   `json:"activeContacts,omitempty"`
	ContactEvents    []ContactEventSnapshot    `json:"contactEvents,omitempty"`
	JointBreakEvents []JointBreakEventSnapshot `json:"jointBreakEvents,omitempty"`
	IgnoredPairs     []PairKeySnapshot         `json:"ignoredPairs,omitempty"`
	Joints           []JointSnapshot           `json:"joints,omitempty"`
	TriMeshes        []TriMeshSnapshot         `json:"triMeshes,omitempty"`
	Heightfields     []HeightfieldSnapshot     `json:"heightfields,omitempty"`
	Voxels           []VoxelColliderSnapshot   `json:"voxels,omitempty"`
}

WorldSnapshot captures the complete deterministic state of a physics3d.World, including all bodies, sleep timers, previous poses, warm-start contact cache, active contacts, contact/joint-break events, ignored pairs, joints and their private solver state, and static colliders. It marshals cleanly with encoding/json.