From 7f9e3a45ad26e1349775db638dbcb7e23076fade Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 20:55:01 +0100 Subject: [PATCH] CultMath: clamp_cone atan2 angle, clamp_twist wraps about the window, inverse scales; tests kill the surviving mutants Co-Authored-By: Claude Sonnet 5.5 --- .../cultmath/src/CultMath/math.Quaternion.cs | 44 ++++--- .../tests/CultMath.Tests/QuaternionTests.cs | 121 +++++++++++++++++- 2 files changed, 146 insertions(+), 19 deletions(-) diff --git a/packages/cultmath/src/CultMath/math.Quaternion.cs b/packages/cultmath/src/CultMath/math.Quaternion.cs index ae75efbc..857f51b6 100644 --- a/packages/cultmath/src/CultMath/math.Quaternion.cs +++ b/packages/cultmath/src/CultMath/math.Quaternion.cs @@ -32,13 +32,17 @@ public static partial class math public static quaternion conjugate(quaternion q) => new(-q.x, -q.y, -q.z, q.w); /// - /// conjugate(q) / dot(q, q). Not guarded: a zero quaternion yields non-finite components, - /// as HLSL division does. + /// conjugate(q) / dot(q, q), computed on q divided by its largest component so that + /// dot(q, q) cannot underflow or overflow: every nonzero finite q gives its true inverse, except + /// where the result itself exceeds the float range. A zero quaternion yields non-finite + /// components, as HLSL division does. /// public static quaternion inverse(quaternion q) { - var n = 1.0f / (q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w); - return new quaternion(-q.x * n, -q.y * n, -q.z * n, q.w * n); + var m = max(max(abs(q.x), abs(q.y)), max(abs(q.z), abs(q.w))); + var s = new float4(q.x, q.y, q.z, q.w) / m; + var n = 1.0f / dot(s, s); + return new quaternion(-s.x * n / m, -s.y * n / m, -s.z * n / m, s.w * n / m); } /// @@ -94,16 +98,20 @@ public static partial class math /// /// Limits a twist (a rotation about , as from swing_twist) to - /// [, ] radians, min <= max. The angle is - /// 2 atan2(dot(twist.xyz, axis), twist.w) wrapped to (-pi, pi]. Inside the limit the input is - /// returned unchanged; outside, AxisAngle(axis, clamp(angle, min, max)). + /// [, ] radians, min <= max. Angles are taken modulo a + /// turn: the twist's angle 2 atan2(dot(twist.xyz, axis), twist.w) is wrapped into the turn + /// centred on the window, (centre - pi, centre + pi], so limits may lie anywhere (beyond pi, or + /// spanning more than half a turn) and a window of a full turn or more admits every twist. Inside the + /// window the input is returned unchanged; outside, AxisAngle(axis, clamp(angle, min, max)), + /// whose boundary is the one nearer by arc. /// public static quaternion clamp_twist(quaternion twist, float3 unitAxis, float min, float max) { var angle = 2.0f * atan2(dot(vec(twist), unitAxis), twist.w); const float pi = MathF.PI; - if (angle > pi) angle -= 2.0f * pi; - else if (angle <= -pi) angle += 2.0f * pi; + var centre = 0.5f * (min + max); + var a = angle - centre; + angle = a - 2.0f * pi * ceil((a - pi) / (2.0f * pi)) + centre; if (angle >= min && angle <= max) return twist; return quaternion.AxisAngle(unitAxis, clamp(angle, min, max)); @@ -120,20 +128,22 @@ public static partial class math } /// - /// Limits a swing to a cone of half-angle about . - /// The angle is that between rotate(swing, axis) and the axis. Inside the cone the input is - /// returned unchanged; outside, the rotation by maxAngle about normalize(cross(axis, - /// rotate(swing, axis))), or about the swing's own axis at a half turn, where that cross - /// product vanishes (length below 1e-6). + /// Limits a swing to a cone of half-angle (at least 0) about + /// . The angle is that between rotate(swing, axis) and the axis, + /// atan2(|cross|, dot), accurate at every size including tiny limits. Inside the cone the input + /// is returned unchanged; outside, the rotation by maxAngle about normalize(cross(axis, + /// rotate(swing, axis))), or about the swing's own axis at a half turn, where that cross product + /// vanishes (length below 1e-6 with the rotated axis pointing away). /// public static quaternion clamp_cone(quaternion swing, float3 unitAxis, float maxAngle) { var d = rotate(swing, unitAxis); - var angle = acos(clamp(dot(unitAxis, d), -1.0f, 1.0f)); + var c = cross(unitAxis, d); + var cosine = dot(unitAxis, d); + var angle = atan2(length(c), cosine); if (angle <= maxAngle) return swing; - var c = cross(unitAxis, d); - var axis = dot(c, c) < 1e-12f ? normalize(vec(swing)) : normalize(c); + var axis = cosine < 0.0f && dot(c, c) < 1e-12f ? normalize(vec(swing)) : normalize(c); return quaternion.AxisAngle(axis, maxAngle); } } diff --git a/packages/cultmath/tests/CultMath.Tests/QuaternionTests.cs b/packages/cultmath/tests/CultMath.Tests/QuaternionTests.cs index 050be34d..ff5c2602 100644 --- a/packages/cultmath/tests/CultMath.Tests/QuaternionTests.cs +++ b/packages/cultmath/tests/CultMath.Tests/QuaternionTests.cs @@ -53,8 +53,8 @@ public sealed class QuaternionTests Assert.True(d >= 1.0f - eps, $"|dot| = {d} for {a} vs {b}"); } - private static float AngleBetween(float3 a, float3 b) => - acos(clamp(dot(a, b) / (length(a) * length(b)), -1.0f, 1.0f)); + // atan2 form: acos resolves nothing below about 5e-4 rad. + private static float AngleBetween(float3 a, float3 b) => atan2(length(cross(a, b)), dot(a, b)); [Fact] public void CompositionAppliesTheRightOperandFirst() @@ -259,4 +259,121 @@ public sealed class QuaternionTests var ch = clamp_cone(half, z, 0.4f); Assert.True(abs(AngleBetween(rotate(ch, z), z) - 0.4f) <= 1e-4f); } + + private static float TwistAngle(quaternion q, float3 axis) => 2.0f * atan2(dot(new float3(q.x, q.y, q.z), axis), q.w); + + [Fact] + public void InverseIsTheTrueInverseAcrossTheFloatRange() + { + // dot(q, q) underflows (5e-21 each, 1e-30) or overflows (5e19 each) in float; the inverse is still + // conjugate(q) / |q|^2. Expected values are computed in double. + foreach (var (x, w) in new[] { (5e-21f, 5e-21f), (1e-30f, 1e-30f), (5e19f, 5e19f), (3e-25f, -4e-25f) }) + { + var q = new quaternion(x, x, x, w); + var n = (double)x * x * 3 + (double)w * w; + var r = inverse(q); + Assert.True(RelativelyEqual(-x / n, r.x) && RelativelyEqual(-x / n, r.y) && RelativelyEqual(-x / n, r.z) && RelativelyEqual(w / n, r.w), $"{q} -> {r}"); + } + // The result itself beyond the float range is infinite, not a wrong finite number. + Assert.True(float.IsInfinity(inverse(new quaternion(1e-40f, 0.0f, 0.0f, 1e-40f)).w)); + } + + private static bool RelativelyEqual(double expected, float actual) => + float.IsFinite(actual) && Math.Abs(expected - actual) <= 1e-5 * Math.Abs(expected); + + [Fact] + public void SwingTwistOfAnExactHalfTurnHasIdentityTwist() + { + // Exactly zero projection onto the axis (and zero w): the twist must be identity, not NaN. + foreach (var q in new[] { new quaternion(1.0f, 0.0f, 0.0f, 0.0f), new quaternion(0.0f, 1.0f, 0.0f, 0.0f) }) + { + swing_twist(q, new float3(0, 0, 1), out var swing, out var twist); + Assert.Equal(quaternion.identity, twist); + AssertSameRotation(swing, q, 1e-6f); + } + } + + [Fact] + public void ClampTwistTakesTheNearerBoundaryAcrossTheWrap() + { + var z = new float3(0, 0, 1); + // 3.1 against [-3.0, -2.5]: -3.0 is 0.18 rad away across the wrap, -2.5 is 5.6 rad away. + AssertSameRotation(clamp_twist(quaternion.AxisAngle(z, 3.1f), z, -3.0f, -2.5f), quaternion.AxisAngle(z, -3.0f)); + // And the mirror image. + AssertSameRotation(clamp_twist(quaternion.AxisAngle(z, -3.1f), z, 2.5f, 3.0f), quaternion.AxisAngle(z, 3.0f)); + // A window centred on pi: an angle just past -pi is inside it and unchanged. + var inside = quaternion.AxisAngle(z, -3.0f); + Assert.True(inside == clamp_twist(inside, z, 3.2f, 4.0f)); + Assert.True(inside == clamp_twist(inside, z, 2.5f, 3.4f)); + // Outside a window beyond pi: -2.0 (= 4.28) is nearer 4.0 than 3.2. + AssertSameRotation(clamp_twist(quaternion.AxisAngle(z, -2.0f), z, 3.2f, 4.0f), quaternion.AxisAngle(z, 4.0f)); + // A window of more than half a turn admits what it contains and clamps what it does not. + var a = quaternion.AxisAngle(z, 3.5f); + Assert.True(a == clamp_twist(a, z, -1.0f, 4.0f)); + AssertSameRotation(clamp_twist(quaternion.AxisAngle(z, 2.0f), z, -1.0f, 1.0f), quaternion.AxisAngle(z, 1.0f)); + // A full turn or more admits everything. + var any = quaternion.AxisAngle(z, 2.9f); + Assert.True(any == clamp_twist(any, z, -3.5f, 3.5f)); + } + + [Fact] + public void ClampHingeUsesTheGivenAxis() + { + var r = new System.Random(20); + for (var i = 0; i < 100; i++) + { + var axis = RandomUnit3(r); + var q = RandomRotation(r); + var h = clamp_hinge(q, axis, -0.7f, 0.7f); + Assert.True(length(cross(new float3(h.x, h.y, h.z), axis)) <= 1e-5f, "pure rotation about the given axis"); + var angle = TwistAngle(h, axis); + Assert.True(angle >= -0.7f - 1e-5f && angle <= 0.7f + 1e-5f); + + // Inside the limit the twist about that axis survives and the swing does not. + var perp = normalize(cross(axis, abs(axis.x) < 0.9f ? new float3(1, 0, 0) : new float3(0, 1, 0))); + var twist = quaternion.AxisAngle(axis, 0.4f); + AssertSameRotation(clamp_hinge(mul(quaternion.AxisAngle(perp, 0.6f), twist), axis, -1.0f, 1.0f), twist, 1e-4f); + } + } + + [Fact] + public void ClampConeEnforcesTinyLimits() + { + var z = new float3(0, 0, 1); + foreach (var angle in new[] { 1e-4f, 3e-5f, 1e-5f * 1.5f }) + { + var swing = quaternion.AxisAngle(new float3(1, 0, 0), angle); + var c = clamp_cone(swing, z, 1e-5f); + Assert.False(swing == c, $"swing of {angle} rad against 1e-5 was returned unchanged"); + Assert.True(abs(AngleBetween(rotate(c, z), z) - 1e-5f) <= 2e-6f, $"{c}"); + } + // Inside a tiny limit stays bit-identical. + var inside = quaternion.AxisAngle(new float3(1, 0, 0), 5e-6f); + Assert.True(inside == clamp_cone(inside, z, 1e-5f)); + } + + [Fact] + public void ClampConeOfAnExactHalfTurnLandsOnTheBoundary() + { + // rotate((1,0,0,0), z) is exactly -z, so cross(axis, rotated) is exactly zero: the swing's own axis + // is used and the result is finite and on the boundary. + var z = new float3(0, 0, 1); + var c = clamp_cone(new quaternion(1.0f, 0.0f, 0.0f, 0.0f), z, 0.4f); + Assert.True(float.IsFinite(c.x) && float.IsFinite(c.w), $"{c}"); + Assert.True(abs(AngleBetween(rotate(c, z), z) - 0.4f) <= 1e-4f); + } + + [Fact] + public void ClampConeUsesTheGivenAxis() + { + var r = new System.Random(21); + for (var i = 0; i < 100; i++) + { + var axis = RandomUnit3(r); + var swing = quaternion.AxisAngle(RandomUnit3(r), Uniform(r, 1.0f, 3.0f)); + if (AngleBetween(rotate(swing, axis), axis) <= 0.4f) continue; + var c = clamp_cone(swing, axis, 0.4f); + Assert.True(abs(AngleBetween(rotate(c, axis), axis) - 0.4f) <= 1e-4f); + } + } }