dymokomi/luce-geocore
Source of release 0.7.1
0.7.1 / src / math / vector.lucb
## Right-handed coordinates, +Y up and camera forward along local -Z.
from luce_std import math
import errors
pub struct Vector3:
pub var x: f64
pub var y: f64
pub var z: f64
pub func init(x: f64 = 0.0, y: f64 = 0.0, z: f64 = 0.0):
self.x = x
self.y = y
self.z = z
pub func add(other: Vector3) -> Vector3:
return Vector3(self.x + other.x, self.y + other.y, self.z + other.z)
pub func subtract(other: Vector3) -> Vector3:
return Vector3(self.x - other.x, self.y - other.y, self.z - other.z)
pub func multiply_scalar(scale: f64) -> Vector3:
return Vector3(self.x * scale, self.y * scale, self.z * scale)
pub func dot(other: Vector3) -> f64:
return self.x * other.x + self.y * other.y + self.z * other.z
pub func cross(other: Vector3) -> Vector3:
return Vector3(self.y * other.z - self.z * other.y,
self.z * other.x - self.x * other.z,
self.x * other.y - self.y * other.x)
pub func length() -> f64:
return math.hypot(math.hypot(self.x, self.y), self.z)
pub func normalized() -> Vector3!:
let length = self.length()
if not (length > 0.000000000001 and math.is_finite(length)):
error(errors.invalid, "a direction must be finite and nonzero")
return self.multiply_scalar(1.0 / length)
pub func is_finite() -> bool:
return math.is_finite(self.x) and math.is_finite(self.y) and math.is_finite(self.z)
## XYZ intrinsic Euler rotation; column vectors encounter Z, then Y, then X.
pub func rotated(angles: Vector3) -> Vector3:
let sx = math.sin(angles.x)
let cx = math.cos(angles.x)
let sy = math.sin(angles.y)
let cy = math.cos(angles.y)
let sz = math.sin(angles.z)
let cz = math.cos(angles.z)
let zx = cz * self.x - sz * self.y
let zy = sz * self.x + cz * self.y
let yx = cy * zx + sy * self.z
let yz = -sy * zx + cy * self.z
return Vector3(yx, cx * zy - sx * yz, sx * zy + cx * yz)