From c64af3ac90b67ed1692753cdb996371e46de970b Mon Sep 17 00:00:00 2001 From: Patrick Nicolas Date: Wed, 16 Sep 2026 21:43:34 +0200 Subject: [PATCH] Fix float errors on quaternions 1% error on norm is too much and can cause overflow in quantization Even accurate normalization can have errors when computing sqrt if one coordinate is almost 0 --- common/packed_quaternion.h | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/common/packed_quaternion.h b/common/packed_quaternion.h index 7aadcb39..70d418c6 100644 --- a/common/packed_quaternion.h +++ b/common/packed_quaternion.h @@ -29,9 +29,15 @@ struct packed_quaternion { uint32_t value; - static packed_quaternion from_quaternion(const XrQuaternionf & q) + static packed_quaternion from_quaternion(XrQuaternionf q) { - assert(std::abs(q.w * q.w + q.x * q.x + q.y * q.y + q.z * q.z - 1) < 0.01); + auto norm = std::sqrt(q.w * q.w + q.x * q.x + q.y * q.y + q.z * q.z); + assert(std::abs(norm - 1) < 0.01); + + q.w /= norm; + q.x /= norm; + q.y /= norm; + q.z /= norm; float abs_w = std::abs(q.w); float abs_x = std::abs(q.x); @@ -81,7 +87,7 @@ struct packed_quaternion float q1 = (int((value >> 20) & 0x3ff) - 512) * scale_factor; float q2 = (int((value >> 10) & 0x3ff) - 512) * scale_factor; float q3 = (int((value >> 0) & 0x3ff) - 512) * scale_factor; - float q0 = std::sqrt(1 - q1 * q1 - q2 * q2 - q3 * q3); + float q0 = std::sqrt(std::max(0.f, 1 - q1 * q1 - q2 * q2 - q3 * q3)); switch (value >> 30) {