Skip to content

Commit

Permalink
MathLib: added WrapToRange function
Browse files Browse the repository at this point in the history
  • Loading branch information
TheMostDiligent committed Jan 29, 2024
1 parent de19e09 commit ec69aba
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
14 changes: 14 additions & 0 deletions Common/interface/BasicMath.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -2668,6 +2668,20 @@ typename std::enable_if<std::is_enum<T>::value, T>::type ExtractLSB(T& bits)
return static_cast<T>(ExtractLSB(reinterpret_cast<typename std::underlying_type<T>::type&>(bits)));
}

/// Wraps Value to the range [Min, Min + Range)
template <typename T>
T WrapToRange(T Value, T Min, T Range)
{
VERIFY_EXPR(Range >= 0);
if (Range <= 0)
return Min;

T Result = (Value - Min) % Range;
if (Result < 0)
Result += Range;

return Result + Min;
}

inline std::ostream& operator<<(std::ostream& os, const float4& vec)
{
Expand Down
34 changes: 33 additions & 1 deletion Tests/DiligentCoreTest/src/Common/MathLibTest.cpp
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2019-2023 Diligent Graphics LLC
* Copyright 2019-2024 Diligent Graphics LLC
* Copyright 2015-2019 Egor Yusov
*
* Licensed under the Apache License, Version 2.0 (the "License");
Expand Down Expand Up @@ -2292,6 +2292,38 @@ TEST(Common_BasicMath, VectorAll)
EXPECT_FALSE(all(double4{1, 1, 1, 0}));
}


TEST(Common_BasicMath, Wrap)
{
EXPECT_EQ(WrapToRange(10, 1, 0), 1);
EXPECT_EQ(WrapToRange(10, 1, 1), 1);
EXPECT_EQ(WrapToRange(-10, 1, 0), 1);
EXPECT_EQ(WrapToRange(-10, 1, 1), 1);

EXPECT_EQ(WrapToRange(0, 200, 10), 200);
EXPECT_EQ(WrapToRange(1, 200, 10), 201);
EXPECT_EQ(WrapToRange(9, 200, 10), 209);
EXPECT_EQ(WrapToRange(10, 200, 10), 200);

EXPECT_EQ(WrapToRange(-1, 200, 10), 209);
EXPECT_EQ(WrapToRange(-9, 200, 10), 201);
EXPECT_EQ(WrapToRange(-10, 200, 10), 200);

for (int Range : {1, 2, 7, 8, 9, 10, 15, 16, 17})
{
int Min = -Range / 2;
for (int i = -2; i <= 2; ++i)
{
for (int Ref = Min; Ref < Min + Range; ++Ref)
{
int Value = i * Range + Ref;
EXPECT_EQ(WrapToRange(Value, Min, Range), Ref) << Value << " " << Min << " " << Range;
}
}
}
}


TEST(Common_AdvancedMath, IsPointInsideTriangleF)
{
{
Expand Down

0 comments on commit ec69aba

Please sign in to comment.