#! Contains `vec2`, a vector of two: a place or a direction in a plane, as of #! a window's pixels, a glyph's outline, or a texture. It's 8 bytes, half the #! lanes of an `f32x4`, so it's worked a number at a time. import std::math; import std::serial; module linear; #! A vector of two: a place or a direction in a plane. @serial pub struct vec2 { @serial pub var x: f32; @serial pub var y: f32; } pub val vec2::zero := vec2{ 0, 0 }; pub val vec2::one := vec2{ 1, 1 }; pub def vec2::add(&this, other: &vec2): vec2 { return vec2{ this.x + other.x, this.y + other.y }; } pub def vec2::sub(&this, other: &vec2): vec2 { return vec2{ this.x - other.x, this.y - other.y }; } pub def vec2::mul(&this, by: &f32): vec2 { return vec2{ this.x * by, this.y * by }; } pub def vec2::mul(&this, other: &vec2): vec2 { return vec2{ this.x * other.x, this.y * other.y }; } pub def vec2::div(&this, by: &f32): vec2 { return vec2{ this.x / by, this.y / by }; } pub def vec2::div(&this, other: &vec2): vec2 { return vec2{ this.x / other.x, this.y / other.y }; } pub def vec2::negate(&this): vec2 { return vec2{ -this.x, -this.y }; } pub def vec2::equals(&this, other: &vec2): bool { return this.x == other.x && this.y == other.y; } pub def vec2::dot(&this, other: vec2): f32 { return this.x * other.x + this.y * other.y; } #! The z of the cross product of the two as vectors of three in the plane z is #! 0: positive where `other` is counterclockwise of this. pub def vec2::cross(&this, other: vec2): f32 { return this.x * other.y - this.y * other.x; } #! The vector turned a quarter counterclockwise. pub def vec2::perpendicular(&this): vec2 { return vec2{ -this.y, this.x }; } pub val vec2::length: f32 { get => math::sqrt(this.x * this.x + this.y * this.y); } #! The length squared, which needs no square root, to compare lengths by. pub val vec2::length_squared: f32 { get => this.x * this.x + this.y * this.y; } pub def vec2::distance(&this, other: vec2): f32 { return (other - this).length; } #! The vector at a length of 1, or none where it has no length. pub def vec2::normalized(&this): vec2 { val l := math::sqrt(this.x * this.x + this.y * this.y); return l > 0 ? vec2{ this.x / l, this.y / l } : vec2{}; } #! The vector a fraction of the way to another. pub def vec2::lerp(&this, to: vec2, t: f32): vec2 { return vec2{ this.x + (to.x - this.x) * t, this.y + (to.y - this.y) * t }; } #! The lesser of each pair of numbers, as `math::min` gives it. pub def vec2::min(&this, other: vec2): vec2 { return vec2{ math::min(this.x, other.x), math::min(this.y, other.y) }; } #! The greater of each pair of numbers, as `math::max` gives it. pub def vec2::max(&this, other: vec2): vec2 { return vec2{ math::max(this.x, other.x), math::max(this.y, other.y) }; } #! Each number's distance from zero. pub def vec2::abs(&this): vec2 { return vec2{ math::abs(this.x), math::abs(this.y) }; }