aboutsummaryrefslogtreecommitdiff
path: root/src/assets.c
blob: 870b3083faba809aaa7d70b690aa94315751f705 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#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, 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);
            fclose(fd);
            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;
    }
}