namespace EvilEngine.GenerativeMotion; internal readonly record struct Double3(double X, double Y, double Z) { public static Double3 Zero => default; public double this[int axis] => axis switch { 0 => X, 1 => Y, _ => Z }; public static Double3 operator +(Double3 a, Double3 b) { return new Double3(a.X + b.X, a.Y + b.Y, a.Z + b.Z); } public static Double3 operator -(Double3 a, Double3 b) { return new Double3(a.X - b.X, a.Y - b.Y, a.Z - b.Z); } public static Double3 operator *(Double3 a, double s) { return new Double3(a.X * s, a.Y * s, a.Z * s); } public static Double3 operator /(Double3 a, double s) { return new Double3(a.X / s, a.Y / s, a.Z / s); } public double Length() { return Math.Sqrt(X * X + Y * Y + Z * Z); } public static double Dot(Double3 a, Double3 b) { return a.X * b.X + a.Y * b.Y + a.Z * b.Z; } public static Double3 Cross(Double3 a, Double3 b) { return new Double3(a.Y * b.Z - a.Z * b.Y, a.Z * b.X - a.X * b.Z, a.X * b.Y - a.Y * b.X); } public Double3 With(int axis, double value) { return axis switch { 0 => this with { X = value }, 1 => this with { Y = value }, _ => this with { Z = value } }; } public Double3 Add(int axis, double value) { return With(axis, this[axis] + value); } } internal readonly record struct DoubleQuat(double X, double Y, double Z, double W) { public static DoubleQuat Identity => new(0, 0, 0, 1); public static DoubleQuat operator *(DoubleQuat a, DoubleQuat b) { return new DoubleQuat( a.W * b.X + a.X * b.W + a.Y * b.Z - a.Z * b.Y, a.W * b.Y - a.X * b.Z + a.Y * b.W + a.Z * b.X, a.W * b.Z + a.X * b.Y - a.Y * b.X + a.Z * b.W, a.W * b.W - a.X * b.X - a.Y * b.Y - a.Z * b.Z); } public DoubleQuat Inverse() { return new DoubleQuat(-X, -Y, -Z, W); } public DoubleQuat Normalized() { var length = Math.Sqrt(X * X + Y * Y + Z * Z + W * W); return new DoubleQuat(X / length, Y / length, Z / length, W / length); } public Double3 Apply(Double3 v) { var u = new Double3(X, Y, Z); var t = Double3.Cross(u, v) * 2.0; return v + t * W + Double3.Cross(u, t); } public static DoubleQuat FromRotationVector(Double3 v) { var angle = v.Length(); var scale = angle <= 1e-3 ? 0.5 - angle * angle / 48.0 + angle * angle * angle * angle / 3840.0 : Math.Sin(angle / 2.0) / angle; return new DoubleQuat(v.X * scale, v.Y * scale, v.Z * scale, Math.Cos(angle / 2.0)); } public static DoubleQuat Between(Double3 u, Double3 v) { u /= u.Length(); v /= v.Length(); var axis = Double3.Cross(u, v); var s = axis.Length(); var c = Math.Clamp(Double3.Dot(u, v), -1.0, 1.0); return s < 1e-9 ? Identity : FromRotationVector(axis / s * Math.Atan2(s, c)); } }