Documentation
¶
Overview ¶
Package box2d is a native Go port of Box2D v3.2.0, the 2D physics engine by Erin Catto (https://github.com/erincatto/box2d).
The port targets full Box2D v3 feature parity: rigid bodies, the v3 TGS-soft solver with sub-stepping, all shape types, all seven joint types, sensors, continuous collision (bullets), and world queries. Source files mirror the upstream C files one-to-one so changes can be diffed against upstream mechanically. Portions of the collision code are seeded from the hand-written ByteArena Go port of Box2D 2.4 (zlib license); see LICENSE.
Differences from upstream ¶
- All arithmetic is float64 (upstream is float32).
- Worlds are values returned by NewWorld, not entries in a global registry; every b2World_*/b2Body_*/b2Shape_*/b2Joint_* function is a method on *World.
- The upstream task system is ported as an internal goroutine pool (worker_pool.go): WorldDef.WorkerCount selects how many workers World.Step may use (0 means 1, i.e. fully serial), and the World owns its worker goroutines from NewWorld to Destroy. Upstream's user-supplied enqueueTask/finishTask callbacks are NOT exposed.
Multithreading ¶
With WorldDef.WorkerCount > 1, World.Step fans its parallel stages out to a persistent internal worker pool. Unlike upstream — where results may vary with the worker count and scheduling — simulation results here are BYTE-IDENTICAL for every worker count: work is split into static contiguous ascending ranges (a pure function of the item count and worker count, no work stealing), per-item arithmetic is unchanged by the split, and every per-worker output is merged either order-free (bit-set OR) or in ascending worker order, which equals the serial order. WorkerCount is therefore purely a throughput knob; it can differ between machines, or between a live run and a replay, without affecting determinism. The count is taken as given (upstream does not clamp it either): values above the machine's core count oversubscribe the scheduler and cost throughput, never correctness. Small dispatches engage fewer workers than WorkerCount — each stage has a minimum items-per-worker grain (upstream minRange) — so tiny worlds run mostly inline no matter how many workers were requested. The golden suites enforce determinism by re-running every scene at WorkerCount 2/4/8 against the serial golden files (golden_workers_test.go).
Everything outside Step keeps the single-goroutine contract: a World must not be stepped, mutated, or queried from two goroutines at once, nor queried while Step is running.
User callbacks run concurrently when WorkerCount > 1: the preSolve callback (SetPreSolveCallback), the custom filter callback (SetCustomFilterCallback) and the friction/restitution mixing callbacks are invoked from pool workers during the parallel stages, possibly simultaneously from several goroutines. They must be safe to call concurrently and must not mutate shared state — a callback that gives scheduling-dependent answers also voids the byte-identical-for-every-worker-count guarantee.
Determinism ¶
The port is bit-deterministic for identical inputs across runs, platforms, and architectures (amd64/arm64). This relies on package-wide coding rules:
- No *unrounded* product may reach a + or -. The Go compiler may fuse such a pair into a single FMA instruction, which rounds once instead of twice and so produces different bits on targets that have FMA (arm64 always, amd64 at GOAMD64=v3) than on targets that do not. The product does not have to be written inline to be fusable: it also fuses when it arrives through a local, a struct field, or a function parameter that is later inlined. Products are therefore rounded with float64(...) where they are formed, and the arithmetic helpers in math_fma.go additionally round the operands they receive. This rule is enforced mechanically by TestNoFusedMultiplyAdd, which compiles the package for FMA-capable targets and fails if any FMA instruction is emitted — reviewing source for this is not reliable.
- Transcendentals use the ported upstream approximations (Atan2, ComputeCosSin). Only exactly-rounded stdlib math functions are used otherwise (Sqrt, Remainder, Floor, Abs).
- No Go maps or time sources in the simulation path; iteration orders are explicit and match upstream data structures. The only goroutines are the internal worker pool's (worker_pool.go), whose static partitioning and ordered merges keep every iteration order equal to the serial one (see Multithreading above).
- Exactly one sort runs in the simulation path: the per-sensor overlap sort in sensor.go (upstream sorts the same array with qsort). Its comparator is a total order over the (shapeID, generation) visitor key, so the unstable sort still produces a unique result. No other code in the step may sort.
Cross-architecture equivalence is enforced in CI by golden-trace hash tests (see testdata/golden).
Profile-guided optimization ¶
The package ships a committed CPU profile, default.pgo, merged from the step benchmarks in bench_test.go (mixed-shape rain at 1000 and 5000 bodies at WorkerCount 1 and the full core count; the pyramid stack and the jointed chain at WorkerCount 1). Go applies PGO where the final binary is built, so the file does not act on this package by itself: library consumers who want PGO-shaped codegen for the engine put a profile named default.pgo in their own main package directory (ideally collected from production runs of their game, which then also covers their own hot code) or build with -pgo=<file>. This package's own tests and benchmarks opt in the same way: go test -pgo=default.pgo — the profile is not picked up automatically for a library's test binary.
PGO cannot change simulation results: it only steers inlining and code layout, the float64(...) roundings that forbid FMA fusion are semantic and survive any inlining decision, and TestNoFusedMultiplyAdd repeats its FMA-instruction scan with -pgo=default.pgo on every checked architecture to prove it.
Index ¶
- Constants
- Variables
- func AABBContains(a, b AABB) bool
- func AABBOverlaps(a, b AABB) bool
- func Atan2(y, x float64) float64
- func ComputeAngularVelocity(q1, q2 Rot, invH float64) float64
- func Cross(a, b Vec2) float64
- func Distance(a, b Vec2) float64
- func DistanceSquared(a, b Vec2) float64
- func Dot(a, b Vec2) float64
- func GetLengthUnitsPerMeter() float64
- func Hash(hash uint32, data []byte) uint32
- func IsNormalized(a Vec2) bool
- func IsNormalizedRot(q Rot) bool
- func IsValidAABB(a AABB) bool
- func IsValidFloat(a float64) bool
- func IsValidPlane(a Plane) bool
- func IsValidRay(input *RayCastInput) bool
- func IsValidRotation(q Rot) bool
- func IsValidTransform(t Transform) bool
- func IsValidVec2(v Vec2) bool
- func Length(v Vec2) float64
- func LengthSquared(v Vec2) float64
- func PackBodyID(id BodyID) uint64
- func PackChainID(id ChainID) uint64
- func PackContactID(id ContactID) [3]uint32
- func PackJointID(id JointID) uint64
- func PackShapeID(id ShapeID) uint64
- func PackWorldID(id WorldID) uint32
- func PlaneSeparation(plane Plane, point Vec2) float64
- func PointInCapsule(shape *Capsule, point Vec2) bool
- func PointInCircle(shape *Circle, point Vec2) bool
- func PointInPolygon(shape *Polygon, point Vec2) bool
- func RelativeAngle(a, b Rot) float64
- func RotGetAngle(q Rot) float64
- func SetLengthUnitsPerMeter(lengthUnits float64)
- func SpringDamper(hertz, dampingRatio, position, velocity, timeStep float64) float64
- func UnwindAngle(radians float64) float64
- func ValidateHull(hull *Hull) bool
- type AABB
- func AABBUnion(a, b AABB) AABB
- func ComputeCapsuleAABB(shape *Capsule, xf Transform) AABB
- func ComputeCircleAABB(shape *Circle, xf Transform) AABB
- func ComputePolygonAABB(shape *Polygon, xf Transform) AABB
- func ComputeSegmentAABB(shape *Segment, xf Transform) AABB
- func MakeAABB(points []Vec2, radius float64) AABB
- type BodyDef
- type BodyEvents
- type BodyID
- type BodyMoveEvent
- type BodyType
- type Capsule
- type CastOutput
- func AABBRayCast(a AABB, p1, p2 Vec2) CastOutput
- func RayCastCapsule(shape *Capsule, input *RayCastInput) CastOutput
- func RayCastCircle(shape *Circle, input *RayCastInput) CastOutput
- func RayCastPolygon(shape *Polygon, input *RayCastInput) CastOutput
- func RayCastSegment(shape *Segment, input *RayCastInput, oneSided bool) CastOutput
- func ShapeCast(input *ShapeCastPairInput) CastOutput
- func ShapeCastCapsule(shape *Capsule, input *ShapeCastInput) CastOutput
- func ShapeCastCircle(shape *Circle, input *ShapeCastInput) CastOutput
- func ShapeCastPolygon(shape *Polygon, input *ShapeCastInput) CastOutput
- func ShapeCastSegment(shape *Segment, input *ShapeCastInput) CastOutput
- type CastResultFcn
- type ChainDef
- type ChainID
- type ChainSegment
- type Circle
- type CollisionPlane
- type ContactBeginTouchEvent
- type ContactData
- type ContactDrawType
- type ContactEndTouchEvent
- type ContactEvents
- type ContactHitEvent
- type ContactID
- type CosSin
- type Counters
- type CustomFilterFcn
- type DebugDraw
- type DistanceInput
- type DistanceJointDef
- type DistanceOutput
- type DynamicTree
- func (tree *DynamicTree) CreateProxy(aabb AABB, categoryBits uint64, userData uint64) int
- func (tree *DynamicTree) Destroy()
- func (tree *DynamicTree) DestroyProxy(proxyID int)
- func (tree *DynamicTree) EnlargeProxy(proxyID int, aabb AABB)
- func (tree *DynamicTree) GetAABB(proxyID int) AABB
- func (tree *DynamicTree) GetAreaRatio() float64
- func (tree *DynamicTree) GetCategoryBits(proxyID int) uint64
- func (tree *DynamicTree) GetHeight() int
- func (tree *DynamicTree) GetProxyCount() int
- func (tree *DynamicTree) GetRootBounds() AABB
- func (tree *DynamicTree) GetUserData(proxyID int) uint64
- func (tree *DynamicTree) MoveProxy(proxyID int, aabb AABB)
- func (tree *DynamicTree) Query(aabb AABB, maskBits uint64, callback TreeQueryCallbackFcn, context any) TreeStats
- func (tree *DynamicTree) QueryAll(aabb AABB, callback TreeQueryCallbackFcn, context any) TreeStats
- func (tree *DynamicTree) RayCast(input *RayCastInput, maskBits uint64, callback TreeRayCastCallbackFcn, ...) TreeStats
- func (tree *DynamicTree) Rebuild(fullBuild bool) int
- func (tree *DynamicTree) SetCategoryBits(proxyID int, categoryBits uint64)
- func (tree *DynamicTree) ShapeCast(input *ShapeCastInput, maskBits uint64, callback TreeShapeCastCallbackFcn, ...) TreeStats
- func (tree *DynamicTree) Validate() error
- func (tree *DynamicTree) ValidateNoEnlarged() error
- type ExplosionDef
- type Filter
- type FilterJointDef
- type FrictionCallback
- type HexColor
- type Hull
- type JointDef
- type JointEvent
- type JointEvents
- type JointID
- type JointType
- type Manifold
- func CollideCapsuleAndCircle(capsuleA *Capsule, xfA Transform, circleB *Circle, xfB Transform) Manifold
- func CollideCapsules(capsuleA *Capsule, xfA Transform, capsuleB *Capsule, xfB Transform) Manifold
- func CollideChainSegmentAndCapsule(segmentA *ChainSegment, xfA Transform, capsuleB *Capsule, xfB Transform, ...) Manifold
- func CollideChainSegmentAndCircle(segmentA *ChainSegment, xfA Transform, circleB *Circle, xfB Transform) Manifold
- func CollideChainSegmentAndPolygon(segmentA *ChainSegment, xfA Transform, polygonB *Polygon, xfB Transform, ...) Manifold
- func CollideCircles(circleA *Circle, xfA Transform, circleB *Circle, xfB Transform) Manifold
- func CollidePolygonAndCapsule(polygonA *Polygon, xfA Transform, capsuleB *Capsule, xfB Transform) Manifold
- func CollidePolygonAndCircle(polygonA *Polygon, xfA Transform, circleB *Circle, xfB Transform) Manifold
- func CollidePolygons(polygonA *Polygon, xfA Transform, polygonB *Polygon, xfB Transform) Manifold
- func CollideSegmentAndCapsule(segmentA *Segment, xfA Transform, capsuleB *Capsule, xfB Transform) Manifold
- func CollideSegmentAndCircle(segmentA *Segment, xfA Transform, circleB *Circle, xfB Transform) Manifold
- func CollideSegmentAndPolygon(segmentA *Segment, xfA Transform, polygonB *Polygon, xfB Transform) Manifold
- type ManifoldPoint
- type MassData
- type Mat22
- type MotionLocks
- type MotorJointDef
- type OverlapResultFcn
- type Plane
- type PlaneResult
- type PlaneResultFcn
- type PlaneSolverResult
- type Polygon
- func MakeBox(halfWidth, halfHeight float64) Polygon
- func MakeOffsetBox(halfWidth, halfHeight float64, center Vec2, rotation Rot) Polygon
- func MakeOffsetPolygon(hull *Hull, position Vec2, rotation Rot) Polygon
- func MakeOffsetRoundedBox(halfWidth, halfHeight float64, center Vec2, rotation Rot, radius float64) Polygon
- func MakeOffsetRoundedPolygon(hull *Hull, position Vec2, rotation Rot, radius float64) Polygon
- func MakePolygon(hull *Hull, radius float64) Polygon
- func MakeRoundedBox(halfWidth, halfHeight, radius float64) Polygon
- func MakeSquare(halfWidth float64) Polygon
- func TransformPolygon(transform Transform, polygon *Polygon) Polygon
- type PreSolveFcn
- type PrismaticJointDef
- type Profile
- type QueryFilter
- type RayCastInput
- type RayResult
- type RestitutionCallback
- type RevoluteJointDef
- type Rot
- func ComputeRotationBetweenUnitVectors(v1, v2 Vec2) Rot
- func IntegrateRotation(q1 Rot, deltaAngle float64) Rot
- func InvMulRot(a, b Rot) Rot
- func InvertRot(a Rot) Rot
- func MakeRot(radians float64) Rot
- func MakeRotFromUnitVector(unitVector Vec2) Rot
- func MulRot(q, r Rot) Rot
- func NLerp(q1, q2 Rot, t float64) Rot
- func NormalizeRot(q Rot) Rot
- type Segment
- type SegmentDistanceResult
- type SensorBeginTouchEvent
- type SensorEndTouchEvent
- type SensorEvents
- type ShapeCastInput
- type ShapeCastPairInput
- type ShapeDef
- type ShapeID
- type ShapeProxy
- type ShapeType
- type Simplex
- type SimplexCache
- type SimplexVertex
- type SurfaceMaterial
- type Sweep
- type TOIInput
- type TOIOutput
- type TOIState
- type Transform
- type TreeNode
- type TreeQueryCallbackFcn
- type TreeRayCastCallbackFcn
- type TreeShapeCastCallbackFcn
- type TreeStats
- type Vec2
- func AABBCenter(a AABB) Vec2
- func AABBExtents(a AABB) Vec2
- func Abs(a Vec2) Vec2
- func Add(a, b Vec2) Vec2
- func Clamp(v, a, b Vec2) Vec2
- func ClipVector(vector Vec2, planes []CollisionPlane) Vec2
- func CrossSV(s float64, v Vec2) Vec2
- func CrossVS(v Vec2, s float64) Vec2
- func GetLengthAndNormalize(v Vec2) (Vec2, float64)
- func InvRotateVector(q Rot, v Vec2) Vec2
- func InvTransformPoint(t Transform, p Vec2) Vec2
- func LeftPerp(v Vec2) Vec2
- func Lerp(a, b Vec2, t float64) Vec2
- func Max(a, b Vec2) Vec2
- func Min(a, b Vec2) Vec2
- func Mul(a, b Vec2) Vec2
- func MulAdd(a Vec2, s float64, b Vec2) Vec2
- func MulMV(a Mat22, v Vec2) Vec2
- func MulSV(s float64, v Vec2) Vec2
- func MulSub(a Vec2, s float64, b Vec2) Vec2
- func Neg(a Vec2) Vec2
- func Normalize(v Vec2) Vec2
- func RightPerp(v Vec2) Vec2
- func RotGetXAxis(q Rot) Vec2
- func RotGetYAxis(q Rot) Vec2
- func RotateVector(q Rot, v Vec2) Vec2
- func Solve22(m Mat22, b Vec2) Vec2
- func Sub(a, b Vec2) Vec2
- func TransformPoint(t Transform, p Vec2) Vec2
- type Version
- type WeldJointDef
- type WheelJointDef
- type World
- func (w *World) ApplyBodyAngularImpulse(bodyID BodyID, impulse float64, wake bool)
- func (w *World) ApplyBodyForce(bodyID BodyID, force, point Vec2, wake bool)
- func (w *World) ApplyBodyForceToCenter(bodyID BodyID, force Vec2, wake bool)
- func (w *World) ApplyBodyLinearImpulse(bodyID BodyID, impulse, point Vec2, wake bool)
- func (w *World) ApplyBodyLinearImpulseToCenter(bodyID BodyID, impulse Vec2, wake bool)
- func (w *World) ApplyBodyMassFromShapes(bodyID BodyID)
- func (w *World) ApplyBodyTorque(bodyID BodyID, torque float64, wake bool)
- func (w *World) ApplyShapeWind(shapeID ShapeID, wind Vec2, drag, lift float64, wake bool)
- func (w *World) AreShapeContactEventsEnabled(shapeID ShapeID) bool
- func (w *World) AreShapeHitEventsEnabled(shapeID ShapeID) bool
- func (w *World) AreShapePreSolveEventsEnabled(shapeID ShapeID) bool
- func (w *World) AreShapeSensorEventsEnabled(shapeID ShapeID) bool
- func (w *World) AwakeBodyCount() int
- func (w *World) BodyAngularDamping(bodyID BodyID) float64
- func (w *World) BodyAngularVelocity(bodyID BodyID) float64
- func (w *World) BodyContactCapacity(bodyID BodyID) int
- func (w *World) BodyContactData(bodyID BodyID, contactData []ContactData) int
- func (w *World) BodyEvents() BodyEvents
- func (w *World) BodyGravityScale(bodyID BodyID) float64
- func (w *World) BodyJointCount(bodyID BodyID) int
- func (w *World) BodyJoints(bodyID BodyID, jointArray []JointID) int
- func (w *World) BodyLinearDamping(bodyID BodyID) float64
- func (w *World) BodyLinearVelocity(bodyID BodyID) Vec2
- func (w *World) BodyLocalCenterOfMass(bodyID BodyID) Vec2
- func (w *World) BodyLocalPoint(bodyID BodyID, worldPoint Vec2) Vec2
- func (w *World) BodyLocalPointVelocity(bodyID BodyID, localPoint Vec2) Vec2
- func (w *World) BodyLocalVector(bodyID BodyID, worldVector Vec2) Vec2
- func (w *World) BodyMass(bodyID BodyID) float64
- func (w *World) BodyMassData(bodyID BodyID) MassData
- func (w *World) BodyMotionLocks(bodyID BodyID) MotionLocks
- func (w *World) BodyName(bodyID BodyID) string
- func (w *World) BodyPosition(bodyID BodyID) Vec2
- func (w *World) BodyRotation(bodyID BodyID) Rot
- func (w *World) BodyRotationalInertia(bodyID BodyID) float64
- func (w *World) BodyShapeCount(bodyID BodyID) int
- func (w *World) BodyShapes(bodyID BodyID, shapeArray []ShapeID) int
- func (w *World) BodySleepThreshold(bodyID BodyID) float64
- func (w *World) BodyTransform(bodyID BodyID) Transform
- func (w *World) BodyType(bodyID BodyID) BodyType
- func (w *World) BodyUserData(bodyID BodyID) uint64
- func (w *World) BodyWorldCenterOfMass(bodyID BodyID) Vec2
- func (w *World) BodyWorldPoint(bodyID BodyID, localPoint Vec2) Vec2
- func (w *World) BodyWorldPointVelocity(bodyID BodyID, worldPoint Vec2) Vec2
- func (w *World) BodyWorldVector(bodyID BodyID, localVector Vec2) Vec2
- func (w *World) CastMover(mover *Capsule, translation Vec2, filter QueryFilter) float64
- func (w *World) CastRay(origin, translation Vec2, filter QueryFilter, fcn CastResultFcn, context any) TreeStats
- func (w *World) CastRayClosest(origin, translation Vec2, filter QueryFilter) RayResult
- func (w *World) CastShape(proxy *ShapeProxy, translation Vec2, filter QueryFilter, fcn CastResultFcn, ...) TreeStats
- func (w *World) ChainSegmentCount(chainID ChainID) int
- func (w *World) ChainSegments(chainID ChainID, segmentArray []ShapeID) int
- func (w *World) ChainSurfaceMaterial(chainID ChainID, segmentIndex int) SurfaceMaterial
- func (w *World) ChainSurfaceMaterialCount(chainID ChainID) int
- func (w *World) ClearBodyForces(bodyID BodyID)
- func (w *World) CollideMover(mover *Capsule, filter QueryFilter, fcn PlaneResultFcn, context any)
- func (w *World) ComputeBodyAABB(bodyID BodyID) AABB
- func (w *World) ContactData(contactID ContactID) ContactData
- func (w *World) ContactEvents() ContactEvents
- func (w *World) ContactRecycleDistance() float64
- func (w *World) Counters() Counters
- func (w *World) CreateBody(def *BodyDef) BodyID
- func (w *World) CreateCapsuleShape(bodyID BodyID, def *ShapeDef, capsule *Capsule) ShapeID
- func (w *World) CreateChain(bodyID BodyID, def *ChainDef) ChainID
- func (w *World) CreateCircleShape(bodyID BodyID, def *ShapeDef, circle *Circle) ShapeID
- func (w *World) CreateDistanceJoint(def *DistanceJointDef) JointID
- func (w *World) CreateFilterJoint(def *FilterJointDef) JointID
- func (w *World) CreateMotorJoint(def *MotorJointDef) JointID
- func (w *World) CreatePolygonShape(bodyID BodyID, def *ShapeDef, polygon *Polygon) ShapeID
- func (w *World) CreatePrismaticJoint(def *PrismaticJointDef) JointID
- func (w *World) CreateRevoluteJoint(def *RevoluteJointDef) JointID
- func (w *World) CreateSegmentShape(bodyID BodyID, def *ShapeDef, segment *Segment) ShapeID
- func (w *World) CreateWeldJoint(def *WeldJointDef) JointID
- func (w *World) CreateWheelJoint(def *WheelJointDef) JointID
- func (w *World) Destroy()
- func (w *World) DestroyBody(bodyID BodyID)
- func (w *World) DestroyChain(chainID ChainID)
- func (w *World) DestroyJoint(jointID JointID, wakeAttached bool)
- func (w *World) DestroyShape(shapeID ShapeID, updateBodyMass bool)
- func (w *World) DisableBody(bodyID BodyID)
- func (w *World) DistanceJointCurrentLength(jointID JointID) float64
- func (w *World) DistanceJointLength(jointID JointID) float64
- func (w *World) DistanceJointMaxLength(jointID JointID) float64
- func (w *World) DistanceJointMaxMotorForce(jointID JointID) float64
- func (w *World) DistanceJointMinLength(jointID JointID) float64
- func (w *World) DistanceJointMotorForce(jointID JointID) float64
- func (w *World) DistanceJointMotorSpeed(jointID JointID) float64
- func (w *World) DistanceJointSpringDampingRatio(jointID JointID) float64
- func (w *World) DistanceJointSpringForceRange(jointID JointID) (float64, float64)
- func (w *World) DistanceJointSpringHertz(jointID JointID) float64
- func (w *World) Draw(draw *DebugDraw)
- func (w *World) EnableBody(bodyID BodyID)
- func (w *World) EnableBodyContactEvents(bodyID BodyID, flag bool)
- func (w *World) EnableBodyHitEvents(bodyID BodyID, flag bool)
- func (w *World) EnableBodySleep(bodyID BodyID, enableSleep bool)
- func (w *World) EnableContinuous(flag bool)
- func (w *World) EnableDistanceJointLimit(jointID JointID, enableLimit bool)
- func (w *World) EnableDistanceJointMotor(jointID JointID, enableMotor bool)
- func (w *World) EnableDistanceJointSpring(jointID JointID, enableSpring bool)
- func (w *World) EnablePrismaticJointLimit(jointID JointID, enableLimit bool)
- func (w *World) EnablePrismaticJointMotor(jointID JointID, enableMotor bool)
- func (w *World) EnablePrismaticJointSpring(jointID JointID, enableSpring bool)
- func (w *World) EnableRevoluteJointLimit(jointID JointID, enableLimit bool)
- func (w *World) EnableRevoluteJointMotor(jointID JointID, enableMotor bool)
- func (w *World) EnableRevoluteJointSpring(jointID JointID, enableSpring bool)
- func (w *World) EnableShapeContactEvents(shapeID ShapeID, flag bool)
- func (w *World) EnableShapeHitEvents(shapeID ShapeID, flag bool)
- func (w *World) EnableShapePreSolveEvents(shapeID ShapeID, flag bool)
- func (w *World) EnableShapeSensorEvents(shapeID ShapeID, flag bool)
- func (w *World) EnableSleeping(flag bool)
- func (w *World) EnableSpeculative(flag bool)
- func (w *World) EnableWarmStarting(flag bool)
- func (w *World) EnableWheelJointLimit(jointID JointID, enableLimit bool)
- func (w *World) EnableWheelJointMotor(jointID JointID, enableMotor bool)
- func (w *World) EnableWheelJointSpring(jointID JointID, enableSpring bool)
- func (w *World) Explode(explosionDef *ExplosionDef)
- func (w *World) Gravity() Vec2
- func (w *World) HitEventThreshold() float64
- func (w *World) ID() WorldID
- func (w *World) IsBodyAwake(bodyID BodyID) bool
- func (w *World) IsBodyBullet(bodyID BodyID) bool
- func (w *World) IsBodyEnabled(bodyID BodyID) bool
- func (w *World) IsBodySleepEnabled(bodyID BodyID) bool
- func (w *World) IsBodyValid(id BodyID) bool
- func (w *World) IsChainValid(id ChainID) bool
- func (w *World) IsContactValid(id ContactID) bool
- func (w *World) IsContinuousEnabled() bool
- func (w *World) IsDistanceJointLimitEnabled(jointID JointID) bool
- func (w *World) IsDistanceJointMotorEnabled(jointID JointID) bool
- func (w *World) IsDistanceJointSpringEnabled(jointID JointID) bool
- func (w *World) IsJointValid(id JointID) bool
- func (w *World) IsPrismaticJointLimitEnabled(jointID JointID) bool
- func (w *World) IsPrismaticJointMotorEnabled(jointID JointID) bool
- func (w *World) IsPrismaticJointSpringEnabled(jointID JointID) bool
- func (w *World) IsRevoluteJointLimitEnabled(jointID JointID) bool
- func (w *World) IsRevoluteJointMotorEnabled(jointID JointID) bool
- func (w *World) IsRevoluteJointSpringEnabled(jointID JointID) bool
- func (w *World) IsShapeSensor(shapeID ShapeID) bool
- func (w *World) IsShapeValid(id ShapeID) bool
- func (w *World) IsSleepingEnabled() bool
- func (w *World) IsWarmStartingEnabled() bool
- func (w *World) IsWheelJointLimitEnabled(jointID JointID) bool
- func (w *World) IsWheelJointMotorEnabled(jointID JointID) bool
- func (w *World) IsWheelJointSpringEnabled(jointID JointID) bool
- func (w *World) IsWorldValid(id WorldID) bool
- func (w *World) JointAngularSeparation(jointID JointID) float64
- func (w *World) JointBodyA(jointID JointID) BodyID
- func (w *World) JointBodyB(jointID JointID) BodyID
- func (w *World) JointCollideConnected(jointID JointID) bool
- func (w *World) JointConstraintForce(jointID JointID) Vec2
- func (w *World) JointConstraintTorque(jointID JointID) float64
- func (w *World) JointConstraintTuning(jointID JointID) (float64, float64)
- func (w *World) JointEvents() JointEvents
- func (w *World) JointForceThreshold(jointID JointID) float64
- func (w *World) JointLinearSeparation(jointID JointID) float64
- func (w *World) JointLocalFrameA(jointID JointID) Transform
- func (w *World) JointLocalFrameB(jointID JointID) Transform
- func (w *World) JointTorqueThreshold(jointID JointID) float64
- func (w *World) JointType(jointID JointID) JointType
- func (w *World) JointUserData(jointID JointID) uint64
- func (w *World) MaximumLinearSpeed() float64
- func (w *World) MotorJointAngularDampingRatio(jointID JointID) float64
- func (w *World) MotorJointAngularHertz(jointID JointID) float64
- func (w *World) MotorJointAngularVelocity(jointID JointID) float64
- func (w *World) MotorJointLinearDampingRatio(jointID JointID) float64
- func (w *World) MotorJointLinearHertz(jointID JointID) float64
- func (w *World) MotorJointLinearVelocity(jointID JointID) Vec2
- func (w *World) MotorJointMaxSpringForce(jointID JointID) float64
- func (w *World) MotorJointMaxSpringTorque(jointID JointID) float64
- func (w *World) MotorJointMaxVelocityForce(jointID JointID) float64
- func (w *World) MotorJointMaxVelocityTorque(jointID JointID) float64
- func (w *World) OverlapAABB(aabb AABB, filter QueryFilter, fcn OverlapResultFcn, context any) TreeStats
- func (w *World) OverlapShape(proxy *ShapeProxy, filter QueryFilter, fcn OverlapResultFcn, context any) TreeStats
- func (w *World) PrismaticJointLowerLimit(jointID JointID) float64
- func (w *World) PrismaticJointMaxMotorForce(jointID JointID) float64
- func (w *World) PrismaticJointMotorForce(jointID JointID) float64
- func (w *World) PrismaticJointMotorSpeed(jointID JointID) float64
- func (w *World) PrismaticJointSpeed(jointID JointID) float64
- func (w *World) PrismaticJointSpringDampingRatio(jointID JointID) float64
- func (w *World) PrismaticJointSpringHertz(jointID JointID) float64
- func (w *World) PrismaticJointTargetTranslation(jointID JointID) float64
- func (w *World) PrismaticJointTranslation(jointID JointID) float64
- func (w *World) PrismaticJointUpperLimit(jointID JointID) float64
- func (w *World) Profile() Profile
- func (w *World) RebuildStaticTree()
- func (w *World) RestitutionThreshold() float64
- func (w *World) RevoluteJointAngle(jointID JointID) float64
- func (w *World) RevoluteJointLowerLimit(jointID JointID) float64
- func (w *World) RevoluteJointMaxMotorTorque(jointID JointID) float64
- func (w *World) RevoluteJointMotorSpeed(jointID JointID) float64
- func (w *World) RevoluteJointMotorTorque(jointID JointID) float64
- func (w *World) RevoluteJointSpringDampingRatio(jointID JointID) float64
- func (w *World) RevoluteJointSpringHertz(jointID JointID) float64
- func (w *World) RevoluteJointTargetAngle(jointID JointID) float64
- func (w *World) RevoluteJointUpperLimit(jointID JointID) float64
- func (w *World) SensorEvents() SensorEvents
- func (w *World) SetBodyAngularDamping(bodyID BodyID, angularDamping float64)
- func (w *World) SetBodyAngularVelocity(bodyID BodyID, angularVelocity float64)
- func (w *World) SetBodyAwake(bodyID BodyID, awake bool)
- func (w *World) SetBodyBullet(bodyID BodyID, flag bool)
- func (w *World) SetBodyGravityScale(bodyID BodyID, gravityScale float64)
- func (w *World) SetBodyLinearDamping(bodyID BodyID, linearDamping float64)
- func (w *World) SetBodyLinearVelocity(bodyID BodyID, linearVelocity Vec2)
- func (w *World) SetBodyMassData(bodyID BodyID, massData MassData)
- func (w *World) SetBodyMotionLocks(bodyID BodyID, locks MotionLocks)
- func (w *World) SetBodyName(bodyID BodyID, name string)
- func (w *World) SetBodySleepThreshold(bodyID BodyID, sleepThreshold float64)
- func (w *World) SetBodyTargetTransform(bodyID BodyID, target Transform, timeStep float64, wake bool)
- func (w *World) SetBodyTransform(bodyID BodyID, position Vec2, rotation Rot)
- func (w *World) SetBodyType(bodyID BodyID, bodyType BodyType)
- func (w *World) SetBodyUserData(bodyID BodyID, userData uint64)
- func (w *World) SetChainSurfaceMaterial(chainID ChainID, material SurfaceMaterial, materialIndex int)
- func (w *World) SetContactRecycleDistance(recycleDistance float64)
- func (w *World) SetContactTuning(hertz, dampingRatio, pushSpeed float64)
- func (w *World) SetCustomFilterCallback(fcn CustomFilterFcn, ctx any)
- func (w *World) SetDistanceJointLength(jointID JointID, length float64)
- func (w *World) SetDistanceJointLengthRange(jointID JointID, minLength, maxLength float64)
- func (w *World) SetDistanceJointMaxMotorForce(jointID JointID, force float64)
- func (w *World) SetDistanceJointMotorSpeed(jointID JointID, motorSpeed float64)
- func (w *World) SetDistanceJointSpringDampingRatio(jointID JointID, dampingRatio float64)
- func (w *World) SetDistanceJointSpringForceRange(jointID JointID, lowerForce, upperForce float64)
- func (w *World) SetDistanceJointSpringHertz(jointID JointID, hertz float64)
- func (w *World) SetFrictionCallback(callback FrictionCallback)
- func (w *World) SetGravity(gravity Vec2)
- func (w *World) SetHitEventThreshold(value float64)
- func (w *World) SetJointCollideConnected(jointID JointID, shouldCollide bool)
- func (w *World) SetJointConstraintTuning(jointID JointID, hertz, dampingRatio float64)
- func (w *World) SetJointForceThreshold(jointID JointID, threshold float64)
- func (w *World) SetJointLocalFrameA(jointID JointID, localFrame Transform)
- func (w *World) SetJointLocalFrameB(jointID JointID, localFrame Transform)
- func (w *World) SetJointTorqueThreshold(jointID JointID, threshold float64)
- func (w *World) SetJointUserData(jointID JointID, userData uint64)
- func (w *World) SetMaximumLinearSpeed(maximumLinearSpeed float64)
- func (w *World) SetMotorJointAngularDampingRatio(jointID JointID, damping float64)
- func (w *World) SetMotorJointAngularHertz(jointID JointID, hertz float64)
- func (w *World) SetMotorJointAngularVelocity(jointID JointID, velocity float64)
- func (w *World) SetMotorJointLinearDampingRatio(jointID JointID, damping float64)
- func (w *World) SetMotorJointLinearHertz(jointID JointID, hertz float64)
- func (w *World) SetMotorJointLinearVelocity(jointID JointID, velocity Vec2)
- func (w *World) SetMotorJointMaxSpringForce(jointID JointID, maxForce float64)
- func (w *World) SetMotorJointMaxSpringTorque(jointID JointID, maxTorque float64)
- func (w *World) SetMotorJointMaxVelocityForce(jointID JointID, maxForce float64)
- func (w *World) SetMotorJointMaxVelocityTorque(jointID JointID, maxTorque float64)
- func (w *World) SetPreSolveCallback(fcn PreSolveFcn, ctx any)
- func (w *World) SetPrismaticJointLimits(jointID JointID, lower, upper float64)
- func (w *World) SetPrismaticJointMaxMotorForce(jointID JointID, force float64)
- func (w *World) SetPrismaticJointMotorSpeed(jointID JointID, motorSpeed float64)
- func (w *World) SetPrismaticJointSpringDampingRatio(jointID JointID, dampingRatio float64)
- func (w *World) SetPrismaticJointSpringHertz(jointID JointID, hertz float64)
- func (w *World) SetPrismaticJointTargetTranslation(jointID JointID, translation float64)
- func (w *World) SetRestitutionCallback(callback RestitutionCallback)
- func (w *World) SetRestitutionThreshold(value float64)
- func (w *World) SetRevoluteJointLimits(jointID JointID, lower, upper float64)
- func (w *World) SetRevoluteJointMaxMotorTorque(jointID JointID, torque float64)
- func (w *World) SetRevoluteJointMotorSpeed(jointID JointID, motorSpeed float64)
- func (w *World) SetRevoluteJointSpringDampingRatio(jointID JointID, dampingRatio float64)
- func (w *World) SetRevoluteJointSpringHertz(jointID JointID, hertz float64)
- func (w *World) SetRevoluteJointTargetAngle(jointID JointID, angle float64)
- func (w *World) SetShapeCapsule(shapeID ShapeID, capsule *Capsule)
- func (w *World) SetShapeCircle(shapeID ShapeID, circle *Circle)
- func (w *World) SetShapeDensity(shapeID ShapeID, density float64, updateBodyMass bool)
- func (w *World) SetShapeFilter(shapeID ShapeID, filter Filter)
- func (w *World) SetShapeFriction(shapeID ShapeID, friction float64)
- func (w *World) SetShapePolygon(shapeID ShapeID, polygon *Polygon)
- func (w *World) SetShapeRestitution(shapeID ShapeID, restitution float64)
- func (w *World) SetShapeSegment(shapeID ShapeID, segment *Segment)
- func (w *World) SetShapeSurfaceMaterial(shapeID ShapeID, surfaceMaterial SurfaceMaterial)
- func (w *World) SetShapeUserData(shapeID ShapeID, userData uint64)
- func (w *World) SetShapeUserMaterial(shapeID ShapeID, material uint64)
- func (w *World) SetUserData(userData uint64)
- func (w *World) SetWeldJointAngularDampingRatio(jointID JointID, dampingRatio float64)
- func (w *World) SetWeldJointAngularHertz(jointID JointID, hertz float64)
- func (w *World) SetWeldJointLinearDampingRatio(jointID JointID, dampingRatio float64)
- func (w *World) SetWeldJointLinearHertz(jointID JointID, hertz float64)
- func (w *World) SetWheelJointLimits(jointID JointID, lower, upper float64)
- func (w *World) SetWheelJointMaxMotorTorque(jointID JointID, torque float64)
- func (w *World) SetWheelJointMotorSpeed(jointID JointID, motorSpeed float64)
- func (w *World) SetWheelJointSpringDampingRatio(jointID JointID, dampingRatio float64)
- func (w *World) SetWheelJointSpringHertz(jointID JointID, hertz float64)
- func (w *World) ShapeAABB(shapeID ShapeID) AABB
- func (w *World) ShapeBody(shapeID ShapeID) BodyID
- func (w *World) ShapeCapsule(shapeID ShapeID) Capsule
- func (w *World) ShapeChainSegment(shapeID ShapeID) ChainSegment
- func (w *World) ShapeCircle(shapeID ShapeID) Circle
- func (w *World) ShapeClosestPoint(shapeID ShapeID, target Vec2) Vec2
- func (w *World) ShapeComputeMassData(shapeID ShapeID) MassData
- func (w *World) ShapeContactCapacity(shapeID ShapeID) int
- func (w *World) ShapeContactData(shapeID ShapeID, contactData []ContactData) int
- func (w *World) ShapeDensity(shapeID ShapeID) float64
- func (w *World) ShapeFilter(shapeID ShapeID) Filter
- func (w *World) ShapeFriction(shapeID ShapeID) float64
- func (w *World) ShapeParentChain(shapeID ShapeID) ChainID
- func (w *World) ShapePolygon(shapeID ShapeID) Polygon
- func (w *World) ShapeRayCast(shapeID ShapeID, input *RayCastInput) CastOutput
- func (w *World) ShapeRestitution(shapeID ShapeID) float64
- func (w *World) ShapeSegment(shapeID ShapeID) Segment
- func (w *World) ShapeSensorCapacity(shapeID ShapeID) int
- func (w *World) ShapeSensorData(shapeID ShapeID, visitorIDs []ShapeID) int
- func (w *World) ShapeSurfaceMaterial(shapeID ShapeID) SurfaceMaterial
- func (w *World) ShapeTestPoint(shapeID ShapeID, point Vec2) bool
- func (w *World) ShapeType(shapeID ShapeID) ShapeType
- func (w *World) ShapeUserData(shapeID ShapeID) uint64
- func (w *World) ShapeUserMaterial(shapeID ShapeID) uint64
- func (w *World) Step(timeStep float64, subStepCount int)
- func (w *World) UserData() uint64
- func (w *World) WakeBodyTouching(bodyID BodyID)
- func (w *World) WakeJointBodies(jointID JointID)
- func (w *World) WeldJointAngularDampingRatio(jointID JointID) float64
- func (w *World) WeldJointAngularHertz(jointID JointID) float64
- func (w *World) WeldJointLinearDampingRatio(jointID JointID) float64
- func (w *World) WeldJointLinearHertz(jointID JointID) float64
- func (w *World) WheelJointLowerLimit(jointID JointID) float64
- func (w *World) WheelJointMaxMotorTorque(jointID JointID) float64
- func (w *World) WheelJointMotorSpeed(jointID JointID) float64
- func (w *World) WheelJointMotorTorque(jointID JointID) float64
- func (w *World) WheelJointSpringDampingRatio(jointID JointID) float64
- func (w *World) WheelJointSpringHertz(jointID JointID) float64
- func (w *World) WheelJointUpperLimit(jointID JointID) float64
- type WorldDef
- type WorldID
Constants ¶
const AABBMarginFraction = 0.125
AABBMarginFraction is B2_AABB_MARGIN_FRACTION. A dimensionless fraction of a shape extent, so it does not scale with the length unit.
const Alignment = 32
Alignment is B2_ALIGNMENT.
const DefaultCategoryBits uint64 = 1
DefaultCategoryBits is B2_DEFAULT_CATEGORY_BITS.
const DefaultMaskBits uint64 = math.MaxUint64
DefaultMaskBits is B2_DEFAULT_MASK_BITS (UINT64_MAX).
const GraphColorCount = 24
GraphColorCount is B2_GRAPH_COLOR_COUNT.
const HashInit = 5381
HashInit is the starting value for the djb2 hash (upstream B2_HASH_INIT).
const MaxPolygonVertices = 8
MaxPolygonVertices is the maximum number of vertices on a convex polygon (upstream B2_MAX_POLYGON_VERTICES). Changing this affects performance even if you don't use more vertices.
const MaxRotation = 0.25 * Pi
MaxRotation is B2_MAX_ROTATION (0.25f * B2_PI). An angle, so it does not scale with the length unit.
const MaxWorkers = 64
MaxWorkers is B2_MAX_WORKERS.
const MaxWorlds = 128
MaxWorlds is B2_MAX_WORLDS.
const NullIndex = -1
NullIndex is B2_NULL_INDEX.
const Pi = 3.14159265359
Pi matches the upstream B2_PI decimal literal (not math.Pi) so ported expressions stay diffable against the C source.
DELIBERATE DEVIATION: upstream writes `3.14159265359f`, a float32 literal that actually evaluates to 3.14159274101257324; this float64 constant keeps the decimal value, which is closer to real pi. Angle wrapping therefore differs from the C by ~1.75e-7 per full turn (see the oracle_foundation UnwindAngle divergence tests). Do not "fix" this to the float32 value without regenerating every golden fixture.
const SecretCookie = 1152023
SecretCookie is B2_SECRET_COOKIE.
const TimeToSleep = 0.5
TimeToSleep is B2_TIME_TO_SLEEP. Seconds, so it does not scale with the length unit.
Variables ¶
var ( // LinearSlop is B2_LINEAR_SLOP (0.005f * b2GetLengthUnitsPerMeter()). LinearSlop = linearSlopPerMeter * lengthUnitsPerMeter // Huge is B2_HUGE (100000.0f * b2GetLengthUnitsPerMeter()). Huge = hugePerMeter * lengthUnitsPerMeter // SpeculativeDistance is B2_SPECULATIVE_DISTANCE (4.0f * B2_LINEAR_SLOP). SpeculativeDistance = speculativeDistancePerMeter * lengthUnitsPerMeter // ContactRecycleDistance is B2_CONTACT_RECYCLE_DISTANCE (10.0f * B2_LINEAR_SLOP). ContactRecycleDistance = contactRecycleDistancePerMeter * lengthUnitsPerMeter // MaxAABBMargin is B2_MAX_AABB_MARGIN (0.05f * b2GetLengthUnitsPerMeter()). MaxAABBMargin = maxAABBMarginPerMeter * lengthUnitsPerMeter )
The length-scaled tolerances. Upstream declares each of these as a macro that calls b2GetLengthUnitsPerMeter() at every use, for example
#define B2_LINEAR_SLOP ( 0.005f * b2GetLengthUnitsPerMeter() )
so they follow b2SetLengthUnitsPerMeter. Go has no macros, so this port mirrors upstream's mutable global with package-level variables that SetLengthUnitsPerMeter recomputes. They are deliberately variables, not constants: freezing them would silently diverge from upstream collision, CCD and broad-phase behaviour for any caller that picks a non-meter length unit.
Each variable is its per-meter constant multiplied by the current length unit. At the default unit of 1.0 that product is exact (IEEE-754 guarantees x*1.0 == x for finite x), so every default is bit-identical to the untyped constant it replaced and the golden traces are unaffected.
Warning
This state is process-global, exactly as upstream's is. Set the length unit once during start-up, BEFORE creating any World — upstream documents the same contract ("This must be modified before any calls to Box2D"). Changing it while a simulation is live invalidates every length already stored in world state (AABBs, contact separations, joint frames) and voids the determinism guarantee of this package, because the same input sequence then produces different results depending on when the change occurred. With WorldDef.WorkerCount > 1 it is also a genuine data race, not just a semantic hazard: Step's pool workers (worker_pool.go) read these variables concurrently.
Treat these as read-only outside SetLengthUnitsPerMeter.
var ( Vec2Zero = Vec2{} RotIdentity = Rot{C: 1.0} TransformIdentity = Transform{Q: Rot{C: 1.0}} Mat22Zero = Mat22{} )
Identity and zero values (upstream b2Vec2_zero, b2Rot_identity, ...). Treat as read-only.
Functions ¶
func AABBContains ¶
AABBContains reports whether a fully contains b.
func Atan2 ¶
Atan2 computes an approximate arctangent in the range [-pi, pi]. This is hand coded for cross-platform determinism (the standard library atan2 is not guaranteed bit-identical across platforms). Accurate to around 0.0023 degrees.
The polynomial constants and the pi/2, pi literals are kept exactly as upstream wrote them (float32 roundings) for behavioral parity. https://stackoverflow.com/questions/46210708
func ComputeAngularVelocity ¶
ComputeAngularVelocity computes the angular velocity necessary to rotate between two rotations over a given time (invH is the inverse time step).
func DistanceSquared ¶
DistanceSquared returns the squared distance between two points.
func GetLengthUnitsPerMeter ¶
func GetLengthUnitsPerMeter() float64
GetLengthUnitsPerMeter returns the current length units per meter (upstream b2GetLengthUnitsPerMeter).
func IsNormalized ¶
IsNormalized reports whether norm(a) == 1 within tolerance.
func IsNormalizedRot ¶
IsNormalizedRot reports whether the rotation is normalized.
func IsValidAABB ¶
IsValidAABB reports whether the AABB is well formed and free of NaN/inf (upstream b2IsValidAABB).
func IsValidFloat ¶
IsValidFloat reports whether a is a valid number (not NaN or infinity).
func IsValidPlane ¶
IsValidPlane reports whether the plane has a valid unit normal and offset.
func IsValidRay ¶
func IsValidRay(input *RayCastInput) bool
IsValidRay validates ray cast input data (NaN, etc.) (upstream b2IsValidRay).
func IsValidRotation ¶
IsValidRotation reports whether q is a valid, normalized rotation.
func IsValidTransform ¶
IsValidTransform reports whether t is a valid transform with a normalized rotation.
func IsValidVec2 ¶
IsValidVec2 reports whether v is a valid vector (not NaN or infinity).
func LengthSquared ¶
LengthSquared returns the squared length of the vector.
func PackBodyID ¶
PackBodyID stores a body id into a uint64 (upstream b2StoreBodyId).
func PackChainID ¶
PackChainID stores a chain id into a uint64 (upstream b2StoreChainId).
func PackContactID ¶
PackContactID stores a contact id into three uint32s (upstream b2StoreContactId).
Slot 0 is the contact's 1-based dense per-world index (index1: the contact pool index plus one, with 0 reserved for null) — a documented part of the format, not an accident of layout: callers may use it as a compact table key for live contacts (physics2d's contact gather does). TestOracleContactID_CReference pins the layout.
func PackJointID ¶
PackJointID stores a joint id into a uint64 (upstream b2StoreJointId).
func PackShapeID ¶
PackShapeID stores a shape id into a uint64 (upstream b2StoreShapeId).
func PackWorldID ¶
PackWorldID stores a world id into a uint32 (upstream b2StoreWorldId).
func PlaneSeparation ¶
PlaneSeparation returns the signed separation of a point from a plane.
func PointInCapsule ¶
PointInCapsule tests a point for overlap with a capsule in local space (upstream b2PointInCapsule).
func PointInCircle ¶
PointInCircle tests a point for overlap with a circle in local space (upstream b2PointInCircle).
func PointInPolygon ¶
PointInPolygon tests a point for overlap with a convex polygon in local space (upstream b2PointInPolygon).
func RelativeAngle ¶
RelativeAngle returns the relative angle between a and b.
func RotGetAngle ¶
RotGetAngle returns the angle in radians in the range [-pi, pi].
func SetLengthUnitsPerMeter ¶
func SetLengthUnitsPerMeter(lengthUnits float64)
SetLengthUnitsPerMeter allows the user to change the length units at runtime (upstream b2SetLengthUnitsPerMeter).
It also recomputes the length-scaled tolerances declared in constants.go (LinearSlop, Huge, SpeculativeDistance, ContactRecycleDistance and MaxAABBMargin). Upstream defines those as macros that re-read the length unit at every use, so they must follow this setter; a Go port that froze them would give a caller with a non-meter length unit silently upstream-divergent collision, continuous-collision and broad-phase behaviour.
Warning ¶
The length unit and everything derived from it are process-global, as they are upstream. Call this once during start-up, BEFORE creating any World — upstream states the same contract, "This must be modified before any calls to Box2D". Calling it while a simulation is live invalidates in-flight state, because lengths already stored in a world (AABBs, contact separations, joint frames) were computed against the previous unit, and it voids this package's determinism guarantee: replaying the same inputs no longer reproduces the same results unless the change happens at the same point in the sequence. It is also not safe to call concurrently with any other use of the package.
func SpringDamper ¶
SpringDamper is a one-dimensional mass-spring-damper simulation. It returns the new velocity given the position and time step. The new position is then position += timeStep * newVelocity. This drives towards a zero position with a stable implicit solution that needs no transcendental functions.
func UnwindAngle ¶
UnwindAngle converts any angle into the range [-pi, pi].
func ValidateHull ¶
ValidateHull determines whether a hull is valid (upstream b2ValidateHull). It checks for:
- convexity
- collinear points
This is expensive and should not be called at runtime.
Types ¶
type AABB ¶
type AABB struct {
LowerBound, UpperBound Vec2
}
AABB is an axis-aligned bounding box.
func ComputeCapsuleAABB ¶
ComputeCapsuleAABB computes the bounding box of a transformed capsule (upstream b2ComputeCapsuleAABB).
func ComputeCircleAABB ¶
ComputeCircleAABB computes the bounding box of a transformed circle (upstream b2ComputeCircleAABB).
func ComputePolygonAABB ¶
ComputePolygonAABB computes the bounding box of a transformed polygon (upstream b2ComputePolygonAABB).
func ComputeSegmentAABB ¶
ComputeSegmentAABB computes the bounding box of a transformed line segment (upstream b2ComputeSegmentAABB).
type BodyDef ¶
type BodyDef struct {
// The body type: static, kinematic, or dynamic.
Type BodyType
// The initial world position of the body. Bodies should be created with the desired position.
//
// Note: creating bodies at the origin and then moving them nearly doubles the cost of body creation, especially
// if the body is moved after shapes have been added.
Position Vec2
// The initial world rotation of the body. Use MakeRot if you have an angle.
Rotation Rot
// The initial linear velocity of the body's origin. Usually in meters per second.
LinearVelocity Vec2
// The initial angular velocity of the body. Radians per second.
AngularVelocity float64
// Linear damping is used to reduce the linear velocity. The damping parameter
// can be larger than 1 but the damping effect becomes sensitive to the
// time step when the damping parameter is large.
// Generally linear damping is undesirable because it makes objects move slowly
// as if they are floating.
LinearDamping float64
// Angular damping is used to reduce the angular velocity. The damping parameter
// can be larger than 1.0 but the damping effect becomes sensitive to the
// time step when the damping parameter is large.
// Angular damping can be use slow down rotating bodies.
AngularDamping float64
// Scale the gravity applied to this body. Non-dimensional.
GravityScale float64
// Sleep speed threshold, default is 0.05 meters per second
SleepThreshold float64
// Optional body name for debugging. Up to 31 characters.
Name string
// Use this to store application specific body data. Deviation from
// upstream: the C void* becomes a uint64 so the ECS wrapper can pack an
// entity id directly.
UserData uint64
// Motions locks to restrict linear and angular movement.
// Caution: may lead to softer constraints along the locked direction
MotionLocks MotionLocks
// Set this flag to false if this body should never fall asleep.
EnableSleep bool
// Is this body initially awake or sleeping?
IsAwake bool
// Treat this body as a high speed object that performs continuous collision detection
// against dynamic and kinematic bodies, but not other bullet bodies.
//
// Warning: bullets should be used sparingly. They are not a solution for general dynamic-versus-dynamic
// continuous collision. They do not guarantee accurate collision if both bodies are fast moving because
// the bullet does a continuous check after all non-bullet bodies have moved. You could get unlucky and have
// the bullet body end a time step very close to a non-bullet body and the non-bullet body then moves over
// the bullet body. In continuous collision, initial overlap is ignored to avoid freezing bodies in place.
// I do not recommend using them for game projectiles if precise collision timing is needed. Instead consider
// using a ray or shape cast. You can use a marching ray or shape cast for projectile that moves over time.
// If you want a fast moving projectile to collide with a fast moving target, you need to consider the relative
// movement in your ray or shape cast. This is out of the scope of Box2D.
// So what are good use cases for bullets? Pinball games or games with dynamic containers that hold other objects.
// It should be a use case where it doesn't break the game if there is a collision missed, but the having them
// captured improves the quality of the game.
IsBullet bool
// Used to disable a body. A disabled body does not move or collide.
IsEnabled bool
// This allows this body to bypass rotational speed limits. Should only be used
// for circular objects, like wheels.
AllowFastRotation bool
// contains filtered or unexported fields
}
BodyDef holds all the data needed to construct a rigid body (upstream b2BodyDef). You can safely re-use body definitions. Shapes are added to a body after construction. Body definitions are temporary objects used to bundle creation parameters. Must be initialized using DefaultBodyDef.
func DefaultBodyDef ¶
func DefaultBodyDef() BodyDef
DefaultBodyDef initializes a body definition (upstream b2DefaultBodyDef).
type BodyEvents ¶
type BodyEvents struct {
// Move events
MoveEvents []BodyMoveEvent
}
BodyEvents are buffered in the world and are available as event slices after the time step is complete (upstream b2BodyEvents). Note: this data becomes invalid if bodies are destroyed.
Deviation from upstream: the pointer+count pair becomes a slice.
type BodyID ¶
type BodyID struct {
// contains filtered or unexported fields
}
BodyID references a body instance (upstream b2BodyId).
func UnpackBodyID ¶
UnpackBodyID loads a uint64 into a body id (upstream b2LoadBodyId).
type BodyMoveEvent ¶
type BodyMoveEvent struct {
// User data. Deviation from upstream: the C void* becomes a uint64 so the
// ECS wrapper can pack an entity id directly.
UserData uint64
Transform Transform
BodyID BodyID
FellAsleep bool
}
BodyMoveEvent is triggered when a body moves due to simulation (upstream b2BodyMoveEvent). Not reported for bodies moved by the user. This also has a flag to indicate that the body went to sleep so the application can also sleep that actor/entity/object associated with the body. On the other hand if the flag does not indicate the body went to sleep then the application can treat the actor/entity/object associated with the body as awake. This is an efficient way for an application to update game object transforms rather than calling functions such as Body.GetTransform because this data is delivered as a contiguous slice and it is only populated with bodies that have moved.
Note: if sleeping is disabled all dynamic and kinematic bodies will trigger move events.
type BodyType ¶
type BodyType int32
BodyType is the body simulation type (upstream b2BodyType). Each body is one of these three types. The type determines how the body behaves in the simulation.
const ( // StaticBody has zero mass, zero velocity, and may be manually moved. StaticBody BodyType = 0 // KinematicBody has zero mass, velocity set by user, and is moved by the solver. KinematicBody BodyType = 1 // DynamicBody has positive mass, velocity determined by forces, and is moved by the solver. DynamicBody BodyType = 2 // BodyTypeCount is the number of body types. BodyTypeCount BodyType = 3 )
type Capsule ¶
type Capsule struct {
// Center1 is the local center of the first semicircle.
Center1 Vec2
// Center2 is the local center of the second semicircle.
Center2 Vec2
// Radius is the radius of the semicircles.
Radius float64
}
Capsule is a solid capsule. It can be viewed as two semicircles connected by a rectangle.
type CastOutput ¶
type CastOutput struct {
// Normal is the surface normal at the hit point.
Normal Vec2
// Point is the surface hit point.
Point Vec2
// Fraction is the fraction of the input translation at collision.
Fraction float64
// Iterations is the number of iterations used.
Iterations int
// Hit reports whether the cast hit.
Hit bool
}
CastOutput is low level ray cast or shape-cast output data. It returns a zero fraction and normal in the case of initial overlap.
func AABBRayCast ¶
func AABBRayCast(a AABB, p1, p2 Vec2) CastOutput
AABBRayCast casts a ray against an AABB (upstream b2AABB_RayCast).
From Real-time Collision Detection, p179.
func RayCastCapsule ¶
func RayCastCapsule(shape *Capsule, input *RayCastInput) CastOutput
RayCastCapsule casts a ray against a capsule shape in local space (upstream b2RayCastCapsule).
func RayCastCircle ¶
func RayCastCircle(shape *Circle, input *RayCastInput) CastOutput
RayCastCircle casts a ray against a circle shape in local space (upstream b2RayCastCircle).
Precision Improvements for Ray / Sphere Intersection - Ray Tracing Gems 2019 http://www.codercorner.com/blog/?p=321
func RayCastPolygon ¶
func RayCastPolygon(shape *Polygon, input *RayCastInput) CastOutput
RayCastPolygon casts a ray against a polygon shape in local space (upstream b2RayCastPolygon).
func RayCastSegment ¶
func RayCastSegment(shape *Segment, input *RayCastInput, oneSided bool) CastOutput
RayCastSegment casts a ray against a segment shape in local space (upstream b2RayCastSegment). Optionally treat the segment as one-sided with hits from the left side being treated as a miss.
func ShapeCast ¶
func ShapeCast(input *ShapeCastPairInput) CastOutput
ShapeCast performs a linear shape cast of shape B moving and shape A fixed using conservative advancement (upstream b2ShapeCast). It determines the hit point, normal, and translation fraction. Initially touching shapes are treated as a miss.
func ShapeCastCapsule ¶
func ShapeCastCapsule(shape *Capsule, input *ShapeCastInput) CastOutput
ShapeCastCapsule performs a shape cast against a capsule in local space (upstream b2ShapeCastCapsule).
func ShapeCastCircle ¶
func ShapeCastCircle(shape *Circle, input *ShapeCastInput) CastOutput
ShapeCastCircle performs a shape cast against a circle in local space (upstream b2ShapeCastCircle).
func ShapeCastPolygon ¶
func ShapeCastPolygon(shape *Polygon, input *ShapeCastInput) CastOutput
ShapeCastPolygon performs a shape cast against a convex polygon in local space (upstream b2ShapeCastPolygon).
func ShapeCastSegment ¶
func ShapeCastSegment(shape *Segment, input *ShapeCastInput) CastOutput
ShapeCastSegment performs a shape cast against a segment in local space (upstream b2ShapeCastSegment).
type CastResultFcn ¶
CastResultFcn is the prototype callback for ray and shape casts (upstream b2CastResultFcn). Called for each shape found in the query. You control how the ray cast proceeds by returning a float:
return -1: ignore this shape and continue return 0: terminate the ray cast return fraction: clip the ray to this point return 1: don't clip the ray and continue
A cast with initial overlap will return a zero fraction and a zero normal. See World.CastRay.
shapeID is the shape hit by the ray, point the point of initial intersection, normal the normal vector at the point of intersection (zero for a shape cast with initial overlap), fraction the fraction along the ray at the point of intersection (zero for a shape cast with initial overlap), and ctx the user context.
type ChainDef ¶
type ChainDef struct {
// Use this to store application specific shape data. Deviation from
// upstream: the C void* becomes a uint64 so the ECS wrapper can pack an
// entity id directly.
UserData uint64
// At least 4 points. These are cloned and may be temporary.
Points []Vec2
// Surface materials for each segment. These are cloned.
// The length must be 1 or len(Points). This allows you to provide one
// material for all segments or a unique material per segment. For open
// chains, the material on the ghost segments are place holders.
Materials []SurfaceMaterial
// Contact filtering data.
Filter Filter
// Indicates a closed chain formed by connecting the first and last points
IsLoop bool
// Enable sensors to detect this chain. False by default.
EnableSensorEvents bool
// contains filtered or unexported fields
}
ChainDef is used to create a chain of line segments (upstream b2ChainDef). This is designed to eliminate ghost collisions with some limitations.
- chains are one-sided
- chains have no mass and should be used on static bodies
- chains have a counter-clockwise winding order (normal points right of segment direction)
- chains are either a loop or open
- a chain must have at least 4 points
- the distance between any two points must be greater than LinearSlop
- a chain shape should not self intersect (this is not validated)
- an open chain shape has NO COLLISION on the first and final edge
- you may overlap two open chains on their first three and/or last three points to get smooth collision
- a chain shape creates multiple line segment shapes on the body
https://en.wikipedia.org/wiki/Polygonal_chain Must be initialized using DefaultChainDef.
Warning: do not use chain shapes unless you understand the limitations. This is an advanced feature.
Deviation from upstream: the pointer+count pairs (points/count and materials/materialCount) become slices; use len to recover the counts.
func DefaultChainDef ¶
func DefaultChainDef() ChainDef
DefaultChainDef initializes a chain definition (upstream b2DefaultChainDef).
Deviation from upstream: upstream points materials at a shared static default material; this allocates a fresh one-element slice per call so the caller cannot mutate a package-level value.
type ChainID ¶
type ChainID struct {
// contains filtered or unexported fields
}
ChainID references a chain instance (upstream b2ChainId).
func UnpackChainID ¶
UnpackChainID loads a uint64 into a chain id (upstream b2LoadChainId).
type ChainSegment ¶
type ChainSegment struct {
// Ghost1 is the tail ghost vertex.
Ghost1 Vec2
// Segment is the line segment.
Segment Segment
// Ghost2 is the head ghost vertex.
Ghost2 Vec2
// ChainID is the owning chain shape index (internal usage only).
ChainID int
}
ChainSegment is a line segment with one-sided collision. It only collides on the right side. Several of these are generated for a chain shape.
ghost1 -> point1 -> point2 -> ghost2
type Circle ¶
type Circle struct {
// Center is the local center.
Center Vec2
// Radius is the radius.
Radius float64
}
Circle is a solid circle.
type CollisionPlane ¶
type CollisionPlane struct {
// Plane is the collision plane between the mover and some shape.
Plane Plane
// PushLimit caps the push applied by this plane. Setting it to a huge
// value makes the plane as rigid as possible; lower values make the
// collision soft. Usually in meters.
PushLimit float64
// Push is the push on the mover determined by SolvePlanes. Usually in
// meters.
Push float64
// ClipVelocity indicates whether ClipVector should clip against this
// plane. Should be false for soft collision.
ClipVelocity bool
}
CollisionPlane is a collision plane that can be fed to SolvePlanes. Normally this is assembled by the user from plane results produced by CollideMover (upstream b2CollisionPlane).
type ContactBeginTouchEvent ¶
type ContactBeginTouchEvent struct {
// Id of the first shape
ShapeIDA ShapeID
// Id of the second shape
ShapeIDB ShapeID
// The transient contact id. This id is valid until the world is modified
// or simulated (upstream b2ContactId contactId).
ContactID ContactID
}
ContactBeginTouchEvent is generated when two shapes begin touching (upstream b2ContactBeginTouchEvent).
type ContactData ¶
type ContactData struct {
// Id of the contact (upstream b2ContactId contactId).
ContactID ContactID
ShapeIDA ShapeID
ShapeIDB ShapeID
// The manifold of the contact. By convention the normal points from
// shape A to shape B (upstream b2Manifold manifold).
Manifold Manifold
}
ContactData is the contact data for two shapes (upstream b2ContactData). By convention the manifold normal points from shape A to shape B. See Shape.GetContactData and Body.GetContactData.
type ContactDrawType ¶
type ContactDrawType int32
ContactDrawType is the type of contact point drawing (upstream b2ContactDrawType).
const ( DrawContactsNone ContactDrawType = 0 DrawContactsClip ContactDrawType = 1 DrawContactsAnchorA ContactDrawType = 2 DrawContactsAnchorB ContactDrawType = 3 DrawContactsAverage ContactDrawType = 4 )
type ContactEndTouchEvent ¶
type ContactEndTouchEvent struct {
// Id of the first shape.
// Warning: this shape may have been destroyed. See Shape.IsValid.
ShapeIDA ShapeID
// Id of the second shape.
// Warning: this shape may have been destroyed. See Shape.IsValid.
ShapeIDB ShapeID
// Id of the contact (upstream b2ContactId contactId).
ContactID ContactID
}
ContactEndTouchEvent is generated when two shapes stop touching (upstream b2ContactEndTouchEvent). You will get an end event if you do anything that destroys contacts previous to the last world step. These include things like setting the transform, destroying a body or shape, or changing a filter or body type.
type ContactEvents ¶
type ContactEvents struct {
// Begin touch events
BeginEvents []ContactBeginTouchEvent
// End touch events
EndEvents []ContactEndTouchEvent
// Hit events
HitEvents []ContactHitEvent
}
ContactEvents are buffered in the world and are available as event slices after the time step is complete (upstream b2ContactEvents). Note: these may become invalid if bodies and/or shapes are destroyed.
Deviation from upstream: the pointer+count pairs become slices.
type ContactHitEvent ¶
type ContactHitEvent struct {
// Id of the first shape
ShapeIDA ShapeID
// Id of the second shape
ShapeIDB ShapeID
// Id of the contact (upstream b2ContactId contactId).
ContactID ContactID
// Point where the shapes hit at the beginning of the time step.
// This is a mid-point between the two surfaces. It could be at speculative
// point where the two shapes were not touching at the beginning of the time step.
Point Vec2
// Normal vector pointing from shape A to shape B
Normal Vec2
// The speed the shapes are approaching. Always positive. Typically in meters per second.
ApproachSpeed float64
}
ContactHitEvent is generated when two shapes collide with a speed faster than the hit speed threshold (upstream b2ContactHitEvent). This may be reported for speculative contacts that have a confirmed impulse.
type ContactID ¶
type ContactID struct {
// contains filtered or unexported fields
}
ContactID references a contact instance (upstream b2ContactId).
func UnpackContactID ¶
UnpackContactID loads three uint32s into a contact id (upstream b2LoadContactId).
type CosSin ¶
type CosSin struct {
Cosine, Sine float64
}
CosSin is a cosine and sine pair produced by ComputeCosSin.
func ComputeCosSin ¶
ComputeCosSin computes the cosine and sine of an angle in radians using Bhāskara I's approximation, implemented for cross-platform determinism. https://en.wikipedia.org/wiki/Bh%C4%81skara_I%27s_sine_approximation_formula
type Counters ¶
type Counters struct {
BodyCount int
ShapeCount int
ContactCount int
JointCount int
IslandCount int
StackUsed int
StaticTreeHeight int
TreeHeight int
ByteCount int
TaskCount int
ColorCounts [GraphColorCount]int
}
Counters give details of the simulation size (upstream b2Counters).
type CustomFilterFcn ¶
CustomFilterFcn is the prototype for a contact filter callback (upstream b2CustomFilterFcn). This is called when a contact pair is considered for collision. This allows you to perform custom logic to prevent collision between shapes. This is only called if one of the two shapes has custom filtering enabled. Notes:
- this is only called if one of the two shapes has enabled custom filtering
- this may be called for awake dynamic bodies and sensors
Return false if you want to disable the collision. See ShapeDef.
Warning: do not attempt to modify the world inside this callback.
type DebugDraw ¶
type DebugDraw struct {
// DrawPolygonFcn draws a closed polygon provided in CCW order.
DrawPolygonFcn func(vertices []Vec2, color HexColor, ctx any)
// DrawSolidPolygonFcn draws a solid closed polygon provided in CCW order.
DrawSolidPolygonFcn func(transform Transform, vertices []Vec2, radius float64, color HexColor, ctx any)
// DrawCircleFcn draws a circle.
DrawCircleFcn func(center Vec2, radius float64, color HexColor, ctx any)
// DrawSolidCircleFcn draws a solid circle.
DrawSolidCircleFcn func(transform Transform, radius float64, color HexColor, ctx any)
// DrawSolidCapsuleFcn draws a solid capsule.
DrawSolidCapsuleFcn func(p1, p2 Vec2, radius float64, color HexColor, ctx any)
// DrawLineFcn draws a line segment.
DrawLineFcn func(p1, p2 Vec2, color HexColor, ctx any)
// DrawTransformFcn draws a transform. Choose your own length scale.
DrawTransformFcn func(transform Transform, ctx any)
// DrawPointFcn draws a point.
DrawPointFcn func(p Vec2, size float64, color HexColor, ctx any)
// DrawStringFcn draws a string in world space.
DrawStringFcn func(p Vec2, s string, color HexColor, ctx any)
// World bounds to use for debug draw
DrawingBounds AABB
// Scale to use when drawing forces
ForceScale float64
// Global scaling for joint drawing
JointScale float64
// Option to draw contact points
ContactDrawType ContactDrawType
// Option to draw shapes
DrawShapes bool
// Option to draw joints
DrawJoints bool
// Option to draw additional information for joints
DrawJointExtras bool
// Option to draw the bounding boxes for shapes
DrawBounds bool
// Option to draw the mass and center of mass of dynamic bodies
DrawMass bool
// Option to draw body names
DrawBodyNames bool
// Option to visualize the graph coloring used for contacts and joints
DrawGraphColors bool
// Option to draw contact feature ids
DrawContactFeatures bool
// Option to draw contact normals
DrawContactNormals bool
// Option to draw contact normal forces
DrawContactForces bool
// Option to draw contact friction forces
DrawFrictionForces bool
// Option to draw islands as bounding boxes
DrawIslands bool
// User context that is passed as an argument to drawing callback functions
Context any
}
DebugDraw holds callbacks you can implement to draw a Box2D world (upstream b2DebugDraw). This structure should be zero initialized.
Deviation from upstream: the vertices pointer+count pairs become slices.
func DefaultDebugDraw ¶
func DefaultDebugDraw() DebugDraw
DefaultDebugDraw initializes a drawing interface (upstream b2DefaultDebugDraw). This allows you to implement a sub-set of the drawing functions.
The drawing bounds keep the upstream FLT_MAX magnitude even though this port computes in float64.
type DistanceInput ¶
type DistanceInput struct {
// ProxyA is the proxy for shape A.
ProxyA ShapeProxy
// ProxyB is the proxy for shape B.
ProxyB ShapeProxy
// TransformA is the world transform for shape A.
TransformA Transform
// TransformB is the world transform for shape B.
TransformB Transform
// UseRadii selects whether the proxy radius is considered.
UseRadii bool
}
DistanceInput is input for ShapeDistance.
type DistanceJointDef ¶
type DistanceJointDef struct {
// Base joint definition
Base JointDef
// The rest length of this joint. Clamped to a stable minimum value.
Length float64
// Enable the distance constraint to behave like a spring. If false
// then the distance joint will be rigid, overriding the limit and motor.
EnableSpring bool
// The lower spring force controls how much tension it can sustain
LowerSpringForce float64
// The upper spring force controls how much compression it an sustain
UpperSpringForce float64
// The spring linear stiffness Hertz, cycles per second
Hertz float64
// The spring linear damping ratio, non-dimensional
DampingRatio float64
// Enable/disable the joint limit
EnableLimit bool
// Minimum length for limit. Clamped to a stable minimum value.
MinLength float64
// Maximum length for limit. Must be greater than or equal to the minimum length.
MaxLength float64
// Enable/disable the joint motor
EnableMotor bool
// The maximum motor force, usually in newtons
MaxMotorForce float64
// The desired motor speed, usually in meters per second
MotorSpeed float64
// contains filtered or unexported fields
}
DistanceJointDef is a distance joint definition (upstream b2DistanceJointDef). Connects a point on body A with a point on body B by a segment. Useful for ropes and springs.
func DefaultDistanceJointDef ¶
func DefaultDistanceJointDef() DistanceJointDef
DefaultDistanceJointDef initializes a distance joint definition (upstream b2DefaultDistanceJointDef).
type DistanceOutput ¶
type DistanceOutput struct {
// PointA is the closest point on shapeA.
PointA Vec2
// PointB is the closest point on shapeB.
PointB Vec2
// Normal is the normal vector that points from A to B. Invalid if distance
// is zero.
Normal Vec2
// Distance is the final distance, zero if overlapped.
Distance float64
// Iterations is the number of GJK iterations used.
Iterations int
// SimplexCount is the number of simplexes stored in the simplex array.
SimplexCount int
}
DistanceOutput is output for ShapeDistance.
func ShapeDistance ¶
func ShapeDistance(input *DistanceInput, cache *SimplexCache, simplexes []Simplex) DistanceOutput
ShapeDistance computes the closest points between two shapes represented as point clouds (upstream b2ShapeDistance). The SimplexCache cache is input/output. On the first call set SimplexCache.Count to zero. The underlying GJK algorithm may be debugged by passing in a debug simplexes slice. You may pass in nil.
Uses GJK for computing the distance between convex shapes. https://box2d.org/files/ErinCatto_GJK_GDC2010.pdf
type DynamicTree ¶
type DynamicTree struct {
// contains filtered or unexported fields
}
DynamicTree is a dynamic AABB tree broad-phase, inspired by Nathanael Presson's btDbvt (upstream b2DynamicTree).
A dynamic tree arranges data in a binary tree to accelerate queries such as AABB queries and ray casts. Leaf nodes are proxies with an AABB. These are used to hold a user collision object. Nodes are pooled and relocatable, so node indices are used rather than pointers.
func NewDynamicTree ¶
func NewDynamicTree() DynamicTree
NewDynamicTree constructs a tree and initializes the node pool (upstream b2DynamicTree_Create).
func (*DynamicTree) CreateProxy ¶
func (tree *DynamicTree) CreateProxy(aabb AABB, categoryBits uint64, userData uint64) int
CreateProxy creates a proxy in the tree as a leaf node and returns the node index (upstream b2DynamicTree_CreateProxy).
func (*DynamicTree) Destroy ¶
func (tree *DynamicTree) Destroy()
Destroy releases the node pool (upstream b2DynamicTree_Destroy).
func (*DynamicTree) DestroyProxy ¶
func (tree *DynamicTree) DestroyProxy(proxyID int)
DestroyProxy destroys a proxy (upstream b2DynamicTree_DestroyProxy).
func (*DynamicTree) EnlargeProxy ¶
func (tree *DynamicTree) EnlargeProxy(proxyID int, aabb AABB)
EnlargeProxy enlarges a proxy and its ancestors as necessary (upstream b2DynamicTree_EnlargeProxy).
func (*DynamicTree) GetAABB ¶
func (tree *DynamicTree) GetAABB(proxyID int) AABB
GetAABB returns the AABB of a proxy (upstream b2DynamicTree_GetAABB).
func (*DynamicTree) GetAreaRatio ¶
func (tree *DynamicTree) GetAreaRatio() float64
GetAreaRatio returns the ratio of the sum of the internal node areas to the root area (upstream b2DynamicTree_GetAreaRatio).
func (*DynamicTree) GetCategoryBits ¶
func (tree *DynamicTree) GetCategoryBits(proxyID int) uint64
GetCategoryBits returns the category bits on a proxy (upstream b2DynamicTree_GetCategoryBits).
func (*DynamicTree) GetHeight ¶
func (tree *DynamicTree) GetHeight() int
GetHeight returns the height of the binary tree (upstream b2DynamicTree_GetHeight).
func (*DynamicTree) GetProxyCount ¶
func (tree *DynamicTree) GetProxyCount() int
GetProxyCount returns the number of proxies created (upstream b2DynamicTree_GetProxyCount).
func (*DynamicTree) GetRootBounds ¶
func (tree *DynamicTree) GetRootBounds() AABB
GetRootBounds returns the bounding box that contains the entire tree (upstream b2DynamicTree_GetRootBounds).
func (*DynamicTree) GetUserData ¶
func (tree *DynamicTree) GetUserData(proxyID int) uint64
GetUserData returns the user data of a proxy (upstream b2DynamicTree_GetUserData).
func (*DynamicTree) MoveProxy ¶
func (tree *DynamicTree) MoveProxy(proxyID int, aabb AABB)
MoveProxy moves a proxy to a new AABB by removing and reinserting it (upstream b2DynamicTree_MoveProxy).
func (*DynamicTree) Query ¶
func (tree *DynamicTree) Query(aabb AABB, maskBits uint64, callback TreeQueryCallbackFcn, context any) TreeStats
Query finds all proxies overlapping the supplied AABB, calling the callback for each (upstream b2DynamicTree_Query).
func (*DynamicTree) QueryAll ¶
func (tree *DynamicTree) QueryAll(aabb AABB, callback TreeQueryCallbackFcn, context any) TreeStats
QueryAll finds all proxies overlapping the supplied AABB without filtering (upstream b2DynamicTree_QueryAll).
func (*DynamicTree) RayCast ¶
func (tree *DynamicTree) RayCast(input *RayCastInput, maskBits uint64, callback TreeRayCastCallbackFcn, context any, ) TreeStats
RayCast casts a ray against the proxies in the tree (upstream b2DynamicTree_RayCast). This relies on the callback to perform an exact ray cast in the case where the proxy contains a shape. The callback also performs any collision filtering.
func (*DynamicTree) Rebuild ¶
func (tree *DynamicTree) Rebuild(fullBuild bool) int
Rebuild rebuilds the tree while retaining subtrees that haven't changed and returns the number of boxes sorted (upstream b2DynamicTree_Rebuild).
It is not safe to access the tree during this operation because it may grow.
func (*DynamicTree) SetCategoryBits ¶
func (tree *DynamicTree) SetCategoryBits(proxyID int, categoryBits uint64)
SetCategoryBits modifies the category bits on a proxy. This is an expensive operation (upstream b2DynamicTree_SetCategoryBits).
func (*DynamicTree) ShapeCast ¶
func (tree *DynamicTree) ShapeCast(input *ShapeCastInput, maskBits uint64, callback TreeShapeCastCallbackFcn, context any, ) TreeStats
ShapeCast casts a shape against the proxies in the tree (upstream b2DynamicTree_ShapeCast).
func (*DynamicTree) Validate ¶
func (tree *DynamicTree) Validate() error
Validate checks the tree invariants (upstream b2DynamicTree_Validate). Upstream asserts; this port returns an error so tests can validate without enabling panics.
func (*DynamicTree) ValidateNoEnlarged ¶
func (tree *DynamicTree) ValidateNoEnlarged() error
ValidateNoEnlarged checks that no allocated node is flagged enlarged (upstream b2DynamicTree_ValidateNoEnlarged).
type ExplosionDef ¶
type ExplosionDef struct {
// Mask bits to filter shapes
MaskBits uint64
// The center of the explosion in world space
Position Vec2
// The radius of the explosion
Radius float64
// The falloff distance beyond the radius. Impulse is reduced to zero at this distance.
Falloff float64
// Impulse per unit length. This applies an impulse according to the shape perimeter that
// is facing the explosion. Explosions only apply to circles, capsules, and polygons. This
// may be negative for implosions.
ImpulsePerLength float64
}
ExplosionDef is used to configure options for explosions (upstream b2ExplosionDef). Explosions consider shape geometry when computing the impulse.
func DefaultExplosionDef ¶
func DefaultExplosionDef() ExplosionDef
DefaultExplosionDef initializes an explosion definition (upstream b2DefaultExplosionDef, which lives in joint.c).
type Filter ¶
type Filter struct {
// The collision category bits. Normally you would just set one bit. The category bits should
// represent your application object types. For example:
//
// const (
// CategoryStatic = 0x00000001
// CategoryDynamic = 0x00000002
// CategoryDebris = 0x00000004
// CategoryPlayer = 0x00000008
// // etc
// )
CategoryBits uint64
// The collision mask bits. This states the categories that this
// shape would accept for collision.
// For example, you may want your player to only collide with static objects
// and other players:
//
// maskBits = CategoryStatic | CategoryPlayer
MaskBits uint64
// Collision groups allow a certain group of objects to never collide (negative)
// or always collide (positive). A group index of zero has no effect. Non-zero group filtering
// always wins against the mask bits.
// For example, you may want ragdolls to collide with other ragdolls but you don't want
// ragdoll self-collision. In this case you would give each ragdoll a unique negative group index
// and apply that group index to all shapes on the ragdoll.
GroupIndex int
}
Filter is used to filter collision on shapes (upstream b2Filter). It affects shape-vs-shape collision and shape-versus-query collision (such as World.CastRay).
func DefaultFilter ¶
func DefaultFilter() Filter
DefaultFilter initializes a collision filter (upstream b2DefaultFilter).
type FilterJointDef ¶
type FilterJointDef struct {
// Base joint definition
Base JointDef
// contains filtered or unexported fields
}
FilterJointDef is used to disable collision between two specific bodies (upstream b2FilterJointDef).
func DefaultFilterJointDef ¶
func DefaultFilterJointDef() FilterJointDef
DefaultFilterJointDef initializes a filter joint definition (upstream b2DefaultFilterJointDef).
type FrictionCallback ¶
type FrictionCallback func(frictionA float64, userMaterialIDA uint64, frictionB float64, userMaterialIDB uint64) float64
FrictionCallback is an optional friction mixing callback. The default uses sqrt(frictionA * frictionB). This intentionally provides no context object because upstream calls it from a worker thread.
Warning: this function should not attempt to modify Box2D state or user application state.
type HexColor ¶
type HexColor int32
HexColor holds colors used for debug draw. They mostly match the named SVG colors (upstream b2HexColor). See https://www.rapidtables.com/web/color/index.html https://johndecember.com/html/spec/colorsvg.html
const ( ColorAliceBlue HexColor = 0xF0F8FF ColorAntiqueWhite HexColor = 0xFAEBD7 ColorAqua HexColor = 0x00FFFF ColorAquamarine HexColor = 0x7FFFD4 ColorAzure HexColor = 0xF0FFFF ColorBeige HexColor = 0xF5F5DC ColorBisque HexColor = 0xFFE4C4 ColorBlack HexColor = 0x000000 ColorBlanchedAlmond HexColor = 0xFFEBCD ColorBlue HexColor = 0x0000FF ColorBlueViolet HexColor = 0x8A2BE2 ColorBrown HexColor = 0xA52A2A ColorBurlywood HexColor = 0xDEB887 ColorCadetBlue HexColor = 0x5F9EA0 ColorChartreuse HexColor = 0x7FFF00 ColorChocolate HexColor = 0xD2691E ColorCoral HexColor = 0xFF7F50 ColorCornflowerBlue HexColor = 0x6495ED ColorCornsilk HexColor = 0xFFF8DC ColorCrimson HexColor = 0xDC143C ColorCyan HexColor = 0x00FFFF ColorDarkBlue HexColor = 0x00008B ColorDarkCyan HexColor = 0x008B8B ColorDarkGoldenRod HexColor = 0xB8860B ColorDarkGray HexColor = 0xA9A9A9 ColorDarkGreen HexColor = 0x006400 ColorDarkKhaki HexColor = 0xBDB76B ColorDarkMagenta HexColor = 0x8B008B ColorDarkOliveGreen HexColor = 0x556B2F ColorDarkOrange HexColor = 0xFF8C00 ColorDarkOrchid HexColor = 0x9932CC ColorDarkRed HexColor = 0x8B0000 ColorDarkSalmon HexColor = 0xE9967A ColorDarkSeaGreen HexColor = 0x8FBC8F ColorDarkSlateBlue HexColor = 0x483D8B ColorDarkSlateGray HexColor = 0x2F4F4F ColorDarkTurquoise HexColor = 0x00CED1 ColorDarkViolet HexColor = 0x9400D3 ColorDeepPink HexColor = 0xFF1493 ColorDeepSkyBlue HexColor = 0x00BFFF ColorDimGray HexColor = 0x696969 ColorDodgerBlue HexColor = 0x1E90FF ColorFireBrick HexColor = 0xB22222 ColorFloralWhite HexColor = 0xFFFAF0 ColorForestGreen HexColor = 0x228B22 ColorFuchsia HexColor = 0xFF00FF ColorGainsboro HexColor = 0xDCDCDC ColorGhostWhite HexColor = 0xF8F8FF ColorGold HexColor = 0xFFD700 ColorGoldenRod HexColor = 0xDAA520 ColorGray HexColor = 0x808080 ColorGreen HexColor = 0x008000 ColorGreenYellow HexColor = 0xADFF2F ColorHoneyDew HexColor = 0xF0FFF0 ColorHotPink HexColor = 0xFF69B4 ColorIndianRed HexColor = 0xCD5C5C ColorIndigo HexColor = 0x4B0082 ColorIvory HexColor = 0xFFFFF0 ColorKhaki HexColor = 0xF0E68C ColorLavender HexColor = 0xE6E6FA ColorLavenderBlush HexColor = 0xFFF0F5 ColorLawnGreen HexColor = 0x7CFC00 ColorLemonChiffon HexColor = 0xFFFACD ColorLightBlue HexColor = 0xADD8E6 ColorLightCoral HexColor = 0xF08080 ColorLightCyan HexColor = 0xE0FFFF ColorLightGoldenRodYellow HexColor = 0xFAFAD2 ColorLightGray HexColor = 0xD3D3D3 ColorLightGreen HexColor = 0x90EE90 ColorLightPink HexColor = 0xFFB6C1 ColorLightSalmon HexColor = 0xFFA07A ColorLightSeaGreen HexColor = 0x20B2AA ColorLightSkyBlue HexColor = 0x87CEFA ColorLightSlateGray HexColor = 0x778899 ColorLightSteelBlue HexColor = 0xB0C4DE ColorLightYellow HexColor = 0xFFFFE0 ColorLime HexColor = 0x00FF00 ColorLimeGreen HexColor = 0x32CD32 ColorLinen HexColor = 0xFAF0E6 ColorMagenta HexColor = 0xFF00FF ColorMaroon HexColor = 0x800000 ColorMediumAquaMarine HexColor = 0x66CDAA ColorMediumBlue HexColor = 0x0000CD ColorMediumOrchid HexColor = 0xBA55D3 ColorMediumPurple HexColor = 0x9370DB ColorMediumSeaGreen HexColor = 0x3CB371 ColorMediumSlateBlue HexColor = 0x7B68EE ColorMediumSpringGreen HexColor = 0x00FA9A ColorMediumTurquoise HexColor = 0x48D1CC ColorMediumVioletRed HexColor = 0xC71585 ColorMidnightBlue HexColor = 0x191970 ColorMintCream HexColor = 0xF5FFFA ColorMistyRose HexColor = 0xFFE4E1 ColorMoccasin HexColor = 0xFFE4B5 ColorOldLace HexColor = 0xFDF5E6 ColorOlive HexColor = 0x808000 ColorOliveDrab HexColor = 0x6B8E23 ColorOrange HexColor = 0xFFA500 ColorOrangeRed HexColor = 0xFF4500 ColorOrchid HexColor = 0xDA70D6 ColorPaleGoldenRod HexColor = 0xEEE8AA ColorPaleGreen HexColor = 0x98FB98 ColorPaleTurquoise HexColor = 0xAFEEEE ColorPaleVioletRed HexColor = 0xDB7093 ColorPapayaWhip HexColor = 0xFFEFD5 ColorPeachPuff HexColor = 0xFFDAB9 ColorPeru HexColor = 0xCD853F ColorPink HexColor = 0xFFC0CB ColorPlum HexColor = 0xDDA0DD ColorPowderBlue HexColor = 0xB0E0E6 ColorPurple HexColor = 0x800080 ColorRebeccaPurple HexColor = 0x663399 ColorRed HexColor = 0xFF0000 ColorRosyBrown HexColor = 0xBC8F8F ColorRoyalBlue HexColor = 0x4169E1 ColorSaddleBrown HexColor = 0x8B4513 ColorSalmon HexColor = 0xFA8072 ColorSandyBrown HexColor = 0xF4A460 ColorSeaGreen HexColor = 0x2E8B57 ColorSeaShell HexColor = 0xFFF5EE ColorSienna HexColor = 0xA0522D ColorSilver HexColor = 0xC0C0C0 ColorSkyBlue HexColor = 0x87CEEB ColorSlateBlue HexColor = 0x6A5ACD ColorSlateGray HexColor = 0x708090 ColorSnow HexColor = 0xFFFAFA ColorSpringGreen HexColor = 0x00FF7F ColorSteelBlue HexColor = 0x4682B4 ColorTan HexColor = 0xD2B48C ColorTeal HexColor = 0x008080 ColorThistle HexColor = 0xD8BFD8 ColorTomato HexColor = 0xFF6347 ColorTurquoise HexColor = 0x40E0D0 ColorViolet HexColor = 0xEE82EE ColorWheat HexColor = 0xF5DEB3 ColorWhite HexColor = 0xFFFFFF ColorWhiteSmoke HexColor = 0xF5F5F5 ColorYellow HexColor = 0xFFFF00 ColorYellowGreen HexColor = 0x9ACD32 ColorBox2DRed HexColor = 0xDC3132 ColorBox2DBlue HexColor = 0x30AEBF ColorBox2DGreen HexColor = 0x8CC924 ColorBox2DYellow HexColor = 0xFFEE8C )
type Hull ¶
type Hull struct {
// Points are the final points of the hull.
Points [MaxPolygonVertices]Vec2
// Count is the number of points.
Count int
}
Hull is a convex hull. It is used to create convex polygons.
Do not modify these values directly, instead use ComputeHull.
func ComputeHull ¶
ComputeHull computes the convex hull of a set of points (upstream b2ComputeHull). It returns an empty hull if it fails. Some failure cases:
- all points very close together
- all points on a line
- less than 3 points
- more than MaxPolygonVertices points
This welds close points and removes collinear points.
Do not modify a hull once it has been computed.
The quickhull algorithm:
- merges vertices based on LinearSlop
- removes collinear points using LinearSlop
- returns an empty hull if it fails
type JointDef ¶
type JointDef struct {
// User data. Deviation from upstream: the C void* becomes a uint64 so the
// ECS wrapper can pack an entity id directly.
UserData uint64
// The first attached body
BodyIDA BodyID
// The second attached body
BodyIDB BodyID
// The first local joint frame
LocalFrameA Transform
// The second local joint frame
LocalFrameB Transform
// Force threshold for joint events
ForceThreshold float64
// Torque threshold for joint events
TorqueThreshold float64
// Constraint hertz (advanced feature)
ConstraintHertz float64
// Constraint damping ratio (advanced feature)
ConstraintDampingRatio float64
// Debug draw scale
DrawScale float64
// Set this flag to true if the attached bodies should collide
CollideConnected bool
}
JointDef is the base joint definition used by all joint types (upstream b2JointDef). The local frames are measured from the body's origin rather than the center of mass because:
- you might not know where the center of mass will be
- if you add/remove shapes from a body and recompute the mass, the joints will be broken
type JointEvent ¶
type JointEvent struct {
// The joint id
JointID JointID
// The user data from the joint for convenience. Deviation from upstream:
// the C void* becomes a uint64 so the ECS wrapper can pack an entity id
// directly.
UserData uint64
}
JointEvent reports a joint that is awake and has a force and/or torque exceeding the threshold (upstream b2JointEvent). The observed forces and torques are not returned for efficiency reasons.
type JointEvents ¶
type JointEvents struct {
// Joint events
JointEvents []JointEvent
}
JointEvents are buffered in the world and are available as event slices after the time step is complete (upstream b2JointEvents). Note: this data becomes invalid if joints are destroyed.
Deviation from upstream: the pointer+count pair becomes a slice.
type JointID ¶
type JointID struct {
// contains filtered or unexported fields
}
JointID references a joint instance (upstream b2JointId).
func UnpackJointID ¶
UnpackJointID loads a uint64 into a joint id (upstream b2LoadJointId).
type JointType ¶
type JointType int32
JointType is the joint type enumeration (upstream b2JointType).
This is useful because all joint types use JointID and sometimes you want to get the type of a joint.
type Manifold ¶
type Manifold struct {
// Normal is the unit normal vector in world space, points from shape A to
// body B.
Normal Vec2
// RollingImpulse is the angular impulse applied for rolling resistance.
// N * m * s = kg * m^2 / s.
RollingImpulse float64
// Points are the manifold points, up to two are possible in 2D.
Points [2]ManifoldPoint
// PointCount is the number of contact points, will be 0, 1, or 2.
PointCount int
}
Manifold describes the contact points between colliding shapes (upstream b2Manifold). Box2D uses speculative collision so some contact points may be separated.
func CollideCapsuleAndCircle ¶
func CollideCapsuleAndCircle(capsuleA *Capsule, xfA Transform, circleB *Circle, xfB Transform) Manifold
CollideCapsuleAndCircle computes the collision manifold between a capsule and circle (upstream b2CollideCapsuleAndCircle).
func CollideCapsules ¶
CollideCapsules computes the contact manifold between two capsules (upstream b2CollideCapsules).
Follows Ericson 5.1.9 Closest Points of Two Line Segments. Adds some logic to support clipping to get two contact points.
func CollideChainSegmentAndCapsule ¶
func CollideChainSegmentAndCapsule(segmentA *ChainSegment, xfA Transform, capsuleB *Capsule, xfB Transform, cache *SimplexCache) Manifold
CollideChainSegmentAndCapsule computes the contact manifold between a chain segment and a capsule (upstream b2CollideChainSegmentAndCapsule).
func CollideChainSegmentAndCircle ¶
func CollideChainSegmentAndCircle(segmentA *ChainSegment, xfA Transform, circleB *Circle, xfB Transform) Manifold
CollideChainSegmentAndCircle computes the contact manifold between a chain segment and a circle (upstream b2CollideChainSegmentAndCircle).
func CollideChainSegmentAndPolygon ¶
func CollideChainSegmentAndPolygon(segmentA *ChainSegment, xfA Transform, polygonB *Polygon, xfB Transform, cache *SimplexCache) Manifold
CollideChainSegmentAndPolygon computes the contact manifold between a chain segment and a rounded polygon (upstream b2CollideChainSegmentAndPolygon).
func CollideCircles ¶
CollideCircles computes the contact manifold between two circles (upstream b2CollideCircles).
point = qA * localAnchorA + pA localAnchorB = qBc * (point - pB) anchorB = point - pB = qA * localAnchorA + pA - pB
= anchorA + (pA - pB)
func CollidePolygonAndCapsule ¶
func CollidePolygonAndCapsule(polygonA *Polygon, xfA Transform, capsuleB *Capsule, xfB Transform) Manifold
CollidePolygonAndCapsule computes the contact manifold between a polygon and a capsule (upstream b2CollidePolygonAndCapsule).
func CollidePolygonAndCircle ¶
func CollidePolygonAndCircle(polygonA *Polygon, xfA Transform, circleB *Circle, xfB Transform) Manifold
CollidePolygonAndCircle computes the collision manifold between a polygon and a circle (upstream b2CollidePolygonAndCircle).
func CollidePolygons ¶
CollidePolygons computes the contact manifold between two polygons (upstream b2CollidePolygons).
Due to speculation, every polygon is rounded. Algorithm:
compute edge separation using the separating axis test (SAT)
if (separation > speculation_distance)
return
find reference and incident edge
if separation >= 0.1f * B2_LINEAR_SLOP
compute closest points between reference and incident edge
if vertices are closest
single vertex-vertex contact
else
clip edges
end
else
clip edges
end
func CollideSegmentAndCapsule ¶
func CollideSegmentAndCapsule(segmentA *Segment, xfA Transform, capsuleB *Capsule, xfB Transform) Manifold
CollideSegmentAndCapsule computes the contact manifold between a segment and a capsule (upstream b2CollideSegmentAndCapsule).
type ManifoldPoint ¶
type ManifoldPoint struct {
// ClipPoint is the location of the contact point in world space when first
// clipped. Subject to precision loss at large coordinates. This point lags
// behind when contact recycling is used. Should only be used for
// debugging; use AnchorA and/or AnchorB for game logic.
ClipPoint Vec2
// AnchorA is the location of the contact point relative to shapeA's origin
// in world space. When used internally to the Box2D solver, this is
// relative to the body center of mass.
AnchorA Vec2
// AnchorB is the location of the contact point relative to shapeB's origin
// in world space. When used internally to the Box2D solver, this is
// relative to the body center of mass.
AnchorB Vec2
// Separation is the separation of the contact point, negative if
// penetrating.
Separation float64
// BaseSeparation is the cached separation used for contact recycling.
BaseSeparation float64
// NormalImpulse is the impulse along the manifold normal vector.
NormalImpulse float64
// TangentImpulse is the friction impulse.
TangentImpulse float64
// TotalNormalImpulse is the total normal impulse applied across
// sub-stepping and restitution. This is important to identify speculative
// contact points that had an interaction in the time step. This includes
// the warm starting impulse, the sub-step delta impulse, and the
// restitution impulse.
TotalNormalImpulse float64
// NormalVelocity is the relative normal velocity pre-solve. Used for hit
// events. If the normal impulse is zero then there was no hit. Negative
// means shapes are approaching.
NormalVelocity float64
// ID uniquely identifies a contact point between two shapes.
ID uint16
// Persisted reports whether this contact point existed the previous step.
Persisted bool
}
ManifoldPoint is a contact point in a Manifold (upstream b2ManifoldPoint).
type MassData ¶
type MassData struct {
// Mass is the mass of the shape, usually in kilograms.
Mass float64
// Center is the position of the shape's centroid relative to the shape's
// origin.
Center Vec2
// RotationalInertia is the rotational inertia of the shape about the shape
// center.
RotationalInertia float64
}
MassData holds the mass data computed for a shape.
func ComputeCapsuleMass ¶
ComputeCapsuleMass computes the mass properties of a capsule (upstream b2ComputeCapsuleMass).
func ComputeCircleMass ¶
ComputeCircleMass computes the mass properties of a circle (upstream b2ComputeCircleMass).
func ComputePolygonMass ¶
ComputePolygonMass computes the mass properties of a polygon (upstream b2ComputePolygonMass).
type Mat22 ¶
type Mat22 struct {
CX, CY Vec2
}
Mat22 is a 2-by-2 matrix stored as columns.
func GetInverse22 ¶
GetInverse22 returns the inverse of a 2-by-2 matrix.
type MotionLocks ¶
type MotionLocks struct {
// Prevent translation along the x-axis
LinearX bool
// Prevent translation along the y-axis
LinearY bool
// Prevent rotation around the z-axis
AngularZ bool
}
MotionLocks holds motion locks to restrict the body movement (upstream b2MotionLocks).
type MotorJointDef ¶
type MotorJointDef struct {
// Base joint definition
Base JointDef
// The desired linear velocity
LinearVelocity Vec2
// The maximum motor force in newtons
MaxVelocityForce float64
// The desired angular velocity
AngularVelocity float64
// The maximum motor torque in newton-meters
MaxVelocityTorque float64
// Linear spring hertz for position control
LinearHertz float64
// Linear spring damping ratio
LinearDampingRatio float64
// Maximum spring force in newtons
MaxSpringForce float64
// Angular spring hertz for position control
AngularHertz float64
// Angular spring damping ratio
AngularDampingRatio float64
// Maximum spring torque in newton-meters
MaxSpringTorque float64
// contains filtered or unexported fields
}
MotorJointDef is used to control the relative velocity and or transform between two bodies (upstream b2MotorJointDef). With a velocity of zero this acts like top-down friction.
func DefaultMotorJointDef ¶
func DefaultMotorJointDef() MotorJointDef
DefaultMotorJointDef initializes a motor joint definition (upstream b2DefaultMotorJointDef).
type OverlapResultFcn ¶
OverlapResultFcn is the prototype callback for overlap queries (upstream b2OverlapResultFcn). Called for each shape found in the query. Return false to terminate the query. See World.OverlapAABB.
type PlaneResult ¶
type PlaneResult struct {
// Plane is the collision plane between the mover and a convex shape.
Plane Plane
// Point is the collision point on the shape.
Point Vec2
// Hit reports whether the collision registered a hit. If not, this plane
// should be ignored.
Hit bool
}
PlaneResult is a collision plane returned from World_CollideMover.
func CollideMoverAndCapsule ¶
func CollideMoverAndCapsule(mover *Capsule, shape *Capsule) PlaneResult
CollideMoverAndCapsule collides a capsule mover with a capsule (upstream b2CollideMoverAndCapsule).
func CollideMoverAndCircle ¶
func CollideMoverAndCircle(mover *Capsule, shape *Circle) PlaneResult
CollideMoverAndCircle collides a capsule mover with a circle (upstream b2CollideMoverAndCircle).
func CollideMoverAndPolygon ¶
func CollideMoverAndPolygon(mover *Capsule, shape *Polygon) PlaneResult
CollideMoverAndPolygon collides a capsule mover with a convex polygon (upstream b2CollideMoverAndPolygon).
func CollideMoverAndSegment ¶
func CollideMoverAndSegment(mover *Capsule, shape *Segment) PlaneResult
CollideMoverAndSegment collides a capsule mover with a segment (upstream b2CollideMoverAndSegment).
type PlaneResultFcn ¶
type PlaneResultFcn func(shapeID ShapeID, plane *PlaneResult, ctx any) bool
PlaneResultFcn is the prototype callback for character movers (upstream b2PlaneResultFcn). Called for each shape found in the query. Return true to continue gathering planes. See World.CollideMover.
type PlaneSolverResult ¶
type PlaneSolverResult struct {
// Translation is the translation of the mover.
Translation Vec2
// IterationCount is the number of iterations used by the plane solver.
// For diagnostics.
IterationCount int
}
PlaneSolverResult is returned by SolvePlanes (upstream b2PlaneSolverResult).
func SolvePlanes ¶
func SolvePlanes(targetDelta Vec2, planes []CollisionPlane) PlaneSolverResult
SolvePlanes solves the position of a mover that satisfies the given collision planes (upstream b2SolvePlanes). targetDelta is the desired movement from the position used to generate the collision planes. The planes' Push fields are written in place.
type Polygon ¶
type Polygon struct {
// Vertices are the polygon vertices.
Vertices [MaxPolygonVertices]Vec2
// Normals are the outward normal vectors of the polygon sides.
Normals [MaxPolygonVertices]Vec2
// Centroid is the centroid of the polygon.
Centroid Vec2
// Radius is the external radius for rounded polygons.
Radius float64
// Count is the number of polygon vertices.
Count int
}
Polygon is a solid convex polygon. It is assumed that the interior of the polygon is to the left of each edge. Polygons have a maximum number of vertices equal to MaxPolygonVertices. In most cases you should not need many vertices for a convex polygon.
Do NOT fill this out manually, instead use a helper function like MakePolygon or MakeBox.
func MakeBox ¶
MakeBox makes a box (rectangle) polygon, bypassing the need for a convex hull (upstream b2MakeBox). halfWidth is the half-width (x-axis) and halfHeight is the half-height (y-axis).
func MakeOffsetBox ¶
MakeOffsetBox makes an offset box, bypassing the need for a convex hull (upstream b2MakeOffsetBox). center is the local center of the box and rotation is the local rotation.
func MakeOffsetPolygon ¶
MakeOffsetPolygon makes an offset convex polygon from a convex hull (upstream b2MakeOffsetPolygon). This will assert if the hull is not valid.
Do not manually fill in the hull data, it must come directly from ComputeHull.
func MakeOffsetRoundedBox ¶
func MakeOffsetRoundedBox(halfWidth, halfHeight float64, center Vec2, rotation Rot, radius float64) Polygon
MakeOffsetRoundedBox makes an offset rounded box, bypassing the need for a convex hull (upstream b2MakeOffsetRoundedBox).
func MakeOffsetRoundedPolygon ¶
MakeOffsetRoundedPolygon makes an offset rounded convex polygon from a convex hull (upstream b2MakeOffsetRoundedPolygon). This will assert if the hull is not valid.
Do not manually fill in the hull data, it must come directly from ComputeHull.
func MakePolygon ¶
MakePolygon makes a convex polygon from a convex hull (upstream b2MakePolygon). This will assert if the hull is not valid.
Do not manually fill in the hull data, it must come directly from ComputeHull.
func MakeRoundedBox ¶
MakeRoundedBox makes a rounded box, bypassing the need for a convex hull (upstream b2MakeRoundedBox). radius is the radius of the rounded extension.
func MakeSquare ¶
MakeSquare makes a square polygon, bypassing the need for a convex hull (upstream b2MakeSquare). halfWidth is the half-width.
func TransformPolygon ¶
TransformPolygon transforms a polygon (upstream b2TransformPolygon). This is useful for transferring a shape from one body to another.
type PreSolveFcn ¶
PreSolveFcn is the prototype for a pre-solve callback (upstream b2PreSolveFcn). This is called after a contact is updated. This allows you to inspect a contact before it goes to the solver. If you are careful, you can modify the contact manifold (e.g. modify the normal). Notes:
- this is only called if the shape has enabled pre-solve events
- this is called only for awake dynamic bodies
- this is not called for sensors
- the supplied manifold has impulse values from the previous step
Return false if you want to disable the contact this step.
Warning: do not attempt to modify the world inside this callback.
type PrismaticJointDef ¶
type PrismaticJointDef struct {
// Base joint definition
Base JointDef
// Enable a linear spring along the prismatic joint axis
EnableSpring bool
// The spring stiffness Hertz, cycles per second
Hertz float64
// The spring damping ratio, non-dimensional
DampingRatio float64
// The target translation for the joint in meters. The spring-damper will drive
// to this translation.
TargetTranslation float64
// Enable/disable the joint limit
EnableLimit bool
// The lower translation limit
LowerTranslation float64
// The upper translation limit
UpperTranslation float64
// Enable/disable the joint motor
EnableMotor bool
// The maximum motor force, typically in newtons
MaxMotorForce float64
// The desired motor speed, typically in meters per second
MotorSpeed float64
// contains filtered or unexported fields
}
PrismaticJointDef is a prismatic joint definition (upstream b2PrismaticJointDef). Body B may slide along the x-axis in local frame A. Body B cannot rotate relative to body A. The joint translation is zero when the local frame origins coincide in world space.
func DefaultPrismaticJointDef ¶
func DefaultPrismaticJointDef() PrismaticJointDef
DefaultPrismaticJointDef initializes a prismatic joint definition (upstream b2DefaultPrismaticJointDef).
type Profile ¶
type Profile struct {
Step float64
Pairs float64
Collide float64
Solve float64
PrepareStages float64
SolveConstraints float64
PrepareConstraints float64
IntegrateVelocities float64
WarmStart float64
SolveImpulses float64
IntegratePositions float64
RelaxImpulses float64
ApplyRestitution float64
StoreImpulses float64
SplitIslands float64
Transforms float64
SensorHits float64
JointEvents float64
HitEvents float64
Refit float64
Bullets float64
SleepIslands float64
Sensors float64
}
Profile holds profiling data. Times are in milliseconds (upstream b2Profile).
type QueryFilter ¶
type QueryFilter struct {
// The collision category bits of this query. Normally you would just set one bit.
CategoryBits uint64
// The collision mask bits. This states the shape categories that this
// query would accept for collision.
MaskBits uint64
}
QueryFilter is used to filter collisions between queries and shapes (upstream b2QueryFilter). For example, you may want a ray-cast representing a projectile to hit players and the static environment but not debris.
func DefaultQueryFilter ¶
func DefaultQueryFilter() QueryFilter
DefaultQueryFilter initializes a query filter (upstream b2DefaultQueryFilter).
type RayCastInput ¶
type RayCastInput struct {
// Origin is the start point of the ray cast.
Origin Vec2
// Translation is the translation of the ray cast.
Translation Vec2
// MaxFraction is the maximum fraction of the translation to consider,
// typically 1.
MaxFraction float64
}
RayCastInput is low level ray cast input data.
type RayResult ¶
type RayResult struct {
ShapeID ShapeID
Point Vec2
Normal Vec2
Fraction float64
NodeVisits int
LeafVisits int
Hit bool
}
RayResult is the result from World.RayCastClosest (upstream b2RayResult). If there is initial overlap the fraction and normal will be zero while the point is an arbitrary point in the overlap region.
type RestitutionCallback ¶
type RestitutionCallback func(restitutionA float64, userMaterialIDA uint64, restitutionB float64, userMaterialIDB uint64) float64
RestitutionCallback is an optional restitution mixing callback. The default uses max(restitutionA, restitutionB). This intentionally provides no context object because upstream calls it from a worker thread.
Warning: this function should not attempt to modify Box2D state or user application state.
type RevoluteJointDef ¶
type RevoluteJointDef struct {
// Base joint definition
Base JointDef
// The target angle for the joint in radians. The spring-damper will drive
// to this angle.
TargetAngle float64
// Enable a rotational spring on the revolute hinge axis
EnableSpring bool
// The spring stiffness Hertz, cycles per second
Hertz float64
// The spring damping ratio, non-dimensional
DampingRatio float64
// A flag to enable joint limits
EnableLimit bool
// The lower angle for the joint limit in radians. Minimum of -0.99*pi radians.
LowerAngle float64
// The upper angle for the joint limit in radians. Maximum of 0.99*pi radians.
UpperAngle float64
// A flag to enable the joint motor
EnableMotor bool
// The maximum motor torque, typically in newton-meters
MaxMotorTorque float64
// The desired motor speed in radians per second
MotorSpeed float64
// contains filtered or unexported fields
}
RevoluteJointDef is a revolute joint definition (upstream b2RevoluteJointDef). A point on body B is fixed to a point on body A. Allows relative rotation.
func DefaultRevoluteJointDef ¶
func DefaultRevoluteJointDef() RevoluteJointDef
DefaultRevoluteJointDef initializes a revolute joint definition (upstream b2DefaultRevoluteJointDef).
type Rot ¶
type Rot struct {
C, S float64
}
Rot is a 2D rotation, similar to using a complex number for rotation.
func ComputeRotationBetweenUnitVectors ¶
ComputeRotationBetweenUnitVectors computes the rotation between two unit vectors.
func IntegrateRotation ¶
IntegrateRotation integrates a rotation from an angular displacement in radians and renormalizes.
func InvMulRot ¶
InvMulRot transpose-multiplies two rotations: inv(a) * b. This rotates a vector local in frame b into a vector local in frame a.
func MakeRotFromUnitVector ¶
MakeRotFromUnitVector makes a rotation from a unit vector.
type Segment ¶
type Segment struct {
// Point1 is the first point.
Point1 Vec2
// Point2 is the second point.
Point2 Vec2
}
Segment is a line segment with two-sided collision.
type SegmentDistanceResult ¶
type SegmentDistanceResult struct {
// Closest1 is the closest point on the first segment.
Closest1 Vec2
// Closest2 is the closest point on the second segment.
Closest2 Vec2
// Fraction1 is the barycentric coordinate on the first segment.
Fraction1 float64
// Fraction2 is the barycentric coordinate on the second segment.
Fraction2 float64
// DistanceSquared is the squared distance between the closest points.
DistanceSquared float64
}
SegmentDistanceResult holds the result of computing the distance between two line segments.
func SegmentDistance ¶
func SegmentDistance(p1, q1, p2, q2 Vec2) SegmentDistanceResult
SegmentDistance computes the distance between two line segments, clamping at the end points if needed (upstream b2SegmentDistance).
Follows Ericson 5.1.9 Closest Points of Two Line Segments.
type SensorBeginTouchEvent ¶
type SensorBeginTouchEvent struct {
// The id of the sensor shape
SensorShapeID ShapeID
// The id of the shape that began touching the sensor shape
VisitorShapeID ShapeID
}
SensorBeginTouchEvent is generated when a shape starts to overlap a sensor shape (upstream b2SensorBeginTouchEvent).
type SensorEndTouchEvent ¶
type SensorEndTouchEvent struct {
// The id of the sensor shape.
// Warning: this shape may have been destroyed. See Shape.IsValid.
SensorShapeID ShapeID
// The id of the shape that stopped touching the sensor shape.
// Warning: this shape may have been destroyed. See Shape.IsValid.
VisitorShapeID ShapeID
}
SensorEndTouchEvent is generated when a shape stops overlapping a sensor shape (upstream b2SensorEndTouchEvent). These include things like setting the transform, destroying a body or shape, or changing a filter. You will also get an end event if the sensor or visitor are destroyed. Therefore you should always confirm the shape id is valid using Shape.IsValid.
type SensorEvents ¶
type SensorEvents struct {
// Sensor begin touch events
BeginEvents []SensorBeginTouchEvent
// Sensor end touch events
EndEvents []SensorEndTouchEvent
}
SensorEvents are buffered in the world and are available as begin/end overlap event slices after the time step is complete (upstream b2SensorEvents). Note: these may become invalid if bodies and/or shapes are destroyed.
Deviation from upstream: the pointer+count pairs become slices.
type ShapeCastInput ¶
type ShapeCastInput struct {
// Proxy is a generic shape.
Proxy ShapeProxy
// Translation is the translation of the shape cast.
Translation Vec2
// MaxFraction is the maximum fraction of the translation to consider,
// typically 1.
MaxFraction float64
// CanEncroach allows the shape cast to encroach when initially touching.
// This only works if the radius is greater than zero.
CanEncroach bool
}
ShapeCastInput is low level shape cast input in generic form. This allows casting an arbitrary point cloud wrap with a radius. For example, a circle is a single point with a non-zero radius. A capsule is two points with a non-zero radius. A box is four points with a zero radius.
type ShapeCastPairInput ¶
type ShapeCastPairInput struct {
// ProxyA is the proxy for shape A.
ProxyA ShapeProxy
// ProxyB is the proxy for shape B.
ProxyB ShapeProxy
// TransformA is the world transform for shape A.
TransformA Transform
// TransformB is the world transform for shape B.
TransformB Transform
// TranslationB is the translation of shape B.
TranslationB Vec2
// MaxFraction is the fraction of the translation to consider, typically 1.
MaxFraction float64
// CanEncroach allows shapes with a radius to move slightly closer if
// already touching.
CanEncroach bool
}
ShapeCastPairInput holds input parameters for ShapeCast.
type ShapeDef ¶
type ShapeDef struct {
// Use this to store application specific shape data. Deviation from
// upstream: the C void* becomes a uint64 so the ECS wrapper can pack an
// entity id directly.
UserData uint64
// The surface material for this shape.
Material SurfaceMaterial
// The density, usually in kg/m^2.
// This is not part of the surface material because this is for the interior, which may have
// other considerations, such as being hollow. For example a wood barrel may be hollow or full of water.
Density float64
// Collision filtering data.
Filter Filter
// Enable custom filtering. Only one of the two shapes needs to enable custom filtering. See WorldDef.
EnableCustomFiltering bool
// A sensor shape generates overlap events but never generates a collision response.
// Sensors do not have continuous collision. Instead, use a ray or shape cast for those scenarios.
// Sensors still contribute to the body mass if they have non-zero density.
//
// Note: sensor events are disabled by default. See EnableSensorEvents.
IsSensor bool
// Enable sensor events for this shape. This applies to sensors and non-sensors. Both shapes involved must have this flag set to true.
// False by default, even for sensors.
EnableSensorEvents bool
// Enable contact events for this shape. Only applies to kinematic and dynamic bodies. Only one shape involved needs this flag set to true.
// Ignored for sensors. False by default.
EnableContactEvents bool
// Enable hit events for this shape. Only applies to kinematic and dynamic bodies. Only one shape involved needs this flag set to true.
// Ignored for sensors. False by default.
EnableHitEvents bool
// Enable pre-solve contact events for this shape. Only applies to dynamic bodies. These are expensive
// and must be carefully handled due to multithreading. Ignored for sensors.
EnablePreSolveEvents bool
// When shapes are created they will scan the environment for collision the next time step. This can significantly slow down
// static body creation when there are many static shapes.
// This is flag is ignored for dynamic and kinematic shapes which always invoke contact creation.
InvokeContactCreation bool
// Should the body update the mass properties when this shape is created. Default is true.
// Set this to false to skip the recomputation while adding many shapes to one body; the
// body is then left with stale mass data, so call World.ApplyBodyMassFromShapes for it
// before simulating.
UpdateBodyMass bool
// contains filtered or unexported fields
}
ShapeDef is used to create a shape (upstream b2ShapeDef). This is a temporary object used to bundle shape creation parameters. You may use the same shape definition to create multiple shapes. Must be initialized using DefaultShapeDef.
func DefaultShapeDef ¶
func DefaultShapeDef() ShapeDef
DefaultShapeDef initializes a shape definition (upstream b2DefaultShapeDef).
type ShapeID ¶
type ShapeID struct {
// contains filtered or unexported fields
}
ShapeID references a shape instance (upstream b2ShapeId).
func UnpackShapeID ¶
UnpackShapeID loads a uint64 into a shape id (upstream b2LoadShapeId).
type ShapeProxy ¶
type ShapeProxy struct {
// Points is the point cloud.
Points [MaxPolygonVertices]Vec2
// Count is the number of points. Must be greater than 0.
Count int
// Radius is the external radius of the point cloud. May be zero.
Radius float64
}
ShapeProxy is a distance proxy used by the GJK algorithm. It encapsulates any shape. You can provide between 1 and MaxPolygonVertices points and a radius.
func MakeOffsetProxy ¶
func MakeOffsetProxy(points []Vec2, count int, radius float64, position Vec2, rotation Rot) ShapeProxy
MakeOffsetProxy makes a proxy with a transform (upstream b2MakeOffsetProxy). This is a deep copy of the points.
type ShapeType ¶
type ShapeType int32
ShapeType is the shape type (upstream b2ShapeType).
const ( // CircleShape is a circle with an offset. CircleShape ShapeType = iota // CapsuleShape is an extruded circle. CapsuleShape // SegmentShape is a line segment. SegmentShape // PolygonShape is a convex polygon. PolygonShape // ChainSegmentShape is a line segment owned by a chain shape. ChainSegmentShape // ShapeTypeCount is the number of shape types. ShapeTypeCount )
type Simplex ¶
type Simplex struct {
// V1, V2, V3 are the vertices.
V1, V2, V3 SimplexVertex
// Count is the number of valid vertices.
Count int
}
Simplex is a simplex from the GJK algorithm.
type SimplexCache ¶
type SimplexCache struct {
// Count is the number of stored simplex points.
Count uint16
// IndexA holds the cached simplex indices on shape A.
IndexA [3]uint8
// IndexB holds the cached simplex indices on shape B.
IndexB [3]uint8
}
SimplexCache is used to warm start the GJK simplex. If you call ShapeDistance multiple times with nearby transforms this might improve performance. Otherwise you can zero initialize this. The distance cache must be initialized to zero on the first call. Users should generally just zero initialize this structure for each call.
type SimplexVertex ¶
type SimplexVertex struct {
// WA is the support point in proxyA.
WA Vec2
// WB is the support point in proxyB.
WB Vec2
// W is wA - wB.
W Vec2
// A is the barycentric coordinate for the closest point.
A float64
// IndexA is the wA index.
IndexA int
// IndexB is the wB index.
IndexB int
}
SimplexVertex is a simplex vertex for debugging the GJK algorithm.
type SurfaceMaterial ¶
type SurfaceMaterial struct {
// The Coulomb (dry) friction coefficient, usually in the range [0,1].
Friction float64
// The coefficient of restitution (bounce) usually in the range [0,1].
// https://en.wikipedia.org/wiki/Coefficient_of_restitution
Restitution float64
// The rolling resistance usually in the range [0,1].
RollingResistance float64
// The tangent speed for conveyor belts
TangentSpeed float64
// User material identifier. This is passed with query results and to friction and restitution
// combining functions. It is not used internally.
UserMaterialID uint64
// Custom debug draw color.
CustomColor uint32
}
SurfaceMaterial allows chain shapes to have per segment surface properties (upstream b2SurfaceMaterial).
func DefaultSurfaceMaterial ¶
func DefaultSurfaceMaterial() SurfaceMaterial
DefaultSurfaceMaterial initializes a surface material (upstream b2DefaultSurfaceMaterial).
type Sweep ¶
type Sweep struct {
// LocalCenter is the local center of mass position.
LocalCenter Vec2
// C1 is the starting center of mass world position.
C1 Vec2
// C2 is the ending center of mass world position.
C2 Vec2
// Q1 is the starting world rotation.
Q1 Rot
// Q2 is the ending world rotation.
Q2 Rot
}
Sweep describes the motion of a body/shape for TOI computation. Shapes are defined with respect to the body origin, which may not coincide with the center of mass. However, to support dynamics we must interpolate the center of mass position.
type TOIInput ¶
type TOIInput struct {
// ProxyA is the proxy for shape A.
ProxyA ShapeProxy
// ProxyB is the proxy for shape B.
ProxyB ShapeProxy
// SweepA is the movement of shape A.
SweepA Sweep
// SweepB is the movement of shape B.
SweepB Sweep
// MaxFraction defines the sweep interval [0, maxFraction].
MaxFraction float64
}
TOIInput is time of impact input.
type TOIOutput ¶
type TOIOutput struct {
// State is the type of result.
State TOIState
// Point is the hit point.
Point Vec2
// Normal is the hit normal.
Normal Vec2
// Fraction is the sweep time of the collision.
Fraction float64
}
TOIOutput is time of impact output.
func TimeOfImpact ¶
TimeOfImpact computes the upper bound on time before two shapes penetrate (upstream b2TimeOfImpact). Time is represented as a fraction between [0,tMax]. This uses a swept separating axis and may miss some intermediate, non-tunneling collisions. If you change the time interval, you should call this function again.
CCD via the local separating axis method. This seeks progression by computing the largest time at which separation is maintained.
type Transform ¶
Transform is a 2D rigid transform.
func GetSweepTransform ¶
GetSweepTransform evaluates the transform sweep at a specific time (upstream b2GetSweepTransform).
func InvMulTransforms ¶
InvMulTransforms creates a transform that converts a local point in frame B to a local point in frame A.
v2 = A.q' * (B.q * v1 + B.p - A.p) = A.q' * B.q * v1 + A.q' * (B.p - A.p)
func MulTransforms ¶
MulTransforms multiplies two transforms. If the result is applied to a point p local to frame B, the transform first converts p to a point local to frame A, then into a point in the world frame.
v2 = A.q.Rot(B.q.Rot(v1) + B.p) + A.p = (A.q * B.q).Rot(v1) + A.q.Rot(B.p) + A.p
type TreeNode ¶
type TreeNode struct {
// AABB is the node bounding box.
AABB AABB
// CategoryBits holds the category bits for collision filtering.
CategoryBits uint64
// UserData is the user data of a leaf node. Upstream shares storage with
// Child1/Child2; it is meaningless for internal nodes.
UserData uint64
// Child1 is the first child of an internal node (NullIndex for a leaf).
// int32 like upstream so the node stays one 64-byte cache line (see the
// file header).
Child1 int32
// Child2 is the second child of an internal node (NullIndex for a leaf).
Child2 int32
// Parent is the parent index of an allocated node and the free-list next
// index of a free node. Upstream reuses this single slot for both
// meanings (union parent/next).
Parent int32
// Height is the node height. Leaves have height zero.
Height uint16
// Flags is a bit mask of allocatedNode, enlargedNode and leafNode.
Flags uint16
}
TreeNode is a node in the dynamic tree (upstream b2TreeNode).
type TreeQueryCallbackFcn ¶
TreeQueryCallbackFcn receives proxies found in an AABB query. It returns true if the query should continue (upstream b2TreeQueryCallbackFcn).
type TreeRayCastCallbackFcn ¶
type TreeRayCastCallbackFcn func(input *RayCastInput, proxyID int, userData uint64, context any) float64
TreeRayCastCallbackFcn receives clipped ray cast input for a proxy and returns the new ray fraction (upstream b2TreeRayCastCallbackFcn).
- return a value of 0 to terminate the ray cast
- return a value less than input.MaxFraction to clip the ray
- return a value of input.MaxFraction to continue without clipping
type TreeShapeCastCallbackFcn ¶
type TreeShapeCastCallbackFcn func(input *ShapeCastInput, proxyID int, userData uint64, context any) float64
TreeShapeCastCallbackFcn receives clipped shape cast input for a proxy and returns the new fraction (upstream b2TreeShapeCastCallbackFcn). The return value semantics match TreeRayCastCallbackFcn.
type TreeStats ¶
type TreeStats struct {
// NodeVisits is the number of internal nodes visited during the query.
NodeVisits int
// LeafVisits is the number of leaf nodes visited during the query.
LeafVisits int
}
TreeStats holds performance results returned by dynamic tree queries (upstream b2TreeStats).
type Vec2 ¶
type Vec2 struct {
X, Y float64
}
Vec2 is a 2D vector. It can represent a point or a free vector.
func AABBExtents ¶
AABBExtents returns the extents (half-widths) of the AABB.
func ClipVector ¶
func ClipVector(vector Vec2, planes []CollisionPlane) Vec2
ClipVector clips the velocity against the given collision planes (upstream b2ClipVector). Planes with zero push or ClipVelocity set to false are skipped.
func GetLengthAndNormalize ¶
GetLengthAndNormalize returns the unit vector of v (or the zero vector) and the length of v (upstream b2GetLengthAndNormalize with an out parameter).
func InvRotateVector ¶
InvRotateVector inverse-rotates a vector.
func InvTransformPoint ¶
InvTransformPoint inverse-transforms a point (e.g. world space to local space).
func Normalize ¶
Normalize converts a vector into a unit vector if possible, otherwise returns the zero vector.
func RightPerp ¶
RightPerp returns a right-pointing perpendicular vector, equivalent to CrossVS(v, 1).
func Solve22 ¶
Solve22 solves A * x = b, where b is a column vector. This is more efficient than computing the inverse in one-shot cases.
func TransformPoint ¶
TransformPoint transforms a point (e.g. local space to world space).
type Version ¶
Version mirrors b2Version from base.h.
func GetVersion ¶
func GetVersion() Version
GetVersion returns the current Box2D version (upstream b2GetVersion).
type WeldJointDef ¶
type WeldJointDef struct {
// Base joint definition
Base JointDef
// Linear stiffness expressed as Hertz (cycles per second). Use zero for maximum stiffness.
LinearHertz float64
// Angular stiffness as Hertz (cycles per second). Use zero for maximum stiffness.
AngularHertz float64
// Linear damping ratio, non-dimensional. Use 1 for critical damping.
LinearDampingRatio float64
// Linear damping ratio, non-dimensional. Use 1 for critical damping.
AngularDampingRatio float64
// contains filtered or unexported fields
}
WeldJointDef is a weld joint definition (upstream b2WeldJointDef). Connects two bodies together rigidly. This constraint provides springs to mimic soft-body simulation.
Note: the approximate solver in Box2D cannot hold many bodies together rigidly.
func DefaultWeldJointDef ¶
func DefaultWeldJointDef() WeldJointDef
DefaultWeldJointDef initializes a weld joint definition (upstream b2DefaultWeldJointDef).
type WheelJointDef ¶
type WheelJointDef struct {
// Base joint definition
Base JointDef
// Enable a linear spring along the local axis
EnableSpring bool
// Spring stiffness in Hertz
Hertz float64
// Spring damping ratio, non-dimensional
DampingRatio float64
// Enable/disable the joint linear limit
EnableLimit bool
// The lower translation limit
LowerTranslation float64
// The upper translation limit
UpperTranslation float64
// Enable/disable the joint rotational motor
EnableMotor bool
// The maximum motor torque, typically in newton-meters
MaxMotorTorque float64
// The desired motor speed in radians per second
MotorSpeed float64
// contains filtered or unexported fields
}
WheelJointDef is a wheel joint definition (upstream b2WheelJointDef). Body B is a wheel that may rotate freely and slide along the local x-axis in frame A. The joint translation is zero when the local frame origins coincide in world space.
func DefaultWheelJointDef ¶
func DefaultWheelJointDef() WheelJointDef
DefaultWheelJointDef initializes a wheel joint definition (upstream b2DefaultWheelJointDef).
type World ¶
type World struct {
// contains filtered or unexported fields
}
World manages all physics entities, dynamic simulation, and queries (upstream b2World). Create one with NewWorld.
func NewWorld ¶
NewWorld creates a world for rigid body simulation. A world contains bodies, shapes, and constraints. Deviation from upstream b2CreateWorld: this returns a *World instead of a b2WorldId into a global registry (see the file header).
func (*World) ApplyBodyAngularImpulse ¶
ApplyBodyAngularImpulse applies an angular impulse. The impulse is ignored if the body is not awake (upstream b2Body_ApplyAngularImpulse).
Warning: this should be used for one-shot impulses. If you need a steady torque, use a torque instead, which will work better with the sub-stepping solver.
func (*World) ApplyBodyForce ¶
ApplyBodyForce applies a force at a world point. If the force is not applied at the center of mass, it will generate a torque and affect the angular velocity. The force is ignored if the body is not awake (upstream b2Body_ApplyForce).
func (*World) ApplyBodyForceToCenter ¶
ApplyBodyForceToCenter applies a force to the center of mass. The force is ignored if the body is not awake (upstream b2Body_ApplyForceToCenter).
func (*World) ApplyBodyLinearImpulse ¶
ApplyBodyLinearImpulse applies an impulse at a point. This immediately modifies the velocity. It also modifies the angular velocity if the point of application is not at the center of mass. The impulse is ignored if the body is not awake (upstream b2Body_ApplyLinearImpulse).
Warning: this should be used for one-shot impulses. If you need a steady force, use a force instead, which will work better with the sub-stepping solver.
func (*World) ApplyBodyLinearImpulseToCenter ¶
ApplyBodyLinearImpulseToCenter applies an impulse to the center of mass. This immediately modifies the velocity. The impulse is ignored if the body is not awake (upstream b2Body_ApplyLinearImpulseToCenter).
Warning: this should be used for one-shot impulses. If you need a steady force, use a force instead, which will work better with the sub-stepping solver.
func (*World) ApplyBodyMassFromShapes ¶
ApplyBodyMassFromShapes updates the body mass data. This should be called if you have added or removed shapes without automatic mass computation, or if you have directly modified a shape's density (upstream b2Body_ApplyMassFromShapes).
func (*World) ApplyBodyTorque ¶
ApplyBodyTorque applies a torque. This affects the angular velocity without affecting the linear velocity. The torque is ignored if the body is not awake (upstream b2Body_ApplyTorque).
func (*World) ApplyShapeWind ¶
ApplyShapeWind applies a wind force to a shape considering its exposed perimeter and velocity (upstream b2Shape_ApplyWind).
https://en.wikipedia.org/wiki/Density_of_air https://www.engineeringtoolbox.com/wind-load-d_1775.html force = 0.5 * air_density * velocity^2 * area https://en.wikipedia.org/wiki/Lift_(force)
func (*World) AreShapeContactEventsEnabled ¶
AreShapeContactEventsEnabled reports whether contact events are enabled (upstream b2Shape_AreContactEventsEnabled).
func (*World) AreShapeHitEventsEnabled ¶
AreShapeHitEventsEnabled reports whether hit events are enabled (upstream b2Shape_AreHitEventsEnabled).
func (*World) AreShapePreSolveEventsEnabled ¶
AreShapePreSolveEventsEnabled reports whether pre-solve events are enabled (upstream b2Shape_ArePreSolveEventsEnabled).
func (*World) AreShapeSensorEventsEnabled ¶
AreShapeSensorEventsEnabled reports whether sensor events are enabled (upstream b2Shape_AreSensorEventsEnabled).
func (*World) AwakeBodyCount ¶
AwakeBodyCount returns the number of awake bodies (upstream b2World_GetAwakeBodyCount).
func (*World) BodyAngularDamping ¶
BodyAngularDamping returns the current angular damping (upstream b2Body_GetAngularDamping).
func (*World) BodyAngularVelocity ¶
BodyAngularVelocity returns the angular velocity of a body in radians per second (upstream b2Body_GetAngularVelocity).
func (*World) BodyContactCapacity ¶
BodyContactCapacity returns the maximum capacity required for retrieving all the touching contacts on a body (upstream b2Body_GetContactCapacity).
func (*World) BodyContactData ¶
func (w *World) BodyContactData(bodyID BodyID, contactData []ContactData) int
BodyContactData fills contactData with the touching contact data for a body, up to len(contactData) elements, and returns the number of elements stored (upstream b2Body_GetContactData).
func (*World) BodyEvents ¶
func (w *World) BodyEvents() BodyEvents
BodyEvents returns the body events for the current time step. The event data is transient — do not store references (upstream b2World_GetBodyEvents).
func (*World) BodyGravityScale ¶
BodyGravityScale returns the current gravity scale (upstream b2Body_GetGravityScale).
func (*World) BodyJointCount ¶
BodyJointCount returns the number of joints on this body (upstream b2Body_GetJointCount).
func (*World) BodyJoints ¶
BodyJoints fills jointArray with the joint ids for all joints on this body, up to len(jointArray), and returns the number of ids stored (upstream b2Body_GetJoints).
func (*World) BodyLinearDamping ¶
BodyLinearDamping returns the current linear damping (upstream b2Body_GetLinearDamping).
func (*World) BodyLinearVelocity ¶
BodyLinearVelocity returns the linear velocity of a body's center of mass, usually in meters per second (upstream b2Body_GetLinearVelocity).
func (*World) BodyLocalCenterOfMass ¶
BodyLocalCenterOfMass returns the center of mass position of the body in local space (upstream b2Body_GetLocalCenterOfMass).
func (*World) BodyLocalPoint ¶
BodyLocalPoint returns a local point on a body given a world point (upstream b2Body_GetLocalPoint).
func (*World) BodyLocalPointVelocity ¶
BodyLocalPointVelocity returns the linear velocity of a local point attached to a body, usually in meters per second (upstream b2Body_GetLocalPointVelocity).
func (*World) BodyLocalVector ¶
BodyLocalVector returns a local vector on a body given a world vector (upstream b2Body_GetLocalVector).
func (*World) BodyMass ¶
BodyMass returns the mass of the body, usually in kilograms (upstream b2Body_GetMass).
func (*World) BodyMassData ¶
BodyMassData returns the mass data for a body (upstream b2Body_GetMassData).
func (*World) BodyMotionLocks ¶
func (w *World) BodyMotionLocks(bodyID BodyID) MotionLocks
BodyMotionLocks returns the motion locks on this body (upstream b2Body_GetMotionLocks).
func (*World) BodyPosition ¶
BodyPosition returns the world position of a body. This is the location of the body origin (upstream b2Body_GetPosition).
func (*World) BodyRotation ¶
BodyRotation returns the world rotation of a body as a cosine/sine pair (upstream b2Body_GetRotation).
func (*World) BodyRotationalInertia ¶
BodyRotationalInertia returns the rotational inertia of the body, usually in kg*m^2 (upstream b2Body_GetRotationalInertia).
func (*World) BodyShapeCount ¶
BodyShapeCount returns the number of shapes on this body (upstream b2Body_GetShapeCount).
func (*World) BodyShapes ¶
BodyShapes fills shapeArray with the shape ids for all shapes on this body, up to len(shapeArray), and returns the number of ids stored (upstream b2Body_GetShapes).
func (*World) BodySleepThreshold ¶
BodySleepThreshold returns the sleep threshold, usually in meters per second (upstream b2Body_GetSleepThreshold).
func (*World) BodyTransform ¶
BodyTransform returns the world transform of a body (upstream b2Body_GetTransform).
func (*World) BodyType ¶
BodyType returns the body type: static, kinematic, or dynamic (upstream b2Body_GetType).
func (*World) BodyUserData ¶
BodyUserData returns the user data stored on a body (upstream b2Body_GetUserData).
func (*World) BodyWorldCenterOfMass ¶
BodyWorldCenterOfMass returns the center of mass position of the body in world space (upstream b2Body_GetWorldCenterOfMass).
func (*World) BodyWorldPoint ¶
BodyWorldPoint returns a world point on a body given a local point (upstream b2Body_GetWorldPoint).
func (*World) BodyWorldPointVelocity ¶
BodyWorldPointVelocity returns the linear velocity of a world point attached to a body, usually in meters per second (upstream b2Body_GetWorldPointVelocity).
func (*World) BodyWorldVector ¶
BodyWorldVector returns a world vector on a body given a local vector (upstream b2Body_GetWorldVector).
func (*World) CastMover ¶
func (w *World) CastMover(mover *Capsule, translation Vec2, filter QueryFilter) float64
CastMover casts a capsule mover through the world (upstream b2World_CastMover). This is a special shape cast that handles sliding along other shapes while reducing clipping.
func (*World) CastRay ¶
func (w *World) CastRay(origin, translation Vec2, filter QueryFilter, fcn CastResultFcn, context any) TreeStats
CastRay casts a ray into the world to collect shapes in the path of the ray (upstream b2World_CastRay). The callback function controls whether you get the closest point, any point, or n-points.
Note: the callback function may receive shapes in any order.
origin is the start point of the ray, translation the translation of the ray from the start point to the end point, filter contains bit flags to filter unwanted shapes from the results, fcn is a user implemented callback function and context a user context passed along to the callback. It returns the traversal performance counters.
func (*World) CastRayClosest ¶
func (w *World) CastRayClosest(origin, translation Vec2, filter QueryFilter) RayResult
CastRayClosest casts a ray into the world to collect the closest hit (upstream b2World_CastRayClosest). This is a convenience function that ignores initial overlap. It is less general than World.CastRay and does not allow for custom filtering.
func (*World) CastShape ¶
func (w *World) CastShape(proxy *ShapeProxy, translation Vec2, filter QueryFilter, fcn CastResultFcn, context any, ) TreeStats
CastShape casts a shape through the world (upstream b2World_CastShape). Similar to a ray cast except that a shape is cast instead of a point. See World.CastRay.
func (*World) ChainSegmentCount ¶
ChainSegmentCount returns the number of segments on this chain shape (upstream b2Chain_GetSegmentCount).
func (*World) ChainSegments ¶
ChainSegments fills segmentArray with the shape ids of the chain segments, up to len(segmentArray), and returns the number of ids stored (upstream b2Chain_GetSegments).
func (*World) ChainSurfaceMaterial ¶
func (w *World) ChainSurfaceMaterial(chainID ChainID, segmentIndex int) SurfaceMaterial
ChainSurfaceMaterial returns the material on a chain shape for the given segment index (upstream b2Chain_GetSurfaceMaterial).
func (*World) ChainSurfaceMaterialCount ¶
ChainSurfaceMaterialCount returns the number of materials on a chain shape (upstream b2Chain_GetSurfaceMaterialCount).
func (*World) ClearBodyForces ¶
ClearBodyForces clears the accumulated force and torque on a body (upstream b2Body_ClearForces).
func (*World) CollideMover ¶
func (w *World) CollideMover(mover *Capsule, filter QueryFilter, fcn PlaneResultFcn, context any)
CollideMover collides a capsule mover with the world, gathering collision planes that can be fed to SolvePlanes (upstream b2World_CollideMover). Useful for kinematic character movement.
It is tempting to use a shape proxy for the mover, but this makes handling deep overlap difficult and the generality may not be worth it.
func (*World) ComputeBodyAABB ¶
ComputeBodyAABB returns the current world AABB that contains all the attached shapes. Note that this may not encompass the body origin. If there are no shapes attached then the returned AABB is empty and centered on the body origin (upstream b2Body_ComputeAABB).
func (*World) ContactData ¶
func (w *World) ContactData(contactID ContactID) ContactData
ContactData returns the contact data for a contact id (upstream b2Contact_GetData).
func (*World) ContactEvents ¶
func (w *World) ContactEvents() ContactEvents
ContactEvents returns the contact events for the current time step. The event data is transient — do not store references (upstream b2World_GetContactEvents).
func (*World) ContactRecycleDistance ¶
ContactRecycleDistance returns the contact recycle distance (upstream b2World_GetContactRecycleDistance).
func (*World) CreateBody ¶
CreateBody creates a rigid body given a definition (upstream b2CreateBody). No reference to the definition is retained. So you can create the definition on the stack and pass it as a pointer.
Warning: this function is locked during callbacks.
func (*World) CreateCapsuleShape ¶
CreateCapsuleShape creates a capsule shape and attaches it to a body. The shape definition and geometry are fully cloned. Contacts are not created until the next time step (upstream b2CreateCapsuleShape).
func (*World) CreateChain ¶
CreateChain creates a chain shape (upstream b2CreateChain).
func (*World) CreateCircleShape ¶
CreateCircleShape creates a circle shape and attaches it to a body. The shape definition and geometry are fully cloned. Contacts are not created until the next time step (upstream b2CreateCircleShape).
func (*World) CreateDistanceJoint ¶
func (w *World) CreateDistanceJoint(def *DistanceJointDef) JointID
CreateDistanceJoint creates a distance joint (upstream b2CreateDistanceJoint).
func (*World) CreateFilterJoint ¶
func (w *World) CreateFilterJoint(def *FilterJointDef) JointID
CreateFilterJoint creates a filter joint. A filter joint disables collision between the attached bodies and has no solve work (upstream b2CreateFilterJoint).
func (*World) CreateMotorJoint ¶
func (w *World) CreateMotorJoint(def *MotorJointDef) JointID
CreateMotorJoint creates a motor joint (upstream b2CreateMotorJoint).
func (*World) CreatePolygonShape ¶
CreatePolygonShape creates a polygon shape and attaches it to a body. The shape definition and geometry are fully cloned. Contacts are not created until the next time step (upstream b2CreatePolygonShape).
func (*World) CreatePrismaticJoint ¶
func (w *World) CreatePrismaticJoint(def *PrismaticJointDef) JointID
CreatePrismaticJoint creates a prismatic (slider) joint (upstream b2CreatePrismaticJoint).
func (*World) CreateRevoluteJoint ¶
func (w *World) CreateRevoluteJoint(def *RevoluteJointDef) JointID
CreateRevoluteJoint creates a revolute (hinge) joint (upstream b2CreateRevoluteJoint).
func (*World) CreateSegmentShape ¶
CreateSegmentShape creates a line segment shape and attaches it to a body. The shape definition and geometry are fully cloned. Contacts are not created until the next time step (upstream b2CreateSegmentShape).
func (*World) CreateWeldJoint ¶
func (w *World) CreateWeldJoint(def *WeldJointDef) JointID
CreateWeldJoint creates a weld joint (upstream b2CreateWeldJoint).
func (*World) CreateWheelJoint ¶
func (w *World) CreateWheelJoint(def *WheelJointDef) JointID
CreateWheelJoint creates a wheel joint (upstream b2CreateWheelJoint).
func (*World) Destroy ¶
func (w *World) Destroy()
Destroy destroys the world and all its contents (upstream b2DestroyWorld). Ids created from this world become invalid.
func (*World) DestroyBody ¶
DestroyBody destroys a rigid body given an id. This destroys all shapes and joints attached to the body. Do not keep references to the associated shapes and joints (upstream b2DestroyBody).
func (*World) DestroyChain ¶
DestroyChain destroys a chain shape (upstream b2DestroyChain).
func (*World) DestroyJoint ¶
DestroyJoint destroys a joint. wakeAttached wakes the attached bodies (upstream b2DestroyJoint).
func (*World) DestroyShape ¶
DestroyShape destroys a shape. You may defer the body mass update which can improve performance if several shapes on a body are destroyed at once (upstream b2DestroyShape).
func (*World) DisableBody ¶
DisableBody disables a body by removing it completely from the simulation. This is expensive (upstream b2Body_Disable).
Disabling a body requires a lot of detailed bookkeeping, but it is a valuable feature. The most challenging aspect is that joints may connect to bodies that are not disabled.
func (*World) DistanceJointCurrentLength ¶
DistanceJointCurrentLength returns the current length of a distance joint (upstream b2DistanceJoint_GetCurrentLength).
func (*World) DistanceJointLength ¶
DistanceJointLength returns the rest length of a distance joint (upstream b2DistanceJoint_GetLength).
func (*World) DistanceJointMaxLength ¶
DistanceJointMaxLength returns the maximum distance joint length (upstream b2DistanceJoint_GetMaxLength).
func (*World) DistanceJointMaxMotorForce ¶
DistanceJointMaxMotorForce returns the maximum motor force, usually in Newtons (upstream b2DistanceJoint_GetMaxMotorForce).
func (*World) DistanceJointMinLength ¶
DistanceJointMinLength returns the minimum distance joint length (upstream b2DistanceJoint_GetMinLength).
func (*World) DistanceJointMotorForce ¶
DistanceJointMotorForce returns the current motor force, usually in Newtons (upstream b2DistanceJoint_GetMotorForce).
func (*World) DistanceJointMotorSpeed ¶
DistanceJointMotorSpeed returns the distance joint motor speed (upstream b2DistanceJoint_GetMotorSpeed).
func (*World) DistanceJointSpringDampingRatio ¶
DistanceJointSpringDampingRatio returns the spring damping ratio (upstream b2DistanceJoint_GetSpringDampingRatio).
func (*World) DistanceJointSpringForceRange ¶
DistanceJointSpringForceRange returns the force range for the spring as (lowerForce, upperForce) (upstream b2DistanceJoint_GetSpringForceRange).
func (*World) DistanceJointSpringHertz ¶
DistanceJointSpringHertz returns the spring Hertz (upstream b2DistanceJoint_GetSpringHertz).
func (*World) Draw ¶
Draw calls the user-supplied debug draw callbacks for every shape, contact, mass center and island that overlaps draw.DrawingBounds (upstream b2World_Draw).
Shapes are gathered with a broad-phase query per body type, which sets one bit per touched body; the second pass then walks the body bit set so each body is visited exactly once regardless of how many shapes it owns.
func (*World) EnableBody ¶
EnableBody enables a body by adding it to the simulation. This is expensive (upstream b2Body_Enable).
func (*World) EnableBodyContactEvents ¶
EnableBodyContactEvents enables/disables contact events on all shapes (upstream b2Body_EnableContactEvents).
Warning: changing this at runtime may cause mismatched begin/end touch events.
func (*World) EnableBodyHitEvents ¶
EnableBodyHitEvents enables/disables hit events on all shapes (upstream b2Body_EnableHitEvents).
func (*World) EnableBodySleep ¶
EnableBodySleep enables or disables sleeping for this body. If sleep is disabled the body will wake (upstream b2Body_EnableSleep).
func (*World) EnableContinuous ¶
EnableContinuous enables/disables continuous collision between dynamic and static bodies. Generally you should keep continuous collision enabled to prevent fast moving objects from going through static objects. The performance gain from disabling continuous collision is minor (upstream b2World_EnableContinuous).
func (*World) EnableDistanceJointLimit ¶
EnableDistanceJointLimit enables/disables the distance joint limit (upstream b2DistanceJoint_EnableLimit).
func (*World) EnableDistanceJointMotor ¶
EnableDistanceJointMotor enables/disables the distance joint motor (upstream b2DistanceJoint_EnableMotor).
func (*World) EnableDistanceJointSpring ¶
EnableDistanceJointSpring enables/disables the distance joint spring. When disabled the distance joint is rigid (upstream b2DistanceJoint_EnableSpring).
func (*World) EnablePrismaticJointLimit ¶
EnablePrismaticJointLimit enables/disables the prismatic joint limit (upstream b2PrismaticJoint_EnableLimit).
func (*World) EnablePrismaticJointMotor ¶
EnablePrismaticJointMotor enables/disables the prismatic joint motor (upstream b2PrismaticJoint_EnableMotor).
func (*World) EnablePrismaticJointSpring ¶
EnablePrismaticJointSpring enables/disables the prismatic joint spring (upstream b2PrismaticJoint_EnableSpring).
func (*World) EnableRevoluteJointLimit ¶
EnableRevoluteJointLimit enables/disables the revolute joint limit (upstream b2RevoluteJoint_EnableLimit).
func (*World) EnableRevoluteJointMotor ¶
EnableRevoluteJointMotor enables/disables the revolute joint motor (upstream b2RevoluteJoint_EnableMotor).
func (*World) EnableRevoluteJointSpring ¶
EnableRevoluteJointSpring enables/disables the revolute joint spring (upstream b2RevoluteJoint_EnableSpring).
func (*World) EnableShapeContactEvents ¶
EnableShapeContactEvents enables contact events for this shape (upstream b2Shape_EnableContactEvents).
Warning: changing this at run-time may lead to lost begin/end events.
func (*World) EnableShapeHitEvents ¶
EnableShapeHitEvents enables contact hit events for this shape (upstream b2Shape_EnableHitEvents).
func (*World) EnableShapePreSolveEvents ¶
EnableShapePreSolveEvents enables pre-solve contact events for this shape. Only applies to dynamic bodies. These are expensive (upstream b2Shape_EnablePreSolveEvents).
func (*World) EnableShapeSensorEvents ¶
EnableShapeSensorEvents enables sensor events for this shape (upstream b2Shape_EnableSensorEvents).
func (*World) EnableSleeping ¶
EnableSleeping enables/disables sleep. If your application does not need sleeping, you can gain some performance by disabling sleep completely at the world level (upstream b2World_EnableSleeping).
func (*World) EnableSpeculative ¶
EnableSpeculative enables/disables speculative contacts. Advanced feature for testing (upstream b2World_EnableSpeculative).
func (*World) EnableWarmStarting ¶
EnableWarmStarting enables/disables constraint warm starting. Advanced feature for testing. Disabling warm starting greatly reduces stability and provides no performance gain (upstream b2World_EnableWarmStarting).
func (*World) EnableWheelJointLimit ¶
EnableWheelJointLimit enables/disables the wheel joint limit (upstream b2WheelJoint_EnableLimit).
func (*World) EnableWheelJointMotor ¶
EnableWheelJointMotor enables/disables the wheel joint motor (upstream b2WheelJoint_EnableMotor).
func (*World) EnableWheelJointSpring ¶
EnableWheelJointSpring enables/disables the wheel joint spring (upstream b2WheelJoint_EnableSpring).
func (*World) Explode ¶
func (w *World) Explode(explosionDef *ExplosionDef)
Explode applies a radial explosion (upstream b2World_Explode).
The explosion only affects dynamic body shapes whose category bits pass the definition mask bits. The impulse is proportional to the shape perimeter projected onto the plane perpendicular to the explosion direction, so larger shapes receive larger impulses. A negative ImpulsePerLength implodes.
func (*World) HitEventThreshold ¶
HitEventThreshold returns the hit event speed threshold, usually in meters per second (upstream b2World_GetHitEventThreshold).
func (*World) ID ¶
ID returns the WorldID of this world. This replaces the b2WorldId returned by upstream b2CreateWorld (see the file header for the registry deviation).
func (*World) IsBodyAwake ¶
IsBodyAwake reports whether this body is awake (upstream b2Body_IsAwake).
func (*World) IsBodyBullet ¶
IsBodyBullet reports whether this body is a bullet (upstream b2Body_IsBullet).
func (*World) IsBodyEnabled ¶
IsBodyEnabled reports whether this body is enabled (upstream b2Body_IsEnabled).
func (*World) IsBodySleepEnabled ¶
IsBodySleepEnabled reports whether this body can fall asleep (upstream b2Body_IsSleepEnabled).
func (*World) IsBodyValid ¶
IsBodyValid reports whether a body id is valid in this world. Can be used to detect orphaned ids. Provides validation for up to 64K allocations (upstream b2Body_IsValid).
func (*World) IsChainValid ¶
IsChainValid reports whether a chain id is valid in this world (upstream b2Chain_IsValid).
func (*World) IsContactValid ¶
IsContactValid reports whether a contact id is valid in this world (upstream b2Contact_IsValid).
func (*World) IsContinuousEnabled ¶
IsContinuousEnabled reports whether continuous collision is enabled (upstream b2World_IsContinuousEnabled).
func (*World) IsDistanceJointLimitEnabled ¶
IsDistanceJointLimitEnabled reports whether the distance joint limit is enabled (upstream b2DistanceJoint_IsLimitEnabled).
func (*World) IsDistanceJointMotorEnabled ¶
IsDistanceJointMotorEnabled reports whether the distance joint motor is enabled (upstream b2DistanceJoint_IsMotorEnabled).
func (*World) IsDistanceJointSpringEnabled ¶
IsDistanceJointSpringEnabled reports whether the distance joint spring is enabled (upstream b2DistanceJoint_IsSpringEnabled).
func (*World) IsJointValid ¶
IsJointValid reports whether a joint id is valid in this world (upstream b2Joint_IsValid).
func (*World) IsPrismaticJointLimitEnabled ¶
IsPrismaticJointLimitEnabled reports whether the prismatic joint limit is enabled (upstream b2PrismaticJoint_IsLimitEnabled).
func (*World) IsPrismaticJointMotorEnabled ¶
IsPrismaticJointMotorEnabled reports whether the prismatic joint motor is enabled (upstream b2PrismaticJoint_IsMotorEnabled).
func (*World) IsPrismaticJointSpringEnabled ¶
IsPrismaticJointSpringEnabled reports whether the prismatic joint spring is enabled (upstream b2PrismaticJoint_IsSpringEnabled).
func (*World) IsRevoluteJointLimitEnabled ¶
IsRevoluteJointLimitEnabled reports whether the revolute joint limit is enabled (upstream b2RevoluteJoint_IsLimitEnabled).
func (*World) IsRevoluteJointMotorEnabled ¶
IsRevoluteJointMotorEnabled reports whether the revolute joint motor is enabled (upstream b2RevoluteJoint_IsMotorEnabled).
func (*World) IsRevoluteJointSpringEnabled ¶
IsRevoluteJointSpringEnabled reports whether the revolute angular spring is enabled (upstream b2RevoluteJoint_IsSpringEnabled).
func (*World) IsShapeSensor ¶
IsShapeSensor reports whether a shape is a sensor (upstream b2Shape_IsSensor).
func (*World) IsShapeValid ¶
IsShapeValid reports whether a shape id is valid in this world (upstream b2Shape_IsValid).
func (*World) IsSleepingEnabled ¶
IsSleepingEnabled reports whether body sleeping is enabled (upstream b2World_IsSleepingEnabled).
func (*World) IsWarmStartingEnabled ¶
IsWarmStartingEnabled reports whether constraint warm starting is enabled (upstream b2World_IsWarmStartingEnabled).
func (*World) IsWheelJointLimitEnabled ¶
IsWheelJointLimitEnabled reports whether the wheel joint limit is enabled (upstream b2WheelJoint_IsLimitEnabled).
func (*World) IsWheelJointMotorEnabled ¶
IsWheelJointMotorEnabled reports whether the wheel joint motor is enabled (upstream b2WheelJoint_IsMotorEnabled).
func (*World) IsWheelJointSpringEnabled ¶
IsWheelJointSpringEnabled reports whether the wheel joint spring is enabled (upstream b2WheelJoint_IsSpringEnabled).
func (*World) IsWorldValid ¶
IsWorldValid reports whether a world id references this world and is not stale (upstream b2World_IsValid; see the file header for the registry deviation).
func (*World) JointAngularSeparation ¶
JointAngularSeparation returns the current angular separation error for this joint. Does not consider admissible movement such as the target angle of a spring (upstream b2Joint_GetAngularSeparation).
func (*World) JointBodyA ¶
JointBodyA returns body A id on a joint (upstream b2Joint_GetBodyA).
func (*World) JointBodyB ¶
JointBodyB returns body B id on a joint (upstream b2Joint_GetBodyB).
func (*World) JointCollideConnected ¶
JointCollideConnected reports whether the connected bodies may collide (upstream b2Joint_GetCollideConnected).
func (*World) JointConstraintForce ¶
JointConstraintForce returns the current constraint force for this joint. Usually in Newtons (upstream b2Joint_GetConstraintForce).
func (*World) JointConstraintTorque ¶
JointConstraintTorque returns the current constraint torque for this joint. Usually in Newton * meters (upstream b2Joint_GetConstraintTorque).
func (*World) JointConstraintTuning ¶
JointConstraintTuning returns the joint constraint tuning as (hertz, dampingRatio) (upstream b2Joint_GetConstraintTuning).
func (*World) JointEvents ¶
func (w *World) JointEvents() JointEvents
JointEvents returns the joint events for the current time step. The event data is transient — do not store references (upstream b2World_GetJointEvents).
func (*World) JointForceThreshold ¶
JointForceThreshold returns the force threshold for joint events (upstream b2Joint_GetForceThreshold).
func (*World) JointLinearSeparation ¶
JointLinearSeparation returns the current linear separation error for this joint. Does not consider admissible movement such as the target length of a spring (upstream b2Joint_GetLinearSeparation).
func (*World) JointLocalFrameA ¶
JointLocalFrameA returns the local frame on bodyA (upstream b2Joint_GetLocalFrameA).
func (*World) JointLocalFrameB ¶
JointLocalFrameB returns the local frame on bodyB (upstream b2Joint_GetLocalFrameB).
func (*World) JointTorqueThreshold ¶
JointTorqueThreshold returns the torque threshold for joint events (upstream b2Joint_GetTorqueThreshold).
func (*World) JointUserData ¶
JointUserData returns the user data on a joint (upstream b2Joint_GetUserData).
func (*World) MaximumLinearSpeed ¶
MaximumLinearSpeed returns the maximum linear speed. Usually in meters per second (upstream b2World_GetMaximumLinearSpeed).
func (*World) MotorJointAngularDampingRatio ¶
MotorJointAngularDampingRatio returns the angular spring damping ratio (upstream b2MotorJoint_GetAngularDampingRatio).
func (*World) MotorJointAngularHertz ¶
MotorJointAngularHertz returns the angular spring stiffness in Hertz (upstream b2MotorJoint_GetAngularHertz).
func (*World) MotorJointAngularVelocity ¶
MotorJointAngularVelocity returns the desired relative angular velocity in radians per second (upstream b2MotorJoint_GetAngularVelocity).
func (*World) MotorJointLinearDampingRatio ¶
MotorJointLinearDampingRatio returns the linear spring damping ratio (upstream b2MotorJoint_GetLinearDampingRatio).
func (*World) MotorJointLinearHertz ¶
MotorJointLinearHertz returns the linear spring stiffness in Hertz (upstream b2MotorJoint_GetLinearHertz).
func (*World) MotorJointLinearVelocity ¶
MotorJointLinearVelocity returns the desired relative linear velocity in meters per second (upstream b2MotorJoint_GetLinearVelocity).
func (*World) MotorJointMaxSpringForce ¶
MotorJointMaxSpringForce returns the maximum spring force in Newtons (upstream b2MotorJoint_GetMaxSpringForce).
func (*World) MotorJointMaxSpringTorque ¶
MotorJointMaxSpringTorque returns the maximum spring torque in Newton * meters (upstream b2MotorJoint_GetMaxSpringTorque).
func (*World) MotorJointMaxVelocityForce ¶
MotorJointMaxVelocityForce returns the maximum velocity motor force (upstream b2MotorJoint_GetMaxVelocityForce).
func (*World) MotorJointMaxVelocityTorque ¶
MotorJointMaxVelocityTorque returns the maximum velocity motor torque (upstream b2MotorJoint_GetMaxVelocityTorque).
func (*World) OverlapAABB ¶
func (w *World) OverlapAABB(aabb AABB, filter QueryFilter, fcn OverlapResultFcn, context any) TreeStats
OverlapAABB performs an overlap test for all shapes that *potentially* overlap the provided AABB (upstream b2World_OverlapAABB).
func (*World) OverlapShape ¶
func (w *World) OverlapShape(proxy *ShapeProxy, filter QueryFilter, fcn OverlapResultFcn, context any) TreeStats
OverlapShape performs an overlap test for all shapes that overlap the provided shape proxy (upstream b2World_OverlapShape).
func (*World) PrismaticJointLowerLimit ¶
PrismaticJointLowerLimit returns the lower joint limit in meters (upstream b2PrismaticJoint_GetLowerLimit).
func (*World) PrismaticJointMaxMotorForce ¶
PrismaticJointMaxMotorForce returns the prismatic joint maximum motor force (upstream b2PrismaticJoint_GetMaxMotorForce).
func (*World) PrismaticJointMotorForce ¶
PrismaticJointMotorForce returns the current motor force, usually in Newtons (upstream b2PrismaticJoint_GetMotorForce).
func (*World) PrismaticJointMotorSpeed ¶
PrismaticJointMotorSpeed returns the prismatic joint motor speed, usually in meters per second (upstream b2PrismaticJoint_GetMotorSpeed).
func (*World) PrismaticJointSpeed ¶
PrismaticJointSpeed returns the current joint translation speed, usually in meters per second (upstream b2PrismaticJoint_GetSpeed).
func (*World) PrismaticJointSpringDampingRatio ¶
PrismaticJointSpringDampingRatio returns the prismatic joint spring damping ratio (upstream b2PrismaticJoint_GetSpringDampingRatio).
func (*World) PrismaticJointSpringHertz ¶
PrismaticJointSpringHertz returns the prismatic joint spring stiffness in Hertz (upstream b2PrismaticJoint_GetSpringHertz).
func (*World) PrismaticJointTargetTranslation ¶
PrismaticJointTargetTranslation returns the prismatic joint spring target translation in meters (upstream b2PrismaticJoint_GetTargetTranslation).
func (*World) PrismaticJointTranslation ¶
PrismaticJointTranslation returns the current joint translation, usually in meters (upstream b2PrismaticJoint_GetTranslation).
func (*World) PrismaticJointUpperLimit ¶
PrismaticJointUpperLimit returns the upper joint limit in meters (upstream b2PrismaticJoint_GetUpperLimit).
func (*World) Profile ¶
Profile returns the current world performance profile (upstream b2World_GetProfile).
func (*World) RebuildStaticTree ¶
func (w *World) RebuildStaticTree()
RebuildStaticTree rebuilds the static broad-phase tree. This is a slow operation used when many static shapes have been created or modified (upstream b2World_RebuildStaticTree).
func (*World) RestitutionThreshold ¶
RestitutionThreshold returns the restitution speed threshold, usually in meters per second (upstream b2World_GetRestitutionThreshold).
func (*World) RevoluteJointAngle ¶
RevoluteJointAngle returns the current joint angle in radians relative to the reference angle (upstream b2RevoluteJoint_GetAngle).
func (*World) RevoluteJointLowerLimit ¶
RevoluteJointLowerLimit returns the lower joint limit in radians (upstream b2RevoluteJoint_GetLowerLimit).
func (*World) RevoluteJointMaxMotorTorque ¶
RevoluteJointMaxMotorTorque returns the revolute joint maximum motor torque (upstream b2RevoluteJoint_GetMaxMotorTorque).
func (*World) RevoluteJointMotorSpeed ¶
RevoluteJointMotorSpeed returns the revolute joint motor speed in radians per second (upstream b2RevoluteJoint_GetMotorSpeed).
func (*World) RevoluteJointMotorTorque ¶
RevoluteJointMotorTorque returns the current motor torque, usually in Newton * meters (upstream b2RevoluteJoint_GetMotorTorque).
func (*World) RevoluteJointSpringDampingRatio ¶
RevoluteJointSpringDampingRatio returns the revolute joint spring damping ratio (upstream b2RevoluteJoint_GetSpringDampingRatio).
func (*World) RevoluteJointSpringHertz ¶
RevoluteJointSpringHertz returns the revolute joint spring stiffness in Hertz (upstream b2RevoluteJoint_GetSpringHertz).
func (*World) RevoluteJointTargetAngle ¶
RevoluteJointTargetAngle returns the revolute joint spring target angle in radians (upstream b2RevoluteJoint_GetTargetAngle).
func (*World) RevoluteJointUpperLimit ¶
RevoluteJointUpperLimit returns the upper joint limit in radians (upstream b2RevoluteJoint_GetUpperLimit).
func (*World) SensorEvents ¶
func (w *World) SensorEvents() SensorEvents
SensorEvents returns the sensor events for the current time step. The event data is transient — do not store references (upstream b2World_GetSensorEvents). The returned slices are valid until the next Step; end events come from the previous end-event buffer, which Step swaps after publishing.
func (*World) SetBodyAngularDamping ¶
SetBodyAngularDamping adjusts the angular damping. Normally this is set in BodyDef before creation (upstream b2Body_SetAngularDamping).
func (*World) SetBodyAngularVelocity ¶
SetBodyAngularVelocity sets the angular velocity of a body in radians per second (upstream b2Body_SetAngularVelocity).
func (*World) SetBodyAwake ¶
SetBodyAwake wakes a body from sleep, or puts it to sleep. Putting a body to sleep will put the entire island of bodies touching this body to sleep, which can be expensive and possibly unintuitive (upstream b2Body_SetAwake).
func (*World) SetBodyBullet ¶
SetBodyBullet sets this body to be a bullet. A bullet does continuous collision detection against dynamic bodies (but not other bullets) (upstream b2Body_SetBullet).
func (*World) SetBodyGravityScale ¶
SetBodyGravityScale adjusts the gravity scale. Normally this is set in BodyDef before creation (upstream b2Body_SetGravityScale).
func (*World) SetBodyLinearDamping ¶
SetBodyLinearDamping adjusts the linear damping. Normally this is set in BodyDef before creation (upstream b2Body_SetLinearDamping).
func (*World) SetBodyLinearVelocity ¶
SetBodyLinearVelocity sets the linear velocity of a body, usually in meters per second (upstream b2Body_SetLinearVelocity).
func (*World) SetBodyMassData ¶
SetBodyMassData overrides the body's mass properties. Normally this is computed automatically using the shape geometry and density. This information is lost if a shape is added or removed or if the body type changes (upstream b2Body_SetMassData).
func (*World) SetBodyMotionLocks ¶
func (w *World) SetBodyMotionLocks(bodyID BodyID, locks MotionLocks)
SetBodyMotionLocks sets the motion locks on this body (upstream b2Body_SetMotionLocks).
func (*World) SetBodyName ¶
SetBodyName sets the body name, up to 31 bytes (upstream b2Body_SetName).
func (*World) SetBodySleepThreshold ¶
SetBodySleepThreshold sets the sleep threshold, usually in meters per second (upstream b2Body_SetSleepThreshold).
func (*World) SetBodyTargetTransform ¶
func (w *World) SetBodyTargetTransform(bodyID BodyID, target Transform, timeStep float64, wake bool)
SetBodyTargetTransform sets the velocity to reach the given transform after a given time step. The result will be close but maybe not exact. This makes it difficult to push a body that is connected with joints or in contact with heavy bodies (upstream b2Body_SetTargetTransform).
func (*World) SetBodyTransform ¶
SetBodyTransform sets the world transform of a body. This acts as a teleport and is fairly expensive.
Note: generally you should create a body with the intended transform. (upstream b2Body_SetTransform).
func (*World) SetBodyType ¶
SetBodyType changes the body type. This is an expensive operation. This automatically updates the mass properties regardless of the automatic mass setting (upstream b2Body_SetType).
This should follow similar steps as you would get destroying and recreating the body, shapes, and joints. Contacts are difficult to preserve because the broad-phase pairs change, so upstream just destroys them.
Revised steps (upstream comment):
- Skip disabled bodies
- Destroy all contacts on the body
- Wake the body
- For all joints attached to the body - wake attached bodies - remove from island - move to static set temporarily
- Change the body type and transfer the body
- If the body was static - create an island for the body Else if the body is becoming static - remove it from the island
- For all joints - if either body is non-static - link into island - transfer to constraint graph
- For all shapes - Destroy proxy in old tree - Create proxy in new tree
Notes:
- the implementation below tries to minimize the number of predicates, so some operations may have no effect, such as transferring a joint to the same set
func (*World) SetBodyUserData ¶
SetBodyUserData sets the user data on a body (upstream b2Body_SetUserData).
func (*World) SetChainSurfaceMaterial ¶
func (w *World) SetChainSurfaceMaterial(chainID ChainID, material SurfaceMaterial, materialIndex int)
SetChainSurfaceMaterial sets the material on a chain shape at the given index (upstream b2Chain_SetSurfaceMaterial).
func (*World) SetContactRecycleDistance ¶
SetContactRecycleDistance sets the contact recycle distance (upstream b2World_SetContactRecycleDistance).
func (*World) SetContactTuning ¶
SetContactTuning adjusts contact tuning parameters: hertz is the contact stiffness (cycles per second), dampingRatio the contact bounciness with 1 being critical damping (non-dimensional), and pushSpeed the maximum contact constraint push out speed (meters per second) (upstream b2World_SetContactTuning).
Note: advanced feature.
func (*World) SetCustomFilterCallback ¶
func (w *World) SetCustomFilterCallback(fcn CustomFilterFcn, ctx any)
SetCustomFilterCallback sets the custom filter callback. This is optional (upstream b2World_SetCustomFilterCallback).
func (*World) SetDistanceJointLength ¶
SetDistanceJointLength sets the rest length of a distance joint (upstream b2DistanceJoint_SetLength).
func (*World) SetDistanceJointLengthRange ¶
SetDistanceJointLengthRange sets the minimum and maximum length parameters of a distance joint (upstream b2DistanceJoint_SetLengthRange).
func (*World) SetDistanceJointMaxMotorForce ¶
SetDistanceJointMaxMotorForce sets the maximum motor force, usually in Newtons (upstream b2DistanceJoint_SetMaxMotorForce).
func (*World) SetDistanceJointMotorSpeed ¶
SetDistanceJointMotorSpeed sets the distance joint motor speed, usually in meters per second (upstream b2DistanceJoint_SetMotorSpeed).
func (*World) SetDistanceJointSpringDampingRatio ¶
SetDistanceJointSpringDampingRatio sets the spring damping ratio, non-dimensional (upstream b2DistanceJoint_SetSpringDampingRatio).
func (*World) SetDistanceJointSpringForceRange ¶
SetDistanceJointSpringForceRange sets the force range for the spring (upstream b2DistanceJoint_SetSpringForceRange).
func (*World) SetDistanceJointSpringHertz ¶
SetDistanceJointSpringHertz sets the spring stiffness in Hertz (upstream b2DistanceJoint_SetSpringHertz).
func (*World) SetFrictionCallback ¶
func (w *World) SetFrictionCallback(callback FrictionCallback)
SetFrictionCallback sets the friction callback. Passing nil restores the default mixing rule sqrt(frictionA * frictionB) (upstream b2World_SetFrictionCallback).
func (*World) SetGravity ¶
SetGravity sets the gravity vector for the entire world. Box2D has no up-vector. This is usually in m/s^2 (upstream b2World_SetGravity).
Note: this does not wake sleeping bodies.
func (*World) SetHitEventThreshold ¶
SetHitEventThreshold adjusts the hit event threshold, usually in meters per second (upstream b2World_SetHitEventThreshold).
func (*World) SetJointCollideConnected ¶
SetJointCollideConnected toggles collision between connected bodies (upstream b2Joint_SetCollideConnected).
Note: enabling collision may add contacts on the next broad-phase update; disabling collision destroys the existing contacts between the bodies.
func (*World) SetJointConstraintTuning ¶
SetJointConstraintTuning sets the joint constraint tuning. Advanced feature. hertz is the stiffness in cycles per second (use zero for the most rigid behavior), dampingRatio the non-dimensional damping (one is critical damping) (upstream b2Joint_SetConstraintTuning).
func (*World) SetJointForceThreshold ¶
SetJointForceThreshold sets the force threshold for joint events, usually in Newtons (upstream b2Joint_SetForceThreshold).
func (*World) SetJointLocalFrameA ¶
SetJointLocalFrameA sets the local frame on bodyA (upstream b2Joint_SetLocalFrameA).
func (*World) SetJointLocalFrameB ¶
SetJointLocalFrameB sets the local frame on bodyB (upstream b2Joint_SetLocalFrameB).
func (*World) SetJointTorqueThreshold ¶
SetJointTorqueThreshold sets the torque threshold for joint events, usually in Newton * meters (upstream b2Joint_SetTorqueThreshold).
func (*World) SetJointUserData ¶
SetJointUserData sets the user data on a joint (upstream b2Joint_SetUserData).
func (*World) SetMaximumLinearSpeed ¶
SetMaximumLinearSpeed sets the maximum linear speed. Usually in meters per second (upstream b2World_SetMaximumLinearSpeed).
func (*World) SetMotorJointAngularDampingRatio ¶
SetMotorJointAngularDampingRatio sets the angular spring damping ratio, non-dimensional (upstream b2MotorJoint_SetAngularDampingRatio).
func (*World) SetMotorJointAngularHertz ¶
SetMotorJointAngularHertz sets the angular spring stiffness in Hertz used for position control (upstream b2MotorJoint_SetAngularHertz).
func (*World) SetMotorJointAngularVelocity ¶
SetMotorJointAngularVelocity sets the desired relative angular velocity in radians per second (upstream b2MotorJoint_SetAngularVelocity).
func (*World) SetMotorJointLinearDampingRatio ¶
SetMotorJointLinearDampingRatio sets the linear spring damping ratio, non-dimensional (upstream b2MotorJoint_SetLinearDampingRatio).
func (*World) SetMotorJointLinearHertz ¶
SetMotorJointLinearHertz sets the linear spring stiffness in Hertz used for position control (upstream b2MotorJoint_SetLinearHertz).
func (*World) SetMotorJointLinearVelocity ¶
SetMotorJointLinearVelocity sets the desired relative linear velocity in meters per second (upstream b2MotorJoint_SetLinearVelocity).
func (*World) SetMotorJointMaxSpringForce ¶
SetMotorJointMaxSpringForce sets the maximum spring force in Newtons (upstream b2MotorJoint_SetMaxSpringForce).
func (*World) SetMotorJointMaxSpringTorque ¶
SetMotorJointMaxSpringTorque sets the maximum spring torque in Newton * meters (upstream b2MotorJoint_SetMaxSpringTorque).
func (*World) SetMotorJointMaxVelocityForce ¶
SetMotorJointMaxVelocityForce sets the maximum force the velocity motor may apply, usually in Newtons (upstream b2MotorJoint_SetMaxVelocityForce).
func (*World) SetMotorJointMaxVelocityTorque ¶
SetMotorJointMaxVelocityTorque sets the maximum torque the velocity motor may apply, usually in Newton * meters (upstream b2MotorJoint_SetMaxVelocityTorque).
func (*World) SetPreSolveCallback ¶
func (w *World) SetPreSolveCallback(fcn PreSolveFcn, ctx any)
SetPreSolveCallback sets the pre-solve callback. This is optional (upstream b2World_SetPreSolveCallback).
func (*World) SetPrismaticJointLimits ¶
SetPrismaticJointLimits sets the joint limits in meters. It is expected that lower <= upper (upstream b2PrismaticJoint_SetLimits).
func (*World) SetPrismaticJointMaxMotorForce ¶
SetPrismaticJointMaxMotorForce sets the prismatic joint maximum motor force, usually in Newtons (upstream b2PrismaticJoint_SetMaxMotorForce).
func (*World) SetPrismaticJointMotorSpeed ¶
SetPrismaticJointMotorSpeed sets the prismatic joint motor speed, usually in meters per second (upstream b2PrismaticJoint_SetMotorSpeed).
func (*World) SetPrismaticJointSpringDampingRatio ¶
SetPrismaticJointSpringDampingRatio sets the prismatic joint spring damping ratio, non-dimensional (upstream b2PrismaticJoint_SetSpringDampingRatio).
func (*World) SetPrismaticJointSpringHertz ¶
SetPrismaticJointSpringHertz sets the prismatic joint spring stiffness in Hertz (upstream b2PrismaticJoint_SetSpringHertz).
func (*World) SetPrismaticJointTargetTranslation ¶
SetPrismaticJointTargetTranslation sets the prismatic joint spring target translation in meters (upstream b2PrismaticJoint_SetTargetTranslation).
func (*World) SetRestitutionCallback ¶
func (w *World) SetRestitutionCallback(callback RestitutionCallback)
SetRestitutionCallback sets the restitution callback. Passing nil restores the default mixing rule max(restitutionA, restitutionB) (upstream b2World_SetRestitutionCallback).
func (*World) SetRestitutionThreshold ¶
SetRestitutionThreshold adjusts the restitution threshold, usually in meters per second (upstream b2World_SetRestitutionThreshold).
func (*World) SetRevoluteJointLimits ¶
SetRevoluteJointLimits sets the revolute joint limits in radians. It is expected that lower <= upper (upstream b2RevoluteJoint_SetLimits).
func (*World) SetRevoluteJointMaxMotorTorque ¶
SetRevoluteJointMaxMotorTorque sets the revolute joint maximum motor torque, usually in Newton * meters (upstream b2RevoluteJoint_SetMaxMotorTorque).
func (*World) SetRevoluteJointMotorSpeed ¶
SetRevoluteJointMotorSpeed sets the revolute joint motor speed in radians per second (upstream b2RevoluteJoint_SetMotorSpeed).
func (*World) SetRevoluteJointSpringDampingRatio ¶
SetRevoluteJointSpringDampingRatio sets the revolute joint spring damping ratio, non-dimensional (upstream b2RevoluteJoint_SetSpringDampingRatio).
func (*World) SetRevoluteJointSpringHertz ¶
SetRevoluteJointSpringHertz sets the revolute joint spring stiffness in Hertz (upstream b2RevoluteJoint_SetSpringHertz).
func (*World) SetRevoluteJointTargetAngle ¶
SetRevoluteJointTargetAngle sets the revolute joint spring target angle in radians (upstream b2RevoluteJoint_SetTargetAngle).
func (*World) SetShapeCapsule ¶
SetShapeCapsule allows you to change a shape to be a capsule or update the current capsule. This does not modify the mass properties (upstream b2Shape_SetCapsule).
func (*World) SetShapeCircle ¶
SetShapeCircle allows you to change a shape to be a circle or update the current circle. This does not modify the mass properties (upstream b2Shape_SetCircle).
func (*World) SetShapeDensity ¶
SetShapeDensity sets the mass density of a shape, usually in kg/m^2. This will optionally update the mass properties on the parent body (upstream b2Shape_SetDensity).
func (*World) SetShapeFilter ¶
SetShapeFilter sets the current filter. This is almost as expensive as recreating the shape. This may cause contacts to be immediately destroyed. However contacts are not created until the next world step. Sensor overlap state is also not updated until the next world step (upstream b2Shape_SetFilter).
func (*World) SetShapeFriction ¶
SetShapeFriction sets the friction on a shape (upstream b2Shape_SetFriction).
func (*World) SetShapePolygon ¶
SetShapePolygon allows you to change a shape to be a polygon or update the current polygon. This does not modify the mass properties (upstream b2Shape_SetPolygon).
func (*World) SetShapeRestitution ¶
SetShapeRestitution sets the shape restitution (bounciness) (upstream b2Shape_SetRestitution).
func (*World) SetShapeSegment ¶
SetShapeSegment allows you to change a shape to be a segment or update the current segment (upstream b2Shape_SetSegment).
func (*World) SetShapeSurfaceMaterial ¶
func (w *World) SetShapeSurfaceMaterial(shapeID ShapeID, surfaceMaterial SurfaceMaterial)
SetShapeSurfaceMaterial sets the shape surface material (upstream b2Shape_SetSurfaceMaterial).
func (*World) SetShapeUserData ¶
SetShapeUserData sets the user data on a shape (upstream b2Shape_SetUserData).
func (*World) SetShapeUserMaterial ¶
SetShapeUserMaterial sets the shape user material identifier (upstream b2Shape_SetUserMaterial).
func (*World) SetUserData ¶
SetUserData sets the user data on the world (upstream b2World_SetUserData).
func (*World) SetWeldJointAngularDampingRatio ¶
SetWeldJointAngularDampingRatio sets the weld joint angular damping ratio, non-dimensional (upstream b2WeldJoint_SetAngularDampingRatio).
func (*World) SetWeldJointAngularHertz ¶
SetWeldJointAngularHertz sets the weld joint angular stiffness in Hertz. Zero means rigid (upstream b2WeldJoint_SetAngularHertz).
func (*World) SetWeldJointLinearDampingRatio ¶
SetWeldJointLinearDampingRatio sets the weld joint linear damping ratio, non-dimensional (upstream b2WeldJoint_SetLinearDampingRatio).
func (*World) SetWeldJointLinearHertz ¶
SetWeldJointLinearHertz sets the weld joint linear stiffness in Hertz. Zero means rigid (upstream b2WeldJoint_SetLinearHertz).
func (*World) SetWheelJointLimits ¶
SetWheelJointLimits sets the joint limits in meters. It is expected that lower <= upper (upstream b2WheelJoint_SetLimits).
func (*World) SetWheelJointMaxMotorTorque ¶
SetWheelJointMaxMotorTorque sets the wheel joint maximum motor torque, usually in Newton * meters (upstream b2WheelJoint_SetMaxMotorTorque).
func (*World) SetWheelJointMotorSpeed ¶
SetWheelJointMotorSpeed sets the wheel joint motor speed in radians per second (upstream b2WheelJoint_SetMotorSpeed).
func (*World) SetWheelJointSpringDampingRatio ¶
SetWheelJointSpringDampingRatio sets the wheel joint spring damping ratio, non-dimensional (upstream b2WheelJoint_SetSpringDampingRatio).
func (*World) SetWheelJointSpringHertz ¶
SetWheelJointSpringHertz sets the wheel joint spring stiffness in Hertz (upstream b2WheelJoint_SetSpringHertz).
func (*World) ShapeAABB ¶
ShapeAABB returns the current world AABB of a shape (upstream b2Shape_GetAABB).
func (*World) ShapeBody ¶
ShapeBody returns the id of the body that a shape is attached to (upstream b2Shape_GetBody).
func (*World) ShapeCapsule ¶
ShapeCapsule returns a copy of the shape's capsule. Asserts the type is correct (upstream b2Shape_GetCapsule).
func (*World) ShapeChainSegment ¶
func (w *World) ShapeChainSegment(shapeID ShapeID) ChainSegment
ShapeChainSegment returns a copy of the shape's chain segment. These come from chain shapes. Asserts the type is correct (upstream b2Shape_GetChainSegment).
func (*World) ShapeCircle ¶
ShapeCircle returns a copy of the shape's circle. Asserts the type is correct (upstream b2Shape_GetCircle).
func (*World) ShapeClosestPoint ¶
ShapeClosestPoint returns the closest point on a shape to a target point. Target and result are in world space (upstream b2Shape_GetClosestPoint).
func (*World) ShapeComputeMassData ¶
ShapeComputeMassData computes the mass data for a shape (upstream b2Shape_ComputeMassData).
func (*World) ShapeContactCapacity ¶
ShapeContactCapacity returns the maximum capacity required for retrieving all the touching contacts on a shape (upstream b2Shape_GetContactCapacity).
func (*World) ShapeContactData ¶
func (w *World) ShapeContactData(shapeID ShapeID, contactData []ContactData) int
ShapeContactData fills contactData with the touching contact data involving a shape, up to len(contactData) elements, and returns the number of elements stored (upstream b2Shape_GetContactData).
func (*World) ShapeDensity ¶
ShapeDensity returns the density of a shape, usually in kg/m^2 (upstream b2Shape_GetDensity).
func (*World) ShapeFilter ¶
ShapeFilter returns the shape filter (upstream b2Shape_GetFilter).
func (*World) ShapeFriction ¶
ShapeFriction returns the friction of a shape (upstream b2Shape_GetFriction).
func (*World) ShapeParentChain ¶
ShapeParentChain returns the parent chain id if the shape type is a chain segment, otherwise returns the zero ChainID (upstream b2Shape_GetParentChain).
func (*World) ShapePolygon ¶
ShapePolygon returns a copy of the shape's convex polygon. Asserts the type is correct (upstream b2Shape_GetPolygon).
func (*World) ShapeRayCast ¶
func (w *World) ShapeRayCast(shapeID ShapeID, input *RayCastInput) CastOutput
ShapeRayCast casts a ray against a shape (upstream b2Shape_RayCast).
func (*World) ShapeRestitution ¶
ShapeRestitution returns the restitution of a shape (upstream b2Shape_GetRestitution).
func (*World) ShapeSegment ¶
ShapeSegment returns a copy of the shape's line segment. Asserts the type is correct (upstream b2Shape_GetSegment).
func (*World) ShapeSensorCapacity ¶
ShapeSensorCapacity returns the maximum capacity required for retrieving all the overlapped shapes on a sensor shape. This returns 0 if the provided shape is not a sensor (upstream b2Shape_GetSensorCapacity).
func (*World) ShapeSensorData ¶
ShapeSensorData fills visitorIDs with the overlapped shapes for a sensor shape, up to len(visitorIDs), and returns the number of ids stored. Overlaps may contain destroyed shapes so use IsShapeValid to confirm each overlap (upstream b2Shape_GetSensorData).
func (*World) ShapeSurfaceMaterial ¶
func (w *World) ShapeSurfaceMaterial(shapeID ShapeID) SurfaceMaterial
ShapeSurfaceMaterial returns the shape surface material (upstream b2Shape_GetSurfaceMaterial).
func (*World) ShapeTestPoint ¶
ShapeTestPoint tests a point for overlap with a shape (upstream b2Shape_TestPoint).
func (*World) ShapeUserData ¶
ShapeUserData returns the user data stored on a shape (upstream b2Shape_GetUserData).
func (*World) ShapeUserMaterial ¶
ShapeUserMaterial returns the shape user material identifier (upstream b2Shape_GetUserMaterial).
func (*World) Step ¶
Step simulates a world for one time step. This performs collision detection, integration, and constraint solution (upstream b2World_Step). timeStep is the amount of time to simulate, this should be a fixed number (usually 1/60). subStepCount is the number of sub-steps, increasing the sub-step count can increase accuracy (usually 4).
func (*World) UserData ¶
UserData returns the user data stored on the world (upstream b2World_GetUserData).
func (*World) WakeBodyTouching ¶
WakeBodyTouching wakes all the bodies touching this body via contacts (upstream b2Body_WakeTouching).
func (*World) WakeJointBodies ¶
WakeJointBodies wakes the bodies connected to this joint (upstream b2Joint_WakeBodies).
func (*World) WeldJointAngularDampingRatio ¶
WeldJointAngularDampingRatio returns the weld joint angular damping ratio (upstream b2WeldJoint_GetAngularDampingRatio).
func (*World) WeldJointAngularHertz ¶
WeldJointAngularHertz returns the weld joint angular stiffness in Hertz (upstream b2WeldJoint_GetAngularHertz).
func (*World) WeldJointLinearDampingRatio ¶
WeldJointLinearDampingRatio returns the weld joint linear damping ratio (upstream b2WeldJoint_GetLinearDampingRatio).
func (*World) WeldJointLinearHertz ¶
WeldJointLinearHertz returns the weld joint linear stiffness in Hertz (upstream b2WeldJoint_GetLinearHertz).
func (*World) WheelJointLowerLimit ¶
WheelJointLowerLimit returns the lower joint limit in meters (upstream b2WheelJoint_GetLowerLimit).
func (*World) WheelJointMaxMotorTorque ¶
WheelJointMaxMotorTorque returns the wheel joint maximum motor torque (upstream b2WheelJoint_GetMaxMotorTorque).
func (*World) WheelJointMotorSpeed ¶
WheelJointMotorSpeed returns the wheel joint motor speed in radians per second (upstream b2WheelJoint_GetMotorSpeed).
func (*World) WheelJointMotorTorque ¶
WheelJointMotorTorque returns the current wheel joint motor torque, usually in Newton * meters (upstream b2WheelJoint_GetMotorTorque).
func (*World) WheelJointSpringDampingRatio ¶
WheelJointSpringDampingRatio returns the wheel joint spring damping ratio (upstream b2WheelJoint_GetSpringDampingRatio).
func (*World) WheelJointSpringHertz ¶
WheelJointSpringHertz returns the wheel joint spring stiffness in Hertz (upstream b2WheelJoint_GetSpringHertz).
func (*World) WheelJointUpperLimit ¶
WheelJointUpperLimit returns the upper joint limit in meters (upstream b2WheelJoint_GetUpperLimit).
type WorldDef ¶
type WorldDef struct {
// Gravity vector. Box2D has no up-vector defined.
Gravity Vec2
// Restitution speed threshold, usually in m/s. Collisions above this
// speed have restitution applied (will bounce).
RestitutionThreshold float64
// Threshold speed for hit events. Usually meters per second.
HitEventThreshold float64
// Contact stiffness. Cycles per second. Increasing this increases the speed of overlap recovery, but can introduce jitter.
ContactHertz float64
// Contact bounciness. Non-dimensional. You can speed up overlap recovery by decreasing this with
// the trade-off that overlap resolution becomes more energetic.
ContactDampingRatio float64
// This parameter controls how fast overlap is resolved and usually has units of meters per second. This only
// puts a cap on the resolution speed. The resolution speed is increased by increasing the hertz and/or
// decreasing the damping ratio.
ContactSpeed float64
// Maximum linear speed. Usually meters per second.
MaximumLinearSpeed float64
// Optional mixing callback for friction. The default uses sqrt(frictionA * frictionB).
FrictionCallback FrictionCallback
// Optional mixing callback for restitution. The default uses max(restitutionA, restitutionB).
RestitutionCallback RestitutionCallback
// Can bodies go to sleep to improve performance
EnableSleep bool
// Enable continuous collision
EnableContinuous bool
// Contact softening when mass ratios are large. Experimental.
//
// Currently INERT: this field is accepted and stored but has no effect on
// simulation. Upstream implements the softening branch only in its SIMD
// prepare path (b2PrepareContactsTask); the scalar prepare path this port
// transliterates (b2PrepareOverflowContacts) never read the flag. The
// field is kept so world definitions stay source-compatible with upstream.
EnableContactSoftening bool
// User data. Deviation from upstream: the C void* becomes a uint64 so the
// ECS wrapper can pack an entity id directly.
UserData uint64
// WorkerCount is the number of workers World.Step may use. 0 means 1
// (serial). NewWorld rejects values outside [0, MaxWorkers] (upstream
// B2_MAX_WORKERS) and otherwise takes the value as given — like
// upstream, it is the caller's explicit choice and is NOT clamped to
// runtime.GOMAXPROCS(0); counts above the core count merely
// oversubscribe, which costs throughput, never correctness. Deviation
// from upstream: the workers are an internal goroutine pool
// (worker_pool.go), not user-supplied threads, and simulation results
// are byte-identical for every value.
WorkerCount int
// contains filtered or unexported fields
}
WorldDef is a world definition used to create a simulation world (upstream b2WorldDef). Must be initialized using DefaultWorldDef.
Deviations from upstream: the user task-system callbacks (enqueueTask, finishTask, userTaskContext) are not ported — WorkerCount selects an internal goroutine pool instead (see worker_pool.go), and unlike upstream the results are byte-identical for every worker count. The b2_secretCookie/internalValue guard is replaced by the private initialized flag set by DefaultWorldDef.
func DefaultWorldDef ¶
func DefaultWorldDef() WorldDef
DefaultWorldDef initializes a world definition (upstream b2DefaultWorldDef).
type WorldID ¶
type WorldID struct {
// contains filtered or unexported fields
}
WorldID references a world instance (upstream b2WorldId).
func UnpackWorldID ¶
UnpackWorldID loads a uint32 into a world id (upstream b2LoadWorldId).
Source Files
¶
- aabb.go
- arena.go
- bitset.go
- body.go
- broad_phase.go
- collision.go
- constants.go
- constraint_graph.go
- contact.go
- contact_solver.go
- core.go
- core_asserts_off.go
- distance.go
- distance_joint.go
- doc.go
- draw.go
- dynamic_tree.go
- geometry.go
- hash_set.go
- hull.go
- id_pool.go
- ids.go
- island.go
- joint.go
- manifold.go
- math.go
- math_fma.go
- math_trig.go
- motor_joint.go
- mover.go
- prismatic_joint.go
- revolute_joint.go
- sensor.go
- shape.go
- solver.go
- solver_continuous.go
- solver_set.go
- types.go
- weld_joint.go
- wheel_joint.go
- worker_pool.go
- world.go
- world_explode.go
- world_query.go
- world_step.go