From 6ffcfcf9afab03ec908b4f33ce8c06fec9845535 Mon Sep 17 00:00:00 2001 From: Webster Sheets Date: Tue, 21 Nov 2023 20:11:00 -0500 Subject: [PATCH] Replace variable-length-arrays with alloca() Sadly, we can't have nice things that C99 has had for 24 years. --- src/collider/BVHTree.cpp | 5 +++-- src/core/macros.h | 11 +++++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/src/collider/BVHTree.cpp b/src/collider/BVHTree.cpp index 335ed07e1d6..a69fe9af304 100644 --- a/src/collider/BVHTree.cpp +++ b/src/collider/BVHTree.cpp @@ -6,6 +6,7 @@ #include "Aabb.h" #include "MathUtil.h" #include "core/Log.h" +#include "core/macros.h" #include "profiler/Profiler.h" const int MAX_SPLITPOS_RETRIES = 15; @@ -326,7 +327,7 @@ void SingleBVHTree::ComputeOverlap(uint32_t nodeId, const AABBd &nodeAabb, std:: PROFILE_SCOPED() int32_t stackLevel = 0; - uint32_t stack[m_treeHeight + 1]; + uint32_t *stack = stackalloc(uint32_t, m_treeHeight + 1); // Push the root node stack[stackLevel++] = 0; @@ -352,7 +353,7 @@ void SingleBVHTree::TraceRay(const vector3d &start, const vector3d &inv_dir, dou PROFILE_SCOPED() int32_t stackLevel = 0; - uint32_t stack[m_treeHeight + 1]; + uint32_t *stack = stackalloc(uint32_t, m_treeHeight + 1); stack[stackLevel++] = 0; while (stackLevel > 0) { diff --git a/src/core/macros.h b/src/core/macros.h index 56da7cffdc2..332d058b05a 100644 --- a/src/core/macros.h +++ b/src/core/macros.h @@ -37,3 +37,14 @@ template char (&COUNTOF_Helper(T (&array)[N]))[N]; #define COUNTOF(array) (sizeof(COUNTOF_Helper(array))) + +// Helper to implement stack-based variable-length arrays in a crossplatform way +// Avoids a heap allocation for std::vector in "hot" code + +#ifdef _MSC_VER +#include +#define stackalloc(T, n) reinterpret_cast(_alloca(sizeof(T) * n)) +#else +#include +#define stackalloc(T, n) reinterpret_cast(alloca(sizeof(T) * n)) +#endif