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 ¶
- Constants
- func ApproxEqual(a, b, eps float32) bool
- func Clamp(v, lo, hi float32) float32
- func DegToRad(deg float32) float32
- func Lerp(a, b, t float32) float32
- func RadToDeg(rad float32) float32
- type AABB
- func (b AABB) Center() Vec3
- func (b AABB) Contains(p Vec3) bool
- func (b AABB) Empty() bool
- func (b AABB) ExpandPoint(p Vec3) AABB
- func (b AABB) HalfExtents() Vec3
- func (b AABB) Intersects(other AABB) bool
- func (a AABB) IsFinite() bool
- func (b AABB) Size() Vec3
- func (b AABB) Transform(m Mat4) AABB
- func (b AABB) Union(other AABB) AABB
- type CatmullRom3D
- func (c *CatmullRom3D) Alpha() float32
- func (c *CatmullRom3D) Closed() bool
- func (c *CatmullRom3D) Derivative(t float32) Vec3
- func (c *CatmullRom3D) DistanceToT(dist float32) float32
- func (c *CatmullRom3D) FrameAt(t float32, worldUp Vec3) CurveFrame
- func (c *CatmullRom3D) FrameAtDistance(dist float32) CurveFrame
- func (c *CatmullRom3D) Length() float32
- func (c *CatmullRom3D) Point(t float32) Vec3
- func (c *CatmullRom3D) PointAtDistance(dist float32) Vec3
- func (c *CatmullRom3D) SegmentCount() int
- func (c *CatmullRom3D) Tangent(t float32) Vec3
- func (c *CatmullRom3D) TangentAtDistance(dist float32) Vec3
- type CubicBezier3D
- func (c *CubicBezier3D) Closed() bool
- func (c *CubicBezier3D) Derivative(t float32) Vec3
- func (c *CubicBezier3D) DistanceToT(dist float32) float32
- func (c *CubicBezier3D) FrameAt(t float32, worldUp Vec3) CurveFrame
- func (c *CubicBezier3D) FrameAtDistance(dist float32) CurveFrame
- func (c *CubicBezier3D) Length() float32
- func (c *CubicBezier3D) Point(t float32) Vec3
- func (c *CubicBezier3D) PointAtDistance(dist float32) Vec3
- func (c *CubicBezier3D) Tangent(t float32) Vec3
- func (c *CubicBezier3D) TangentAtDistance(dist float32) Vec3
- type CubicHermite3D
- func (c *CubicHermite3D) Closed() bool
- func (c *CubicHermite3D) Derivative(t float32) Vec3
- func (c *CubicHermite3D) DistanceToT(dist float32) float32
- func (c *CubicHermite3D) FrameAt(t float32, worldUp Vec3) CurveFrame
- func (c *CubicHermite3D) FrameAtDistance(dist float32) CurveFrame
- func (c *CubicHermite3D) Length() float32
- func (c *CubicHermite3D) Point(t float32) Vec3
- func (c *CubicHermite3D) PointAtDistance(dist float32) Vec3
- func (c *CubicHermite3D) Tangent(t float32) Vec3
- func (c *CubicHermite3D) TangentAtDistance(dist float32) Vec3
- type Curve3D
- type CurveFrame
- type Frustum
- type HermiteSpline3D
- func (c *HermiteSpline3D) Closed() bool
- func (c *HermiteSpline3D) Derivative(t float32) Vec3
- func (c *HermiteSpline3D) DistanceToT(dist float32) float32
- func (c *HermiteSpline3D) FrameAt(t float32, worldUp Vec3) CurveFrame
- func (c *HermiteSpline3D) FrameAtDistance(dist float32) CurveFrame
- func (c *HermiteSpline3D) Length() float32
- func (c *HermiteSpline3D) Point(t float32) Vec3
- func (c *HermiteSpline3D) PointAtDistance(dist float32) Vec3
- func (c *HermiteSpline3D) SegmentCount() int
- func (c *HermiteSpline3D) Tangent(t float32) Vec3
- func (c *HermiteSpline3D) TangentAtDistance(dist float32) Vec3
- type Mat3
- func (m Mat3) ApproxEqual(b Mat3, eps float32) bool
- func (m Mat3) At(row, col int) float32
- func (m Mat3) Col(col int) Vec3
- func (m Mat3) Det() float32
- func (m Mat3) Inverse() (Mat3, bool)
- func (m Mat3) Mul(b Mat3) Mat3
- func (m Mat3) MulVec3(v Vec3) Vec3
- func (m Mat3) Row(row int) Vec3
- func (m Mat3) Transpose() Mat3
- type Mat4
- func LookAt(eye, target, up Vec3) Mat4
- func Mat4FromCols(c0, c1, c2, c3 Vec4) Mat4
- func Mat4Identity() Mat4
- func Ortho(left, right, bottom, top, near, far float32) Mat4
- func OrthoNO(left, right, bottom, top, near, far float32) Mat4
- func OrthoZO(left, right, bottom, top, near, far float32) Mat4
- func Perspective(fovY, aspect, near, far float32) Mat4
- func PerspectiveNO(fovY, aspect, near, far float32) Mat4
- func PerspectiveZO(fovY, aspect, near, far float32) Mat4
- func RotateAxis(axis Vec3, rad float32) Mat4
- func RotateX(rad float32) Mat4
- func RotateY(rad float32) Mat4
- func RotateZ(rad float32) Mat4
- func Scale(v Vec3) Mat4
- func TRS(pos Vec3, rot Quat, scale Vec3) Mat4
- func Translate(v Vec3) Mat4
- func (m Mat4) ApproxEqual(b Mat4, eps float32) bool
- func (m Mat4) At(row, col int) float32
- func (m Mat4) Col(col int) Vec4
- func (m Mat4) Decompose() (pos Vec3, rot Quat, scale Vec3, ok bool)
- func (m Mat4) Det() float32
- func (m Mat4) Inverse() (Mat4, bool)
- func (m Mat4) Mat3() Mat3
- func (m Mat4) Mul(b Mat4) Mat4
- func (m Mat4) MulVec4(v Vec4) Vec4
- func (m Mat4) Row(row int) Vec4
- func (m Mat4) TransformDir(d Vec3) Vec3
- func (m Mat4) TransformPoint(p Vec3) Vec3
- func (m Mat4) Transpose() Mat4
- type Plane
- type QuadraticBezier3D
- func (c *QuadraticBezier3D) Closed() bool
- func (c *QuadraticBezier3D) Derivative(t float32) Vec3
- func (c *QuadraticBezier3D) DistanceToT(dist float32) float32
- func (c *QuadraticBezier3D) FrameAt(t float32, worldUp Vec3) CurveFrame
- func (c *QuadraticBezier3D) FrameAtDistance(dist float32) CurveFrame
- func (c *QuadraticBezier3D) Length() float32
- func (c *QuadraticBezier3D) Point(t float32) Vec3
- func (c *QuadraticBezier3D) PointAtDistance(dist float32) Vec3
- func (c *QuadraticBezier3D) Tangent(t float32) Vec3
- func (c *QuadraticBezier3D) TangentAtDistance(dist float32) Vec3
- type Quat
- func (q Quat) ApproxEqual(b Quat, eps float32) bool
- func (q Quat) Conj() Quat
- func (q Quat) Dot(b Quat) float32
- func (q Quat) Inverse() Quat
- func (q Quat) Len() float32
- func (q Quat) LenSq() float32
- func (q Quat) Mul(b Quat) Quat
- func (q Quat) Nlerp(b Quat, t float32) Quat
- func (q Quat) Norm() Quat
- func (q Quat) RotateVec3(v Vec3) Vec3
- func (q Quat) Slerp(b Quat, t float32) Quat
- func (q Quat) ToEuler() (pitch, yaw, roll float32)
- func (q Quat) ToEulerXYZ() (x, y, z float32)
- func (q Quat) ToMat3() Mat3
- func (q Quat) ToMat4() Mat4
- type Ray
- type Sphere
- type Transform
- func (t Transform) ApproxEqual(b Transform, eps float32) bool
- func (t Transform) Inverse() Transform
- func (t Transform) InverseMat4() (Mat4, bool)
- func (t Transform) Lerp(b Transform, alpha float32) Transform
- func (t Transform) Mul(child Transform) Transform
- func (t Transform) ToMat4() Mat4
- func (t Transform) TransformDir(d Vec3) Vec3
- func (t Transform) TransformPoint(p Vec3) Vec3
- type Vec2
- func (v Vec2) Add(b Vec2) Vec2
- func (v Vec2) ApproxEqual(b Vec2, eps float32) bool
- func (v Vec2) Clamp(lo, hi Vec2) Vec2
- func (v Vec2) Dist(b Vec2) float32
- func (v Vec2) DistSq(b Vec2) float32
- func (v Vec2) Div(b Vec2) Vec2
- func (v Vec2) Dot(b Vec2) float32
- func (v Vec2) Len() float32
- func (v Vec2) LenSq() float32
- func (v Vec2) Lerp(b Vec2, t float32) Vec2
- func (v Vec2) Max(b Vec2) Vec2
- func (v Vec2) Min(b Vec2) Vec2
- func (v Vec2) Mul(b Vec2) Vec2
- func (v Vec2) Neg() Vec2
- func (v Vec2) Norm() Vec2
- func (v Vec2) Scale(s float32) Vec2
- func (v Vec2) Sub(b Vec2) Vec2
- func (v Vec2) Vec3(z float32) Vec3
- type Vec3
- func (v Vec3) Add(b Vec3) Vec3
- func (v Vec3) ApproxEqual(b Vec3, eps float32) bool
- func (v Vec3) Clamp(lo, hi Vec3) Vec3
- func (v Vec3) Cross(b Vec3) Vec3
- func (v Vec3) Dist(b Vec3) float32
- func (v Vec3) DistSq(b Vec3) float32
- func (v Vec3) Div(b Vec3) Vec3
- func (v Vec3) Dot(b Vec3) float32
- func (v Vec3) IsFinite() bool
- func (v Vec3) Len() float32
- func (v Vec3) LenSq() float32
- func (v Vec3) Lerp(b Vec3, t float32) Vec3
- func (v Vec3) Max(b Vec3) Vec3
- func (v Vec3) Min(b Vec3) Vec3
- func (v Vec3) Mul(b Vec3) Vec3
- func (v Vec3) Neg() Vec3
- func (v Vec3) Norm() Vec3
- func (v Vec3) Scale(s float32) Vec3
- func (v Vec3) Sub(b Vec3) Vec3
- func (v Vec3) Vec4(w float32) Vec4
- func (v Vec3) XY() Vec2
- type Vec4
- func (v Vec4) Add(b Vec4) Vec4
- func (v Vec4) ApproxEqual(b Vec4, eps float32) bool
- func (v Vec4) Clamp(lo, hi Vec4) Vec4
- func (v Vec4) Dist(b Vec4) float32
- func (v Vec4) DistSq(b Vec4) float32
- func (v Vec4) Div(b Vec4) Vec4
- func (v Vec4) Dot(b Vec4) float32
- func (v Vec4) Len() float32
- func (v Vec4) LenSq() float32
- func (v Vec4) Lerp(b Vec4, t float32) Vec4
- func (v Vec4) Max(b Vec4) Vec4
- func (v Vec4) Min(b Vec4) Vec4
- func (v Vec4) Mul(b Vec4) Vec4
- func (v Vec4) Neg() Vec4
- func (v Vec4) Norm() Vec4
- func (v Vec4) Scale(s float32) Vec4
- func (v Vec4) Sub(b Vec4) Vec4
- func (v Vec4) XYZ() Vec3
Examples ¶
Constants ¶
const ( FrustumLeft = iota FrustumRight FrustumBottom FrustumTop FrustumNear FrustumFar )
Frustum plane indices.
Variables ¶
This section is empty.
Functions ¶
func ApproxEqual ¶
ApproxEqual reports whether |a - b| <= eps.
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) Empty ¶
Empty reports whether b represents an empty volume (any Min component exceeds Max).
func (AABB) ExpandPoint ¶
ExpandPoint returns the smallest AABB containing both b and point p.
func (AABB) HalfExtents ¶
HalfExtents returns half the size of b along each axis, or Vec3Zero if b is empty.
func (AABB) Intersects ¶
Intersects reports whether b overlaps or touches other.
func (AABB) IsFinite ¶
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 ¶
Size returns the full width, height, and depth of b (Max - Min), or Vec3Zero if b is empty.
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 ¶
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 ¶
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 ¶
FrustumFromMat4NO extracts frustum planes from a view-projection matrix using negative-one-to-one [-1, 1] NDC depth (PerspectiveNO / OrthoNO).
func FrustumFromMat4ZO ¶
FrustumFromMat4ZO extracts frustum planes from a view-projection matrix using zero-to-one [0, 1] NDC depth.
func (Frustum) ContainsPoint ¶
ContainsPoint reports whether p lies inside or on the boundary of f.
func (Frustum) IntersectsAABB ¶
IntersectsAABB reports whether box b lies inside or intersects f using the positive-vertex (p-vertex) test against each frustum plane.
func (Frustum) IntersectsSphere ¶
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 ¶
Mat3FromCols builds a Mat3 from its three column vectors.
func Mat3FromMat4 ¶
Mat3FromMat4 extracts the upper-left 3x3 submatrix of m.
func NormalMatrix ¶
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 ¶
ApproxEqual reports whether every element of m is within eps of b.
func (Mat3) Inverse ¶
Inverse returns the inverse of m and true, or the zero matrix and false if m is singular.
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 ¶
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 ¶
Mat4FromCols builds a Mat4 from its four column vectors.
func Ortho ¶
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 ¶
OrthoNO returns a right-handed orthographic projection matrix for negative-one-to-one NDC depth [-1, 1] (OpenGL, WebGL).
func OrthoZO ¶
OrthoZO returns a right-handed orthographic projection matrix for zero-to-one NDC depth [0, 1] (WebGPU, Metal, Vulkan, D3D).
func Perspective ¶
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 ¶
PerspectiveNO returns a right-handed perspective projection matrix for negative-one-to-one NDC depth [-1, 1] (OpenGL, WebGL).
func PerspectiveZO ¶
PerspectiveZO returns a right-handed perspective projection matrix for zero-to-one NDC depth [0, 1] (WebGPU, Metal, Vulkan, D3D).
func RotateAxis ¶
RotateAxis returns a right-handed rotation matrix around axis by rad radians. If axis has zero length, Mat4Identity is returned.
func TRS ¶
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 (Mat4) ApproxEqual ¶
ApproxEqual reports whether every element of m is within eps of b.
func (Mat4) Decompose ¶
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) Inverse ¶
Inverse returns the inverse of m and true, or the zero matrix and false if m is singular.
func (Mat4) TransformDir ¶
TransformDir transforms a 3D direction vector d as (d.X, d.Y, d.Z, 0), ignoring translation.
func (Mat4) TransformPoint ¶
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.
type Plane ¶
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 ¶
PlaneFromPointNormal builds a normalized plane passing through point with the given outward normal.
func (Plane) Normalized ¶
Normalized returns an equivalent plane with a unit-length Normal. If Normal has zero length, p is returned unchanged.
func (Plane) SignedDist ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
QuatFromMat3 converts a pure 3x3 right-handed rotation matrix into a unit quaternion using Shepperd's method.
func QuatFromMat4 ¶
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 ¶
ApproxEqual reports whether q and b represent approximately the same rotation (accounting for the double-cover equivalence q == -q).
func (Quat) Conj ¶
Conj returns the conjugate of q: (-X, -Y, -Z, W). For unit quaternions, Conj equals Inverse.
func (Quat) Inverse ¶
Inverse returns the multiplicative inverse of q, or QuatIdentity if q has zero norm.
func (Quat) Nlerp ¶
Nlerp performs shortest-path normalized linear interpolation from q (t=0) to b (t=1).
func (Quat) RotateVec3 ¶
RotateVec3 rotates v by the unit rotation q.
func (Quat) Slerp ¶
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 ¶
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 ¶
ToEulerXYZ extracts intrinsic XYZ Euler angles (x, y, z) in radians such that QuatFromEulerXYZ(x, y, z) reproduces q (up to sign ±q).
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) IntersectAABB ¶
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 ¶
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 ¶
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 ¶
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 ¶
Sphere is a 3D bounding sphere defined by Center and Radius.
func (Sphere) IntersectsAABB ¶
IntersectsAABB reports whether s overlaps or touches b.
func (Sphere) IntersectsSphere ¶
IntersectsSphere reports whether s overlaps or touches other.
type Transform ¶
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 ¶
ApproxEqual reports whether t and b are approximately equal within eps.
func (Transform) Inverse ¶
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 ¶
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 ¶
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 ¶
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) TransformDir ¶
TransformDir applies t's scale and rotation to direction vector d (ignoring translation).
func (Transform) TransformPoint ¶
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 (Vec2) ApproxEqual ¶
ApproxEqual reports whether each component of v is within eps of b.
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 (Vec3) ApproxEqual ¶
ApproxEqual reports whether each component of v is within eps of b.
func (Vec3) Norm ¶
Norm returns the unit vector in the direction of v, or the zero vector if v has zero length.
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 (Vec4) ApproxEqual ¶
ApproxEqual reports whether each component of v is within eps of b.