#include #include #include #include #include "miniz.h" #include "ubox_debug.h" #include "ubox_assets.h" #define EXT "pak" static char *base = NULL; static uint8_t has_zip = 0; static mz_zip_archive zip; uint8_t ubox_assets_init(const char *dirname) { char buff[256]; base = (char *)calloc(strlen(dirname) + 1, 1); if (!base) return 0; strcpy(base, dirname); UBOX_DEBUG_LOG("%s: resources base\n", base); snprintf(buff, 255, "%s." EXT, base); memset(&zip, 0, sizeof(zip)); if (mz_zip_reader_init_file(&zip, buff, 0)) has_zip = 1; UBOX_DEBUG_LOG("%s: open %d\n", buff, has_zip); return 1; } uint8_t ubox_assets_read(const char *name, uint8_t **data, size_t *data_size) { char buff[256]; FILE *fd; /* check directory first */ snprintf(buff, 255, "%s/%s", base, name); fd = fopen(buff, "rb"); if (fd) { UBOX_DEBUG_LOG("%s: file resource\n", buff); fseek(fd, 0, SEEK_END); *data_size = ftell(fd); (*data) = (uint8_t *)calloc(*data_size, 1); if (!(*data)) goto error_close; fseek(fd, 0, SEEK_SET); if (fread(*data, 1, *data_size, fd) == *data_size) { UBOX_DEBUG_LOG("%s: %li bytes\n", buff, *data_size); return 1; } free(*data); error_close: (*data) = NULL; *data_size = 0; fclose(fd); } /* then check the archive if open */ if (has_zip) { *data = mz_zip_reader_extract_file_to_heap(&zip, name, data_size, 0); if (*data) { UBOX_DEBUG_LOG("%s: " EXT " resource, %li bytes\n", buff, *data_size); return 1; } } return 0; } void ubox_assets_free() { if (base) { free(base); base = NULL; } if (has_zip) { mz_zip_reader_end(&zip); has_zip = 0; } }