math3d

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2026 License: Apache-2.0 Imports: 1 Imported by: 4 modules, 3 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package math3d provides 3D linear algebra, rotations, transforms, and spatial primitives for NSGo 3D games using pure Go float32 types with zero external dependencies.

Conventions

Every type and function in this package follows one consistent set of conventions aligned with glTF 2.0, WebGPU, and Metal so matrices and vectors can be uploaded directly to GPU uniform buffers without transposing or flipping handedness:

  • Coordinate system: Right-handed, Y-up. +X points right (Vec3Right), +Y points up (Vec3Up), and -Z points forward (Vec3Forward). A default camera at the origin looks down -Z; +Z points toward the viewer. Cross products obey the right-hand rule: X × Y = Z, Y × Z = X, Z × X = Y.

  • Angles and rotations: All angles are in radians (use DegToRad and RadToDeg to convert). Positive rotation angles are counter-clockwise when looking from the positive tip of the rotation axis toward the origin (right-hand thumb rule).

  • Matrix layout: Mat3 ([9]float32) and Mat4 ([16]float32) are stored in column-major order: column c, row r lives at index c*3+r (Mat3) or c*4+r (Mat4). This matches WGSL mat4x4<f32>, Metal simd::float4x4, GLSL mat4, and glTF 2.0 node matrices directly.

  • Vector multiplication and composition: Vectors are treated as column vectors and multiplied on the right (M * v). Matrix multiplication composes right-to-left: (A.Mul(B)).MulVec4(v) == A.MulVec4(B.MulVec4(v)). Model transforms use TRS order: M = T * R * S (scale, then rotate, then translate). The full clip-space transform is P * V * M.

  • Clip-space (NDC) depth range: Perspective and Ortho default to WebGPU / Metal / Vulkan zero-to-one depth [0, 1] (also available explicitly as PerspectiveZO and OrthoZO), mapping view-space z = -near to NDC z = 0 and z = -far to NDC z = 1. OpenGL / WebGL negative-one-to-one depth [-1, 1] is available via PerspectiveNO and OrthoNO.

  • Quaternions: Quat stores (X, Y, Z, W) matching glTF 2.0's [x, y, z, w] order, with identity QuatIdentity() = {0, 0, 0, 1}. Unit quaternions represent right-handed rotations; q and -q represent the same rotation. Multiplication composes right-to-left, matching Mat4: (q1.Mul(q2)).RotateVec3(v) == q1.RotateVec3(q2.RotateVec3(v)). QuatFromEuler and ToEuler use intrinsic YXZ (yaw-pitch-roll: Ry(yaw) * Rx(pitch) * Rz(roll)); QuatFromEulerXYZ and ToEulerXYZ use intrinsic XYZ (Rx(x) * Ry(y) * Rz(z)).

  • Frustums and planes: Plane represents {p | Normal·p + D = 0}. FrustumFromMat4 (and FrustumFromMat4ZO) extracts six inward-pointing normalized planes via Gribb-Hartmann for [0, 1] depth projections; FrustumFromMat4NO extracts planes for [-1, 1] depth projections.

Index

Examples

Constants

View Source
const (
	FrustumLeft = iota
	FrustumRight
	FrustumBottom
	FrustumTop
	FrustumNear
	FrustumFar
)

Frustum plane indices.

Variables

This section is empty.

Functions

func ApproxEqual

func ApproxEqual(a, b, eps float32) bool

ApproxEqual reports whether |a - b| <= eps.

func Clamp

func Clamp(v, lo, hi float32) float32

Clamp restricts v to the closed interval [lo, hi].

func DegToRad

func DegToRad(deg float32) float32

DegToRad converts degrees to radians.

func Lerp

func Lerp(a, b, t float32) float32

Lerp linearly interpolates between a (at t=0) and b (at t=1).

func RadToDeg

func RadToDeg(rad float32) float32

RadToDeg converts radians to degrees.

Types

type AABB

type AABB struct {
	Min, Max Vec3
}

AABB is an axis-aligned bounding box defined by its minimum and maximum corners. An AABB is empty when Min.X > Max.X, Min.Y > Max.Y, or Min.Z > Max.Z. Use AABBEmpty to construct an identity box for incremental expansion.

Example

AABB grows to contain points and tests overlaps between boxes.

package main

import (
	"fmt"
	"strconv"

	"github.com/nsgo-dev/game/pkg/math3d"
)

// v prints a vector to two decimals, writing a rounded negative zero as 0.
func v(p math3d.Vec3) string {
	num := func(f float32) string {
		s := strconv.FormatFloat(float64(f), 'f', 2, 32)
		if s == "-0.00" {
			s = "0.00"
		}
		return s
	}
	return "(" + num(p.X) + ", " + num(p.Y) + ", " + num(p.Z) + ")"
}

func main() {
	b := math3d.AABBEmpty()
	for _, p := range []math3d.Vec3{{X: 1, Y: 2}, {X: -1, Z: 3}, {Y: -2}} {
		b = b.ExpandPoint(p)
	}
	fmt.Println(v(b.Min), v(b.Max), v(b.Center()))
	fmt.Println(b.Intersects(math3d.AABB{Min: math3d.Vec3{X: 0.5}, Max: math3d.Vec3{X: 5, Y: 5, Z: 5}}))
}
Output:
(-1.00, -2.00, 0.00) (1.00, 2.00, 3.00) (0.00, 0.00, 1.50)
true

func AABBEmpty

func AABBEmpty() AABB

AABBEmpty returns an empty AABB with Min at +Inf and Max at -Inf, ready to accumulate points with ExpandPoint or boxes with Union.

func (AABB) Center

func (b AABB) Center() Vec3

Center returns the center point of b, or Vec3Zero if b is empty.

func (AABB) Contains

func (b AABB) Contains(p Vec3) bool

Contains reports whether p lies inside or on the boundary of b.

func (AABB) Empty

func (b AABB) Empty() bool

Empty reports whether b represents an empty volume (any Min component exceeds Max).

func (AABB) ExpandPoint

func (b AABB) ExpandPoint(p Vec3) AABB

ExpandPoint returns the smallest AABB containing both b and point p.

func (AABB) HalfExtents

func (b AABB) HalfExtents() Vec3

HalfExtents returns half the size of b along each axis, or Vec3Zero if b is empty.

func (AABB) Intersects

func (b AABB) Intersects(other AABB) bool

Intersects reports whether b overlaps or touches other.

func (AABB) IsFinite

func (a AABB) IsFinite() bool

IsFinite reports whether both corners are finite. A NaN bound is not empty (its comparisons are false) and would otherwise poison spatial indexes.

func (AABB) Size

func (b AABB) Size() Vec3

Size returns the full width, height, and depth of b (Max - Min), or Vec3Zero if b is empty.

func (AABB) Transform

func (b AABB) Transform(m Mat4) AABB

Transform returns the tight axis-aligned bounding box enclosing b after transforming by m. For affine matrices this uses Arvo's exact O(1) method; for projective matrices all 8 corners are transformed.

func (AABB) Union

func (b AABB) Union(other AABB) AABB

Union returns the smallest AABB containing both b and other.

type CatmullRom3D

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

CatmullRom3D is a multi-segment interpolating 3D Catmull-Rom spline with configurable Barry-Goldman knot parameterization (alpha in [0, 1]).

Parameter t in [0, 1] maps uniformly across segments so control point i lies at t = float32(i) / float32(SegmentCount()).

Example

A CatmullRom3D curve passes through its control points; PointAtDistance moves along it at an even speed, as a camera rail or a patrol route needs.

package main

import (
	"fmt"
	"strconv"

	"github.com/nsgo-dev/game/pkg/math3d"
)

// v prints a vector to two decimals, writing a rounded negative zero as 0.
func v(p math3d.Vec3) string {
	num := func(f float32) string {
		s := strconv.FormatFloat(float64(f), 'f', 2, 32)
		if s == "-0.00" {
			s = "0.00"
		}
		return s
	}
	return "(" + num(p.X) + ", " + num(p.Y) + ", " + num(p.Z) + ")"
}

func main() {
	c := math3d.NewCatmullRom3D([]math3d.Vec3{{}, {X: 10}, {X: 10, Z: -10}}, false)
	fmt.Println(v(c.Point(0)), v(c.Point(1)))
	fmt.Printf("length %.1f\n", c.Length())
	fmt.Println(v(c.PointAtDistance(0)))
}
Output:
(0.00, 0.00, 0.00) (10.00, 0.00, -10.00)
length 20.4
(0.00, 0.00, 0.00)

func NewCatmullRom3D

func NewCatmullRom3D(points []Vec3, closed bool) *CatmullRom3D

NewCatmullRom3D constructs a centripetal (alpha = 0.5) 3D Catmull-Rom spline interpolating all points. Centripetal parameterization prevents cusps and self-intersections within segments.

func NewCatmullRom3DAlpha

func NewCatmullRom3DAlpha(points []Vec3, alpha float32, closed bool) *CatmullRom3D

NewCatmullRom3DAlpha constructs a 3D Catmull-Rom spline interpolating all points with knot parameterization exponent alpha clamped to [0, 1]:

  • alpha = 0.0: uniform
  • alpha = 0.5: centripetal (default)
  • alpha = 1.0: chordal

Open splines synthesize reflected ghost endpoints so the spline starts at points[0] and ends at points[len(points)-1]. Closed splines wrap seamlessly through all points. If len(points) < 2, an empty zero-length spline is returned.

func (*CatmullRom3D) Alpha

func (c *CatmullRom3D) Alpha() float32

Alpha returns the knot parameterization exponent in [0, 1].

func (*CatmullRom3D) Closed

func (c *CatmullRom3D) Closed() bool

Closed reports whether the spline forms a closed loop.

func (*CatmullRom3D) Derivative

func (c *CatmullRom3D) Derivative(t float32) Vec3

Derivative evaluates the unnormalized first derivative dP/dt at parameter t in [0, 1].

func (*CatmullRom3D) DistanceToT

func (c *CatmullRom3D) DistanceToT(dist float32) float32

DistanceToT maps an arc-length distance to parameter t in [0, 1].

func (*CatmullRom3D) FrameAt

func (c *CatmullRom3D) FrameAt(t float32, worldUp Vec3) CurveFrame

FrameAt evaluates the Rotation-Minimizing Frame at parameter t in [0, 1], initialized with worldUp at t=0.

func (*CatmullRom3D) FrameAtDistance

func (c *CatmullRom3D) FrameAtDistance(dist float32) CurveFrame

FrameAtDistance evaluates the Rotation-Minimizing Frame at arc-length distance dist.

func (*CatmullRom3D) Length

func (c *CatmullRom3D) Length() float32

Length returns the total arc length of the spline.

func (*CatmullRom3D) Point

func (c *CatmullRom3D) Point(t float32) Vec3

Point evaluates the spline position at parameter t in [0, 1].

func (*CatmullRom3D) PointAtDistance

func (c *CatmullRom3D) PointAtDistance(dist float32) Vec3

PointAtDistance evaluates the spline position at arc-length distance dist.

func (*CatmullRom3D) SegmentCount

func (c *CatmullRom3D) SegmentCount() int

SegmentCount returns the number of cubic segments in the spline.

func (*CatmullRom3D) Tangent

func (c *CatmullRom3D) Tangent(t float32) Vec3

Tangent evaluates the unit tangent vector at parameter t in [0, 1].

func (*CatmullRom3D) TangentAtDistance

func (c *CatmullRom3D) TangentAtDistance(dist float32) Vec3

TangentAtDistance evaluates the unit tangent vector at arc-length distance dist.

type CubicBezier3D

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

CubicBezier3D is a 3D cubic Bézier curve defined by four control points.

func NewCubicBezier3D

func NewCubicBezier3D(p0, p1, p2, p3 Vec3) *CubicBezier3D

NewCubicBezier3D constructs a 3D cubic Bézier curve from p0 to p3 with control handles p1 and p2, precomputing its Gauss-Legendre arc-length LUT and Rotation-Minimizing Frames.

func (*CubicBezier3D) Closed

func (c *CubicBezier3D) Closed() bool

Closed reports false because a single cubic Bézier segment is open.

func (*CubicBezier3D) Derivative

func (c *CubicBezier3D) Derivative(t float32) Vec3

Derivative evaluates the unnormalized first derivative dP/dt at parameter t in [0, 1].

func (*CubicBezier3D) DistanceToT

func (c *CubicBezier3D) DistanceToT(dist float32) float32

DistanceToT maps an arc-length distance in [0, Length()] to parameter t in [0, 1].

func (*CubicBezier3D) FrameAt

func (c *CubicBezier3D) FrameAt(t float32, worldUp Vec3) CurveFrame

FrameAt evaluates the Rotation-Minimizing Frame at parameter t in [0, 1], initialized with worldUp at t=0.

func (*CubicBezier3D) FrameAtDistance

func (c *CubicBezier3D) FrameAtDistance(dist float32) CurveFrame

FrameAtDistance evaluates the Rotation-Minimizing Frame at arc-length distance dist.

func (*CubicBezier3D) Length

func (c *CubicBezier3D) Length() float32

Length returns the total arc length of the curve.

func (*CubicBezier3D) Point

func (c *CubicBezier3D) Point(t float32) Vec3

Point evaluates the curve position at parameter t in [0, 1].

func (*CubicBezier3D) PointAtDistance

func (c *CubicBezier3D) PointAtDistance(dist float32) Vec3

PointAtDistance evaluates the curve position at arc-length distance dist.

func (*CubicBezier3D) Tangent

func (c *CubicBezier3D) Tangent(t float32) Vec3

Tangent evaluates the unit tangent vector at parameter t in [0, 1].

func (*CubicBezier3D) TangentAtDistance

func (c *CubicBezier3D) TangentAtDistance(dist float32) Vec3

TangentAtDistance evaluates the unit tangent vector at arc-length distance dist.

type CubicHermite3D

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

CubicHermite3D is a single-segment 3D cubic Hermite curve defined by start and end positions and their parametric endpoint tangents.

func NewCubicHermite3D

func NewCubicHermite3D(p0, m0, p1, m1 Vec3) *CubicHermite3D

NewCubicHermite3D constructs a 3D cubic Hermite curve starting at p0 with derivative m0 and ending at p1 with derivative m1, precomputing its Gauss-Legendre arc-length LUT and Rotation-Minimizing Frames.

func (*CubicHermite3D) Closed

func (c *CubicHermite3D) Closed() bool

Closed reports false because a single cubic Hermite segment is open.

func (*CubicHermite3D) Derivative

func (c *CubicHermite3D) Derivative(t float32) Vec3

Derivative evaluates the unnormalized first derivative dP/dt at parameter t in [0, 1]. At t=0 this equals m0; at t=1 this equals m1.

func (*CubicHermite3D) DistanceToT

func (c *CubicHermite3D) DistanceToT(dist float32) float32

DistanceToT maps an arc-length distance in [0, Length()] to parameter t in [0, 1].

func (*CubicHermite3D) FrameAt

func (c *CubicHermite3D) FrameAt(t float32, worldUp Vec3) CurveFrame

FrameAt evaluates the Rotation-Minimizing Frame at parameter t in [0, 1], initialized with worldUp at t=0.

func (*CubicHermite3D) FrameAtDistance

func (c *CubicHermite3D) FrameAtDistance(dist float32) CurveFrame

FrameAtDistance evaluates the Rotation-Minimizing Frame at arc-length distance dist.

func (*CubicHermite3D) Length

func (c *CubicHermite3D) Length() float32

Length returns the total arc length of the curve.

func (*CubicHermite3D) Point

func (c *CubicHermite3D) Point(t float32) Vec3

Point evaluates the curve position at parameter t in [0, 1].

func (*CubicHermite3D) PointAtDistance

func (c *CubicHermite3D) PointAtDistance(dist float32) Vec3

PointAtDistance evaluates the curve position at arc-length distance dist.

func (*CubicHermite3D) Tangent

func (c *CubicHermite3D) Tangent(t float32) Vec3

Tangent evaluates the unit tangent vector at parameter t in [0, 1].

func (*CubicHermite3D) TangentAtDistance

func (c *CubicHermite3D) TangentAtDistance(dist float32) Vec3

TangentAtDistance evaluates the unit tangent vector at arc-length distance dist.

type Curve3D

type Curve3D interface {
	// Point evaluates the 3D position at parameter t in [0, 1].
	Point(t float32) Vec3
	// Tangent evaluates the unit forward tangent vector at parameter t in [0, 1].
	Tangent(t float32) Vec3
	// Length returns the total arc length of the curve.
	Length() float32
	// DistanceToT maps an arc-length distance in [0, Length()] to parameter t in [0, 1].
	DistanceToT(dist float32) float32
	// PointAtDistance evaluates the 3D position at arc-length distance dist.
	PointAtDistance(dist float32) Vec3
	// TangentAtDistance evaluates the unit forward tangent at arc-length distance dist.
	TangentAtDistance(dist float32) Vec3
	// FrameAt evaluates a smooth Rotation-Minimizing Frame at parameter t in [0, 1],
	// initialized at t=0 with worldUp (or Vec3Up if worldUp is zero).
	FrameAt(t float32, worldUp Vec3) CurveFrame
	// FrameAtDistance evaluates the Rotation-Minimizing Frame at arc-length distance dist
	// using default world up (Vec3Up).
	FrameAtDistance(dist float32) CurveFrame
	// Closed reports whether the curve forms a closed loop.
	Closed() bool
}

Curve3D is a parameterized 3D curve supporting arc-length reparameterization and smooth Rotation-Minimizing Frames (RMF).

Parameter t lies in [0, 1]. Open curves clamp out-of-range t and dist values; closed curves wrap out-of-range values around the loop.

type CurveFrame

type CurveFrame struct {
	Position Vec3
	Tangent  Vec3
	Up       Vec3
	Right    Vec3
}

CurveFrame is an orthonormal right-handed reference frame attached to a 3D curve.

Following math3d conventions, Tangent points forward along the curve (local -Z), Up points along local +Y, and Right points along local +X (Right = Tangent × Up). The basis matrix columns [Right, Up, -Tangent] form a proper right-handed rotation with determinant +1.

func (CurveFrame) Mat4

func (f CurveFrame) Mat4() Mat4

Mat4 returns the column-major 4x4 rigid transform matrix for the frame, equivalent to f.Transform().ToMat4().

func (CurveFrame) Rotation

func (f CurveFrame) Rotation() Quat

Rotation returns the unit quaternion orienting local +X to Right, local +Y to Up, and local -Z (Vec3Forward) to Tangent.

func (CurveFrame) Transform

func (f CurveFrame) Transform() Transform

Transform returns the rigid TRS transform placing an object at Position oriented along the frame (with unit scale).

type Frustum

type Frustum struct {
	Planes [6]Plane
}

Frustum is a 6-plane view volume with normalized inward-pointing normals. A point lies inside the frustum when SignedDist >= 0 for all six planes.

func FrustumFromMat4

func FrustumFromMat4(vp Mat4) Frustum

FrustumFromMat4 extracts the six normalized inward-pointing frustum planes from a view-projection matrix vp using the Gribb-Hartmann method, assuming WebGPU/Metal [0, 1] NDC depth (Perspective / PerspectiveZO / Ortho / OrthoZO).

This is equivalent to FrustumFromMat4ZO. Use FrustumFromMat4NO for OpenGL [-1, 1] depth projections.

func FrustumFromMat4NO

func FrustumFromMat4NO(vp Mat4) Frustum

FrustumFromMat4NO extracts frustum planes from a view-projection matrix using negative-one-to-one [-1, 1] NDC depth (PerspectiveNO / OrthoNO).

func FrustumFromMat4ZO

func FrustumFromMat4ZO(vp Mat4) Frustum

FrustumFromMat4ZO extracts frustum planes from a view-projection matrix using zero-to-one [0, 1] NDC depth.

func (Frustum) ContainsPoint

func (f Frustum) ContainsPoint(p Vec3) bool

ContainsPoint reports whether p lies inside or on the boundary of f.

func (Frustum) IntersectsAABB

func (f Frustum) IntersectsAABB(b AABB) bool

IntersectsAABB reports whether box b lies inside or intersects f using the positive-vertex (p-vertex) test against each frustum plane.

func (Frustum) IntersectsSphere

func (f Frustum) IntersectsSphere(s Sphere) bool

IntersectsSphere reports whether sphere s lies inside or intersects f.

type HermiteSpline3D

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

HermiteSpline3D is a C1-continuous multi-segment 3D cubic Hermite spline.

func NewHermiteSpline3D

func NewHermiteSpline3D(points, tangents []Vec3, closed bool) *HermiteSpline3D

NewHermiteSpline3D constructs a multi-segment cubic Hermite spline interpolating points with corresponding per-point tangents.

When closed is false, len(points)-1 segments connect points[0] through points[n-1]. When closed is true, len(points) segments form a closed loop back to points[0]. Missing tangent entries (if len(tangents) < len(points)) default to the uniform Catmull-Rom tangent (points[i+1] - points[i-1]) / 2, one-sided at the ends of an open spline, so the curve keeps moving through those points instead of stopping and flipping its frame there (#546). Pass Vec3Zero explicitly for a point where the curve should stop. If len(points) < 2, an empty zero-length spline is returned.

func (*HermiteSpline3D) Closed

func (c *HermiteSpline3D) Closed() bool

Closed reports whether the spline forms a closed loop.

func (*HermiteSpline3D) Derivative

func (c *HermiteSpline3D) Derivative(t float32) Vec3

Derivative evaluates the unnormalized first derivative dP/dt at parameter t in [0, 1].

func (*HermiteSpline3D) DistanceToT

func (c *HermiteSpline3D) DistanceToT(dist float32) float32

DistanceToT maps an arc-length distance to parameter t in [0, 1].

func (*HermiteSpline3D) FrameAt

func (c *HermiteSpline3D) FrameAt(t float32, worldUp Vec3) CurveFrame

FrameAt evaluates the Rotation-Minimizing Frame at parameter t in [0, 1], initialized with worldUp at t=0.

func (*HermiteSpline3D) FrameAtDistance

func (c *HermiteSpline3D) FrameAtDistance(dist float32) CurveFrame

FrameAtDistance evaluates the Rotation-Minimizing Frame at arc-length distance dist.

func (*HermiteSpline3D) Length

func (c *HermiteSpline3D) Length() float32

Length returns the total arc length of the spline.

func (*HermiteSpline3D) Point

func (c *HermiteSpline3D) Point(t float32) Vec3

Point evaluates the spline position at parameter t in [0, 1].

func (*HermiteSpline3D) PointAtDistance

func (c *HermiteSpline3D) PointAtDistance(dist float32) Vec3

PointAtDistance evaluates the spline position at arc-length distance dist.

func (*HermiteSpline3D) SegmentCount

func (c *HermiteSpline3D) SegmentCount() int

SegmentCount returns the number of cubic segments in the spline.

func (*HermiteSpline3D) Tangent

func (c *HermiteSpline3D) Tangent(t float32) Vec3

Tangent evaluates the unit tangent vector at parameter t in [0, 1].

func (*HermiteSpline3D) TangentAtDistance

func (c *HermiteSpline3D) TangentAtDistance(dist float32) Vec3

TangentAtDistance evaluates the unit tangent vector at arc-length distance dist.

type Mat3

type Mat3 [9]float32

Mat3 is a 3x3 float32 matrix stored in column-major order. Element at (row, col) is at index col*3 + row.

func Mat3FromCols

func Mat3FromCols(c0, c1, c2 Vec3) Mat3

Mat3FromCols builds a Mat3 from its three column vectors.

func Mat3FromMat4

func Mat3FromMat4(m Mat4) Mat3

Mat3FromMat4 extracts the upper-left 3x3 submatrix of m.

func Mat3Identity

func Mat3Identity() Mat3

Mat3Identity returns the 3x3 identity matrix.

func NormalMatrix

func NormalMatrix(model Mat4) (Mat3, bool)

NormalMatrix returns the inverse-transpose of the upper-left 3x3 of model, suitable for transforming surface normals under non-uniform scale. It returns false if the upper-left 3x3 is singular.

func (Mat3) ApproxEqual

func (m Mat3) ApproxEqual(b Mat3, eps float32) bool

ApproxEqual reports whether every element of m is within eps of b.

func (Mat3) At

func (m Mat3) At(row, col int) float32

At returns the element at (row, col).

func (Mat3) Col

func (m Mat3) Col(col int) Vec3

Col returns column col (0..2) as a Vec3.

func (Mat3) Det

func (m Mat3) Det() float32

Det returns the determinant of m.

func (Mat3) Inverse

func (m Mat3) Inverse() (Mat3, bool)

Inverse returns the inverse of m and true, or the zero matrix and false if m is singular.

func (Mat3) Mul

func (m Mat3) Mul(b Mat3) Mat3

Mul returns the matrix product m * b.

func (Mat3) MulVec3

func (m Mat3) MulVec3(v Vec3) Vec3

MulVec3 returns the column-vector product m * v.

func (Mat3) Row

func (m Mat3) Row(row int) Vec3

Row returns row row (0..2) as a Vec3.

func (Mat3) Transpose

func (m Mat3) Transpose() Mat3

Transpose returns the transpose of m.

type Mat4

type Mat4 [16]float32

Mat4 is a 4x4 float32 matrix stored in column-major order, matching WGSL, Metal, GLSL, and glTF 2.0 directly. Element at (row, col) is at index col*4 + row.

func LookAt

func LookAt(eye, target, up Vec3) Mat4

LookAt returns a right-handed view matrix for a camera positioned at eye, looking toward target, with world up direction up. In the resulting view space, the camera sits at the origin looking down -Z with +X right and +Y up.

Example

Perspective and LookAt build the view-projection matrix of a camera, which maps a point in front of it into clip space and a Frustum for culling.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/math3d"
)

func main() {
	view := math3d.LookAt(math3d.Vec3{Z: 5}, math3d.Vec3Zero(), math3d.Vec3Up())
	proj := math3d.Perspective(math3d.DegToRad(90), 1, 0.1, 100)
	vp := proj.Mul(view)
	clip := vp.MulVec4(math3d.Vec3{X: 1, Y: 1}.Vec4(1))
	fmt.Printf("ndc x=%.2f y=%.2f\n", clip.X/clip.W, clip.Y/clip.W)

	f := math3d.FrustumFromMat4(vp)
	fmt.Println(f.ContainsPoint(math3d.Vec3Zero()), f.ContainsPoint(math3d.Vec3{Z: 10}))
}
Output:
ndc x=0.20 y=0.20
true false

func Mat4FromCols

func Mat4FromCols(c0, c1, c2, c3 Vec4) Mat4

Mat4FromCols builds a Mat4 from its four column vectors.

func Mat4Identity

func Mat4Identity() Mat4

Mat4Identity returns the 4x4 identity matrix.

func Ortho

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

Ortho returns a right-handed orthographic projection matrix mapping view-space [left, right] x [bottom, top] x [-far, -near] to [-1, 1] x [-1, 1] x [0, 1] (WebGPU/Metal NDC depth [0, 1]).

This is equivalent to OrthoZO. Use OrthoNO for OpenGL [-1, 1] depth.

func OrthoNO

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

OrthoNO returns a right-handed orthographic projection matrix for negative-one-to-one NDC depth [-1, 1] (OpenGL, WebGL).

func OrthoZO

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

OrthoZO returns a right-handed orthographic projection matrix for zero-to-one NDC depth [0, 1] (WebGPU, Metal, Vulkan, D3D).

func Perspective

func Perspective(fovY, aspect, near, far float32) Mat4

Perspective returns a right-handed perspective projection matrix mapping view-space z in [-near, -far] to WebGPU/Metal NDC depth [0, 1]. fovY is the vertical field of view in radians; aspect is width/height; near and far are positive distances from the camera (0 < near < far).

This is equivalent to PerspectiveZO. Use PerspectiveNO for OpenGL [-1, 1] depth.

func PerspectiveNO

func PerspectiveNO(fovY, aspect, near, far float32) Mat4

PerspectiveNO returns a right-handed perspective projection matrix for negative-one-to-one NDC depth [-1, 1] (OpenGL, WebGL).

func PerspectiveZO

func PerspectiveZO(fovY, aspect, near, far float32) Mat4

PerspectiveZO returns a right-handed perspective projection matrix for zero-to-one NDC depth [0, 1] (WebGPU, Metal, Vulkan, D3D).

func RotateAxis

func RotateAxis(axis Vec3, rad float32) Mat4

RotateAxis returns a right-handed rotation matrix around axis by rad radians. If axis has zero length, Mat4Identity is returned.

func RotateX

func RotateX(rad float32) Mat4

RotateX returns a right-handed rotation matrix around the +X axis by rad radians.

func RotateY

func RotateY(rad float32) Mat4

RotateY returns a right-handed rotation matrix around the +Y axis by rad radians.

func RotateZ

func RotateZ(rad float32) Mat4

RotateZ returns a right-handed rotation matrix around the +Z axis by rad radians.

func Scale

func Scale(v Vec3) Mat4

Scale returns a scaling matrix with diagonal (v.X, v.Y, v.Z, 1).

func TRS

func TRS(pos Vec3, rot Quat, scale Vec3) Mat4

TRS builds a model matrix from translation pos, rotation rot, and scale in standard T * R * S order (scale first, then rotate, then translate).

func Translate

func Translate(v Vec3) Mat4

Translate returns a translation matrix by v.

func (Mat4) ApproxEqual

func (m Mat4) ApproxEqual(b Mat4, eps float32) bool

ApproxEqual reports whether every element of m is within eps of b.

func (Mat4) At

func (m Mat4) At(row, col int) float32

At returns the element at (row, col).

func (Mat4) Col

func (m Mat4) Col(col int) Vec4

Col returns column col (0..3) as a Vec4.

func (Mat4) Decompose

func (m Mat4) Decompose() (pos Vec3, rot Quat, scale Vec3, ok bool)

Decompose factors an affine TRS matrix into translation pos, unit rotation rot, and scale such that TRS(pos, rot, scale) reproduces m.

If m has a reflection (negative upper-left 3x3 determinant), the sign is placed on scale.X so rot remains a proper right-handed rotation. It returns ok = false if m has projective terms or a zero scale axis.

func (Mat4) Det

func (m Mat4) Det() float32

Det returns the determinant of m.

func (Mat4) Inverse

func (m Mat4) Inverse() (Mat4, bool)

Inverse returns the inverse of m and true, or the zero matrix and false if m is singular.

func (Mat4) Mat3

func (m Mat4) Mat3() Mat3

Mat3 extracts the upper-left 3x3 submatrix of m.

func (Mat4) Mul

func (m Mat4) Mul(b Mat4) Mat4

Mul returns the matrix product m * b (applying b first, then m).

func (Mat4) MulVec4

func (m Mat4) MulVec4(v Vec4) Vec4

MulVec4 returns the column-vector product m * v.

func (Mat4) Row

func (m Mat4) Row(row int) Vec4

Row returns row row (0..3) as a Vec4.

func (Mat4) TransformDir

func (m Mat4) TransformDir(d Vec3) Vec3

TransformDir transforms a 3D direction vector d as (d.X, d.Y, d.Z, 0), ignoring translation.

func (Mat4) TransformPoint

func (m Mat4) TransformPoint(p Vec3) Vec3

TransformPoint transforms a 3D point p as (p.X, p.Y, p.Z, 1), performing perspective division by w when w is neither 1 nor 0.

func (Mat4) Transpose

func (m Mat4) Transpose() Mat4

Transpose returns the transpose of m.

type Plane

type Plane struct {
	Normal Vec3
	D      float32
}

Plane is an infinite plane satisfying Normal · p + D = 0. When Normal is unit-length, SignedDist returns the signed Euclidean distance from the plane (positive on the side Normal points toward).

func PlaneFromPointNormal

func PlaneFromPointNormal(point, normal Vec3) Plane

PlaneFromPointNormal builds a normalized plane passing through point with the given outward normal.

func (Plane) Normalized

func (p Plane) Normalized() Plane

Normalized returns an equivalent plane with a unit-length Normal. If Normal has zero length, p is returned unchanged.

func (Plane) SignedDist

func (p Plane) SignedDist(point Vec3) float32

SignedDist returns Normal · point + D (signed Euclidean distance when Normal is normalized).

type QuadraticBezier3D

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

QuadraticBezier3D is a 3D quadratic Bézier curve defined by three control points.

func NewQuadraticBezier3D

func NewQuadraticBezier3D(p0, p1, p2 Vec3) *QuadraticBezier3D

NewQuadraticBezier3D constructs a 3D quadratic Bézier curve from p0 through control point p1 to p2, precomputing its Gauss-Legendre arc-length LUT and Rotation-Minimizing Frames.

func (*QuadraticBezier3D) Closed

func (c *QuadraticBezier3D) Closed() bool

Closed reports false because a single quadratic Bézier segment is open.

func (*QuadraticBezier3D) Derivative

func (c *QuadraticBezier3D) Derivative(t float32) Vec3

Derivative evaluates the unnormalized first derivative dP/dt at parameter t in [0, 1].

func (*QuadraticBezier3D) DistanceToT

func (c *QuadraticBezier3D) DistanceToT(dist float32) float32

DistanceToT maps an arc-length distance in [0, Length()] to parameter t in [0, 1].

func (*QuadraticBezier3D) FrameAt

func (c *QuadraticBezier3D) FrameAt(t float32, worldUp Vec3) CurveFrame

FrameAt evaluates the Rotation-Minimizing Frame at parameter t in [0, 1], initialized with worldUp at t=0.

func (*QuadraticBezier3D) FrameAtDistance

func (c *QuadraticBezier3D) FrameAtDistance(dist float32) CurveFrame

FrameAtDistance evaluates the Rotation-Minimizing Frame at arc-length distance dist.

func (*QuadraticBezier3D) Length

func (c *QuadraticBezier3D) Length() float32

Length returns the total arc length of the curve.

func (*QuadraticBezier3D) Point

func (c *QuadraticBezier3D) Point(t float32) Vec3

Point evaluates the curve position at parameter t in [0, 1].

func (*QuadraticBezier3D) PointAtDistance

func (c *QuadraticBezier3D) PointAtDistance(dist float32) Vec3

PointAtDistance evaluates the curve position at arc-length distance dist.

func (*QuadraticBezier3D) Tangent

func (c *QuadraticBezier3D) Tangent(t float32) Vec3

Tangent evaluates the unit tangent vector at parameter t in [0, 1].

func (*QuadraticBezier3D) TangentAtDistance

func (c *QuadraticBezier3D) TangentAtDistance(dist float32) Vec3

TangentAtDistance evaluates the unit tangent vector at arc-length distance dist.

type Quat

type Quat struct {
	X, Y, Z, W float32
}

Quat is a quaternion stored as (X, Y, Z, W), matching glTF 2.0's [x, y, z, w] order. Unit quaternions represent right-handed 3D rotations; q and -q represent the same rotation.

Example

A Quat rotates vectors; composing quaternions composes their rotations.

package main

import (
	"fmt"
	"strconv"

	"github.com/nsgo-dev/game/pkg/math3d"
)

// v prints a vector to two decimals, writing a rounded negative zero as 0.
func v(p math3d.Vec3) string {
	num := func(f float32) string {
		s := strconv.FormatFloat(float64(f), 'f', 2, 32)
		if s == "-0.00" {
			s = "0.00"
		}
		return s
	}
	return "(" + num(p.X) + ", " + num(p.Y) + ", " + num(p.Z) + ")"
}

func main() {
	yaw := math3d.QuatFromAxisAngle(math3d.Vec3Up(), math3d.DegToRad(90))
	fmt.Println(v(yaw.RotateVec3(math3d.Vec3Forward())))
	turnAround := yaw.Mul(yaw)
	fmt.Println(v(turnAround.RotateVec3(math3d.Vec3Forward())))
	half := math3d.QuatIdentity().Slerp(yaw, 0.5)
	_, y, _ := half.ToEuler()
	fmt.Printf("%.0f\n", math3d.RadToDeg(y))
}
Output:
(-1.00, 0.00, 0.00)
(0.00, 0.00, 1.00)
45

func LookRotation

func LookRotation(forward, up Vec3) Quat

LookRotation returns a unit quaternion that orients an object's local forward (-Z) along forward and its local up (+Y) toward up.

For a camera at eye looking at target, Transform{Pos: eye, Rot: LookRotation(target.Sub(eye), up), Scale: Vec3One()}.ToMat4() is the inverse of LookAt(eye, target, up).

func QuatFromAxisAngle

func QuatFromAxisAngle(axis Vec3, rad float32) Quat

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

func QuatFromEuler

func QuatFromEuler(pitch, yaw, roll float32) Quat

QuatFromEuler builds a unit quaternion from intrinsic YXZ Euler angles (yaw around +Y, then pitch around local +X, then roll around local +Z), equivalent to Ry(yaw) * Rx(pitch) * Rz(roll). All angles are in radians.

func QuatFromEulerXYZ

func QuatFromEulerXYZ(x, y, z float32) Quat

QuatFromEulerXYZ builds a unit quaternion from intrinsic XYZ Euler angles, equivalent to Rx(x) * Ry(y) * Rz(z). All angles are in radians.

func QuatFromMat3

func QuatFromMat3(m Mat3) Quat

QuatFromMat3 converts a pure 3x3 right-handed rotation matrix into a unit quaternion using Shepperd's method.

func QuatFromMat4

func QuatFromMat4(m Mat4) Quat

QuatFromMat4 converts the upper-left 3x3 rotation part of m into a unit quaternion. The upper-left 3x3 must be a pure rotation (orthonormal with determinant +1); use Decompose when scale is present.

func QuatIdentity

func QuatIdentity() Quat

QuatIdentity returns the identity rotation quaternion (0, 0, 0, 1).

func (Quat) ApproxEqual

func (q Quat) ApproxEqual(b Quat, eps float32) bool

ApproxEqual reports whether q and b represent approximately the same rotation (accounting for the double-cover equivalence q == -q).

func (Quat) Conj

func (q Quat) Conj() Quat

Conj returns the conjugate of q: (-X, -Y, -Z, W). For unit quaternions, Conj equals Inverse.

func (Quat) Dot

func (q Quat) Dot(b Quat) float32

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

func (Quat) Inverse

func (q Quat) Inverse() Quat

Inverse returns the multiplicative inverse of q, or QuatIdentity if q has zero norm.

func (Quat) Len

func (q Quat) Len() float32

Len returns the norm of q.

func (Quat) LenSq

func (q Quat) LenSq() float32

LenSq returns the squared norm of q.

func (Quat) Mul

func (q Quat) Mul(b Quat) Quat

Mul returns the Hamilton product q * b, composing rotation b followed by q.

func (Quat) Nlerp

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

Nlerp performs shortest-path normalized linear interpolation from q (t=0) to b (t=1).

func (Quat) Norm

func (q Quat) Norm() Quat

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

func (Quat) RotateVec3

func (q Quat) RotateVec3(v Vec3) Vec3

RotateVec3 rotates v by the unit rotation q.

func (Quat) Slerp

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

Slerp performs shortest-path spherical linear interpolation from q (t=0) to b (t=1). If q·b < 0, b is negated so interpolation always takes the shorter arc.

func (Quat) ToEuler

func (q Quat) ToEuler() (pitch, yaw, roll float32)

ToEuler extracts intrinsic YXZ Euler angles (pitch, yaw, roll) in radians such that QuatFromEuler(pitch, yaw, roll) reproduces q (up to sign ±q). Near ±90° pitch it still separates yaw and roll; only an exact gimbal lock folds roll into yaw.

func (Quat) ToEulerXYZ

func (q Quat) ToEulerXYZ() (x, y, z float32)

ToEulerXYZ extracts intrinsic XYZ Euler angles (x, y, z) in radians such that QuatFromEulerXYZ(x, y, z) reproduces q (up to sign ±q).

func (Quat) ToMat3

func (q Quat) ToMat3() Mat3

ToMat3 converts q to a 3x3 column-major rotation matrix.

func (Quat) ToMat4

func (q Quat) ToMat4() Mat4

ToMat4 converts q to a 4x4 column-major rotation matrix.

type Ray

type Ray struct {
	Origin, Dir Vec3
}

Ray is a half-line P(t) = Origin + t * Dir for t >= 0.

Example

Ray tests intersections with boxes, spheres, planes and triangles, as picking and line-of-sight checks do.

package main

import (
	"fmt"
	"strconv"

	"github.com/nsgo-dev/game/pkg/math3d"
)

// v prints a vector to two decimals, writing a rounded negative zero as 0.
func v(p math3d.Vec3) string {
	num := func(f float32) string {
		s := strconv.FormatFloat(float64(f), 'f', 2, 32)
		if s == "-0.00" {
			s = "0.00"
		}
		return s
	}
	return "(" + num(p.X) + ", " + num(p.Y) + ", " + num(p.Z) + ")"
}

func main() {
	r := math3d.Ray{Origin: math3d.Vec3{Z: 10}, Dir: math3d.Vec3Forward()}
	box := math3d.AABB{Min: math3d.Vec3{X: -1, Y: -1, Z: -1}, Max: math3d.Vec3One()}
	tMin, tMax, hit := r.IntersectAABB(box)
	fmt.Println(hit, tMin, tMax, v(r.At(tMin)))
	t, hit := r.IntersectSphere(math3d.Sphere{Center: math3d.Vec3{Z: -5}, Radius: 2})
	fmt.Println(hit, t)
}
Output:
true 9 11 (0.00, 0.00, 1.00)
true 13

func (Ray) At

func (r Ray) At(t float32) Vec3

At returns the point along the ray at parameter t: Origin + t * Dir.

func (Ray) IntersectAABB

func (r Ray) IntersectAABB(b AABB) (tMin, tMax float32, hit bool)

IntersectAABB tests r against b using the slab method. On a hit, tMin is the nearest non-negative entry parameter (0 when r.Origin lies inside b) and tMax is the exit parameter.

func (Ray) IntersectPlane

func (r Ray) IntersectPlane(p Plane) (t float32, hit bool)

IntersectPlane tests r against plane p, returning the parameter t >= 0 of the intersection point, or false if the ray is parallel to or points away from p.

func (Ray) IntersectSphere

func (r Ray) IntersectSphere(s Sphere) (t float32, hit bool)

IntersectSphere tests r against sphere s, returning the smallest non-negative parameter t where r.At(t) touches the surface of s. Works whether or not r.Dir is unit-length.

func (Ray) IntersectTriangle

func (r Ray) IntersectTriangle(v0, v1, v2 Vec3) (t, u, v float32, hit bool)

IntersectTriangle tests r against triangle (v0, v1, v2) using the Möller-Trumbore algorithm (double-sided). On a hit, t >= 0 is the ray parameter and (u, v) are barycentric coordinates such that r.At(t) == v0*(1-u-v) + v1*u + v2*v.

type Sphere

type Sphere struct {
	Center Vec3
	Radius float32
}

Sphere is a 3D bounding sphere defined by Center and Radius.

func (Sphere) Contains

func (s Sphere) Contains(p Vec3) bool

Contains reports whether p lies inside or on the surface of s.

func (Sphere) IntersectsAABB

func (s Sphere) IntersectsAABB(b AABB) bool

IntersectsAABB reports whether s overlaps or touches b.

func (Sphere) IntersectsSphere

func (s Sphere) IntersectsSphere(other Sphere) bool

IntersectsSphere reports whether s overlaps or touches other.

type Transform

type Transform struct {
	Pos   Vec3
	Rot   Quat
	Scale Vec3
}

Transform represents a 3D TRS (translation, rotation, scale) transform. Its zero value has zero scale and a zero quaternion; use TransformIdentity for a default identity transform.

Example

Transform composes a parent's and a child's translation, rotation and scale, and Inverse maps world points back into local space.

package main

import (
	"fmt"
	"strconv"

	"github.com/nsgo-dev/game/pkg/math3d"
)

// v prints a vector to two decimals, writing a rounded negative zero as 0.
func v(p math3d.Vec3) string {
	num := func(f float32) string {
		s := strconv.FormatFloat(float64(f), 'f', 2, 32)
		if s == "-0.00" {
			s = "0.00"
		}
		return s
	}
	return "(" + num(p.X) + ", " + num(p.Y) + ", " + num(p.Z) + ")"
}

func main() {
	parent := math3d.Transform{Pos: math3d.Vec3{X: 10}, Rot: math3d.QuatFromAxisAngle(math3d.Vec3Up(), math3d.DegToRad(90)), Scale: math3d.Vec3{X: 2, Y: 2, Z: 2}}
	child := math3d.TransformIdentity()
	child.Pos = math3d.Vec3{X: 1}
	world := parent.Mul(child)
	fmt.Println(v(world.Pos))
	fmt.Println(v(parent.Inverse().TransformPoint(world.Pos)))
}
Output:
(10.00, 0.00, -2.00)
(1.00, 0.00, 0.00)

func TransformIdentity

func TransformIdentity() Transform

TransformIdentity returns the identity transform (Pos: 0, Rot: identity, Scale: 1).

func (Transform) ApproxEqual

func (t Transform) ApproxEqual(b Transform, eps float32) bool

ApproxEqual reports whether t and b are approximately equal within eps.

func (Transform) Inverse

func (t Transform) Inverse() Transform

Inverse returns the Transform that undoes t under Transform.Mul: t.Mul(t.Inverse()) is the identity whenever every scale component is non-zero.

It is the geometric inverse (t.Inverse().TransformPoint(t.TransformPoint(p)) == p) only when t is rigid, its scale is uniform, or it has no rotation. The inverse of a non-uniform scale combined with a rotation is S⁻¹·R⁻¹, which shears and so is not a TRS that a Transform can hold; use Transform.InverseMat4 for it.

func (Transform) InverseMat4

func (t Transform) InverseMat4() (Mat4, bool)

InverseMat4 returns the exact inverse of t.ToMat4(), S⁻¹·R⁻¹·T⁻¹, built in closed form rather than by general 4x4 inversion, and true. It is right for every transform, including the non-uniform scale with rotation that Transform.Inverse cannot represent. It returns the zero matrix and false when a scale component is zero, a component of t is not finite, or the inverse overflows float32 (a subnormal scale).

Example

InverseMat4 inverts any Transform exactly, including a non-uniform scale under a rotation, whose inverse shears and so is not a Transform.

package main

import (
	"fmt"
	"strconv"

	"github.com/nsgo-dev/game/pkg/math3d"
)

// v prints a vector to two decimals, writing a rounded negative zero as 0.
func v(p math3d.Vec3) string {
	num := func(f float32) string {
		s := strconv.FormatFloat(float64(f), 'f', 2, 32)
		if s == "-0.00" {
			s = "0.00"
		}
		return s
	}
	return "(" + num(p.X) + ", " + num(p.Y) + ", " + num(p.Z) + ")"
}

func main() {
	t := math3d.Transform{
		Pos:   math3d.Vec3{X: 1},
		Rot:   math3d.QuatFromAxisAngle(math3d.Vec3Up(), math3d.DegToRad(90)),
		Scale: math3d.Vec3{X: 2, Y: 1, Z: 1},
	}
	world := t.TransformPoint(math3d.Vec3{X: 1, Y: 1})
	inv, _ := t.InverseMat4()
	fmt.Println(v(world), v(inv.TransformPoint(world)))
}
Output:
(1.00, 1.00, -2.00) (1.00, 1.00, 0.00)

func (Transform) Lerp

func (t Transform) Lerp(b Transform, alpha float32) Transform

Lerp interpolates from t (alpha=0) to b (alpha=1), using linear interpolation for position and scale and shortest-path Slerp for rotation.

func (Transform) Mul

func (t Transform) Mul(child Transform) Transform

Mul composes parent and child transforms (parent * child), transforming child's local space into parent's space.

Because a Transform cannot represent shear, this matches parent.ToMat4().Mul(child.ToMat4()) exactly whenever parent.Scale is uniform (or child has no rotation). For hierarchies with non-uniform parent scale and rotated children, compose as Mat4.

func (Transform) ToMat4

func (t Transform) ToMat4() Mat4

ToMat4 converts t to a column-major 4x4 matrix in T * R * S order.

func (Transform) TransformDir

func (t Transform) TransformDir(d Vec3) Vec3

TransformDir applies t's scale and rotation to direction vector d (ignoring translation).

func (Transform) TransformPoint

func (t Transform) TransformPoint(p Vec3) Vec3

TransformPoint applies t to point p (scale, rotate, then translate).

type Vec2

type Vec2 struct {
	X, Y float32
}

Vec2 is a 2-component float32 vector.

func Vec2One

func Vec2One() Vec2

Vec2One returns (1, 1).

func Vec2UnitX

func Vec2UnitX() Vec2

Vec2UnitX returns the +X unit vector (1, 0).

func Vec2UnitY

func Vec2UnitY() Vec2

Vec2UnitY returns the +Y unit vector (0, 1).

func Vec2Zero

func Vec2Zero() Vec2

Vec2Zero returns the zero 2D vector (0, 0).

func (Vec2) Add

func (v Vec2) Add(b Vec2) Vec2

Add returns v + b.

func (Vec2) ApproxEqual

func (v Vec2) ApproxEqual(b Vec2, eps float32) bool

ApproxEqual reports whether each component of v is within eps of b.

func (Vec2) Clamp

func (v Vec2) Clamp(lo, hi Vec2) Vec2

Clamp restricts each component of v to [lo, hi].

func (Vec2) Dist

func (v Vec2) Dist(b Vec2) float32

Dist returns the Euclidean distance between v and b.

func (Vec2) DistSq

func (v Vec2) DistSq(b Vec2) float32

DistSq returns the squared Euclidean distance between v and b.

func (Vec2) Div

func (v Vec2) Div(b Vec2) Vec2

Div returns the component-wise quotient v / b.

func (Vec2) Dot

func (v Vec2) Dot(b Vec2) float32

Dot returns the dot product v · b.

func (Vec2) Len

func (v Vec2) Len() float32

Len returns the Euclidean length of v.

func (Vec2) LenSq

func (v Vec2) LenSq() float32

LenSq returns the squared Euclidean length of v.

func (Vec2) Lerp

func (v Vec2) Lerp(b Vec2, t float32) Vec2

Lerp linearly interpolates from v (t=0) to b (t=1).

func (Vec2) Max

func (v Vec2) Max(b Vec2) Vec2

Max returns the component-wise maximum of v and b.

func (Vec2) Min

func (v Vec2) Min(b Vec2) Vec2

Min returns the component-wise minimum of v and b.

func (Vec2) Mul

func (v Vec2) Mul(b Vec2) Vec2

Mul returns the component-wise product of v and b.

func (Vec2) Neg

func (v Vec2) Neg() Vec2

Neg returns -v.

func (Vec2) Norm

func (v Vec2) Norm() Vec2

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

func (Vec2) Scale

func (v Vec2) Scale(s float32) Vec2

Scale returns v multiplied by scalar s.

func (Vec2) Sub

func (v Vec2) Sub(b Vec2) Vec2

Sub returns v - b.

func (Vec2) Vec3

func (v Vec2) Vec3(z float32) Vec3

Vec3 promotes v to a Vec3 with the given z component.

type Vec3

type Vec3 struct {
	X, Y, Z float32
}

Vec3 is a 3-component float32 vector in right-handed Y-up space (+X right, +Y up, -Z forward).

Example

Vec3 holds positions and directions in a right-handed, Y-up space where -Z is forward.

package main

import (
	"fmt"
	"strconv"

	"github.com/nsgo-dev/game/pkg/math3d"
)

// v prints a vector to two decimals, writing a rounded negative zero as 0.
func v(p math3d.Vec3) string {
	num := func(f float32) string {
		s := strconv.FormatFloat(float64(f), 'f', 2, 32)
		if s == "-0.00" {
			s = "0.00"
		}
		return s
	}
	return "(" + num(p.X) + ", " + num(p.Y) + ", " + num(p.Z) + ")"
}

func main() {
	a := math3d.Vec3{X: 1, Y: 2, Z: 2}
	fmt.Println(a.Len(), v(a.Norm()))
	fmt.Println(v(math3d.Vec3Right().Cross(math3d.Vec3Up())), v(math3d.Vec3Forward()))
	fmt.Println(v(a.Lerp(math3d.Vec3Zero(), 0.5)))
}
Output:
3 (0.33, 0.67, 0.67)
(0.00, 0.00, 1.00) (0.00, 0.00, -1.00)
(0.50, 1.00, 1.00)

func Vec3Forward

func Vec3Forward() Vec3

Vec3Forward returns the right-handed forward -Z axis (0, 0, -1).

func Vec3One

func Vec3One() Vec3

Vec3One returns (1, 1, 1).

func Vec3Right

func Vec3Right() Vec3

Vec3Right returns the right-handed +X axis (1, 0, 0).

func Vec3UnitX

func Vec3UnitX() Vec3

Vec3UnitX returns the +X unit vector (1, 0, 0).

func Vec3UnitY

func Vec3UnitY() Vec3

Vec3UnitY returns the +Y unit vector (0, 1, 0).

func Vec3UnitZ

func Vec3UnitZ() Vec3

Vec3UnitZ returns the +Z unit vector (0, 0, 1).

func Vec3Up

func Vec3Up() Vec3

Vec3Up returns the right-handed +Y axis (0, 1, 0).

func Vec3Zero

func Vec3Zero() Vec3

Vec3Zero returns the zero 3D vector (0, 0, 0).

func (Vec3) Add

func (v Vec3) Add(b Vec3) Vec3

Add returns v + b.

func (Vec3) ApproxEqual

func (v Vec3) ApproxEqual(b Vec3, eps float32) bool

ApproxEqual reports whether each component of v is within eps of b.

func (Vec3) Clamp

func (v Vec3) Clamp(lo, hi Vec3) Vec3

Clamp restricts each component of v to [lo, hi].

func (Vec3) Cross

func (v Vec3) Cross(b Vec3) Vec3

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

func (Vec3) Dist

func (v Vec3) Dist(b Vec3) float32

Dist returns the Euclidean distance between v and b.

func (Vec3) DistSq

func (v Vec3) DistSq(b Vec3) float32

DistSq returns the squared Euclidean distance between v and b.

func (Vec3) Div

func (v Vec3) Div(b Vec3) Vec3

Div returns the component-wise quotient v / b.

func (Vec3) Dot

func (v Vec3) Dot(b Vec3) float32

Dot returns the dot product v · b.

func (Vec3) IsFinite

func (v Vec3) IsFinite() bool

IsFinite reports whether x is neither NaN nor an infinity.

func (Vec3) Len

func (v Vec3) Len() float32

Len returns the Euclidean length of v.

func (Vec3) LenSq

func (v Vec3) LenSq() float32

LenSq returns the squared Euclidean length of v.

func (Vec3) Lerp

func (v Vec3) Lerp(b Vec3, t float32) Vec3

Lerp linearly interpolates from v (t=0) to b (t=1).

func (Vec3) Max

func (v Vec3) Max(b Vec3) Vec3

Max returns the component-wise maximum of v and b.

func (Vec3) Min

func (v Vec3) Min(b Vec3) Vec3

Min returns the component-wise minimum of v and b.

func (Vec3) Mul

func (v Vec3) Mul(b Vec3) Vec3

Mul returns the component-wise product of v and b.

func (Vec3) Neg

func (v Vec3) Neg() Vec3

Neg returns -v.

func (Vec3) Norm

func (v Vec3) Norm() Vec3

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

func (Vec3) Scale

func (v Vec3) Scale(s float32) Vec3

Scale returns v multiplied by scalar s.

func (Vec3) Sub

func (v Vec3) Sub(b Vec3) Vec3

Sub returns v - b.

func (Vec3) Vec4

func (v Vec3) Vec4(w float32) Vec4

Vec4 promotes v to a Vec4 with the given w component (use 1 for points, 0 for directions).

func (Vec3) XY

func (v Vec3) XY() Vec2

XY returns the X and Y components as a Vec2.

type Vec4

type Vec4 struct {
	X, Y, Z, W float32
}

Vec4 is a 4-component float32 vector, commonly used for homogeneous coordinates and colors.

func Vec4One

func Vec4One() Vec4

Vec4One returns (1, 1, 1, 1).

func Vec4Zero

func Vec4Zero() Vec4

Vec4Zero returns the zero 4D vector (0, 0, 0, 0).

func (Vec4) Add

func (v Vec4) Add(b Vec4) Vec4

Add returns v + b.

func (Vec4) ApproxEqual

func (v Vec4) ApproxEqual(b Vec4, eps float32) bool

ApproxEqual reports whether each component of v is within eps of b.

func (Vec4) Clamp

func (v Vec4) Clamp(lo, hi Vec4) Vec4

Clamp restricts each component of v to [lo, hi].

func (Vec4) Dist

func (v Vec4) Dist(b Vec4) float32

Dist returns the Euclidean distance between v and b.

func (Vec4) DistSq

func (v Vec4) DistSq(b Vec4) float32

DistSq returns the squared Euclidean distance between v and b.

func (Vec4) Div

func (v Vec4) Div(b Vec4) Vec4

Div returns the component-wise quotient v / b.

func (Vec4) Dot

func (v Vec4) Dot(b Vec4) float32

Dot returns the dot product v · b.

func (Vec4) Len

func (v Vec4) Len() float32

Len returns the Euclidean length of v.

func (Vec4) LenSq

func (v Vec4) LenSq() float32

LenSq returns the squared Euclidean length of v.

func (Vec4) Lerp

func (v Vec4) Lerp(b Vec4, t float32) Vec4

Lerp linearly interpolates from v (t=0) to b (t=1).

func (Vec4) Max

func (v Vec4) Max(b Vec4) Vec4

Max returns the component-wise maximum of v and b.

func (Vec4) Min

func (v Vec4) Min(b Vec4) Vec4

Min returns the component-wise minimum of v and b.

func (Vec4) Mul

func (v Vec4) Mul(b Vec4) Vec4

Mul returns the component-wise product of v and b.

func (Vec4) Neg

func (v Vec4) Neg() Vec4

Neg returns -v.

func (Vec4) Norm

func (v Vec4) Norm() Vec4

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

func (Vec4) Scale

func (v Vec4) Scale(s float32) Vec4

Scale returns v multiplied by scalar s.

func (Vec4) Sub

func (v Vec4) Sub(b Vec4) Vec4

Sub returns v - b.

func (Vec4) XYZ

func (v Vec4) XYZ() Vec3

XYZ returns the X, Y, and Z components as a Vec3.

Jump to

Keyboard shortcuts

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