aboutsummaryrefslogtreecommitdiff
path: root/src/assets.c
diff options
context:
space:
mode:
authorJuan J. Martinez <jjm@usebox.net>2023-08-28 15:16:12 +0100
committerJuan J. Martinez <jjm@usebox.net>2023-08-28 15:30:25 +0100
commite35cff6d299a07d9b34f303717083a9299a37e82 (patch)
tree7204099ad4978dfc67e04bc11df29d0f366af851 /src/assets.c
downloaduboxlib-dos-e35cff6d299a07d9b34f303717083a9299a37e82.tar.gz
uboxlib-dos-e35cff6d299a07d9b34f303717083a9299a37e82.zip
Initial import
Diffstat (limited to 'src/assets.c')
-rw-r--r--src/assets.c98
1 files changed, 98 insertions, 0 deletions
diff --git a/src/assets.c b/src/assets.c
new file mode 100644
index 0000000..cfeeb20
--- /dev/null
+++ b/src/assets.c
@@ -0,0 +1,98 @@
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#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, char **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) = (char *)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;
+ }
+}