ebimath

package module
v1.2.4 Latest Latest
Warning

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

Go to latest
Published: Sep 19, 2025 License: MIT Imports: 6 Imported by: 9

README

ebi-math

ebi-math is a versatile Go package designed for Ebitengine to assist with various mathematical and geometric computations often needed in game development, graphics programming, or any 2D spatial calculations. This library provides a rich set of tools, including vector operations, transformation matrices, random number generation, and more.

Overview

This library consolidates and enhances functionalities from various sources into a unified, easy-to-use math toolkit. Here's what you can expect:

Key Features
  • Vector Operations:

    • 2D Vector (Vector) with operations like addition, subtraction, scaling, rotation, normalization, and more.
    • Functions for vector creation, manipulation, and component-wise math operations.
  • Rectangle Manipulations:

    • Rectangle type for handling 2D rectangular areas, including intersection checks, containment, and transformations considering rotation.
  • Transformations:

    • Transform structure for complex transformations, including positions, scales, rotations, and matrix operations for hierarchical transformations.
  • Point Handling:

    • Point type for integer-based coordinate systems, with methods for conversion between float and integer coordinates.
  • Random Number Generation:

    • Rand type for pseudo-random number generation, offering methods for different data types and distributions, including weighted random selection with RandPicker.
  • Utility Functions:

    • Mathematical utilities like linear interpolation (Lerp), cubic interpolation, clamping, angle conversions, and more.
Core Components
  • Vector: A 2D vector type with methods for geometric calculations.
  • Rectangle: Supports operations on 2D rectangles, including rotated rectangles.
  • Transform: A system for managing transformations in a scene graph-like structure.
  • Point: For handling discrete 2D points.
  • Rand: Customized random number generation with methods tailored for game logic or simulations.
  • RandPicker: Allows for weighted random selection, useful in scenarios where outcomes should have varying probabilities.
Usage Examples
import ebimath "github.com/edwinsyarief/ebi-math"

// Creating a vector
v := ebimath.V(3.0, 4.0)
fmt.Println(v.Length()) // Output: 5.0

// Handling transformations
t := ebimath.T()
t.SetPosition(ebimath.V(10, 10))
t.SetRotation(math.Pi / 4)
fmt.Println(t.Matrix()) // Outputs transformation matrix

// Using random number generation
r := ebimath.Random()
fmt.Println(r.FloatRange(0, 10)) // Random float between 0 and 10

// Weighted random selection
picker := ebimath.RandomPicker[int](r)
picker.AddOption(1, 0.3)
picker.AddOption(2, 0.7)
fmt.Println(picker.Pick()) // Either 1 or 2, with probabilities 30% and 70%
Installation

To use ebi-math in your Go project:

go get github.com/edwinsyarief/ebi-math

Wiki

For a more detailed documentation of all components and their usage, please visit the wiki.

Contributing

Contributions are welcome! If you have a bug report, a feature request, or would like to contribute code, please follow these steps:

  1. Fork the repository.

  2. Create a new branch for your feature or bug fix (git checkout -b feature/your-feature).

  3. Commit your changes (git commit -m 'feat: Add a new feature').

  4. Push to the branch (git push origin feature/your-feature).

  5. Open a Pull Request with a clear description of your changes.

License

This project is licensed under the MIT License. For more details, see the LICENSE file in this repository.

Documentation

Index

Constants

View Source
const (
	Pi      = 3.141592653589793
	Epsilon = 1e-9
)

Constants ---------

Variables

View Source
var (
	// ZeroVector represents a Vector at the origin (0, 0).
	ZeroVector = V2(0)
	// Right represents a unit vector pointing to the right (1, 0).
	Right = V(1, 0)
	// Left represents a unit vector pointing to the left (-1, 0).
	Left = Right.Negate()
	// Up represents a unit vector pointing up (0, 1).
	Up = V(0, 1)
	// Down represents a unit vector pointing down (0, -1).
	Down = Up.Negate()
)

Functions

func Abs

func Abs[T Number](value T) T

Absolute and Sign Functions --------------------------- Abs returns the absolute value.

func AdjustDestinationPixel

func AdjustDestinationPixel(x float32) float32

Pixel Adjustment ---------------- AdjustDestinationPixel adjusts the pixel position to avoid center issues in rendering.

func Clamp

func Clamp[T Number](value, min, max T) T

Clamping and Rounding --------------------- Clamp restricts a value to be within specified bounds.

func ClampTowardsZero

func ClampTowardsZero[T Number](value, clampReference T) T

ClampTowardsZero clamps a value towards zero based on another value's sign.

func CubicInterpolate

func CubicInterpolate(from, to, pre, post, t float64) float64

CubicInterpolate performs cubic interpolation between values.

func EqualsApproximately

func EqualsApproximately[T Float](a, b T) bool

Utility Functions for Floating Point Comparisons ------------------------------------------------ EqualsApproximately checks if two numbers of a generic float type are approximately equal.

func FastFloor

func FastFloor[T Float, U Number](value T) U

FastFloor performs a fast floor operation for floating-point numbers.

func Lerp

func Lerp[T Number](from, to, t T) T

Linear Interpolation -------------------- Lerp performs linear interpolation.

func Max

func Max[T Number](v1, v2 T) T

Min and Max Functions --------------------- Max returns the larger of two values.

func Min

func Min[T Number](v1, v2 T) T

Min returns the smaller of two values.

func RandomChoose

func RandomChoose[T any](r *Rand, elements ...T) (element T)

RandomChoose selects a random element from the provided elements.

func RandomElement

func RandomElement[T any](r *Rand, slice []T) (element T)

RandomElement selects a random element from the slice. Returns the zero value if the slice is empty.

func RandomIndex

func RandomIndex[T any](r *Rand, slice []T) int

RandomIndex selects a random index from a slice. Returns -1 if the slice is empty.

func RandomShuffle

func RandomShuffle[T any](r *Rand, slice []T)

RandomShuffle shuffles the elements of the slice in place.

func Repeat

func Repeat(t, length float64) float64

Math Utilities -------------- Repeat normalizes a value within a range.

func Sign

func Sign[T Number](value T) T

Sign returns +1 for positive numbers, -1 for negative numbers, ignoring zero.

func ToDegrees

func ToDegrees(radians float64) float64

Angle Conversion ---------------- ToDegrees converts radians to degrees.

func ToRadians

func ToRadians(degrees float64) float64

ToRadians converts degrees to radians.

Types

type Float added in v1.2.1

type Float interface {
	~float32 | ~float64
}

type Matrix

type Matrix = ebiten.GeoM

Type Aliases ------------

type Number added in v1.2.1

type Number interface {
	Float | ~int | ~int8 | ~int16 | ~int32 | ~int64
}

type Point

type Point struct {
	X, Y int
}

Point represents a point in 2D space with integer coordinates.

func P

func P(x, y int) Point

Constructor functions for Point ------------------------------- P creates a new Point with given integer x and y coordinates.

func Pf

func Pf(x, y float64) Point

Pf converts floating-point coordinates to a Point with integer coordinates.

type Rand

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

Rand provides methods for generating random numbers with various distributions.

func Random

func Random() *Rand

Random creates a new random number generator with the current time as seed.

func RandomWidthSeed

func RandomWidthSeed(seed1, seed2 int64) *Rand

RandomWidthSeed initializes a random number generator with a specific seed.

func (*Rand) Bool

func (self *Rand) Bool() bool

Bool returns a random boolean value where true has a 50% chance.

func (*Rand) Chance

func (self *Rand) Chance(probability float64) bool

Chance returns true with the given probability, false otherwise.

func (*Rand) Float64

func (self *Rand) Float64() float64

Float64 returns a random float64 in the range [0.0, 1.0).

func (*Rand) FloatRange

func (self *Rand) FloatRange(min, max float64) float64

FloatRange returns a random float64 within the specified range [min, max).

func (*Rand) IntRange

func (self *Rand) IntRange(min, max int) int

IntRange generates a random integer within the range [min, max].

func (*Rand) NextFloat64

func (self *Rand) NextFloat64(max float64) float64

NextFloat64 returns a random float64 in the range [0.0, max).

func (*Rand) Offset

func (self *Rand) Offset(min, max float64) Vector

Offset generates a random Vector within the given range for both X and Y components.

func (*Rand) PositiveInt

func (self *Rand) PositiveInt() int

PositiveInt returns a non-negative random int.

func (*Rand) PositiveInt64

func (self *Rand) PositiveInt64() int64

PositiveInt64 returns a non-negative random int64.

func (*Rand) Rad

func (self *Rand) Rad() float64

Rad returns a random angle in radians within the range [0, 2π).

func (*Rand) SetSeed

func (self *Rand) SetSeed(seed int64)

SetSeed sets the seed for the random number generator, allowing for reproducible randomness.

func (*Rand) Uint64

func (self *Rand) Uint64() uint64

Uint64 returns a random uint64 value.

func (*Rand) VectorRange

func (self *Rand) VectorRange(min, max Vector) Vector

VectorRange returns a random Vector within the specified range for both X and Y.

type RandPicker

type RandPicker[T any] struct {
	// contains filtered or unexported fields
}

RandPicker for weighted random selection ---------------------------------------

func RandomPicker

func RandomPicker[T any](r *Rand) *RandPicker[T]

RandomPicker creates a new RandPicker with the given random number generator.

func (*RandPicker[T]) AddOption

func (self *RandPicker[T]) AddOption(value T, weight float64)

AddOption adds a new option to the picker with the given weight for selection probability.

func (*RandPicker[T]) AddOptions

func (self *RandPicker[T]) AddOptions(values ...T)

AddOptions adds multiple options to the picker, each with a default weight of 1.

func (*RandPicker[T]) IsEmpty

func (self *RandPicker[T]) IsEmpty() bool

IsEmpty checks if there are no options in the picker.

func (*RandPicker[T]) Pick

func (self *RandPicker[T]) Pick() T

Pick selects a random option based on the weights provided. If no options exist, returns the zero value.

func (*RandPicker[T]) Reset

func (self *RandPicker[T]) Reset()

Reset clears all options from the picker, resetting it to an empty state.

type Rectangle

type Rectangle struct {
	Min   Vector
	Max   Vector
	Angle float64
}

Rectangle represents a 2D rectangle with min and max vectors for bounds and an orientation angle.

func NewRectangle

func NewRectangle(x1, y1, x2, y2 float64) Rectangle

NewRectangle creates a new axis-aligned rectangle.

func (Rectangle) Center

func (r Rectangle) Center() Vector

Center calculates and returns the center point of the rectangle.

func (Rectangle) Contains

func (r Rectangle) Contains(p Vector) bool

Contains checks if a point is within the rectangle.

func (Rectangle) ContainsRect

func (r Rectangle) ContainsRect(other Rectangle) bool

ContainsRect checks if one rectangle is completely inside another.

func (Rectangle) Equals

func (r Rectangle) Equals(other Rectangle) bool

Equals checks if two rectangles are equal.

func (Rectangle) GetAxis

func (r Rectangle) GetAxis(angle float64, index int) Vector

GetAxis returns one of the two axes of the rectangle based on its angle.

func (Rectangle) GetCorners

func (r Rectangle) GetCorners() [4]Vector

GetCorners returns the four corners of the rectangle, considering rotation.

func (Rectangle) Height

func (r Rectangle) Height() float64

Height returns the height of the rectangle.

func (Rectangle) Intersects

func (r Rectangle) Intersects(other Rectangle) bool

Intersects checks if two rectangles intersect using the Separating Axis Theorem. This handles rotated rectangles.

func (Rectangle) IntersectsCircle

func (r Rectangle) IntersectsCircle(center Vector, radius float64) bool

IntersectsCircle checks if the rectangle intersects with a circle.

func (Rectangle) IsEmpty

func (r Rectangle) IsEmpty() bool

IsEmpty checks if the rectangle has no area.

func (Rectangle) OverlapOnAxis

func (r Rectangle) OverlapOnAxis(other Rectangle, axis Vector) bool

OverlapOnAxis checks if there's overlap along a specific axis.

func (Rectangle) ProjectOntoAxis

func (r Rectangle) ProjectOntoAxis(axis Vector) struct{ Min, Max float64 }

ProjectOntoAxis projects the rectangle onto an axis, returning the min and max values.

func (*Rectangle) SetAngle

func (r *Rectangle) SetAngle(angle float64)

SetAngle updates the rotation angle of the rectangle.

func (Rectangle) Width

func (r Rectangle) Width() float64

Width returns the width of the rectangle.

func (Rectangle) X1

func (r Rectangle) X1() float64

X1 returns the min X coordinate.

func (Rectangle) X2

func (r Rectangle) X2() float64

X2 returns the max X coordinate.

func (Rectangle) Y1

func (r Rectangle) Y1() float64

Y1 returns the min Y coordinate.

func (Rectangle) Y2

func (r Rectangle) Y2() float64

Y2 returns the max Y coordinate.

type Transform

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

Transform represents a transformation in 2D space. It includes position, scale, rotation, and a parent for hierarchical transforms.

func T

func T() *Transform

T creates a new Transform with default values. The default scale is 1, and the dirty flag is set to true.

func (*Transform) Abs

func (self *Transform) Abs() Transform

Transform Modifiers ------------------- Abs returns a new transform with the absolute world properties of this transform, effectively disconnecting it from its parent hierarchy.

func (*Transform) AddScale

func (self *Transform) AddScale(add ...Vector)

AddScale adds to the current local scale.

func (*Transform) Connect

func (self *Transform) Connect(parent Transformer)

Connect establishes a parent-child relationship, preserving the object's world space transform.

func (*Transform) Connected

func (self *Transform) Connected() bool

Parent Management ----------------- Connected returns true if the transform has a parent.

func (*Transform) Disconnect

func (self *Transform) Disconnect()

Disconnect removes the parent relationship, making the transform absolute. It does this by creating a new absolute transform and overwriting the current one.

func (*Transform) GetInitialParentTransform

func (self *Transform) GetInitialParentTransform() *Transform

GetInitialParentTransform finds the topmost parent in the hierarchy. It iterates up the parent chain until it finds the root transform.

func (*Transform) GetParentTransform

func (self *Transform) GetParentTransform() *Transform

Methods for Parent Hierarchy ---------------------------- GetParentTransform returns the parent Transform or nil if there is no parent.

func (*Transform) GetTransform

func (self *Transform) GetTransform() *Transform

GetTransform returns this Transform. This method fulfills the Transformer interface.

func (*Transform) IsDirty

func (self *Transform) IsDirty() bool

IsDirty checks if this transform or any of its parents are dirty. This recursive check is used for cache invalidation.

func (*Transform) Matrix

func (self *Transform) Matrix() Matrix

Matrix computes the full world transformation matrix for this node. The result is cached to avoid repeated calculations.

func (*Transform) MatrixForParenting

func (self *Transform) MatrixForParenting() (Matrix, Matrix)

Matrix Operations ----------------- MatrixForParenting returns matrices for child positioning. It returns the world matrix without the origin offset and its inverse. It ensures the world matrix is up-to-date by calling Matrix() if needed.

func (*Transform) Move

func (self *Transform) Move(v ...Vector)

Move translates the transform by the given vector(s).

func (*Transform) Offset

func (self *Transform) Offset() Vector

Offset returns the local offset.

func (*Transform) Origin

func (self *Transform) Origin() Vector

Transformation Properties ------------------------- Origin returns the origin of the transform.

func (*Transform) Position

func (self *Transform) Position() Vector

Position returns the absolute position in world space. It calculates the world position by applying the transform's world matrix to the zero vector.

func (*Transform) Rel

func (self *Transform) Rel() Transform

Rel returns a copy of the transform with its parent set to nil.

func (*Transform) Replace

func (self *Transform) Replace(new Transformer)

Replace updates this transform's local properties to match the world properties of another transform.

func (*Transform) Rotate

func (self *Transform) Rotate(rotation float64)

Rotate adds to the current rotation.

func (*Transform) Rotation

func (self *Transform) Rotation() float64

Rotation returns the absolute rotation in world space.

func (*Transform) Scale

func (self *Transform) Scale() Vector

Scale returns the absolute scale in world space by multiplying with the parent's scale.

func (*Transform) SetOffset

func (self *Transform) SetOffset(offset Vector)

Offset ------ SetOffset updates the local offset.

func (*Transform) SetOrigin

func (self *Transform) SetOrigin(origin Vector)

SetOrigin updates the transform's origin and marks it as dirty.

func (*Transform) SetPosition

func (self *Transform) SetPosition(position Vector)

Position and Movement --------------------- SetPosition updates the position, preserving the world-space position by adjusting the local position based on the parent's inverse matrix.

func (*Transform) SetRotation

func (self *Transform) SetRotation(rotation float64)

Rotation -------- SetRotation updates the rotation, preserving the world-space rotation by adjusting the local rotation based on the parent's rotation.

func (*Transform) SetScale

func (self *Transform) SetScale(scale Vector)

Scale ----- SetScale updates the local scale.

type Transformer

type Transformer interface {
	GetParentTransform() *Transform
	GetTransform() *Transform
}

Transformer defines the interface for objects that have transforms.

type Vector

type Vector struct {
	X, Y float64
}

Vector represents a 2D vector with X and Y components.

func AngleToVector

func AngleToVector(angleRadians float64, length float64) Vector

Vector and Angle ---------------- AngleToVector converts an angle in radians to a vector with a given length.

func V

func V(x, y float64) Vector

V creates a new Vector with given x and y coordinates.

func V2

func V2(v float64) Vector

V2 creates a Vector where both X and Y are set to the same value.

func V2Int

func V2Int(v int) Vector

V2Int creates a Vector where both X and Y are set to the integer value converted to float64.

func VInt

func VInt(x, y int) Vector

VInt converts integer coordinates to a Vector.

func (Vector) Abs

func (self Vector) Abs() Vector

Abs returns a new Vector with the absolute values of X and Y.

func (Vector) Add

func (self Vector) Add(others ...Vector) Vector

Add adds one or more Vectors to this Vector, returning a new Vector.

func (Vector) AddF

func (self Vector) AddF(scalar float64) Vector

AddF adds a scalar to both components of the Vector, returning a new Vector.

func (Vector) Angle

func (self Vector) Angle() float64

Angle returns the angle of the Vector from the positive X-axis in radians.

func (Vector) AngleToPoint

func (self Vector) AngleToPoint(other Vector) float64

AngleToPoint returns the angle from this Vector towards another point.

func (Vector) Apply

func (self Vector) Apply(m Matrix) Vector

Apply applies a matrix transformation to this Vector.

func (Vector) Ceil

func (self Vector) Ceil() Vector

Ceil returns a new Vector with each component rounded up to the nearest integer.

func (Vector) ClampLength

func (self Vector) ClampLength(limit float64) Vector

ClampLength ensures the Vector's length does not exceed a given limit.

func (Vector) Cross added in v1.2.2

func (self Vector) Cross(other Vector) float64

func (Vector) DirectionTo

func (self Vector) DirectionTo(other Vector) Vector

DirectionTo returns a normalized vector pointing from this Vector to another.

func (Vector) DistanceSquaredTo

func (self Vector) DistanceSquaredTo(v2 Vector) float64

DistanceSquaredTo computes the squared distance to another Vector.

func (Vector) DistanceTo

func (self Vector) DistanceTo(v2 Vector) float64

DistanceTo calculates the Euclidean distance to another Vector.

func (Vector) Div

func (self Vector) Div(other Vector) Vector

Div divides the Vector by another Vector component-wise, returning a new Vector.

func (Vector) DivF

func (self Vector) DivF(scalar float64) Vector

DivF divides the Vector by a scalar, returning a new Vector.

func (Vector) Dot

func (self Vector) Dot(v2 Vector) float64

Dot computes the dot product between this Vector and another.

func (Vector) Equals

func (self Vector) Equals(other Vector) bool

Equals checks if two Vectors are equal within a small tolerance.

func (Vector) Extend added in v1.2.0

func (self Vector) Extend(length float64) Vector

Extend adds magnitude to the Vector in the direction it's already pointing.

func (Vector) Floor

func (self Vector) Floor() Vector

Floor returns a new Vector with each component rounded down to the nearest integer.

func (Vector) IsNormalized

func (self Vector) IsNormalized() bool

IsNormalized checks if the vector's length is approximately 1.

func (Vector) IsZero

func (self Vector) IsZero() bool

IsZero checks if the Vector is at the origin (0, 0).

func (Vector) Length

func (self Vector) Length() float64

Length returns the magnitude of the Vector.

func (Vector) LengthSquared

func (self Vector) LengthSquared() float64

LengthSquared returns the square of the Vector's length.

func (Vector) Lerp added in v1.2.3

func (v Vector) Lerp(other Vector, t float64) Vector

Lerp performs linear interpolation between two vectors. t is the interpolation factor, typically between 0 and 1.

func (Vector) MoveInDirection

func (self Vector) MoveInDirection(angle, distance float64) Vector

MoveInDirection moves the Vector in the direction of the angle by a given distance.

func (Vector) MoveTowards

func (self Vector) MoveTowards(other Vector, length float64) Vector

MoveTowards moves the Vector towards another Vector by a maximum distance.

func (Vector) Negate added in v1.2.0

func (self Vector) Negate() Vector

Negate returns a new Vector with both components negated.

func (Vector) Normalize added in v1.2.0

func (self Vector) Normalize() Vector

Normalize returns a unit vector in the same direction as this Vector.

func (Vector) Orthogonal added in v1.2.2

func (self Vector) Orthogonal() Vector

func (Vector) Reflect

func (self Vector) Reflect(normal Vector) Vector

Reflect reflects the vector against the given surface normal.

func (Vector) Rotate

func (self Vector) Rotate(angle float64) Vector

Rotate rotates the Vector by the given angle in radians.

func (Vector) RotateAround

func (self Vector) RotateAround(around Vector, angle float64) Vector

RotateAround rotates this Vector around another Vector by an angle in radians.

func (Vector) RotateDegrees

func (self Vector) RotateDegrees(degrees float64) Vector

RotateDegrees rotates the Vector by degrees.

func (Vector) Round

func (self Vector) Round() Vector

Round returns a new Vector with each component rounded to the nearest integer.

func (Vector) Scale

func (self Vector) Scale(other Vector) Vector

Scale scales the Vector by another Vector component-wise, returning a new Vector.

func (Vector) ScaleF

func (self Vector) ScaleF(scalar float64) Vector

ScaleF scales the Vector by a scalar, returning a new Vector.

func (Vector) Shorten added in v1.2.0

func (self Vector) Shorten(limit float64) Vector

Shorten subtracts the given magnitude from the Vector's existing magnitude.

func (Vector) String

func (self Vector) String() string

String returns a string representation of the Vector.

func (Vector) Sub

func (self Vector) Sub(others ...Vector) Vector

Sub subtracts one or more Vectors from this Vector, returning a new Vector.

func (Vector) SubF

func (self Vector) SubF(scalar float64) Vector

SubF subtracts a scalar from both components of the Vector, returning a new Vector.

func (Vector) ToInt

func (self Vector) ToInt() (int, int)

ToInt converts the Vector to integer coordinates.

func (Vector) VecTowards

func (self Vector) VecTowards(other Vector, length float64) Vector

VecTowards calculates a Vector of given length towards another point.

Jump to

Keyboard shortcuts

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