summaryrefslogtreecommitdiffstats
path: root/src/map.c
blob: 314ae92ceb3dc4434b13c0236a1658a7c4ae7120 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
/*
 * Copyright (C) 2013, 2021  P. J. McDermott
 *
 * This file is part of Dodge Balls
 *
 * Dodge Balls is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Dodge Balls is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Dodge Balls.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <expat.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "base64.h"
#include "compression.h"
#include "defs.h"
#include "dirs.h"
#include "map.h"
#include "tileset.h"
#include "output.h"
#include "xml.h"

struct db_map_layer {
	Uint32              *tiles;
	char                *encoding;
	char                *compression;
	char                *raw_data;
	struct db_map_layer *next;
};

struct db_map {
	char                *game_id;
	int                  w;
	int                  h;
	int                  tw;
	int                  th;
	Uint8                bg_r;
	Uint8                bg_g;
	Uint8                bg_b;
	int                  fr;
	struct db_tileset   *tileset_head;
	struct db_tileset   *tileset_tail;
	struct db_map_layer *layer_head;
	struct db_map_layer *layer_tail;
};

static char *
_db_map_path(const char *game_id, const char *file, const char *ext)
{
	const char *games_dir;
	char       *path;

	games_dir = db_get_games_dir();

	path = malloc((strlen(games_dir) + strlen(game_id) + strlen(file) +
				strlen(ext) + 3) * sizeof(*path));
	if (path == NULL) {
		db_err("Failed to allocate memory");
		return NULL;
	}

	sprintf(path, "%s/%s/%s%s", games_dir, game_id, file, ext);

	return path;
}

static void XMLCALL
_db_tmx_invalid_end(void *pv, const char *name)
{
	XML_Parser p;

	db_dbg("  </%s> (invalid)", name);

	p = (XML_Parser) pv;

	db_xml_node_pop(p);
}

static void XMLCALL
_db_tmx_invalid_start(void *pv, const char *name,
		const char **attr __attribute__((__unused__)))
{
	XML_Parser p;

	db_dbg("  <%s> (invalid)", name);

	p = (XML_Parser) pv;

	db_xml_node_push(p, NULL, _db_tmx_invalid_start,
			_db_tmx_invalid_end, NULL);
}

static void XMLCALL
_db_tmx_property_end(void *pv, const char *name)
{
	XML_Parser p;

	db_dbg("      </%s> (property)", name);

	p = (XML_Parser) pv;

	if (db_xml_check_tag(name, "property")) {
		db_xml_node_pop(p);
	} else {
		db_xml_unexpected_end_tag(p, name, "property");
	}
}

static void XMLCALL
_db_tmx_property_start(void *pv, const char *name, const char **attr)
{
	XML_Parser     p;
	struct db_map *map;
	char          *p_name;
	char          *p_type;

	db_dbg("      <%s> (property)", name);

	p = (XML_Parser) pv;
	map = db_xml_node_peek(p);

	if (db_xml_check_tag(name, "property")) {
		db_xml_get_string_attr(p, attr, "name", &p_name, 1);
		db_xml_get_string_attr(p, attr, "type", &p_type, 1);
		if (strcmp(p_name, "framerate") == 0) {
			if (strcmp(p_type, "int") != 0) {
				db_err("Framerate must be an integer");
				free(p_name);
				free(p_type);
				XML_StopParser(p, XML_FALSE);
				return;
			}
			db_xml_get_int_attr(p, attr, "value", &map->fr,  1);
			db_dbg("          Framerate: %d", map->fr);
		} else {
			db_dbg("Skipping unknown property \"%s\"", p_name);
		}
		free(p_name);
		free(p_type);
		db_xml_node_push(p, map, _db_tmx_invalid_start,
				_db_tmx_property_end, NULL);
	} else {
		db_xml_unexpected_start_tag(p, name, "property");
	}
}

static void XMLCALL
_db_tmx_properties_end(void *pv, const char *name)
{
	XML_Parser p;

	db_dbg("    </%s> (properties)", name);

	p = (XML_Parser) pv;

	if (db_xml_check_tag(name, "properties")) {
		db_xml_node_pop(p);
	} else {
		db_xml_unexpected_end_tag(p, name, "properties");
	}
}

static void XMLCALL
_db_tmx_tileset_end(void *pv, const char *name)
{
	XML_Parser p;

	db_dbg("    </%s> (tileset)", name);

	p = (XML_Parser) pv;

	if (db_xml_check_tag(name, "tileset")) {
		db_xml_node_pop(p);
	} else {
		db_xml_unexpected_end_tag(p, name, "tileset");
	}
}

static void XMLCALL
_db_tmx_cdata(void *pv, const char *s, int len)
{
	XML_Parser      p;
	struct db_map  *map;
	char           *s_z;
	char           *s_z_trimmed;
	char           *s_z_trimmed_end;
	char           *old_data;

	p = (XML_Parser) pv;
	map = db_xml_node_peek(p);

	s_z = s_z_trimmed = strndup(s, len);

	while(isspace(*s_z_trimmed)) {
		++s_z_trimmed;
		--len;
	}
	if (*s_z_trimmed == '\0') {
		db_dbg("        (null)");
		free(s_z);
		return;
	}
	s_z_trimmed_end = s_z_trimmed + len - 1;
	while (s_z_trimmed_end > s_z_trimmed && isspace(*s_z_trimmed_end)) {
		--s_z_trimmed_end;
	}
	*(s_z_trimmed_end + 1) = '\0';

	db_dbg("        %s", s_z_trimmed);
	if (map->layer_tail->raw_data != NULL &&
			*map->layer_tail->raw_data != '\0') {
		old_data = map->layer_tail->raw_data;
		sprintf(map->layer_tail->raw_data, "%s %s",
				map->layer_tail->raw_data, strdup(s_z_trimmed));
		free(old_data);
	} else {
		map->layer_tail->raw_data = strdup(s_z_trimmed);
	}

	free(s_z);
}

static void XMLCALL
_db_tmx_data_end(void *pv, const char *name)
{
	XML_Parser      p;
	struct db_map  *map;
	size_t          decoded_len;
	size_t          decomp_len;
	char           *decoded_buf;
	char           *decomp_buf;
	size_t          i;

	db_dbg("      </%s> (data)", name);

	p = (XML_Parser) pv;
	map = db_xml_node_peek(p);

	if (db_xml_check_tag(name, "data")) {
		decoded_len = strlen(map->layer_tail->raw_data);
		decomp_len = 4 * map->w* map->h;
		db_dbg("        Expected map data size: %zu", decomp_len);
		decoded_buf = malloc(decoded_len + 1);
		if (decoded_buf == NULL) {
			db_warn("        Failed to allocate layer data buffer");
			XML_StopParser(p, XML_FALSE);
			return;
		}
		if (strcmp(map->layer_tail->encoding, "base64") == 0) {
			db_dbg("        Decoding base 64 layer data...");
			db_base64_decode(map->layer_tail->raw_data,
					decoded_buf, decoded_len + 1);
		}
		if (map->layer_tail->compression == NULL) {
			db_dbg("        Layer data already decompressed");
			decomp_buf = decoded_buf;
		} else if (strcmp(map->layer_tail->compression, "zlib") == 0) {
			db_dbg("        Decompressing layer data with zlib...");
			decomp_buf = malloc(decomp_len);
			if (decomp_buf == NULL) {
				db_err("Failed to allocate layer data buffer");
				free(decoded_buf);
				XML_StopParser(p, XML_FALSE);
				return;
			}
			db_decompress(decoded_buf, decoded_len,
					decomp_buf, decomp_len);
			free(decoded_buf);
		} else if (strcmp(map->layer_tail->compression, "gzip") == 0) {
			db_dbg("        Decompressing layer data with gzip...");
			decomp_buf = malloc(decomp_len);
			if (decomp_buf == NULL) {
				db_err("Failed to allocate layer data buffer");
				free(decoded_buf);
				XML_StopParser(p, XML_FALSE);
				return;
			}
			db_decompress(decoded_buf, decoded_len,
					decomp_buf, decomp_len);
			free(decoded_buf);
		} else {
			/* This should never happen.  This branch exists only to
			 * silence GCC's maybe-uninitialized warning on
			 * decomp_buf below. */
			return;
		}
		free(map->layer_tail->raw_data);
		map->layer_tail->tiles = malloc(decomp_len);
		for (i = 0; i < decomp_len / 4; ++i) {
			/* Convert each tile GID to the system's byte order. */
			map->layer_tail->tiles[i] =
				(decomp_buf[i * 4 + 0] & 0xFF << 000) |
				(decomp_buf[i * 4 + 1] & 0xFF << 010) |
				(decomp_buf[i * 4 + 2] & 0xFF << 020) |
				(decomp_buf[i * 4 + 3] & 0xFF << 030);
		}
		free(decomp_buf);
		db_xml_node_pop(p);
	} else {
		db_xml_unexpected_end_tag(p, name, "data");
	}
}

static void XMLCALL
_db_tmx_data_start(void *pv, const char *name, const char **attr)
{
	XML_Parser     p;
	struct db_map *map;

	db_dbg("      <%s> (data)", name);

	p = (XML_Parser) pv;
	map = db_xml_node_peek(p);

	if (db_xml_check_tag(name, "data")) {
		map->layer_tail = calloc(1, sizeof(*map->layer_tail));
		if (map->layer_tail == NULL) {
			XML_StopParser(p, XML_FALSE);
			return;
		}
		if (map->layer_head == NULL) {
			map->layer_head = map->layer_tail;
		}
		db_xml_get_string_attr(p, attr, "encoding",
				&map->layer_tail->encoding, 1);
		db_xml_get_string_attr(p, attr, "compression",
				&map->layer_tail->compression, 0);
		db_xml_node_push(p, map, _db_tmx_invalid_start,
				_db_tmx_data_end, _db_tmx_cdata);
	} else {
		db_xml_unexpected_start_tag(p, name, "data");
	}
}

static void XMLCALL
_db_tmx_layer_end(void *pv, const char *name)
{
	XML_Parser p;

	db_dbg("    </%s> (layer)", name);

	p = (XML_Parser) pv;

	if (db_xml_check_tag(name, "layer")) {
		db_xml_node_pop(p);
	} else {
		db_xml_unexpected_end_tag(p, name, "layer");
	}
}

static void XMLCALL
_db_tmx_objectgroup_end(void *pv, const char *name)
{
	XML_Parser p;

	db_dbg("    </%s> (objectgroup)", name);

	p = (XML_Parser) pv;

	if (db_xml_check_tag(name, "objectgroup")) {
		db_xml_node_pop(p);
	} else {
		db_xml_unexpected_end_tag(p, name, "objectgroup");
	}
}

static void XMLCALL
_db_tmx_map_el_start(void *pv, const char *name, const char **attr)
{
	XML_Parser     p;
	struct db_map *map;
	int            firstgid;
	char          *source;

	db_dbg("    <%s> (map child)", name);

	p = (XML_Parser) pv;
	map = db_xml_node_peek(p);

	if (db_xml_check_tag(name, "properties")) {
		db_xml_node_push(p, map, _db_tmx_property_start,
				_db_tmx_properties_end, NULL);
	} else if (db_xml_check_tag(name, "tileset")) {
		db_xml_get_int_attr(p, attr, "firstgid", &firstgid, 1);
		db_xml_get_string_attr(p, attr, "source", &source, 1);
		db_dbg("        Tileset: <%s>", source);
		map->tileset_tail = db_tileset_new(map->game_id, source,
				firstgid, map->tileset_tail);
		if (map->tileset_head == NULL) {
			map->tileset_head = map->tileset_tail;
		}
		free(source);
		if (map->tileset_tail == NULL) {
			XML_StopParser(p, XML_FALSE);
			return;
		}
		db_xml_node_push(p, map, _db_tmx_invalid_start,
				_db_tmx_tileset_end, NULL);
	} else if (db_xml_check_tag(name, "layer")) {
		db_xml_node_push(p, map, _db_tmx_data_start,
				_db_tmx_layer_end, NULL);
	} else if (db_xml_check_tag(name, "objectgroup")) {
		/* TODO: object */
		db_xml_node_push(p, map, _db_tmx_invalid_start,
				_db_tmx_objectgroup_end, NULL);
	} else {
		db_xml_unexpected_start_tag(p, name,
				"properties, tileset, layer, or objectgroup");
	}
}

static void XMLCALL
_db_tmx_map_end(void *pv, const char *name)
{
	XML_Parser p;

	db_dbg("  </%s> (map)", name);

	p = (XML_Parser) pv;

	if (db_xml_check_tag(name, "map")) {
		db_xml_node_pop(p);
	} else {
		db_xml_unexpected_end_tag(p, name, "map");
	}
}

static void XMLCALL
_db_tmx_map_start(void *pv, const char *name, const char **attr)
{
	XML_Parser     p;
	struct db_map *map;
	char          *orientation;
	char          *renderorder;
	char          *backgroundcolor;
	unsigned int   bg_r;
	unsigned int   bg_g;
	unsigned int   bg_b;

	db_dbg("  <%s> (map)", name);

	p = (XML_Parser) pv;
	map = db_xml_node_peek(p);

	if (db_xml_check_tag(name, "map")) {
		/* Check orientation */
		db_xml_get_string_attr(p, attr, "orientation", &orientation, 1);
		if (strcmp(orientation, "orthogonal") != 0) {
			db_err("Map must be orthogonal");
			XML_StopParser(p, XML_FALSE);
			return;
		}
		free(orientation);
		/* Check render order */
		db_xml_get_string_attr(p, attr, "renderorder", &renderorder, 1);
		if (strcmp(renderorder, "right-down") != 0) {
			db_err("Map must be rendered right-down");
			XML_StopParser(p, XML_FALSE);
			return;
		}
		free(renderorder);
		/* Get and check size */
		db_xml_get_int_attr(p, attr, "width",      &map->w,  1);
		db_xml_get_int_attr(p, attr, "height",     &map->h,  1);
		db_xml_get_int_attr(p, attr, "tilewidth",  &map->tw, 1);
		db_xml_get_int_attr(p, attr, "tileheight", &map->th, 1);
		if (map->w * map->tw != DB_WINDOW_W ||
				map->h * map->th != DB_WINDOW_H) {
			db_err("Map size must be %dx%d px",
					DB_WINDOW_W, DB_WINDOW_H);
			XML_StopParser(p, XML_FALSE);
			return;
		}
		db_dbg("      Map size:  %dx%d px", map->w,  map->h);
		db_dbg("      Tile size: %dx%d px", map->tw, map->th);
		/* Get and check background color */
		db_xml_get_string_attr(p, attr, "backgroundcolor",
				&backgroundcolor, 1);
		if (sscanf(backgroundcolor, "#%02x%02x%02x",
					&bg_r, &bg_g, &bg_b) != 3) {
			db_err("Background color must be \"#xxxxxx\"");
			XML_StopParser(p, XML_FALSE);
			return;
		}
		map->bg_r = bg_r;
		map->bg_g = bg_g;
		map->bg_b = bg_b;
		db_dbg("      Background color: (0x%02x, 0x%02x, 0x%02x)",
				map->bg_r, map->bg_g, map->bg_b);
		db_xml_node_push(p, map, _db_tmx_map_el_start,
				_db_tmx_map_end, NULL);
	} else {
		db_xml_unexpected_start_tag(p, name, "map");
	}
}

struct db_map *
db_map_new(const char *game_id, const char *level_id)
{
	struct db_map   *map;
	XML_Parser       p;
	char            *path;
	FILE            *fp;
	void            *buf;
	size_t           len;
	enum XML_Status  status;

	map = calloc(1, sizeof(*map));
	if (map == NULL) {
		db_err("Failed to allocate memory");
		return NULL;
	}

	map->game_id = strdup(game_id);
	if (map->game_id == NULL) {
		db_err("Failed to allocate memory");
		free(map);
		return NULL;
	}

	p = XML_ParserCreate(NULL);
	if (p == NULL) {
		free(map->game_id);
		free(map);
		return NULL;
	}
	XML_UseParserAsHandlerArg(p);
	db_xml_node_push(p, map, _db_tmx_map_start, _db_tmx_invalid_end, NULL);

	path = _db_map_path(game_id, level_id, ".tmx");
	if (path == NULL) {
		db_xml_node_pop(p);
		XML_ParserFree(p);
		free(path);
		free(map->game_id);
		free(map);
		return NULL;
	}

	fp = fopen(path, "rb");
	if (fp == NULL) {
		db_xml_node_pop(p);
		XML_ParserFree(p);
		free(path);
		free(map->game_id);
		free(map);
		return NULL;
	}

	buf = XML_GetBuffer(p, 8192);
	if (buf == NULL) {
		db_xml_node_pop(p);
		XML_ParserFree(p);
		free(path);
		fclose(fp);
		free(map->game_id);
		free(map);
		return NULL;
	}

	db_dbg("Parsing <%s>:", path);
	free(path);

	while (!feof(fp)) {
		len = fread(buf, 1, 8192, fp);
		status = XML_ParseBuffer(p, len, feof(fp));
		if (status == XML_STATUS_OK) {
			continue;
		}
		db_err("Failed to parse map information (%s)",
				XML_ErrorString(XML_GetErrorCode(p)));
		db_xml_node_pop(p);
		XML_ParserFree(p);
		fclose(fp);
		free(map->game_id);
		free(map);
		return NULL;
	}

	db_dbg("Parsing done");

	db_xml_node_pop(p);
	XML_ParserFree(p);
	fclose(fp);

	return map;
}