8 int init_level(struct level *lvl, int xsz, int ysz)
10 if(!(lvl->cells = calloc(xsz * ysz, sizeof *lvl->cells))) {
19 void destroy_level(struct level *lvl)
25 int load_level(struct level *lvl, const char *fname)
28 struct ts_node *ts, *node, *iter;
32 if(!(fp = fopen(fname, "rb"))) {
36 if(!(ts = ts_load(fname))) {
37 fprintf(stderr, "failed to load level: %s\n", fname);
40 if(strcmp(ts->name, "dunged_level") != 0) {
41 fprintf(stderr, "invalid or corrupted level file: %s\n", fname);
46 if((sz = ts_get_attr_int(ts, "size", 0)) <= 0) {
50 if(init_level(lvl, sz, sz) == -1) {
51 fprintf(stderr, "failed to initialize a %dx%d level\n", sz, sz);
56 iter = ts->child_list;
61 if(strcmp(node->name, "cell") == 0) {
62 cx = ts_get_attr_int(node, "x", -1);
63 cy = ts_get_attr_int(node, "y", -1);
64 if(cx < 0 || cy < 0 || cx >= sz || cy >= sz) {
65 fprintf(stderr, "ignoring cell with invalid or missing coordinates\n");
68 cell = lvl->cells + cy * sz + cx;
69 cell->type = ts_get_attr_int(node, "blocked", 0) ? CELL_BLOCKED : CELL_WALK;
70 /* TODO wall tiles and detail objects */
78 int save_level(struct level *lvl, const char *fname)
81 struct ts_node *root, *node;
85 if(!(root = ts_alloc_node()) || ts_set_node_name(root, "dunged_level") == -1) {
89 if(!(attr = ts_alloc_attr()) || ts_set_attr_name(attr, "size") == -1) {
93 ts_set_valuei(&attr->val, lvl->width);
94 ts_add_attr(root, attr);
96 for(i=0; i<lvl->height; i++) {
97 for(j=0; j<lvl->width; j++) {
98 cell = lvl->cells + i * lvl->width + j;
99 if(cell->type == CELL_SOLID) continue;
101 if(!(node = ts_alloc_node()) || ts_set_node_name(node, "cell") == -1) {
105 if(!(attr = ts_alloc_attr()) || ts_set_attr_name(attr, "x") == -1) {
109 ts_set_valuei(&attr->val, j);
110 ts_add_attr(node, attr);
111 if(!(attr = ts_alloc_attr()) || ts_set_attr_name(attr, "y") == -1) {
115 ts_set_valuei(&attr->val, i);
116 ts_add_attr(node, attr);
118 if(cell->type == CELL_BLOCKED) {
119 if(!(attr = ts_alloc_attr()) || ts_set_attr_name(attr, "blocked") == -1) {
123 ts_set_valuei(&attr->val, 1);
124 ts_add_attr(node, attr);
127 ts_add_child(root, node);
131 if(ts_save(root, fname) == -1) {
132 fprintf(stderr, "failed to save level: %s\n", fname);
140 fprintf(stderr, "failed to construct treestore tree\n");