cm

package module
v1.13.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 8, 2024 License: MIT Imports: 6 Imported by: 7

README

GoDoc

cm

Go language port of Chipmunk2D 7.0.3 physics library.

Documentation

Index

Constants

View Source
const (
	// Arbiter is active and its the first collision.
	ArbiterStateFirstCollision = iota
	// Arbiter is active and its not the first collision.
	ArbiterStateNormal
	// Collision has been explicitly ignored. Either by returning false from a
	// begin collision handler or calling ArbiterIgnore().
	ArbiterStateIgnore
	// Collison is no longer active. A space will cache an arbiter for up to Space.
	// CollisionPersistence more steps.
	ArbiterStateCached
	// Collison arbiter is invalid because one of the shapes was removed.
	ArbiterStateInvalidated
)

Arbiter states

View Source
const (
	// Value for group signifying that a shape is in no group.
	NoGroup uint = 0
	// Value for Shape layers signifying that a shape is in every layer.
	AllCategories uint = ^uint(0)
)
View Source
const (
	DrawShapes          = 1 << 0
	DrawConstraints     = 1 << 1
	DrawCollisionPoints = 1 << 2
)

Draw flags

View Source
const (
	MaxContactsPerArbiter int = 2
	ContactsBufferSize    int = 1024
)
View Source
const (
	ShapeTypeNum = 3
)

Variables

ShapeFilterAll is s collision filter value for a shape that will collide with anything except ShapeFilterNone.

ShapeFilterNone is a collision filter value for a shape that does not collide with anything.

View Source
var ShapeUpdateFunc = func(shape *Shape) {
	shape.CacheBB()
}
View Source
var ShapeVelocityFunc = func(obj any) vec.Vec2 {
	return obj.(*Shape).Body.velocity
}

Functions

func AlwaysCollide

func AlwaysCollide(_ *Arbiter, _ *Space, _ any) bool

func AreaForCircle

func AreaForCircle(r1, r2 float64) float64

AreaForCircle returns area of a hollow circle.

r1 and r2 are the inner and outer diameters. A solid circle has an inner diameter of 0.

func AreaForPoly

func AreaForPoly(count int, verts []vec.Vec2, r float64) float64

AreaForPoly calculates the signed area of a polygon.

A Clockwise winding gives positive area. This is probably backwards from what you expect, but matches Chipmunk's the winding for poly shapes.

func AreaForSegment

func AreaForSegment(a, b vec.Vec2, r float64) float64

AreaForSegment calculates the area of a fattened (capsule shaped) line segment.

func BodyUpdatePosition

func BodyUpdatePosition(body *Body, dt float64)

BodyUpdatePosition is default position integration function.

func BodyUpdateVelocity

func BodyUpdateVelocity(body *Body, gravity vec.Vec2, damping, dt float64)

BodyUpdateVelocity is default velocity integration function.

func CachedArbitersFilter

func CachedArbitersFilter(arb *Arbiter, space *Space, shape *Shape, body *Body) bool

func CentroidForPoly

func CentroidForPoly(count int, verts []vec.Vec2) vec.Vec2

CentroidForPoly calculates the natural centroid of a polygon.

func CircleSegmentQuery

func CircleSegmentQuery(shape *Shape, center vec.Vec2, r1 float64, a, b vec.Vec2, r2 float64, info *SegmentQueryInfo)

func CircleToCircle

func CircleToCircle(info *CollisionInfo)

func CircleToPoly

func CircleToPoly(info *CollisionInfo)

func CircleToSegment

func CircleToSegment(info *CollisionInfo)

func CollisionError

func CollisionError(_ *CollisionInfo)

func ComponentActive

func ComponentActive(root *Body, threshold float64) bool

func ContactPoints

func ContactPoints(e1, e2 Edge, points ClosestPoints, info *CollisionInfo)

ContactPoints finds contact point pairs on two support edges' surfaces

func Contains

func Contains(bodies []*Body, body *Body) bool

func DebugInfo

func DebugInfo(space *Space) string

DebugInfo returns info of space

func DefaultBegin

func DefaultBegin(arb *Arbiter, space *Space, _ any) bool

func DefaultPostSolve

func DefaultPostSolve(arb *Arbiter, space *Space, _ any)

func DefaultPreSolve

func DefaultPreSolve(arb *Arbiter, space *Space, _ any) bool

func DefaultSeparate

func DefaultSeparate(arb *Arbiter, space *Space, _ any)

func DefaultSpringForce

func DefaultSpringForce(spring *DampedSpring, dist float64) float64

func DoNothing

func DoNothing(_ *Arbiter, _ *Space, _ any)

func DrawConstraint

func DrawConstraint(constraint *Constraint, drawer IDrawer)

DrawConstraint draws constraints with the drawer implementation

func DrawShape

func DrawShape(shape *Shape, drawer IDrawer)

DrawShape draws shapes with the drawer implementation

func DrawSpace

func DrawSpace(space *Space, drawer IDrawer)

DrawSpace draws all shapes in space with the drawer implementation

func FloodFillComponent

func FloodFillComponent(root *Body, body *Body)

func MomentForBox

func MomentForBox(mass, width, height float64) float64

MomentForBox calculates the moment of inertia for a solid box.

func MomentForBox2

func MomentForBox2(mass float64, box BB) float64

MomentForBox2 calculates the moment of inertia for a solid box.

func MomentForCircle

func MomentForCircle(mass, d1, d2 float64, offset vec.Vec2) float64

MomentForCircle calculates the moment of inertia for a circle.

d1 and d2 are the inner and outer diameters. A solid circle has an inner diameter (d1) of 0. offset is a Vec2 representing the displacement of the circle's center of mass from the axis of rotation. If the center is not aligned with the axis, the offset increases the moment of inertia.

func MomentForCircle2 added in v1.10.0

func MomentForCircle2(mass, radius float64) float64

MomentForCircle calculates the moment of inertia for a solid circle with radius and mass

func MomentForPoly

func MomentForPoly(mass float64, count int, verts []vec.Vec2, offset vec.Vec2, r float64) float64

MomentForPoly calculates the moment of inertia for a solid polygon shape assuming it's center of gravity is at it's centroid.

The offset is added to each vertex.

func MomentForSegment

func MomentForSegment(mass float64, a, b vec.Vec2, radius float64) float64

MomentForSegment calculates the moment of inertia for a line segment.

Beveling radius is not supported.

func NearestPointQueryNearest

func NearestPointQueryNearest(obj any, shape *Shape, collisionId uint32, out any) uint32

func NodeSetA

func NodeSetA(node, value *Node)

func NodeSetB

func NodeSetB(node, value *Node)

func PolyLineCollectSegment

func PolyLineCollectSegment(v0, v1 vec.Vec2, pls *PolyLineSet)

Add a segment to a polyline set. A segment will either start a new polyline, join two others, or add to or loop an existing polyline.

func PolySupportPointIndex

func PolySupportPointIndex(count int, planes []SplittingPlane, n vec.Vec2) int

func PolyToPoly

func PolyToPoly(info *CollisionInfo)

func PostStepDoNothing

func PostStepDoNothing(space *Space, key, data any)

func QHullPartition

func QHullPartition(verts []vec.Vec2, count int, a, b vec.Vec2, tol float64) int

func QHullReduce

func QHullReduce(tol float64, verts []vec.Vec2, count int, a, pivot, b vec.Vec2, result []vec.Vec2) int

func QueryReject

func QueryReject(a, b *Shape) bool

QueryReject returns true if shapes a and b reject to collide.

func QueryRejectConstraints

func QueryRejectConstraints(a, b *Body) bool

func SegmentToPoly

func SegmentToPoly(info *CollisionInfo)

func SegmentToSegment

func SegmentToSegment(info *CollisionInfo)

func Sharpness

func Sharpness(a, b, c vec.Vec2) float64

func SpaceArbiterSetFilter

func SpaceArbiterSetFilter(arb *Arbiter, space *Space) bool

SpaceArbiterSetFilter throws away old arbiters.

func SpaceCollideShapesFunc

func SpaceCollideShapesFunc(obj any, b *Shape, collisionId uint32, vspace any) uint32

func VoidQueryFunc

func VoidQueryFunc(obj1 any, obj2 *Shape, collisionId uint32, data any) uint32

Types

type Arbiter

type Arbiter struct {
	UserData any

	Contacts []Contact // a slice onto the current buffer array of contacts
	// contains filtered or unexported fields
}

Arbiter struct tracks pairs of colliding shapes.

They are also used in conjuction with collision handler callbacks allowing you to retrieve information on the collision or change it. A unique arbiter value is used for each pair of colliding objects. It persists until the shapes separate.

func ArbiterNext

func ArbiterNext(arb *Arbiter, body *Body) *Arbiter

func (*Arbiter) ApplyCachedImpulse

func (arbiter *Arbiter) ApplyCachedImpulse(dtCoef float64)

func (*Arbiter) ApplyImpulse

func (arbiter *Arbiter) ApplyImpulse()

func (*Arbiter) Bodies

func (arb *Arbiter) Bodies() (*Body, *Body)

Bodies returns the colliding bodies involved for this arbiter. The order of the space.CollisionType the bodies are associated with values will match the order set when the collision handler was registered.

func (*Arbiter) CallWildcardBeginA

func (arb *Arbiter) CallWildcardBeginA(space *Space) bool

CallWildcardBeginA if you want a custom callback to invoke the wildcard callback for the first collision type, you must call this function explicitly.

You must decide how to handle the wildcard's return value since it may disagree with the other wildcard handler's return value or your own.

func (*Arbiter) CallWildcardBeginB

func (arb *Arbiter) CallWildcardBeginB(space *Space) bool

CallWildcardBeginB If you want a custom callback to invoke the wildcard callback for the second collision type, you must call this function explicitly.

func (*Arbiter) CallWildcardPostSolveA

func (arb *Arbiter) CallWildcardPostSolveA(space *Space)

func (*Arbiter) CallWildcardPostSolveB

func (arb *Arbiter) CallWildcardPostSolveB(space *Space)

func (*Arbiter) CallWildcardPreSolveA

func (arb *Arbiter) CallWildcardPreSolveA(space *Space) bool

CallWildcardPreSolveA If you want a custom callback to invoke the wildcard callback for the first collision type, you must call this function explicitly.

func (*Arbiter) CallWildcardPreSolveB

func (arb *Arbiter) CallWildcardPreSolveB(space *Space) bool

CallWildcardPreSolveB If you want a custom callback to invoke the wildcard callback for the second collision type, you must call this function explicitly.

func (*Arbiter) CallWildcardSeparateA

func (arb *Arbiter) CallWildcardSeparateA(space *Space)

func (*Arbiter) CallWildcardSeparateB

func (arb *Arbiter) CallWildcardSeparateB(space *Space)

func (*Arbiter) ContactPointSet

func (arb *Arbiter) ContactPointSet() ContactPointSet

ContactPointSet returns ContactPointSet

func (*Arbiter) Count

func (arb *Arbiter) Count() int

func (*Arbiter) Ignore

func (arb *Arbiter) Ignore() bool

Ignore marks a collision pair to be ignored until the two objects separate.

Pre-solve and post-solve callbacks will not be called, but the separate callback will be called.

func (*Arbiter) Init

func (arbiter *Arbiter) Init(a, b *Shape) *Arbiter

Init initializes and returns Arbiter

func (*Arbiter) IsFirstContact

func (arbiter *Arbiter) IsFirstContact() bool

func (*Arbiter) Next

func (node *Arbiter) Next(body *Body) *Arbiter

func (*Arbiter) Normal

func (arb *Arbiter) Normal() vec.Vec2

func (*Arbiter) PreStep

func (arb *Arbiter) PreStep(dt, slop, bias float64)

func (*Arbiter) SetContactPointSet

func (arb *Arbiter) SetContactPointSet(set *ContactPointSet)

SetContactPointSet replaces the contact point set.

This can be a very powerful feature, but use it with caution!

func (*Arbiter) Shapes

func (arb *Arbiter) Shapes() (*Shape, *Shape)

Shapes return the colliding shapes involved for this arbiter. The order of their space.CollisionType values will match the order set when the collision handler was registered.

func (*Arbiter) ThreadForBody

func (arbiter *Arbiter) ThreadForBody(body *Body) *ArbiterThread

func (*Arbiter) TotalImpulse

func (arb *Arbiter) TotalImpulse() vec.Vec2

TotalImpulse calculates the total impulse including the friction that was applied by this arbiter.

This function should only be called from a post-solve, post-step or EachArbiter callback.

func (*Arbiter) Unthread

func (arbiter *Arbiter) Unthread()

func (*Arbiter) Update

func (arb *Arbiter) Update(info *CollisionInfo, space *Space)

type ArbiterThread

type ArbiterThread struct {
	// contains filtered or unexported fields
}

type BB

type BB struct {
	L, B, R, T float64
}

BB is Chipmunk's axis-aligned 2D bounding box type. (left, bottom, right, top)

func NewBB

func NewBB(l, b, r, t float64) BB

NewBB is convenience constructor for BB structs.

func NewBBForCircle

func NewBBForCircle(p vec.Vec2, r float64) BB

NewBBForCircle constructs a BB for a circle with the given position and radius.

func NewBBForExtents

func NewBBForExtents(c vec.Vec2, hw, hh float64) BB

NewBBForExtents constructs a BB centered on a point with the given extents (half sizes).

func ShapeGetBB

func ShapeGetBB(obj *Shape) BB

func (BB) Area

func (bb BB) Area() float64

Area returns the area of the bounding box.

func (BB) Center

func (bb BB) Center() vec.Vec2

Center returns the center of a bounding box.

func (BB) ClampVect

func (bb BB) ClampVect(v *vec.Vec2) vec.Vec2

ClampVect clamps a vector to bounding box.

func (BB) Contains

func (bb BB) Contains(other BB) bool

Contains returns true if other lies completely within bb.

func (BB) ContainsVect

func (bb BB) ContainsVect(v vec.Vec2) bool

ContainsVect returns true if bb contains v.

func (BB) Expand

func (bb BB) Expand(v vec.Vec2) BB

Expand returns a bounding box that holds both bb and v.

func (BB) Intersects

func (bb BB) Intersects(b BB) bool

Intersects returns true if a and b intersect.

func (BB) IntersectsSegment

func (bb BB) IntersectsSegment(a, b vec.Vec2) bool

IntersectsSegment returns true if the bounding box intersects the line segment with ends a and b.

func (BB) Merge

func (a BB) Merge(b BB) BB

Merge returns a bounding box that holds both bounding boxes.

func (BB) MergedArea

func (a BB) MergedArea(b BB) float64

MergedArea merges a and b and returns the area of the merged bounding box.

func (BB) Offset

func (bb BB) Offset(v vec.Vec2) BB

Offset returns a bounding box offseted by v.

func (BB) Proximity

func (a BB) Proximity(b BB) float64

func (BB) SegmentQuery

func (bb BB) SegmentQuery(a, b vec.Vec2) float64

SegmentQuery returns the fraction along the segment query the BB is hit. Returns cm.INFINITY if it doesn't hit.

func (BB) String

func (bb BB) String() string

func (BB) WrapVect

func (bb BB) WrapVect(v vec.Vec2) vec.Vec2

WrapVect wraps a vector to bounding box.

type BBQueryContext

type BBQueryContext struct {
	// contains filtered or unexported fields
}

type BBTree

type BBTree struct {
	// contains filtered or unexported fields
}

BBTree represents a bounding box tree used for spatial indexing and collision detection.

func (*BBTree) Contains

func (bbt *BBTree) Contains(obj *Shape, hashId HashValue) bool

func (*BBTree) Count

func (bbt *BBTree) Count() int

func (*BBTree) Each

func (bbt *BBTree) Each(f SpatialIndexIterator)

func (*BBTree) GetBB

func (bbt *BBTree) GetBB(obj *Shape) BB

func (*BBTree) GetMasterTree

func (tree *BBTree) GetMasterTree() *BBTree

func (*BBTree) IncrementStamp

func (tree *BBTree) IncrementStamp()

func (*BBTree) Insert

func (bbt *BBTree) Insert(obj *Shape, hashId HashValue)

func (*BBTree) LeafAddPairs

func (tree *BBTree) LeafAddPairs(leaf *Node)

func (*BBTree) LeafUpdate

func (tree *BBTree) LeafUpdate(leaf *Node) bool

func (*BBTree) NewLeaf

func (tree *BBTree) NewLeaf(obj *Shape) *Node

func (*BBTree) NewNode

func (bbt *BBTree) NewNode(a, b *Node) *Node

func (*BBTree) NodeFromPool

func (tree *BBTree) NodeFromPool() *Node

func (*BBTree) PairFromPool

func (bbt *BBTree) PairFromPool() *Pair

func (*BBTree) PairInsert

func (tree *BBTree) PairInsert(a *Node, b *Node)

func (*BBTree) PairsClear

func (tree *BBTree) PairsClear(leaf *Node)

func (*BBTree) Query

func (bbt *BBTree) Query(obj any, bb BB, f SpatialIndexQuery, data any)

func (*BBTree) RecycleNode

func (tree *BBTree) RecycleNode(node *Node)

func (*BBTree) RecyclePair

func (bbt *BBTree) RecyclePair(pair *Pair)

func (*BBTree) Reindex

func (tree *BBTree) Reindex()

func (*BBTree) ReindexObject

func (bbt *BBTree) ReindexObject(obj *Shape, hashId HashValue)

func (*BBTree) ReindexQuery

func (tree *BBTree) ReindexQuery(f SpatialIndexQuery, data any)

func (*BBTree) Remove

func (tree *BBTree) Remove(obj *Shape, hashId HashValue)

func (*BBTree) ReplaceChild

func (tree *BBTree) ReplaceChild(parent, child, value *Node)

func (*BBTree) SegmentQuery

func (bbt *BBTree) SegmentQuery(obj any, a, b vec.Vec2, tExit float64, f SpatialIndexSegmentQuery, data any)

func (*BBTree) SubtreeInsert

func (bbt *BBTree) SubtreeInsert(subtree *Node, leaf *Node) *Node

func (*BBTree) SubtreeRemove

func (tree *BBTree) SubtreeRemove(subtree *Node, leaf *Node) *Node

type BBTreeVelocityFunc

type BBTreeVelocityFunc func(obj any) vec.Vec2

type Body

type Body struct {
	// UserData is an object that this constraint is associated with.
	//
	// You can use this get a reference to your game object or controller object from within callbacks.
	UserData any
	Space    *Space

	Shapes []*Shape
	// contains filtered or unexported fields
}

func NewBody

func NewBody(mass, moment float64) *Body

NewBody Initializes a rigid body with the given mass and moment of inertia.

Guessing the moment of inertia is usually a bad idea. Use the moment estimation functions MomentFor*().

func NewKinematicBody

func NewKinematicBody() *Body

NewKinematicBody allocates and initializes a Body, and set it as a kinematic body.

func NewStaticBody

func NewStaticBody() *Body

NewStaticBody allocates and initializes a Body, and set it as a static body.

func (*Body) AccumulateMassFromShapes

func (body *Body) AccumulateMassFromShapes()

AccumulateMassFromShapes should *only* be called when shapes with mass info are modified, added or removed.

func (*Body) Activate

func (body *Body) Activate()

Activate wakes up a sleeping or idle body.

func (*Body) ActivateStatic

func (body *Body) ActivateStatic(filter *Shape)

ActivateStatic wakes up any sleeping or idle bodies touching this static body.

func (*Body) Angle

func (body *Body) Angle() float64

Angle returns the angle of the body.

func (*Body) AngularVelocity

func (body *Body) AngularVelocity() float64

AngularVelocity returns the angular velocity of the body.

func (*Body) ApplyForceAtLocalPoint

func (body *Body) ApplyForceAtLocalPoint(force, point vec.Vec2)

ApplyForceAtLocalPoint applies a force at local point.

func (*Body) ApplyForceAtWorldPoint

func (body *Body) ApplyForceAtWorldPoint(force, point vec.Vec2)

ApplyForceAtWorldPoint applies a force at world point.

func (*Body) ApplyImpulseAtLocalPoint

func (body *Body) ApplyImpulseAtLocalPoint(impulse, point vec.Vec2)

ApplyImpulseAtLocalPoint applies impulse at local point

func (*Body) ApplyImpulseAtWorldPoint

func (body *Body) ApplyImpulseAtWorldPoint(impulse, point vec.Vec2)

ApplyImpulseAtWorldPoint applies impulse at world point

func (*Body) AttachShape added in v1.10.0

func (body *Body) AttachShape(shape *Shape)

AttachShape adds shape to the body

func (Body) CenterOfGravity

func (body Body) CenterOfGravity() vec.Vec2

CenterOfGravity returns the offset of the center of gravity in body local coordinates.

func (*Body) ComponentAdd

func (root *Body) ComponentAdd(body *Body)

func (*Body) ComponentRoot

func (body *Body) ComponentRoot() *Body

func (*Body) EachArbiter

func (body *Body) EachArbiter(f func(*Arbiter))

EachArbiter calls f once for each arbiter that is currently active on the body.

func (*Body) EachConstraint

func (body *Body) EachConstraint(f func(*Constraint))

EachConstraint calls f once for each constraint attached to this body

func (*Body) EachShape

func (body *Body) EachShape(f func(*Shape))

EachShape calls f once for each shape attached to this body

func (*Body) Force

func (body *Body) Force() vec.Vec2

Force returns the force applied to the body for the next time step.

func (*Body) IdleTime

func (body *Body) IdleTime() float64

IdleTime returns sleeping idle time of the body

func (*Body) IsSleeping

func (body *Body) IsSleeping() bool

IsSleeping returns true if the body is sleeping.

func (*Body) KineticEnergy

func (body *Body) KineticEnergy() float64

KineticEnergy returns the kinetic energy of this body.

func (*Body) LocalToWorld

func (body *Body) LocalToWorld(point vec.Vec2) vec.Vec2

LocalToWorld converts from body local to world coordinates.

Convert a point in world (absolute) coordinates to body local coordinates affected by the position and rotation of the rigid body.

func (*Body) Mass

func (body *Body) Mass() float64

Mass returns mass of the body

func (Body) Moment

func (body Body) Moment() float64

Moment returns moment of inertia of the body.

func (*Body) Position

func (body *Body) Position() vec.Vec2

Position returns the position of the body.

func (*Body) PushArbiter

func (body *Body) PushArbiter(arb *Arbiter)

func (*Body) RemoveConstraint

func (body *Body) RemoveConstraint(constraint *Constraint)

RemoveConstraint removes constraint from the body.

func (*Body) RemoveShape

func (body *Body) RemoveShape(shape *Shape)

RemoveShape removes collision shape from the body.

func (*Body) RemoveShapeAtIndex added in v1.10.0

func (body *Body) RemoveShapeAtIndex(index int)

RemoveShapeAtIndex removes collision shape from the body.

func (*Body) Rotation

func (body *Body) Rotation() vec.Vec2

Rotation returns the rotation vector of the body.

(The x basis vector of it's transform.)

func (*Body) SetAngle

func (body *Body) SetAngle(angle float64)

SetAngle sets the angle of body.

func (*Body) SetAngularVelocity

func (body *Body) SetAngularVelocity(angularVelocity float64)

SetAngularVelocity sets the angular velocity of the body.

func (*Body) SetForce

func (body *Body) SetForce(force vec.Vec2)

SetForce sets the force applied to the body for the next time step.

func (*Body) SetMass

func (body *Body) SetMass(mass float64)

SetMass sets mass of the body

func (*Body) SetMoment

func (body *Body) SetMoment(moment float64)

SetMoment sets moment of inertia of the body.

func (*Body) SetPosition

func (body *Body) SetPosition(position vec.Vec2)

SetPosition sets the position of the body.

func (*Body) SetPositionUpdateFunc

func (body *Body) SetPositionUpdateFunc(f BodyPositionFunc)

SetPositionUpdateFunc sets the callback used to update a body's position.

func (*Body) SetTorque

func (body *Body) SetTorque(torque float64)

SetTorque sets the torque applied to the body for the next time step.

func (*Body) SetTransform

func (body *Body) SetTransform(p vec.Vec2, a float64)

SetTransform sets transform

func (*Body) SetType

func (body *Body) SetType(bt BodyType)

SetType sets the type of the body.

func (*Body) SetVelocity

func (body *Body) SetVelocity(x, y float64)

SetVelocity sets the velocity of the body.

Shorthand for Body.SetVelocityVector()

func (*Body) SetVelocityUpdateFunc

func (body *Body) SetVelocityUpdateFunc(f BodyVelocityFunc)

SetVelocityUpdateFunc sets the callback used to update a body's velocity.

func (*Body) SetVelocityVector

func (body *Body) SetVelocityVector(v vec.Vec2)

SetVelocityVector sets the velocity of the body

func (*Body) ShapeAtIndex added in v1.10.0

func (b *Body) ShapeAtIndex(index int) *Shape

ShapeAtIndex returns shape at index attached to this body

func (Body) String

func (b Body) String() string

String returns body id as string

func (*Body) Torque

func (body *Body) Torque() float64

Torque returns the torque applied to the body for the next time step.

func (*Body) Transform added in v1.6.0

func (body *Body) Transform() Transform

Transform returns body's transform

func (*Body) Type added in v1.10.0

func (body *Body) Type() BodyType

Type returns the type of the body.

func (*Body) UpdateVelocity

func (body *Body) UpdateVelocity(gravity vec.Vec2, damping, dt float64)

UpdateVelocity is the default velocity integration function.

func (*Body) Velocity

func (body *Body) Velocity() vec.Vec2

Velocity returns the velocity of the body.

func (*Body) VelocityAtLocalPoint

func (body *Body) VelocityAtLocalPoint(point vec.Vec2) vec.Vec2

VelocityAtLocalPoint returns the velocity of a point on a body.

Get the world (absolute) velocity of a point on a rigid body specified in body local coordinates.

func (*Body) VelocityAtWorldPoint

func (body *Body) VelocityAtWorldPoint(point vec.Vec2) vec.Vec2

VelocityAtWorldPoint returns the velocity of a point on a body.

Get the world (absolute) velocity of a point on a rigid body specified in world coordinates.

func (*Body) WorldToLocal

func (body *Body) WorldToLocal(point vec.Vec2) vec.Vec2

WorldToLocal converts from world to body local Coordinates.

Convert a point in body local coordinates to world (absolute) coordinates.

type BodyPositionFunc

type BodyPositionFunc func(body *Body, dt float64)

BodyPositionFunc is rigid body position update function type.

type BodyType added in v1.10.0

type BodyType uint8

BodyType for bodies; Dynamic, Kinematic or Static

const (
	Dynamic   BodyType = 0
	Kinematic BodyType = 1
	Static    BodyType = 2
)

type BodyVelocityFunc

type BodyVelocityFunc func(body *Body, gravity vec.Vec2, damping float64, dt float64)

BodyVelocityFunc is rigid body velocity update function type.

type Children

type Children struct {
	// contains filtered or unexported fields
}

type Circle

type Circle struct {
	*Shape
	// contains filtered or unexported fields
}

func (*Circle) CacheData

func (circle *Circle) CacheData(transform Transform) BB

func (*Circle) PointQuery

func (circle *Circle) PointQuery(p vec.Vec2, info *PointQueryInfo)

func (*Circle) Radius

func (circle *Circle) Radius() float64

func (*Circle) SegmentQuery

func (circle *Circle) SegmentQuery(a, b vec.Vec2, radius float64, info *SegmentQueryInfo)

func (*Circle) SetRadius

func (circle *Circle) SetRadius(r float64)

func (*Circle) TransformC

func (circle *Circle) TransformC() vec.Vec2

type ClosestPoints

type ClosestPoints struct {
	// contains filtered or unexported fields
}

func EPA

func EPA(ctx SupportContext, v0, v1, v2 MinkowskiPoint) ClosestPoints

EPA is called from GJK when two shapes overlap. Finds the closest points on the surface of two overlapping shapes using the EPA algorithm. This is a moderately expensive step! Avoid it by adding radii to your shapes so their inner polygons won't overlap.

func EPARecurse

func EPARecurse(ctx SupportContext, count int, hull []MinkowskiPoint, iteration int) ClosestPoints

EPARecurse implementation of the EPA loop. Each recursion adds a point to the convex hull until it's known that we have the closest point on the surface.

func GJK

func GJK(ctx SupportContext, collisionId *uint32) ClosestPoints

GJK finds the closest points between two shapes using the GJK algorithm.

func GJKRecurse

func GJKRecurse(ctx SupportContext, v0, v1 MinkowskiPoint, iteration int) ClosestPoints

GJKRecurse implementation of the GJK loop.

type CollisionBeginFunc

type CollisionBeginFunc func(arb *Arbiter, space *Space, userData any) bool

CollisionBeginFunc is collision begin event function callback type. Returning false from a begin callback causes the collision to be ignored until the the separate callback is called when the objects stop colliding.

type CollisionFunc

type CollisionFunc func(info *CollisionInfo)

type CollisionHandler

type CollisionHandler struct {
	// Collision type identifier of the first shape that this handler recognizes.
	// In the collision handler callback, the shape with this type will be the first argument. Read only.
	TypeA CollisionType
	// Collision type identifier of the second shape that this handler recognizes.
	// In the collision handler callback, the shape with this type will be the second argument. Read only.
	TypeB CollisionType
	// This function is called when two shapes with types that match this collision handler begin colliding.
	BeginFunc CollisionBeginFunc
	// This function is called each step when two shapes with types that match this collision handler are colliding.
	// It's called before the collision solver runs so that you can affect a collision's outcome.
	PreSolveFunc CollisionPreSolveFunc
	// This function is called each step when two shapes with types that match this collision handler are colliding.
	// It's called after the collision solver runs so that you can read back information about the collision to trigger events in your game.
	PostSolveFunc CollisionPostSolveFunc
	// This function is called when two shapes with types that match this collision handler stop colliding.
	SeparateFunc CollisionSeparateFunc
	// This is a user definable context pointer that is passed to all of the collision handler functions.
	UserData any
}

CollisionHandler is struct that holds function callback pointers to configure custom collision handling. Collision handlers have a pair of types; when a collision occurs between two shapes that have these types, the collision handler functions are triggered.

type CollisionInfo

type CollisionInfo struct {
	// contains filtered or unexported fields
}

CollisionInfo collision info struct

func Collide

func Collide(a, b *Shape, collisionID uint32, contacts []Contact) CollisionInfo

Collide performs a collision between two shapes

func (*CollisionInfo) PushContact

func (info *CollisionInfo) PushContact(p1, p2 vec.Vec2, hash HashValue)

type CollisionPostSolveFunc

type CollisionPostSolveFunc func(arb *Arbiter, space *Space, userData any)

CollisionPostSolveFunc is collision post-solve event function callback type.

type CollisionPreSolveFunc

type CollisionPreSolveFunc func(arb *Arbiter, space *Space, userData any) bool

CollisionPreSolveFunc is collision pre-solve event function callback type.

Returning false from a pre-step callback causes the collision to be ignored until the next step.

type CollisionSeparateFunc

type CollisionSeparateFunc func(arb *Arbiter, space *Space, userData any)

CollisionSeparateFunc is collision separate event function callback type.

type CollisionType

type CollisionType uintptr
const WildcardCollisionType CollisionType = ^CollisionType(0)

type Constrainer

type Constrainer interface {
	PreStep(dt float64)
	ApplyCachedImpulse(dtCoef float64)
	ApplyImpulse(dt float64)
	GetImpulse() float64
}

type Constraint

type Constraint struct {
	Class Constrainer

	PreSolve  ConstraintPreSolveFunc
	PostSolve ConstraintPostSolveFunc

	UserData any
	// contains filtered or unexported fields
}

func NewConstraint

func NewConstraint(class Constrainer, a, b *Body) *Constraint

func NewDampedRotarySpring

func NewDampedRotarySpring(a, b *Body, restAngle, stiffness, damping float64) *Constraint

func NewDampedSpring

func NewDampedSpring(a, b *Body, anchorA, anchorB vec.Vec2, restLength, stiffness, damping float64) *Constraint

func NewGearJoint

func NewGearJoint(a, b *Body, phase, ratio float64) *Constraint

func NewGrooveJoint

func NewGrooveJoint(a, b *Body, grooveA, grooveB, anchorB vec.Vec2) *Constraint

func NewPinJoint

func NewPinJoint(a, b *Body, anchorA, anchorB vec.Vec2) *Constraint

func NewPivotJoint

func NewPivotJoint(a, b *Body, pivot vec.Vec2) *Constraint

func NewPivotJoint2

func NewPivotJoint2(a, b *Body, anchorA, anchorB vec.Vec2) *Constraint

func NewRatchetJoint

func NewRatchetJoint(a, b *Body, phase, ratchet float64) *Constraint

func NewRotaryLimitJoint

func NewRotaryLimitJoint(a, b *Body, min, max float64) *Constraint

func NewSimpleMotor

func NewSimpleMotor(a, b *Body, rate float64) *Constraint

func NewSlideJoint

func NewSlideJoint(a, b *Body, anchorA, anchorB vec.Vec2, min, max float64) *Constraint

func (*Constraint) ActivateBodies

func (c *Constraint) ActivateBodies()

func (*Constraint) BodyA added in v1.6.0

func (c *Constraint) BodyA() *Body

func (*Constraint) BodyB added in v1.6.0

func (c *Constraint) BodyB() *Body

func (Constraint) ErrorBias

func (c Constraint) ErrorBias() float64

func (Constraint) MaxBias

func (c Constraint) MaxBias() float64

func (Constraint) MaxForce

func (c Constraint) MaxForce() float64

func (*Constraint) Next

func (c *Constraint) Next(body *Body) *Constraint

func (*Constraint) SetCollideBodies

func (c *Constraint) SetCollideBodies(collideBodies bool)

func (*Constraint) SetErrorBias

func (c *Constraint) SetErrorBias(errorBias float64)

func (*Constraint) SetMaxBias

func (c *Constraint) SetMaxBias(max float64)

func (*Constraint) SetMaxForce

func (c *Constraint) SetMaxForce(max float64)

type ConstraintPostSolveFunc

type ConstraintPostSolveFunc func(*Constraint, *Space)

type ConstraintPreSolveFunc

type ConstraintPreSolveFunc func(*Constraint, *Space)

type Contact

type Contact struct {
	R1, R2 vec.Vec2
	// contains filtered or unexported fields
}

func (*Contact) Clone

func (c *Contact) Clone() Contact

type ContactBuffer

type ContactBuffer struct {
	// contains filtered or unexported fields
}

func NewContactBuffer

func NewContactBuffer(stamp uint, slice *ContactBuffer) *ContactBuffer

func (*ContactBuffer) InitHeader

func (c *ContactBuffer) InitHeader(stamp uint, splice *ContactBuffer) *ContactBuffer

type ContactPointSet

type ContactPointSet struct {
	// Count is the number of contact points in the set.
	Count int
	// Normal is the normal of the collision.
	Normal vec.Vec2

	Points [MaxContactsPerArbiter]struct {
		// The position of the contact on the surface of each shape.
		PointA, PointB vec.Vec2
		// Distance is penetration distance of the two shapes. Overlapping means it will be negative.
		//
		// This value is calculated as p2.Sub(p1).Dot(n) and is ignored by Arbiter.SetContactPointSet().
		Distance float64
	}
}

ContactPointSet wraps up the important collision data for an arbiter.

func ShapesCollideInfo added in v1.11.0

func ShapesCollideInfo(a, b *Shape) ContactPointSet

Return contact information about two shapes.

type DampedRotarySpring

type DampedRotarySpring struct {
	*Constraint

	RestAngle, Stiffness, Damping float64
	SpringTorqueFunc              func(spring *DampedRotarySpring, relativeAngle float64) float64
	// contains filtered or unexported fields
}

func (*DampedRotarySpring) ApplyCachedImpulse

func (joint *DampedRotarySpring) ApplyCachedImpulse(dtCoef float64)

func (*DampedRotarySpring) ApplyImpulse

func (spring *DampedRotarySpring) ApplyImpulse(dt float64)

func (*DampedRotarySpring) GetImpulse

func (joint *DampedRotarySpring) GetImpulse() float64

func (*DampedRotarySpring) PreStep

func (spring *DampedRotarySpring) PreStep(dt float64)

type DampedSpring

type DampedSpring struct {
	*Constraint

	AnchorA, AnchorB               vec.Vec2
	RestLength, Stiffness, Damping float64
	SpringForceFunc                DampedSpringForceFunc
	// contains filtered or unexported fields
}

func (*DampedSpring) ApplyCachedImpulse

func (spring *DampedSpring) ApplyCachedImpulse(dtCoef float64)

func (*DampedSpring) ApplyImpulse

func (spring *DampedSpring) ApplyImpulse(dt float64)

func (*DampedSpring) GetImpulse

func (spring *DampedSpring) GetImpulse() float64

func (*DampedSpring) PreStep

func (spring *DampedSpring) PreStep(dt float64)

type DampedSpringForceFunc

type DampedSpringForceFunc func(spring *DampedSpring, dist float64) float64

type Edge

type Edge struct {
	// contains filtered or unexported fields
}

func SupportEdgeForPoly

func SupportEdgeForPoly(poly *PolyShape, n vec.Vec2) Edge

func SupportEdgeForSegment

func SupportEdgeForSegment(seg *Segment, n vec.Vec2) Edge

type EdgePoint

type EdgePoint struct {
	// contains filtered or unexported fields
}

type FColor

type FColor struct {
	R, G, B, A float32
}

16 bytes

type GearJoint

type GearJoint struct {
	*Constraint
	// contains filtered or unexported fields
}

func (*GearJoint) ApplyCachedImpulse

func (joint *GearJoint) ApplyCachedImpulse(dtCoef float64)

func (*GearJoint) ApplyImpulse

func (joint *GearJoint) ApplyImpulse(dt float64)

func (*GearJoint) GetImpulse

func (joint *GearJoint) GetImpulse() float64

func (*GearJoint) PreStep

func (joint *GearJoint) PreStep(dt float64)

type GrooveJoint

type GrooveJoint struct {
	*Constraint

	GrooveN, GrooveA, GrooveB vec.Vec2
	AnchorB                   vec.Vec2
	// contains filtered or unexported fields
}

func (*GrooveJoint) ApplyCachedImpulse

func (joint *GrooveJoint) ApplyCachedImpulse(dtCoef float64)

func (*GrooveJoint) ApplyImpulse

func (joint *GrooveJoint) ApplyImpulse(dt float64)

func (*GrooveJoint) GetImpulse

func (joint *GrooveJoint) GetImpulse() float64

func (*GrooveJoint) PreStep

func (joint *GrooveJoint) PreStep(dt float64)

type Handle

type Handle struct {
	// contains filtered or unexported fields
}

func (*Handle) Init

func (hand *Handle) Init(obj *Shape)

type HashSet

type HashSet[T, U comparable] struct {
	// contains filtered or unexported fields
}

HashSet implements a hash set

func NewHashSet

func NewHashSet[T, U comparable](isEqual func(ptr T, elt U) bool) *HashSet[T, U]

NewHashSet is a HashSet constructor

func (*HashSet[T, U]) Count

func (set *HashSet[T, U]) Count() uint

Count returns the number of entries

func (*HashSet[T, U]) Each

func (set *HashSet[T, U]) Each(f func(U))

Each calls f for every U in the HashSet.

func (*HashSet[T, U]) Filter

func (set *HashSet[T, U]) Filter(f func(U) bool)

Filter removes elements if f returns false

func (*HashSet[T, U]) Find

func (set *HashSet[T, U]) Find(hash HashValue, ptr T) U

Find returns the U the T is in, or nil.

func (*HashSet[T, U]) Insert

func (set *HashSet[T, U]) Insert(hash HashValue, ptr T, transform func(obj T) U) U

Insert returns the U the T is in, or inserts a new U and returns it.

func (*HashSet[T, U]) Remove

func (set *HashSet[T, U]) Remove(hash HashValue, ptr T) U

Remove removes the T from the HashSet, returning the U it was in.

type HashSetBin

type HashSetBin[U comparable] struct {
	// contains filtered or unexported fields
}

HashSetBin implements a linked list

type HashValue

type HashValue uintptr

func HashPair

func HashPair(a, b HashValue) HashValue

type IDrawer added in v1.9.0

type IDrawer interface {
	DrawCircle(pos vec.Vec2, angle, radius float64, outline, fill FColor, data any)
	DrawSegment(a, b vec.Vec2, fill FColor, data any)
	DrawFatSegment(a, b vec.Vec2, radius float64, outline, fill FColor, data any)
	DrawPolygon(count int, verts []vec.Vec2, radius float64, outline, fill FColor, data any)
	DrawDot(size float64, pos vec.Vec2, fill FColor, data any)

	Flags() uint
	OutlineColor() FColor
	ShapeColor(shape *Shape, data any) FColor
	ConstraintColor() FColor
	CollisionPointColor() FColor
	Data() any
}

type IShape added in v1.10.0

type IShape interface {
	CacheData(transform Transform) BB
	PointQuery(p vec.Vec2, info *PointQueryInfo)
	SegmentQuery(a, b vec.Vec2, radius float64, info *SegmentQueryInfo)
}

type Leaf

type Leaf struct {
	// contains filtered or unexported fields
}

type MarkContext

type MarkContext struct {
	// contains filtered or unexported fields
}

type Mat2x2

type Mat2x2 struct {
	// contains filtered or unexported fields
}

Mat2x2 is a 2x2 matrix type used for tensors and such.

func (*Mat2x2) Transform

func (m *Mat2x2) Transform(v vec.Vec2) vec.Vec2

Transform transforms Vector v

type MinkowskiPoint

type MinkowskiPoint struct {
	// contains filtered or unexported fields
}

MinkowskiPoint is a point on the surface of two shapes' minkowski difference.

func NewMinkowskiPoint

func NewMinkowskiPoint(a, b SupportPoint) MinkowskiPoint

func (MinkowskiPoint) ClosestPoints

func (v0 MinkowskiPoint) ClosestPoints(v1 MinkowskiPoint) ClosestPoints

ClosestPoints calculates the closest points on two shapes given the closest edge on their minkowski difference to (0, 0)

type Node

type Node struct {
	Children
	Leaf
	// contains filtered or unexported fields
}

func (*Node) IsLeaf

func (node *Node) IsLeaf() bool

func (*Node) MarkLeaf

func (leaf *Node) MarkLeaf(context *MarkContext)

func (*Node) MarkLeafQuery

func (subtree *Node) MarkLeafQuery(leaf *Node, left bool, context *MarkContext)

func (*Node) MarkSubtree

func (subtree *Node) MarkSubtree(context *MarkContext)

func (*Node) Other

func (node *Node) Other(child *Node) *Node

func (*Node) SubtreeQuery

func (subtree *Node) SubtreeQuery(obj any, bb BB, query SpatialIndexQuery, data any)

func (*Node) SubtreeSegmentQuery

func (subtree *Node) SubtreeSegmentQuery(obj any, a, b vec.Vec2, tExit float64, f SpatialIndexSegmentQuery, data any) float64

type Pair

type Pair struct {
	// contains filtered or unexported fields
}

type PinJoint

type PinJoint struct {
	*Constraint
	AnchorA, AnchorB vec.Vec2
	Dist             float64
	// contains filtered or unexported fields
}

func (*PinJoint) ApplyCachedImpulse

func (joint *PinJoint) ApplyCachedImpulse(dtCoef float64)

func (*PinJoint) ApplyImpulse

func (joint *PinJoint) ApplyImpulse(dt float64)

func (*PinJoint) GetImpulse

func (joint *PinJoint) GetImpulse() float64

func (*PinJoint) PreStep

func (joint *PinJoint) PreStep(dt float64)

type PivotJoint

type PivotJoint struct {
	*Constraint
	AnchorA, AnchorB vec.Vec2
	// contains filtered or unexported fields
}

func (*PivotJoint) ApplyCachedImpulse

func (joint *PivotJoint) ApplyCachedImpulse(dtCoef float64)

func (*PivotJoint) ApplyImpulse

func (joint *PivotJoint) ApplyImpulse(dt float64)

func (*PivotJoint) GetImpulse

func (joint *PivotJoint) GetImpulse() float64

func (*PivotJoint) PreStep

func (joint *PivotJoint) PreStep(dt float64)

type PointQueryContext

type PointQueryContext struct {
	// contains filtered or unexported fields
}

type PointQueryInfo

type PointQueryInfo struct {
	// The nearest shape, nil if no shape was within range.
	Shape *Shape
	// The closest point on the shape's surface. (in world space coordinates)
	Point vec.Vec2
	// The distance to the point. The distance is negative if the point is inside the shape.
	Distance float64
	// The gradient of the signed distance function.
	// The value should be similar to info.p/info.d, but accurate even for very small values of info.d.
	Gradient vec.Vec2
}

PointQueryInfo is point query info struct.

type PolyLine

type PolyLine struct {
	Verts []vec.Vec2
}

func DouglasPeucker

func DouglasPeucker(
	verts []vec.Vec2,
	reduced *PolyLine,
	length, start, end int,
	min, tol float64,
) *PolyLine

Recursive function used by PolylineSimplifyCurves().

func (*PolyLine) Enqueue

func (pl *PolyLine) Enqueue(v vec.Vec2) *PolyLine

func (*PolyLine) IsClosed

func (pl *PolyLine) IsClosed() bool

func (*PolyLine) IsShort

func (pl *PolyLine) IsShort(count, start, end int, min float64) bool

IsShort checks if the total length of a polyline segment is less than 'min'. It iterates from 'start' to 'end', summing the distances between consecutive vertices. If the length exceeds 'min', it returns false, otherwise true.

Parameters:
- count: // Total number of vertices in the polyline.
- start: // Starting index for the length calculation.
- end: // Ending index for the length calculation.
- min: // Minimum length threshold.

func (*PolyLine) Push

func (pl *PolyLine) Push(v vec.Vec2) *PolyLine

func (*PolyLine) SimplifyCurves

func (pl *PolyLine) SimplifyCurves(tol float64) *PolyLine

Recursively reduce the vertex count on a polyline. Works best for smooth shapes. 'tol' is the maximum error for the reduction. The reduced polyline will never be farther than this distance from the original polyline.

func (*PolyLine) SimplifyVertexes

func (pl *PolyLine) SimplifyVertexes(tol float64) *PolyLine

Join similar adjacent line segments together. Works well for hard edged shapes. 'tol' is the minimum anglular difference in radians of a vertex.

type PolyLineSet

type PolyLineSet struct {
	Lines []*PolyLine
}

func (*PolyLineSet) FindEnds

func (pls *PolyLineSet) FindEnds(v vec.Vec2) int

Find the polyline that ends with v.

func (*PolyLineSet) FindStarts

func (pls *PolyLineSet) FindStarts(v vec.Vec2) int

Find the polyline that starts with v.

func (*PolyLineSet) Join

func (pls *PolyLineSet) Join(before, after int)

this may deletion could be slow? https://yourbasic.org/golang/delete-element-slice/

func (*PolyLineSet) Push

func (pls *PolyLineSet) Push(v *PolyLine)

Add a new polyline to a polyline set.

type PolyShape

type PolyShape struct {
	*Shape
	Radius float64

	// The untransformed Planes are appended at the end of the transformed Planes.
	Planes []SplittingPlane
	// contains filtered or unexported fields
}

func (*PolyShape) CacheData

func (ps *PolyShape) CacheData(transform Transform) BB

func (*PolyShape) Count

func (ps *PolyShape) Count() int

func (*PolyShape) PointQuery

func (ps *PolyShape) PointQuery(p vec.Vec2, info *PointQueryInfo)

func (*PolyShape) SegmentQuery

func (ps *PolyShape) SegmentQuery(a, b vec.Vec2, r2 float64, info *SegmentQueryInfo)

func (*PolyShape) SetVerts

func (ps *PolyShape) SetVerts(count int, verts []vec.Vec2)

func (*PolyShape) SetVertsRaw

func (p *PolyShape) SetVertsRaw(count int, verts []vec.Vec2)

func (*PolyShape) SetVertsUnsafe

func (ps *PolyShape) SetVertsUnsafe(count int, verts []vec.Vec2, transform Transform)

func (*PolyShape) TransformVert

func (ps *PolyShape) TransformVert(i int) vec.Vec2

func (*PolyShape) Vert

func (ps *PolyShape) Vert(vertIndex int) vec.Vec2

type PostStepCallback

type PostStepCallback struct {
	// contains filtered or unexported fields
}

type PostStepCallbackFunc

type PostStepCallbackFunc func(space *Space, key any, data any)

type RatchetJoint

type RatchetJoint struct {
	*Constraint

	Angle, Phase, Ratchet float64
	// contains filtered or unexported fields
}

func (*RatchetJoint) ApplyCachedImpulse

func (joint *RatchetJoint) ApplyCachedImpulse(dtCoef float64)

func (*RatchetJoint) ApplyImpulse

func (joint *RatchetJoint) ApplyImpulse(dt float64)

func (*RatchetJoint) GetImpulse

func (joint *RatchetJoint) GetImpulse() float64

func (*RatchetJoint) PreStep

func (joint *RatchetJoint) PreStep(dt float64)

type RotaryLimitJoint

type RotaryLimitJoint struct {
	*Constraint

	Min, Max float64
	// contains filtered or unexported fields
}

func (*RotaryLimitJoint) ApplyCachedImpulse

func (joint *RotaryLimitJoint) ApplyCachedImpulse(dtCoef float64)

func (*RotaryLimitJoint) ApplyImpulse

func (joint *RotaryLimitJoint) ApplyImpulse(dt float64)

func (*RotaryLimitJoint) GetImpulse

func (joint *RotaryLimitJoint) GetImpulse() float64

func (*RotaryLimitJoint) PreStep

func (joint *RotaryLimitJoint) PreStep(dt float64)

type Segment

type Segment struct {
	*Shape
	// contains filtered or unexported fields
}

Segment is a segment Shape

func (*Segment) A

func (seg *Segment) A() vec.Vec2

func (*Segment) B

func (seg *Segment) B() vec.Vec2

func (*Segment) CacheData

func (seg *Segment) CacheData(transform Transform) BB

func (*Segment) Normal

func (seg *Segment) Normal() vec.Vec2

func (*Segment) PointQuery

func (seg *Segment) PointQuery(p vec.Vec2, info *PointQueryInfo)

func (*Segment) Radius

func (seg *Segment) Radius() float64

func (*Segment) SegmentQuery

func (seg *Segment) SegmentQuery(a, b vec.Vec2, r2 float64, info *SegmentQueryInfo)

func (*Segment) SetEndpoints

func (seg *Segment) SetEndpoints(a, b vec.Vec2)

func (*Segment) SetRadius

func (seg *Segment) SetRadius(r float64)

func (*Segment) TransformA

func (seg *Segment) TransformA() vec.Vec2

func (*Segment) TransformB

func (seg *Segment) TransformB() vec.Vec2

type SegmentQueryContext

type SegmentQueryContext struct {
	// contains filtered or unexported fields
}

type SegmentQueryInfo

type SegmentQueryInfo struct {
	// The shape that was hit, or nil if no collision occurred.
	Shape *Shape
	// The point of impact.
	Point vec.Vec2
	// The normal of the surface hit.
	Normal vec.Vec2
	// The normalized distance along the query segment in the range [0, 1].
	Alpha float64
}

SegmentQueryInfo is segment query info struct.

type Shape

type Shape struct {
	Class    IShape
	Body     *Body
	Space    *Space
	UserData any
	Filter   ShapeFilter
	// You can assign types to collision shapes that triggercallbacks when objects
	// of certain types touch.
	CollisionType CollisionType
	// Sensor is a boolean value if this shape is a Sensor or not.
	// Sensors only call collision callbacks, and never generate real collisions.
	Sensor bool
	// The surface velocity of the object. Useful for creating conveyor belts or
	// players that move around. This value is only used when calculating friction,
	// not resolving the collision.
	SurfaceVelocity      vec.Vec2
	Elasticity, Friction float64
	BB                   BB
	// contains filtered or unexported fields
}

func NewBoxShape added in v1.11.0

func NewBoxShape(body *Body, w, h, r float64) *Shape

NewBoxShape returns a Box shape with specified width 'w', height 'h', and rounding radius 'roundingRadius'. The shape is attached to the body.

Parameters:

  • body: The body to which the shape will be attached.
  • w: The width of the box.
  • h: The height of the box.
  • r: The rounding radius of the box corners.

func NewBoxShape2 added in v1.11.0

func NewBoxShape2(body *Body, bb BB, r float64) *Shape

NewBoxShape2 returns a Box shape using a bounding box 'bb' and a rounding radius 'roundingRadius'. The shape is attached to the body.

Parameters:

  • body: The body to which the shape will be attached.
  • bb: The bounding box defining the shape dimensions.
  • r: The rounding radius of the box corners.

func NewCircleShape added in v1.11.0

func NewCircleShape(b *Body, r float64, offset vec.Vec2) *Shape

NewCircleShape returns a Circle shape with a specified radius and offset.

The shape is attached to the given body.

Parameters:

  • b: The body to which the shape will be attached.
  • r: The radius of the circle.
  • offset: The position of the circle's center.

func NewPolyShape

func NewPolyShape(b *Body, vertices []vec.Vec2, t Transform, r float64) *Shape

NewPolyShape returns a Polygon shape with a given vertices.

Parameters:

  • b: The body to which the shape will be attached.
  • vertices: The list of vertex positions.
  • t: The transformation applied to the vertex positions.
  • r: The rounding radius of the polygon corners.

func NewPolyShapeRaw

func NewPolyShapeRaw(
	body *Body,
	count int,
	verts []vec.Vec2,
	roundingRadius float64,
) *Shape

Initialize a polygon shape with rounded corners. The vertexes must be convex with a counter-clockwise winding.

func NewSegmentShape added in v1.11.0

func NewSegmentShape(body *Body, a, b vec.Vec2, r float64) *Shape

NewSegmentShape returns a new Segment shape using two points 'a' and 'b' and rounding radius 'r'. The shape is attached to the given body.

Parameters:

  • body: The body to which the shape will be attached.
  • a: The first point of the segment.
  • b: The second point of the segment.
  • r: The radius of the segment shape.

func NewShape

func NewShape(class IShape, body *Body, massInfo *ShapeMassInfo) *Shape

func (*Shape) Area

func (sh *Shape) Area() float64

func (*Shape) CacheBB

func (sh *Shape) CacheBB() BB

func (*Shape) CenterOfGravity

func (sh *Shape) CenterOfGravity() vec.Vec2

func (*Shape) Density

func (sh *Shape) Density() float64

func (*Shape) HashId

func (sh *Shape) HashId() HashValue

func (*Shape) Mass

func (sh *Shape) Mass() float64

func (*Shape) MassInfo

func (sh *Shape) MassInfo() *ShapeMassInfo

func (*Shape) Moment

func (sh *Shape) Moment() float64

func (*Shape) Order

func (s *Shape) Order() int

func (*Shape) Point

func (sh *Shape) Point(i uint32) SupportPoint

func (*Shape) PointQuery

func (sh *Shape) PointQuery(p vec.Vec2) PointQueryInfo

Perform a nearest point query.

It finds the closest point on the surface of shape to a specific point. The value returned is the distance between the points. A negative distance means the point is inside the shape.

func (*Shape) SegmentQuery

func (sh *Shape) SegmentQuery(a, b vec.Vec2, radius float64, info *SegmentQueryInfo) bool

Perform a segment query against a shape.

info must be a pointer to a valid SegmentQueryInfo structure.

func (*Shape) SetBody added in v1.10.0

func (sh *Shape) SetBody(b *Body)

func (*Shape) SetCollisionType

func (sh *Shape) SetCollisionType(collisionType CollisionType)

SetCollisionType sets collision type. You can assign types to shapes that trigger callbacks (CollisionHandler) when objects of certain types touch

func (*Shape) SetDensity

func (sh *Shape) SetDensity(density float64)

func (*Shape) SetElasticity

func (sh *Shape) SetElasticity(e float64)

SetElasticity sets elasticity (0-1 range)

func (*Shape) SetFriction

func (sh *Shape) SetFriction(u float64)

func (*Shape) SetHashId

func (sh *Shape) SetHashId(hashid HashValue)

func (*Shape) SetMass

func (sh *Shape) SetMass(mass float64)

SetMass wakes up sleeping or idle body then sets mass

func (*Shape) SetSensor

func (sh *Shape) SetSensor(sensor bool)

SetSensor wakes up sleeping or idle body then sets Shape.Sensor. sensor is a boolean value if this shape is a sensor or not. Sensors only call collision callbacks, and never generate real collisions.

func (*Shape) SetShapeFilter added in v1.0.1

func (sh *Shape) SetShapeFilter(filter ShapeFilter)

func (Shape) String

func (s Shape) String() string

func (*Shape) Update

func (sh *Shape) Update(transform Transform) BB

type ShapeFilter

type ShapeFilter struct {
	// Two objects with the same non-zero group value do not collide.
	// This is generally used to group objects in a composite object together to disable self collisions.
	Group uint
	// A bitmask of user definable categories that this object belongs to.
	// The category/mask combinations of both objects in a collision must agree for a collision to occur.
	Categories uint
	// A bitmask of user definable category types that this object object collides with.
	// The category/mask combinations of both objects in a collision must agree for a collision to occur.
	Mask uint
}

ShapeFilter is fast collision filtering type that is used to determine if two objects collide before calling collision or query callbacks.

func (ShapeFilter) Reject

func (sf ShapeFilter) Reject(other ShapeFilter) bool

Reject checks whether two ShapeFilter objects should be considered incompatible. It returns true if the filters should be rejected based on the following conditions: - If both filters belong to the same group (and the group is not 0). - If the category/mask combination of either filter does not match the other.

  • Specifically, it checks if the categories of the first filter don't match the mask of the second, or vice versa.

Returns true if the filters are considered incompatible, otherwise false.

type ShapeMassInfo

type ShapeMassInfo struct {
	// contains filtered or unexported fields
}

ShapeMassInfo is mass info struct

func CircleShapeMassInfo

func CircleShapeMassInfo(mass, radius float64, center vec.Vec2) *ShapeMassInfo

func NewSegmentMassInfo

func NewSegmentMassInfo(mass float64, a, b vec.Vec2, r float64) *ShapeMassInfo

func PolyShapeMassInfo

func PolyShapeMassInfo(mass float64, count int, verts []vec.Vec2, r float64) *ShapeMassInfo

type ShapePair

type ShapePair struct {
	// contains filtered or unexported fields
}

type SimpleMotor

type SimpleMotor struct {
	*Constraint

	Rate float64
	// contains filtered or unexported fields
}

func (*SimpleMotor) ApplyCachedImpulse

func (motor *SimpleMotor) ApplyCachedImpulse(dtCoef float64)

func (*SimpleMotor) ApplyImpulse

func (motor *SimpleMotor) ApplyImpulse(dt float64)

func (*SimpleMotor) GetImpulse

func (motor *SimpleMotor) GetImpulse() float64

func (*SimpleMotor) PreStep

func (motor *SimpleMotor) PreStep(dt float64)

type SlideJoint

type SlideJoint struct {
	*Constraint

	AnchorA, AnchorB vec.Vec2
	Min, Max         float64
	// contains filtered or unexported fields
}

func (*SlideJoint) ApplyCachedImpulse

func (joint *SlideJoint) ApplyCachedImpulse(dtCoef float64)

func (*SlideJoint) ApplyImpulse

func (joint *SlideJoint) ApplyImpulse(dt float64)

func (*SlideJoint) GetImpulse

func (joint *SlideJoint) GetImpulse() float64

func (*SlideJoint) PreStep

func (joint *SlideJoint) PreStep(dt float64)

type Space

type Space struct {
	UserData any

	// Iterations is number of iterations to use in the impulse solver to solve
	// contacts and other constrain. Must be non-zero.
	Iterations uint

	// IdleSpeedThreshold is speed threshold for a body to be considered idle.
	// The default value of 0 means to let the space guess a good threshold based on gravity.
	IdleSpeedThreshold float64

	// SleepTimeThreshold is time a group of bodies must remain idle in order to fall asleep.
	// Enabling sleeping also implicitly enables the the contact graph.
	// The default value of INFINITY disables the sleeping algorithm.
	SleepTimeThreshold float64

	// StaticBody is the Space provided static body for a given s.
	// This is merely provided for convenience and you are not required to use it.
	StaticBody *Body

	// Gravity to pass to rigid bodies when integrating velocity.
	Gravity vec.Vec2

	// Damping rate expressed as the fraction of velocity bodies retain each second.
	//
	// A value of 0.9 would mean that each body's velocity will drop 10% per second.
	// The default value is 1.0, meaning no Damping is applied.
	// @note This Damping value is different than those of DampedSpring and DampedRotarySpring.
	Damping float64

	// CollisionSlop is amount of encouraged penetration between colliding shapes.
	//
	// Used to reduce oscillating contacts and keep the collision cache warm.
	// Defaults to 0.1. If you have poor simulation quality,
	// increase this number as much as possible without allowing visible amounts of overlap.
	CollisionSlop float64

	// CollisionBias determines how fast overlapping shapes are pushed apart.
	//
	// Expressed as a fraction of the error remaining after each second.
	// Defaults to math.Pow(0.9, 60) meaning that Chipmunk fixes 10% of overlap each frame at 60Hz.
	CollisionBias float64

	// Number of frames that contact information should persist.
	// Defaults to 3. There is probably never a reason to change this value.
	CollisionPersistence uint
	Arbiters             []*Arbiter
	DynamicBodies        []*Body
	StaticBodies         []*Body

	PostStepCallbacks []*PostStepCallback
	// contains filtered or unexported fields
}

func NewSpace

func NewSpace() *Space

NewSpace allocates and initializes a Space

func (*Space) Activate

func (s *Space) Activate(body *Body)

func (*Space) AddBody

func (s *Space) AddBody(body *Body)

AddBody adds body to the space.

Do not add the same Body twice.

func (*Space) AddBodyWithShapes added in v1.10.0

func (s *Space) AddBodyWithShapes(body *Body)

AddBodyWithShapes adds body to the space with body's shapes.

Do not add the same Body twice.

func (*Space) AddCollisionHandler added in v1.13.1

func (s *Space) AddCollisionHandler(a, b CollisionType) *CollisionHandler

AddCollisionHandler adds and returns the CollisionHandler for collisions between objects of type a and b.

Fill the desired collision callback functions, for details see the CollisionHandler object.

Whenever shapes with collision types (Shape.CollisionType) a and b collide, this handler will be used to process the collision events. When a new collision handler is created, the callbacks will all be set to builtin callbacks that perform the default behavior (call the wildcard handlers, and accept all collisions).

func (*Space) AddCollisionHandler2 added in v1.13.1

func (s *Space) AddCollisionHandler2(handler *CollisionHandler)

AddCollisionHandler adds handler to space, for details see the CollisionHandler{} struct.

func (*Space) AddConstraint

func (s *Space) AddConstraint(constraint *Constraint) *Constraint

func (*Space) AddPostStepCallback

func (s *Space) AddPostStepCallback(f PostStepCallbackFunc, key, data any) bool

AddPostStepCallback defines a callback to be run just before s.Step() finishes.

The main reason you want to define post-step callbacks is to get around the restriction that you cannot call the add/remove methods from a collision handler callback. Post-step callbacks run right before the next (or current) call to s.Step() returns when it is safe to add and remove objects. You can only schedule one post-step callback per key value, this prevents you from accidentally removing an object twice. Registering a second callback for the same key is a no-op.

example: type PostStepCallbackFunc func(space *Space, key any, data any)

func (*Space) AddShape

func (s *Space) AddShape(shape *Shape) *Shape

AddShape adds a collision shape to the simulation.

If the shape is attached to a static body, it will be added as a static shape

func (*Space) AddWildcardCollisionHandler added in v1.13.1

func (s *Space) AddWildcardCollisionHandler(typeA CollisionType) *CollisionHandler

AddWildcardCollisionHandler sets a collision handler for given collision type. This handler will be used any time an object with this type collides with another object, regardless of its type. A good example is a projectile that should be destroyed the first time it hits anything. There may be a specific collision handler and two wildcard handlers. It’s up to the specific handler to decide if and when to call the wildcard handlers and what to do with their return values. When a new wildcard handler is created, the callbacks will all be set to builtin callbacks that perform the default behavior. (accept all collisions in Begin() and PreSolve(), or do nothing for PostSolve() and Separate().

func (*Space) BBQuery

func (s *Space) BBQuery(bb BB, filter ShapeFilter, f SpaceBBQueryFunc, data any)

func (*Space) ContactBufferGetArray

func (s *Space) ContactBufferGetArray() []Contact

func (*Space) ContainsBody

func (s *Space) ContainsBody(body *Body) bool

func (*Space) ContainsConstraint

func (s *Space) ContainsConstraint(constraint *Constraint) bool

func (*Space) ContainsShape

func (s *Space) ContainsShape(shape *Shape) bool

func (*Space) Deactivate

func (s *Space) Deactivate(body *Body)

func (*Space) DynamicBodyCount

func (s *Space) DynamicBodyCount() int

DynamicBodyCount returns the total number of dynamic bodies in space

func (*Space) DynamicShapeCount added in v1.10.0

func (s *Space) DynamicShapeCount() int

func (*Space) EachBody

func (s *Space) EachBody(f func(b *Body))

EachBody calls func f for each body in the space

Example:

s.EachBody(func(body *cm.Body) {
	fmt.Println(body.Position())
})

func (*Space) EachConstraint

func (s *Space) EachConstraint(f func(*Constraint))

func (*Space) EachDynamicBody added in v1.7.1

func (s *Space) EachDynamicBody(f func(b *Body))

EachDynamicBody calls func f for each dynamic body in the space

func (*Space) EachDynamicShape added in v1.7.1

func (s *Space) EachDynamicShape(f func(*Shape))

EachDynamicShape calls func f for each dynamic shape in the space

func (*Space) EachShape

func (s *Space) EachShape(f func(*Shape))

EachShape calls func f for each shape in the space

func (*Space) EachStaticBody added in v1.7.1

func (s *Space) EachStaticBody(f func(b *Body))

EachStaticBody calls func f for each static body in the space

func (*Space) EachStaticShape added in v1.7.1

func (s *Space) EachStaticShape(f func(*Shape))

EachStaticShape calls func f for each static shape in the space

func (*Space) FilterArbiters

func (s *Space) FilterArbiters(body *Body, filter *Shape)

func (*Space) IsLocked added in v1.7.0

func (s *Space) IsLocked() bool

IsLocked returns true from inside a callback when objects cannot be added/removed.

func (*Space) Lock

func (s *Space) Lock()

func (*Space) LookupHandler

func (s *Space) LookupHandler(a, b CollisionType, defaultHandler *CollisionHandler) *CollisionHandler

LookupHandler finds and returns the matching a/b handler

func (*Space) PointQueryNearest

func (s *Space) PointQueryNearest(point vec.Vec2, maxDistance float64, filter ShapeFilter) *PointQueryInfo

Query the space at a point and return the nearest shape found. Returns nil if no shapes were found.

func (*Space) PopContacts

func (s *Space) PopContacts(count int)

func (*Space) PostStepCallback

func (s *Space) PostStepCallback(key any) *PostStepCallback

func (*Space) ProcessComponents

func (s *Space) ProcessComponents(dt float64)

func (*Space) PushContacts

func (s *Space) PushContacts(count int)

func (*Space) PushFreshContactBuffer

func (s *Space) PushFreshContactBuffer()

func (*Space) ReindexShape added in v1.9.1

func (s *Space) ReindexShape(shape *Shape)

ReindexShape re-computes the hash of the shape in both the dynamic and static list.

func (*Space) RemoveBody

func (s *Space) RemoveBody(body *Body)

RemoveBody removes a body from the simulation

func (*Space) RemoveBodyWithShapes added in v1.0.1

func (s *Space) RemoveBodyWithShapes(body *Body)

RemoveBodyWithShapes removes a body and body's shapes from the simulation

func (*Space) RemoveConstraint

func (s *Space) RemoveConstraint(constraint *Constraint)

func (*Space) RemoveShape

func (s *Space) RemoveShape(shape *Shape)

RemoveShape removes a collision shape from the simulation.

func (*Space) SegmentQuery

func (s *Space) SegmentQuery(start, end vec.Vec2, radius float64, filter ShapeFilter, f SpaceSegmentQueryFunc, data any)

func (*Space) SegmentQueryFirst

func (s *Space) SegmentQueryFirst(start, end vec.Vec2, radius float64, filter ShapeFilter) SegmentQueryInfo

func (*Space) SetGravity

func (s *Space) SetGravity(gravity vec.Vec2)

SetGravity sets gravity and wake up all of the sleeping bodies since the gravity changed.

func (*Space) SetStaticBody

func (s *Space) SetStaticBody(body *Body)

func (*Space) ShapeCount added in v1.10.0

func (s *Space) ShapeCount() int

func (*Space) ShapeQuery

func (s *Space) ShapeQuery(shape *Shape, callback func(shape *Shape, points *ContactPointSet)) bool

ShapeQuery queries a space for any shapes overlapping the this shape and call the callback for each shape found.

func (*Space) SliceForBodyType added in v1.13.1

func (s *Space) SliceForBodyType(t BodyType) *[]*Body

SliceForBodyType returns bodies of the given type in the space.

func (*Space) StaticBodyCount

func (s *Space) StaticBodyCount() int

StaticBodyCount returns the total number of static bodies in space

func (*Space) StaticShapeCount added in v1.10.0

func (s *Space) StaticShapeCount() int

func (*Space) Step

func (s *Space) Step(dt float64)

func (*Space) TimeStep

func (s *Space) TimeStep() float64

func (*Space) UncacheArbiter

func (s *Space) UncacheArbiter(arb *Arbiter)

func (*Space) Unlock

func (s *Space) Unlock(runPostStep bool)

func (*Space) UseSpatialHash

func (s *Space) UseSpatialHash(dim float64, count int)

func (*Space) UseWildcardDefaultHandler

func (s *Space) UseWildcardDefaultHandler()

type SpaceBBQueryFunc

type SpaceBBQueryFunc func(shape *Shape, data any)

type SpaceHash

type SpaceHash struct {
	*SpatialIndex
	// contains filtered or unexported fields
}

func (*SpaceHash) Contains

func (hash *SpaceHash) Contains(obj *Shape, hashId HashValue) bool

func (*SpaceHash) Count

func (hash *SpaceHash) Count() int

func (*SpaceHash) Each

func (hash *SpaceHash) Each(f SpatialIndexIterator)

func (*SpaceHash) Insert

func (hash *SpaceHash) Insert(obj *Shape, hashId HashValue)

func (*SpaceHash) Query

func (hash *SpaceHash) Query(obj any, bb BB, f SpatialIndexQuery, data any)

func (*SpaceHash) Reindex

func (hash *SpaceHash) Reindex()

func (*SpaceHash) ReindexObject

func (hash *SpaceHash) ReindexObject(obj *Shape, hashId HashValue)

func (*SpaceHash) ReindexQuery

func (hash *SpaceHash) ReindexQuery(f SpatialIndexQuery, data any)

func (*SpaceHash) Remove

func (hash *SpaceHash) Remove(obj *Shape, hashId HashValue)

func (*SpaceHash) SegmentQuery

func (hash *SpaceHash) SegmentQuery(obj any, a, b vec.Vec2, tExit float64, f SpatialIndexSegmentQuery, data any)

modified from http://playtechs.blogspot.com/2007/03/raytracing-on-grid.html

type SpaceHashBin

type SpaceHashBin struct {
	// contains filtered or unexported fields
}

type SpacePointQueryFunc

type SpacePointQueryFunc func(*Shape, vec.Vec2, float64, vec.Vec2, any)

type SpaceSegmentQueryFunc

type SpaceSegmentQueryFunc func(shape *Shape, point, normal vec.Vec2, alpha float64, data any)

type SpatialIndex

type SpatialIndex struct {
	// contains filtered or unexported fields
}

func NewBBTree

func NewBBTree(bbfunc SpatialIndexBB, staticIndex *SpatialIndex) *SpatialIndex

func NewSpaceHash

func NewSpaceHash(celldim float64, num int, bbfunc SpatialIndexBB, staticIndex *SpatialIndex) *SpatialIndex

func NewSpatialIndex

func NewSpatialIndex(klass SpatialIndexer, bbfunc SpatialIndexBB, staticIndex *SpatialIndex) *SpatialIndex

func (*SpatialIndex) CollideStatic

func (dynamicIndex *SpatialIndex) CollideStatic(staticIndex *SpatialIndex, f SpatialIndexQuery, data any)

func (*SpatialIndex) GetRootIfTree

func (index *SpatialIndex) GetRootIfTree() *Node

func (*SpatialIndex) GetTree

func (index *SpatialIndex) GetTree() *BBTree

type SpatialIndexBB

type SpatialIndexBB func(obj *Shape) BB

type SpatialIndexIterator

type SpatialIndexIterator func(obj *Shape)

type SpatialIndexQuery

type SpatialIndexQuery func(obj1 any, obj2 *Shape, collisionId uint32, data any) uint32

type SpatialIndexSegmentQuery

type SpatialIndexSegmentQuery func(obj1 any, obj2 *Shape, data any) float64

type SpatialIndexer

type SpatialIndexer interface {
	// Count returns the number of objects currently stored in the index.
	Count() int

	// Each iterates over all objects in the spatial index, applying
	// the provided iterator function `f` to each object.
	Each(f SpatialIndexIterator)

	// Contains checks if a given object `obj` with the specified
	// `hashId` exists in the spatial index.
	Contains(obj *Shape, hashId HashValue) bool

	// Insert adds a new object `obj` with the specified `hashId` to
	// the spatial index.
	Insert(obj *Shape, hashId HashValue)

	// Remove deletes the object `obj` with the specified `hashId`
	// from the spatial index, if it exists.
	Remove(obj *Shape, hashId HashValue)

	// Reindex rebuilds the spatial index from the existing objects
	// to optimize query performance.
	Reindex()

	// ReindexObject updates the spatial position of the given object
	// `obj` in the index using the specified `hashId`.
	ReindexObject(obj *Shape, hashId HashValue)

	// ReindexQuery performs a reindexing query using the given
	// spatial query function `f` and additional `data`.
	ReindexQuery(f SpatialIndexQuery, data any)

	// Query allows querying the spatial index for objects that intersect
	// or are contained within the bounding box `bb` using the provided
	// query function `f` and additional `data`.
	Query(obj any, bb BB, f SpatialIndexQuery, data any)

	// SegmentQuery performs a segment-based query using the line segment
	// defined by points `a` and `b`. It allows querying objects affected
	// by the segment based on the `tExit` parameter, applying the
	// provided segment query function `f` and additional `data`.
	SegmentQuery(obj any, a, b vec.Vec2, tExit float64, f SpatialIndexSegmentQuery, data any)
}

SpatialIndexer is an interface for spatial indexing that provides methods to manage spatial objects efficiently. It is implemented by a BBTree structure, which organizes objects in a bounding volume tree.

type SplittingPlane

type SplittingPlane struct {
	V0, N vec.Vec2
}

type SupportContext

type SupportContext struct {
	// contains filtered or unexported fields
}

func (*SupportContext) Support

func (ctx *SupportContext) Support(n vec.Vec2) MinkowskiPoint

Support calculates the maximal point on the minkowski difference of two shapes along a particular axis.

type SupportPoint

type SupportPoint struct {
	// contains filtered or unexported fields
}

func CircleSupportPoint

func CircleSupportPoint(shape *Shape, _ vec.Vec2) SupportPoint

func NewSupportPoint

func NewSupportPoint(p vec.Vec2, index uint32) SupportPoint

func PolySupportPoint

func PolySupportPoint(shape *Shape, n vec.Vec2) SupportPoint

func SegmentSupportPoint

func SegmentSupportPoint(shape *Shape, n vec.Vec2) SupportPoint

type SupportPointFunc

type SupportPointFunc func(shape *Shape, n vec.Vec2) SupportPoint

type Thread

type Thread struct {
	// contains filtered or unexported fields
}
func (thread *Thread) Unlink()

type Transform

type Transform struct {
	// contains filtered or unexported fields
}

Transform represents a 2D affine transformation using a 2x3 matrix. This structure can be used to perform various transformations such as translation, rotation, scaling, and shearing of 2D objects.

The transformation matrix is represented as follows:

| a  b  tx |   -> X' = a * X + b * Y + tx
| c  d  ty |   -> Y' = c * X + d * Y + ty

Where:

  • a: Scaling factor in the X direction and component for rotation.
  • b: Shearing factor in the X direction (affects X based on Y).
  • c: Shearing factor in the Y direction (affects Y based on X).
  • d: Scaling factor in the Y direction and component for rotation.
  • tx: Translation in the X direction.
  • ty: Translation in the Y direction.

The Transform type can be used to compose multiple transformations, enabling complex transformations by multiplying matrices together.

func NewTransform

func NewTransform(a, c, tx, b, d, ty float64) Transform

NewTransform returns a new transform matrix.

Parameters:

  • (a, b) is the x basis vector.
  • (c, d) is the y basis vector.
  • (tx, ty) is the translation.

func NewTransformIdentity

func NewTransformIdentity() Transform

NewTransformIdentity creates and returns an identity transformation. The identity transformation is a special case of affine transformation that leaves the object's coordinates unchanged.

The identity matrix in 2D transforms points according to the following:

| 1  0  0 |   -> X' = 1 * X + 0 * Y + 0 = X
| 0  1  0 |   -> Y' = 0 * X + 1 * Y + 0 = Y

The identity transform is useful as a starting point for composing transformations, as applying it to any object will yield the same object without any modifications.

func NewTransformRigid

func NewTransformRigid(translate vec.Vec2, rotation float64) Transform

NewTransformRigid creates a new rigid transformation that combines translation and rotation.

Rigid transformation, or rigid motion, refers to a transformation that preserves the shape and size of objects while allowing them to change position and orientation in space. It includes translation, rotation, and reflection, maintaining distances and angles within the object.

Parameters:

  • translate: A 2D vector specifying the translation component.
  • rotation: The angle of rotation in radians.

Returns:

  • A Transform representing the combined translation and rotation.

func NewTransformRigidInverse

func NewTransformRigidInverse(t Transform) Transform

NewTransformRigidInverse returns the inverse of a given rigid transformation.

Rigid transformation, or rigid motion, refers to a transformation that preserves the shape and size of objects while allowing them to change position and orientation in space. It includes translation, rotation, and reflection, maintaining distances and angles within the object.

Parameters:

  • t: The original Transform to invert.

Returns:

  • The inverted Transform.

func NewTransformRotate

func NewTransformRotate(rotation float64) Transform

NewTransformRotate returns a new rigid transformation with rotation

func NewTransformScale

func NewTransformScale(scaleX, scaleY float64) Transform

NewTransformScale returns a new transformation with scaling

func NewTransformTranslate

func NewTransformTranslate(translate vec.Vec2) Transform

NewTransformTranslate returns a new transformation matrix with translation

func NewTransformTranspose

func NewTransformTranspose(a, c, tx, b, d, ty float64) Transform

NewTransformTranspose returns a new transformation matrix in transposed order.

func (Transform) Apply added in v1.11.0

func (t Transform) Apply(p vec.Vec2) vec.Vec2

Apply applies the transformation to a given abs point `p` and returns the transformed point. This transformation involves scaling, rotation, and translation based on the matrix values.

func (Transform) ApplyVector added in v1.11.0

func (t Transform) ApplyVector(v vec.Vec2) vec.Vec2

ApplyVector applies the transformation matrix (t) to a vector (v). This transformation modifies the vector's direction based on the current transformation without affecting its position.

Parameters:

  • v: the vector (Vec2) to be transformed, represented by X and Y coordinates.

Returns:

  • Vec2: the transformed vector after applying the matrix transformation.

func (Transform) AxialScale

func (t Transform) AxialScale(axis, pivot vec.Vec2, scale float64) Transform

Creates a transformation matrix for scaling along a given axis.

This function generates a transformation matrix that scales along a specified axis around a pivot point. If the scaling factor (scale) is different from 1.0, the transformation matrix will apply scaling along the direction of the axis.

Parameters:

  • axis: A vector representing the axis along which scaling will be applied.
  • pivot: The pivot point around which scaling is applied.
  • scale: The scaling factor. Values other than 1.0 scale the axis direction accordingly.

Returns:

  • Transform: Axial scale transformation matrix.

func (Transform) BB

func (t Transform) BB(bb BB) BB

BB applies the current transformation (t) to a bounding box (BB). It scales and rotates the bounding box around its center to create a transformed bounding box that accounts for the dimensions after transformation.

Parameters:

  • bb: the bounding box (BB) to be transformed, defined by its left (L), right (R), top (T), and bottom (B) boundaries.

Returns:

  • BB: the transformed bounding box, with dimensions adjusted based on the transformation applied.

func (Transform) BoneScale

func (t Transform) BoneScale(v0, v1 vec.Vec2) Transform

BoneScale creates a scaling and rotation transformation matrix based on a bone vector defined by the start and end points v0 and v1. It translates to v0 and scales along the direction to v1.

Parameters: - v0: The starting vector of the bone. - v1: The ending vector of the bone.

Returns: - A Transform that represents the scaling and rotation transformation matrix.

func (Transform) Inverse

func (t Transform) Inverse() Transform

Inverse returns the inverse of this matrix t.

func (Transform) Mult

func (t Transform) Mult(t2 Transform) Transform

Mult multiplies this and t2

Parameters:

  • t2 - The Transform to be multiplied with the receiver.

Returns:

  • A new Transform representing the result of the multiplication.

func (Transform) Ortho

func (t Transform) Ortho(bb BB) Transform

Ortho creates an orthographic transformation matrix based on the given bounding box (bb). It performs scaling and translation to fit coordinates within the bounding box.

Parameters: - bb: A bounding box with left (L), right (R), bottom (B), and top (T) boundaries.

Returns: - A Transform that represents the orthographic projection transformation matrix.

func (*Transform) Scale added in v1.11.0

func (t *Transform) Scale(x, y float64)

Scale matrix inplace

func (Transform) Wrap

func (t Transform) Wrap(inner Transform) Transform

Wrap applies the inverse of the current transformation (t) around another transformation (inner). This wraps inner with the inverse of t, then applies t, effectively creating a nested transformation.

Parameters:

  • inner: the Transform to wrap with the inverse of the current transformation.

Returns:

  • Transform: the resulting transformation after wrapping.

Directories

Path Synopsis
utils

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL