이 페이지는 아직 한국어로 번역되지 않아 영문 원문을 표시하고 있습니다.
3Dphysics3d
import "github.com/nsgo-dev/game/pkg/physics3d"
Compact, deterministic 3D collision detection, raycasting, rigid-body dynamics, and a kinematic character controller written in pure Go.
Architectural Decision (#180)
physics3d uses option (a): a self-contained, zero-cgo Go implementation built only on the Go standard library.
Why pure Go instead of wrapping a C/C++ physics engine (such as Jolt, Bullet, or PhysX):
- Every NSGo target compiles out of the box: macOS, Windows, Linux, iOS, Android, and WebAssembly build with a plain
go build/go tool nsgo check— no C/C++ toolchains, per-platform static libraries, or Emscripten/Wasm glue. - No FFI overhead: Queries, raycasts, rigid-body steps, and character moves operate directly on Go values with zero cgo boundary crossings.
- Bit-for-bit determinism: Stepping a
Worldwith fixed durations fromgame.Loopruns broadphase, narrowphase, impulse solving, and positional correction in a fixed body and contact order with no map-order iteration or wall-clock input.
The scope is intentionally focused: boxes (axis-aligned or oriented), spheres, capsules, convex hulls, cylinders, and compound shapes assembled from child colliders, static triangle meshes (TriMeshCollider, added with World.AddTriMesh), heightfields (HeightfieldCollider, added with World.AddHeightfield), and voxel grids (VoxelCollider, added with World.AddVoxelCollider) that collide with bodies and the character controller, exact overlap, raycast, and voxel sweep queries, rigid bodies with linear and angular dynamics, joints, ragdolls, and a capsule character controller. Single-primitive bodies use a scalar (isotropic) inertia, while compound bodies compute a combined CenterOfMass and 3×3 symmetric InvInertiaTensor (SymMat3) from their solid children via the parallel-axis theorem. Contacts between boxes, spheres and capsules use one representative point per collider pair; a pair that involves a convex hull or a cylinder gets up to four points spread over the touching area.
Coordinate Convention
physics3d uses a right-handed, Y-up coordinate system (+X right, +Y up, +Z toward the viewer). NewWorld() sets default gravity to (0, -9.81, 0).
Shapes, Overlaps, and Raycasts
Five primitives and a compound assembly are wrapped by the tagged Shape value (BoxShape, SphereShape, CapsuleShape, ConvexHullShape, CylinderShape, CompoundShape):
Box— box defined byCenterandHalfExtents(or constructed viaBoxFromMinMax(min, max)). It is axis-aligned unless the wrappingShapesetsRot, which orients it about itsCenter.Shape.Transformed(pos, rot)andBody.WorldShape()keep a rotated body's box oriented, so overlap tests, raycasts and debug drawing see its real corners;Shape.Bounds()returns the enclosing AABB for broad-phase use.Sphere—CenterandRadius.Capsule— line segment fromAtoBswept byRadius(orVerticalCapsule(center, radius, height)).ConvexHull— a convex polyhedron for props such as rocks, debris, furniture, wedges and low-poly vehicle hulls, built once byNewConvexHull(points, maxVertices)and then shared, read-only, by every shape and body that uses it. Its vertices are relative toCenter, and the wrappingShape'sRotturns it aboutCenteras it does a box.Cylinder— a solid cylinder with flat caps whose axis runs fromAtoB, of the givenRadius(orVerticalCylinder(center, radius, height)), for barrels, wheels and pillars. A cylinder whoseAandBcoincide or whoseRadiusis not positive has no volume, and collisions, raycasts and areas ignore it.ShapeCompound— multipleCompoundChildcolliders (Box,Sphere,Capsule,ConvexHull,Cylinder, or nestedShapeCompound) on one rigid body, each with its own localOffsetandRot, optionalMassorDensity, and optional per-childTrigger,Layer, andMask.
Convex hulls
NewConvexHull builds the hull with quickhull: it starts from a tetrahedron of extreme points and adds the point furthest outside the hull until none is left or the hull has maxVertices vertices (DefaultHullVertices, 64, for a limit of 0 or less, at most MaxHullVertices, 256, and at least 4, the fewest vertices a hull with volume has, for a limit of 1 to 3). When the limit stops it early, the hull keeps the most prominent corners and lies inside the full hull. Points inside the hull or within a small tolerance of a face are dropped, and coplanar triangles are merged into polygon faces, so a cube gives 8 vertices and 6 square faces. The result depends only on the points and their order, so the same input always gives the same hull. Points that do not span a volume (fewer than four, all on a plane or a line, or not finite) return ErrDegenerateHull.
ConvexHullFromMesh(positions, indices, maxVertices) builds a hull from a triangle mesh, using only the vertices the indices reference, so a glTF primitive's or a render3d.Mesh's Positions and Indices go in as they are:
doc, _ := gltf.LoadFS(assets, "rock.gltf")
prim := doc.Meshes[0].Primitives[0]
hull, err := physics3d.ConvexHullFromMesh(prim.Positions, prim.Indices, 32)
if err != nil {
return err
}
// Move the hull's centroid to the body's origin, so the body rotates about its center of mass.
hull = hull.Recentered()
pos := hull.Center
hull.Center = physics3d.Vec3{}
rock := world.AddBody(physics3d.NewDynamicBody(physics3d.ConvexHullShape(hull), pos, 40))
A hull reports its Vertices, Faces (vertex indices counter-clockwise seen from outside), FaceNormals, Edges, Volume, Centroid and InertiaTensor(mass) for uniform density. A body's inertia comes from the hull's exact tensor (the mean of its principal moments, as the scalar inertia above), and a cylinder's from the solid-cylinder formula.
Compound shapes
CompoundShape(children...) combines several CompoundChild colliders onto a single rigid body so furniture, vehicles, or characters with separate hitboxes move and rotate as one body without fixed joints:
leg := physics3d.BoxShape(physics3d.Box{HalfExtents: physics3d.Vec3{X: 0.06, Y: 0.4, Z: 0.06}})
top := physics3d.BoxShape(physics3d.Box{HalfExtents: physics3d.Vec3{X: 0.75, Y: 0.05, Z: 0.35}})
tableShape := physics3d.CompoundShape(
physics3d.CompoundChild{Shape: top, Offset: physics3d.Vec3{Y: 0.85}, Mass: 3},
physics3d.CompoundChild{Shape: leg, Offset: physics3d.Vec3{X: -0.69, Y: 0.4, Z: -0.29}, Mass: 1.5},
physics3d.CompoundChild{Shape: leg, Offset: physics3d.Vec3{X: 0.69, Y: 0.4, Z: -0.29}, Mass: 1.5},
physics3d.CompoundChild{Shape: leg, Offset: physics3d.Vec3{X: -0.69, Y: 0.4, Z: 0.29}, Mass: 1.5},
physics3d.CompoundChild{Shape: leg, Offset: physics3d.Vec3{X: 0.69, Y: 0.4, Z: 0.29}, Mass: 1.5},
)
// Passing mass 0 derives total mass, CenterOfMass, and InvInertiaTensor from the children.
table := world.AddBody(physics3d.NewDynamicBody(tableShape, physics3d.Vec3{}, 0))
- Mass, center of mass, and inertia:
ComputeCompoundMassProperties(called automatically byAddBodyandBody.RecomputeMassProperties) computes combinedMass, localCenterOfMass, and the 3×3 symmetricInvInertiaTensor(SymMat3) from all non-trigger children via the parallel-axis theorem. Children can specify explicitMassorDensity; passing a positivemasstoNewDynamicBodydistributes or scales child masses to match.Body.WorldCenterOfMass()returns the world-space center of mass, andBody.ApplyImpulseAtPoint(impulse, worldPoint)applies linear and angular impulses about it. - Bounds and queries:
Shape.Bounds()encloses every child. Contacts (ContactEvent.ChildIndexA/ChildIndexB), raycasts (RaycastHit.ChildIndex), and overlaps (OverlapHit.ChildIndex) test every child and report its zero-based child index (-1for non-compound bodies and static colliders). - Per-child triggers and layers: setting
CompoundChild.Trigger = trueturns that child into a sensor volume (such as a head hurtbox on a solid character body) that emitsOnTriggerevents without applying impulses, blocking character controllers or CCD sweeps, or contributing to mass and inertia. OptionalCompoundChild.LayerandMaskoverride the parentBody.LayerandBody.Maskwhen non-zero.
Overlap tests return a Contact whose unit Normal points from B toward A (the direction to translate A by Depth to separate the shapes):
TestBoxBox,TestOrientedBoxBox(separating axis theorem over the 15 face and edge axes),TestSphereSphere,TestCapsuleCapsule,TestBoxSphere,TestBoxCapsule,TestSphereCapsule, andTestShapes(a, b), which handles oriented boxes.TestShapestests every pair that involves a convex hull or a cylinder, against any other shape, with GJK for the distance and EPA for the penetration depth and normal, in float64 and a fixed iteration order, so the same shapes always give the same contact.Pointis the center of the touching area (a face resting on a face reports the middle of the overlap, not a corner). The same test runs against each triangle of aTriMeshColliderand aHeightfieldCollider, and against voxel colliders.- When a capsule's segment passes through a box,
TestBoxCapsuletakes the axis of least penetration over the box faces and the edges crossed with the segment, so moving the box byNormal*Depthclears the whole capsule. Crossing capsules, and a sphere centered on a capsule's axis, get a normal perpendicular to the axes rather than an arbitrary one. world.QueryOverlap(shape)returns all overlapping bodies in deterministic insertion order.
Raycasts test a Ray{Origin, Dir, MaxDist} against standalone shapes (RaycastBox, RaycastSphere, RaycastCapsule, RaycastConvexHull, RaycastCylinder, RaycastShape) or cast a segment through a world (world.Raycast(from, to) and world.RaycastFirst(from, to)), returning RaycastHit entries sorted by ascending T in [0, 1] with world-space Point, Distance, and outward unit Normal. A ray that starts inside any shape hits it at T 0 with Point at the origin and Normal facing back along the ray (-Dir).
Shape Casts
Sweep any Shape (Box, Sphere, Capsule, or ShapeCompound composed of them) with a Quat orientation from origin along displacement delta against bodies, triangle meshes (TriMeshCollider), heightfields (HeightfieldCollider), and voxel colliders (VoxelCollider):
world.ShapeCast(shape, origin, rot, delta)returns the earliestRaycastHit(Body/TriMesh/Heightfield/Voxel,ChildIndex,T,Distance,Point,Normal);world.ShapeCastAll(...)returns all hits sorted by ascendingTwith the same deterministic tie-breaking order asRaycast(Body<TriMesh<Heightfield<Voxel, then ascending ID andChildIndex). Compound bodies are tested per child with per-childLayerandTriggerfiltering.- Use
world.ShapeCastLayer(shape, origin, rot, delta, mask, ignore)andShapeCastAllLayerforLayerMaskfiltering and excluding a*Body, orShapeCastWith/ShapeCastAllWith(ShapeCastOptions) to also excludeIgnoreBodyIDor triggers (IgnoreTriggers). - Standalone helpers
ShapeCastShape(moving, delta, target),TriMeshCollider.ShapeCast(shape, delta), andHeightfieldCollider.ShapeCast(shape, delta)test individual colliders directly. Sphere, box/OBB, and box-triangle pairs use exact analytic sweeps (Minkowski sums and moving SAT); capsule-box, capsule-capsule, and capsule-triangle pairs use exact-distance conservative advancement (<= 1e-4). Initial overlaps returnT == 0,Distance == 0, and theTestShapesseparation normal.
// Third-person camera spring arm that pulls forward before clipping a wall.
cameraProbe := physics3d.SphereShape(physics3d.Sphere{Radius: 0.25})
camPos := pivot.Add(armDelta)
if hit, ok := world.ShapeCastLayer(cameraProbe, pivot, physics3d.QuatIdentity(), armDelta, physics3d.LayerAll, playerBody); ok {
camPos = pivot.Add(armDelta.Scale(hit.T))
}
Rigid Bodies
A World holds static (Static: true or zero mass) and dynamic Body values and advances them in Step(dt) using velocity-first symplectic Euler integration (with implicit midpoint gyroscopic Euler torque), deterministic collision detection with multi-point contact manifolds, per-point warm-started iterative impulse solving with symmetric block LCP normals and 3D Coulomb friction, non-linear Gauss-Seidel positional correction, and automatic sleeping for settled bodies.
world := physics3d.NewWorld()
world.AddBody(physics3d.NewStaticBody(
physics3d.BoxShape(physics3d.Box{HalfExtents: physics3d.Vec3{X: 20, Y: 1, Z: 20}}),
physics3d.Vec3{Y: -1},
))
crate := world.AddBody(physics3d.NewDynamicBody(
physics3d.BoxShape(physics3d.Box{HalfExtents: physics3d.Vec3{X: 0.5, Y: 0.5, Z: 0.5}}),
physics3d.Vec3{Y: 3},
1.0,
))
loop := &game.Loop{
Update: func(dt time.Duration) {
world.Step(dt)
_ = crate.Pos
},
}
Inertia tensors, gyroscopic motion, and per-body overrides
Every dynamic Body computes a body-space inverse inertia tensor (InvInertiaTensor SymMat3) from its Shape, Mass, and CenterOfMass: exact diagonal principal moments for axis-aligned boxes, spheres, capsules, and cylinders, and full symmetric tensors (including the parallel-axis shift) for offset, rotated, convex-hull, and compound shapes. At each step the solver, all seven built-in Joint3D types, and game/vehicle rotate InvInertiaTensor into world space (Body.WorldInvInertiaTensor()), and free angular motion integrates Euler's gyroscopic torque term ($I\dot{\omega} + \omega \times (I\omega) = 0$) via an energy-conserving implicit midpoint update so asymmetric spinning bodies (such as a plank spun near its intermediate principal axis) exhibit realistic Dzhanibekov flips while symmetric cubes remain stable.
Override mass distribution per body when needed:
Body.SetInertia(diag Vec3)sets diagonal body-space principal moments $(I_x, I_y, I_z)$ directly (zero axes lock rotation about that axis;DiagSymMat3constructs a diagonalSymMat3).Body.SetInertiaTensor(inertia SymMat3)sets a full symmetric body-space inertia tensor and inverts it intoInvInertiaTensor.Body.SetCenterOfMass(localCOM Vec3)shifts the local center of mass and recomputesInvInertiaTensorabout the new pivot unless inertia was explicitly overridden.Body.RecomputeMassProperties()clears custom inertia and center-of-mass overrides and restores the shape-derived defaults.LockRotationkeeps a dynamic body from rotating. Inputs that are not finite (a NaN velocity or mass) fall back to defaults inAddBody, and a kinematic body without mass stays kinematic.
Contact manifolds, warm starting, and stacking
Face-to-face collisions generate persistent multi-point contact manifolds rather than a single contact point:
- Box-box and convex hull / cylinder faces: Sutherland-Hodgman face clipping produces up to 4 contact points with persistent feature IDs and per-point penetration depths, reduced deterministically to maximize support area.
- Capsule on face: capsules resting on boxes, convex hulls, cylinder caps, or triangles clip the centerline segment against the reference face prism to produce up to 2 contact points (collapsing to 1 when standing upright on an end cap).
- Per-point warm starting and friction: each manifold point tracks its own accumulated normal and tangent impulses across steps (matched by feature ID first, then local-space proximity). Normal impulses for 2–4 point manifolds are solved simultaneously with a regularized float64 active-set Cholesky LCP so flat faces never incur corner-order tipping torque, followed by per-point 3D Coulomb friction and planar non-linear Gauss-Seidel positional/angular correction.
Contact impulses act at each contact point, so friction makes a sliding sphere roll, a flat box rests without rocking, and a box standing on an edge tips over onto a face.
Physics materials
Attach a shared *PhysicsMaterial (Friction, Restitution, LinearDamping, AngularDamping) to Body.Material, or copy its values onto a body with Body.ApplyMaterial(mat). When Body.Material is non-nil, contact resolution and velocity damping read the material's clamped surface properties directly (Friction >= 0, Restitution in [0, 1], non-negative damping), so editing a shared material takes effect across every body referencing it. Shared *.physics.yaml files from game/resource apply to 3D bodies with mat.ApplyTo3D(body).
Settled bodies sleep. A sleeping body wakes when a moving dynamic body or a kinematic body (moving by velocity or by setting Pos/Rot directly) touches it, when a body jointed to it moves, when one of its contacts ends (its support moved away), when a VoxelCollider block near it changes solidity or disappears under it, and on Wake, WakeInBox, ApplyImpulse, and the removal of bodies, meshes, voxel colliders, or joints.
Ordinary stacks (such as a 10-box uniform tower) settle cleanly and stand without residual drift from multi-point manifolds and per-point warm starting alone. Scoped shock propagation stays active only for vertical support columns (within about 45° of -Gravity) that contain a large upper-to-lower mass ratio (> 4:1, such as a 100 kg box on 1 kg boxes) or more than 12 stacked dynamic bodies, making one bottom-up pass that treats the lower body as immovable and keeps overlap near 1 mm. A body still sunk more than 5 mm into a neighbor does not fall asleep, and a sleeping body pushed deeper than 1 cm wakes, so sleeping never freezes an overlap in place. With zero gravity there is no "up" and the shock pass is skipped.
A shape that ends up below a heightfield's surface is pushed out upward, by the depth measured along the upward triangle normal, so it clears the surface in one correction rather than by the shallower distance to the nearest point underneath. A shape beside a cell, such as one at the foot of a step touching the plateau's edge, keeps the depth of its own contact, so it is not lifted onto the plateau.
A dynamic body that moves more than half its smallest dimension in one step is swept in sub-steps against static, kinematic and sleeping bodies, triangle meshes, heightfields, and voxel colliders, and stops at the first new overlap, so fast bodies do not tunnel through thin geometry. Contacts the body already has when the step begins, such as the floor under a fast sliding or rolling body, do not stop it unless the body sinks clearly deeper into them. Fast dynamic bodies are not swept against each other.
Broadphase
World accelerates body-pair detection, raycasts (Raycast, RaycastFirst, RaycastLayer, RaycastFirstLayer), overlaps (QueryOverlap, OverlapLayer), CCD sweeps, WakeInBox, and CharacterController queries with separate deterministic static and dynamic AABB trees:
- Separate static and dynamic trees: static non-trigger bodies,
TriMeshColliders, andHeightfieldColliders live in the static tree (each triangle mesh and heightfield stays as a single broadphase entry, backed by its own internal BVH or grid), built top-down for tight spatial partitioning so stationary level geometry costs almost nothing until something moves near it. Dynamic, kinematic, and trigger bodies live in the dynamic tree with fattened AABBs, predictive displacement expansion, and SAH-minimizing rotations so sleeping or slowly moving bodies rarely update the tree. - Deterministic order: candidate pairs are sorted into body insertion order and raycast/overlap tie-breaking follows the same deterministic rules as a linear scan, so trajectories, events, and query hits remain bit-identical to a brute-force pass.
- Automatic sync:
AddBody,RemoveBody,AddTriMesh,RemoveTriMesh,AddHeightfield,RemoveHeightfield,Restore, andStepmaintain the broadphase automatically. If you mutate a body'sPos,Rot,Shape,Static, orIsTriggerfields directly and run raycast or overlap queries before the nextStep, callworld.SyncBroadphase()first.
Voxel Colliders
VoxelCollider (created with NewVoxelCollider(grid) and added with World.AddVoxelCollider, or adapted from game/voxel via voxel.NewCollider(w) / w.Collider()) collides bodies, CharacterController, CCD, and world raycast/overlap queries directly against any VoxelGrid without building a triangle mesh:
- Direct queries:
QueryBlocks,TestShape,CollectContacts,Raycast(3D Amanatides & Woo DDA, accelerated when the grid implementsVoxelBoundsGrid), andSweep(exact Minkowski-sum swept AABB for axis-aligned boxes; sub-stepped binary-search TOI for spheres, capsules, and oriented boxes) visit solid voxels in deterministic(y, z, x)order. - Internal-seam filtering: faces occluded by adjacent solid blocks are filtered out so crates, spheres, capsules, and characters never snag on flat voxel floor or wall seams.
- Instant edit reflection & wakeup: block changes take effect immediately with zero rebuild. Grids implementing
VoxelEditNotifierautomatically callNotifyBlockChanged/NotifyReset(which wake nearby sleeping bodies and stacked contacts viaWorld.WakeInBox), while plainVoxelGridimplementations still wake bodies whose voxel support disappears on the nextWorld.Step.
glTF, GridMap, and Heightmap Colliders
Build static level geometry directly from glTF scenes, world3d GridMaps, and standard Go heightmap images without manually unpacking vertices or cell boxes:
- glTF triangle meshes:
NewTriMeshFromGLTFPrimitive(prim, worldMat),NewTriMeshFromGLTFMesh(mesh, worldMat), andNewTriMeshFromGLTFNode(doc, nodeIdx)build BVH-accelerated*TriMeshCollidervalues from indexed or non-indexedTriangles,TriangleStrip, andTriangleFanprimitives, applying full node world transforms and flipping winding automatically when the transform has a negative determinant. - glTF collider conventions (
-colonly&extras.collider):World.AddGLTFColliders(doc, opts)andBuildGLTFColliders(doc, opts)recognize Godot-style node name suffixes (-col,-colonly,-boxcol,-boxcolonly,-spherecol,-spherecolonly,-capsulecol,-capsulecolonly,-convcol,-convcolonly, case-insensitive and tolerating Blender.001duplicate numbering) as well asnode.Extras({"collider": "box" | true | {"shape", "draw", "only", "trigger", "tag", "center", "halfExtents"|"size", "radius", "height", "friction", "restitution", "layer", "mask"}}). Primitive box and capsule colliders preserve full node rotation as oriented boxes and rotated capsules;-convcol/-convcolonlybuild aTriMeshCollideruntil native convex hulls are added. Visual renderers filter out collider-only nodes withdoc.DrawableNodes()ornode.IsDrawable()ingame/gltf. CallGLTFColliders.RemoveFromWorld(world)when unloading a streamed level. - Greedy 3D box merging &
GridMapbodies:MergeBoxes(boxes, eps)greedily merges adjacent axis-aligned boxes along X, then Z, then Y within toleranceeps(default1e-4), preserving the exact solid volume in deterministic order. On aworld3d.GridMap,grid.AddCollidersToWorld(world, opts)extracts cellColliderBoxesand merges adjacent cells into minimal static bodies (setDisableMerge: trueto emit one body per box). - Heightfields from
image.Image:NewHeightfieldFromImage(img, HeightfieldImageOptions{...})builds a*HeightfieldColliderfrom any 8-bit/16-bit grayscale or colorimage.Image(HeightmapLuminance,HeightmapRed,HeightmapGreen,HeightmapBlue,HeightmapAlpha), with configurableCellSizeorWorldWidth/WorldDepth,MinHeight/MaxHeight,Origin,FlipZ, and optional(Cols, Rows)resampling (Bilinear: truefor smooth interpolation). For an existingworld3d.Heightmap, callhm.Collider().
doc, err := gltf.LoadFS(assetsFS, "levels/courtyard.glb")
if err != nil {
return err
}
levelCols, err := world.AddGLTFColliders(doc, physics3d.GLTFColliderOptions{})
if err != nil {
return err
}
// Render only visual nodes (skips -colonly / draw:false collider nodes):
for _, nodeIdx := range doc.DrawableNodes() {
drawGLTFNode(doc, nodeIdx)
}
hf, err := physics3d.NewHeightfieldFromImage(heightImg, physics3d.HeightfieldImageOptions{
WorldWidth: 64,
MinHeight: -2,
MaxHeight: 18,
})
if err == nil {
world.AddHeightfield(hf)
}
_ = levelCols
Gravity Scale and Area Volumes
Body and CharacterController each support a per-entity GravityScale (initialized to 1 by NewDynamicBody and NewCharacterController; use SetGravityScale(0) for weightless objects or negative values to invert gravity).
Any trigger body (Body.IsTrigger = true) can configure Body.Area (AreaSettings) to override gravity, linear/angular damping, and fluid buoyancy/drag for overlapping dynamic bodies during World.Step and for CharacterController.Move:
- Gravity modes & priority: set
GravityModetoAreaOverrideCombine,AreaOverrideReplace, orAreaOverrideAddordered byPriority(higher priority first, deterministic insertion-order tie-breaking). Supports both directionalGravityand radialPointGravitytowardGravityPointwithGravityStrength,GravityFalloff(GravityFalloffNone,GravityFalloffLinear,GravityFalloffInverse,GravityFalloffInverseSquare), andGravityUnitDistance. - Damping overrides:
LinearDampingMode/LinearDampingandAngularDampingMode/AngularDampingoverride body damping using the same priority and combine/replace/add rules. - Buoyancy and fluid drag: set
FluidDensity(kg/m³) to apply Archimedes buoyancy from the submerged fraction of each body's bounds so a body with densityMass / Volumesettles at submerged fraction(Mass / Volume) / FluidDensity, alongsideFluidLinearDrag,FluidAngularDrag, and optionalFluidVelocitycurrent. - Area shapes: an area can be any shape. A point is inside a convex hull or a cylinder area by its exact shape, not its bounds, and a hull's or cylinder's buoyant volume is its own (
ConvexHull.Volume, or πr²h). - Queries & characters: call
world.GravityAt(point)orworld.AreaEffectAtShape(shape, layer, mask)to inspect the resolved field.CharacterController.Moveautomatically applies overlapping area gravity (scaled byCharacterController.GravityScale), fluid drag, and linear damping, andCharacterController.EffectiveGravity(world)reports the active gravity vector.
water := physics3d.NewStaticBody(
physics3d.BoxShape(physics3d.Box{HalfExtents: physics3d.Vec3{X: 20, Y: 5, Z: 20}}),
physics3d.Vec3{Y: -5},
)
water.IsTrigger = true
water.Area = physics3d.AreaSettings{
FluidDensity: 1000,
FluidLinearDrag: 5.0,
FluidAngularDrag: 2.0,
}
world.AddBody(water)
Joints and Ragdolls
World.AddJoint solves DistanceJoint, BallJoint, SwingTwistJoint, HingeJoint, SliderJoint, FixedJoint, and SixDOFJoint in deterministic insertion order:
HingeJoint.Angleis tracked across steps, so a hinge that keeps turning reports angles past ±π andMinAngle/MaxAnglecan span more than one turn. Optional spring and position drives (DriveTargetAngle,DriveStiffness,DriveDamping,DriveMaxTorque) pull a hinge smoothly toward a target angle (for self-closing doors or active joints), alongside velocity motors (MotorTargetVel,MotorMaxTorque).SliderJointsupports optional linear spring and position drives (DriveTargetPos,DriveStiffness,DriveDamping,DriveMaxForce) in addition to limits and velocity motors.DistanceJointis slack while its distance is inside[MinDistance, MaxDistance];StiffnessandDampingsoften the limits, so for a spring with rest lengthLset both limits toL.SwingTwistJointconstrains a ball-and-socket pivot with a four-quadrant asymmetric elliptic swing cone (SwingMin1,SwingMax1,SwingMin2,SwingMax2) and an independent twist range (MinTwist,MaxTwist), readable viaSwingAngles()andTwistAngle().BuildRagdollusesSwingTwistJointfor non-hinge limbs (shoulders, hips, spine, head) andHingeJointfor elbows, knees, and bones with an explicitHingeAxis;SkeletonJointaccepts optional asymmetric swing limits andTwistLimit/MinTwist/MaxTwist(defaulting to ±π/4 twist whenSwingLimit > 0so limbs cannot spin freely around their own axis).SixDOFJointconfigures each of the 3 linear (Linear[0..2]) and 3 angular (Angular[0..2]) axes independently viaAxisConfig:Mode(AxisFree,AxisLocked,AxisLimitedwithMin/Max), passive springStiffness/Damping, andDrive(DriveNone,DrivePosition,DriveVelocity) towardTargetPos/TargetVelclamped byMaxForce.- Every built-in joint reports its last-step world-space
ReactionForce()(N) andReactionTorque()(N·m) applied toBodyB, and supports optionalBreakForceandBreakTorquethresholds. When a joint exceeds either threshold duringWorld.Step, it is markedBroken(), removed from the world before positional correction, wakes dynamic bodies, and is reported deterministically inWorld.JointBreakEvents()andWorld.OnJointBreak.
Character Controller
CharacterController moves a kinematic capsule (Pos at the feet, Radius, Height) through a World via Move(world, wishMove, dt):
- Walks across flat ground and glides smoothly up and down slopes up to
MaxSlopeAngle(default 45°), staying grounded on descents. - Prevents climbing slopes steeper than
MaxSlopeAngleand slides down them under gravity. - Automatically steps up stairs up to
StepHeightafter verifying headroom clearance, forward progress, and a walkable landing tread. - Stops cleanly and slides tangentially along vertical walls without penetration.
- Pushes dynamic bodies it walks into with
PushForcenewtons; with the default 0 they block it like walls. - Tracks the supporting body (
GroundBody), its velocity at the contact point (GroundVelocity), and its per-step yaw rotation (GroundYawDelta) in bothCharacterControllerandMoveResult. - Carries the character by the exact linear and angular motion of kinematic or dynamic ground bodies each step — rotating the capsule around the platform pivot without drift and adding
GroundYawDeltatoYawwhenApplyPlatformYawis enabled (the default inNewCharacterController). - Configures velocity inheritance on jump or walk-off via
PlatformOnLeave:PlatformLeaveAddVelocity(default, inherits full ground velocity),PlatformLeaveAddUpwardVelocity(inherits horizontal and upward velocity while ignoring downward motion), orPlatformLeaveDoNothing(drops platform velocity). - Resolves moving kinematic bodies (sliding doors, walls, lifts) that sweep into the capsule by pushing it out along the separating normal, and reports
CrushedinMoveResult(andCharacterController.Crushed) when squeezed between opposing surfaces with no valid depenetration.
cc := physics3d.NewCharacterController(physics3d.Vec3{Y: 0}, 0.3, 1.8)
cc.PlatformOnLeave = physics3d.PlatformLeaveAddUpwardVelocity
loop := &game.Loop{
Update: func(dt time.Duration) {
res := cc.Move(world, physics3d.Vec3{X: 3.5}, dt)
_, _, _ = res.Pos, res.GroundBody, res.Crushed
},
}
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.
Debug Drawing
DrawWorld, DrawBody, DrawShape, DrawCharacter, DrawContact and DrawRaycast draw collider wireframes, contacts and rays onto a core.Drawing through a view-projection matrix, styled by DebugStyle; DrawLine3D draws one segment. Convex hulls draw every hull edge in HullColor, cylinders draw a ring around each cap and four side lines in CylinderColor, and compound shapes draw every child in its primitive's color (with DrawWorld marking contacts per colliding child pair); ConvexHullEdges and CylinderEdges return those segments for other renderers. Release builds compile them to no-ops.
Segments are clipped to the camera frustum before projection. By default the near plane is clip z >= -w, which matches this package's Mat4Perspective and Mat4Ortho ([-1, 1] depth). For a [0, 1] depth projection, such as math3d.Perspective, math3d.Ortho or a render3d camera, set DebugStyle.DepthZO (and use DrawLine3DZO for single segments): it clips at z >= 0, as render3d.ProjectSegment does. Without it an orthographic [0, 1] camera, whose w is 1 everywhere, draws colliders behind the camera.
style := physics3d.DefaultDebugStyle()
style.DepthZO = true // viewProj comes from math3d.Perspective or math3d.Ortho
physics3d.DrawWorld(d, physics3d.Mat4(viewProj), viewport, world, style)
Ropes, Cloth, and Soft Bodies (XPBD)
SoftWorld simulates 3D ropes, cloth meshes, and tetrahedral soft bodies using deterministic Extended Position-Based Dynamics (XPBD):
- Particles & constraints:
Particle(Pos,Vel,InvMass,Radius,Friction,Restitution,Pinned,Layer/Mask), bilateral & unilateralDistanceConstraint(AddDistance,AddTether), singularity-free dihedralBendingConstraint(AddBending), and tetrahedralVolumeConstraint(AddVolume). - Two-way rigid-body attachments:
AttachBodycouples particles to dynamic or kinematic*Bodyinstances at local anchors (Compliance == 0for rigid pins,> 0for elastic tethers), returning linear and angular reaction impulses to the attached body and waking sleeping bodies automatically. - Collisions & layer filtering: setting
SoftWorld.Worldcollides particles against non-triggerBodyshapes (oriented boxes, spheres, capsules),TriMeshCollider, andHeightfieldCollider, respectingLayer/Maskfiltering. - Builders & debug drawing:
AddRope(RopeConfig)builds inextensible 3D ropes with unilateral long-range tethers;AddCloth(ClothConfig)builds a triangulated cloth grid with structural, shear, and dihedral bending constraints (ClothGrid.Index(col, row));AddSoftBox(SoftBoxConfig)builds an 8-vertex, 5-tetrahedron deformable cube;Edges()returns structural wireframe segments, andDrawSoftWorld(d, viewProj, viewport, sw, style)renders them (no-op in-tags releasebuilds).
world := physics3d.NewWorld()
world.AddBody(physics3d.NewStaticBody(
physics3d.SphereShape(physics3d.Sphere{Radius: 1.0}),
physics3d.Vec3{Y: 1.0},
))
sw := physics3d.NewSoftWorld()
sw.World = world
sw.AddCloth(physics3d.ClothConfig{
Origin: physics3d.Vec3{X: -1.1, Y: 2.25, Z: -1.1},
Width: 2.2,
Height: 2.2,
Cols: 10,
Rows: 10,
PinTopLeft: true,
PinTopRight: true,
})
// Inside game.Loop.Update:
world.Step(dt)
sw.Step(dt)
Snapshots, Rollback, and Cross-Architecture Determinism
World supports full state snapshots, deterministic FNV-1a 64-bit checksums, and cross-architecture determinism across amd64 and arm64:
Save() / Restore(snap) / Checksum():World.Save()captures all public and private solver state into a versionedWorldSnapshot(SnapshotVersion), including gravity and solver/sleep settings, bodies (with their full shape, including aConvexHull's geometry,Cylinder, andShapeCompoundchildren,CenterOfMass,InvInertiaTensor, custom center-of-mass/inertia override flags, private sleep timers, gravity-scale flags, residual depth, previous interpolation poses, and voxel resting state), sorted per-child multi-point (up to 4 points with feature IDs and local offsets) warm-start contact impulse cache, active contact/trigger pair sets, last-step contact and joint-break events (including compound child indices), ignored body pairs, all 7 built-inJoint3Dtypes (DistanceJoint,BallJoint,HingeJoint,SliderJoint,FixedJoint,SwingTwistJoint,SixDOFJoint, including unwrapped angle state and last reaction impulses), plusTriMeshCollider,HeightfieldCollider, andVoxelGridcollider bindings.- JSON-serializable plain text:
WorldSnapshotmarshals cleanly withencoding/json(noencoding/gobor custom binary layout). - In-place pointer & callback preservation:
Restoreupdates existing*Body,Joint3D, and collider instances in place when counts/kinds match, rebuilds the broadphase trees deterministically, and preserves gameplay pointers,UserData, and world callbacks (OnContact,OnTrigger,OnJointBreak). - Cross-architecture determinism: all stepped 3D integration, broadphase, narrowphase (GJK/EPA/SAT, OBB, mesh/heightfield, voxel), sequential impulse solver, joint, area, and
vehiclesuspension/tire paths avoid arm64 FMA contraction and FMA-using standard library transcendentals, ensuring bit-identical trajectories andChecksum()values on amd64 and arm64.
snap := world.Save()
hash := world.Checksum()
// Serialize to plain-text JSON (or store in a net.SimState rollback buffer):
raw, _ := json.Marshal(snap)
var restored physics3d.WorldSnapshot
_ = json.Unmarshal(raw, &restored)
if err := world.Restore(restored); err != nil {
return err
}
_ = hash
Authoring in scene files
3D physics bodies, colliders, and triggers can be authored directly in *.scene.yaml files with the built-in body3d, collider3d, and trigger3d components from sceneformat, using 3D gravity, solver iterations, and named collision layers defined under physics: in game.yaml. body3d supports static, dynamic, kinematic, and trigger kinds, layer/mask, and physicsMaterial / material paths; collider3d supports box, sphere, capsule, cylinder, convex and static trimesh from the object's model or mesh, and static heightfield from a *.terrain.yaml file, with local offsetX/offsetY/offsetZ and rotX/rotY/rotZ. sceneformat.BuildPhysics(built, gameProject.PhysicsSettings(), lib) populates physics3d.World (Bodies3D, TriMeshes3D, Heightfields3D), resolves named layer and mask lists, applies *.physics.yaml files, and keeps body poses synchronized with BuiltScene and the editor's Play mode. In the 3D editor viewport, switch to Gizmo3DCollider (shift+c) to drag collider size handles as single undo steps or press Fit to Model Bounds (Editor.FitCollider3DToBounds) to match a collider to its model's bounds.