aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authornathansmithsmith <nathansmith7@mailfence.com>2023-11-08 12:12:29 -0700
committernathansmithsmith <nathansmith7@mailfence.com>2023-11-08 12:12:29 -0700
commitac7470ce5d680caa7fb53c235aea10cba45e1836 (patch)
tree4eeb6912414ac9280cf8c1fad267040b0ada2e98
parent10a0fb1c52a50b44bd2df064c977a3a15146facf (diff)
rres asset loading working
-rw-r--r--CMakeLists.txt2
-rw-r--r--assets/assets.rresbin0 -> 10362055 bytes
-rw-r--r--include/external/qoi.h671
-rw-r--r--include/rres-raylib.h1094
-rw-r--r--include/rres.h1094
-rw-r--r--src/assets.c131
-rw-r--r--src/implementations.c6
7 files changed, 2979 insertions, 19 deletions
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 991753a..16d2099 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -15,6 +15,8 @@ add_executable(${PROJECT_NAME} ${SRC_FILES})
target_include_directories(${PROJECT_NAME} PUBLIC include src)
target_link_libraries(${PROJECT_NAME} raylib m)
+file(COPY assets/assets.rres DESTINATION ${CMAKE_BINARY_DIR})
+
# Checks if OSX and links appropriate frameworks (Only required on MacOS)
if (APPLE)
target_link_libraries(${PROJECT_NAME} "-framework IOKit")
diff --git a/assets/assets.rres b/assets/assets.rres
new file mode 100644
index 0000000..ef9f06a
--- /dev/null
+++ b/assets/assets.rres
Binary files differ
diff --git a/include/external/qoi.h b/include/external/qoi.h
new file mode 100644
index 0000000..988f9ed
--- /dev/null
+++ b/include/external/qoi.h
@@ -0,0 +1,671 @@
+/*
+
+QOI - The "Quite OK Image" format for fast, lossless image compression
+
+Dominic Szablewski - https://phoboslab.org
+
+
+-- LICENSE: The MIT License(MIT)
+
+Copyright(c) 2021 Dominic Szablewski
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files(the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies
+of the Software, and to permit persons to whom the Software is furnished to do
+so, subject to the following conditions :
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+
+-- About
+
+QOI encodes and decodes images in a lossless format. Compared to stb_image and
+stb_image_write QOI offers 20x-50x faster encoding, 3x-4x faster decoding and
+20% better compression.
+
+
+-- Synopsis
+
+// Define `QOI_IMPLEMENTATION` in *one* C/C++ file before including this
+// library to create the implementation.
+
+#define QOI_IMPLEMENTATION
+#include "qoi.h"
+
+// Encode and store an RGBA buffer to the file system. The qoi_desc describes
+// the input pixel data.
+qoi_write("image_new.qoi", rgba_pixels, &(qoi_desc){
+ .width = 1920,
+ .height = 1080,
+ .channels = 4,
+ .colorspace = QOI_SRGB
+});
+
+// Load and decode a QOI image from the file system into a 32bbp RGBA buffer.
+// The qoi_desc struct will be filled with the width, height, number of channels
+// and colorspace read from the file header.
+qoi_desc desc;
+void *rgba_pixels = qoi_read("image.qoi", &desc, 4);
+
+
+
+-- Documentation
+
+This library provides the following functions;
+- qoi_read -- read and decode a QOI file
+- qoi_decode -- decode the raw bytes of a QOI image from memory
+- qoi_write -- encode and write a QOI file
+- qoi_encode -- encode an rgba buffer into a QOI image in memory
+
+See the function declaration below for the signature and more information.
+
+If you don't want/need the qoi_read and qoi_write functions, you can define
+QOI_NO_STDIO before including this library.
+
+This library uses malloc() and free(). To supply your own malloc implementation
+you can define QOI_MALLOC and QOI_FREE before including this library.
+
+This library uses memset() to zero-initialize the index. To supply your own
+implementation you can define QOI_ZEROARR before including this library.
+
+
+-- Data Format
+
+A QOI file has a 14 byte header, followed by any number of data "chunks" and an
+8-byte end marker.
+
+struct qoi_header_t {
+ char magic[4]; // magic bytes "qoif"
+ uint32_t width; // image width in pixels (BE)
+ uint32_t height; // image height in pixels (BE)
+ uint8_t channels; // 3 = RGB, 4 = RGBA
+ uint8_t colorspace; // 0 = sRGB with linear alpha, 1 = all channels linear
+};
+
+Images are encoded row by row, left to right, top to bottom. The decoder and
+encoder start with {r: 0, g: 0, b: 0, a: 255} as the previous pixel value. An
+image is complete when all pixels specified by width * height have been covered.
+
+Pixels are encoded as
+ - a run of the previous pixel
+ - an index into an array of previously seen pixels
+ - a difference to the previous pixel value in r,g,b
+ - full r,g,b or r,g,b,a values
+
+The color channels are assumed to not be premultiplied with the alpha channel
+("un-premultiplied alpha").
+
+A running array[64] (zero-initialized) of previously seen pixel values is
+maintained by the encoder and decoder. Each pixel that is seen by the encoder
+and decoder is put into this array at the position formed by a hash function of
+the color value. In the encoder, if the pixel value at the index matches the
+current pixel, this index position is written to the stream as QOI_OP_INDEX.
+The hash function for the index is:
+
+ index_position = (r * 3 + g * 5 + b * 7 + a * 11) % 64
+
+Each chunk starts with a 2- or 8-bit tag, followed by a number of data bits. The
+bit length of chunks is divisible by 8 - i.e. all chunks are byte aligned. All
+values encoded in these data bits have the most significant bit on the left.
+
+The 8-bit tags have precedence over the 2-bit tags. A decoder must check for the
+presence of an 8-bit tag first.
+
+The byte stream's end is marked with 7 0x00 bytes followed a single 0x01 byte.
+
+
+The possible chunks are:
+
+
+.- QOI_OP_INDEX ----------.
+| Byte[0] |
+| 7 6 5 4 3 2 1 0 |
+|-------+-----------------|
+| 0 0 | index |
+`-------------------------`
+2-bit tag b00
+6-bit index into the color index array: 0..63
+
+A valid encoder must not issue 2 or more consecutive QOI_OP_INDEX chunks to the
+same index. QOI_OP_RUN should be used instead.
+
+
+.- QOI_OP_DIFF -----------.
+| Byte[0] |
+| 7 6 5 4 3 2 1 0 |
+|-------+-----+-----+-----|
+| 0 1 | dr | dg | db |
+`-------------------------`
+2-bit tag b01
+2-bit red channel difference from the previous pixel between -2..1
+2-bit green channel difference from the previous pixel between -2..1
+2-bit blue channel difference from the previous pixel between -2..1
+
+The difference to the current channel values are using a wraparound operation,
+so "1 - 2" will result in 255, while "255 + 1" will result in 0.
+
+Values are stored as unsigned integers with a bias of 2. E.g. -2 is stored as
+0 (b00). 1 is stored as 3 (b11).
+
+The alpha value remains unchanged from the previous pixel.
+
+
+.- QOI_OP_LUMA -------------------------------------.
+| Byte[0] | Byte[1] |
+| 7 6 5 4 3 2 1 0 | 7 6 5 4 3 2 1 0 |
+|-------+-----------------+-------------+-----------|
+| 1 0 | green diff | dr - dg | db - dg |
+`---------------------------------------------------`
+2-bit tag b10
+6-bit green channel difference from the previous pixel -32..31
+4-bit red channel difference minus green channel difference -8..7
+4-bit blue channel difference minus green channel difference -8..7
+
+The green channel is used to indicate the general direction of change and is
+encoded in 6 bits. The red and blue channels (dr and db) base their diffs off
+of the green channel difference and are encoded in 4 bits. I.e.:
+ dr_dg = (cur_px.r - prev_px.r) - (cur_px.g - prev_px.g)
+ db_dg = (cur_px.b - prev_px.b) - (cur_px.g - prev_px.g)
+
+The difference to the current channel values are using a wraparound operation,
+so "10 - 13" will result in 253, while "250 + 7" will result in 1.
+
+Values are stored as unsigned integers with a bias of 32 for the green channel
+and a bias of 8 for the red and blue channel.
+
+The alpha value remains unchanged from the previous pixel.
+
+
+.- QOI_OP_RUN ------------.
+| Byte[0] |
+| 7 6 5 4 3 2 1 0 |
+|-------+-----------------|
+| 1 1 | run |
+`-------------------------`
+2-bit tag b11
+6-bit run-length repeating the previous pixel: 1..62
+
+The run-length is stored with a bias of -1. Note that the run-lengths 63 and 64
+(b111110 and b111111) are illegal as they are occupied by the QOI_OP_RGB and
+QOI_OP_RGBA tags.
+
+
+.- QOI_OP_RGB ------------------------------------------.
+| Byte[0] | Byte[1] | Byte[2] | Byte[3] |
+| 7 6 5 4 3 2 1 0 | 7 .. 0 | 7 .. 0 | 7 .. 0 |
+|-------------------------+---------+---------+---------|
+| 1 1 1 1 1 1 1 0 | red | green | blue |
+`-------------------------------------------------------`
+8-bit tag b11111110
+8-bit red channel value
+8-bit green channel value
+8-bit blue channel value
+
+The alpha value remains unchanged from the previous pixel.
+
+
+.- QOI_OP_RGBA ---------------------------------------------------.
+| Byte[0] | Byte[1] | Byte[2] | Byte[3] | Byte[4] |
+| 7 6 5 4 3 2 1 0 | 7 .. 0 | 7 .. 0 | 7 .. 0 | 7 .. 0 |
+|-------------------------+---------+---------+---------+---------|
+| 1 1 1 1 1 1 1 1 | red | green | blue | alpha |
+`-----------------------------------------------------------------`
+8-bit tag b11111111
+8-bit red channel value
+8-bit green channel value
+8-bit blue channel value
+8-bit alpha channel value
+
+*/
+
+
+/* -----------------------------------------------------------------------------
+Header - Public functions */
+
+#ifndef QOI_H
+#define QOI_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* A pointer to a qoi_desc struct has to be supplied to all of qoi's functions.
+It describes either the input format (for qoi_write and qoi_encode), or is
+filled with the description read from the file header (for qoi_read and
+qoi_decode).
+
+The colorspace in this qoi_desc is an enum where
+ 0 = sRGB, i.e. gamma scaled RGB channels and a linear alpha channel
+ 1 = all channels are linear
+You may use the constants QOI_SRGB or QOI_LINEAR. The colorspace is purely
+informative. It will be saved to the file header, but does not affect
+how chunks are en-/decoded. */
+
+#define QOI_SRGB 0
+#define QOI_LINEAR 1
+
+typedef struct {
+ unsigned int width;
+ unsigned int height;
+ unsigned char channels;
+ unsigned char colorspace;
+} qoi_desc;
+
+#ifndef QOI_NO_STDIO
+
+/* Encode raw RGB or RGBA pixels into a QOI image and write it to the file
+system. The qoi_desc struct must be filled with the image width, height,
+number of channels (3 = RGB, 4 = RGBA) and the colorspace.
+
+The function returns 0 on failure (invalid parameters, or fopen or malloc
+failed) or the number of bytes written on success. */
+
+int qoi_write(const char *filename, const void *data, const qoi_desc *desc);
+
+
+/* Read and decode a QOI image from the file system. If channels is 0, the
+number of channels from the file header is used. If channels is 3 or 4 the
+output format will be forced into this number of channels.
+
+The function either returns NULL on failure (invalid data, or malloc or fopen
+failed) or a pointer to the decoded pixels. On success, the qoi_desc struct
+will be filled with the description from the file header.
+
+The returned pixel data should be free()d after use. */
+
+void *qoi_read(const char *filename, qoi_desc *desc, int channels);
+
+#endif /* QOI_NO_STDIO */
+
+
+/* Encode raw RGB or RGBA pixels into a QOI image in memory.
+
+The function either returns NULL on failure (invalid parameters or malloc
+failed) or a pointer to the encoded data on success. On success the out_len
+is set to the size in bytes of the encoded data.
+
+The returned qoi data should be free()d after use. */
+
+void *qoi_encode(const void *data, const qoi_desc *desc, int *out_len);
+
+
+/* Decode a QOI image from memory.
+
+The function either returns NULL on failure (invalid parameters or malloc
+failed) or a pointer to the decoded pixels. On success, the qoi_desc struct
+is filled with the description from the file header.
+
+The returned pixel data should be free()d after use. */
+
+void *qoi_decode(const void *data, int size, qoi_desc *desc, int channels);
+
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* QOI_H */
+
+
+/* -----------------------------------------------------------------------------
+Implementation */
+
+#ifdef QOI_IMPLEMENTATION
+#include <stdlib.h>
+#include <string.h>
+
+#ifndef QOI_MALLOC
+ #define QOI_MALLOC(sz) malloc(sz)
+ #define QOI_FREE(p) free(p)
+#endif
+#ifndef QOI_ZEROARR
+ #define QOI_ZEROARR(a) memset((a),0,sizeof(a))
+#endif
+
+#define QOI_OP_INDEX 0x00 /* 00xxxxxx */
+#define QOI_OP_DIFF 0x40 /* 01xxxxxx */
+#define QOI_OP_LUMA 0x80 /* 10xxxxxx */
+#define QOI_OP_RUN 0xc0 /* 11xxxxxx */
+#define QOI_OP_RGB 0xfe /* 11111110 */
+#define QOI_OP_RGBA 0xff /* 11111111 */
+
+#define QOI_MASK_2 0xc0 /* 11000000 */
+
+#define QOI_COLOR_HASH(C) (C.rgba.r*3 + C.rgba.g*5 + C.rgba.b*7 + C.rgba.a*11)
+#define QOI_MAGIC \
+ (((unsigned int)'q') << 24 | ((unsigned int)'o') << 16 | \
+ ((unsigned int)'i') << 8 | ((unsigned int)'f'))
+#define QOI_HEADER_SIZE 14
+
+/* 2GB is the max file size that this implementation can safely handle. We guard
+against anything larger than that, assuming the worst case with 5 bytes per
+pixel, rounded down to a nice clean value. 400 million pixels ought to be
+enough for anybody. */
+#define QOI_PIXELS_MAX ((unsigned int)400000000)
+
+typedef union {
+ struct { unsigned char r, g, b, a; } rgba;
+ unsigned int v;
+} qoi_rgba_t;
+
+static const unsigned char qoi_padding[8] = {0,0,0,0,0,0,0,1};
+
+static void qoi_write_32(unsigned char *bytes, int *p, unsigned int v) {
+ bytes[(*p)++] = (0xff000000 & v) >> 24;
+ bytes[(*p)++] = (0x00ff0000 & v) >> 16;
+ bytes[(*p)++] = (0x0000ff00 & v) >> 8;
+ bytes[(*p)++] = (0x000000ff & v);
+}
+
+static unsigned int qoi_read_32(const unsigned char *bytes, int *p) {
+ unsigned int a = bytes[(*p)++];
+ unsigned int b = bytes[(*p)++];
+ unsigned int c = bytes[(*p)++];
+ unsigned int d = bytes[(*p)++];
+ return a << 24 | b << 16 | c << 8 | d;
+}
+
+void *qoi_encode(const void *data, const qoi_desc *desc, int *out_len) {
+ int i, max_size, p, run;
+ int px_len, px_end, px_pos, channels;
+ unsigned char *bytes;
+ const unsigned char *pixels;
+ qoi_rgba_t index[64];
+ qoi_rgba_t px, px_prev;
+
+ if (
+ data == NULL || out_len == NULL || desc == NULL ||
+ desc->width == 0 || desc->height == 0 ||
+ desc->channels < 3 || desc->channels > 4 ||
+ desc->colorspace > 1 ||
+ desc->height >= QOI_PIXELS_MAX / desc->width
+ ) {
+ return NULL;
+ }
+
+ max_size =
+ desc->width * desc->height * (desc->channels + 1) +
+ QOI_HEADER_SIZE + sizeof(qoi_padding);
+
+ p = 0;
+ bytes = (unsigned char *) QOI_MALLOC(max_size);
+ if (!bytes) {
+ return NULL;
+ }
+
+ qoi_write_32(bytes, &p, QOI_MAGIC);
+ qoi_write_32(bytes, &p, desc->width);
+ qoi_write_32(bytes, &p, desc->height);
+ bytes[p++] = desc->channels;
+ bytes[p++] = desc->colorspace;
+
+
+ pixels = (const unsigned char *)data;
+
+ QOI_ZEROARR(index);
+
+ run = 0;
+ px_prev.rgba.r = 0;
+ px_prev.rgba.g = 0;
+ px_prev.rgba.b = 0;
+ px_prev.rgba.a = 255;
+ px = px_prev;
+
+ px_len = desc->width * desc->height * desc->channels;
+ px_end = px_len - desc->channels;
+ channels = desc->channels;
+
+ for (px_pos = 0; px_pos < px_len; px_pos += channels) {
+ if (channels == 4) {
+ px = *(qoi_rgba_t *)(pixels + px_pos);
+ }
+ else {
+ px.rgba.r = pixels[px_pos + 0];
+ px.rgba.g = pixels[px_pos + 1];
+ px.rgba.b = pixels[px_pos + 2];
+ }
+
+ if (px.v == px_prev.v) {
+ run++;
+ if (run == 62 || px_pos == px_end) {
+ bytes[p++] = QOI_OP_RUN | (run - 1);
+ run = 0;
+ }
+ }
+ else {
+ int index_pos;
+
+ if (run > 0) {
+ bytes[p++] = QOI_OP_RUN | (run - 1);
+ run = 0;
+ }
+
+ index_pos = QOI_COLOR_HASH(px) % 64;
+
+ if (index[index_pos].v == px.v) {
+ bytes[p++] = QOI_OP_INDEX | index_pos;
+ }
+ else {
+ index[index_pos] = px;
+
+ if (px.rgba.a == px_prev.rgba.a) {
+ signed char vr = px.rgba.r - px_prev.rgba.r;
+ signed char vg = px.rgba.g - px_prev.rgba.g;
+ signed char vb = px.rgba.b - px_prev.rgba.b;
+
+ signed char vg_r = vr - vg;
+ signed char vg_b = vb - vg;
+
+ if (
+ vr > -3 && vr < 2 &&
+ vg > -3 && vg < 2 &&
+ vb > -3 && vb < 2
+ ) {
+ bytes[p++] = QOI_OP_DIFF | (vr + 2) << 4 | (vg + 2) << 2 | (vb + 2);
+ }
+ else if (
+ vg_r > -9 && vg_r < 8 &&
+ vg > -33 && vg < 32 &&
+ vg_b > -9 && vg_b < 8
+ ) {
+ bytes[p++] = QOI_OP_LUMA | (vg + 32);
+ bytes[p++] = (vg_r + 8) << 4 | (vg_b + 8);
+ }
+ else {
+ bytes[p++] = QOI_OP_RGB;
+ bytes[p++] = px.rgba.r;
+ bytes[p++] = px.rgba.g;
+ bytes[p++] = px.rgba.b;
+ }
+ }
+ else {
+ bytes[p++] = QOI_OP_RGBA;
+ bytes[p++] = px.rgba.r;
+ bytes[p++] = px.rgba.g;
+ bytes[p++] = px.rgba.b;
+ bytes[p++] = px.rgba.a;
+ }
+ }
+ }
+ px_prev = px;
+ }
+
+ for (i = 0; i < (int)sizeof(qoi_padding); i++) {
+ bytes[p++] = qoi_padding[i];
+ }
+
+ *out_len = p;
+ return bytes;
+}
+
+void *qoi_decode(const void *data, int size, qoi_desc *desc, int channels) {
+ const unsigned char *bytes;
+ unsigned int header_magic;
+ unsigned char *pixels;
+ qoi_rgba_t index[64];
+ qoi_rgba_t px;
+ int px_len, chunks_len, px_pos;
+ int p = 0, run = 0;
+
+ if (
+ data == NULL || desc == NULL ||
+ (channels != 0 && channels != 3 && channels != 4) ||
+ size < QOI_HEADER_SIZE + (int)sizeof(qoi_padding)
+ ) {
+ return NULL;
+ }
+
+ bytes = (const unsigned char *)data;
+
+ header_magic = qoi_read_32(bytes, &p);
+ desc->width = qoi_read_32(bytes, &p);
+ desc->height = qoi_read_32(bytes, &p);
+ desc->channels = bytes[p++];
+ desc->colorspace = bytes[p++];
+
+ if (
+ desc->width == 0 || desc->height == 0 ||
+ desc->channels < 3 || desc->channels > 4 ||
+ desc->colorspace > 1 ||
+ header_magic != QOI_MAGIC ||
+ desc->height >= QOI_PIXELS_MAX / desc->width
+ ) {
+ return NULL;
+ }
+
+ if (channels == 0) {
+ channels = desc->channels;
+ }
+
+ px_len = desc->width * desc->height * channels;
+ pixels = (unsigned char *) QOI_MALLOC(px_len);
+ if (!pixels) {
+ return NULL;
+ }
+
+ QOI_ZEROARR(index);
+ px.rgba.r = 0;
+ px.rgba.g = 0;
+ px.rgba.b = 0;
+ px.rgba.a = 255;
+
+ chunks_len = size - (int)sizeof(qoi_padding);
+ for (px_pos = 0; px_pos < px_len; px_pos += channels) {
+ if (run > 0) {
+ run--;
+ }
+ else if (p < chunks_len) {
+ int b1 = bytes[p++];
+
+ if (b1 == QOI_OP_RGB) {
+ px.rgba.r = bytes[p++];
+ px.rgba.g = bytes[p++];
+ px.rgba.b = bytes[p++];
+ }
+ else if (b1 == QOI_OP_RGBA) {
+ px.rgba.r = bytes[p++];
+ px.rgba.g = bytes[p++];
+ px.rgba.b = bytes[p++];
+ px.rgba.a = bytes[p++];
+ }
+ else if ((b1 & QOI_MASK_2) == QOI_OP_INDEX) {
+ px = index[b1];
+ }
+ else if ((b1 & QOI_MASK_2) == QOI_OP_DIFF) {
+ px.rgba.r += ((b1 >> 4) & 0x03) - 2;
+ px.rgba.g += ((b1 >> 2) & 0x03) - 2;
+ px.rgba.b += ( b1 & 0x03) - 2;
+ }
+ else if ((b1 & QOI_MASK_2) == QOI_OP_LUMA) {
+ int b2 = bytes[p++];
+ int vg = (b1 & 0x3f) - 32;
+ px.rgba.r += vg - 8 + ((b2 >> 4) & 0x0f);
+ px.rgba.g += vg;
+ px.rgba.b += vg - 8 + (b2 & 0x0f);
+ }
+ else if ((b1 & QOI_MASK_2) == QOI_OP_RUN) {
+ run = (b1 & 0x3f);
+ }
+
+ index[QOI_COLOR_HASH(px) % 64] = px;
+ }
+
+ if (channels == 4) {
+ *(qoi_rgba_t*)(pixels + px_pos) = px;
+ }
+ else {
+ pixels[px_pos + 0] = px.rgba.r;
+ pixels[px_pos + 1] = px.rgba.g;
+ pixels[px_pos + 2] = px.rgba.b;
+ }
+ }
+
+ return pixels;
+}
+
+#ifndef QOI_NO_STDIO
+#include <stdio.h>
+
+int qoi_write(const char *filename, const void *data, const qoi_desc *desc) {
+ FILE *f = fopen(filename, "wb");
+ int size;
+ void *encoded;
+
+ if (!f) {
+ return 0;
+ }
+
+ encoded = qoi_encode(data, desc, &size);
+ if (!encoded) {
+ fclose(f);
+ return 0;
+ }
+
+ fwrite(encoded, 1, size, f);
+ fclose(f);
+
+ QOI_FREE(encoded);
+ return size;
+}
+
+void *qoi_read(const char *filename, qoi_desc *desc, int channels) {
+ FILE *f = fopen(filename, "rb");
+ int size, bytes_read;
+ void *pixels, *data;
+
+ if (!f) {
+ return NULL;
+ }
+
+ fseek(f, 0, SEEK_END);
+ size = ftell(f);
+ if (size <= 0) {
+ fclose(f);
+ return NULL;
+ }
+ fseek(f, 0, SEEK_SET);
+
+ data = QOI_MALLOC(size);
+ if (!data) {
+ fclose(f);
+ return NULL;
+ }
+
+ bytes_read = fread(data, 1, size, f);
+ fclose(f);
+
+ pixels = qoi_decode(data, bytes_read, desc, channels);
+ QOI_FREE(data);
+ return pixels;
+}
+
+#endif /* QOI_NO_STDIO */
+#endif /* QOI_IMPLEMENTATION */
diff --git a/include/rres-raylib.h b/include/rres-raylib.h
new file mode 100644
index 0000000..71d6f2a
--- /dev/null
+++ b/include/rres-raylib.h
@@ -0,0 +1,1094 @@
+/**********************************************************************************************
+*
+* rres-raylib v1.2 - rres loaders specific for raylib data structures
+*
+* CONFIGURATION:
+*
+* #define RRES_RAYLIB_IMPLEMENTATION
+* Generates the implementation of the library into the included file.
+* If not defined, the library is in header only mode and can be included in other headers
+* or source files without problems. But only ONE file should hold the implementation.
+*
+* #define RRES_SUPPORT_COMPRESSION_LZ4
+* Support data compression algorithm LZ4, provided by lz4.h/lz4.c library
+*
+* #define RRES_SUPPORT_ENCRYPTION_AES
+* Support data encryption algorithm AES, provided by aes.h/aes.c library
+*
+* #define RRES_SUPPORT_ENCRYPTION_XCHACHA20
+* Support data encryption algorithm XChaCha20-Poly1305,
+* provided by monocypher.h/monocypher.c library
+*
+* DEPENDENCIES:
+*
+* - raylib.h: Data types definition and data loading from memory functions
+* WARNING: raylib.h MUST be included before including rres-raylib.h
+* - rres.h: Base implementation of rres specs, required to read rres files and resource chunks
+* - lz4.h: LZ4 compression support (optional)
+* - aes.h: AES-256 CTR encryption support (optional)
+* - monocypher.h: for XChaCha20-Poly1305 encryption support (optional)
+*
+* VERSION HISTORY:
+*
+* - 1.2 (15-Apr-2023): Updated to monocypher 4.0.1
+* - 1.0 (11-May-2022): Initial implementation release
+*
+*
+* LICENSE: MIT
+*
+* Copyright (c) 2020-2023 Ramon Santamaria (@raysan5)
+*
+* Permission is hereby granted, free of charge, to any person obtaining a copy
+* of this software and associated documentation files (the "Software"), to deal
+* in the Software without restriction, including without limitation the rights
+* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+* copies of the Software, and to permit persons to whom the Software is
+* furnished to do so, subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all
+* copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+* SOFTWARE.
+*
+**********************************************************************************************/
+
+#ifndef RRES_RAYLIB_H
+#define RRES_RAYLIB_H
+
+#ifndef RRES_H
+ #include "rres.h"
+#endif
+
+//----------------------------------------------------------------------------------
+// Defines and Macros
+//----------------------------------------------------------------------------------
+//...
+
+//----------------------------------------------------------------------------------
+// Types and Structures Definition
+//----------------------------------------------------------------------------------
+//...
+
+//----------------------------------------------------------------------------------
+// Global variables
+//----------------------------------------------------------------------------------
+//...
+
+//----------------------------------------------------------------------------------
+// Module Functions Declaration
+//----------------------------------------------------------------------------------
+#if defined(__cplusplus)
+extern "C" { // Prevents name mangling of functions
+#endif
+
+// rres data loading to raylib data structures
+// NOTE: Chunk data must be provided uncompressed/unencrypted
+RLAPI void *LoadDataFromResource(rresResourceChunk chunk, unsigned int *size); // Load raw data from rres resource chunk
+RLAPI char *LoadTextFromResource(rresResourceChunk chunk); // Load text data from rres resource chunk
+RLAPI Image LoadImageFromResource(rresResourceChunk chunk); // Load Image data from rres resource chunk
+RLAPI Wave LoadWaveFromResource(rresResourceChunk chunk); // Load Wave data from rres resource chunk
+RLAPI Font LoadFontFromResource(rresResourceMulti multi); // Load Font data from rres resource multiple chunks
+RLAPI Mesh LoadMeshFromResource(rresResourceMulti multi); // Load Mesh data from rres resource multiple chunks
+
+// Unpack resource chunk data (decompres/decrypt data)
+// NOTE: Function return 0 on success or other value on failure
+RLAPI int UnpackResourceChunk(rresResourceChunk *chunk); // Unpack resource chunk data (decompress/decrypt)
+
+// Set base directory for externally linked data
+// NOTE: When resource chunk contains an external link (FourCC: LINK, Type: RRES_DATA_LINK),
+// a base directory is required to be prepended to link path
+// If not provided, the application path is prepended to link by default
+RLAPI void SetBaseDirectory(const char *baseDir); // Set base directory for externally linked data
+
+#if defined(__cplusplus)
+}
+#endif
+
+#endif // RRES_RAYLIB_H
+
+/***********************************************************************************
+*
+* RRES RAYLIB IMPLEMENTATION
+*
+************************************************************************************/
+
+#if defined(RRES_RAYLIB_IMPLEMENTATION)
+
+// Compression/Encryption algorithms supported
+// NOTE: They should be the same supported by the rres packaging tool (rrespacker)
+// https://github.com/phoboslab/qoi
+#include "external/qoi.h" // Compression algorithm: QOI (implementation in raylib)
+
+#if defined(RRES_SUPPORT_COMPRESSION_LZ4)
+ // https://github.com/lz4/lz4
+ #include "external/lz4.h" // Compression algorithm: LZ4
+ #include "external/lz4.c" // Compression algorithm implementation: LZ4
+#endif
+#if defined(RRES_SUPPORT_ENCRYPTION_AES)
+ // https://github.com/kokke/tiny-AES-c
+ #include "external/aes.h" // Encryption algorithm: AES
+ #include "external/aes.c" // Encryption algorithm implementation: AES
+#endif
+#if defined(RRES_SUPPORT_ENCRYPTION_XCHACHA20)
+ // https://github.com/LoupVaillant/Monocypher
+ #include "external/monocypher.h" // Encryption algorithm: XChaCha20-Poly1305
+ #include "external/monocypher.c" // Encryption algorithm implementation: XChaCha20-Poly1305
+#endif
+
+//----------------------------------------------------------------------------------
+// Defines and Macros
+//----------------------------------------------------------------------------------
+//...
+
+//----------------------------------------------------------------------------------
+// Types and Structures Definition
+//----------------------------------------------------------------------------------
+//...
+
+//----------------------------------------------------------------------------------
+// Global Variables Definition
+//----------------------------------------------------------------------------------
+static const char *baseDir = NULL; // Base directory pointer, used on external linked data loading
+
+//----------------------------------------------------------------------------------
+// Module specific Functions Declaration
+//----------------------------------------------------------------------------------
+
+// Load simple data chunks that are later required by multi-chunk resources
+// NOTE: Chunk data must be provided uncompressed/unencrypted
+static void *LoadDataFromResourceLink(rresResourceChunk chunk, unsigned int *size); // Load chunk: RRES_DATA_LINK
+static void *LoadDataFromResourceChunk(rresResourceChunk chunk, unsigned int *size); // Load chunk: RRES_DATA_RAW
+static char *LoadTextFromResourceChunk(rresResourceChunk chunk, unsigned int *codeLang); // Load chunk: RRES_DATA_TEXT
+static Image LoadImageFromResourceChunk(rresResourceChunk chunk); // Load chunk: RRES_DATA_IMAGE
+
+static const char *GetExtensionFromProps(unsigned int ext01, unsigned int ext02); // Get file extension from RRES_DATA_RAW properties (unsigned int)
+static unsigned int *ComputeMD5(unsigned char *data, int size); // Compute MD5 hash code, returns 4 integers array (static)
+
+//----------------------------------------------------------------------------------
+// Module Functions Definition
+//----------------------------------------------------------------------------------
+
+// Load raw data from rres resource
+void *LoadDataFromResource(rresResourceChunk chunk, unsigned int *size)
+{
+ void *rawData = NULL;
+
+ // Data can be provided in the resource or linked to an external file
+ if (rresGetDataType(chunk.info.type) == RRES_DATA_RAW) // Raw data
+ {
+ rawData = LoadDataFromResourceChunk(chunk, size);
+ }
+ else if (rresGetDataType(chunk.info.type) == RRES_DATA_LINK) // Link to external file
+ {
+ // Get raw data from external linked file
+ unsigned int dataSize = 0;
+ void *data = LoadDataFromResourceLink(chunk, &dataSize);
+
+ rawData = data;
+ *size = dataSize;
+ }
+
+ return rawData;
+}
+
+// Load text data from rres resource
+// NOTE: Text must be NULL terminated
+char *LoadTextFromResource(rresResourceChunk chunk)
+{
+ char *text = NULL;
+ int codeLang = 0;
+
+ if (rresGetDataType(chunk.info.type) == RRES_DATA_TEXT) // Text data
+ {
+ text = LoadTextFromResourceChunk(chunk, &codeLang);
+
+ // TODO: Consider text code language to load shader or code scripts
+ }
+ else if (rresGetDataType(chunk.info.type) == RRES_DATA_RAW) // Raw text file
+ {
+ unsigned int size = 0;
+ text = LoadDataFromResourceChunk(chunk, &size);
+ }
+ else if (rresGetDataType(chunk.info.type) == RRES_DATA_LINK) // Link to external file
+ {
+ // Get raw data from external linked file
+ unsigned int dataSize = 0;
+ void *data = LoadDataFromResourceLink(chunk, &dataSize);
+ text = data;
+ }
+
+ return text;
+}
+
+// Load Image data from rres resource
+Image LoadImageFromResource(rresResourceChunk chunk)
+{
+ Image image = { 0 };
+
+ if (rresGetDataType(chunk.info.type) == RRES_DATA_IMAGE) // Image data
+ {
+ image = LoadImageFromResourceChunk(chunk);
+ }
+ else if (rresGetDataType(chunk.info.type) == RRES_DATA_RAW) // Raw image file
+ {
+ unsigned int dataSize = 0;
+ unsigned char *data = LoadDataFromResourceChunk(chunk, &dataSize);
+
+ image = LoadImageFromMemory(GetExtensionFromProps(chunk.data.props[1], chunk.data.props[2]), data, dataSize);
+
+ RL_FREE(data);
+ }
+ else if (rresGetDataType(chunk.info.type) == RRES_DATA_LINK) // Link to external file
+ {
+ // Get raw data from external linked file
+ unsigned int dataSize = 0;
+ void *data = LoadDataFromResourceLink(chunk, &dataSize);
+
+ // Load image from linked file data
+ // NOTE: Function checks internally if the file extension is supported to
+ // properly load the data, if it fails it logs the result and image.data = NULL
+ image = LoadImageFromMemory(GetFileExtension(chunk.data.raw), data, dataSize);
+ }
+
+ return image;
+}
+
+// Load Wave data from rres resource
+Wave LoadWaveFromResource(rresResourceChunk chunk)
+{
+ Wave wave = { 0 };
+
+ if (rresGetDataType(chunk.info.type) == RRES_DATA_WAVE) // Wave data
+ {
+ if ((chunk.info.compType == RRES_COMP_NONE) && (chunk.info.cipherType == RRES_CIPHER_NONE))
+ {
+ wave.frameCount = chunk.data.props[0];
+ wave.sampleRate = chunk.data.props[1];
+ wave.sampleSize = chunk.data.props[2];
+ wave.channels = chunk.data.props[3];
+
+ unsigned int size = wave.frameCount*wave.sampleSize/8;
+ wave.data = RL_CALLOC(size, 1);
+ memcpy(wave.data, chunk.data.raw, size);
+ }
+ RRES_LOG("RRES: %c%c%c%c: WARNING: Data must be decompressed/decrypted\n", chunk.info.type[0], chunk.info.type[1], chunk.info.type[2], chunk.info.type[3]);
+ }
+ else if (rresGetDataType(chunk.info.type) == RRES_DATA_RAW) // Raw wave file
+ {
+ unsigned int dataSize = 0;
+ unsigned char *data = LoadDataFromResourceChunk(chunk, &dataSize);
+
+ wave = LoadWaveFromMemory(GetExtensionFromProps(chunk.data.props[1], chunk.data.props[2]), data, dataSize);
+
+ RL_FREE(data);
+ }
+ else if (rresGetDataType(chunk.info.type) == RRES_DATA_LINK) // Link to external file
+ {
+ // Get raw data from external linked file
+ unsigned int dataSize = 0;
+ void *data = LoadDataFromResourceLink(chunk, &dataSize);
+
+ // Load wave from linked file data
+ // NOTE: Function checks internally if the file extension is supported to
+ // properly load the data, if it fails it logs the result and wave.data = NULL
+ wave = LoadWaveFromMemory(GetFileExtension(chunk.data.raw), data, dataSize);
+ }
+
+ return wave;
+}
+
+// Load Font data from rres resource
+Font LoadFontFromResource(rresResourceMulti multi)
+{
+ Font font = { 0 };
+
+ // Font resource consist of (2) chunks:
+ // - RRES_DATA_FONT_GLYPHS: Basic font and glyphs properties/data
+ // - RRES_DATA_IMAGE: Image atlas for the font characters
+ if (multi.count >= 2)
+ {
+ if (rresGetDataType(multi.chunks[0].info.type) == RRES_DATA_FONT_GLYPHS)
+ {
+ if ((multi.chunks[0].info.compType == RRES_COMP_NONE) && (multi.chunks[0].info.cipherType == RRES_CIPHER_NONE))
+ {
+ // Load font basic properties from chunk[0]
+ font.baseSize = multi.chunks[0].data.props[0]; // Base size (default chars height)
+ font.glyphCount = multi.chunks[0].data.props[1]; // Number of characters (glyphs)
+ font.glyphPadding = multi.chunks[0].data.props[2]; // Padding around the chars
+
+ font.recs = (Rectangle *)RL_CALLOC(font.glyphCount, sizeof(Rectangle));
+ font.glyphs = (GlyphInfo *)RL_CALLOC(font.glyphCount, sizeof(GlyphInfo));
+
+ for (int i = 0; i < font.glyphCount; i++)
+ {
+ // Font glyphs info comes as a data blob
+ font.recs[i].x = (float)((rresFontGlyphInfo *)multi.chunks[0].data.raw)[i].x;
+ font.recs[i].y = (float)((rresFontGlyphInfo *)multi.chunks[0].data.raw)[i].y;
+ font.recs[i].width = (float)((rresFontGlyphInfo *)multi.chunks[0].data.raw)[i].width;
+ font.recs[i].height = (float)((rresFontGlyphInfo *)multi.chunks[0].data.raw)[i].height;
+
+ font.glyphs[i].value = ((rresFontGlyphInfo *)multi.chunks[0].data.raw)[i].value;
+ font.glyphs[i].offsetX = ((rresFontGlyphInfo *)multi.chunks[0].data.raw)[i].offsetX;
+ font.glyphs[i].offsetY = ((rresFontGlyphInfo *)multi.chunks[0].data.raw)[i].offsetY;
+ font.glyphs[i].advanceX = ((rresFontGlyphInfo *)multi.chunks[0].data.raw)[i].advanceX;
+
+ // NOTE: font.glyphs[i].image is not loaded
+ }
+ }
+ else RRES_LOG("RRES: %s: WARNING: Data must be decompressed/decrypted\n", multi.chunks[0].info.type);
+ }
+
+ // Load font image chunk
+ if (rresGetDataType(multi.chunks[1].info.type) == RRES_DATA_IMAGE)
+ {
+ if ((multi.chunks[0].info.compType == RRES_COMP_NONE) && (multi.chunks[0].info.cipherType == RRES_CIPHER_NONE))
+ {
+ Image image = LoadImageFromResourceChunk(multi.chunks[1]);
+ font.texture = LoadTextureFromImage(image);
+ UnloadImage(image);
+ }
+ else RRES_LOG("RRES: %s: WARNING: Data must be decompressed/decrypted\n", multi.chunks[1].info.type);
+ }
+ }
+ else // One chunk of data: RRES_DATA_RAW or RRES_DATA_LINK?
+ {
+ if (rresGetDataType(multi.chunks[0].info.type) == RRES_DATA_RAW) // Raw font file
+ {
+ unsigned int dataSize = 0;
+ unsigned char *rawData = LoadDataFromResourceChunk(multi.chunks[0], &dataSize);
+
+ font = LoadFontFromMemory(GetExtensionFromProps(multi.chunks[0].data.props[1], multi.chunks[0].data.props[2]), rawData, dataSize, 32, NULL, 0);
+
+ RL_FREE(rawData);
+ }
+ if (rresGetDataType(multi.chunks[0].info.type) == RRES_DATA_LINK) // Link to external font file
+ {
+ // Get raw data from external linked file
+ unsigned int dataSize = 0;
+ void *rawData = LoadDataFromResourceLink(multi.chunks[0], &dataSize);
+
+ // Load image from linked file data
+ // NOTE 1: Loading font at 32px base size and default charset (95 glyphs)
+ // NOTE 2: Function checks internally if the file extension is supported to
+ // properly load the data, if it fails it logs the result and font.texture.id = 0
+ font = LoadFontFromMemory(GetFileExtension(multi.chunks[0].data.raw), rawData, dataSize, 32, NULL, 0);
+
+ RRES_FREE(rawData);
+ }
+ }
+
+ return font;
+}
+
+// Load Mesh data from rres resource
+// NOTE: We try to load vertex data following raylib structure constraints,
+// in case data does not fit raylib Mesh structure, it is not loaded
+Mesh LoadMeshFromResource(rresResourceMulti multi)
+{
+ Mesh mesh = { 0 };
+
+ // TODO: Support externally linked mesh resource?
+
+ // Mesh resource consist of (n) chunks:
+ for (unsigned int i = 0; i < multi.count; i++)
+ {
+ if ((multi.chunks[0].info.compType == RRES_COMP_NONE) && (multi.chunks[0].info.cipherType == RRES_CIPHER_NONE))
+ {
+ // NOTE: raylib only supports vertex arrays with same vertex count,
+ // rres.chunks[0] defined vertexCount will be the reference for the following chunks
+ // The only exception to vertexCount is the mesh.indices array
+ if (mesh.vertexCount == 0) mesh.vertexCount = multi.chunks[0].data.props[0];
+
+ // Verify chunk type and vertex count
+ if (rresGetDataType(multi.chunks[i].info.type) == RRES_DATA_VERTEX)
+ {
+ // In case vertex count do not match we skip that resource chunk
+ if ((multi.chunks[i].data.props[1] != RRES_VERTEX_ATTRIBUTE_INDEX) && (multi.chunks[i].data.props[0] != mesh.vertexCount)) continue;
+
+ // NOTE: We are only loading raylib supported rresVertexFormat and raylib expected components count
+ switch (multi.chunks[i].data.props[1]) // Check rresVertexAttribute value
+ {
+ case RRES_VERTEX_ATTRIBUTE_POSITION:
+ {
+ // raylib expects 3 components per vertex and float vertex format
+ if ((multi.chunks[i].data.props[2] == 3) && (multi.chunks[i].data.props[3] == RRES_VERTEX_FORMAT_FLOAT))
+ {
+ mesh.vertices = (float *)RL_CALLOC(mesh.vertexCount*3, sizeof(float));
+ memcpy(mesh.vertices, multi.chunks[i].data.raw, mesh.vertexCount*3*sizeof(float));
+ }
+ else RRES_LOG("RRES: WARNING: MESH: Vertex attribute position not valid, componentCount/vertexFormat do not fit\n");
+
+ } break;
+ case RRES_VERTEX_ATTRIBUTE_TEXCOORD1:
+ {
+ // raylib expects 2 components per vertex and float vertex format
+ if ((multi.chunks[i].data.props[2] == 2) && (multi.chunks[i].data.props[3] == RRES_VERTEX_FORMAT_FLOAT))
+ {
+ mesh.texcoords = (float *)RL_CALLOC(mesh.vertexCount*2, sizeof(float));
+ memcpy(mesh.texcoords, multi.chunks[i].data.raw, mesh.vertexCount*2*sizeof(float));
+ }
+ else RRES_LOG("RRES: WARNING: MESH: Vertex attribute texcoord1 not valid, componentCount/vertexFormat do not fit\n");
+
+ } break;
+ case RRES_VERTEX_ATTRIBUTE_TEXCOORD2:
+ {
+ // raylib expects 2 components per vertex and float vertex format
+ if ((multi.chunks[i].data.props[2] == 2) && (multi.chunks[i].data.props[3] == RRES_VERTEX_FORMAT_FLOAT))
+ {
+ mesh.texcoords2 = (float *)RL_CALLOC(mesh.vertexCount*2, sizeof(float));
+ memcpy(mesh.texcoords2, multi.chunks[i].data.raw, mesh.vertexCount*2*sizeof(float));
+ }
+ else RRES_LOG("RRES: WARNING: MESH: Vertex attribute texcoord2 not valid, componentCount/vertexFormat do not fit\n");
+
+ } break;
+ case RRES_VERTEX_ATTRIBUTE_TEXCOORD3:
+ {
+ RRES_LOG("RRES: WARNING: MESH: Vertex attribute texcoord3 not supported\n");
+
+ } break;
+ case RRES_VERTEX_ATTRIBUTE_TEXCOORD4:
+ {
+ RRES_LOG("RRES: WARNING: MESH: Vertex attribute texcoord4 not supported\n");
+
+ } break;
+ case RRES_VERTEX_ATTRIBUTE_NORMAL:
+ {
+ // raylib expects 3 components per vertex and float vertex format
+ if ((multi.chunks[i].data.props[2] == 3) && (multi.chunks[i].data.props[3] == RRES_VERTEX_FORMAT_FLOAT))
+ {
+ mesh.normals = (float *)RL_CALLOC(mesh.vertexCount*3, sizeof(float));
+ memcpy(mesh.normals, multi.chunks[i].data.raw, mesh.vertexCount*3*sizeof(float));
+ }
+ else RRES_LOG("RRES: WARNING: MESH: Vertex attribute normal not valid, componentCount/vertexFormat do not fit\n");
+
+ } break;
+ case RRES_VERTEX_ATTRIBUTE_TANGENT:
+ {
+ // raylib expects 4 components per vertex and float vertex format
+ if ((multi.chunks[i].data.props[2] == 4) && (multi.chunks[i].data.props[3] == RRES_VERTEX_FORMAT_FLOAT))
+ {
+ mesh.tangents = (float *)RL_CALLOC(mesh.vertexCount*4, sizeof(float));
+ memcpy(mesh.tangents, multi.chunks[i].data.raw, mesh.vertexCount*4*sizeof(float));
+ }
+ else RRES_LOG("RRES: WARNING: MESH: Vertex attribute tangent not valid, componentCount/vertexFormat do not fit\n");
+
+ } break;
+ case RRES_VERTEX_ATTRIBUTE_COLOR:
+ {
+ // raylib expects 4 components per vertex and unsigned char vertex format
+ if ((multi.chunks[i].data.props[2] == 4) && (multi.chunks[i].data.props[3] == RRES_VERTEX_FORMAT_UBYTE))
+ {
+ mesh.colors = (unsigned char *)RL_CALLOC(mesh.vertexCount*4, sizeof(unsigned char));
+ memcpy(mesh.colors, multi.chunks[i].data.raw, mesh.vertexCount*4*sizeof(unsigned char));
+ }
+ else RRES_LOG("RRES: WARNING: MESH: Vertex attribute color not valid, componentCount/vertexFormat do not fit\n");
+
+ } break;
+ case RRES_VERTEX_ATTRIBUTE_INDEX:
+ {
+ // raylib expects 1 components per index and unsigned short vertex format
+ if ((multi.chunks[i].data.props[2] == 1) && (multi.chunks[i].data.props[3] == RRES_VERTEX_FORMAT_USHORT))
+ {
+ mesh.indices = (unsigned short *)RL_CALLOC(multi.chunks[i].data.props[0], sizeof(unsigned short));
+ memcpy(mesh.indices, multi.chunks[i].data.raw, multi.chunks[i].data.props[0]*sizeof(unsigned short));
+ }
+ else RRES_LOG("RRES: WARNING: MESH: Vertex attribute index not valid, componentCount/vertexFormat do not fit\n");
+
+ } break;
+ default: break;
+ }
+ }
+ }
+ else RRES_LOG("RRES: WARNING: Vertex provided data must be decompressed/decrypted\n");
+ }
+
+ return mesh;
+}
+
+// Unpack compressed/encrypted data from resource chunk
+// In case data could not be processed by rres.h, it is just copied in chunk.data.raw for processing here
+// NOTE 1: Function return 0 on success or an error code on failure
+// NOTE 2: Data corruption CRC32 check has already been performed by rresLoadResourceMulti() on rres.h
+int UnpackResourceChunk(rresResourceChunk *chunk)
+{
+ int result = 0;
+ bool updateProps = false;
+
+ // Result error codes:
+ // 0 - No error, decompression/decryption successful
+ // 1 - Encryption algorithm not supported
+ // 2 - Invalid password on decryption
+ // 3 - Compression algorithm not supported
+ // 4 - Error on data decompression
+
+ // NOTE 1: If data is compressed/encrypted the properties are not loaded by rres.h because
+ // it's up to the user to process the data; *chunk must be properly updated by this function
+ // NOTE 2: rres-raylib should support the same algorithms and libraries used by rrespacker tool
+ void *unpackedData = NULL;
+
+ // STEP 1. Data decryption
+ //-------------------------------------------------------------------------------------
+ unsigned char *decryptedData = NULL;
+
+ switch (chunk->info.cipherType)
+ {
+ case RRES_CIPHER_NONE: decryptedData = chunk->data.raw; break;
+#if defined(RRES_SUPPORT_ENCRYPTION_AES)
+ case RRES_CIPHER_AES:
+ {
+ // WARNING: Implementation dependant!
+ // rrespacker tool appends (salt[16] + MD5[16]) to encrypted data for convenience,
+ // Actually, chunk->info.packedSize considers those additional elements
+
+ // Get some memory for the possible message output
+ decryptedData = (unsigned char *)RL_CALLOC(chunk->info.packedSize - 16 - 16, 1);
+ if (decryptedData != NULL) memcpy(decryptedData, chunk->data.raw, chunk->info.packedSize - 16 - 16);
+
+ // Required variables for key stretching
+ uint8_t key[32] = { 0 }; // Encryption key
+ uint8_t salt[16] = { 0 }; // Key stretching salt
+
+ // Retrieve salt from chunk packed data
+ // salt is stored at the end of packed data, before nonce and MAC: salt[16] + MD5[16]
+ memcpy(salt, ((unsigned char *)chunk->data.raw) + (chunk->info.packedSize - 16 - 16), 16);
+
+ // Key stretching configuration
+ crypto_argon2_config config = {
+ .algorithm = CRYPTO_ARGON2_I, // Algorithm: Argon2i
+ .nb_blocks = 16384, // Blocks: 16 MB
+ .nb_passes = 3, // Iterations
+ .nb_lanes = 1 // Single-threaded
+ };
+ crypto_argon2_inputs inputs = {
+ .pass = (const uint8_t *)rresGetCipherPassword(), // User password
+ .pass_size = strlen(rresGetCipherPassword()), // Password length
+ .salt = salt, // Salt for the password
+ .salt_size = 16
+ };
+ crypto_argon2_extras extras = { 0 }; // Extra parameters unused
+
+ void *workArea = RL_MALLOC(config.nb_blocks*1024); // Key stretching work area
+
+ // Generate strong encryption key, generated from user password using Argon2i algorithm (256 bit)
+ crypto_argon2(key, 32, workArea, config, inputs, extras);
+
+ // Wipe key generation secrets, they are no longer needed
+ crypto_wipe(salt, 16);
+ RL_FREE(workArea);
+
+ // Required variables for decryption and message authentication
+ unsigned int md5[4] = { 0 }; // Message Authentication Code generated on encryption
+
+ // Retrieve MD5 from chunk packed data
+ // NOTE: MD5 is stored at the end of packed data, after salt: salt[16] + MD5[16]
+ memcpy(md5, ((unsigned char *)chunk->data.raw) + (chunk->info.packedSize - 16), 4*sizeof(unsigned int));
+
+ // Message decryption, requires key
+ struct AES_ctx ctx = { 0 };
+ AES_init_ctx(&ctx, key);
+ AES_CTR_xcrypt_buffer(&ctx, (uint8_t *)decryptedData, chunk->info.packedSize - 16 - 16); // AES Counter mode, stream cipher
+
+ // Verify MD5 to check if data decryption worked
+ unsigned int decryptMD5[4] = { 0 };
+ unsigned int *md5Ptr = ComputeMD5(decryptedData, chunk->info.packedSize - 16 - 16);
+ for (int i = 0; i < 4; i++) decryptMD5[i] = md5Ptr[i];
+
+ // Wipe secrets if they are no longer needed
+ crypto_wipe(key, 32);
+
+ if (memcmp(decryptMD5, md5, 4*sizeof(unsigned int)) == 0) // Decrypted successfully!
+ {
+ chunk->info.packedSize -= (16 + 16); // We remove additional data size from packed size (salt[16] + MD5[16])
+ RRES_LOG("RRES: %c%c%c%c: Data decrypted successfully (AES)\n", chunk->info.type[0], chunk->info.type[1], chunk->info.type[2], chunk->info.type[3]);
+ }
+ else
+ {
+ result = 2; // Data was not decrypted as expected, wrong password or message corrupted
+ RRES_LOG("RRES: WARNING: %c%c%c%c: Data decryption failed, wrong password or corrupted data\n", chunk->info.type[0], chunk->info.type[1], chunk->info.type[2], chunk->info.type[3]);
+ }
+
+ } break;
+#endif
+#if defined(RRES_SUPPORT_ENCRYPTION_XCHACHA20)
+ case RRES_CIPHER_XCHACHA20_POLY1305:
+ {
+ // WARNING: Implementation dependant!
+ // rrespacker tool appends (salt[16] + nonce[24] + MAC[16]) to encrypted data for convenience,
+ // Actually, chunk->info.packedSize considers those additional elements
+
+ // Get some memory for the possible message output
+ decryptedData = (unsigned char *)RL_CALLOC(chunk->info.packedSize - 16 - 24 - 16, 1);
+
+ // Required variables for key stretching
+ uint8_t key[32] = { 0 }; // Encryption key
+ uint8_t salt[16] = { 0 }; // Key stretching salt
+
+ // Retrieve salt from chunk packed data
+ // salt is stored at the end of packed data, before nonce and MAC: salt[16] + nonce[24] + MAC[16]
+ memcpy(salt, ((unsigned char *)chunk->data.raw) + (chunk->info.packedSize - 16 - 24 - 16), 16);
+
+ // Key stretching configuration
+ crypto_argon2_config config = {
+ .algorithm = CRYPTO_ARGON2_I, // Algorithm: Argon2i
+ .nb_blocks = 16384, // Blocks: 16 MB
+ .nb_passes = 3, // Iterations
+ .nb_lanes = 1 // Single-threaded
+ };
+ crypto_argon2_inputs inputs = {
+ .pass = (const uint8_t *)rresGetCipherPassword(), // User password
+ .pass_size = strlen(rresGetCipherPassword()), // Password length
+ .salt = salt, // Salt for the password
+ .salt_size = 16
+ };
+ crypto_argon2_extras extras = { 0 }; // Extra parameters unused
+
+ void *workArea = RL_MALLOC(config.nb_blocks*1024); // Key stretching work area
+
+ // Generate strong encryption key, generated from user password using Argon2i algorithm (256 bit)
+ crypto_argon2(key, 32, workArea, config, inputs, extras);
+
+ // Wipe key generation secrets, they are no longer needed
+ crypto_wipe(salt, 16);
+ RL_FREE(workArea);
+
+ // Required variables for decryption and message authentication
+ uint8_t nonce[24] = { 0 }; // nonce used on encryption, unique to processed file
+ uint8_t mac[16] = { 0 }; // Message Authentication Code generated on encryption
+
+ // Retrieve nonce and MAC from chunk packed data
+ // nonce and MAC are stored at the end of packed data, after salt: salt[16] + nonce[24] + MAC[16]
+ memcpy(nonce, ((unsigned char *)chunk->data.raw) + (chunk->info.packedSize - 16 - 24), 24);
+ memcpy(mac, ((unsigned char *)chunk->data.raw) + (chunk->info.packedSize - 16), 16);
+
+ // Message decryption requires key, nonce and MAC
+ int decryptResult = crypto_aead_unlock(decryptedData, mac, key, nonce, NULL, 0, chunk->data.raw, (chunk->info.packedSize - 16 - 24 - 16));
+
+ // Wipe secrets if they are no longer needed
+ crypto_wipe(nonce, 24);
+ crypto_wipe(key, 32);
+
+ if (decryptResult == 0) // Decrypted successfully!
+ {
+ chunk->info.packedSize -= (16 + 24 + 16); // We remove additional data size from packed size
+ RRES_LOG("RRES: %c%c%c%c: Data decrypted successfully (XChaCha20)\n", chunk->info.type[0], chunk->info.type[1], chunk->info.type[2], chunk->info.type[3]);
+ }
+ else if (decryptResult == -1)
+ {
+ result = 2; // Wrong password or message corrupted
+ RRES_LOG("RRES: WARNING: %c%c%c%c: Data decryption failed, wrong password or corrupted data\n", chunk->info.type[0], chunk->info.type[1], chunk->info.type[2], chunk->info.type[3]);
+ }
+ } break;
+#endif
+ default:
+ {
+ result = 1; // Decryption algorithm not supported
+ RRES_LOG("RRES: WARNING: %c%c%c%c: Chunk data encryption algorithm not supported\n", chunk->info.type[0], chunk->info.type[1], chunk->info.type[2], chunk->info.type[3]);
+
+ } break;
+ }
+
+ if ((result == 0) && (chunk->info.cipherType != RRES_CIPHER_NONE))
+ {
+ // Data is not encrypted any more, register it
+ chunk->info.cipherType = RRES_CIPHER_NONE;
+ updateProps = true;
+ }
+
+ // STEP 2: Data decompression (if decryption was successful)
+ //-------------------------------------------------------------------------------------
+ unsigned char *uncompData = NULL;
+
+ if (result == 0)
+ {
+ switch (chunk->info.compType)
+ {
+ case RRES_COMP_NONE: unpackedData = decryptedData; break;
+ case RRES_COMP_DEFLATE:
+ {
+ int uncompDataSize = 0;
+
+ // TODO: WARNING: Possible issue with allocators: RL_CALLOC() vs RRES_CALLOC()
+ uncompData = DecompressData(decryptedData, chunk->info.packedSize, &uncompDataSize);
+
+ if ((uncompData != NULL) && (uncompDataSize > 0)) // Decompression successful
+ {
+ unpackedData = uncompData;
+ chunk->info.packedSize = uncompDataSize;
+ RRES_LOG("RRES: %c%c%c%c: Data decompressed successfully (DEFLATE)\n", chunk->info.type[0], chunk->info.type[1], chunk->info.type[2], chunk->info.type[3]);
+ }
+ else
+ {
+ result = 4; // Decompression process failed
+ RRES_LOG("RRES: WARNING: %c%c%c%c: Chunk data decompression failed\n", chunk->info.type[0], chunk->info.type[1], chunk->info.type[2], chunk->info.type[3]);
+ }
+
+ // Security check, uncompDataSize must match the provided chunk->baseSize
+ if (uncompDataSize != chunk->info.baseSize) RRES_LOG("RRES: WARNING: Decompressed data could be corrupted, unexpected size\n");
+ } break;
+#if defined(RRES_SUPPORT_COMPRESSION_LZ4)
+ case RRES_COMP_LZ4:
+ {
+ int uncompDataSize = 0;
+ uncompData = (unsigned char *)RRES_CALLOC(chunk->info.baseSize, 1);
+ uncompDataSize = LZ4_decompress_safe(decryptedData, uncompData, chunk->info.packedSize, chunk->info.baseSize);
+
+ if ((uncompData != NULL) && (uncompDataSize > 0)) // Decompression successful
+ {
+ unpackedData = uncompData;
+ chunk->info.packedSize = uncompDataSize;
+ RRES_LOG("RRES: %c%c%c%c: Data decompressed successfully (LZ4)\n", chunk->info.type[0], chunk->info.type[1], chunk->info.type[2], chunk->info.type[3]);
+ }
+ else
+ {
+ result = 4; // Decompression process failed
+ RRES_LOG("RRES: WARNING: %c%c%c%c: Chunk data decompression failed\n", chunk->info.type[0], chunk->info.type[1], chunk->info.type[2], chunk->info.type[3]);
+ }
+
+ // WARNING: Decompression could be successful but not the original message size returned
+ if (uncompDataSize != chunk->info.baseSize) RRES_LOG("RRES: WARNING: Decompressed data could be corrupted, unexpected size\n");
+ } break;
+#endif
+ case RRES_COMP_QOI:
+ {
+ int uncompDataSize = 0;
+ qoi_desc desc = { 0 };
+
+ // TODO: WARNING: Possible issue with allocators: QOI_MALLOC() vs RRES_MALLOC()
+ uncompData = qoi_decode(decryptedData, chunk->info.packedSize, &desc, 0);
+ uncompDataSize = (desc.width*desc.height*desc.channels) + 20; // Add the 20 bytes of (propCount + props[4])
+
+ if ((uncompData != NULL) && (uncompDataSize > 0)) // Decompression successful
+ {
+ unpackedData = uncompData;
+ chunk->info.packedSize = uncompDataSize;
+ RRES_LOG("RRES: %c%c%c%c: Data decompressed successfully (QOI)\n", chunk->info.type[0], chunk->info.type[1], chunk->info.type[2], chunk->info.type[3]);
+ }
+ else
+ {
+ result = 4; // Decompression process failed
+ RRES_LOG("RRES: WARNING: %c%c%c%c: Chunk data decompression failed\n", chunk->info.type[0], chunk->info.type[1], chunk->info.type[2], chunk->info.type[3]);
+ }
+
+ if (uncompDataSize != chunk->info.baseSize) RRES_LOG("RRES: WARNING: Decompressed data could be corrupted, unexpected size\n");
+ } break;
+ default:
+ {
+ result = 3;
+ RRES_LOG("RRES: WARNING: %c%c%c%c: Chunk data compression algorithm not supported\n", chunk->info.type[0], chunk->info.type[1], chunk->info.type[2], chunk->info.type[3]);
+ } break;
+ }
+ }
+
+ if ((result == 0) && (chunk->info.compType != RRES_COMP_NONE))
+ {
+ // Data is not encrypted any more, register it
+ chunk->info.compType = RRES_COMP_NONE;
+ updateProps = true;
+ }
+
+ // Update chunk->data.propCount and chunk->data.props if required
+ if (updateProps && (unpackedData != NULL))
+ {
+ // Data is decompressed/decrypted into chunk->data.raw but data.propCount and data.props[] are still empty,
+ // they must be filled with the just updated chunk->data.raw (that contains everything)
+ chunk->data.propCount = ((int *)unpackedData)[0];
+
+ if (chunk->data.propCount > 0)
+ {
+ chunk->data.props = (unsigned int *)RRES_CALLOC(chunk->data.propCount, sizeof(int));
+ for (unsigned int i = 0; i < chunk->data.propCount; i++) chunk->data.props[i] = ((int *)unpackedData)[1 + i];
+ }
+
+ // Move chunk->data.raw pointer (chunk->data.propCount*sizeof(int)) positions
+ void *raw = RRES_CALLOC(chunk->info.baseSize - 20, 1);
+ if (raw != NULL) memcpy(raw, ((unsigned char *)unpackedData) + 20, chunk->info.baseSize - 20);
+ RRES_FREE(chunk->data.raw);
+ chunk->data.raw = raw;
+ RL_FREE(unpackedData);
+ }
+
+ return result;
+}
+
+//----------------------------------------------------------------------------------
+// Module specific Functions Definition
+//----------------------------------------------------------------------------------
+
+// Load data chunk: RRES_DATA_LINK
+static void *LoadDataFromResourceLink(rresResourceChunk chunk, unsigned int *size)
+{
+ unsigned char fullFilePath[2048] = { 0 };
+ void *data = NULL;
+ *size = 0;
+
+ // Get external link filepath
+ unsigned char *linkFilePath = RL_CALLOC(chunk.data.props[0], 1);
+ if (linkFilePath != NULL) memcpy(linkFilePath, chunk.data.raw, chunk.data.props[0]);
+
+ // Get base directory to append filepath if not provided by user
+ if (baseDir == NULL) baseDir = GetApplicationDirectory();
+
+ strcpy(fullFilePath, baseDir);
+ strcat(fullFilePath, linkFilePath);
+
+ RRES_LOG("RRES: %c%c%c%c: Data file linked externally: %s\n", chunk.info.type[0], chunk.info.type[1], chunk.info.type[2], chunk.info.type[3], linkFilePath);
+
+ if (FileExists(fullFilePath))
+ {
+ // Load external file as raw data
+ // NOTE: We check if file is a text file to allow automatic line-endings processing
+ if (IsFileExtension(linkFilePath, ".txt;.md;.vs;.fs;.info;.c;.h;.json;.xml;.glsl")) // Text file
+ {
+ data = LoadFileText(fullFilePath);
+ *size = TextLength(data);
+ }
+ else data = LoadFileData(fullFilePath, size);
+
+ if ((data != NULL) && (*size > 0)) RRES_LOG("RRES: %c%c%c%c: External linked file loaded successfully\n", chunk.info.type[0], chunk.info.type[1], chunk.info.type[2], chunk.info.type[3]);
+ }
+ else RRES_LOG("RRES: WARNING: [%s] Linked external file could not be found\n", linkFilePath);
+
+ return data;
+}
+
+// Load data chunk: RRES_DATA_RAW
+// NOTE: This chunk can be used raw files embedding or other binary blobs
+static void *LoadDataFromResourceChunk(rresResourceChunk chunk, unsigned int *size)
+{
+ void *rawData = NULL;
+
+ if ((chunk.info.compType == RRES_COMP_NONE) && (chunk.info.cipherType == RRES_CIPHER_NONE))
+ {
+ rawData = RL_CALLOC(chunk.data.props[0], 1);
+ if (rawData != NULL) memcpy(rawData, chunk.data.raw, chunk.data.props[0]);
+ *size = chunk.data.props[0];
+ }
+ else RRES_LOG("RRES: %c%c%c%c: WARNING: Data must be decompressed/decrypted\n", chunk.info.type[0], chunk.info.type[1], chunk.info.type[2], chunk.info.type[3]);
+
+ return rawData;
+}
+
+// Load data chunk: RRES_DATA_TEXT
+// NOTE: This chunk can be used for shaders or other text data elements (materials?)
+static char *LoadTextFromResourceChunk(rresResourceChunk chunk, unsigned int *codeLang)
+{
+ void *text = NULL;
+
+ if ((chunk.info.compType == RRES_COMP_NONE) && (chunk.info.cipherType == RRES_CIPHER_NONE))
+ {
+ text = (char *)RL_CALLOC(chunk.data.props[0] + 1, 1); // We add NULL terminator, just in case
+ if (text != NULL) memcpy(text, chunk.data.raw, chunk.data.props[0]);
+
+ // TODO: We got some extra text properties, in case they could be useful for users:
+ // chunk.props[1]:rresTextEncoding, chunk.props[2]:rresCodeLang, chunk. props[3]:cultureCode
+ *codeLang = chunk.data.props[2];
+ //chunks.props[3]:cultureCode could be useful for localized text
+ }
+ else RRES_LOG("RRES: %c%c%c%c: WARNING: Data must be decompressed/decrypted\n", chunk.info.type[0], chunk.info.type[1], chunk.info.type[2], chunk.info.type[3]);
+
+ return text;
+}
+
+// Load data chunk: RRES_DATA_IMAGE
+// NOTE: Many data types use images data in some way (font, material...)
+static Image LoadImageFromResourceChunk(rresResourceChunk chunk)
+{
+ Image image = { 0 };
+
+ if ((chunk.info.compType == RRES_COMP_NONE) && (chunk.info.cipherType == RRES_CIPHER_NONE))
+ {
+ image.width = chunk.data.props[0];
+ image.height = chunk.data.props[1];
+ int format = chunk.data.props[2];
+
+ // Assign equivalent pixel formats for our engine
+ // NOTE: In this case rresPixelFormat defined values match raylib PixelFormat values
+ switch (format)
+ {
+ case RRES_PIXELFORMAT_UNCOMP_GRAYSCALE: image.format = PIXELFORMAT_UNCOMPRESSED_GRAYSCALE; break;
+ case RRES_PIXELFORMAT_UNCOMP_GRAY_ALPHA: image.format = PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA; break;
+ case RRES_PIXELFORMAT_UNCOMP_R5G6B5: image.format = PIXELFORMAT_UNCOMPRESSED_R5G6B5; break;
+ case RRES_PIXELFORMAT_UNCOMP_R8G8B8: image.format = PIXELFORMAT_UNCOMPRESSED_R8G8B8; break;
+ case RRES_PIXELFORMAT_UNCOMP_R5G5B5A1: image.format = PIXELFORMAT_UNCOMPRESSED_R5G5B5A1; break;
+ case RRES_PIXELFORMAT_UNCOMP_R4G4B4A4: image.format = PIXELFORMAT_UNCOMPRESSED_R4G4B4A4; break;
+ case RRES_PIXELFORMAT_UNCOMP_R8G8B8A8: image.format = PIXELFORMAT_UNCOMPRESSED_R8G8B8A8; break;
+ case RRES_PIXELFORMAT_UNCOMP_R32: image.format = PIXELFORMAT_UNCOMPRESSED_R32; break;
+ case RRES_PIXELFORMAT_UNCOMP_R32G32B32: image.format = PIXELFORMAT_UNCOMPRESSED_R32G32B32; break;
+ case RRES_PIXELFORMAT_UNCOMP_R32G32B32A32: image.format = PIXELFORMAT_UNCOMPRESSED_R32G32B32A32; break;
+ case RRES_PIXELFORMAT_COMP_DXT1_RGB: image.format = PIXELFORMAT_COMPRESSED_DXT1_RGB; break;
+ case RRES_PIXELFORMAT_COMP_DXT1_RGBA: image.format = PIXELFORMAT_COMPRESSED_DXT1_RGBA; break;
+ case RRES_PIXELFORMAT_COMP_DXT3_RGBA: image.format = PIXELFORMAT_COMPRESSED_DXT3_RGBA; break;
+ case RRES_PIXELFORMAT_COMP_DXT5_RGBA: image.format = PIXELFORMAT_COMPRESSED_DXT5_RGBA; break;
+ case RRES_PIXELFORMAT_COMP_ETC1_RGB: image.format = PIXELFORMAT_COMPRESSED_ETC1_RGB; break;
+ case RRES_PIXELFORMAT_COMP_ETC2_RGB: image.format = PIXELFORMAT_COMPRESSED_ETC2_RGB; break;
+ case RRES_PIXELFORMAT_COMP_ETC2_EAC_RGBA: image.format = PIXELFORMAT_COMPRESSED_ETC2_EAC_RGBA; break;
+ case RRES_PIXELFORMAT_COMP_PVRT_RGB: image.format = PIXELFORMAT_COMPRESSED_PVRT_RGB; break;
+ case RRES_PIXELFORMAT_COMP_PVRT_RGBA: image.format = PIXELFORMAT_COMPRESSED_PVRT_RGBA; break;
+ case RRES_PIXELFORMAT_COMP_ASTC_4x4_RGBA: image.format = PIXELFORMAT_COMPRESSED_ASTC_4x4_RGBA; break;
+ case RRES_PIXELFORMAT_COMP_ASTC_8x8_RGBA: image.format = PIXELFORMAT_COMPRESSED_ASTC_8x8_RGBA; break;
+ default: break;
+ }
+
+ image.mipmaps = chunk.data.props[3];
+
+ // Image data size can be computed from image properties
+ unsigned int size = GetPixelDataSize(image.width, image.height, image.format);
+
+ // NOTE: Computed image data must match the data size of the chunk processed (minus propCount + props[4] size)
+ if (size == (chunk.info.baseSize - 20))
+ {
+ image.data = RL_CALLOC(size, 1);
+ if (image.data != NULL) memcpy(image.data, chunk.data.raw, size);
+ }
+ else RRES_LOG("RRES: WARNING: IMGE: Chunk data size do not match expected image data size\n");
+ }
+ else RRES_LOG("RRES: %c%c%c%c: WARNING: Data must be decompressed/decrypted\n", chunk.info.type[0], chunk.info.type[1], chunk.info.type[2], chunk.info.type[3]);
+
+ return image;
+}
+
+// Get file extension from RRES_DATA_RAW properties (unsigned int)
+static const char *GetExtensionFromProps(unsigned int ext01, unsigned int ext02)
+{
+ static char extension[8] = { 0 };
+ memset(extension, 0, 8);
+
+ // Convert file extension provided as 2 unsigned int properties, to a char[] array
+ // NOTE: Extension is defined as 2 unsigned int big-endian values (4 bytes each),
+ // starting with a dot, i.e 0x2e706e67 => ".png"
+ extension[0] = (unsigned char)((ext01 & 0xff000000) >> 24);
+ extension[1] = (unsigned char)((ext01 & 0x00ff0000) >> 16);
+ extension[2] = (unsigned char)((ext01 & 0x0000ff00) >> 8);
+ extension[3] = (unsigned char)(ext01 & 0x000000ff);
+
+ extension[4] = (unsigned char)((ext02 & 0xff000000) >> 24);
+ extension[5] = (unsigned char)((ext02 & 0x00ff0000) >> 16);
+ extension[6] = (unsigned char)((ext02 & 0x0000ff00) >> 8);
+ extension[7] = (unsigned char)(ext02 & 0x000000ff);
+
+ return extension;
+}
+
+// Compute MD5 hash code, returns 4 integers array (static)
+static unsigned int *ComputeMD5(unsigned char *data, int size)
+{
+#define LEFTROTATE(x, c) (((x) << (c)) | ((x) >> (32 - (c))))
+
+ static unsigned int hash[4] = { 0 };
+
+ // NOTE: All variables are unsigned 32 bit and wrap modulo 2^32 when calculating
+
+ // r specifies the per-round shift amounts
+ unsigned int r[] = {
+ 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
+ 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
+ 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
+ 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21
+ };
+
+ // Use binary integer part of the sines of integers (in radians) as constants// Initialize variables:
+ unsigned int k[] = {
+ 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee,
+ 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,
+ 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be,
+ 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,
+ 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa,
+ 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,
+ 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,
+ 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,
+ 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c,
+ 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,
+ 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05,
+ 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
+ 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039,
+ 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
+ 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1,
+ 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391
+ };
+
+ hash[0] = 0x67452301;
+ hash[1] = 0xefcdab89;
+ hash[2] = 0x98badcfe;
+ hash[3] = 0x10325476;
+
+ // Pre-processing: adding a single 1 bit
+ // Append '1' bit to message
+ // NOTE: The input bytes are considered as bits strings,
+ // where the first bit is the most significant bit of the byte
+
+ // Pre-processing: padding with zeros
+ // Append '0' bit until message length in bit 448 (mod 512)
+ // Append length mod (2 pow 64) to message
+
+ int newDataSize = ((((size + 8)/64) + 1)*64) - 8;
+
+ unsigned char *msg = RL_CALLOC(newDataSize + 64, 1); // Also appends "0" bits (we alloc also 64 extra bytes...)
+ memcpy(msg, data, size);
+ msg[size] = 128; // Write the "1" bit
+
+ unsigned int bitsLen = 8*size;
+ memcpy(msg + newDataSize, &bitsLen, 4); // We append the len in bits at the end of the buffer
+
+ // Process the message in successive 512-bit chunks for each 512-bit chunk of message
+ for (int offset = 0; offset < newDataSize; offset += (512/8))
+ {
+ // Break chunk into sixteen 32-bit words w[j], 0 <= j <= 15
+ unsigned int *w = (unsigned int *)(msg + offset);
+
+ // Initialize hash value for this chunk
+ unsigned int a = hash[0];
+ unsigned int b = hash[1];
+ unsigned int c = hash[2];
+ unsigned int d = hash[3];
+
+ for (int i = 0; i < 64; i++)
+ {
+ unsigned int f, g;
+
+ if (i < 16)
+ {
+ f = (b & c) | ((~b) & d);
+ g = i;
+ }
+ else if (i < 32)
+ {
+ f = (d & b) | ((~d) & c);
+ g = (5*i + 1)%16;
+ }
+ else if (i < 48)
+ {
+ f = b ^ c ^ d;
+ g = (3*i + 5)%16;
+ }
+ else
+ {
+ f = c ^ (b | (~d));
+ g = (7*i)%16;
+ }
+
+ unsigned int temp = d;
+ d = c;
+ c = b;
+ b = b + LEFTROTATE((a + f + k[i] + w[g]), r[i]);
+ a = temp;
+ }
+
+ // Add chunk's hash to result so far
+ hash[0] += a;
+ hash[1] += b;
+ hash[2] += c;
+ hash[3] += d;
+ }
+
+ RL_FREE(msg);
+
+ return hash;
+}
+
+#endif // RRES_RAYLIB_IMPLEMENTATION
diff --git a/include/rres.h b/include/rres.h
new file mode 100644
index 0000000..bd91713
--- /dev/null
+++ b/include/rres.h
@@ -0,0 +1,1094 @@
+/**********************************************************************************************
+*
+* rres v1.0 - A simple and easy-to-use file-format to package resources
+*
+* CONFIGURATION:
+*
+* #define RRES_IMPLEMENTATION
+* Generates the implementation of the library into the included file.
+* If not defined, the library is in header only mode and can be included in other headers
+* or source files without problems. But only ONE file should hold the implementation.
+*
+* FEATURES:
+*
+* - Multi-resource files: Some files could end-up generating multiple connected resources in
+* the rres output file (i.e TTF files could generate RRES_DATA_FONT_GLYPHS and RRES_DATA_IMAGE).
+* - File packaging as raw resource data: Avoid data processing and just package the file bytes.
+* - Per-file data compression/encryption: Configure compression/encription for every input file.
+* - Externally linked files: Package only the file path, to be loaded from external file when the
+* specific id is requested. WARNING: Be careful with path, it should be relative to application dir.
+* - Central Directory resource (optional): Create a central directory with the input filename relation
+* to the resource(s) id. This is the default option but it can be avoided; in that case, a header
+* file (.h) is generated with the file ids definitions.
+*
+* FILE STRUCTURE:
+*
+* rres files consist of a file header followed by a number of resource chunks.
+*
+* Optionally it can contain a Central Directory resource chunk (usually at the end) with the info
+* of all the files processed into the rres file.
+*
+* NOTE: Chunks count could not match files count, some processed files (i.e Font, Mesh)
+* could generate multiple chunks with the same id related by the rresResourceChunkInfo.nextOffset
+* Those chunks are loaded together when resource is loaded
+*
+* rresFileHeader (16 bytes)
+* Signature Id (4 bytes) // File signature id: 'rres'
+* Version (2 bytes) // Format version
+* Resource Count (2 bytes) // Number of resource chunks contained
+* CD Offset (4 bytes) // Central Directory offset (if available)
+* Reserved (4 bytes) // <reserved>
+*
+* rresResourceChunk[]
+* {
+* rresResourceChunkInfo (32 bytes)
+* Type (4 bytes) // Resource type (FourCC)
+* Id (4 bytes) // Resource identifier (CRC32 filename hash or custom)
+* Compressor (1 byte) // Data compression algorithm
+* Cipher (1 byte) // Data encryption algorithm
+* Flags (2 bytes) // Data flags (if required)
+* Data Packed Size (4 bytes) // Data packed size (compressed/encrypted + custom data appended)
+* Data Base Size (4 bytes) // Data base size (uncompressed/unencrypted)
+* Next Offset (4 bytes) // Next resource chunk offset (if required)
+* Reserved (4 bytes) // <reserved>
+* CRC32 (4 bytes) // Resource Data Chunk CRC32
+*
+* rresResourceChunkData (n bytes) // Packed data
+* Property Count (4 bytes) // Number of properties contained
+* Properties[] (4*i bytes) // Resource data required properties, depend on Type
+* Data (m bytes) // Resource data
+* }
+*
+* rresResourceChunk: RRES_DATA_DIRECTORY // Central directory (special resource chunk)
+* {
+* rresResourceChunkInfo (32 bytes)
+*
+* rresCentralDir (n bytes) // rresResourceChunkData
+* Entries Count (4 bytes) // Central directory entries count (files)
+* rresDirEntry[]
+* {
+* Id (4 bytes) // Resource id
+* Offset (4 bytes) // Resource global offset in file
+* reserved (4 bytes) // <reserved>
+* FileName Size (4 bytes) // Resource fileName size (NULL terminator and 4-bytes align padding considered)
+* FileName (m bytes) // Resource original fileName (NULL terminated and padded to 4-byte alignment)
+* }
+* }
+*
+* DESIGN DECISIONS / LIMITATIONS:
+*
+* - rres file maximum chunks: 65535 (16bit chunk count in rresFileHeader)
+* - rres file maximum size: 4GB (chunk offset and Central Directory Offset is 32bit, so it can not address more than 4GB
+* - Chunk search by ID is done one by one, starting at first chunk and accessed with fread() function
+* - Endianness: rres does not care about endianness, data is stored as desired by the host platform (most probably Little Endian)
+* Endianness won't affect chunk data but it will affect rresFileHeader and rresResourceChunkInfo
+* - CRC32 hash is used to to generate the rres file identifier from filename
+* There is a "small" probability of random collision (1 in 2^32 approx.) but considering
+* the chance of collision is related to the number of data inputs, not the size of the inputs, we assume that risk
+* Also note that CRC32 is not used as a security/cryptographic hash, just an identifier for the input file
+* - CRC32 hash is also used to detect chunk data corruption. CRC32 is smaller and computationally much less complex than MD5 or SHA1.
+* Using a hash function like MD5 is probably overkill for random error detection
+* - Central Directory rresDirEntry.fileName is NULL terminated and padded to 4-byte, rresDirEntry.fileNameSize considers the padding
+* - Compression and Encryption. rres supports chunks data compression and encryption, it provides two fields in the rresResourceChunkInfo to
+* note it, but in those cases is up to the user to implement the desired compressor/uncompressor and encryption/decryption mechanisms
+* In case of data encryption, it's recommended that any additional resource data (i.e. MAC) to be appended to data chunk and properly
+* noted in the packed data size field of rresResourceChunkInfo. Data compression should be applied before encryption.
+*
+* DEPENDENCIES:
+*
+* rres library dependencies has been keep to the minimum. It depends only some libc functionality:
+*
+* - stdlib.h: Required for memory allocation: malloc(), calloc(), free()
+* NOTE: Allocators can be redefined with macros RRES_MALLOC, RRES_CALLOC, RRES_FREE
+* - stdio.h: Required for file access functionality: FILE, fopen(), fseek(), fread(), fclose()
+* - string.h: Required for memory data management: memcpy(), memcmp()
+*
+* VERSION HISTORY:
+*
+* - 1.0 (12-May-2022): Implementation review for better alignment with rres specs
+* - 0.9 (28-Apr-2022): Initial implementation of rres specs
+*
+*
+* LICENSE: MIT
+*
+* Copyright (c) 2016-2022 Ramon Santamaria (@raysan5)
+*
+* Permission is hereby granted, free of charge, to any person obtaining a copy
+* of this software and associated documentation files (the "Software"), to deal
+* in the Software without restriction, including without limitation the rights
+* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+* copies of the Software, and to permit persons to whom the Software is
+* furnished to do so, subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all
+* copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+* SOFTWARE.
+*
+**********************************************************************************************/
+
+#ifndef RRES_H
+#define RRES_H
+
+// Function specifiers in case library is build/used as a shared library (Windows)
+// NOTE: Microsoft specifiers to tell compiler that symbols are imported/exported from a .dll
+#if defined(_WIN32)
+ #if defined(BUILD_LIBTYPE_SHARED)
+ #define RRESAPI __declspec(dllexport) // We are building the library as a Win32 shared library (.dll)
+ #elif defined(USE_LIBTYPE_SHARED)
+ #define RRESAPI __declspec(dllimport) // We are using the library as a Win32 shared library (.dll)
+ #endif
+#endif
+
+// Function specifiers definition
+#ifndef RRESAPI
+ #define RRESAPI // Functions defined as 'extern' by default (implicit specifiers)
+#endif
+
+//----------------------------------------------------------------------------------
+// Defines and Macros
+//----------------------------------------------------------------------------------
+
+// Allow custom memory allocators
+#ifndef RRES_MALLOC
+ #define RRES_MALLOC(sz) malloc(sz)
+#endif
+#ifndef RRES_CALLOC
+ #define RRES_CALLOC(ptr,sz) calloc(ptr,sz)
+#endif
+#ifndef RRES_REALLOC
+ #define RRES_REALLOC(ptr,sz) realloc(ptr,sz)
+#endif
+#ifndef RRES_FREE
+ #define RRES_FREE(ptr) free(ptr)
+#endif
+
+// Simple log system to avoid printf() calls if required
+// NOTE: Avoiding those calls, also avoids const strings memory usage
+#define RRES_SUPPORT_LOG_INFO
+#if defined(RRES_SUPPORT_LOG_INFO)
+ #define RRES_LOG(...) printf(__VA_ARGS__)
+#else
+ #define RRES_LOG(...)
+#endif
+
+// On Windows, MAX_PATH is limited to 256 by default,
+// on Linux, it could go up to 4096
+#define RRES_MAX_FILENAME_SIZE 1024
+
+//----------------------------------------------------------------------------------
+// Types and Structures Definition
+//----------------------------------------------------------------------------------
+// rres file header (16 bytes)
+typedef struct rresFileHeader {
+ unsigned char id[4]; // File identifier: rres
+ unsigned short version; // File version: 100 for version 1.0
+ unsigned short chunkCount; // Number of resource chunks in the file (MAX: 65535)
+ unsigned int cdOffset; // Central Directory offset in file (0 if not available)
+ unsigned int reserved; // <reserved>
+} rresFileHeader;
+
+// rres resource chunk info header (32 bytes)
+typedef struct rresResourceChunkInfo {
+ unsigned char type[4]; // Resource chunk type (FourCC)
+ unsigned int id; // Resource chunk identifier (generated from filename CRC32 hash)
+ unsigned char compType; // Data compression algorithm
+ unsigned char cipherType; // Data encription algorithm
+ unsigned short flags; // Data flags (if required)
+ unsigned int packedSize; // Data chunk size (compressed/encrypted + custom data appended)
+ unsigned int baseSize; // Data base size (uncompressed/unencrypted)
+ unsigned int nextOffset; // Next resource chunk global offset (if resource has multiple chunks)
+ unsigned int reserved; // <reserved>
+ unsigned int crc32; // Data chunk CRC32 (propCount + props[] + data)
+} rresResourceChunkInfo;
+
+// rres resource chunk data
+typedef struct rresResourceChunkData {
+ unsigned int propCount; // Resource chunk properties count
+ unsigned int *props; // Resource chunk properties
+ void *raw; // Resource chunk raw data
+} rresResourceChunkData;
+
+// rres resource chunk
+typedef struct rresResourceChunk {
+ rresResourceChunkInfo info; // Resource chunk info
+ rresResourceChunkData data; // Resource chunk packed data, contains propCount, props[] and raw data
+} rresResourceChunk;
+
+// rres resource multi
+// NOTE: It supports multiple resource chunks
+typedef struct rresResourceMulti {
+ unsigned int count; // Resource chunks count
+ rresResourceChunk *chunks; // Resource chunks
+} rresResourceMulti;
+
+// Useful data types for specific chunk types
+//----------------------------------------------------------------------
+// CDIR: rres central directory entry
+typedef struct rresDirEntry {
+ unsigned int id; // Resource id
+ unsigned int offset; // Resource global offset in file
+ unsigned int reserved; // reserved
+ unsigned int fileNameSize; // Resource fileName size (NULL terminator and 4-byte alignment padding considered)
+ char fileName[RRES_MAX_FILENAME_SIZE]; // Resource original fileName (NULL terminated and padded to 4-byte alignment)
+} rresDirEntry;
+
+// CDIR: rres central directory
+// NOTE: This data conforms the rresResourceChunkData
+typedef struct rresCentralDir {
+ unsigned int count; // Central directory entries count
+ rresDirEntry *entries; // Central directory entries
+} rresCentralDir;
+
+// FNTG: rres font glyphs info (32 bytes)
+// NOTE: And array of this type conforms the rresResourceChunkData
+typedef struct rresFontGlyphInfo {
+ int x, y, width, height; // Glyph rectangle in the atlas image
+ int value; // Glyph codepoint value
+ int offsetX, offsetY; // Glyph drawing offset (from base line)
+ int advanceX; // Glyph advance X for next character
+} rresFontGlyphInfo;
+
+//----------------------------------------------------------------------------------
+// Enums Definition
+// The following enums are useful to fill some fields of the rresResourceChunkInfo
+// and also some fields of the different data types properties
+//----------------------------------------------------------------------------------
+
+// rres resource chunk data type
+// NOTE 1: Data type determines the properties and the data included in every chunk
+// NOTE 2: This enum defines the basic resource data types,
+// some input files could generate multiple resource chunks:
+// Fonts processed could generate (2) resource chunks:
+// - [FNTG] rres[0]: RRES_DATA_FONT_GLYPHS
+// - [IMGE] rres[1]: RRES_DATA_IMAGE
+//
+// Mesh processed could generate (n) resource chunks:
+// - [VRTX] rres[0]: RRES_DATA_VERTEX
+// ...
+// - [VRTX] rres[n]: RRES_DATA_VERTEX
+typedef enum rresResourceDataType {
+ RRES_DATA_NULL = 0, // FourCC: NULL - Reserved for empty chunks, no props/data
+ RRES_DATA_RAW = 1, // FourCC: RAWD - Raw file data, 4 properties
+ // props[0]:size (bytes)
+ // props[1]:extension01 (big-endian: ".png" = 0x2e706e67)
+ // props[2]:extension02 (additional part, extensions with +3 letters)
+ // props[3]:reserved
+ // data: raw bytes
+ RRES_DATA_TEXT = 2, // FourCC: TEXT - Text file data, 4 properties
+ // props[0]:size (bytes)
+ // props[1]:rresTextEncoding
+ // props[2]:rresCodeLang
+ // props[3]:cultureCode
+ // data: text
+ RRES_DATA_IMAGE = 3, // FourCC: IMGE - Image file data, 4 properties
+ // props[0]:width
+ // props[1]:height
+ // props[2]:rresPixelFormat
+ // props[3]:mipmaps
+ // data: pixels
+ RRES_DATA_WAVE = 4, // FourCC: WAVE - Audio file data, 4 properties
+ // props[0]:frameCount
+ // props[1]:sampleRate
+ // props[2]:sampleSize
+ // props[3]:channels
+ // data: samples
+ RRES_DATA_VERTEX = 5, // FourCC: VRTX - Vertex file data, 4 properties
+ // props[0]:vertexCount
+ // props[1]:rresVertexAttribute
+ // props[2]:componentCount
+ // props[3]:rresVertexFormat
+ // data: vertex
+ RRES_DATA_FONT_GLYPHS = 6, // FourCC: FNTG - Font glyphs info data, 4 properties
+ // props[0]:baseSize
+ // props[1]:glyphCount
+ // props[2]:glyphPadding
+ // props[3]:rresFontStyle
+ // data: rresFontGlyphInfo[0..glyphCount]
+ RRES_DATA_LINK = 99, // FourCC: LINK - External linked file, 1 property
+ // props[0]:size (bytes)
+ // data: filepath (as provided on input)
+ RRES_DATA_DIRECTORY = 100, // FourCC: CDIR - Central directory for input files
+ // props[0]:entryCount, 1 property
+ // data: rresDirEntry[0..entryCount]
+
+ // TODO: 2.0: Support resource package types (muti-resource)
+ // NOTE: They contains multiple rresResourceChunk in rresResourceData.raw
+ //RRES_DATA_PACK_FONT = 110, // FourCC: PFNT - Resources Pack: Font data, 1 property (2 resource chunks: RRES_DATA_GLYPHS, RRES_DATA_IMAGE)
+ // props[0]:chunkCount
+ //RRES_DATA_PACK_MESH = 120, // FourCC: PMSH - Resources Pack: Mesh data, 1 property (n resource chunks: RRES_DATA_VERTEX)
+ // props[0]:chunkCount
+
+ // TODO: Add additional resource data types if required (define props + data)
+
+} rresResourceDataType;
+
+// Compression algorithms
+// Value required by rresResourceChunkInfo.compType
+// NOTE 1: This enum just list some common data compression algorithms for convenience,
+// The rres packer tool and the engine-specific library are responsible to implement the desired ones,
+// NOTE 2: rresResourceChunkInfo.compType is a byte-size value, limited to [0..255]
+typedef enum rresCompressionType {
+ RRES_COMP_NONE = 0, // No data compression
+ RRES_COMP_RLE = 1, // RLE compression
+ RRES_COMP_DEFLATE = 10, // DEFLATE compression
+ RRES_COMP_LZ4 = 20, // LZ4 compression
+ RRES_COMP_LZMA2 = 30, // LZMA2 compression
+ RRES_COMP_QOI = 40, // QOI compression, useful for RGB(A) image data
+ // TODO: Add additional compression algorithms if required
+} rresCompressionType;
+
+// Encryption algoritms
+// Value required by rresResourceChunkInfo.cipherType
+// NOTE 1: This enum just lists some common data encryption algorithms for convenience,
+// The rres packer tool and the engine-specific library are responsible to implement the desired ones,
+// NOTE 2: Some encryption algorithm could require/generate additional data (seed, salt, nonce, MAC...)
+// in those cases, that extra data must be appended to the original encrypted message and added to the resource data chunk
+// NOTE 3: rresResourceChunkInfo.cipherType is a byte-size value, limited to [0..255]
+typedef enum rresEncryptionType {
+ RRES_CIPHER_NONE = 0, // No data encryption
+ RRES_CIPHER_XOR = 1, // XOR encryption, generic using 128bit key in blocks
+ RRES_CIPHER_DES = 10, // DES encryption
+ RRES_CIPHER_TDES = 11, // Triple DES encryption
+ RRES_CIPHER_IDEA = 20, // IDEA encryption
+ RRES_CIPHER_AES = 30, // AES (128bit or 256bit) encryption
+ RRES_CIPHER_AES_GCM = 31, // AES Galois/Counter Mode (Galois Message Authentification Code - GMAC)
+ RRES_CIPHER_XTEA = 40, // XTEA encryption
+ RRES_CIPHER_BLOWFISH = 50, // BLOWFISH encryption
+ RRES_CIPHER_RSA = 60, // RSA asymmetric encryption
+ RRES_CIPHER_SALSA20 = 70, // SALSA20 encryption
+ RRES_CIPHER_CHACHA20 = 71, // CHACHA20 encryption
+ RRES_CIPHER_XCHACHA20 = 72, // XCHACHA20 encryption
+ RRES_CIPHER_XCHACHA20_POLY1305 = 73, // XCHACHA20 with POLY1305 for message authentification (MAC)
+ // TODO: Add additional encryption algorithm if required
+} rresEncryptionType;
+
+// TODO: rres error codes (not used at this moment)
+// NOTE: Error codes when processing rres files
+typedef enum rresErrorType {
+ RRES_SUCCESS = 0, // rres file loaded/saved successfully
+ RRES_ERROR_FILE_NOT_FOUND, // rres file can not be opened (spelling issues, file actually does not exist...)
+ RRES_ERROR_FILE_FORMAT, // rres file format not a supported (wrong header, wrong identifier)
+ RRES_ERROR_MEMORY_ALLOC, // Memory could not be allocated for operation.
+} rresErrorType;
+
+// Enums required by specific resource types for its properties
+//----------------------------------------------------------------------------------
+// TEXT: Text encoding property values
+typedef enum rresTextEncoding {
+ RRES_TEXT_ENCODING_UNDEFINED = 0, // Not defined, usually UTF-8
+ RRES_TEXT_ENCODING_UTF8 = 1, // UTF-8 text encoding
+ RRES_TEXT_ENCODING_UTF8_BOM = 2, // UTF-8 text encoding with Byte-Order-Mark
+ RRES_TEXT_ENCODING_UTF16_LE = 10, // UTF-16 Little Endian text encoding
+ RRES_TEXT_ENCODING_UTF16_BE = 11, // UTF-16 Big Endian text encoding
+ // TODO: Add additional encodings if required
+} rresTextEncoding;
+
+// TEXT: Text code language
+// NOTE: It could be useful for code script resources
+typedef enum rresCodeLang {
+ RRES_CODE_LANG_UNDEFINED = 0, // Undefined code language, text is plain text
+ RRES_CODE_LANG_C, // Text contains C code
+ RRES_CODE_LANG_CPP, // Text contains C++ code
+ RRES_CODE_LANG_CS, // Text contains C# code
+ RRES_CODE_LANG_LUA, // Text contains Lua code
+ RRES_CODE_LANG_JS, // Text contains JavaScript code
+ RRES_CODE_LANG_PYTHON, // Text contains Python code
+ RRES_CODE_LANG_RUST, // Text contains Rust code
+ RRES_CODE_LANG_ZIG, // Text contains Zig code
+ RRES_CODE_LANG_ODIN, // Text contains Odin code
+ RRES_CODE_LANG_JAI, // Text contains Jai code
+ RRES_CODE_LANG_GDSCRIPT, // Text contains GDScript (Godot) code
+ RRES_CODE_LANG_GLSL, // Text contains GLSL shader code
+ // TODO: Add additional code languages if required
+} rresCodeLang;
+
+// IMGE: Image/Texture pixel formats
+typedef enum rresPixelFormat {
+ RRES_PIXELFORMAT_UNDEFINED = 0,
+ RRES_PIXELFORMAT_UNCOMP_GRAYSCALE = 1, // 8 bit per pixel (no alpha)
+ RRES_PIXELFORMAT_UNCOMP_GRAY_ALPHA, // 16 bpp (2 channels)
+ RRES_PIXELFORMAT_UNCOMP_R5G6B5, // 16 bpp
+ RRES_PIXELFORMAT_UNCOMP_R8G8B8, // 24 bpp
+ RRES_PIXELFORMAT_UNCOMP_R5G5B5A1, // 16 bpp (1 bit alpha)
+ RRES_PIXELFORMAT_UNCOMP_R4G4B4A4, // 16 bpp (4 bit alpha)
+ RRES_PIXELFORMAT_UNCOMP_R8G8B8A8, // 32 bpp
+ RRES_PIXELFORMAT_UNCOMP_R32, // 32 bpp (1 channel - float)
+ RRES_PIXELFORMAT_UNCOMP_R32G32B32, // 32*3 bpp (3 channels - float)
+ RRES_PIXELFORMAT_UNCOMP_R32G32B32A32, // 32*4 bpp (4 channels - float)
+ RRES_PIXELFORMAT_COMP_DXT1_RGB, // 4 bpp (no alpha)
+ RRES_PIXELFORMAT_COMP_DXT1_RGBA, // 4 bpp (1 bit alpha)
+ RRES_PIXELFORMAT_COMP_DXT3_RGBA, // 8 bpp
+ RRES_PIXELFORMAT_COMP_DXT5_RGBA, // 8 bpp
+ RRES_PIXELFORMAT_COMP_ETC1_RGB, // 4 bpp
+ RRES_PIXELFORMAT_COMP_ETC2_RGB, // 4 bpp
+ RRES_PIXELFORMAT_COMP_ETC2_EAC_RGBA, // 8 bpp
+ RRES_PIXELFORMAT_COMP_PVRT_RGB, // 4 bpp
+ RRES_PIXELFORMAT_COMP_PVRT_RGBA, // 4 bpp
+ RRES_PIXELFORMAT_COMP_ASTC_4x4_RGBA, // 8 bpp
+ RRES_PIXELFORMAT_COMP_ASTC_8x8_RGBA // 2 bpp
+ // TOO: Add additional pixel formats if required
+} rresPixelFormat;
+
+// VRTX: Vertex data attribute
+// NOTE: The expected number of components for every vertex attributes is provided as a property to data,
+// the listed components count are the expected/default ones
+typedef enum rresVertexAttribute {
+ RRES_VERTEX_ATTRIBUTE_POSITION = 0, // Vertex position attribute: [x, y, z]
+ RRES_VERTEX_ATTRIBUTE_TEXCOORD1 = 10, // Vertex texture coordinates attribute: [u, v]
+ RRES_VERTEX_ATTRIBUTE_TEXCOORD2 = 11, // Vertex texture coordinates attribute: [u, v]
+ RRES_VERTEX_ATTRIBUTE_TEXCOORD3 = 12, // Vertex texture coordinates attribute: [u, v]
+ RRES_VERTEX_ATTRIBUTE_TEXCOORD4 = 13, // Vertex texture coordinates attribute: [u, v]
+ RRES_VERTEX_ATTRIBUTE_NORMAL = 20, // Vertex normal attribute: [x, y, z]
+ RRES_VERTEX_ATTRIBUTE_TANGENT = 30, // Vertex tangent attribute: [x, y, z, w]
+ RRES_VERTEX_ATTRIBUTE_COLOR = 40, // Vertex color attribute: [r, g, b, a]
+ RRES_VERTEX_ATTRIBUTE_INDEX = 100, // Vertex index attribute: [i]
+ // TODO: Add additional attributes if required
+} rresVertexAttribute;
+
+// VRTX: Vertex data format type
+typedef enum rresVertexFormat {
+ RRES_VERTEX_FORMAT_UBYTE = 0, // 8 bit unsigned integer data
+ RRES_VERTEX_FORMAT_BYTE, // 8 bit signed integer data
+ RRES_VERTEX_FORMAT_USHORT, // 16 bit unsigned integer data
+ RRES_VERTEX_FORMAT_SHORT, // 16 bit signed integer data
+ RRES_VERTEX_FORMAT_UINT, // 32 bit unsigned integer data
+ RRES_VERTEX_FORMAT_INT, // 32 bit integer data
+ RRES_VERTEX_FORMAT_HFLOAT, // 16 bit float data
+ RRES_VERTEX_FORMAT_FLOAT, // 32 bit float data
+ // TODO: Add additional required vertex formats (i.e. normalized data)
+} rresVertexFormat;
+
+// FNTG: Font style
+typedef enum rresFontStyle {
+ RRES_FONT_STYLE_UNDEFINED = 0, // Undefined font style
+ RRES_FONT_STYLE_REGULAR, // Regular font style
+ RRES_FONT_STYLE_BOLD, // Bold font style
+ RRES_FONT_STYLE_ITALIC, // Italic font style
+ // TODO: Add additional font styles if required
+} rresFontStyle;
+
+//----------------------------------------------------------------------------------
+// Global variables
+//----------------------------------------------------------------------------------
+//...
+
+//----------------------------------------------------------------------------------
+// Module Functions Declaration
+//----------------------------------------------------------------------------------
+#ifdef __cplusplus
+extern "C" { // Prevents name mangling of functions
+#endif
+
+// Load only one resource chunk (first resource id found)
+RRESAPI rresResourceChunk rresLoadResourceChunk(const char *fileName, int rresId); // Load one resource chunk for provided id
+RRESAPI void rresUnloadResourceChunk(rresResourceChunk chunk); // Unload resource chunk from memory
+
+// Load multi resource chunks for a specified rresId
+RRESAPI rresResourceMulti rresLoadResourceMulti(const char *fileName, int rresId); // Load resource for provided id (multiple resource chunks)
+RRESAPI void rresUnloadResourceMulti(rresResourceMulti multi); // Unload resource from memory (multiple resource chunks)
+
+// Load resource(s) chunk info from file
+RRESAPI rresResourceChunkInfo rresLoadResourceChunkInfo(const char *fileName, int rresId); // Load resource chunk info for provided id
+RRESAPI rresResourceChunkInfo *rresLoadResourceChunkInfoAll(const char *fileName, unsigned int *chunkCount); // Load all resource chunks info
+
+RRESAPI rresCentralDir rresLoadCentralDirectory(const char *fileName); // Load central directory resource chunk from file
+RRESAPI void rresUnloadCentralDirectory(rresCentralDir dir); // Unload central directory resource chunk
+
+RRESAPI unsigned int rresGetDataType(const unsigned char *fourCC); // Get rresResourceDataType from FourCC code
+RRESAPI int rresGetResourceId(rresCentralDir dir, const char *fileName); // Get resource id for a provided filename
+ // NOTE: It requires CDIR available in the file (it's optinal by design)
+RRESAPI unsigned int rresComputeCRC32(unsigned char *data, int len); // Compute CRC32 for provided data
+
+// Manage password for data encryption/decryption
+// NOTE: The cipher password is kept as an internal pointer to provided string, it's up to the user to manage that sensible data properly
+// Password should be to allocate and set before loading an encrypted resource and it should be cleaned/wiped after the encrypted resource has been loaded
+// TODO: Move this functionality to engine-library, after all rres.h does not manage data decryption
+RRESAPI void rresSetCipherPassword(const char *pass); // Set password to be used on data decryption
+RRESAPI const char *rresGetCipherPassword(void); // Get password to be used on data decryption
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // RRES_H
+
+
+/***********************************************************************************
+*
+* RRES IMPLEMENTATION
+*
+************************************************************************************/
+
+#if defined(RRES_IMPLEMENTATION)
+
+// Boolean type
+#if (defined(__STDC__) && __STDC_VERSION__ >= 199901L) || (defined(_MSC_VER) && _MSC_VER >= 1800)
+ #include <stdbool.h>
+#elif !defined(__cplusplus) && !defined(bool)
+ typedef enum bool { false = 0, true = !false } bool;
+ #define RL_BOOL_TYPE
+#endif
+
+#include <stdlib.h> // Required for: malloc(), free()
+#include <stdio.h> // Required for: FILE, fopen(), fseek(), fread(), fclose()
+#include <string.h> // Required for: memcpy(), memcmp()
+
+//----------------------------------------------------------------------------------
+// Defines and Macros
+//----------------------------------------------------------------------------------
+//...
+
+//----------------------------------------------------------------------------------
+// Types and Structures Definition
+//----------------------------------------------------------------------------------
+//...
+
+//----------------------------------------------------------------------------------
+// Global Variables Definition
+//----------------------------------------------------------------------------------
+static const char *password = NULL; // Password pointer, managed by user libraries
+
+//----------------------------------------------------------------------------------
+// Module Internal Functions Declaration
+//----------------------------------------------------------------------------------
+// Load resource chunk packed data into our data struct
+static rresResourceChunkData rresLoadResourceChunkData(rresResourceChunkInfo info, void *packedData);
+
+//----------------------------------------------------------------------------------
+// Module Functions Definition
+//----------------------------------------------------------------------------------
+// Load one resource chunk for provided id
+rresResourceChunk rresLoadResourceChunk(const char *fileName, int rresId)
+{
+ rresResourceChunk chunk = { 0 };
+
+ FILE *rresFile = fopen(fileName, "rb");
+
+ if (rresFile == NULL) RRES_LOG("RRES: WARNING: [%s] rres file could not be opened\n", fileName);
+ else
+ {
+ RRES_LOG("RRES: INFO: Loading resource from file: %s\n", fileName);
+
+ rresFileHeader header = { 0 };
+
+ // Read rres file header
+ fread(&header, sizeof(rresFileHeader), 1, rresFile);
+
+ // Verify file signature: "rres" and file version: 100
+ if (((header.id[0] == 'r') && (header.id[1] == 'r') && (header.id[2] == 'e') && (header.id[3] == 's')) && (header.version == 100))
+ {
+ bool found = false;
+
+ // Check all available chunks looking for the requested id
+ for (int i = 0; i < header.chunkCount; i++)
+ {
+ rresResourceChunkInfo info = { 0 };
+
+ // Read resource info header
+ fread(&info, sizeof(rresResourceChunkInfo), 1, rresFile);
+
+ // Check if resource id is the requested one
+ if (info.id == rresId)
+ {
+ found = true;
+
+ RRES_LOG("RRES: INFO: Found requested resource id: 0x%08x\n", info.id);
+ RRES_LOG("RRES: %c%c%c%c: Id: 0x%08x | Base size: %i | Packed size: %i\n", info.type[0], info.type[1], info.type[2], info.type[3], info.id, info.baseSize, info.packedSize);
+
+ // NOTE: We only load first matching id resource chunk found but
+ // we show a message if additional chunks are detected
+ if (info.nextOffset != 0) RRES_LOG("RRES: WARNING: Multiple linked resource chunks available for the provided id");
+
+ /*
+ // Variables required to check multiple chunks
+ int chunkCount = 0;
+ long currentFileOffset = ftell(rresFile); // Store current file position
+ rresResourceChunkInfo temp = info; // Temp info header to scan resource chunks
+
+ // Count all linked resource chunks checking temp.nextOffset
+ while (temp.nextOffset != 0)
+ {
+ fseek(rresFile, temp.nextOffset, SEEK_SET); // Jump to next linked resource
+ fread(&temp, sizeof(rresResourceChunkInfo), 1, rresFile); // Read next resource info header
+ chunkCount++;
+ }
+
+ fseek(rresFile, currentFileOffset, SEEK_SET); // Return to first resource chunk position
+ */
+
+ // Read and resource chunk from file data
+ // NOTE: Read data can be compressed/encrypted, it's up to the user library to manage decompression/decryption
+ void *data = RRES_MALLOC(info.packedSize); // Allocate enough memory to store resource data chunk
+ fread(data, info.packedSize, 1, rresFile); // Read data: propsCount + props[] + data (+additional_data)
+
+ // Get chunk.data properly organized (only if uncompressed/unencrypted)
+ chunk.data = rresLoadResourceChunkData(info, data);
+ chunk.info = info;
+
+ RRES_FREE(data);
+
+ break; // Resource id found and loaded, stop checking the file
+ }
+ else
+ {
+ // Skip required data size to read next resource info header
+ fseek(rresFile, info.packedSize, SEEK_CUR);
+ }
+ }
+
+ if (!found) RRES_LOG("RRES: WARNING: Requested resource not found: 0x%08x\n", rresId);
+ }
+ else RRES_LOG("RRES: WARNING: The provided file is not a valid rres file, file signature or version not valid\n");
+
+ fclose(rresFile);
+ }
+
+ return chunk;
+}
+
+// Unload resource chunk from memory
+void rresUnloadResourceChunk(rresResourceChunk chunk)
+{
+ RRES_FREE(chunk.data.props); // Resource chunk properties
+ RRES_FREE(chunk.data.raw); // Resource chunk raw data
+}
+
+// Load resource from file by id
+// NOTE: All resources conected to base id are loaded
+rresResourceMulti rresLoadResourceMulti(const char *fileName, int rresId)
+{
+ rresResourceMulti rres = { 0 };
+
+ FILE *rresFile = fopen(fileName, "rb");
+
+ if (rresFile == NULL) RRES_LOG("RRES: WARNING: [%s] rres file could not be opened\n", fileName);
+ else
+ {
+ rresFileHeader header = { 0 };
+
+ // Read rres file header
+ fread(&header, sizeof(rresFileHeader), 1, rresFile);
+
+ // Verify file signature: "rres" and file version: 100
+ if (((header.id[0] == 'r') && (header.id[1] == 'r') && (header.id[2] == 'e') && (header.id[3] == 's')) && (header.version == 100))
+ {
+ bool found = false;
+
+ // Check all available chunks looking for the requested id
+ for (int i = 0; i < header.chunkCount; i++)
+ {
+ rresResourceChunkInfo info = { 0 };
+
+ // Read resource info header
+ fread(&info, sizeof(rresResourceChunkInfo), 1, rresFile);
+
+ // Check if resource id is the requested one
+ if (info.id == rresId)
+ {
+ found = true;
+
+ RRES_LOG("RRES: INFO: Found requested resource id: 0x%08x\n", info.id);
+ RRES_LOG("RRES: %c%c%c%c: Id: 0x%08x | Base size: %i | Packed size: %i\n", info.type[0], info.type[1], info.type[2], info.type[3], info.id, info.baseSize, info.packedSize);
+
+ rres.count = 1;
+
+ long currentFileOffset = ftell(rresFile); // Store current file position
+ rresResourceChunkInfo temp = info; // Temp info header to scan resource chunks
+
+ // Count all linked resource chunks checking temp.nextOffset
+ while (temp.nextOffset != 0)
+ {
+ fseek(rresFile, temp.nextOffset, SEEK_SET); // Jump to next linked resource
+ fread(&temp, sizeof(rresResourceChunkInfo), 1, rresFile); // Read next resource info header
+ rres.count++;
+ }
+
+ rres.chunks = (rresResourceChunk *)RRES_CALLOC(rres.count, sizeof(rresResourceChunk)); // Load as many rres slots as required
+ fseek(rresFile, currentFileOffset, SEEK_SET); // Return to first resource chunk position
+
+ // Read and load data chunk from file data
+ // NOTE: Read data can be compressed/encrypted,
+ // it's up to the user library to manage decompression/decryption
+ void *data = RRES_MALLOC(info.packedSize); // Allocate enough memory to store resource data chunk
+ fread(data, info.packedSize, 1, rresFile); // Read data: propsCount + props[] + data (+additional_data)
+
+ // Get chunk.data properly organized (only if uncompressed/unencrypted)
+ rres.chunks[0].data = rresLoadResourceChunkData(info, data);
+ rres.chunks[0].info = info;
+
+ RRES_FREE(data);
+
+ int i = 1;
+
+ // Load all linked resource chunks
+ while (info.nextOffset != 0)
+ {
+ fseek(rresFile, info.nextOffset, SEEK_SET); // Jump to next resource chunk
+ fread(&info, sizeof(rresResourceChunkInfo), 1, rresFile); // Read next resource info header
+
+ RRES_LOG("RRES: %c%c%c%c: Id: 0x%08x | Base size: %i | Packed size: %i\n", info.type[0], info.type[1], info.type[2], info.type[3], info.id, info.baseSize, info.packedSize);
+
+ void *data = RRES_MALLOC(info.packedSize); // Allocate enough memory to store resource data chunk
+ fread(data, info.packedSize, 1, rresFile); // Read data: propsCount + props[] + data (+additional_data)
+
+ // Get chunk.data properly organized (only if uncompressed/unencrypted)
+ rres.chunks[i].data = rresLoadResourceChunkData(info, data);
+ rres.chunks[i].info = info;
+
+ RRES_FREE(data);
+
+ i++;
+ }
+
+ break; // Resource id found and loaded, stop checking the file
+ }
+ else
+ {
+ // Skip required data size to read next resource info header
+ fseek(rresFile, info.packedSize, SEEK_CUR);
+ }
+ }
+
+ if (!found) RRES_LOG("RRES: WARNING: Requested resource not found: 0x%08x\n", rresId);
+ }
+ else RRES_LOG("RRES: WARNING: The provided file is not a valid rres file, file signature or version not valid\n");
+
+ fclose(rresFile);
+ }
+
+ return rres;
+}
+
+// Unload resource data
+void rresUnloadResourceMulti(rresResourceMulti multi)
+{
+ for (unsigned int i = 0; i < multi.count; i++) rresUnloadResourceChunk(multi.chunks[i]);
+
+ RRES_FREE(multi.chunks);
+}
+
+// Load resource chunk info for provided id
+RRESAPI rresResourceChunkInfo rresLoadResourceChunkInfo(const char *fileName, int rresId)
+{
+ rresResourceChunkInfo info = { 0 };
+
+ FILE *rresFile = fopen(fileName, "rb");
+
+ if (rresFile != NULL)
+ {
+ rresFileHeader header = { 0 };
+
+ fread(&header, sizeof(rresFileHeader), 1, rresFile);
+
+ // Verify file signature: "rres", file version: 100
+ if (((header.id[0] == 'r') && (header.id[1] == 'r') && (header.id[2] == 'e') && (header.id[3] == 's')) && (header.version == 100))
+ {
+ // Try to find provided resource chunk id and read info chunk
+ for (int i = 0; i < header.chunkCount; i++)
+ {
+ // Read resource chunk info
+ fread(&info, sizeof(rresResourceChunkInfo), 1, rresFile);
+
+ if (info.id == rresId)
+ {
+ // TODO: Jump to next resource chunk for provided id
+ //if (info.nextOffset > 0) fseek(rresFile, info.nextOffset, SEEK_SET);
+
+ break; // If requested rresId is found, we return the read rresResourceChunkInfo
+ }
+ else fseek(rresFile, info.packedSize, SEEK_CUR); // Jump to next resource
+ }
+ }
+ else RRES_LOG("RRES: WARNING: The provided file is not a valid rres file, file signature or version not valid\n");
+
+ fclose(rresFile);
+ }
+
+ return info;
+}
+
+// Load all resource chunks info
+RRESAPI rresResourceChunkInfo *rresLoadResourceChunkInfoAll(const char *fileName, unsigned int *chunkCount)
+{
+ rresResourceChunkInfo *infos = { 0 };
+ unsigned int count = 0;
+
+ FILE *rresFile = fopen(fileName, "rb");
+
+ if (rresFile != NULL)
+ {
+ rresFileHeader header = { 0 };
+
+ fread(&header, sizeof(rresFileHeader), 1, rresFile);
+
+ // Verify file signature: "rres", file version: 100
+ if (((header.id[0] == 'r') && (header.id[1] == 'r') && (header.id[2] == 'e') && (header.id[3] == 's')) && (header.version == 100))
+ {
+ // Load all resource chunks info
+ infos = (rresResourceChunkInfo *)RRES_CALLOC(header.chunkCount, sizeof(rresResourceChunkInfo));
+ count = header.chunkCount;
+
+ for (unsigned int i = 0; i < count; i++)
+ {
+ fread(&infos[i], sizeof(rresResourceChunkInfo), 1, rresFile); // Read resource chunk info
+
+ if (infos[i].nextOffset > 0) fseek(rresFile, infos[i].nextOffset, SEEK_SET); // Jump to next resource
+ else fseek(rresFile, infos[i].packedSize, SEEK_CUR); // Jump to next resource
+ }
+ }
+ else RRES_LOG("RRES: WARNING: The provided file is not a valid rres file, file signature or version not valid\n");
+
+ fclose(rresFile);
+ }
+
+ *chunkCount = count;
+ return infos;
+}
+
+// Load central directory data
+rresCentralDir rresLoadCentralDirectory(const char *fileName)
+{
+ rresCentralDir dir = { 0 };
+
+ FILE *rresFile = fopen(fileName, "rb");
+
+ if (rresFile != NULL)
+ {
+ rresFileHeader header = { 0 };
+
+ fread(&header, sizeof(rresFileHeader), 1, rresFile);
+
+ // Verify file signature: "rres", file version: 100
+ if (((header.id[0] == 'r') && (header.id[1] == 'r') && (header.id[2] == 'e') && (header.id[3] == 's')) && (header.version == 100))
+ {
+ // Check if there is a Central Directory available
+ if (header.cdOffset == 0) RRES_LOG("RRES: WARNING: CDIR: No central directory found\n");
+ else
+ {
+ rresResourceChunkInfo info = { 0 };
+
+ fseek(rresFile, header.cdOffset, SEEK_CUR); // Move to central directory position
+ fread(&info, sizeof(rresResourceChunkInfo), 1, rresFile); // Read resource info
+
+ // Verify resource type is CDIR
+ if ((info.type[0] == 'C') && (info.type[1] == 'D') && (info.type[2] == 'I') && (info.type[3] == 'R'))
+ {
+ RRES_LOG("RRES: CDIR: Central Directory found at offset: 0x%08x\n", header.cdOffset);
+
+ void *data = RRES_MALLOC(info.packedSize);
+ fread(data, info.packedSize, 1, rresFile);
+
+ // Load resource chunk data (central directory), data is uncompressed/unencrypted by default
+ rresResourceChunkData chunkData = rresLoadResourceChunkData(info, data);
+ RRES_FREE(data);
+
+ dir.count = chunkData.props[0]; // File entries count
+
+ RRES_LOG("RRES: CDIR: Central Directory file entries count: %i\n", dir.count);
+
+ unsigned char *ptr = (unsigned char *)chunkData.raw;
+ dir.entries = (rresDirEntry *)RRES_CALLOC(dir.count, sizeof(rresDirEntry));
+
+ for (unsigned int i = 0; i < dir.count; i++)
+ {
+ dir.entries[i].id = ((int *)ptr)[0]; // Resource id
+ dir.entries[i].offset = ((int *)ptr)[1]; // Resource offset in file
+ // NOTE: There is a reserved integer value before fileNameSize
+ dir.entries[i].fileNameSize = ((int *)ptr)[3]; // Resource fileName size
+
+ // Resource fileName, NULL terminated and 0-padded to 4-byte,
+ // fileNameSize considers NULL and padding
+ memcpy(dir.entries[i].fileName, ptr + 16, dir.entries[i].fileNameSize);
+
+ ptr += (16 + dir.entries[i].fileNameSize); // Move pointer for next entry
+ }
+
+ RRES_FREE(chunkData.props);
+ RRES_FREE(chunkData.raw);
+ }
+ }
+ }
+ else RRES_LOG("RRES: WARNING: The provided file is not a valid rres file, file signature or version not valid\n");
+
+ fclose(rresFile);
+ }
+
+ return dir;
+}
+
+// Unload central directory data
+void rresUnloadCentralDirectory(rresCentralDir dir)
+{
+ RRES_FREE(dir.entries);
+}
+
+// Get rresResourceDataType from FourCC code
+// NOTE: Function expects to receive a char[4] array
+unsigned int rresGetDataType(const unsigned char *fourCC)
+{
+ unsigned int type = 0;
+
+ if (fourCC != NULL)
+ {
+ if (memcmp(fourCC, "NULL", 4) == 0) type = RRES_DATA_NULL; // Reserved for empty chunks, no props/data
+ else if (memcmp(fourCC, "RAWD", 4) == 0) type = RRES_DATA_RAW; // Raw file data, input file is not processed, just packed as is
+ else if (memcmp(fourCC, "TEXT", 4) == 0) type = RRES_DATA_TEXT; // Text file data, byte data extracted from text file
+ else if (memcmp(fourCC, "IMGE", 4) == 0) type = RRES_DATA_IMAGE; // Image file data, pixel data extracted from image file
+ else if (memcmp(fourCC, "WAVE", 4) == 0) type = RRES_DATA_WAVE; // Audio file data, samples data extracted from audio file
+ else if (memcmp(fourCC, "VRTX", 4) == 0) type = RRES_DATA_VERTEX; // Vertex file data, extracted from a mesh file
+ else if (memcmp(fourCC, "FNTG", 4) == 0) type = RRES_DATA_FONT_GLYPHS; // Font glyphs info, generated from an input font file
+ else if (memcmp(fourCC, "LINK", 4) == 0) type = RRES_DATA_LINK; // External linked file, filepath as provided on file input
+ else if (memcmp(fourCC, "CDIR", 4) == 0) type = RRES_DATA_DIRECTORY; // Central directory for input files relation to resource chunks
+ }
+
+ /*
+ // Assign type (unsigned int) FourCC (char[4])
+ if ((fourCC[0] == 'N') && (fourCC[1] == 'U') && (fourCC[2] == 'L') && (fourCC[3] == 'L')) type = RRES_DATA_NULL; // NULL
+ if ((fourCC[0] == 'R') && (fourCC[1] == 'A') && (fourCC[2] == 'W') && (fourCC[3] == 'D')) type = RRES_DATA_RAW; // RAWD
+ else if ((fourCC[0] == 'T') && (fourCC[1] == 'E') && (fourCC[2] == 'X') && (fourCC[3] == 'T')) type = RRES_DATA_TEXT; // TEXT
+ else if ((fourCC[0] == 'I') && (fourCC[1] == 'M') && (fourCC[2] == 'G') && (fourCC[3] == 'E')) type = RRES_DATA_IMAGE; // IMGE
+ else if ((fourCC[0] == 'W') && (fourCC[1] == 'A') && (fourCC[2] == 'V') && (fourCC[3] == 'E')) type = RRES_DATA_WAVE; // WAVE
+ else if ((fourCC[0] == 'V') && (fourCC[1] == 'R') && (fourCC[2] == 'T') && (fourCC[3] == 'X')) type = RRES_DATA_VERTEX; // VRTX
+ else if ((fourCC[0] == 'F') && (fourCC[1] == 'N') && (fourCC[2] == 'T') && (fourCC[3] == 'G')) type = RRES_DATA_FONT_GLYPHS; // FNTG
+ else if ((fourCC[0] == 'L') && (fourCC[1] == 'I') && (fourCC[2] == 'N') && (fourCC[3] == 'K')) type = RRES_DATA_LINK; // LINK
+ else if ((fourCC[0] == 'C') && (fourCC[1] == 'D') && (fourCC[2] == 'I') && (fourCC[3] == 'R')) type = RRES_DATA_DIRECTORY; // CDIR
+ */
+
+ return type;
+}
+
+// Get resource identifier from filename
+// WARNING: It requires the central directory previously loaded
+int rresGetResourceId(rresCentralDir dir, const char *fileName)
+{
+ int id = 0;
+
+ for (unsigned int i = 0, len = 0; i < dir.count; i++)
+ {
+ len = (unsigned int)strlen(fileName);
+
+ // NOTE: entries[i].fileName is NULL terminated and padded to 4-bytes
+ if (strncmp((const char *)dir.entries[i].fileName, fileName, len) == 0)
+ {
+ id = dir.entries[i].id;
+ break;
+ }
+ }
+
+ return id;
+}
+
+// Compute CRC32 hash
+// NOTE: CRC32 is used as rres id, generated from original filename
+unsigned int rresComputeCRC32(unsigned char *data, int len)
+{
+ static unsigned int crcTable[256] = {
+ 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3,
+ 0x0eDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91,
+ 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,
+ 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5,
+ 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
+ 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,
+ 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F,
+ 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D,
+ 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,
+ 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
+ 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457,
+ 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,
+ 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB,
+ 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9,
+ 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
+ 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD,
+ 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683,
+ 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,
+ 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7,
+ 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
+ 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,
+ 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79,
+ 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F,
+ 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,
+ 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
+ 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21,
+ 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,
+ 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45,
+ 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB,
+ 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
+ 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF,
+ 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D
+ };
+
+ unsigned int crc = ~0u;
+
+ for (int i = 0; i < len; i++) crc = (crc >> 8)^crcTable[data[i]^(crc&0xff)];
+
+ return ~crc;
+}
+
+// Set password to be used on data decryption
+void rresSetCipherPassword(const char *pass)
+{
+ password = pass;
+}
+
+// Get password to be used on data decryption
+const char *rresGetCipherPassword(void)
+{
+ if (password == NULL) password = "password12345";
+
+ return password;
+}
+
+//----------------------------------------------------------------------------------
+// Module Internal Functions Definition
+//----------------------------------------------------------------------------------
+// Load user resource chunk from resource packed data (as contained in .rres file)
+// WARNING: Data can be compressed and/or encrypted, in those cases is up to the user to process it,
+// and chunk.data.propCount = 0, chunk.data.props = NULL and chunk.data.raw contains all resource packed data
+static rresResourceChunkData rresLoadResourceChunkData(rresResourceChunkInfo info, void *data)
+{
+ rresResourceChunkData chunkData = { 0 };
+
+ // CRC32 data validation, verify packed data is not corrupted
+ unsigned int crc32 = rresComputeCRC32((unsigned char *)data, info.packedSize);
+
+ if ((rresGetDataType(info.type) != RRES_DATA_NULL) && (crc32 == info.crc32)) // Make sure chunk contains data and data is not corrupted
+ {
+ // Check if data chunk is compressed/encrypted to retrieve properties + data
+ if ((info.compType == RRES_COMP_NONE) && (info.cipherType == RRES_CIPHER_NONE))
+ {
+ // Data is not compressed/encrypted (info.packedSize = info.baseSize)
+ chunkData.propCount = ((unsigned int *)data)[0];
+
+ if (chunkData.propCount > 0)
+ {
+ chunkData.props = (unsigned int *)RRES_CALLOC(chunkData.propCount, sizeof(unsigned int));
+ for (unsigned int i = 0; i < chunkData.propCount; i++) chunkData.props[i] = ((unsigned int *)data)[i + 1];
+ }
+
+ int rawSize = info.baseSize - sizeof(int) - (chunkData.propCount*sizeof(int));
+ chunkData.raw = RRES_MALLOC(rawSize);
+ memcpy(chunkData.raw, ((unsigned char *)data) + sizeof(int) + (chunkData.propCount*sizeof(int)), rawSize);
+ }
+ else
+ {
+ // Data is compressed/encrypted
+ // We just return the loaded resource packed data from .rres file,
+ // it's up to the user to manage decompression/decryption on user library
+ chunkData.raw = RRES_MALLOC(info.packedSize);
+ memcpy(chunkData.raw, (unsigned char *)data, info.packedSize);
+ }
+ }
+
+ if (crc32 != info.crc32) RRES_LOG("RRES: WARNING: [ID %i] CRC32 does not match, data can be corrupted\n", info.id);
+
+ return chunkData;
+}
+
+#endif // RRES_IMPLEMENTATION
diff --git a/src/assets.c b/src/assets.c
index bdd0d8d..ad8e40a 100644
--- a/src/assets.c
+++ b/src/assets.c
@@ -1,25 +1,27 @@
#include "assets.h"
+#include "rres.h"
+#include "rres-raylib.h"
const char textureAssetPaths[TEXTURE_ASSET_COUNT][ASSET_PATH_MAX] = {
- "/home/nathan/Documents/KillaFacsista/assets/icon.png",
- "/home/nathan/Documents/KillaFacsista/assets/icon128.png",
- "/home/nathan/Documents/KillaFacsista/assets/icon64.png",
- "/home/nathan/Documents/KillaFacsista/assets/gyroscope.png",
- "/home/nathan/Documents/KillaFacsista/assets/skyTexture.png"
+ "icon.png",
+ "icon128.png",
+ "icon64.png",
+ "gyroscope.png",
+ "skyTexture.png"
};
const char modelAssetPaths[MODEL_ASSET_COUNT][ASSET_PATH_MAX] = {
- "/home/nathan/Documents/KillaFacsista/assets/antifaShip.obj",
- "/home/nathan/Documents/KillaFacsista/assets/soldato.obj",
- "/home/nathan/Documents/KillaFacsista/assets/caporale.obj",
- "/home/nathan/Documents/KillaFacsista/assets/sergente.obj",
- "/home/nathan/Documents/KillaFacsista/assets/maresciallo.obj",
- "/home/nathan/Documents/KillaFacsista/assets/generale.obj",
- "/home/nathan/Documents/KillaFacsista/assets/mussolini.obj",
- "/home/nathan/Documents/KillaFacsista/assets/guidedMissile.obj",
- "/home/nathan/Documents/KillaFacsista/assets/missile.obj",
- "/home/nathan/Documents/KillaFacsista/assets/gyroscope.obj",
- "/home/nathan/Documents/KillaFacsista/assets/sky.obj"
+ "antifaShip.obj",
+ "soldato.obj",
+ "caporale.obj",
+ "sergente.obj",
+ "maresciallo.obj",
+ "generale.obj",
+ "mussolini.obj",
+ "guidedMissile.obj",
+ "missile.obj",
+ "gyroscope.obj",
+ "sky.obj"
};
// Some models have textures and other stuff to be set.
@@ -39,21 +41,112 @@ void configModelAssets(Assets * assets) {
);
}
+void loadTextureAsset(Assets * assets, int index, rresCentralDir dir, const char * filePath) {
+ // Load and unpack.
+ rresResourceChunk chunk = rresLoadResourceChunk(filePath, rresGetResourceId(dir, textureAssetPaths[index]));
+ int result = UnpackResourceChunk(&chunk);
+
+ if (result == 0) {
+ Image image = LoadImageFromResource(chunk);
+
+ if (image.data == NULL) {
+ TraceLog(LOG_WARNING, "Issue loading image: %s", textureAssetPaths[index]);
+ } else {
+ // Load texture and unload image.
+ assets->textures[index] = LoadTextureFromImage(image);
+ UnloadImage(image);
+ }
+ } else {
+ TraceLog(LOG_WARNING, "Issue unpacking resource: %s", textureAssetPaths[index]);
+ }
+
+ rresUnloadResourceChunk(chunk);
+}
+
+void loadModelAsset(Assets * assets, int index, rresCentralDir dir, const char * filePath) {
+ // Model chunk.
+ rresResourceChunk modelChunk = rresLoadResourceChunk(filePath, rresGetResourceId(dir, modelAssetPaths[index]));
+
+ // Material chunk.
+ char materialPath[ASSET_PATH_MAX];
+ snprintf(materialPath, ASSET_PATH_MAX, "%s.mtl", GetFileNameWithoutExt(modelAssetPaths[index]));
+ rresResourceChunk materialChunk = rresLoadResourceChunk(filePath, rresGetResourceId(dir, materialPath));
+
+ int result = UnpackResourceChunk(&modelChunk);
+
+ // Load and create temp file for model.
+ if (result == 0) {
+ unsigned int dataSize;
+ void * data = LoadDataFromResource(modelChunk, &dataSize);
+
+ if (data == NULL || data <= 0) {
+ TraceLog(LOG_WARNING, "Issues loading model: %s", modelAssetPaths[index]);
+ } else {
+ FILE * tempFile = fopen("temp.obj", "wb");
+ fwrite(data, 1, dataSize, tempFile);
+ MemFree(data);
+ fclose(tempFile);
+ }
+ } else {
+ TraceLog(LOG_WARNING, "Issue unpacking resource: %s", modelAssetPaths[index]);
+ }
+
+ result = UnpackResourceChunk(&materialChunk);
+
+ // Load and create temp file for material.
+ if (result == 0) {
+ unsigned int dataSize;
+ void * data = LoadDataFromResource(materialChunk, &dataSize);
+
+ if (data == NULL || data <= 0) {
+ TraceLog(LOG_WARNING, "Issues loading material: %s", materialPath);
+ } else {
+ FILE * tempFile = fopen(materialPath, "wb");
+ fwrite(data, 1, dataSize, tempFile);
+ MemFree(data);
+ fclose(tempFile);
+ }
+ } else {
+ TraceLog(LOG_WARNING, "Issue unpacking resource: %s", materialPath);
+ }
+
+ // Load model now (:
+ assets->models[index] = LoadModel("temp.obj");
+
+ // Remove temp files.
+ remove("temp.obj");
+ remove(materialPath);
+
+ // Free this bloody shit.
+ rresUnloadResourceChunk(modelChunk);
+ rresUnloadResourceChunk(materialChunk);
+}
+
void LoadAssets(Assets * assets) {
int i;
+ TraceLog(LOG_INFO, "Loading assets");
+
+ const char * filePath = "assets.rres";
+
+ // Load centeral dir.
+ rresCentralDir dir = rresLoadCentralDirectory(filePath);
+
+ if (dir.count == 0)
+ TraceLog(LOG_WARNING, "No central directory available in %s", filePath);
+
// Textures first because models can use textures.
// Textures.
for (i = 0; i < TEXTURE_ASSET_COUNT; ++i)
- assets->textures[i] = LoadTexture(textureAssetPaths[i]);
+ loadTextureAsset(assets, i, dir, filePath);
// Models.
for (i = 0; i < MODEL_ASSET_COUNT; ++i)
- assets->models[i] = LoadModel(modelAssetPaths[i]);
+ loadModelAsset(assets, i, dir, filePath);
+ rresUnloadCentralDirectory(dir);
configModelAssets(assets);
-
TraceLog(LOG_INFO, "Assets loaded");
}
diff --git a/src/implementations.c b/src/implementations.c
index be0ea1a..ab8beae 100644
--- a/src/implementations.c
+++ b/src/implementations.c
@@ -2,3 +2,9 @@
#define RAYGUI_IMPLEMENTATION
#include "raygui.h"
+
+#define RRES_IMPLEMENTATION
+#include "rres.h"
+
+#define RRES_RAYLIB_IMPLEMENTATION
+#include "rres-raylib.h"