Add wrappers for malloc functions;

This commit is contained in:
bjorn 2024-03-11 14:38:00 -07:00
parent 2d7b636a90
commit d097d9819d
32 changed files with 330 additions and 456 deletions

View File

@ -521,9 +521,8 @@ int luax_readmesh(lua_State* L, int index, float** vertices, uint32_t* vertexCou
lovrCheck(*vertexCount > 0, "Invalid mesh data: vertex count is zero");
lovrCheck(*indexCount > 0, "Invalid mesh data: index count is zero");
lovrCheck(*indexCount % 3 == 0, "Index count must be a multiple of 3");
*vertices = malloc(sizeof(float) * *vertexCount * 3);
*indices = malloc(sizeof(uint32_t) * *indexCount);
lovrAssert(vertices && indices, "Out of memory");
*vertices = lovrMalloc(sizeof(float) * *vertexCount * 3);
*indices = lovrMalloc(sizeof(uint32_t) * *indexCount);
*shouldFree = true;
if (nested) {

View File

@ -200,8 +200,8 @@ static int l_lovrAudioSetGeometry(lua_State* L) {
AudioMaterial material = luax_checkenum(L, index, AudioMaterial, "generic");
bool success = lovrAudioSetGeometry(vertices, indices, vertexCount, indexCount, material);
if (shouldFree) {
free(vertices);
free(indices);
lovrFree(vertices);
lovrFree(indices);
}
lua_pushboolean(L, success);
return 1;

View File

@ -79,19 +79,16 @@ static int l_lovrDataNewBlob(lua_State* L) {
int isize = lua_tonumber(L, 1);
lovrCheck(isize > 0, "Blob size must be positive");
size = (size_t) isize;
data = calloc(1, size);
lovrAssert(data, "Out of memory");
data = lovrCalloc(size);
} else if (type == LUA_TSTRING) {
const char* str = luaL_checklstring(L, 1, &size);
data = malloc(size + 1);
lovrAssert(data, "Out of memory");
data = lovrMalloc(size + 1);
memcpy(data, str, size);
data[size] = '\0';
} else {
Blob* blob = luax_checktype(L, 1, Blob);
size = blob->size;
data = malloc(size);
lovrAssert(data, "Out of memory");
data = lovrMalloc(size);
memcpy(data, blob->data, size);
}
const char* name = luaL_optstring(L, 2, "");

View File

@ -55,8 +55,7 @@ void luax_checkvariant(lua_State* L, int index, Variant* variant) {
memcpy(variant->value.ministring.data, string, length);
} else {
variant->type = TYPE_STRING;
variant->value.string.pointer = malloc(length + 1);
lovrAssert(variant->value.string.pointer, "Out of memory");
variant->value.string.pointer = lovrMalloc(length + 1);
memcpy(variant->value.string.pointer, string, length);
variant->value.string.pointer[length] = '\0';
variant->value.string.length = length;
@ -92,8 +91,7 @@ void luax_checkvariant(lua_State* L, int index, Variant* variant) {
if (v) {
if (type == V_MAT4) {
variant->type = TYPE_MATRIX;
variant->value.matrix.data = malloc(16 * sizeof(float));
lovrAssert(variant->value.matrix.data, "Out of memory");
variant->value.matrix.data = lovrMalloc(16 * sizeof(float));
memcpy(variant->value.matrix.data, v, 16 * sizeof(float));
break;
} else {
@ -205,7 +203,7 @@ static int nextEvent(lua_State* L) {
luax_pushtype(L, Thread, event.data.thread.thread);
lua_pushstring(L, event.data.thread.error);
lovrRelease(event.data.thread.thread, lovrThreadDestroy);
free(event.data.thread.error);
lovrFree(event.data.thread.error);
return 3;
#endif

View File

@ -74,7 +74,7 @@ static int luax_loadfile(lua_State* L, const char* path, const char* debug, cons
return 2;
}
int status = luax_loadbufferx(L, buffer, size, debug, mode);
free(buffer);
lovrFree(buffer);
switch (status) {
case LUA_ERRMEM: return luaL_error(L, "Memory allocation error: %s", lua_tostring(L, -1));
case LUA_ERRSYNTAX: return luaL_error(L, "Syntax error: %s", lua_tostring(L, -1));
@ -315,7 +315,7 @@ static int l_lovrFilesystemRead(lua_State* L) {
return 1;
}
lua_pushlstring(L, data, size);
free(data);
lovrFree(data);
return 1;
}

View File

@ -41,17 +41,16 @@ static int l_lovrFileRead(lua_State* L) {
size = lovrFileGetSize(file) - lovrFileTell(file);
}
size_t count;
void* data = malloc(size);
lovrAssert(data, "Out of memory");
void* data = lovrMalloc(size);
bool success = lovrFileRead(file, data, size, &count);
if (success) {
lua_pushlstring(L, data, count);
lua_pushnumber(L, count);
free(data);
lovrFree(data);
return 2;
} else {
lua_pushnil(L);
free(data);
lovrFree(data);
return 1;
}
}

View File

@ -305,19 +305,14 @@ static void luax_writeshadercache(void) {
return;
}
void* data = malloc(size);
if (!data) {
return;
}
void* data = lovrMalloc(size);
lovrGraphicsGetShaderCache(data, &size);
if (size > 0) {
luax_writefile(".lovrshadercache", data, size);
}
free(data);
lovrFree(data);
}
static int l_lovrGraphicsInitialize(lua_State* L) {
@ -366,7 +361,7 @@ static int l_lovrGraphicsInitialize(lua_State* L) {
luax_atexit(L, luax_writeshadercache);
}
free(config.cacheData);
lovrFree(config.cacheData);
return 0;
}
@ -394,8 +389,7 @@ static int l_lovrGraphicsSubmit(lua_State* L) {
uint32_t count = 0;
Pass* stack[8];
Pass** passes = (size_t) length > COUNTOF(stack) ? malloc(length * sizeof(Pass*)) : stack;
lovrAssert(passes, "Out of memory");
Pass** passes = (size_t) length > COUNTOF(stack) ? lovrMalloc(length * sizeof(Pass*)) : stack;
if (table) {
for (int i = 0; i < length; i++) {
@ -414,7 +408,7 @@ static int l_lovrGraphicsSubmit(lua_State* L) {
}
lovrGraphicsSubmit(passes, count);
if (passes != stack) free(passes);
if (passes != stack) lovrFree(passes);
lua_pushboolean(L, true);
return 1;
}
@ -750,8 +744,7 @@ static int l_lovrGraphicsNewTexture(lua_State* L) {
info.mipmaps = 1;
} else if (lua_istable(L, 1)) {
info.imageCount = luax_len(L, index++);
images = info.imageCount > COUNTOF(stack) ? malloc(info.imageCount * sizeof(Image*)) : stack;
lovrAssert(images, "Out of memory");
images = info.imageCount > COUNTOF(stack) ? lovrMalloc(info.imageCount * sizeof(Image*)) : stack;
if (info.imageCount == 0) {
info.layers = 6;
@ -870,7 +863,7 @@ static int l_lovrGraphicsNewTexture(lua_State* L) {
}
if (images != stack) {
free(images);
lovrFree(images);
}
luax_pushtype(L, Texture, texture);
@ -1035,7 +1028,7 @@ static int l_lovrGraphicsCompileShader(lua_State* L) {
lovrGraphicsCompileShader(inputs, outputs, count, luax_readfile);
for (uint32_t i = 0; i < count; i++) {
if (shouldFree[i] && outputs[i].code != inputs[i].code) free((void*) inputs[i].code);
if (shouldFree[i] && outputs[i].code != inputs[i].code) lovrFree((void*) inputs[i].code);
Blob* blob = lovrBlobCreate((void*) outputs[i].code, outputs[i].size, "Shader code");
luax_pushtype(L, Blob, blob);
lovrRelease(blob, lovrBlobDestroy);
@ -1106,8 +1099,8 @@ static int l_lovrGraphicsNewShader(lua_State* L) {
lovrRelease(shader, lovrShaderDestroy);
for (uint32_t i = 0; i < info.stageCount; i++) {
if (shouldFree[i]) free((void*) source[i].code);
if (source[i].code != compiled[i].code) free((void*) compiled[i].code);
if (shouldFree[i]) lovrFree((void*) source[i].code);
if (source[i].code != compiled[i].code) lovrFree((void*) compiled[i].code);
}
arr_free(&flags);

View File

@ -7,8 +7,7 @@
ColoredString* luax_checkcoloredstrings(lua_State* L, int index, uint32_t* count, ColoredString* stack) {
if (lua_istable(L, index)) {
*count = luax_len(L, index) / 2;
ColoredString* strings = malloc(*count * sizeof(*strings));
lovrAssert(strings, "Out of memory");
ColoredString* strings = lovrMalloc(*count * sizeof(*strings));
for (uint32_t i = 0; i < *count; i++) {
lua_rawgeti(L, index, i * 2 + 1);
lua_rawgeti(L, index, i * 2 + 2);
@ -123,7 +122,7 @@ static int l_lovrFontGetLines(lua_State* L) {
float wrap = luax_checkfloat(L, 3);
lua_newtable(L);
lovrFontGetLines(font, strings, 1, wrap, online, L);
if (strings != &stack) free(strings);
if (strings != &stack) lovrFree(strings);
return 1;
}
@ -139,8 +138,7 @@ static int l_lovrFontGetVertices(lua_State* L) {
for (uint32_t i = 0; i < count; i++) {
totalLength += strings[i].length;
}
GlyphVertex* vertices = malloc(totalLength * 4 * sizeof(GlyphVertex));
lovrAssert(vertices, "Out of memory");
GlyphVertex* vertices = lovrMalloc(totalLength * 4 * sizeof(GlyphVertex));
uint32_t glyphCount, lineCount;
Material* material;
lovrFontGetVertices(font, strings, count, wrap, halign, valign, vertices, &glyphCount, &lineCount, &material, false);
@ -159,8 +157,8 @@ static int l_lovrFontGetVertices(lua_State* L) {
lua_rawseti(L, -2, i + 1);
}
luax_pushtype(L, Material, material);
if (strings != &stack) free(strings);
free(vertices);
if (strings != &stack) lovrFree(strings);
lovrFree(vertices);
return 2;
}

View File

@ -943,7 +943,7 @@ static int l_lovrPassText(lua_State* L) {
HorizontalAlign halign = luax_checkenum(L, index++, HorizontalAlign, "center");
VerticalAlign valign = luax_checkenum(L, index++, VerticalAlign, "middle");
lovrPassText(pass, strings, count, transform, wrap, halign, valign);
if (strings != &stack) free(strings);
if (strings != &stack) lovrFree(strings);
return 0;
}

View File

@ -81,9 +81,8 @@ Shape* luax_newmeshshape(lua_State* L, int index) {
if (!shouldFree) {
float* v = vertices;
uint32_t* i = indices;
vertices = malloc(3 * vertexCount * sizeof(float));
indices = malloc(indexCount * sizeof(uint32_t));
lovrAssert(vertices && indices, "Out of memory");
vertices = lovrMalloc(3 * vertexCount * sizeof(float));
indices = lovrMalloc(indexCount * sizeof(uint32_t));
memcpy(vertices, v, 3 * vertexCount * sizeof(float));
memcpy(indices, i, indexCount * sizeof(uint32_t));
}
@ -99,8 +98,7 @@ Shape* luax_newterrainshape(lua_State* L, int index) {
return lovrTerrainShapeCreate(vertices, 2, 2, horizontalScale, 1.f);
} else if (type == LUA_TFUNCTION) {
uint32_t samples = luax_optu32(L, index + 1, 100);
float* vertices = malloc(sizeof(float) * samples * samples);
lovrAssert(vertices, "Out of memory");
float* vertices = lovrMalloc(sizeof(float) * samples * samples);
for (uint32_t i = 0; i < samples * samples; i++) {
float x = horizontalScale * (-.5f + ((float) (i % samples)) / samples);
float z = horizontalScale * (-.5f + ((float) (i / samples)) / samples);
@ -113,15 +111,14 @@ Shape* luax_newterrainshape(lua_State* L, int index) {
lua_pop(L, 1);
}
TerrainShape* shape = lovrTerrainShapeCreate(vertices, samples, samples, horizontalScale, 1.f);
free(vertices);
lovrFree(vertices);
return shape;
} else if (type == LUA_TUSERDATA) {
Image* image = luax_checktype(L, index, Image);
uint32_t imageWidth = lovrImageGetWidth(image, 0);
uint32_t imageHeight = lovrImageGetHeight(image, 0);
float verticalScale = luax_optfloat(L, index + 1, 1.f);
float* vertices = malloc(sizeof(float) * imageWidth * imageHeight);
lovrAssert(vertices, "Out of memory");
float* vertices = lovrMalloc(sizeof(float) * imageWidth * imageHeight);
for (uint32_t y = 0; y < imageHeight; y++) {
for (uint32_t x = 0; x < imageWidth; x++) {
float pixel[4];
@ -130,7 +127,7 @@ Shape* luax_newterrainshape(lua_State* L, int index) {
}
}
TerrainShape* shape = lovrTerrainShapeCreate(vertices, imageWidth, imageHeight, horizontalScale, verticalScale);
free(vertices);
lovrFree(vertices);
return shape;
} else {
luax_typeerror(L, index, "Image, number, or function");

View File

@ -30,9 +30,9 @@ static char* threadRunner(Thread* thread, Blob* body, Variant* arguments, uint32
// Error handling
size_t length;
const char* message = lua_tolstring(L, -1, &length);
char* error = message ? malloc(length + 1) : NULL;
if (error) {
if (message) {
char* error = lovrMalloc(length + 1);
memcpy(error, message, length + 1);
lua_close(L);
return error;
@ -48,8 +48,7 @@ static int l_lovrThreadNewThread(lua_State* L) {
size_t length;
const char* str = luaL_checklstring(L, 1, &length);
if (memchr(str, '\n', MIN(1024, length))) {
void* data = malloc(length + 1);
lovrAssert(data, "Out of memory");
void* data = lovrMalloc(length + 1);
memcpy(data, str, length + 1);
blob = lovrBlobCreate(data, length, "thread code");
} else {

View File

@ -229,7 +229,7 @@ void lovrAudioDestroy(void) {
if (atomic_fetch_sub(&state.ref, 1) != 1) return;
for (size_t i = 0; i < 2; i++) {
ma_device_uninit(&state.devices[i]);
free(state.deviceInfo[i]);
lovrFree(state.deviceInfo[i]);
}
Source* source;
FOREACH_SOURCE(source) lovrRelease(source, lovrSourceDestroy);
@ -267,8 +267,7 @@ bool lovrAudioGetDevice(AudioType type, AudioDevice* device) {
}
if (!state.deviceInfo[type]) {
state.deviceInfo[type] = malloc(sizeof(ma_device_info));
lovrAssert(state.deviceInfo[type], "Out of memory");
state.deviceInfo[type] = lovrMalloc(sizeof(ma_device_info));
}
ma_device_info* info = state.deviceInfo[type];
@ -408,8 +407,7 @@ void lovrAudioSetAbsorption(float absorption[3]) {
Source* lovrSourceCreate(Sound* sound, bool pitchable, bool spatial, uint32_t effects) {
lovrCheck(lovrSoundGetChannelLayout(sound) != CHANNEL_AMBISONIC, "Ambisonic Sources are not currently supported");
Source* source = calloc(1, sizeof(Source));
lovrAssert(source, "Out of memory");
Source* source = lovrCalloc(sizeof(Source));
source->ref = 1;
source->index = ~0u;
source->sound = sound;
@ -432,8 +430,7 @@ Source* lovrSourceCreate(Sound* sound, bool pitchable, bool spatial, uint32_t ef
config.allowDynamicSampleRate = pitchable;
if (pitchable || config.formatIn != config.formatOut || config.channelsIn != config.channelsOut || config.sampleRateIn != config.sampleRateOut) {
source->converter = malloc(sizeof(ma_data_converter));
lovrAssert(source->converter, "Out of memory");
source->converter = lovrMalloc(sizeof(ma_data_converter));
ma_result status = ma_data_converter_init(&config, NULL, source->converter);
lovrAssert(status == MA_SUCCESS, "Problem creating Source data converter: %s (%d)", ma_result_description(status), status);
}
@ -442,8 +439,7 @@ Source* lovrSourceCreate(Sound* sound, bool pitchable, bool spatial, uint32_t ef
}
Source* lovrSourceClone(Source* source) {
Source* clone = calloc(1, sizeof(Source));
lovrAssert(clone, "Out of memory");
Source* clone = lovrCalloc(sizeof(Source));
clone->ref = 1;
clone->index = ~0u;
clone->sound = source->sound;
@ -460,8 +456,7 @@ Source* lovrSourceClone(Source* source) {
clone->pitchable = source->pitchable;
clone->spatial = source->spatial;
if (source->converter) {
clone->converter = malloc(sizeof(ma_data_converter));
lovrAssert(clone->converter, "Out of memory");
clone->converter = lovrMalloc(sizeof(ma_data_converter));
ma_data_converter_config config = ma_data_converter_config_init_default();
config.formatIn = source->converter->formatIn;
config.formatOut = source->converter->formatOut;
@ -480,8 +475,8 @@ void lovrSourceDestroy(void* ref) {
Source* source = ref;
lovrRelease(source->sound, lovrSoundDestroy);
ma_data_converter_uninit(source->converter, NULL);
free(source->converter);
free(source);
lovrFree(source->converter);
lovrFree(source);
}
Sound* lovrSourceGetSound(Source* source) {

View File

@ -150,8 +150,7 @@ bool phonon_init(void) {
state.renderingSettings.frameSize = BUFFER_SIZE;
state.renderingSettings.convolutionType = IPL_CONVOLUTIONTYPE_PHONON;
state.scratchpad = malloc(BUFFER_SIZE * 4 * sizeof(float));
if (!state.scratchpad) return phonon_destroy(), false;
state.scratchpad = lovrMalloc(BUFFER_SIZE * 4 * sizeof(float));
IPLHrtfParams hrtfParams = {
.type = IPL_HRTFDATABASETYPE_DEFAULT
@ -167,7 +166,7 @@ bool phonon_init(void) {
}
void phonon_destroy(void) {
if (state.scratchpad) free(state.scratchpad);
if (state.scratchpad) lovrFree(state.scratchpad);
for (size_t i = 0; i < MAX_SOURCES; i++) {
if (state.binauralEffect[i]) phonon_iplDestroyBinauralEffect(&state.binauralEffect[i]);
if (state.directSoundEffect[i]) phonon_iplDestroyDirectSoundEffect(&state.directSoundEffect[i]);
@ -334,8 +333,7 @@ bool phonon_setGeometry(float* vertices, uint32_t* indices, uint32_t vertexCount
.irradianceMinDistance = .1f
};
IPLint32* triangleMaterials = malloc(indexCount / 3 * sizeof(IPLint32));
if (!triangleMaterials) goto fail;
IPLint32* triangleMaterials = lovrMalloc(indexCount / 3 * sizeof(IPLint32));
for (uint32_t i = 0; i < indexCount / 3; i++) {
triangleMaterials[i] = material;
@ -356,11 +354,11 @@ bool phonon_setGeometry(float* vertices, uint32_t* indices, uint32_t vertexCount
status = phonon_iplCreateEnvironmentalRenderer(state.context, state.environment, state.renderingSettings, AMBISONIC, NULL, NULL, &state.environmentalRenderer);
if (status != IPL_STATUS_SUCCESS) goto fail;
free(triangleMaterials);
lovrFree(triangleMaterials);
return true;
fail:
free(triangleMaterials);
lovrFree(triangleMaterials);
if (state.mesh) phonon_iplDestroyStaticMesh(&state.mesh);
if (state.scene) phonon_iplDestroyScene(&state.scene);
if (state.environment) phonon_iplDestroyEnvironment(&state.environment);

View File

@ -3,8 +3,7 @@
#include <stdlib.h>
Blob* lovrBlobCreate(void* data, size_t size, const char* name) {
Blob* blob = calloc(1, sizeof(Blob));
lovrAssert(blob, "Out of memory");
Blob* blob = lovrMalloc(sizeof(Blob));
blob->ref = 1;
blob->data = data;
blob->size = size;
@ -14,6 +13,6 @@ Blob* lovrBlobCreate(void* data, size_t size, const char* name) {
void lovrBlobDestroy(void* ref) {
Blob* blob = ref;
free(blob->data);
free(blob);
lovrFree(blob->data);
lovrFree(blob);
}

View File

@ -83,9 +83,8 @@ Image* lovrImageCreateRaw(uint32_t width, uint32_t height, TextureFormat format,
lovrCheck(width > 0 && height > 0, "Image dimensions must be positive");
lovrCheck(format < FORMAT_BC1, "Blank images cannot be compressed");
size_t size = measure(width, height, format);
void* data = malloc(size);
Image* image = calloc(1, sizeof(Image));
lovrAssert(image && data, "Out of memory");
void* data = lovrMalloc(size);
Image* image = lovrCalloc(sizeof(Image));
image->ref = 1;
image->flags = srgb ? IMAGE_SRGB : 0;
image->width = width;
@ -120,7 +119,7 @@ Image* lovrImageCreateFromFile(Blob* blob) {
void lovrImageDestroy(void* ref) {
Image* image = ref;
lovrRelease(image->blob, lovrBlobDestroy);
free(image);
lovrFree(image);
}
bool lovrImageIsSRGB(Image* image) {
@ -350,8 +349,7 @@ Blob* lovrImageEncode(Image* image) {
size += 4 + strlen("IHDR") + sizeof(header) + 4;
size += 4 + strlen("IDAT") + idatSize + 4;
size += 4 + strlen("IEND") + 4;
uint8_t* data = malloc(size);
lovrAssert(data, "Out of memory");
uint8_t* data = lovrMalloc(size);
crc_init();
uint32_t crc;
@ -790,8 +788,7 @@ static Image* loadDDS(Blob* blob) {
lovrCheck(~header->flags & DDSD_DEPTH, "Loading 3D DDS images is not supported");
uint32_t levels = MAX(1, header->mipmapCount);
Image* image = calloc(1, offsetof(Image, mipmaps) + levels * sizeof(Mipmap));
lovrAssert(image, "Out of memory");
Image* image = lovrCalloc(offsetof(Image, mipmaps) + levels * sizeof(Mipmap));
image->ref = 1;
image->flags = flags;
image->width = header->width;
@ -870,8 +867,7 @@ static Image* loadASTC(Blob* blob) {
return NULL;
}
Image* image = calloc(1, sizeof(Image));
lovrAssert(image, "Out of memory");
Image* image = lovrCalloc(sizeof(Image));
image->ref = 1;
image->width = width;
image->height = height;
@ -934,8 +930,7 @@ static Image* loadKTX1(Blob* blob) {
uint32_t layers = MAX(header.numberOfArrayElements, 1);
uint32_t levels = MAX(header.numberOfMipmapLevels, 1);
Image* image = calloc(1, offsetof(Image, mipmaps) + levels * sizeof(Mipmap));
lovrAssert(image, "Out of memory");
Image* image = lovrCalloc(offsetof(Image, mipmaps) + levels * sizeof(Mipmap));
image->ref = 1;
image->width = header.pixelWidth;
image->height = header.pixelHeight;
@ -1084,8 +1079,7 @@ static Image* loadKTX2(Blob* blob) {
uint32_t layers = MAX(header->layerCount, 1);
uint32_t levels = MAX(header->levelCount, 1);
Image* image = calloc(1, offsetof(Image, mipmaps) + levels * sizeof(Mipmap));
lovrAssert(image, "Out of memory");
Image* image = lovrCalloc(offsetof(Image, mipmaps) + levels * sizeof(Mipmap));
image->ref = 1;
image->width = header->pixelWidth;
image->height = header->pixelHeight;
@ -1194,8 +1188,7 @@ static Image* loadSTB(Blob* blob) {
size_t size = measure(width, height, format);
Image* image = calloc(1, sizeof(Image));
lovrAssert(image, "Out of memory");
Image* image = lovrCalloc(sizeof(Image));
image->ref = 1;
image->flags = flags;
image->width = width;

View File

@ -21,8 +21,7 @@ static void* nullIO(const char* path, size_t* count) {
}
ModelData* lovrModelDataCreate(Blob* source, ModelDataIO* io) {
ModelData* model = calloc(1, sizeof(ModelData));
lovrAssert(model, "Out of memory");
ModelData* model = lovrCalloc(sizeof(ModelData));
model->ref = 1;
if (!io) {
@ -55,11 +54,11 @@ void lovrModelDataDestroy(void* ref) {
map_free(&model->animationMap);
map_free(&model->materialMap);
map_free(&model->nodeMap);
free(model->vertices);
free(model->indices);
free(model->metadata);
free(model->data);
free(model);
lovrFree(model->vertices);
lovrFree(model->indices);
lovrFree(model->metadata);
lovrFree(model->data);
lovrFree(model);
}
// Batches allocations for all the ModelData arrays
@ -84,8 +83,7 @@ void lovrModelDataAllocate(ModelData* model) {
totalSize += sizes[14] = model->charCount * sizeof(char);
size_t offset = 0;
char* p = model->data = calloc(1, totalSize);
lovrAssert(model->data, "Out of memory");
char* p = model->data = lovrCalloc(totalSize);
model->blobs = (Blob**) (p + offset), offset += sizes[0];
model->buffers = (ModelBuffer*) (p + offset), offset += sizes[1];
model->images = (Image**) (p + offset), offset += sizes[2];
@ -389,8 +387,7 @@ void lovrModelDataGetBoundingSphere(ModelData* model, float sphere[4]) {
}
uint32_t pointCount = totalPrimitiveCount * 8;
float* points = malloc(pointCount * 3 * sizeof(float));
lovrAssert(points, "Out of memory");
float* points = lovrMalloc(pointCount * 3 * sizeof(float));
uint32_t pointIndex = 0;
boundingSphereHelper(model, model->rootNode, &pointIndex, points, (float[16]) MAT4_IDENTITY);
@ -445,7 +442,7 @@ void lovrModelDataGetBoundingSphere(ModelData* model, float sphere[4]) {
model->boundingSphere[1] = y;
model->boundingSphere[2] = z;
model->boundingSphere[3] = r;
free(points);
lovrFree(points);
}
memcpy(sphere, model->boundingSphere, sizeof(model->boundingSphere));
@ -562,9 +559,8 @@ void lovrModelDataGetTriangles(ModelData* model, float** vertices, uint32_t** in
if (vertices && !model->vertices) {
uint32_t baseIndex = 0;
model->vertices = malloc(model->totalVertexCount * 3 * sizeof(float));
model->indices = malloc(model->totalIndexCount * sizeof(uint32_t));
lovrAssert(model->vertices && model->indices, "Out of memory");
model->vertices = lovrMalloc(model->totalVertexCount * 3 * sizeof(float));
model->indices = lovrMalloc(model->totalIndexCount * sizeof(uint32_t));
*vertices = model->vertices;
*indices = model->indices;
collectVertices(model, model->rootNode, vertices, indices, &baseIndex, (float[16]) MAT4_IDENTITY);

View File

@ -88,10 +88,7 @@ static void* decodeBase64(char* str, size_t length, size_t* decodedLength) {
length -= s - str;
int padding = (s[length - 1] == '=') + (s[length - 2] == '=');
*decodedLength = length / 4 * 3 - padding;
uint8_t* data = malloc(*decodedLength);
if (!data) {
return NULL;
}
uint8_t* data = lovrMalloc(*decodedLength);
uint32_t num = 0;
uint32_t bits = 0;
@ -113,7 +110,7 @@ static void* decodeBase64(char* str, size_t length, size_t* decodedLength) {
} else if (c == '=') {
break;
} else {
free(data);
lovrFree(data);
return NULL;
}
@ -241,8 +238,7 @@ ModelData* lovrModelDataInitGltf(ModelData* model, Blob* source, ModelDataIO* io
binOffset = 0;
}
model->metadata = malloc(jsonLength);
lovrAssert(model->metadata, "Out of memory");
model->metadata = lovrMalloc(jsonLength);
memcpy(model->metadata, json, jsonLength);
model->metadataSize = jsonLength;
model->metadataType = META_GLTF_JSON;
@ -271,7 +267,7 @@ ModelData* lovrModelDataInitGltf(ModelData* model, Blob* source, ModelDataIO* io
}
if (tokenCount <= 0 || tokens[0].type != JSMN_OBJECT) {
free(heapTokens);
lovrFree(heapTokens);
return NULL;
}
@ -325,8 +321,7 @@ ModelData* lovrModelDataInitGltf(ModelData* model, Blob* source, ModelDataIO* io
}
}
animationSamplers = malloc(samplerCount * sizeof(gltfAnimationSampler));
lovrAssert(animationSamplers, "Out of memory");
animationSamplers = lovrMalloc(samplerCount * sizeof(gltfAnimationSampler));
gltfAnimationSampler* sampler = animationSamplers;
for (int i = (token++)->size; i > 0; i--) {
for (int k = (token++)->size; k > 0; k--) {
@ -369,8 +364,7 @@ ModelData* lovrModelDataInitGltf(ModelData* model, Blob* source, ModelDataIO* io
} else if (STR_EQ(key, "images")) {
model->imageCount = token->size;
images = malloc(model->imageCount * sizeof(gltfImage));
lovrAssert(images, "Out of memory");
images = lovrMalloc(model->imageCount * sizeof(gltfImage));
gltfImage* image = images;
for (int i = (token++)->size; i > 0; i--, image++) {
image->bufferView = ~0u;
@ -388,8 +382,7 @@ ModelData* lovrModelDataInitGltf(ModelData* model, Blob* source, ModelDataIO* io
}
} else if (STR_EQ(key, "textures")) {
textures = malloc(token->size * sizeof(gltfTexture));
lovrAssert(textures, "Out of memory");
textures = lovrMalloc(token->size * sizeof(gltfTexture));
gltfTexture* texture = textures;
for (int i = (token++)->size; i > 0; i--, texture++) {
texture->image = ~0u;
@ -433,8 +426,7 @@ ModelData* lovrModelDataInitGltf(ModelData* model, Blob* source, ModelDataIO* io
} else if (STR_EQ(key, "meshes")) {
info.meshes = token;
meshes = malloc(token->size * sizeof(gltfMesh));
lovrAssert(meshes, "Out of memory");
meshes = lovrMalloc(token->size * sizeof(gltfMesh));
gltfMesh* mesh = meshes;
model->primitiveCount = 0;
model->blendShapeCount = 0;
@ -500,8 +492,7 @@ ModelData* lovrModelDataInitGltf(ModelData* model, Blob* source, ModelDataIO* io
} else if (STR_EQ(key, "scenes")) {
info.scenes = token;
info.sceneCount = token->size;
scenes = malloc(info.sceneCount * sizeof(gltfScene));
lovrAssert(scenes, "Out of memory");
scenes = lovrMalloc(info.sceneCount * sizeof(gltfScene));
gltfScene* scene = scenes;
for (int i = (token++)->size; i > 0; i--, scene++) {
for (int k = (token++)->size; k > 0; k--) {
@ -1058,11 +1049,11 @@ ModelData* lovrModelDataInitGltf(ModelData* model, Blob* source, ModelDataIO* io
model->rootNode = scenes[rootScene].node;
}
free(animationSamplers);
free(meshes);
free(images);
free(textures);
free(scenes);
free(heapTokens);
lovrFree(animationSamplers);
lovrFree(meshes);
lovrFree(images);
lovrFree(textures);
lovrFree(scenes);
lovrFree(heapTokens);
return model;
}

View File

@ -101,7 +101,7 @@ static void parseMtl(char* path, char* base, ModelDataIO* io, arr_image_t* image
data = newline + 1;
}
free(p);
lovrFree(p);
}
ModelData* lovrModelDataInitObj(ModelData* model, Blob* source, ModelDataIO* io) {

View File

@ -17,8 +17,7 @@ static ModelData* lovrModelDataInitStlBinary(ModelData* model, Blob* source, Mod
uint32_t vertexCount = triangleCount * 3;
size_t vertexBufferSize = vertexCount * 6 * sizeof(float);
float* vertices = malloc(vertexBufferSize);
lovrAssert(vertices, "Out of memory");
float* vertices = lovrMalloc(vertexBufferSize);
model->blobCount = 1;
model->bufferCount = 1;

View File

@ -19,8 +19,7 @@ struct Rasterizer {
};
Rasterizer* lovrRasterizerCreate(Blob* blob, float size) {
Rasterizer* rasterizer = calloc(1, sizeof(Rasterizer));
lovrAssert(rasterizer, "Out of memory");
Rasterizer* rasterizer = lovrCalloc(sizeof(Rasterizer));
rasterizer->ref = 1;
stbtt_fontinfo* font = &rasterizer->font;
@ -47,7 +46,7 @@ Rasterizer* lovrRasterizerCreate(Blob* blob, float size) {
void lovrRasterizerDestroy(void* ref) {
Rasterizer* rasterizer = ref;
lovrRelease(rasterizer->blob, lovrBlobDestroy);
free(rasterizer);
lovrFree(rasterizer);
}
float lovrRasterizerGetFontSize(Rasterizer* rasterizer) {

View File

@ -78,8 +78,7 @@ static uint32_t lovrSoundReadMp3(Sound* sound, uint32_t offset, uint32_t count,
// Sound
Sound* lovrSoundCreateRaw(uint32_t frames, SampleFormat format, ChannelLayout layout, uint32_t sampleRate, Blob* blob) {
Sound* sound = calloc(1, sizeof(Sound));
lovrAssert(sound, "Out of memory");
Sound* sound = lovrCalloc(sizeof(Sound));
sound->ref = 1;
sound->frames = frames;
sound->format = format;
@ -87,8 +86,7 @@ Sound* lovrSoundCreateRaw(uint32_t frames, SampleFormat format, ChannelLayout la
sound->sampleRate = sampleRate;
sound->read = lovrSoundReadRaw;
size_t size = frames * lovrSoundGetStride(sound);
void* data = calloc(1, size);
lovrAssert(data, "Out of memory");
void* data = lovrCalloc(size);
sound->blob = lovrBlobCreate(data, size, "Sound");
if (blob) {
@ -99,19 +97,16 @@ Sound* lovrSoundCreateRaw(uint32_t frames, SampleFormat format, ChannelLayout la
}
Sound* lovrSoundCreateStream(uint32_t frames, SampleFormat format, ChannelLayout layout, uint32_t sampleRate) {
Sound* sound = calloc(1, sizeof(Sound));
lovrAssert(sound, "Out of memory");
Sound* sound = lovrCalloc(sizeof(Sound));
sound->ref = 1;
sound->frames = frames;
sound->format = format;
sound->layout = layout;
sound->sampleRate = sampleRate;
sound->read = lovrSoundReadStream;
sound->stream = malloc(sizeof(ma_pcm_rb));
lovrAssert(sound->stream, "Out of memory");
sound->stream = lovrMalloc(sizeof(ma_pcm_rb));
size_t size = frames * lovrSoundGetStride(sound);
void* data = malloc(size);
lovrAssert(data, "Out of memory");
void* data = lovrMalloc(size);
sound->blob = lovrBlobCreate(data, size, NULL);
ma_result status = ma_pcm_rb_init(miniaudioFormats[format], lovrSoundGetChannelCount(sound), frames, data, NULL, sound->stream);
lovrAssert(status == MA_SUCCESS, "Failed to create ring buffer for streamed Sound: %s (%d)", ma_result_description(status), status);
@ -135,8 +130,7 @@ static bool loadOgg(Sound* sound, Blob* blob, bool decode) {
uint32_t channels = lovrSoundGetChannelCount(sound);
lovrAssert(sound->frames * channels <= INT_MAX, "Decoded OGG file has too many samples");
size_t size = sound->frames * lovrSoundGetStride(sound);
void* data = calloc(1, size);
lovrAssert(data, "Out of memory");
void* data = lovrCalloc(size);
sound->blob = lovrBlobCreate(data, size, "Sound");
if (stb_vorbis_get_samples_float_interleaved(sound->decoder, channels, data, (int) size / sizeof(float)) < (int) sound->frames) {
lovrThrow("Could not decode vorbis from '%s'", blob->name);
@ -229,8 +223,7 @@ static bool loadWAV(Sound* sound, Blob* blob, bool decode) {
// Conversion
size_t samples = sound->frames * lovrSoundGetChannelCount(sound);
size_t bytes = sound->frames * lovrSoundGetStride(sound);
void* raw = malloc(bytes);
lovrAssert(raw, "Out of memory");
void* raw = lovrMalloc(bytes);
if (pcm && wav->sampleSize == 24) {
float* out = raw;
const uint8_t* in = (const uint8_t*) data;
@ -296,10 +289,9 @@ static bool loadMP3(Sound* sound, Blob* blob, bool decode) {
sound->read = lovrSoundReadRaw;
return true;
} else {
mp3dec_ex_t* decoder = sound->decoder = malloc(sizeof(mp3dec_ex_t));
lovrAssert(decoder, "Out of memory");
mp3dec_ex_t* decoder = sound->decoder = lovrMalloc(sizeof(mp3dec_ex_t));
if (mp3dec_ex_open_buf(sound->decoder, blob->data, blob->size, MP3D_SEEK_TO_SAMPLE)) {
free(sound->decoder);
lovrFree(sound->decoder);
lovrThrow("Could not load mp3 from '%s'", blob->name);
}
sound->format = SAMPLE_F32;
@ -314,8 +306,7 @@ static bool loadMP3(Sound* sound, Blob* blob, bool decode) {
}
Sound* lovrSoundCreateFromFile(Blob* blob, bool decode) {
Sound* sound = calloc(1, sizeof(Sound));
lovrAssert(sound, "Out of memory");
Sound* sound = lovrCalloc(sizeof(Sound));
sound->ref = 1;
if (loadOgg(sound, blob, decode)) return sound;
@ -326,8 +317,7 @@ Sound* lovrSoundCreateFromFile(Blob* blob, bool decode) {
}
Sound* lovrSoundCreateFromCallback(SoundCallback read, void *callbackMemo, SoundDestroyCallback callbackMemoDestroy, SampleFormat format, uint32_t sampleRate, ChannelLayout layout, uint32_t maxFrames) {
Sound* sound = calloc(1, sizeof(Sound));
lovrAssert(sound, "Out of memory");
Sound* sound = lovrCalloc(sizeof(Sound));
sound->ref = 1;
sound->read = read;
sound->format = format;
@ -344,10 +334,10 @@ void lovrSoundDestroy(void* ref) {
if (sound->callbackMemoDestroy) sound->callbackMemoDestroy(sound);
lovrRelease(sound->blob, lovrBlobDestroy);
if (sound->read == lovrSoundReadOgg) stb_vorbis_close(sound->decoder);
if (sound->read == lovrSoundReadMp3) mp3dec_ex_close(sound->decoder), free(sound->decoder);
if (sound->read == lovrSoundReadMp3) mp3dec_ex_close(sound->decoder), lovrFree(sound->decoder);
ma_pcm_rb_uninit(sound->stream);
free(sound->stream);
free(sound);
lovrFree(sound->stream);
lovrFree(sound);
}
Blob* lovrSoundGetBlob(Sound* sound) {

View File

@ -13,9 +13,9 @@ static struct {
void lovrVariantDestroy(Variant* variant) {
switch (variant->type) {
case TYPE_STRING: free(variant->value.string.pointer); return;
case TYPE_STRING: lovrFree(variant->value.string.pointer); return;
case TYPE_OBJECT: lovrRelease(variant->value.object.pointer, variant->value.object.destructor); return;
case TYPE_MATRIX: free(variant->value.matrix.data); return;
case TYPE_MATRIX: lovrFree(variant->value.matrix.data); return;
default: return;
}
}
@ -51,8 +51,7 @@ void lovrEventPush(Event event) {
if (event.type == EVENT_THREAD_ERROR) {
lovrRetain(event.data.thread.thread);
size_t length = strlen(event.data.thread.error);
char* copy = malloc(length + 1);
lovrAssert(copy, "Out of memory");
char* copy = lovrMalloc(length + 1);
memcpy(copy, event.data.thread.error, length);
copy[length] = '\0';
event.data.thread.error = copy;

View File

@ -310,8 +310,7 @@ void* lovrFilesystemRead(const char* p, size_t* size) {
}
*size = (size_t) bytes;
void* data = malloc(*size);
lovrAssert(data, "Out of memory");
void* data = lovrMalloc(*size);
if (archive->read(archive, &handle, data, *size, size)) {
archive->close(archive, &handle);
@ -737,8 +736,7 @@ static bool zip_open(Archive* archive, const char* path, Handle* handle) {
}
if (handle->node->compressed) {
zip_stream* stream = handle->stream = malloc(sizeof(zip_stream));
lovrAssert(stream, "Out of memory");
zip_stream* stream = handle->stream = lovrMalloc(sizeof(zip_stream));
tinfl_init(&stream->decompressor);
stream->inputCursor = 0;
stream->outputCursor = 0;
@ -752,7 +750,7 @@ static bool zip_open(Archive* archive, const char* path, Handle* handle) {
}
static bool zip_close(Archive* archive, Handle* handle) {
free(handle->stream);
lovrFree(handle->stream);
return true;
}
@ -906,8 +904,7 @@ static void zip_list(Archive* archive, const char* path, fs_list_cb callback, vo
// Archive
Archive* lovrArchiveCreate(const char* path, const char* mountpoint, const char* root) {
Archive* archive = calloc(1, sizeof(Archive));
lovrAssert(archive, "Out of memory");
Archive* archive = lovrCalloc(sizeof(Archive));
archive->ref = 1;
if (dir_init(archive, path, root)) {
@ -927,20 +924,18 @@ Archive* lovrArchiveCreate(const char* path, const char* mountpoint, const char*
archive->stat = zip_stat;
archive->list = zip_list;
} else {
free(archive);
lovrFree(archive);
return NULL;
}
if (mountpoint) {
size_t length = strlen(mountpoint);
archive->mountpoint = malloc(length + 1);
lovrAssert(archive->mountpoint, "Out of memory");
archive->mountpoint = lovrMalloc(length + 1);
archive->mountLength = normalize(mountpoint, length, archive->mountpoint);
}
archive->pathLength = strlen(path);
archive->path = malloc(archive->pathLength + 1);
lovrAssert(archive->path, "Out of memory");
archive->path = lovrMalloc(archive->pathLength + 1);
memcpy(archive->path, path, archive->pathLength + 1);
return archive;
@ -949,9 +944,9 @@ Archive* lovrArchiveCreate(const char* path, const char* mountpoint, const char*
void lovrArchiveDestroy(void* ref) {
Archive* archive = ref;
if (archive->data) zip_free(archive);
free(archive->mountpoint);
free(archive->path);
free(archive);
lovrFree(archive->mountpoint);
lovrFree(archive->path);
lovrFree(archive);
}
// File
@ -990,16 +985,14 @@ File* lovrFileCreate(const char* p, OpenMode mode, const char** error) {
}
}
File* file = calloc(1, sizeof(File));
lovrAssert(file, "Out of memory");
File* file = lovrCalloc(sizeof(File));
file->ref = 1;
file->mode = mode;
file->handle = handle;
file->archive = archive;
lovrRetain(archive);
file->path = malloc(length + 1);
lovrAssert(file->path, "Out of memory");
file->path = lovrMalloc(length + 1);
memcpy(file->path, path, length + 1);
return file;
@ -1009,8 +1002,8 @@ void lovrFileDestroy(void* ref) {
File* file = ref;
if (file->archive) file->archive->close(file->archive, &file->handle);
lovrRelease(file->archive, lovrArchiveDestroy);
free(file->path);
free(file);
lovrFree(file->path);
lovrFree(file);
}
const char* lovrFileGetPath(File* file) {

View File

@ -653,8 +653,8 @@ bool lovrGraphicsInit(GraphicsConfig* config) {
gpu_config gpu = {
.debug = config->debug,
.fnLog = onMessage,
.fnAlloc = malloc,
.fnFree = free,
.fnAlloc = lovrMalloc,
.fnFree = lovrFree,
.engineName = "LOVR",
.engineVersion = { LOVR_VERSION_MAJOR, LOVR_VERSION_MINOR, LOVR_VERSION_PATCH },
.device = &state.device,
@ -858,7 +858,7 @@ void lovrGraphicsDestroy(void) {
readback = next;
}
if (state.timestamps) gpu_tally_destroy(state.timestamps);
free(state.timestamps);
lovrFree(state.timestamps);
lovrRelease(state.window, lovrTextureDestroy);
lovrRelease(state.windowPass, lovrPassDestroy);
lovrRelease(state.defaultFont, lovrFontDestroy);
@ -877,14 +877,14 @@ void lovrGraphicsDestroy(void) {
freeBlock(&state.bufferAllocators[GPU_BUFFER_STATIC], block->view.block);
}
gpu_bundle_pool_destroy(block->bundlePool);
free(block->list);
free(block->bundlePool);
free(block->bundles);
lovrFree(block->list);
lovrFree(block->bundlePool);
lovrFree(block->bundles);
}
arr_free(&state.materialBlocks);
for (size_t i = 0; i < state.scratchTextures.length; i++) {
gpu_texture_destroy(state.scratchTextures.data[i].texture);
free(state.scratchTextures.data[i].texture);
lovrFree(state.scratchTextures.data[i].texture);
}
arr_free(&state.scratchTextures);
for (size_t i = 0; i < state.pipelineCount; i++) {
@ -896,7 +896,7 @@ void lovrGraphicsDestroy(void) {
if (state.passLookup.values[i] != MAP_NIL) {
gpu_pass* pass = (gpu_pass*) (uintptr_t) state.passLookup.values[i];
gpu_pass_destroy(pass);
free(pass);
lovrFree(pass);
}
}
map_free(&state.passLookup);
@ -905,7 +905,7 @@ void lovrGraphicsDestroy(void) {
while (block) {
gpu_buffer_destroy(block->handle);
BufferBlock* next = block->next;
free(block);
lovrFree(block);
block = next;
}
@ -913,7 +913,7 @@ void lovrGraphicsDestroy(void) {
if (current) {
gpu_buffer_destroy(current->handle);
free(current);
lovrFree(current);
}
}
for (size_t i = 0; i < state.layouts.length; i++) {
@ -921,13 +921,13 @@ void lovrGraphicsDestroy(void) {
while (pool) {
BundlePool* next = pool->next;
gpu_bundle_pool_destroy(pool->gpu);
free(pool->gpu);
free(pool->bundles);
free(pool);
lovrFree(pool->gpu);
lovrFree(pool->bundles);
lovrFree(pool);
pool = next;
}
gpu_layout_destroy(state.layouts.data[i].gpu);
free(state.layouts.data[i].gpu);
lovrFree(state.layouts.data[i].gpu);
}
arr_free(&state.layouts);
gpu_destroy();
@ -1358,8 +1358,7 @@ static void recordRenderPass(Pass* pass, gpu_stream* stream) {
if (pass->tally.buffer && pass->tally.count > 0) {
if (!pass->tally.gpu) {
pass->tally.gpu = malloc(gpu_sizeof_tally());
lovrAssert(pass->tally.gpu, "Out of memory");
pass->tally.gpu = lovrMalloc(gpu_sizeof_tally());
gpu_tally_init(pass->tally.gpu, &(gpu_tally_info) {
.type = GPU_TALLY_PIXEL,
.count = MAX_TALLIES * state.limits.renderSize[2]
@ -1666,8 +1665,7 @@ void lovrGraphicsSubmit(Pass** passes, uint32_t count) {
TimingInfo* times = NULL;
if (state.timingEnabled && count > 0) {
times = malloc(count * sizeof(TimingInfo));
lovrAssert(times, "Out of memory");
times = lovrMalloc(count * sizeof(TimingInfo));
for (uint32_t i = 0; i < count; i++) {
times[i].pass = passes[i];
@ -1680,8 +1678,7 @@ void lovrGraphicsSubmit(Pass** passes, uint32_t count) {
if (state.timestamps) {
gpu_tally_destroy(state.timestamps);
} else {
state.timestamps = malloc(gpu_sizeof_tally());
lovrAssert(state.timestamps, "Out of memory");
state.timestamps = lovrMalloc(gpu_sizeof_tally());
}
gpu_tally_info info = {
@ -1896,9 +1893,7 @@ Buffer* lovrBufferCreate(const BufferInfo* info, void** data) {
charCount = ALIGN(charCount, 8);
Buffer* buffer = calloc(1, sizeof(Buffer) + charCount + fieldCount * sizeof(DataField));
lovrAssert(buffer, "Out of memory");
Buffer* buffer = lovrCalloc(sizeof(Buffer) + charCount + fieldCount * sizeof(DataField));
buffer->ref = 1;
buffer->info = *info;
buffer->info.fieldCount = fieldCount;
@ -1980,7 +1975,7 @@ void lovrBufferDestroy(void* ref) {
if (buffer->block != allocator->current && atomic_fetch_sub(&buffer->block->ref, 1) == 1) {
freeBlock(allocator, buffer->block);
}
free(buffer);
lovrFree(buffer);
}
const BufferInfo* lovrBufferGetInfo(Buffer* buffer) {
@ -2050,9 +2045,7 @@ Texture* lovrGraphicsGetWindowTexture(void) {
width *= density;
height *= density;
state.window = calloc(1, sizeof(Texture));
lovrAssert(state.window, "Out of memory");
state.window = lovrCalloc(sizeof(Texture));
state.window->ref = 1;
state.window->gpu = NULL;
state.window->renderView = NULL;
@ -2148,8 +2141,7 @@ Texture* lovrTextureCreate(const TextureInfo* info) {
lovrCheck((info->format < FORMAT_BC1 || info->format > FORMAT_BC7) || state.features.textureBC, "%s textures are not supported on this GPU", "BC");
lovrCheck(info->format < FORMAT_ASTC_4x4 || state.features.textureASTC, "%s textures are not supported on this GPU", "ASTC");
Texture* texture = calloc(1, sizeof(Texture) + gpu_sizeof_texture());
lovrAssert(texture, "Out of memory");
Texture* texture = lovrCalloc(sizeof(Texture) + gpu_sizeof_texture());
texture->ref = 1;
texture->gpu = (gpu_texture*) (texture + 1);
texture->root = texture;
@ -2233,8 +2225,7 @@ Texture* lovrTextureCreate(const TextureInfo* info) {
.levelCount = 1
};
texture->renderView = malloc(gpu_sizeof_texture());
lovrAssert(texture->renderView, "Out of memory");
texture->renderView = lovrMalloc(gpu_sizeof_texture());
gpu_texture_init_view(texture->renderView, &view);
}
}
@ -2248,8 +2239,7 @@ Texture* lovrTextureCreate(const TextureInfo* info) {
.srgb = false
};
texture->storageView = malloc(gpu_sizeof_texture());
lovrAssert(texture->storageView, "Out of memory");
texture->storageView = lovrMalloc(gpu_sizeof_texture());
gpu_texture_init_view(texture->storageView, &view);
} else {
texture->storageView = texture->gpu;
@ -2285,8 +2275,7 @@ Texture* lovrTextureCreateView(Texture* parent, const TextureViewInfo* info) {
lovrCheck(info->levelCount == 1 || base->type != TEXTURE_3D, "Views of volume textures may only have a single mipmap level");
lovrCheck(info->layerCount % 6 == 0 || info->type != TEXTURE_CUBE, "Cubemap layer count must be a multiple of 6");
Texture* texture = calloc(1, sizeof(Texture) + gpu_sizeof_texture());
lovrAssert(texture, "Out of memory");
Texture* texture = lovrCalloc(sizeof(Texture) + gpu_sizeof_texture());
texture->ref = 1;
texture->gpu = (gpu_texture*) (texture + 1);
texture->info = *base;
@ -2330,8 +2319,7 @@ Texture* lovrTextureCreateView(Texture* parent, const TextureViewInfo* info) {
.levelCount = 1
};
texture->renderView = malloc(gpu_sizeof_texture());
lovrAssert(texture->renderView, "Out of memory");
texture->renderView = lovrMalloc(gpu_sizeof_texture());
gpu_texture_init_view(texture->renderView, &subview);
}
}
@ -2348,8 +2336,7 @@ Texture* lovrTextureCreateView(Texture* parent, const TextureViewInfo* info) {
.levelCount = info->levelCount
};
texture->storageView = malloc(gpu_sizeof_texture());
lovrAssert(texture->storageView, "Out of memory");
texture->storageView = lovrMalloc(gpu_sizeof_texture());
gpu_texture_init_view(texture->storageView, &subview);
} else {
texture->storageView = texture->gpu;
@ -2369,7 +2356,7 @@ void lovrTextureDestroy(void* ref) {
if (texture->storageView && texture->storageView != texture->gpu) gpu_texture_destroy(texture->storageView);
if (texture->gpu) gpu_texture_destroy(texture->gpu);
}
free(texture);
lovrFree(texture);
}
const TextureInfo* lovrTextureGetInfo(Texture* texture) {
@ -2535,8 +2522,7 @@ Sampler* lovrSamplerCreate(const SamplerInfo* info) {
lovrCheck(info->range[1] < 0.f || info->range[1] >= info->range[0], "Invalid Sampler mipmap range");
lovrCheck(info->anisotropy <= state.limits.anisotropy, "Sampler anisotropy (%f) exceeds anisotropy limit (%f)", info->anisotropy, state.limits.anisotropy);
Sampler* sampler = calloc(1, sizeof(Sampler) + gpu_sizeof_sampler());
lovrAssert(sampler, "Out of memory");
Sampler* sampler = lovrCalloc(sizeof(Sampler) + gpu_sizeof_sampler());
sampler->ref = 1;
sampler->gpu = (gpu_sampler*) (sampler + 1);
sampler->info = *info;
@ -2561,7 +2547,7 @@ Sampler* lovrSamplerCreate(const SamplerInfo* info) {
void lovrSamplerDestroy(void* ref) {
Sampler* sampler = ref;
gpu_sampler_destroy(sampler->gpu);
free(sampler);
lovrFree(sampler);
}
const SamplerInfo* lovrSamplerGetInfo(Sampler* sampler) {
@ -2715,8 +2701,7 @@ void lovrGraphicsCompileShader(ShaderSource* stages, ShaderSource* outputs, uint
void* words = glslang_program_SPIRV_get_ptr(program);
size_t size = glslang_program_SPIRV_get_size(program) * 4;
void* data = malloc(size);
lovrAssert(data, "Out of memory");
void* data = lovrMalloc(size);
memcpy(data, words, size);
outputs[i].stage = source->stage;
@ -2850,8 +2835,7 @@ Shader* lovrGraphicsGetDefaultShader(DefaultShader type) {
}
Shader* lovrShaderCreate(const ShaderInfo* info) {
Shader* shader = calloc(1, sizeof(Shader) + gpu_sizeof_shader());
lovrAssert(shader, "Out of memory");
Shader* shader = lovrCalloc(sizeof(Shader) + gpu_sizeof_shader());
shader->ref = 1;
shader->gpu = (gpu_shader*) (shader + 1);
shader->info = *info;
@ -2911,16 +2895,11 @@ Shader* lovrShaderCreate(const ShaderInfo* info) {
}
// Allocate memory
shader->resources = malloc(maxResources * sizeof(ShaderResource));
shader->fields = malloc(maxFields * sizeof(DataField));
shader->names = malloc(maxChars);
shader->flags = malloc(maxSpecConstants * sizeof(gpu_shader_flag));
shader->flagLookup = malloc(maxSpecConstants * sizeof(uint32_t));
lovrAssert(shader->resources, "Out of memory");
lovrAssert(shader->fields, "Out of memory");
lovrAssert(shader->names, "Out of memory");
lovrAssert(shader->flags, "Out of memory");
lovrAssert(shader->flagLookup, "Out of memory");
shader->resources = lovrMalloc(maxResources * sizeof(ShaderResource));
shader->fields = lovrMalloc(maxFields * sizeof(DataField));
shader->names = lovrMalloc(maxChars);
shader->flags = lovrMalloc(maxSpecConstants * sizeof(gpu_shader_flag));
shader->flagLookup = lovrMalloc(maxSpecConstants * sizeof(uint32_t));
// Workgroup size
if (info->type == SHADER_COMPUTE) {
@ -2936,8 +2915,7 @@ Shader* lovrShaderCreate(const ShaderInfo* info) {
// Vertex attributes
if (info->type == SHADER_GRAPHICS && spv[0].attributeCount > 0) {
shader->attributeCount = spv[0].attributeCount;
shader->attributes = malloc(shader->attributeCount * sizeof(ShaderAttribute));
lovrAssert(shader->attributes, "Out of memory");
shader->attributes = lovrMalloc(shader->attributeCount * sizeof(ShaderAttribute));
for (uint32_t i = 0; i < shader->attributeCount; i++) {
shader->attributes[i].location = spv[0].attributes[i].location;
shader->attributes[i].hash = (uint32_t) hash64(spv[0].attributes[i].name, strlen(spv[0].attributes[i].name));
@ -3240,8 +3218,7 @@ Shader* lovrShaderCreate(const ShaderInfo* info) {
}
Shader* lovrShaderClone(Shader* parent, ShaderFlag* flags, uint32_t count) {
Shader* shader = calloc(1, sizeof(Shader) + gpu_sizeof_shader());
lovrAssert(shader, "Out of memory");
Shader* shader = lovrCalloc(sizeof(Shader) + gpu_sizeof_shader());
shader->ref = 1;
lovrRetain(parent);
shader->parent = parent;
@ -3264,9 +3241,8 @@ Shader* lovrShaderClone(Shader* parent, ShaderFlag* flags, uint32_t count) {
shader->uniforms = parent->uniforms;
shader->fields = parent->fields;
shader->names = parent->names;
shader->flags = malloc(shader->flagCount * sizeof(gpu_shader_flag));
shader->flagLookup = malloc(shader->flagCount * sizeof(uint32_t));
lovrAssert(shader->flags && shader->flagLookup, "Out of memory");
shader->flags = lovrMalloc(shader->flagCount * sizeof(gpu_shader_flag));
shader->flagLookup = lovrMalloc(shader->flagCount * sizeof(uint32_t));
memcpy(shader->flags, parent->flags, shader->flagCount * sizeof(gpu_shader_flag));
memcpy(shader->flagLookup, parent->flagLookup, shader->flagCount * sizeof(uint32_t));
lovrShaderInit(shader);
@ -3279,14 +3255,14 @@ void lovrShaderDestroy(void* ref) {
lovrRelease(shader->parent, lovrShaderDestroy);
} else {
gpu_shader_destroy(shader->gpu);
free(shader->attributes);
free(shader->resources);
free(shader->fields);
free(shader->names);
lovrFree(shader->attributes);
lovrFree(shader->resources);
lovrFree(shader->fields);
lovrFree(shader->names);
}
free(shader->flags);
free(shader->flagLookup);
free(shader);
lovrFree(shader->flags);
lovrFree(shader->flagLookup);
lovrFree(shader);
}
const ShaderInfo* lovrShaderGetInfo(Shader* shader) {
@ -3357,10 +3333,9 @@ Material* lovrMaterialCreate(const MaterialInfo* info) {
lovrAssert(state.materialBlocks.length < UINT16_MAX, "Out of memory");
state.materialBlock = state.materialBlocks.length++;
block = &state.materialBlocks.data[state.materialBlock];
block->list = malloc(MATERIALS_PER_BLOCK * sizeof(Material));
block->bundlePool = malloc(gpu_sizeof_bundle_pool());
block->bundles = malloc(MATERIALS_PER_BLOCK * gpu_sizeof_bundle());
lovrAssert(block->list && block->bundlePool && block->bundles, "Out of memory");
block->list = lovrMalloc(MATERIALS_PER_BLOCK * sizeof(Material));
block->bundlePool = lovrMalloc(gpu_sizeof_bundle_pool());
block->bundles = lovrMalloc(MATERIALS_PER_BLOCK * gpu_sizeof_bundle());
for (uint32_t i = 0; i < MATERIALS_PER_BLOCK; i++) {
block->list[i].next = i + 1;
@ -3488,8 +3463,7 @@ Font* lovrGraphicsGetDefaultFont(void) {
}
Font* lovrFontCreate(const FontInfo* info) {
Font* font = calloc(1, sizeof(Font));
lovrAssert(font, "Out of memory");
Font* font = lovrCalloc(sizeof(Font));
font->ref = 1;
font->info = *info;
lovrRetain(info->rasterizer);
@ -3524,7 +3498,7 @@ void lovrFontDestroy(void* ref) {
arr_free(&font->glyphs);
map_free(&font->glyphLookup);
map_free(&font->kerning);
free(font);
lovrFree(font);
}
const FontInfo* lovrFontGetInfo(Font* font) {
@ -3980,8 +3954,7 @@ Mesh* lovrMeshCreate(const MeshInfo* info, void** vertices) {
lovrCheck(attribute->type < TYPE_INDEX16 || attribute->type > TYPE_INDEX32, "Mesh attributes can not use index types");
}
Mesh* mesh = calloc(1, sizeof(Mesh));
lovrAssert(mesh, "Out of memory");
Mesh* mesh = lovrCalloc(sizeof(Mesh));
mesh->ref = 1;
mesh->vertexBuffer = buffer;
mesh->storage = info->storage;
@ -3990,8 +3963,7 @@ Mesh* lovrMeshCreate(const MeshInfo* info, void** vertices) {
if (info->vertexBuffer) {
lovrRetain(info->vertexBuffer);
} else if (mesh->storage == MESH_CPU) {
mesh->vertices = vertices ? malloc(buffer->info.size) : calloc(1, buffer->info.size);
lovrAssert(mesh->vertices, "Out of memory");
mesh->vertices = vertices ? lovrMalloc(buffer->info.size) : lovrCalloc(buffer->info.size);
if (vertices) {
*vertices = mesh->vertices;
@ -4011,9 +3983,9 @@ void lovrMeshDestroy(void* ref) {
lovrRelease(mesh->vertexBuffer, lovrBufferDestroy);
lovrRelease(mesh->indexBuffer, lovrBufferDestroy);
lovrRelease(mesh->material, lovrMaterialDestroy);
free(mesh->vertices);
free(mesh->indices);
free(mesh);
lovrFree(mesh->vertices);
lovrFree(mesh->indices);
lovrFree(mesh);
}
const DataField* lovrMeshGetVertexFormat(Mesh* mesh) {
@ -4143,8 +4115,7 @@ void lovrMeshGetTriangles(Mesh* mesh, float** vertices, uint32_t** indices, uint
lovrCheck(position, "Mesh has no VertexPosition attribute with vec3 type");
const DataField* format = lovrMeshGetVertexFormat(mesh);
*vertices = malloc(format->length * 3 * sizeof(float));
lovrAssert(*vertices, "Out of memory");
*vertices = lovrMalloc(format->length * 3 * sizeof(float));
for (uint32_t i = 0; i < format->length; i++) {
vec3_init(*vertices, position);
@ -4154,8 +4125,7 @@ void lovrMeshGetTriangles(Mesh* mesh, float** vertices, uint32_t** indices, uint
if (mesh->indexCount > 0) {
*indexCount = mesh->indexCount;
*indices = malloc(*indexCount * sizeof(uint32_t));
lovrAssert(*indices, "Out of memory");
*indices = lovrMalloc(*indexCount * sizeof(uint32_t));
if (mesh->indexBuffer->info.format[1].type == TYPE_U16 || mesh->indexBuffer->info.format[1].type == TYPE_INDEX16) {
for (uint32_t i = 0; i < mesh->indexCount; i++) {
*indices[i] = (uint32_t) ((uint16_t*) mesh->indices)[i];
@ -4165,8 +4135,7 @@ void lovrMeshGetTriangles(Mesh* mesh, float** vertices, uint32_t** indices, uint
}
} else {
*indexCount = format->length;
*indices = malloc(*indexCount * sizeof(uint32_t));
lovrAssert(*indices, "Out of memory");
*indices = lovrMalloc(*indexCount * sizeof(uint32_t));
lovrCheck(format->length >= 3 && format->length % 3 == 0, "Mesh vertex count must be divisible by 3");
for (uint32_t i = 0; i < format->length; i++) {
**indices = i;
@ -4283,8 +4252,7 @@ static void lovrMeshFlush(Mesh* mesh) {
Model* lovrModelCreate(const ModelInfo* info) {
ModelData* data = info->data;
Model* model = calloc(1, sizeof(Model));
lovrAssert(model, "Out of memory");
Model* model = lovrCalloc(sizeof(Model));
model->ref = 1;
model->info = *info;
lovrRetain(info->data);
@ -4295,9 +4263,8 @@ Model* lovrModelCreate(const ModelInfo* info) {
// Materials and Textures
if (info->materials) {
model->textures = calloc(data->imageCount, sizeof(Texture*));
model->materials = malloc(data->materialCount * sizeof(Material*));
lovrAssert(model->textures && model->materials, "Out of memory");
model->textures = lovrCalloc(data->imageCount * sizeof(Texture*));
model->materials = lovrMalloc(data->materialCount * sizeof(Material*));
for (uint32_t i = 0; i < data->materialCount; i++) {
MaterialInfo material;
ModelMaterial* properties = &data->materials[i];
@ -4439,9 +4406,8 @@ Model* lovrModelCreate(const ModelInfo* info) {
qsort(primitiveOrder, data->primitiveCount, sizeof(uint64_t), u64cmp);
// Draws
model->draws = calloc(data->primitiveCount, sizeof(DrawInfo));
model->boundingBoxes = malloc(data->primitiveCount * 6 * sizeof(float));
lovrAssert(model->draws && model->boundingBoxes, "Out of memory");
model->draws = lovrCalloc(data->primitiveCount * sizeof(DrawInfo));
model->boundingBoxes = lovrMalloc(data->primitiveCount * 6 * sizeof(float));
for (uint32_t i = 0, vertexCursor = 0, indexCursor = 0; i < data->primitiveCount; i++) {
ModelPrimitive* primitive = &data->primitives[primitiveOrder[i] & ~0u];
ModelAttribute* position = primitive->attributes[ATTR_POSITION];
@ -4515,9 +4481,8 @@ Model* lovrModelCreate(const ModelInfo* info) {
}
}
model->blendGroups = malloc(model->blendGroupCount * sizeof(BlendGroup));
model->blendShapeWeights = malloc(data->blendShapeCount * sizeof(float));
lovrAssert(model->blendGroups && model->blendShapeWeights, "Out of memory");
model->blendGroups = lovrMalloc(model->blendGroupCount * sizeof(BlendGroup));
model->blendShapeWeights = lovrMalloc(data->blendShapeCount * sizeof(float));
BlendGroup* group = model->blendGroups;
@ -4552,9 +4517,8 @@ Model* lovrModelCreate(const ModelInfo* info) {
}
// Transforms
model->localTransforms = malloc(sizeof(NodeTransform) * data->nodeCount);
model->globalTransforms = malloc(16 * sizeof(float) * data->nodeCount);
lovrAssert(model->localTransforms && model->globalTransforms, "Out of memory");
model->localTransforms = lovrMalloc(sizeof(NodeTransform) * data->nodeCount);
model->globalTransforms = lovrMalloc(16 * sizeof(float) * data->nodeCount);
lovrModelResetNodeTransforms(model);
tempPop(&state.allocator, stack);
@ -4564,8 +4528,7 @@ Model* lovrModelCreate(const ModelInfo* info) {
Model* lovrModelClone(Model* parent) {
ModelData* data = parent->info.data;
Model* model = calloc(1, sizeof(Model));
lovrAssert(model, "Out of memory");
Model* model = lovrCalloc(sizeof(Model));
model->ref = 1;
model->parent = parent;
model->info = parent->info;
@ -4602,21 +4565,18 @@ Model* lovrModelClone(Model* parent) {
}, 1);
}
model->draws = malloc(data->primitiveCount * sizeof(DrawInfo));
lovrAssert(model->draws, "Out of memory");
model->draws = lovrMalloc(data->primitiveCount * sizeof(DrawInfo));
for (uint32_t i = 0; i < data->primitiveCount; i++) {
model->draws[i] = parent->draws[i];
model->draws[i].vertex.buffer = model->vertexBuffer;
}
model->blendShapeWeights = malloc(data->blendShapeCount * sizeof(float));
lovrAssert(model->blendShapeWeights, "Out of memory");
model->blendShapeWeights = lovrMalloc(data->blendShapeCount * sizeof(float));
lovrModelResetBlendShapes(model);
model->localTransforms = malloc(sizeof(NodeTransform) * data->nodeCount);
model->globalTransforms = malloc(16 * sizeof(float) * data->nodeCount);
lovrAssert(model->localTransforms && model->globalTransforms, "Out of memory");
model->localTransforms = lovrMalloc(sizeof(NodeTransform) * data->nodeCount);
model->globalTransforms = lovrMalloc(16 * sizeof(float) * data->nodeCount);
lovrModelResetNodeTransforms(model);
return model;
@ -4627,12 +4587,12 @@ void lovrModelDestroy(void* ref) {
if (model->parent) {
lovrRelease(model->parent, lovrModelDestroy);
lovrRelease(model->vertexBuffer, lovrBufferDestroy);
free(model->localTransforms);
free(model->globalTransforms);
free(model->blendShapeWeights);
free(model->meshes);
free(model->draws);
free(model);
lovrFree(model->localTransforms);
lovrFree(model->globalTransforms);
lovrFree(model->blendShapeWeights);
lovrFree(model->meshes);
lovrFree(model->draws);
lovrFree(model);
return;
}
ModelData* data = model->info.data;
@ -4643,8 +4603,8 @@ void lovrModelDestroy(void* ref) {
for (uint32_t i = 0; i < data->imageCount; i++) {
lovrRelease(model->textures[i], lovrTextureDestroy);
}
free(model->materials);
free(model->textures);
lovrFree(model->materials);
lovrFree(model->textures);
}
lovrRelease(model->rawVertexBuffer, lovrBufferDestroy);
lovrRelease(model->vertexBuffer, lovrBufferDestroy);
@ -4652,14 +4612,14 @@ void lovrModelDestroy(void* ref) {
lovrRelease(model->blendBuffer, lovrBufferDestroy);
lovrRelease(model->skinBuffer, lovrBufferDestroy);
lovrRelease(model->info.data, lovrModelDataDestroy);
free(model->localTransforms);
free(model->globalTransforms);
free(model->boundingBoxes);
free(model->blendShapeWeights);
free(model->blendGroups);
free(model->meshes);
free(model->draws);
free(model);
lovrFree(model->localTransforms);
lovrFree(model->globalTransforms);
lovrFree(model->boundingBoxes);
lovrFree(model->blendShapeWeights);
lovrFree(model->blendGroups);
lovrFree(model->meshes);
lovrFree(model->draws);
lovrFree(model);
}
const ModelInfo* lovrModelGetInfo(Model* model) {
@ -4854,8 +4814,7 @@ Mesh* lovrModelGetMesh(Model* model, uint32_t index) {
lovrCheck(index < data->primitiveCount, "Invalid mesh index '%d' (Model has %d mesh%s)", index + 1, data->primitiveCount, data->primitiveCount == 1 ? "" : "es");
if (!model->meshes) {
model->meshes = calloc(data->primitiveCount, sizeof(Mesh*));
lovrAssert(model->meshes, "Out of memory");
model->meshes = lovrCalloc(data->primitiveCount * sizeof(Mesh*));
}
if (!model->meshes[index]) {
@ -5026,8 +4985,7 @@ static void lovrModelAnimateVertices(Model* model) {
static Readback* lovrReadbackCreate(ReadbackType type) {
beginFrame();
Readback* readback = calloc(1, sizeof(Readback));
lovrAssert(readback, "Out of memory");
Readback* readback = lovrCalloc(sizeof(Readback));
readback->ref = 1;
readback->tick = state.tick;
readback->type = type;
@ -5045,8 +5003,7 @@ Readback* lovrReadbackCreateBuffer(Buffer* buffer, uint32_t offset, uint32_t ext
lovrCheck(!buffer->info.format || extent % buffer->info.format->stride == 0, "Readback size must be a multiple of Buffer's stride");
Readback* readback = lovrReadbackCreate(READBACK_BUFFER);
readback->buffer = buffer;
void* data = malloc(extent);
lovrAssert(data, "Out of memory");
void* data = lovrMalloc(extent);
readback->blob = lovrBlobCreate(data, extent, "Readback");
readback->view = getBuffer(GPU_BUFFER_DOWNLOAD, extent, 4);
lovrRetain(buffer);
@ -5097,11 +5054,11 @@ void lovrReadbackDestroy(void* ref) {
for (uint32_t i = 0; i < readback->count; i++) {
lovrRelease(readback->times[i].pass, lovrPassDestroy);
}
free(readback->times);
lovrFree(readback->times);
break;
default: break;
}
free(readback);
lovrFree(readback);
}
bool lovrReadbackIsComplete(Readback* readback) {
@ -5220,8 +5177,7 @@ Pass* lovrGraphicsGetWindowPass(void) {
}
Pass* lovrPassCreate(void) {
Pass* pass = calloc(1, sizeof(Pass));
lovrAssert(pass, "Out of memory");
Pass* pass = lovrCalloc(sizeof(Pass));
pass->ref = 1;
pass->allocator.limit = 1 << 28;
@ -5251,7 +5207,7 @@ void lovrPassDestroy(void* ref) {
freeBlock(&state.bufferAllocators[GPU_BUFFER_STREAM], pass->buffers.current);
}
os_vm_free(pass->allocator.memory, pass->allocator.limit);
free(pass);
lovrFree(pass);
}
void lovrPassReset(Pass* pass) {
@ -7348,8 +7304,7 @@ static BufferBlock* getBlock(gpu_buffer_type type, uint32_t size) {
return block;
}
block = malloc(sizeof(BufferBlock) + gpu_sizeof_buffer());
lovrAssert(block, "Out of memory");
block = lovrMalloc(sizeof(BufferBlock) + gpu_sizeof_buffer());
block->handle = (gpu_buffer*) (block + 1);
block->size = MAX(size, 1 << 22);
block->next = NULL;
@ -7507,8 +7462,7 @@ static gpu_pass* getPass(Canvas* canvas) {
uint64_t value = map_get(&state.passLookup, hash);
if (value == MAP_NIL) {
gpu_pass* pass = malloc(gpu_sizeof_pass());
lovrAssert(pass, "Out of memory");
gpu_pass* pass = lovrMalloc(gpu_sizeof_pass());
gpu_pass_init(pass, &info);
map_set(&state.passLookup, hash, (uint64_t) (uintptr_t) pass);
return pass;
@ -7532,8 +7486,7 @@ static size_t getLayout(gpu_slot* slots, uint32_t count) {
.count = count
};
gpu_layout* handle = malloc(gpu_sizeof_layout());
lovrAssert(handle, "Out of memory");
gpu_layout* handle = lovrMalloc(gpu_sizeof_layout());
gpu_layout_init(handle, &info);
Layout layout = {
@ -7574,10 +7527,9 @@ static gpu_bundle* getBundle(size_t layoutIndex, gpu_binding* bindings, uint32_t
}
// If no pool was available, make a new one
pool = malloc(sizeof(BundlePool));
gpu_bundle_pool* gpu = malloc(gpu_sizeof_bundle_pool());
gpu_bundle* bundles = malloc(POOL_SIZE * gpu_sizeof_bundle());
lovrAssert(pool && gpu && bundles, "Out of memory");
pool = lovrMalloc(sizeof(BundlePool));
gpu_bundle_pool* gpu = lovrMalloc(gpu_sizeof_bundle_pool());
gpu_bundle* bundles = lovrMalloc(POOL_SIZE * gpu_sizeof_bundle());
pool->gpu = gpu;
pool->bundles = bundles;
pool->cursor = 1;
@ -7624,8 +7576,7 @@ static gpu_texture* getScratchTexture(gpu_stream* stream, Canvas* canvas, Textur
} else {
arr_expand(&state.scratchTextures, 1);
scratch = &state.scratchTextures.data[state.scratchTextures.length++];
scratch->texture = calloc(1, gpu_sizeof_texture());
lovrAssert(scratch->texture, "Out of memory");
scratch->texture = lovrCalloc(gpu_sizeof_texture());
}
gpu_texture_info info = {
@ -8020,11 +7971,10 @@ static void onMessage(void* context, const char* message, bool severe) {
if (!state.defaultTexture) { // Hacky way to determine if initialization has completed
const char* format = "This program requires a graphics card with support for Vulkan 1.1, but no device was found or it failed to initialize properly. The error message was:\n\n%s";
size_t size = snprintf(NULL, 0, format, message) + 1;
char* string = malloc(size);
lovrAssert(string, "Out of memory");
char* string = lovrMalloc(size);
snprintf(string, size, format, message);
os_window_message_box(string);
free(string);
lovrFree(string);
exit(1);
}
#endif

View File

@ -581,8 +581,7 @@ static bool openxr_init(HeadsetConfig* config) {
XR_INIT(result, "Failed to query extensions");
}
XrExtensionProperties* extensionProperties = calloc(extensionCount, sizeof(*extensionProperties));
lovrAssert(extensionProperties, "Out of memory");
XrExtensionProperties* extensionProperties = lovrCalloc(extensionCount * sizeof(*extensionProperties));
for (uint32_t i = 0; i < extensionCount; i++) extensionProperties[i].type = XR_TYPE_EXTENSION_PROPERTIES;
xrEnumerateInstanceExtensionProperties(NULL, extensionCount, &extensionCount, extensionProperties);
@ -631,7 +630,7 @@ static bool openxr_init(HeadsetConfig* config) {
}
}
free(extensionProperties);
lovrFree(extensionProperties);
#ifdef __ANDROID__
XrInstanceCreateInfoAndroidKHR androidInfo = {
@ -725,8 +724,7 @@ static bool openxr_init(HeadsetConfig* config) {
// Blend modes
XR_INIT(xrEnumerateEnvironmentBlendModes(state.instance, state.system, XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO, 0, &state.blendModeCount, NULL), "Failed to query blend modes");
state.blendModes = malloc(state.blendModeCount * sizeof(XrEnvironmentBlendMode));
lovrAssert(state.blendModes, "Out of memory");
state.blendModes = lovrMalloc(state.blendModeCount * sizeof(XrEnvironmentBlendMode));
XR_INIT(xrEnumerateEnvironmentBlendModes(state.instance, state.system, XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO, state.blendModeCount, &state.blendModeCount, state.blendModes), "Failed to query blend modes");
state.blendMode = state.blendModes[0];
}
@ -1468,8 +1466,7 @@ static void openxr_start(void) {
if (state.features.refreshRate) {
XR(xrEnumerateDisplayRefreshRatesFB(state.session, 0, &state.refreshRateCount, NULL), "Failed to query refresh rates");
state.refreshRates = malloc(state.refreshRateCount * sizeof(float));
lovrAssert(state.refreshRates, "Out of memory");
state.refreshRates = lovrMalloc(state.refreshRateCount * sizeof(float));
XR(xrEnumerateDisplayRefreshRatesFB(state.session, state.refreshRateCount, &state.refreshRateCount, state.refreshRates), "Failed to query refresh rates");
}
}
@ -2090,8 +2087,7 @@ static ModelData* openxr_newModelDataFB(XrHandTrackerEXT tracker, bool animated)
totalSize += sizes[9] = ALIGN(jointCount * 16 * sizeof(float), alignment);
// Allocate
char* meshData = malloc(totalSize);
if (!meshData) return NULL;
char* meshData = lovrMalloc(totalSize);
// Write offseted pointers to the mesh struct, to be filled in by the second call
size_t offset = 0;
@ -2110,12 +2106,11 @@ static ModelData* openxr_newModelDataFB(XrHandTrackerEXT tracker, bool animated)
// Populate the data
result = xrGetHandMeshFB(tracker, &mesh);
if (XR_FAILED(result)) {
free(meshData);
lovrFree(meshData);
return NULL;
}
ModelData* model = calloc(1, sizeof(ModelData));
lovrAssert(model, "Out of memory");
ModelData* model = lovrCalloc(sizeof(ModelData));
model->ref = 1;
model->blobCount = 1;
model->bufferCount = 6;
@ -2127,8 +2122,7 @@ static ModelData* openxr_newModelDataFB(XrHandTrackerEXT tracker, bool animated)
model->nodeCount = 2 + jointCount;
lovrModelDataAllocate(model);
model->metadata = malloc(sizeof(XrHandTrackerEXT));
lovrAssert(model->metadata, "Out of memory");
model->metadata = lovrMalloc(sizeof(XrHandTrackerEXT));
*((XrHandTrackerEXT*)model->metadata) = tracker;
model->metadataSize = sizeof(XrHandTrackerEXT);
model->metadataType = META_HANDTRACKING_FB;
@ -2271,11 +2265,10 @@ static ModelData* openxr_newModelDataMSFT(XrControllerModelKeyMSFT modelKey, boo
return NULL;
}
unsigned char* modelData = malloc(size);
if (!modelData) return NULL;
unsigned char* modelData = lovrMalloc(size);
if (XR_FAILED(xrLoadControllerModelMSFT(state.session, modelKey, size, &size, modelData))) {
free(modelData);
lovrFree(modelData);
return NULL;
}
@ -2298,11 +2291,10 @@ static ModelData* openxr_newModelDataMSFT(XrControllerModelKeyMSFT modelKey, boo
return false;
}
free(model->metadata);
lovrFree(model->metadata);
model->metadataType = META_CONTROLLER_MSFT;
model->metadataSize = sizeof(MetadataControllerMSFT) + sizeof(uint32_t) * properties.nodeCountOutput;
model->metadata = malloc(model->metadataSize);
lovrAssert(model->metadata, "Out of memory");
model->metadata = lovrMalloc(model->metadataSize);
MetadataControllerMSFT* metadata = model->metadata;
metadata->modelKey = modelKey;
@ -2451,8 +2443,7 @@ static bool openxr_animate(Model* model) {
}
static Layer* openxr_newLayer(uint32_t width, uint32_t height) {
Layer* layer = calloc(1, sizeof(Layer));
lovrAssert(layer, "Out of memory");
Layer* layer = lovrCalloc(sizeof(Layer));
layer->ref = 1;
layer->width = width;
layer->height = height;
@ -2488,7 +2479,7 @@ static void openxr_destroyLayer(void* ref) {
Layer* layer = ref;
swapchain_destroy(&layer->swapchain);
lovrRelease(layer->pass, lovrPassDestroy);
free(layer);
lovrFree(layer);
}
static Layer** openxr_getLayers(uint32_t* count) {

View File

@ -272,7 +272,7 @@ static bool simulator_animate(struct Model* model) {
}
static Layer* simulator_newLayer(uint32_t width, uint32_t height) {
Layer* layer = calloc(1, sizeof(Layer));
Layer* layer = lovrCalloc(sizeof(Layer));
layer->ref = 1;
layer->textureWidth = width;
layer->textureWeight = height;
@ -281,7 +281,7 @@ static Layer* simulator_newLayer(uint32_t width, uint32_t height) {
static void simulator_destroyLayer(void* ref) {
Layer* layer = ref;
free(layer);
lovrFree(layer);
}
static Layer** simulator_getLayers(uint32_t* count) {

View File

@ -129,8 +129,7 @@ static void evaluate(float* restrict P, size_t n, float t, vec4 p) {
}
Curve* lovrCurveCreate(void) {
Curve* curve = calloc(1, sizeof(Curve));
lovrAssert(curve, "Out of memory");
Curve* curve = lovrCalloc(sizeof(Curve));
curve->ref = 1;
arr_init(&curve->points, arr_alloc);
arr_reserve(&curve->points, 16);
@ -140,7 +139,7 @@ Curve* lovrCurveCreate(void) {
void lovrCurveDestroy(void* ref) {
Curve* curve = ref;
arr_free(&curve->points);
free(curve);
lovrFree(curve);
}
void lovrCurveEvaluate(Curve* curve, float t, vec4 p) {
@ -227,8 +226,7 @@ static const size_t vectorComponents[] = {
};
Pool* lovrPoolCreate(void) {
Pool* pool = calloc(1, sizeof(Pool));
lovrAssert(pool, "Out of memory");
Pool* pool = lovrCalloc(sizeof(Pool));
pool->ref = 1;
pool->data = os_vm_init((1 << 24) * sizeof(float));
lovrPoolGrow(pool, 1 << 12);
@ -238,7 +236,7 @@ Pool* lovrPoolCreate(void) {
void lovrPoolDestroy(void* ref) {
Pool* pool = ref;
os_vm_free(pool->data, (1 << 24) * sizeof(float));
free(pool);
lovrFree(pool);
}
void lovrPoolGrow(Pool* pool, size_t count) {
@ -300,8 +298,7 @@ static uint64_t wangHash64(uint64_t key) {
// Use an 'Xorshift*' variant, as shown here: http://xorshift.di.unimi.it
RandomGenerator* lovrRandomGeneratorCreate(void) {
RandomGenerator* generator = calloc(1, sizeof(RandomGenerator));
lovrAssert(generator, "Out of memory");
RandomGenerator* generator = lovrCalloc(sizeof(RandomGenerator));
generator->ref = 1;
Seed seed = { .b32 = { .lo = 0xCBBF7A44, .hi = 0x0139408D } };
lovrRandomGeneratorSetSeed(generator, seed);
@ -310,7 +307,7 @@ RandomGenerator* lovrRandomGeneratorCreate(void) {
}
void lovrRandomGeneratorDestroy(void* ref) {
free(ref);
lovrFree(ref);
}
Seed lovrRandomGeneratorGetSeed(RandomGenerator* generator) {

View File

@ -110,8 +110,7 @@ void lovrPhysicsDestroy(void) {
}
World* lovrWorldCreate(float xg, float yg, float zg, bool allowSleep, const char** tags, uint32_t tagCount) {
World* world = calloc(1, sizeof(World));
lovrAssert(world, "Out of memory");
World* world = lovrCalloc(sizeof(World));
world->collision_steps = 1;
world->ref = 1;
@ -149,7 +148,7 @@ World* lovrWorldCreate(float xg, float yg, float zg, bool allowSleep, const char
lovrWorldSetGravity(world, xg, yg, zg);
for (uint32_t i = 0; i < tagCount; i++) {
size_t size = strlen(tags[i]) + 1;
world->tags[i] = malloc(size);
world->tags[i] = lovrMalloc(size);
memcpy(world->tags[i], tags[i], size);
}
return world;
@ -160,12 +159,12 @@ void lovrWorldDestroy(void* ref) {
lovrWorldDestroyData(world);
// todo: free up overlaps/contacts (once their allocation is implemented)
for (uint32_t i = 0; i < MAX_TAGS - 1 && world->tags[i]; i++) {
free(world->tags[i]);
lovrFree(world->tags[i]);
}
if (world->tags[15]) {
free(world->tags[15]);
lovrFree(world->tags[15]);
}
free(world);
lovrFree(world);
}
void lovrWorldDestroyData(World* world) {
@ -394,8 +393,7 @@ bool lovrWorldIsCollisionEnabledBetween(World* world, const char* tag1, const ch
Collider* lovrColliderCreate(World* world, float x, float y, float z) {
// todo: crashes when too many are added
Collider* collider = calloc(1, sizeof(Collider));
lovrAssert(collider, "Out of memory");
Collider* collider = lovrCalloc(sizeof(Collider));
collider->ref = 1;
collider->world = world;
collider->tag = UNTAGGED;
@ -437,7 +435,7 @@ void lovrColliderDestroy(void* ref) {
lovrColliderDestroyData(collider);
arr_free(&collider->shapes);
arr_free(&collider->joints);
free(collider);
lovrFree(collider);
}
void lovrColliderDestroyData(Collider* collider) {
@ -862,7 +860,7 @@ void lovrColliderGetAABB(Collider* collider, float aabb[6]) {
void lovrShapeDestroy(void* ref) {
Shape* shape = ref;
lovrShapeDestroyData(shape);
free(shape);
lovrFree(shape);
}
void lovrShapeDestroyData(Shape* shape) {
@ -939,8 +937,7 @@ void lovrShapeGetAABB(Shape* shape, float aabb[6]) {
SphereShape* lovrSphereShapeCreate(float radius) {
lovrCheck(radius > 0.f, "SphereShape radius must be positive");
SphereShape* sphere = calloc(1, sizeof(SphereShape));
lovrAssert(sphere, "Out of memory");
SphereShape* sphere = lovrCalloc(sizeof(SphereShape));
sphere->ref = 1;
sphere->type = SHAPE_SPHERE;
sphere->shape = (JPH_Shape *) JPH_SphereShape_Create(radius);
@ -957,8 +954,7 @@ void lovrSphereShapeSetRadius(SphereShape* sphere, float radius) {
}
BoxShape* lovrBoxShapeCreate(float w, float h, float d) {
BoxShape* box = calloc(1, sizeof(BoxShape));
lovrAssert(box, "Out of memory");
BoxShape* box = lovrCalloc(sizeof(BoxShape));
box->ref = 1;
box->type = SHAPE_BOX;
const JPH_Vec3 halfExtent = {
@ -985,8 +981,7 @@ void lovrBoxShapeSetDimensions(BoxShape* box, float w, float h, float d) {
CapsuleShape* lovrCapsuleShapeCreate(float radius, float length) {
lovrCheck(radius > 0.f && length > 0.f, "CapsuleShape dimensions must be positive");
CapsuleShape* capsule = calloc(1, sizeof(CapsuleShape));
lovrAssert(capsule, "Out of memory");
CapsuleShape* capsule = lovrCalloc(sizeof(CapsuleShape));
capsule->ref = 1;
capsule->type = SHAPE_CAPSULE;
capsule->shape = (JPH_Shape *) JPH_CapsuleShape_Create(length / 2, radius);
@ -1013,8 +1008,7 @@ void lovrCapsuleShapeSetLength(CapsuleShape* capsule, float length) {
CylinderShape* lovrCylinderShapeCreate(float radius, float length) {
lovrCheck(radius > 0.f && length > 0.f, "CylinderShape dimensions must be positive");
CylinderShape* Cylinder = calloc(1, sizeof(CylinderShape));
lovrAssert(Cylinder, "Out of memory");
CylinderShape* Cylinder = lovrCalloc(sizeof(CylinderShape));
Cylinder->ref = 1;
Cylinder->type = SHAPE_CYLINDER;
Cylinder->shape = (JPH_Shape *) JPH_CylinderShape_Create(length / 2.f, radius);
@ -1040,13 +1034,12 @@ void lovrCylinderShapeSetLength(CylinderShape* cylinder, float length) {
}
MeshShape* lovrMeshShapeCreate(int vertexCount, float vertices[], int indexCount, uint32_t indices[]) {
MeshShape* mesh = calloc(1, sizeof(MeshShape));
lovrAssert(mesh, "Out of memory");
MeshShape* mesh = lovrCalloc(sizeof(MeshShape));
mesh->ref = 1;
mesh->type = SHAPE_MESH;
int triangleCount = indexCount / 3;
JPH_IndexedTriangle * indexedTriangles = malloc(triangleCount * sizeof(JPH_IndexedTriangle));
JPH_IndexedTriangle * indexedTriangles = lovrMalloc(triangleCount * sizeof(JPH_IndexedTriangle));
for (int i = 0; i < triangleCount; i++) {
indexedTriangles[i].i1 = indices[i * 3 + 0];
indexedTriangles[i].i2 = indices[i * 3 + 1];
@ -1065,8 +1058,7 @@ MeshShape* lovrMeshShapeCreate(int vertexCount, float vertices[], int indexCount
TerrainShape* lovrTerrainShapeCreate(float* vertices, uint32_t widthSamples, uint32_t depthSamples, float horizontalScale, float verticalScale) {
lovrCheck(widthSamples == depthSamples, "Jolt needs terrain width and depth to be the same");
TerrainShape* terrain = calloc(1, sizeof(TerrainShape));
lovrAssert(terrain, "Out of memory");
TerrainShape* terrain = lovrCalloc(sizeof(TerrainShape));
terrain->ref = 1;
terrain->type = SHAPE_TERRAIN;
const JPH_Vec3 offset = {
@ -1127,7 +1119,7 @@ void lovrJointGetAnchors(Joint* joint, float anchor1[3], float anchor2[3]) {
void lovrJointDestroy(void* ref) {
Joint* joint = ref;
lovrJointDestroyData(joint);
free(joint);
lovrFree(joint);
}
void lovrJointDestroyData(Joint* joint) {
@ -1198,8 +1190,7 @@ void lovrJointSetEnabled(Joint* joint, bool enable) {
BallJoint* lovrBallJointCreate(Collider* a, Collider* b, float anchor[3]) {
lovrCheck(a->world == b->world, "Joint bodies must exist in same World");
BallJoint* joint = calloc(1, sizeof(BallJoint));
lovrAssert(joint, "Out of memory");
BallJoint* joint = lovrCalloc(sizeof(BallJoint));
joint->ref = 1;
joint->type = JOINT_BALL;
@ -1256,8 +1247,7 @@ void lovrBallJointSetTightness(Joint* joint, float tightness) {
DistanceJoint* lovrDistanceJointCreate(Collider* a, Collider* b, float anchor1[3], float anchor2[3]) {
lovrCheck(a->world == b->world, "Joint bodies must exist in same World");
DistanceJoint* joint = calloc(1, sizeof(DistanceJoint));
lovrAssert(joint, "Out of memory");
DistanceJoint* joint = lovrCalloc(sizeof(DistanceJoint));
joint->ref = 1;
joint->type = JOINT_DISTANCE;
@ -1325,8 +1315,7 @@ void lovrDistanceJointSetTightness(Joint* joint, float tightness) {
HingeJoint* lovrHingeJointCreate(Collider* a, Collider* b, float anchor[3], float axis[3]) {
lovrCheck(a->world == b->world, "Joint bodies must exist in the same World");
HingeJoint* joint = calloc(1, sizeof(HingeJoint));
lovrAssert(joint, "Out of memory");
HingeJoint* joint = lovrCalloc(sizeof(HingeJoint));
joint->ref = 1;
joint->type = JOINT_HINGE;
@ -1419,8 +1408,7 @@ void lovrHingeJointSetUpperLimit(HingeJoint* joint, float limit) {
SliderJoint* lovrSliderJointCreate(Collider* a, Collider* b, float axis[3]) {
lovrCheck(a->world == b->world, "Joint bodies must exist in the same World");
SliderJoint* joint = calloc(1, sizeof(SliderJoint));
lovrAssert(joint, "Out of memory");
SliderJoint* joint = lovrCalloc(sizeof(SliderJoint));
joint->ref = 1;
joint->type = JOINT_SLIDER;

View File

@ -158,8 +158,7 @@ void lovrPhysicsDestroy(void) {
}
World* lovrWorldCreate(float xg, float yg, float zg, bool allowSleep, const char** tags, uint32_t tagCount) {
World* world = calloc(1, sizeof(World));
lovrAssert(world, "Out of memory");
World* world = lovrCalloc(sizeof(World));
world->ref = 1;
world->id = dWorldCreate();
world->space = dHashSpaceCreate(0);
@ -170,7 +169,7 @@ World* lovrWorldCreate(float xg, float yg, float zg, bool allowSleep, const char
lovrWorldSetSleepingAllowed(world, allowSleep);
for (uint32_t i = 0; i < tagCount; i++) {
size_t size = strlen(tags[i]) + 1;
world->tags[i] = malloc(size);
world->tags[i] = lovrMalloc(size);
memcpy(world->tags[i], tags[i], size);
}
memset(world->masks, 0xff, sizeof(world->masks));
@ -182,9 +181,9 @@ void lovrWorldDestroy(void* ref) {
lovrWorldDestroyData(world);
arr_free(&world->overlaps);
for (uint32_t i = 0; i < MAX_TAGS && world->tags[i]; i++) {
free(world->tags[i]);
lovrFree(world->tags[i]);
}
free(world);
lovrFree(world);
}
void lovrWorldDestroyData(World* world) {
@ -441,8 +440,7 @@ bool lovrWorldIsCollisionEnabledBetween(World* world, const char* tag1, const ch
}
Collider* lovrColliderCreate(World* world, float x, float y, float z) {
Collider* collider = calloc(1, sizeof(Collider));
lovrAssert(collider, "Out of memory");
Collider* collider = lovrCalloc(sizeof(Collider));
collider->ref = 1;
collider->body = dBodyCreate(world->id);
collider->world = world;
@ -474,7 +472,7 @@ void lovrColliderDestroy(void* ref) {
lovrColliderDestroyData(collider);
arr_free(&collider->shapes);
arr_free(&collider->joints);
free(collider);
lovrFree(collider);
}
void lovrColliderDestroyData(Collider* collider) {
@ -854,7 +852,7 @@ void lovrColliderGetAABB(Collider* collider, float aabb[6]) {
void lovrShapeDestroy(void* ref) {
Shape* shape = ref;
lovrShapeDestroyData(shape);
free(shape);
lovrFree(shape);
}
void lovrShapeDestroyData(Shape* shape) {
@ -862,8 +860,8 @@ void lovrShapeDestroyData(Shape* shape) {
if (shape->type == SHAPE_MESH) {
dTriMeshDataID dataID = dGeomTriMeshGetData(shape->id);
dGeomTriMeshDataDestroy(dataID);
free(shape->vertices);
free(shape->indices);
lovrFree(shape->vertices);
lovrFree(shape->indices);
} else if (shape->type == SHAPE_TERRAIN) {
dHeightfieldDataID dataID = dGeomHeightfieldGetHeightfieldData(shape->id);
dGeomHeightfieldDataDestroy(dataID);
@ -1003,8 +1001,7 @@ void lovrShapeGetAABB(Shape* shape, float aabb[6]) {
SphereShape* lovrSphereShapeCreate(float radius) {
lovrCheck(radius > 0.f, "SphereShape radius must be positive");
SphereShape* sphere = calloc(1, sizeof(SphereShape));
lovrAssert(sphere, "Out of memory");
SphereShape* sphere = lovrCalloc(sizeof(SphereShape));
sphere->ref = 1;
sphere->type = SHAPE_SPHERE;
sphere->id = dCreateSphere(0, radius);
@ -1022,8 +1019,7 @@ void lovrSphereShapeSetRadius(SphereShape* sphere, float radius) {
}
BoxShape* lovrBoxShapeCreate(float w, float h, float d) {
BoxShape* box = calloc(1, sizeof(BoxShape));
lovrAssert(box, "Out of memory");
BoxShape* box = lovrCalloc(sizeof(BoxShape));
box->ref = 1;
box->type = SHAPE_BOX;
box->id = dCreateBox(0, w, h, d);
@ -1046,8 +1042,7 @@ void lovrBoxShapeSetDimensions(BoxShape* box, float w, float h, float d) {
CapsuleShape* lovrCapsuleShapeCreate(float radius, float length) {
lovrCheck(radius > 0.f && length > 0.f, "CapsuleShape dimensions must be positive");
CapsuleShape* capsule = calloc(1, sizeof(CapsuleShape));
lovrAssert(capsule, "Out of memory");
CapsuleShape* capsule = lovrCalloc(sizeof(CapsuleShape));
capsule->ref = 1;
capsule->type = SHAPE_CAPSULE;
capsule->id = dCreateCapsule(0, radius, length);
@ -1079,8 +1074,7 @@ void lovrCapsuleShapeSetLength(CapsuleShape* capsule, float length) {
CylinderShape* lovrCylinderShapeCreate(float radius, float length) {
lovrCheck(radius > 0.f && length > 0.f, "CylinderShape dimensions must be positive");
CylinderShape* cylinder = calloc(1, sizeof(CylinderShape));
lovrAssert(cylinder, "Out of memory");
CylinderShape* cylinder = lovrCalloc(sizeof(CylinderShape));
cylinder->ref = 1;
cylinder->type = SHAPE_CYLINDER;
cylinder->id = dCreateCylinder(0, radius, length);
@ -1111,8 +1105,7 @@ void lovrCylinderShapeSetLength(CylinderShape* cylinder, float length) {
}
MeshShape* lovrMeshShapeCreate(int vertexCount, float* vertices, int indexCount, dTriIndex* indices) {
MeshShape* mesh = calloc(1, sizeof(MeshShape));
lovrAssert(mesh, "Out of memory");
MeshShape* mesh = lovrCalloc(sizeof(MeshShape));
mesh->ref = 1;
dTriMeshDataID dataID = dGeomTriMeshDataCreate();
dGeomTriMeshDataBuildSingle(dataID, vertices, 3 * sizeof(float), vertexCount, indices, indexCount, 3 * sizeof(dTriIndex));
@ -1127,8 +1120,7 @@ MeshShape* lovrMeshShapeCreate(int vertexCount, float* vertices, int indexCount,
TerrainShape* lovrTerrainShapeCreate(float* vertices, uint32_t widthSamples, uint32_t depthSamples, float horizontalScale, float verticalScale) {
const float thickness = 10.f;
TerrainShape* terrain = calloc(1, sizeof(TerrainShape));
lovrAssert(terrain, "Out of memory");
TerrainShape* terrain = lovrCalloc(sizeof(TerrainShape));
terrain->ref = 1;
dHeightfieldDataID dataID = dGeomHeightfieldDataCreate();
dGeomHeightfieldDataBuildSingle(dataID, vertices, 1, horizontalScale, horizontalScale,
@ -1142,7 +1134,7 @@ TerrainShape* lovrTerrainShapeCreate(float* vertices, uint32_t widthSamples, uin
void lovrJointDestroy(void* ref) {
Joint* joint = ref;
lovrJointDestroyData(joint);
free(joint);
lovrFree(joint);
}
void lovrJointDestroyData(Joint* joint) {
@ -1191,8 +1183,7 @@ void lovrJointSetEnabled(Joint* joint, bool enable) {
BallJoint* lovrBallJointCreate(Collider* a, Collider* b, float anchor[3]) {
lovrCheck(a->world == b->world, "Joint bodies must exist in same World");
BallJoint* joint = calloc(1, sizeof(BallJoint));
lovrAssert(joint, "Out of memory");
BallJoint* joint = lovrCalloc(sizeof(BallJoint));
joint->ref = 1;
joint->type = JOINT_BALL;
joint->id = dJointCreateBall(a->world->id, 0);
@ -1237,8 +1228,7 @@ void lovrBallJointSetTightness(Joint* joint, float tightness) {
DistanceJoint* lovrDistanceJointCreate(Collider* a, Collider* b, float anchor1[3], float anchor2[3]) {
lovrCheck(a->world == b->world, "Joint bodies must exist in same World");
DistanceJoint* joint = calloc(1, sizeof(DistanceJoint));
lovrAssert(joint, "Out of memory");
DistanceJoint* joint = lovrCalloc(sizeof(DistanceJoint));
joint->ref = 1;
joint->type = JOINT_DISTANCE;
joint->id = dJointCreateDBall(a->world->id, 0);
@ -1292,8 +1282,7 @@ void lovrDistanceJointSetTightness(Joint* joint, float tightness) {
HingeJoint* lovrHingeJointCreate(Collider* a, Collider* b, float anchor[3], float axis[3]) {
lovrCheck(a->world == b->world, "Joint bodies must exist in same World");
HingeJoint* joint = calloc(1, sizeof(HingeJoint));
lovrAssert(joint, "Out of memory");
HingeJoint* joint = lovrCalloc(sizeof(HingeJoint));
joint->ref = 1;
joint->type = JOINT_HINGE;
joint->id = dJointCreateHinge(a->world->id, 0);
@ -1355,8 +1344,7 @@ void lovrHingeJointSetUpperLimit(HingeJoint* joint, float limit) {
SliderJoint* lovrSliderJointCreate(Collider* a, Collider* b, float axis[3]) {
lovrCheck(a->world == b->world, "Joint bodies must exist in the same world");
SliderJoint* joint = calloc(1, sizeof(SliderJoint));
lovrAssert(joint, "Out of memory");
SliderJoint* joint = lovrCalloc(sizeof(SliderJoint));
joint->ref = 1;
joint->type = JOINT_SLIDER;
joint->id = dJointCreateSlider(a->world->id, 0);

View File

@ -110,8 +110,7 @@ static int threadFunction(void* data) {
}
Thread* lovrThreadCreate(ThreadFunction* function, Blob* body) {
Thread* thread = calloc(1, sizeof(Thread));
lovrAssert(thread, "Out of memory");
Thread* thread = lovrCalloc(sizeof(Thread));
thread->ref = 1;
thread->body = body;
thread->function = function;
@ -125,8 +124,8 @@ void lovrThreadDestroy(void* ref) {
mtx_destroy(&thread->lock);
if (thread->handle) thrd_detach(thread->handle);
lovrRelease(thread->body, lovrBlobDestroy);
free(thread->error);
free(thread);
lovrFree(thread->error);
lovrFree(thread);
}
void lovrThreadStart(Thread* thread, Variant* arguments, uint32_t argumentCount) {
@ -136,7 +135,7 @@ void lovrThreadStart(Thread* thread, Variant* arguments, uint32_t argumentCount)
return;
}
free(thread->error);
lovrFree(thread->error);
thread->error = NULL;
lovrCheck(argumentCount <= MAX_THREAD_ARGUMENTS, "Too many Thread arguments (max is %d)", MAX_THREAD_ARGUMENTS);
@ -170,8 +169,7 @@ const char* lovrThreadGetError(Thread* thread) {
// Channel
Channel* lovrChannelCreate(uint64_t hash) {
Channel* channel = calloc(1, sizeof(Channel));
lovrAssert(channel, "Out of memory");
Channel* channel = lovrCalloc(sizeof(Channel));
channel->ref = 1;
arr_init(&channel->messages, arr_alloc);
mtx_init(&channel->lock, mtx_plain);
@ -186,7 +184,7 @@ void lovrChannelDestroy(void* ref) {
arr_free(&channel->messages);
mtx_destroy(&channel->lock);
cnd_destroy(&channel->cond);
free(channel);
lovrFree(channel);
}
bool lovrChannelPush(Channel* channel, Variant* variant, double timeout, uint64_t* id) {

View File

@ -2,6 +2,30 @@
#include <string.h>
#include <stdlib.h>
#include <stdatomic.h>
#include <stdio.h>
// Allocation
void* lovrMalloc(size_t size) {
void* data = malloc(size);
if (!data) fprintf(stderr, "Out of memory"), abort();
return data;
}
void* lovrCalloc(size_t size) {
void* data = calloc(1, size);
if (!data) fprintf(stderr, "Out of memory"), abort();
return data;
}
void* lovrRealloc(void* old, size_t size) {
void* data = realloc(old, size);
if (!data) fprintf(stderr, "Out of memory"), abort();
return data;
}
void lovrFree(void* data) {
free(data);
}
// Error handling
static LOVR_THREAD_LOCAL errorFn* lovrErrorCallback;

View File

@ -33,6 +33,12 @@
#define CHECK_SIZEOF(T) int(*_o)[sizeof(T)]=1
#define BREAK() __asm("int $3")
// Allocation
void* lovrMalloc(size_t size);
void* lovrCalloc(size_t size);
void* lovrRealloc(void* data, size_t size);
void lovrFree(void* data);
// Error handling
typedef void errorFn(void*, const char*, va_list);
void lovrSetErrorCallback(errorFn* callback, void* userdata);