summaryrefslogtreecommitdiff
path: root/src/kalmia.c
blob: b789c4d6a4e6a422ce1a95081e22206be814f1e4 (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
#include <kalmia.h>
#include "geometry/geometry.h"
#include "image/image.h"
#include "material/material.h"
#include "util/util.h"
#include "xml/xml.h"

#define CHECK_ERROR(condition) \
do { \
	if (condition) { \
		kai_tag_destroy(document); \
		kalmia_destroy(k); \
		return NULL; \
	} \
} while (0)


struct kalmia_t * kalmia_parse_file(const char *filename)
{
	struct kai_tag_t *document = kai_parse_file(filename);
	if (document == NULL) {
		return NULL;
	}

	struct kai_tag_t *lib;
	int result;

	/* create kalmia_t */
	struct kalmia_t *k = kai_alloc(sizeof(struct kalmia_t), "kalmia_t");
	if (k == NULL) {
		kai_tag_destroy(document);
		return NULL;
	}

	k->library_geometries = NULL;
	k->library_materials  = NULL;
	k->library_images     = NULL;

	/* parse geometry */
	lib = kai_tag_get_first_child_with_type(document, "library_geometries");
	if (lib == NULL) {
		/* no geometry to read */
		k->library_geometries = NULL;
	}
	else {
		k->library_geometries = kai_alloc(sizeof(struct ka_library_geometries_t), "library_geometries");
		CHECK_ERROR(k->library_geometries == NULL);
		result = kai_read_library_geometries(k->library_geometries, lib);
		CHECK_ERROR(result != 0);
	}

	/* parse materials */
	lib = kai_tag_get_first_child_with_type(document, "library_materials");
	if (lib == NULL) {
		/* no materials to read */
		k->library_materials = NULL;
	}
	else {
		k->library_materials = kai_alloc(sizeof(struct ka_library_materials_t), "library_materials");
		CHECK_ERROR(k->library_materials == NULL);
		result = kai_read_library_materials(k->library_materials, lib);
		CHECK_ERROR(result != 0);
	}

	/* parse images */
	lib = kai_tag_get_first_child_with_type(document, "library_images");
	if (lib == NULL) {
		/* no images to read */
		k->library_images = NULL;
	}
	else {
		k->library_images = kai_alloc(sizeof(struct ka_library_images_t), "library_images");
		CHECK_ERROR(k->library_images == NULL);
		result = kai_read_library_images(k->library_images, lib);
		CHECK_ERROR(result != 0);
	}

	/* clean up */
	kai_tag_destroy(document);

	return k;
}


void kalmia_destroy(struct kalmia_t *k)
{
	if (k->library_geometries != NULL) {
		kai_release_library_geometries(*(k->library_geometries));
		free(k->library_geometries);
	}

	free(k);
}