#if REAL_T_IS_DOUBLE using real_t = System.Double; #else using real_t = System.Single; #endif using System; using System.Runtime.InteropServices; namespace Godot { /// /// 3-element structure that can be used to represent positions in 3D space or any other pair of numeric values. /// [Serializable] [StructLayout(LayoutKind.Sequential)] public struct Vector3 : IEquatable { /// /// Enumerated index values for the axes. /// Returned by and . /// public enum Axis { X = 0, Y, Z } /// /// The vector's X component. Also accessible by using the index position `[0]`. /// public real_t x; /// /// The vector's Y component. Also accessible by using the index position `[1]`. /// public real_t y; /// /// The vector's Z component. Also accessible by using the index position `[2]`. /// public real_t z; /// /// Access vector components using their index. /// /// `[0]` is equivalent to `.x`, `[1]` is equivalent to `.y`, `[2]` is equivalent to `.z`. public real_t this[int index] { get { switch (index) { case 0: return x; case 1: return y; case 2: return z; default: throw new IndexOutOfRangeException(); } } set { switch (index) { case 0: x = value; return; case 1: y = value; return; case 2: z = value; return; default: throw new IndexOutOfRangeException(); } } } internal void Normalize() { real_t lengthsq = LengthSquared(); if (lengthsq == 0) { x = y = z = 0f; } else { real_t length = Mathf.Sqrt(lengthsq); x /= length; y /= length; z /= length; } } /// /// Returns a new vector with all components in absolute values (i.e. positive). /// /// A vector with called on each component. public Vector3 Abs() { return new Vector3(Mathf.Abs(x), Mathf.Abs(y), Mathf.Abs(z)); } /// /// Returns the unsigned minimum angle to the given vector, in radians. /// /// The other vector to compare this vector to. /// The unsigned angle between the two vectors, in radians. public real_t AngleTo(Vector3 to) { return Mathf.Atan2(Cross(to).Length(), Dot(to)); } /// /// Returns this vector "bounced off" from a plane defined by the given normal. /// /// The normal vector defining the plane to bounce off. Must be normalized. /// The bounced vector. public Vector3 Bounce(Vector3 normal) { return -Reflect(normal); } /// /// Returns a new vector with all components rounded up (towards positive infinity). /// /// A vector with called on each component. public Vector3 Ceil() { return new Vector3(Mathf.Ceil(x), Mathf.Ceil(y), Mathf.Ceil(z)); } /// /// Returns a new vector with all components clamped between the /// components of `min` and `max` using /// . /// /// The vector with minimum allowed values. /// The vector with maximum allowed values. /// The vector with all components clamped. public Vector3 Clamp(Vector3 min, Vector3 max) { return new Vector3 ( Mathf.Clamp(x, min.x, max.x), Mathf.Clamp(y, min.y, max.y), Mathf.Clamp(z, min.z, max.z) ); } /// /// Returns the cross product of this vector and `b`. /// /// The other vector. /// The cross product vector. public Vector3 Cross(Vector3 b) { return new Vector3 ( y * b.z - z * b.y, z * b.x - x * b.z, x * b.y - y * b.x ); } /// /// Performs a cubic interpolation between vectors `preA`, this vector, /// `b`, and `postB`, by the given amount `t`. /// /// The destination vector. /// A vector before this vector. /// A vector after `b`. /// A value on the range of 0.0 to 1.0, representing the amount of interpolation. /// The interpolated vector. public Vector3 CubicInterpolate(Vector3 b, Vector3 preA, Vector3 postB, real_t weight) { Vector3 p0 = preA; Vector3 p1 = this; Vector3 p2 = b; Vector3 p3 = postB; real_t t = weight; real_t t2 = t * t; real_t t3 = t2 * t; return 0.5f * ( p1 * 2.0f + (-p0 + p2) * t + (2.0f * p0 - 5.0f * p1 + 4f * p2 - p3) * t2 + (-p0 + 3.0f * p1 - 3.0f * p2 + p3) * t3 ); } /// /// Returns the normalized vector pointing from this vector to `b`. /// /// The other vector to point towards. /// The direction from this vector to `b`. public Vector3 DirectionTo(Vector3 b) { return new Vector3(b.x - x, b.y - y, b.z - z).Normalized(); } /// /// Returns the squared distance between this vector and `b`. /// This method runs faster than , so prefer it if /// you need to compare vectors or need the squared distance for some formula. /// /// The other vector to use. /// The squared distance between the two vectors. public real_t DistanceSquaredTo(Vector3 b) { return (b - this).LengthSquared(); } /// /// Returns the distance between this vector and `b`. /// /// The other vector to use. /// The distance between the two vectors. public real_t DistanceTo(Vector3 b) { return (b - this).Length(); } /// /// Returns the dot product of this vector and `b`. /// /// The other vector to use. /// The dot product of the two vectors. public real_t Dot(Vector3 b) { return x * b.x + y * b.y + z * b.z; } /// /// Returns a new vector with all components rounded down (towards negative infinity). /// /// A vector with called on each component. public Vector3 Floor() { return new Vector3(Mathf.Floor(x), Mathf.Floor(y), Mathf.Floor(z)); } /// /// Returns the inverse of this vector. This is the same as `new Vector3(1 / v.x, 1 / v.y, 1 / v.z)`. /// /// The inverse of this vector. public Vector3 Inverse() { return new Vector3(1 / x, 1 / y, 1 / z); } /// /// Returns true if the vector is normalized, and false otherwise. /// /// A bool indicating whether or not the vector is normalized. public bool IsNormalized() { return Mathf.Abs(LengthSquared() - 1.0f) < Mathf.Epsilon; } /// /// Returns the length (magnitude) of this vector. /// /// The length of this vector. public real_t Length() { real_t x2 = x * x; real_t y2 = y * y; real_t z2 = z * z; return Mathf.Sqrt(x2 + y2 + z2); } /// /// Returns the squared length (squared magnitude) of this vector. /// This method runs faster than , so prefer it if /// you need to compare vectors or need the squared length for some formula. /// /// The squared length of this vector. public real_t LengthSquared() { real_t x2 = x * x; real_t y2 = y * y; real_t z2 = z * z; return x2 + y2 + z2; } /// /// Returns the result of the linear interpolation between /// this vector and `to` by amount `weight`. /// /// The destination vector for interpolation. /// A value on the range of 0.0 to 1.0, representing the amount of interpolation. /// The resulting vector of the interpolation. public Vector3 Lerp(Vector3 to, real_t weight) { return new Vector3 ( Mathf.Lerp(x, to.x, weight), Mathf.Lerp(y, to.y, weight), Mathf.Lerp(z, to.z, weight) ); } /// /// Returns the result of the linear interpolation between /// this vector and `to` by the vector amount `weight`. /// /// The destination vector for interpolation. /// A vector with components on the range of 0.0 to 1.0, representing the amount of interpolation. /// The resulting vector of the interpolation. public Vector3 Lerp(Vector3 to, Vector3 weight) { return new Vector3 ( Mathf.Lerp(x, to.x, weight.x), Mathf.Lerp(y, to.y, weight.y), Mathf.Lerp(z, to.z, weight.z) ); } /// /// Returns the vector with a maximum length by limiting its length to `length`. /// /// The length to limit to. /// The vector with its length limited. public Vector3 LimitLength(real_t length = 1.0f) { Vector3 v = this; real_t l = Length(); if (l > 0 && length < l) { v /= l; v *= length; } return v; } /// /// Returns the axis of the vector's largest value. See . /// If all components are equal, this method returns . /// /// The index of the largest axis. public Axis MaxAxis() { return x < y ? (y < z ? Axis.Z : Axis.Y) : (x < z ? Axis.Z : Axis.X); } /// /// Returns the axis of the vector's smallest value. See . /// If all components are equal, this method returns . /// /// The index of the smallest axis. public Axis MinAxis() { return x < y ? (x < z ? Axis.X : Axis.Z) : (y < z ? Axis.Y : Axis.Z); } /// /// Moves this vector toward `to` by the fixed `delta` amount. /// /// The vector to move towards. /// The amount to move towards by. /// The resulting vector. public Vector3 MoveToward(Vector3 to, real_t delta) { var v = this; var vd = to - v; var len = vd.Length(); return len <= delta || len < Mathf.Epsilon ? to : v + vd / len * delta; } /// /// Returns the vector scaled to unit length. Equivalent to `v / v.Length()`. /// /// A normalized version of the vector. public Vector3 Normalized() { var v = this; v.Normalize(); return v; } /// /// Returns the outer product with `b`. /// /// The other vector. /// A representing the outer product matrix. public Basis Outer(Vector3 b) { return new Basis( x * b.x, x * b.y, x * b.z, y * b.x, y * b.y, y * b.z, z * b.x, z * b.y, z * b.z ); } /// /// Returns a vector composed of the of this vector's components and `mod`. /// /// A value representing the divisor of the operation. /// A vector with each component by `mod`. public Vector3 PosMod(real_t mod) { Vector3 v; v.x = Mathf.PosMod(x, mod); v.y = Mathf.PosMod(y, mod); v.z = Mathf.PosMod(z, mod); return v; } /// /// Returns a vector composed of the of this vector's components and `modv`'s components. /// /// A vector representing the divisors of the operation. /// A vector with each component by `modv`'s components. public Vector3 PosMod(Vector3 modv) { Vector3 v; v.x = Mathf.PosMod(x, modv.x); v.y = Mathf.PosMod(y, modv.y); v.z = Mathf.PosMod(z, modv.z); return v; } /// /// Returns this vector projected onto another vector `b`. /// /// The vector to project onto. /// The projected vector. public Vector3 Project(Vector3 onNormal) { return onNormal * (Dot(onNormal) / onNormal.LengthSquared()); } /// /// Returns this vector reflected from a plane defined by the given `normal`. /// /// The normal vector defining the plane to reflect from. Must be normalized. /// The reflected vector. public Vector3 Reflect(Vector3 normal) { #if DEBUG if (!normal.IsNormalized()) { throw new ArgumentException("Argument is not normalized", nameof(normal)); } #endif return 2.0f * Dot(normal) * normal - this; } /// /// Rotates this vector around a given `axis` vector by `phi` radians. /// The `axis` vector must be a normalized vector. /// /// The vector to rotate around. Must be normalized. /// The angle to rotate by, in radians. /// The rotated vector. public Vector3 Rotated(Vector3 axis, real_t phi) { #if DEBUG if (!axis.IsNormalized()) { throw new ArgumentException("Argument is not normalized", nameof(axis)); } #endif return new Basis(axis, phi).Xform(this); } /// /// Returns this vector with all components rounded to the nearest integer, /// with halfway cases rounded towards the nearest multiple of two. /// /// The rounded vector. public Vector3 Round() { return new Vector3(Mathf.Round(x), Mathf.Round(y), Mathf.Round(z)); } /// /// Returns a vector with each component set to one or negative one, depending /// on the signs of this vector's components, or zero if the component is zero, /// by calling on each component. /// /// A vector with all components as either `1`, `-1`, or `0`. public Vector3 Sign() { Vector3 v; v.x = Mathf.Sign(x); v.y = Mathf.Sign(y); v.z = Mathf.Sign(z); return v; } /// /// Returns the signed angle to the given vector, in radians. /// The sign of the angle is positive in a counter-clockwise /// direction and negative in a clockwise direction when viewed /// from the side specified by the `axis`. /// /// The other vector to compare this vector to. /// The reference axis to use for the angle sign. /// The signed angle between the two vectors, in radians. public real_t SignedAngleTo(Vector3 to, Vector3 axis) { Vector3 crossTo = Cross(to); real_t unsignedAngle = Mathf.Atan2(crossTo.Length(), Dot(to)); real_t sign = crossTo.Dot(axis); return (sign < 0) ? -unsignedAngle : unsignedAngle; } /// /// Returns the result of the spherical linear interpolation between /// this vector and `to` by amount `weight`. /// /// Note: Both vectors must be normalized. /// /// The destination vector for interpolation. Must be normalized. /// A value on the range of 0.0 to 1.0, representing the amount of interpolation. /// The resulting vector of the interpolation. public Vector3 Slerp(Vector3 to, real_t weight) { #if DEBUG if (!IsNormalized()) { throw new InvalidOperationException("Vector3.Slerp: From vector is not normalized."); } if (!to.IsNormalized()) { throw new InvalidOperationException("Vector3.Slerp: `to` is not normalized."); } #endif real_t theta = AngleTo(to); return Rotated(Cross(to), theta * weight); } /// /// Returns this vector slid along a plane defined by the given normal. /// /// The normal vector defining the plane to slide on. /// The slid vector. public Vector3 Slide(Vector3 normal) { return this - normal * Dot(normal); } /// /// Returns this vector with each component snapped to the nearest multiple of `step`. /// This can also be used to round to an arbitrary number of decimals. /// /// A vector value representing the step size to snap to. /// The snapped vector. public Vector3 Snapped(Vector3 step) { return new Vector3 ( Mathf.Snapped(x, step.x), Mathf.Snapped(y, step.y), Mathf.Snapped(z, step.z) ); } /// /// Returns a diagonal matrix with the vector as main diagonal. /// /// This is equivalent to a Basis with no rotation or shearing and /// this vector's components set as the scale. /// /// A Basis with the vector as its main diagonal. public Basis ToDiagonalMatrix() { return new Basis( x, 0, 0, 0, y, 0, 0, 0, z ); } // Constants private static readonly Vector3 _zero = new Vector3(0, 0, 0); private static readonly Vector3 _one = new Vector3(1, 1, 1); private static readonly Vector3 _inf = new Vector3(Mathf.Inf, Mathf.Inf, Mathf.Inf); private static readonly Vector3 _up = new Vector3(0, 1, 0); private static readonly Vector3 _down = new Vector3(0, -1, 0); private static readonly Vector3 _right = new Vector3(1, 0, 0); private static readonly Vector3 _left = new Vector3(-1, 0, 0); private static readonly Vector3 _forward = new Vector3(0, 0, -1); private static readonly Vector3 _back = new Vector3(0, 0, 1); /// /// Zero vector, a vector with all components set to `0`. /// /// Equivalent to `new Vector3(0, 0, 0)` public static Vector3 Zero { get { return _zero; } } /// /// One vector, a vector with all components set to `1`. /// /// Equivalent to `new Vector3(1, 1, 1)` public static Vector3 One { get { return _one; } } /// /// Infinity vector, a vector with all components set to `Mathf.Inf`. /// /// Equivalent to `new Vector3(Mathf.Inf, Mathf.Inf, Mathf.Inf)` public static Vector3 Inf { get { return _inf; } } /// /// Up unit vector. /// /// Equivalent to `new Vector3(0, 1, 0)` public static Vector3 Up { get { return _up; } } /// /// Down unit vector. /// /// Equivalent to `new Vector3(0, -1, 0)` public static Vector3 Down { get { return _down; } } /// /// Right unit vector. Represents the local direction of right, /// and the global direction of east. /// /// Equivalent to `new Vector3(1, 0, 0)` public static Vector3 Right { get { return _right; } } /// /// Left unit vector. Represents the local direction of left, /// and the global direction of west. /// /// Equivalent to `new Vector3(-1, 0, 0)` public static Vector3 Left { get { return _left; } } /// /// Forward unit vector. Represents the local direction of forward, /// and the global direction of north. /// /// Equivalent to `new Vector3(0, 0, -1)` public static Vector3 Forward { get { return _forward; } } /// /// Back unit vector. Represents the local direction of back, /// and the global direction of south. /// /// Equivalent to `new Vector3(0, 0, 1)` public static Vector3 Back { get { return _back; } } /// /// Constructs a new with the given components. /// /// The vector's X component. /// The vector's Y component. /// The vector's Z component. public Vector3(real_t x, real_t y, real_t z) { this.x = x; this.y = y; this.z = z; } /// /// Constructs a new from an existing . /// /// The existing . public Vector3(Vector3 v) { x = v.x; y = v.y; z = v.z; } public static Vector3 operator +(Vector3 left, Vector3 right) { left.x += right.x; left.y += right.y; left.z += right.z; return left; } public static Vector3 operator -(Vector3 left, Vector3 right) { left.x -= right.x; left.y -= right.y; left.z -= right.z; return left; } public static Vector3 operator -(Vector3 vec) { vec.x = -vec.x; vec.y = -vec.y; vec.z = -vec.z; return vec; } public static Vector3 operator *(Vector3 vec, real_t scale) { vec.x *= scale; vec.y *= scale; vec.z *= scale; return vec; } public static Vector3 operator *(real_t scale, Vector3 vec) { vec.x *= scale; vec.y *= scale; vec.z *= scale; return vec; } public static Vector3 operator *(Vector3 left, Vector3 right) { left.x *= right.x; left.y *= right.y; left.z *= right.z; return left; } public static Vector3 operator /(Vector3 vec, real_t divisor) { vec.x /= divisor; vec.y /= divisor; vec.z /= divisor; return vec; } public static Vector3 operator /(Vector3 vec, Vector3 divisorv) { vec.x /= divisorv.x; vec.y /= divisorv.y; vec.z /= divisorv.z; return vec; } public static Vector3 operator %(Vector3 vec, real_t divisor) { vec.x %= divisor; vec.y %= divisor; vec.z %= divisor; return vec; } public static Vector3 operator %(Vector3 vec, Vector3 divisorv) { vec.x %= divisorv.x; vec.y %= divisorv.y; vec.z %= divisorv.z; return vec; } public static bool operator ==(Vector3 left, Vector3 right) { return left.Equals(right); } public static bool operator !=(Vector3 left, Vector3 right) { return !left.Equals(right); } public static bool operator <(Vector3 left, Vector3 right) { if (left.x == right.x) { if (left.y == right.y) { return left.z < right.z; } return left.y < right.y; } return left.x < right.x; } public static bool operator >(Vector3 left, Vector3 right) { if (left.x == right.x) { if (left.y == right.y) { return left.z > right.z; } return left.y > right.y; } return left.x > right.x; } public static bool operator <=(Vector3 left, Vector3 right) { if (left.x == right.x) { if (left.y == right.y) { return left.z <= right.z; } return left.y < right.y; } return left.x < right.x; } public static bool operator >=(Vector3 left, Vector3 right) { if (left.x == right.x) { if (left.y == right.y) { return left.z >= right.z; } return left.y > right.y; } return left.x > right.x; } public override bool Equals(object obj) { if (obj is Vector3) { return Equals((Vector3)obj); } return false; } public bool Equals(Vector3 other) { return x == other.x && y == other.y && z == other.z; } /// /// Returns true if this vector and `other` are approximately equal, by running /// on each component. /// /// The other vector to compare. /// Whether or not the vectors are approximately equal. public bool IsEqualApprox(Vector3 other) { return Mathf.IsEqualApprox(x, other.x) && Mathf.IsEqualApprox(y, other.y) && Mathf.IsEqualApprox(z, other.z); } public override int GetHashCode() { return y.GetHashCode() ^ x.GetHashCode() ^ z.GetHashCode(); } public override string ToString() { return String.Format("({0}, {1}, {2})", new object[] { x.ToString(), y.ToString(), z.ToString() }); } public string ToString(string format) { return String.Format("({0}, {1}, {2})", new object[] { x.ToString(format), y.ToString(format), z.ToString(format) }); } } }