1
0
Fork 0
go-raytracer/math/vec2.go
2025-06-08 15:51:07 +02:00

82 lines
1.2 KiB
Go

package math
import stdmath "math"
type UnsignedInteger interface {
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}
type SignedInteger interface {
~int | ~int8 | ~int16 | ~int32 | ~int64
}
type Integer interface {
UnsignedInteger | SignedInteger
}
type Float interface {
~float32 | ~float64
}
type Number interface {
Integer | Float
}
type Vec2[T Number] struct {
X, Y T
}
type (
Vec2i = Vec2[int]
Vec2i32 = Vec2[int32]
Vec2f = Vec2[float64]
Vec2u8 = Vec2[uint8]
)
func (v Vec2[T]) Add(x, y T) Vec2[T] {
return Vec2[T]{
X: v.X + x,
Y: v.Y + y,
}
}
func (v Vec2[T]) AddS(s T) Vec2[T] {
return v.Add(s, s)
}
func (v Vec2[T]) AddVec(other Vec2[T]) Vec2[T] {
return Vec2[T]{
X: v.X + other.X,
Y: v.Y + other.Y,
}
}
func (v Vec2[T]) Mul(x, y T) Vec2[T] {
return Vec2[T]{
X: v.X * x,
Y: v.Y * y,
}
}
func (v Vec2[T]) MulVec(other Vec2[T]) Vec2[T] {
return v.Mul(other.X, other.Y)
}
func (v Vec2[T]) Scale(f T) Vec2[T] {
return v.Mul(f, f)
}
func (v Vec2[T]) Length() float64 {
return stdmath.Sqrt(float64(v.X*v.X) + float64(v.Y*v.Y))
}
func (v Vec2[T]) Normalize() Vec2[T] {
l := v.Length()
if l <= 0.0 {
return Vec2[T]{}
}
return Vec2[T]{
X: T(float64(v.X) / l),
Y: T(float64(v.Y) / l),
}
}