summary refs log tree commit diff stats
path: root/src/world.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'src/world.cpp')
-rw-r--r--src/world.cpp99
1 files changed, 99 insertions, 0 deletions
diff --git a/src/world.cpp b/src/world.cpp new file mode 100644 index 0000000..9b1e4f6 --- /dev/null +++ b/src/world.cpp
@@ -0,0 +1,99 @@
1#include "world.h"
2#include <libxml/parser.h>
3#include <stdexcept>
4#include <cstring>
5#include "consts.h"
6
7inline xmlChar* getProp(xmlNodePtr node, const char* attr)
8{
9 xmlChar* key = xmlGetProp(node, reinterpret_cast<const xmlChar*>(attr));
10 if (key == nullptr)
11 {
12 throw std::invalid_argument("Error parsing world file");
13 }
14
15 return key;
16}
17
18World::World(std::string filename)
19{
20 xmlDocPtr doc = xmlParseFile(filename.c_str());
21 if (doc == nullptr)
22 {
23 throw std::invalid_argument("Cannot find world file");
24 }
25
26 xmlNodePtr top = xmlDocGetRootElement(doc);
27 if (top == nullptr)
28 {
29 throw std::invalid_argument("Error parsing world file");
30 }
31
32 if (xmlStrcmp(top->name, reinterpret_cast<const xmlChar*>("world")))
33 {
34 throw std::invalid_argument("Error parsing world file");
35 }
36
37 xmlChar* key = nullptr;
38
39 key = getProp(top, "startx");
40 startX_ = atoi(reinterpret_cast<char*>(key));
41 xmlFree(key);
42
43 key = getProp(top, "starty");
44 startY_ = atoi(reinterpret_cast<char*>(key));
45 xmlFree(key);
46
47 key = getProp(top, "startmap");
48 startMap_ = atoi(reinterpret_cast<char*>(key));
49 xmlFree(key);
50
51 for (xmlNodePtr node = top->xmlChildrenNode;
52 node != nullptr;
53 node = node->next)
54 {
55 if (!xmlStrcmp(node->name, reinterpret_cast<const xmlChar*>("map")))
56 {
57 key = getProp(node, "id");
58 size_t mapId = atoi(reinterpret_cast<char*>(key));
59 xmlFree(key);
60
61 key = getProp(node, "title");
62 std::string mapTitle(reinterpret_cast<char*>(key));
63 xmlFree(key);
64
65 std::vector<int> mapTiles;
66
67 for (xmlNodePtr mapNode = node->xmlChildrenNode;
68 mapNode != nullptr;
69 mapNode = mapNode->next)
70 {
71 if (!xmlStrcmp(
72 mapNode->name,
73 reinterpret_cast<const xmlChar*>("environment")))
74 {
75 key = xmlNodeGetContent(mapNode);
76
77 mapTiles.clear();
78 mapTiles.push_back(atoi(strtok(reinterpret_cast<char*>(key), ",\n")));
79 for (size_t i = 1; i < (MAP_WIDTH * MAP_HEIGHT); i++)
80 {
81 mapTiles.push_back(atoi(strtok(nullptr, ",\n")));
82 }
83
84 xmlFree(key);
85 }
86 }
87
88 maps_.emplace(
89 std::piecewise_construct,
90 std::forward_as_tuple(mapId),
91 std::forward_as_tuple(
92 mapId,
93 std::move(mapTiles),
94 std::move(mapTitle)));
95 }
96 }
97
98 xmlFreeDoc(doc);
99}