载入中...
搜索中...
未找到
JsonExport.cpp
浏览该文件的文档.
2
3#include "procgen/Semantic.h"
4
5#include <fstream>
6#include <sstream>
7
8namespace eve::procgen {
9namespace {
10
11std::string escapeJson(const std::string &s) {
12 std::string out;
13 out.reserve(s.size() + 8);
14 for (char c : s) {
15 switch (c) {
16 case '\\': out += "\\\\"; break;
17 case '"': out += "\\\""; break;
18 case '\n': out += "\\n"; break;
19 case '\r': out += "\\r"; break;
20 case '\t': out += "\\t"; break;
21 default: out += c; break;
22 }
23 }
24 return out;
25}
26
27} // namespace
28
29std::string gridToJson(const Grid2D &grid) {
30 std::ostringstream oss;
31 oss << "{\"width\":" << grid.getWidth() << ",\"height\":" << grid.getHeight()
32 << ",\"algorithm\":\"" << escapeJson(grid.getMeta("algorithm", "")) << "\",\"cells\":[";
33 const auto &cells = grid.cells();
34 for (size_t i = 0; i < cells.size(); ++i) {
35 if (i) oss << ',';
36 oss << cells[i];
37 }
38 oss << "],\"semantics\":[";
39 for (size_t i = 0; i < cells.size(); ++i) {
40 if (i) oss << ',';
41 oss << '"' << semanticName(cells[i]) << '"';
42 }
43 oss << "],\"objects\":[";
44 for (int i = 0; i < grid.getObjectCount(); ++i) {
45 if (i) oss << ',';
46 oss << "{\"name\":\"" << escapeJson(grid.getObjectName(i)) << "\",\"type\":\""
47 << escapeJson(grid.getObjectType(i)) << "\",\"x\":" << grid.getObjectX(i)
48 << ",\"y\":" << grid.getObjectY(i) << ",\"width\":" << grid.getObjectWidth(i)
49 << ",\"height\":" << grid.getObjectHeight(i) << ",\"gid\":" << grid.getObjectGid(i)
50 << ",\"asset\":\"" << escapeJson(grid.getObjectAsset(i)) << "\",\"rotation\":"
51 << grid.getObjectRotation(i) << ",\"flags\":" << grid.getObjectFlags(i)
52 << '}';
53 }
54 oss << "]}";
55 return oss.str();
56}
57
58bool writeGridJson(const Grid2D &grid, const std::string &path, std::string *error) {
59 if (path.empty()) {
60 if (error) *error = "json path is empty";
61 return false;
62 }
63 std::ofstream ofs(path, std::ios::binary);
64 if (!ofs) {
65 if (error) *error = "failed to open json path: " + path;
66 return false;
67 }
68 ofs << gridToJson(grid);
69 if (!ofs) {
70 if (error) *error = "failed to write json path: " + path;
71 return false;
72 }
73 return true;
74}
75
76} // namespace eve::procgen
const std::string & s
std::int32_t c
std::string error
Definition Package.cpp:60
std::array< PixelCell, kPixelChunkSize *kPixelChunkSize > cells
std::string path
Definition PlayHost.cpp:110
Intermediate 2D generation result. cells store semantic ids (see Semantic.h), not tile GIDs — convert...
Definition Grid2D.h:36
const char * semanticName(uint32_t id)
Semantic name.
Definition Semantic.cpp:22
std::string gridToJson(const Grid2D &grid)
Compact JSON for debugging / reload workflows (not full Tiled).
bool writeGridJson(const Grid2D &grid, const std::string &path, std::string *error)
Writes grid json.