Debian Codegraph @

src/cdogs/cwolfmap/vswap.c

raw symbols SCIP
1 #include "vswap.h"
2
3 #include <stdbool.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
7
8 // https://web.archive.org/web/20201206195550/http://gaarabis.free.fr/_sites/specs/wlspec_index.html
9
10 #define PATH_MAX 4096
11
12 int CWVSwapLoad(CWVSwap *vswap, const char *path)
13 {
14 int err = 0;
15 FILE *f = fopen(path, "rb");
16 if (!f)
17 {
18 err = -1;
19 fprintf(stderr, "Failed to read %s\n", path);
20 goto bail;
21 }
22
23 CWVSwapFree(vswap);
24
25 fseek(f, 0, SEEK_END);
26 vswap->dataLen = (size_t)ftell(f);
27 fseek(f, 0, SEEK_SET);
28 vswap->data = malloc(vswap->dataLen);
29 if (fread(vswap->data, 1, vswap->dataLen, f) != vswap->dataLen)
30 {
31 err = -1;
32 fprintf(stderr, "Failed to read chunk data\n");
33 goto bail;
34 }
35 memcpy(&vswap->head, vswap->data, sizeof vswap->head);
36 vswap->chunkOffset = (uint32_t *)(vswap->data + sizeof vswap->head);
37 vswap->chunkLength = (uint16_t *)(vswap->chunkOffset + vswap->head.chunkCount);
38
39 // Read sounds
40 // Sounds can span multiple chunks
41 // Last chunk is not a sound
42 for (int i = vswap->head.firstSound; i < vswap->head.chunkCount - 1; i++)
43 {
44 const int size = vswap->chunkLength[i];
45 if (size != 4096)
46 {
47 vswap->nSounds++;
48 }
49 }
50 vswap->sounds = calloc(vswap->nSounds, sizeof(CWVSwapSound));
51 for (int i = vswap->head.firstSound, sound = 0; i < vswap->head.chunkCount - 1; i++, sound++)
52 {
53 const uint32_t off = vswap->chunkOffset[i];
54 uint16_t size = vswap->chunkLength[i];
55 vswap->sounds[sound].off = off;
56 vswap->sounds[sound].len = size;
57 while (size == 4096)
58 {
59 i++;
60 size = vswap->chunkLength[i];
61 vswap->sounds[sound].len += size;
62 }
63 }
64
65 bail:
66 if (f)
67 {
68 fclose(f);
69 }
70 return err;
71 }
72
73 void CWVSwapFree(CWVSwap *vswap)
74 {
75 free(vswap->data);
76 free(vswap->sounds);
77 vswap->nSounds = 0;
78 }
79
80 int CWVSwapGetNumSounds(const CWVSwap *vswap)
81 {
82 return vswap->head.chunkCount - vswap->head.firstSound;
83 }
84 int CWVSwapGetSound(
85 const CWVSwap *vswap, const int i, const char **data, size_t *len)
86 {
87 int err = 0;
88 if (vswap->sounds[i].off == 0)
89 {
90 err = -1;
91 goto bail;
92 }
93 *len = vswap->sounds[i].len;
94 *data = &vswap->data[vswap->sounds[i].off];
95
96 bail:
97 return err;
98 }