Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ClampLength functions to C++ Vector3 #1001

Merged
merged 1 commit into from Apr 16, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
52 changes: 52 additions & 0 deletions Source/Engine/Core/Math/Vector3.h
Expand Up @@ -566,6 +566,58 @@ API_STRUCT(Template) struct Vector3Base
result = Vector3Base(Math::Clamp(v.X, min.X, max.X), Math::Clamp(v.Y, min.Y, max.Y), Math::Clamp(v.Z, min.Z, max.Z));
}

/// <summary>
/// Makes sure that Length of the output vector is always below max and above 0.
/// </summary>
/// <param name="vector">Input Vector.</param>
/// <param name="max">Max Length</param>
static Vector3Base ClampLength(const Vector3Base& v, float max)
{
return ClampLength(v, 0, max);
}

/// <summary>
/// Makes sure that Length of the output vector is always below max and above min.
/// </summary>
/// <param name="vector">Input Vector.</param>
/// <param name="min">Min Length</param>
/// <param name="max">Max Length</param>
static Vector3Base ClampLength(const Vector3Base& v, float min, float max)
{
Vector3Base result;
ClampLength(v, min, max, result);
return result;
}

/// <summary>
/// Makes sure that Length of the output vector is always below max and above min.
/// </summary>
/// <param name="vector">Input Vector.</param>
/// <param name="min">Min Length</param>
/// <param name="max">Max Length</param>
/// <param name="result">The result vector.</param>
static void ClampLength(const Vector3Base& v, float min, float max, Vector3Base& result)
{
result.X = v.X;
result.Y = v.Y;
result.Z = v.Z;
auto lenSq = result.LengthSquared();
if (lenSq > max * max)
{
auto scaleFactor = max / (float)Math::Sqrt(lenSq);
result.X *= scaleFactor;
result.Y *= scaleFactor;
result.Z *= scaleFactor;
}
if (lenSq < min * min)
{
auto scaleFactor = min / (float)Math::Sqrt(lenSq);
result.X *= scaleFactor;
result.Y *= scaleFactor;
result.Z *= scaleFactor;
}
}

// Calculates the distance between two vectors
// @param a The first vector
// @param b The second vector
Expand Down