json import of regions

this is terribly untested, it barely compiles.
This commit is contained in:
Enno Rehling 2014-03-16 01:51:08 -07:00
parent 3c706cf29b
commit 7845de0403
4 changed files with 57 additions and 5 deletions

View File

@ -42,3 +42,17 @@ int eressea_export_json(const char * filename, unsigned int flags) {
perror(filename);
return -1;
}
int eressea_import_json(const char * filename) {
FILE *F = fopen(filename, "rt");
if (F) {
stream out = { 0 };
int err;
fstream_init(&out, F);
err = json_import(&out);
fstream_done(&out);
return err;
}
perror(filename);
return -1;
}

View File

@ -8,7 +8,9 @@ void eressea_free_game(void);
int eressea_read_game(const char * filename);
int eressea_write_game(const char * filename);
int eressea_read_orders(const char * filename);
int eressea_export_json(const char * filename, unsigned int flags);
int eressea_import_json(const char * filename);
#ifdef __cplusplus
}
#endif

View File

@ -1,9 +1,10 @@
$#include "bind_eressea.h"
module eressea {
void eressea_free_game @ free_game(void);
int eressea_read_game @ read_game(const char * filename);
int eressea_write_game @ write_game(const char * filename);
int eressea_read_orders @ read_orders(const char * filename);
int eressea_export_json @ export(const char * filename, unsigned int flags);
void eressea_free_game @ free_game(void);
int eressea_read_game @ read_game(const char * filename);
int eressea_write_game @ write_game(const char * filename);
int eressea_read_orders @ read_orders(const char * filename);
int eressea_export_json @ export(const char * filename, unsigned int flags);
int eressea_import_json @ import(const char * filename);
}

View File

@ -16,6 +16,41 @@
#include <assert.h>
int json_import(struct stream * out) {
cJSON *json, *child;
char buffer[1024], *data = 0;
size_t sz = 0;
assert(out && out->api);
while (!out->api->readln(out->handle, buffer, sizeof(buffer))) {
size_t len = strlen(buffer);
data = (char *)realloc(data, sz + len + 1);
memcpy(data + sz, buffer, len);
sz += len;
data[sz] = 0;
}
json = cJSON_Parse(data);
child = cJSON_GetObjectItem(json, "regions");
if (child && child->type==cJSON_Object) {
cJSON *j;
for (j = child->child; j; j = j->next) {
cJSON *attr;
unsigned int id = 0;
int x = 0, y = 0;
region * r;
id = (unsigned int)atol(j->string);
if ((attr = cJSON_GetObjectItem(j, "x")) != 0 && attr->type == cJSON_Number) x = attr->valueint;
if ((attr = cJSON_GetObjectItem(j, "y")) != 0 && attr->type == cJSON_Number) y = attr->valueint;
r = new_region(x, y, 0, id);
if ((attr = cJSON_GetObjectItem(j, "type")) != 0 && attr->type == cJSON_String) {
const terrain_type *terrain = get_terrain(attr->valuestring);
terraform_region(r, terrain);
}
if ((attr = cJSON_GetObjectItem(j, "name")) != 0 && attr->type == cJSON_String) {
region_setname(r, attr->valuestring);
}
}
}
cJSON_Delete(json);
return 0;
}