Allocate Lua PenArray objects using an existing buffer

develop
lethosor 2015-03-28 11:27:47 -04:00
parent 99f4ea4d2b
commit e2b6ae9beb
4 changed files with 14 additions and 4 deletions

@ -1064,7 +1064,8 @@ static int dfhack_penarray_new(lua_State *L)
{ {
int bufwidth = luaL_checkint(L, 1); int bufwidth = luaL_checkint(L, 1);
int bufheight = luaL_checkint(L, 2); int bufheight = luaL_checkint(L, 2);
new (L) PenArray(bufwidth, bufheight); void *buf = lua_newuserdata(L, sizeof(PenArray) + (sizeof(Pen) * bufwidth * bufheight));
new (buf) PenArray(bufwidth, bufheight, buf);
lua_rawgetp(L, LUA_REGISTRYINDEX, &DFHACK_PENARRAY_TOKEN); lua_rawgetp(L, LUA_REGISTRYINDEX, &DFHACK_PENARRAY_TOKEN);
lua_setmetatable(L, -2); lua_setmetatable(L, -2);

@ -48,7 +48,6 @@ namespace DFHack {
} }
namespace Screen { namespace Screen {
struct Pen; struct Pen;
struct PenArray;
}; };
} }

@ -118,8 +118,10 @@ namespace DFHack
Pen *buffer; Pen *buffer;
unsigned int dimx; unsigned int dimx;
unsigned int dimy; unsigned int dimy;
bool static_alloc;
public: public:
PenArray(unsigned int bufwidth, unsigned int bufheight); PenArray(unsigned int bufwidth, unsigned int bufheight);
PenArray(unsigned int bufwidth, unsigned int bufheight, void *buf);
~PenArray(); ~PenArray();
void clear(); void clear();
void set_tile(unsigned int x, unsigned int y, Screen::Pen pen); void set_tile(unsigned int x, unsigned int y, Screen::Pen pen);

@ -442,15 +442,23 @@ df::interface_key Screen::charToKey(char code)
*/ */
PenArray::PenArray(unsigned int bufwidth, unsigned int bufheight) PenArray::PenArray(unsigned int bufwidth, unsigned int bufheight)
:dimx(bufwidth), dimy(bufheight) :dimx(bufwidth), dimy(bufheight), static_alloc(false)
{ {
buffer = new Pen[bufwidth * bufheight]; buffer = new Pen[bufwidth * bufheight];
clear(); clear();
} }
PenArray::PenArray(unsigned int bufwidth, unsigned int bufheight, void *buf)
:dimx(bufwidth), dimy(bufheight), static_alloc(true)
{
buffer = (Pen*)((uint8_t*)buf + sizeof(PenArray));
clear();
}
PenArray::~PenArray() PenArray::~PenArray()
{ {
delete[] buffer; if (!static_alloc)
delete[] buffer;
} }
void PenArray::clear() void PenArray::clear()