diff options
-rw-r--r-- | source/blender/blenlib/BLI_math_base.h | 1 | ||||
-rw-r--r-- | source/blender/blenlib/intern/math_base_inline.c | 7 | ||||
-rw-r--r-- | tests/gtests/blenlib/BLI_math_base_test.cc | 12 |
3 files changed, 20 insertions, 0 deletions
diff --git a/source/blender/blenlib/BLI_math_base.h b/source/blender/blenlib/BLI_math_base.h index c456ab0ecef..49aa9f3b465 100644 --- a/source/blender/blenlib/BLI_math_base.h +++ b/source/blender/blenlib/BLI_math_base.h @@ -103,6 +103,7 @@ MINLINE float pow2f(float x); MINLINE float pow3f(float x); MINLINE float pow4f(float x); MINLINE float pow7f(float x); +MINLINE float safe_powf(float base, float exponent); MINLINE float sqrt3f(float f); MINLINE double sqrt3d(double d); diff --git a/source/blender/blenlib/intern/math_base_inline.c b/source/blender/blenlib/intern/math_base_inline.c index 1b388dcf11f..26dc4d35c80 100644 --- a/source/blender/blenlib/intern/math_base_inline.c +++ b/source/blender/blenlib/intern/math_base_inline.c @@ -70,6 +70,13 @@ MINLINE float pow7f(float x) { return pow2f(pow3f(x)) * x; } +MINLINE float safe_powf(float base, float exponent) +{ + if (UNLIKELY(base < 0.0f && exponent != (int)exponent)) { + return 0.0f; + } + return powf(base, exponent); +} MINLINE float sqrt3f(float f) { diff --git a/tests/gtests/blenlib/BLI_math_base_test.cc b/tests/gtests/blenlib/BLI_math_base_test.cc index dc20c75576d..b7e7472eab2 100644 --- a/tests/gtests/blenlib/BLI_math_base_test.cc +++ b/tests/gtests/blenlib/BLI_math_base_test.cc @@ -113,3 +113,15 @@ TEST(math_base, Log2CeilU) EXPECT_EQ(log2_ceil_u(9), 4); EXPECT_EQ(log2_ceil_u(123456), 17); } + +TEST(math_base, SafePowf) +{ + EXPECT_FLOAT_EQ(safe_powf(4.0f, 3.0f), 64.0f); + EXPECT_FLOAT_EQ(safe_powf(3.2f, 5.6f), 674.2793796f); + EXPECT_FLOAT_EQ(safe_powf(4.0f, -2.0f), 0.0625f); + EXPECT_FLOAT_EQ(safe_powf(6.0f, -3.2f), 0.003235311f); + EXPECT_FLOAT_EQ(safe_powf(-4.0f, 6), 4096.0f); + EXPECT_FLOAT_EQ(safe_powf(-3.0f, 5.5), 0.0f); + EXPECT_FLOAT_EQ(safe_powf(-2.5f, -4.0f), 0.0256f); + EXPECT_FLOAT_EQ(safe_powf(-3.7f, -4.5f), 0.0f); +} |