Game Engine Architecture

(Ben Green) #1

214 5. Engine Support Systems


// ...
// Allocate from the single-frame buffer. We never
// need to free this data! Just be sure to use it
// only this frame.
void* p = g_singleFrameAllocator.alloc(nBytes);

// ...
}

One of the primary benefi ts of a single-frame allocator is that allocated
memory needn’t ever be freed—we can rely on the fact that the allocator will
be cleared at the start of every frame. Single-frame allocators are also blind-
ingly fast. The one big negative is that using a single-frame allocator requires
a reasonable level of discipline on the part of the programmer. You need to
realize that a memory block allocated out of the single-frame buff er will only
be valid during the current frame. Programmers must never cache a pointer to
a single-frame memory block across the frame boundary!

Double-Buffered Allocators
A double-buff ered allocator allows a block of memory allocated on frame i to
be used on frame (i + 1). To accomplish this, we create two single-frame stack
allocators of equal size and then ping-pong between them every frame.

classDoubleBufferedAllocator
{
U32 m_curStack;
StackAllocator m_stack[2];
public:
void swapBuffers()
{
m_curStack = (U32)!m_curStack;
}
void clearCurrentBuffer()
{
m_stack[m_curStack]. clear();
}
void* alloc(U32 nBytes)
{
return m_stack[m_curStack].alloc(nBytes);
}

// ...
};
Free download pdf