Skip to content

Commit

Permalink
Replace variable-length-arrays with alloca()
Browse files Browse the repository at this point in the history
Sadly, we can't have nice things that C99 has had for 24 years.
  • Loading branch information
sturnclaw committed Nov 22, 2023
1 parent fc36c6a commit 6ffcfcf
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
5 changes: 3 additions & 2 deletions src/collider/BVHTree.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;

Expand All @@ -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) {
Expand Down
11 changes: 11 additions & 0 deletions src/core/macros.h
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,14 @@
template <typename T, size_t N>
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 <malloc.h>
#define stackalloc(T, n) reinterpret_cast<T *>(_alloca(sizeof(T) * n))
#else
#include <alloca.h>
#define stackalloc(T, n) reinterpret_cast<T *>(alloca(sizeof(T) * n))
#endif

0 comments on commit 6ffcfcf

Please sign in to comment.