From 9450111ae6c972bea301a189044085eca7428e26 Mon Sep 17 00:00:00 2001 From: Wojtek Figat Date: Mon, 11 Oct 2021 14:32:34 +0200 Subject: [PATCH] Fix possible division by zero in `Plane.Normalize` #648 --- Source/Engine/Core/Math/Plane.cpp | 11 +++++++++++ Source/Engine/Core/Math/Plane.cs | 15 +++++++++------ Source/Engine/Core/Math/Plane.h | 9 ++------- 3 files changed, 22 insertions(+), 13 deletions(-) diff --git a/Source/Engine/Core/Math/Plane.cpp b/Source/Engine/Core/Math/Plane.cpp index 341f33a8c..da225870d 100644 --- a/Source/Engine/Core/Math/Plane.cpp +++ b/Source/Engine/Core/Math/Plane.cpp @@ -29,6 +29,17 @@ String Plane::ToString() const return String::Format(TEXT("{}"), *this); } +void Plane::Normalize() +{ + const float length = Normal.Length(); + if (!Math::IsZero(length)) + { + const float rcp = 1.0f / length; + Normal *= rcp; + D *= rcp; + } +} + void Plane::Constlection(Matrix& result) const { const float x = Normal.X; diff --git a/Source/Engine/Core/Math/Plane.cs b/Source/Engine/Core/Math/Plane.cs index 79bf86bd8..4a4f96b82 100644 --- a/Source/Engine/Core/Math/Plane.cs +++ b/Source/Engine/Core/Math/Plane.cs @@ -214,12 +214,15 @@ namespace FlaxEngine /// public void Normalize() { - float magnitude = 1.0f / (float)Math.Sqrt(Normal.X * Normal.X + Normal.Y * Normal.Y + Normal.Z * Normal.Z); - - Normal.X *= magnitude; - Normal.Y *= magnitude; - Normal.Z *= magnitude; - D *= magnitude; + float length = (float)Math.Sqrt(Normal.X * Normal.X + Normal.Y * Normal.Y + Normal.Z * Normal.Z); + if (!Mathf.IsZero(length)) + { + float rcp = 1.0f / length; + Normal.X *= rcp; + Normal.Y *= rcp; + Normal.Z *= rcp; + D *= rcp; + } } /// diff --git a/Source/Engine/Core/Math/Plane.h b/Source/Engine/Core/Math/Plane.h index 2fbe7438c..448fc7573 100644 --- a/Source/Engine/Core/Math/Plane.h +++ b/Source/Engine/Core/Math/Plane.h @@ -97,14 +97,9 @@ public: public: /// - /// Changes the coefficients of the normal vector of the plane to make it of unit length + /// Changes the coefficients of the normal vector of the plane to make it of unit length. /// - void Normalize() - { - const float magnitude = Normal.InvLength(); - Normal *= magnitude; - D *= magnitude; - } + void Normalize(); void Negate() {