载入中...
搜索中...
未找到
GridGraphAlgorithms.cpp
浏览该文件的文档.
2#include <algorithm>
3#include <cmath>
4#include <functional>
5#include <queue>
6#include <random>
7#include <simplesquirrel/simplesquirrel.hpp>
8#include <sstream>
9#include "common/Diagnostic.h"
13#include "procgen/GridGraph.h"
16#include "procgen/MeshGraph.h"
18#include "procgen/PointGraph.h"
19#include "procgen/Semantic.h"
20
21// GridGraphAlgorithms.cpp
23namespace {
24
25bool occupied(const Grid2D& grid, int x, int y) { return grid.getCell(x, y) != int(Semantic::Empty); }
26
27Grid2D makeGrid(const GenerateSettings& settings) {
28 Grid2D grid;
29 grid.resize(settings.width, settings.height);
30 return grid;
31}
32
33void setOccupied(Grid2D& grid, int x, int y, int semantic) {
34 if (x >= 0 && y >= 0 && x < grid.getWidth() && y < grid.getHeight()) grid.setCell(x, y, semantic);
35}
36
37std::vector<std::pair<int, int>> cells(const Grid2D& grid) {
38 std::vector<std::pair<int, int>> result;
39 for (int y = 0; y < grid.getHeight(); ++y)
40 for (int x = 0; x < grid.getWidth(); ++x)
41 if (occupied(grid, x, y)) result.emplace_back(x, y);
42 return result;
43}
44
45std::vector<std::vector<std::pair<int, int>>> islands(const Grid2D& grid) {
46 std::vector<std::vector<std::pair<int, int>>> result;
47 std::vector<unsigned char> visited(std::size_t(grid.getWidth() * grid.getHeight()));
48 constexpr int dx[] = {-1, 1, 0, 0};
49 constexpr int dy[] = {0, 0, -1, 1};
50 for (int y = 0; y < grid.getHeight(); ++y) {
51 for (int x = 0; x < grid.getWidth(); ++x) {
52 const int start = y * grid.getWidth() + x;
53 if (!occupied(grid, x, y) || visited[std::size_t(start)]) continue;
54 result.emplace_back();
55 std::queue<std::pair<int, int>> pending;
56 pending.emplace(x, y);
57 visited[std::size_t(start)] = 1;
58 while (!pending.empty()) {
59 const auto current = pending.front();
60 pending.pop();
61 result.back().push_back(current);
62 for (int direction = 0; direction < 4; ++direction) {
63 const int nx = current.first + dx[direction];
64 const int ny = current.second + dy[direction];
65 if (nx < 0 || ny < 0 || nx >= grid.getWidth() || ny >= grid.getHeight()) continue;
66 const int index = ny * grid.getWidth() + nx;
67 if (occupied(grid, nx, ny) && !visited[std::size_t(index)]) {
68 visited[std::size_t(index)] = 1;
69 pending.emplace(nx, ny);
70 }
71 }
72 }
73 }
74 }
75 return result;
76}
77
78Grid2D cellular(const GenerateSettings& settings) {
79 Grid2D grid = makeGrid(settings);
80 std::mt19937_64 rng(settings.seed);
81 std::uniform_real_distribution<float> probability(0.f, 1.f);
82 for (int y = 0; y < settings.height; ++y)
83 for (int x = 0; x < settings.width; ++x)
84 if (probability(rng) < settings.x) grid.setCell(x, y, settings.semantic);
85 for (int step = 0; step < settings.a; ++step) {
86 Grid2D next = grid;
87 for (int y = 0; y < settings.height; ++y) {
88 for (int x = 0; x < settings.width; ++x) {
89 int neighbors = 0;
90 for (int oy = -1; oy <= 1; ++oy)
91 for (int ox = -1; ox <= 1; ++ox)
92 if ((ox != 0 || oy != 0) && occupied(grid, x + ox, y + oy)) ++neighbors;
93 next.setCell(
94 x, y,
95 neighbors > 4 ? settings.semantic : (neighbors < 4 ? int(Semantic::Empty) : grid.getCell(x, y)));
96 }
97 }
98 grid = std::move(next);
99 }
100 return grid;
101}
102
103Grid2D randomWalk(const GenerateSettings& settings) {
104 Grid2D grid = makeGrid(settings);
105 std::mt19937_64 rng(settings.seed);
106 std::uniform_int_distribution<int> startX(0, settings.width - 1);
107 std::uniform_int_distribution<int> startY(0, settings.height - 1);
108 std::uniform_int_distribution<int> direction(0, 3);
109 int x = settings.b != 0 ? std::clamp(settings.b, 0, settings.width - 1) : startX(rng);
110 int y = settings.c != 0 ? std::clamp(settings.c, 0, settings.height - 1) : startY(rng);
111 const int iterations = std::max(1, settings.a);
112 const int length = std::max(1, int(settings.x));
113 constexpr int dx[] = {-1, 1, 0, 0};
114 constexpr int dy[] = {0, 0, -1, 1};
115 for (int iteration = 0; iteration < iterations; ++iteration) {
116 for (int step = 0; step < length; ++step) {
117 setOccupied(grid, x, y, settings.semantic);
118 const int d = direction(rng);
119 x = std::clamp(x + dx[d], 0, settings.width - 1);
120 y = std::clamp(y + dy[d], 0, settings.height - 1);
121 }
122 if (settings.y > 0.5f) {
123 x = startX(rng);
124 y = startY(rng);
125 }
126 }
127 return grid;
128}
129
130Grid2D maze(const GenerateSettings& settings) {
131 Grid2D grid = makeGrid(settings);
132 if (settings.width < 3 || settings.height < 3) return grid;
133 std::mt19937_64 rng(settings.seed);
134 std::vector<std::pair<int, int>> stack{{1, 1}};
135 setOccupied(grid, 1, 1, settings.semantic);
136 constexpr int dx[] = {-2, 2, 0, 0};
137 constexpr int dy[] = {0, 0, -2, 2};
138 while (!stack.empty()) {
139 const auto current = stack.back();
140 std::vector<int> candidates;
141 for (int d = 0; d < 4; ++d) {
142 const int nx = current.first + dx[d];
143 const int ny = current.second + dy[d];
144 if (nx > 0 && ny > 0 && nx < settings.width - 1 && ny < settings.height - 1 && !occupied(grid, nx, ny))
145 candidates.push_back(d);
146 }
147 if (candidates.empty()) {
148 stack.pop_back();
149 continue;
150 }
151 std::shuffle(candidates.begin(), candidates.end(), rng);
152 const int d = candidates.front();
153 const int nx = current.first + dx[d];
154 const int ny = current.second + dy[d];
155 setOccupied(grid, current.first + dx[d] / 2, current.second + dy[d] / 2, settings.semantic);
156 setOccupied(grid, nx, ny, settings.semantic);
157 stack.emplace_back(nx, ny);
158 }
159 return grid;
160}
161
162} // namespace
163
165 if (settings.width <= 0 || settings.height <= 0)
167 DiagnosticCode::InvalidArgument, "generator dimensions must be positive", {}, {}, "procgen.gridGraph"));
168 Grid2D grid = makeGrid(settings);
169 std::mt19937_64 rng(settings.seed);
170 if (operation == "generate.fill") {
171 grid.fill(settings.semantic);
172 } else if (operation == "generate.random_noise") {
173 std::uniform_real_distribution<float> probability(0.f, 1.f);
174 for (int y = 0; y < settings.height; ++y)
175 for (int x = 0; x < settings.width; ++x)
176 if (probability(rng) < settings.x) grid.setCell(x, y, settings.semantic);
177 } else if (operation == "generate.checkerboard" || operation == "generate.dot_grid") {
178 const int spacing = std::max(1, settings.a);
179 for (int y = 0; y < settings.height; ++y)
180 for (int x = 0; x < settings.width; ++x)
181 if (operation == "generate.checkerboard" ? ((x / spacing + y / spacing) % 2 == 0)
182 : (x % spacing == 0 && y % spacing == 0))
183 grid.setCell(x, y, settings.semantic);
184 } else if (operation == "generate.shape") {
185 const int cx = settings.a;
186 const int cy = settings.b;
187 const int radius = std::max(1, settings.c);
188 for (int y = 0; y < settings.height; ++y)
189 for (int x = 0; x < settings.width; ++x) {
190 bool inside = settings.x < 0.5f ? ((x - cx) * (x - cx) + (y - cy) * (y - cy) <= radius * radius)
191 : (std::abs(x - cx) <= radius && std::abs(y - cy) <= radius);
192 if (inside) grid.setCell(x, y, settings.semantic);
193 }
194 } else if (operation == "generate.cellular") {
195 grid = cellular(settings);
196 } else if (operation == "generate.random_walk") {
197 grid = randomWalk(settings);
198 } else if (operation == "generate.maze") {
199 grid = maze(settings);
200 } else if (operation == "generate.poisson") {
201 const float radius = std::max(1.f, settings.x);
202 std::vector<std::pair<int, int>> accepted;
203 std::vector<std::pair<int, int>> candidates;
204 for (int y = 0; y < settings.height; ++y)
205 for (int x = 0; x < settings.width; ++x) candidates.emplace_back(x, y);
206 std::shuffle(candidates.begin(), candidates.end(), rng);
207 for (const auto& candidate : candidates) {
208 const bool clear = std::none_of(accepted.begin(), accepted.end(), [&](const auto& point) {
209 const float dx = float(point.first - candidate.first);
210 const float dy = float(point.second - candidate.second);
211 return dx * dx + dy * dy < radius * radius;
212 });
213 if (clear) {
214 accepted.push_back(candidate);
215 grid.setCell(candidate.first, candidate.second, settings.semantic);
216 }
217 }
218 } else {
220 "unsupported generator: " + std::string(operation), {}, {},
221 "procgen.gridGraph"));
222 }
223 return Result<Grid2D>::success(std::move(grid));
224}
225
226Result<Grid2D> select(const Grid2D& input, std::string_view operation, int mode, int count, float weight,
227 std::uint64_t seed, std::string_view rule) {
228 Grid2D out;
229 out.resize(input.getWidth(), input.getHeight());
230 auto active = cells(input);
231 if (operation == "select.random") {
232 std::mt19937_64 rng(seed);
233 std::shuffle(active.begin(), active.end(), rng);
234 const int amount = count > 0 ? std::min(count, int(active.size()))
235 : int(std::round(std::clamp(weight, 0.f, 1.f) * float(active.size())));
236 active.resize(std::size_t(amount));
237 for (const auto& point : active)
238 out.setCell(point.first, point.second, input.getCell(point.first, point.second));
239 } else if (operation == "select.border" || operation == "select.fill") {
240 for (const auto& point : active) {
241 bool border = false;
242 constexpr int dx[] = {-1, 1, 0, 0};
243 constexpr int dy[] = {0, 0, -1, 1};
244 for (int d = 0; d < 4; ++d) border = border || !occupied(input, point.first + dx[d], point.second + dy[d]);
245 if ((operation == "select.border" && border) || (operation == "select.fill" && !border))
246 out.setCell(point.first, point.second, input.getCell(point.first, point.second));
247 }
248 } else if (operation == "select.neighbors") {
249 for (const auto& point : active) {
250 int neighbors = 0;
251 for (int oy = -1; oy <= 1; ++oy)
252 for (int ox = -1; ox <= 1; ++ox)
253 if ((ox != 0 || oy != 0) && occupied(input, point.first + ox, point.second + oy)) ++neighbors;
254 if ((mode == 0 && neighbors == count) || (mode == 1 && neighbors >= count) ||
255 (mode == 2 && neighbors <= count))
256 out.setCell(point.first, point.second, input.getCell(point.first, point.second));
257 }
258 } else if (operation == "select.rule") {
259 if (rule.size() != 9)
261 "rule must contain exactly nine characters (0/1/*)", {},
262 {}, "procgen.gridGraph"));
263 for (const auto& point : active) {
264 bool match = true;
265 for (int oy = -1; oy <= 1 && match; ++oy)
266 for (int ox = -1; ox <= 1; ++ox) {
267 const char expected = rule[std::size_t((oy + 1) * 3 + ox + 1)];
268 if (expected != '*' &&
269 (occupied(input, point.first + ox, point.second + oy) != (expected == '1'))) {
270 match = false;
271 break;
272 }
273 }
274 if (match) out.setCell(point.first, point.second, input.getCell(point.first, point.second));
275 }
276 } else if (operation == "select.islands" || operation == "select.island_centers") {
277 for (const auto& island : islands(input)) {
278 const bool keep = mode == 0 ? int(island.size()) < count
279 : (mode == 1 ? int(island.size()) > count : int(island.size()) == count);
280 if (!keep) continue;
281 if (operation == "select.island_centers") {
282 long long sx = 0;
283 long long sy = 0;
284 for (const auto& point : island) {
285 sx += point.first;
286 sy += point.second;
287 }
288 const int x = int(std::llround(double(sx) / double(island.size())));
289 const int y = int(std::llround(double(sy) / double(island.size())));
290 out.setCell(x, y, input.getCell(island.front().first, island.front().second));
291 } else {
292 for (const auto& point : island)
293 out.setCell(point.first, point.second, input.getCell(point.first, point.second));
294 }
295 }
296 } else {
298 "unsupported selector: " + std::string(operation), {}, {},
299 "procgen.gridGraph"));
300 }
301 return Result<Grid2D>::success(std::move(out));
302}
303
304Result<Grid2D> findPath(const Grid2D& navigation, const Grid2D& starts, const Grid2D& targets, int semantic) {
305 if (navigation.getWidth() != starts.getWidth() || navigation.getHeight() != starts.getHeight() ||
306 navigation.getWidth() != targets.getWidth() || navigation.getHeight() != targets.getHeight())
308 "pathfinding grids must have equal dimensions", {}, {},
309 "procgen.gridGraph"));
310 const auto startCells = cells(starts);
311 const auto targetCells = cells(targets);
312 if (startCells.empty() || targetCells.empty())
314 "pathfinding requires start and target cells", {}, {},
315 "procgen.gridGraph"));
316 const int width = navigation.getWidth();
317 const int height = navigation.getHeight();
318 std::vector<int> previous(std::size_t(width * height), -1);
319 std::queue<int> pending;
320 const int start = startCells.front().second * width + startCells.front().first;
321 pending.push(start);
322 previous[std::size_t(start)] = start;
323 int destination = -1;
324 while (!pending.empty() && destination < 0) {
325 const int current = pending.front();
326 pending.pop();
327 const int x = current % width;
328 const int y = current / width;
329 if (occupied(targets, x, y)) {
330 destination = current;
331 break;
332 }
333 constexpr int dx[] = {-1, 1, 0, 0};
334 constexpr int dy[] = {0, 0, -1, 1};
335 for (int d = 0; d < 4; ++d) {
336 const int nx = x + dx[d];
337 const int ny = y + dy[d];
338 if (nx < 0 || ny < 0 || nx >= width || ny >= height || !occupied(navigation, nx, ny)) continue;
339 const int next = ny * width + nx;
340 if (previous[std::size_t(next)] < 0) {
341 previous[std::size_t(next)] = current;
342 pending.push(next);
343 }
344 }
345 }
346 if (destination < 0)
348 Diagnostic::error(DiagnosticCode::InvalidArgument, "no path found", {}, {}, "procgen.gridGraph"));
349 Grid2D out;
351 for (int current = destination;; current = previous[std::size_t(current)]) {
352 out.setCell(current % width, current / width, semantic);
353 if (current == start) break;
354 }
355 return Result<Grid2D>::success(std::move(out));
356}
357
358} // namespace eve::procgen::gridgraph
359
360// GridMeshGraphScript.cpp
361namespace eve::procgen {
362
363void exposeGridMeshGraphs(ssq::Table& table) {
364 auto grid = table.addClass<GridGraph>("ProcgenGridGraph",
365 std::function<GridGraph*()>([]() -> GridGraph* { return nullptr; }), true);
366 const HSQUIRRELVM gridVm = grid.getHandle();
367 grid.addFunc("addNode", [gridVm](GridGraph* self, const std::string& id, const std::string& operation) {
368 return eve::script::projectResult(gridVm, self->addNode(id, operation));
369 });
370 grid.addFunc("connect", [gridVm](GridGraph* self, const std::string& from, const std::string& to, int slot) {
371 return eve::script::projectResult(gridVm, self->connect(from, to, slot));
372 });
373 grid.addFunc("setNodeGrid", [gridVm](GridGraph* self, const std::string& id, Grid2D* value) {
374 if (!value)
377 return eve::script::projectResult(gridVm, self->setNodeGrid(id, *value));
378 });
379 grid.addFunc("setNodeInt", [gridVm](GridGraph* self, const std::string& id, const std::string& key, int value) {
380 return eve::script::projectResult(gridVm, self->setNodeInt(id, key, value));
381 });
382 grid.addFunc("setNodeFloat", [gridVm](GridGraph* self, const std::string& id, const std::string& key, float value) {
383 return eve::script::projectResult(gridVm, self->setNodeFloat(id, key, value));
384 });
385 grid.addFunc("setNodeString",
386 [gridVm](GridGraph* self, const std::string& id, const std::string& key, const std::string& value) {
387 return eve::script::projectResult(gridVm, self->setNodeString(id, key, value));
388 });
389 grid.addFunc("setNodePointSubgraph", [gridVm](GridGraph* self, const std::string& id, PointGraph* nested,
390 const std::string& input, const std::string& output) {
391 if (!nested)
393 DiagnosticCode::InvalidArgument, "point graph is null")));
394 return eve::script::projectResult(gridVm, self->setNodePointSubgraph(id, *nested, input, output));
395 });
396 grid.addFunc("execute", [gridVm](GridGraph* self, const std::string& output) -> ssq::Table {
397 auto result = self->execute(output);
398 if (!result.ok()) return eve::script::projectStatusResult(gridVm, result.status());
399 auto value = std::move(result).takeValue();
400 ssq::Object object;
401 if (auto* outputGrid = std::get_if<Grid2D>(&value)) {
402 auto instance =
403 eve::script::makeOwnedSquirrelInstance<Grid2D>(gridVm, std::make_unique<Grid2D>(*outputGrid));
404 if (!instance.ok()) return eve::script::projectStatusResult(gridVm, instance.status());
405 object = std::move(instance).takeValue();
406 } else {
407 auto instance = eve::script::makeOwnedSquirrelInstance<PointSet>(
408 gridVm, std::make_unique<PointSet>(std::get<PointSet>(std::move(value))));
409 if (!instance.ok()) return eve::script::projectStatusResult(gridVm, instance.status());
410 object = std::move(instance).takeValue();
411 }
412 return eve::script::projectStatusResult(gridVm, Status::success(), std::move(object));
413 });
414 grid.addFunc("validate", [gridVm](GridGraph* self, const std::string& output) {
415 return eve::script::projectResult(gridVm, self->validate(output));
416 });
417 grid.addFunc("clearCache", &GridGraph::clearCache);
418 grid.addFunc("getRevision", [](GridGraph* self) { return self->revision(); });
419 grid.addFunc("serializeDefinition", &GridGraph::serializeDefinition);
420 grid.addFunc("deserializeDefinition", [gridVm](GridGraph* self, const std::string& definition) {
421 return eve::script::projectResult(gridVm, self->deserializeDefinition(definition));
422 });
423
424 auto mesh = table.addClass<MeshGraph>("ProcgenMeshGraph",
425 std::function<MeshGraph*()>([]() -> MeshGraph* { return nullptr; }), true);
426 const HSQUIRRELVM meshVm = mesh.getHandle();
427 mesh.addFunc("addNode", [meshVm](MeshGraph* self, const std::string& id, const std::string& operation) {
428 return eve::script::projectResult(meshVm, self->addNode(id, operation));
429 });
430 mesh.addFunc("connect", [meshVm](MeshGraph* self, const std::string& from, const std::string& to, int slot) {
431 return eve::script::projectResult(meshVm, self->connect(from, to, slot));
432 });
433 mesh.addFunc("setNodeGrid", [meshVm](MeshGraph* self, const std::string& id, Grid2D* value) {
434 if (!value)
437 return eve::script::projectResult(meshVm, self->setNodeGrid(id, *value));
438 });
439 mesh.addFunc("setNodePoints", [meshVm](MeshGraph* self, const std::string& id, PointSet* value) {
440 if (!value)
443 return eve::script::projectResult(meshVm, self->setNodePoints(id, *value));
444 });
445 mesh.addFunc("setNodeMesh", [meshVm](MeshGraph* self, const std::string& id, MeshBuild* value) {
446 if (!value)
449 return eve::script::projectResult(meshVm, self->setNodeMesh(id, *value));
450 });
451 mesh.addFunc("setNodeFloat", [meshVm](MeshGraph* self, const std::string& id, const std::string& key, float value) {
452 return eve::script::projectResult(meshVm, self->setNodeFloat(id, key, value));
453 });
454 mesh.addFunc("setNodeString",
455 [meshVm](MeshGraph* self, const std::string& id, const std::string& key, const std::string& value) {
456 return eve::script::projectResult(meshVm, self->setNodeString(id, key, value));
457 });
458 mesh.addFunc("execute", [meshVm](MeshGraph* self, const std::string& output) -> ssq::Table {
459 auto result = self->execute(output);
460 if (!result.ok()) return eve::script::projectStatusResult(meshVm, result.status());
461 auto instance = eve::script::makeOwnedSquirrelInstance<MeshBuild>(
462 meshVm, std::make_unique<MeshBuild>(std::move(result).takeValue()));
463 if (!instance.ok()) return eve::script::projectStatusResult(meshVm, instance.status());
464 return eve::script::projectStatusResult(meshVm, Status::success(), std::move(instance).takeValue());
465 });
466 mesh.addFunc("validate", [meshVm](MeshGraph* self, const std::string& output) {
467 return eve::script::projectResult(meshVm, self->validate(output));
468 });
469 mesh.addFunc("clearCache", &MeshGraph::clearCache);
470 mesh.addFunc("getRevision", [](MeshGraph* self) { return self->revision(); });
471 mesh.addFunc("serializeDefinition", &MeshGraph::serializeDefinition);
472 mesh.addFunc("deserializeDefinition", [meshVm](MeshGraph* self, const std::string& definition) {
473 return eve::script::projectResult(meshVm, self->deserializeDefinition(definition));
474 });
475
476 auto objects = table.addClass<ObjectBuildLayer>("ProcgenObjectBuildLayer", ssq::Class::Ctor<ObjectBuildLayer()>());
477 const HSQUIRRELVM objectsVm = objects.getHandle();
478 objects.addFunc("addAsset", [objectsVm](ObjectBuildLayer* self, const std::string& asset, float weight) {
479 return eve::script::projectResult(objectsVm, self->addAsset(asset, weight));
480 });
481 objects.addFunc("clearAssets", &ObjectBuildLayer::clearAssets);
482 objects.addFunc("setSeed", [](ObjectBuildLayer* self, std::uint32_t seed) { self->setSeed(seed); });
483 objects.addFunc("setLayerOffset",
484 [](ObjectBuildLayer* self, float x, float y, float z) { self->setLayerOffset(x, y, z); });
485 objects.addFunc("setLayerScale", [objectsVm](ObjectBuildLayer* self, float x, float y, float z) {
486 return eve::script::projectResult(objectsVm, self->setLayerScale(x, y, z));
487 });
488 objects.addFunc("setPositionRadius", [objectsVm](ObjectBuildLayer* self, float radius) {
489 return eve::script::projectResult(objectsVm, self->setPositionRadius(radius));
490 });
491 objects.addFunc("setRandomRotation", [objectsVm](ObjectBuildLayer* self, float minPitch, float maxPitch,
492 float minYaw, float maxYaw, float minRoll, float maxRoll) {
494 objectsVm, self->setRandomRotation(minPitch, maxPitch, minYaw, maxYaw, minRoll, maxRoll));
495 });
496 objects.addFunc("setRandomScale", [objectsVm](ObjectBuildLayer* self, float minX, float maxX, float minY,
497 float maxY, float minZ, float maxZ, bool uniform) {
498 return eve::script::projectResult(objectsVm, self->setRandomScale(minX, maxX, minY, maxY, minZ, maxZ, uniform));
499 });
500 objects.addFunc("setOrientation",
501 [objectsVm](ObjectBuildLayer* self, float cellSize, float yawOffset, bool invert) {
502 return eve::script::projectResult(objectsVm, self->setOrientation(cellSize, yawOffset, invert));
503 });
504 objects.addFunc("disableOrientation", [](ObjectBuildLayer* self) { self->disableOrientation(); });
505 objects.addFunc("setPlaceOnTop", [](ObjectBuildLayer* self, bool enabled, bool useLowest, float topOffset) {
506 self->setPlaceOnTop(enabled, useLowest, topOffset);
507 });
508 objects.addFunc("addChild", [objectsVm](ObjectBuildLayer* self, const std::string& asset, int count, float radius,
509 float minScale, float maxScale, float minYaw, float maxYaw) {
510 return eve::script::projectResult(objectsVm,
511 self->addChild(asset, count, radius, minScale, maxScale, minYaw, maxYaw));
512 });
513 objects.addFunc("clearChildRules", &ObjectBuildLayer::clearChildRules);
514 objects.addFunc("serializeDefinition", &ObjectBuildLayer::serializeDefinition);
515 objects.addFunc("deserializeDefinition", [objectsVm](ObjectBuildLayer* self, const std::string& definition) {
516 return eve::script::projectResult(objectsVm, self->deserializeDefinition(definition));
517 });
518 objects.addFunc("build", [objectsVm](ObjectBuildLayer* self, PointSet* source) -> ssq::Table {
519 if (!source)
521 objectsVm,
523 .status());
524 auto result = self->build(*source);
525 if (!result.ok()) return eve::script::projectStatusResult(objectsVm, result.status());
526 auto instance = eve::script::makeOwnedSquirrelInstance<PointSet>(
527 objectsVm, std::make_unique<PointSet>(std::move(result).takeValue()));
528 if (!instance.ok()) return eve::script::projectStatusResult(objectsVm, instance.status());
529 return eve::script::projectStatusResult(objectsVm, Status::success(), std::move(instance).takeValue());
530 });
531 objects.addFunc(
532 "buildOriented", [objectsVm](ObjectBuildLayer* self, PointSet* source, PointSet* orientation) -> ssq::Table {
533 if (!source || !orientation)
535 objectsVm, Result<void>::failure(
536 Diagnostic::error(DiagnosticCode::InvalidArgument, "source or orientation is null"))
537 .status());
538 auto result = self->build(*source, orientation);
539 if (!result.ok()) return eve::script::projectStatusResult(objectsVm, result.status());
540 auto instance = eve::script::makeOwnedSquirrelInstance<PointSet>(
541 objectsVm, std::make_unique<PointSet>(std::move(result).takeValue()));
542 if (!instance.ok()) return eve::script::projectStatusResult(objectsVm, instance.status());
543 return eve::script::projectStatusResult(objectsVm, Status::success(), std::move(instance).takeValue());
544 });
545
546 auto execution = table.addClass<BuildLayerExecution>(
547 "ProcgenBuildLayerExecution",
548 std::function<BuildLayerExecution*()>([]() -> BuildLayerExecution* { return nullptr; }), true);
549 const HSQUIRRELVM executionVm = execution.getHandle();
550 execution.addFunc("getCount", [](BuildLayerExecution* self) { return self->getCount(); });
551 execution.addFunc("getId", &BuildLayerExecution::getId);
552 execution.addFunc("getType", &BuildLayerExecution::getType);
553 execution.addFunc("getMesh", [executionVm](BuildLayerExecution* self, int index) -> ssq::Table {
554 auto result = self->getMesh(index);
555 if (!result.ok()) return eve::script::projectStatusResult(executionVm, result.status());
556 auto instance = eve::script::makeOwnedSquirrelInstance<MeshBuild>(
557 executionVm, std::make_unique<MeshBuild>(std::move(result).takeValue()));
558 if (!instance.ok()) return eve::script::projectStatusResult(executionVm, instance.status());
559 return eve::script::projectStatusResult(executionVm, Status::success(), std::move(instance).takeValue());
560 });
561 execution.addFunc("getPoints", [executionVm](BuildLayerExecution* self, int index) -> ssq::Table {
562 auto result = self->getPoints(index);
563 if (!result.ok()) return eve::script::projectStatusResult(executionVm, result.status());
564 auto instance = eve::script::makeOwnedSquirrelInstance<PointSet>(
565 executionVm, std::make_unique<PointSet>(std::move(result).takeValue()));
566 if (!instance.ok()) return eve::script::projectStatusResult(executionVm, instance.status());
567 return eve::script::projectStatusResult(executionVm, Status::success(), std::move(instance).takeValue());
568 });
569
570 auto stack = table.addClass<BuildLayerStack>("ProcgenBuildLayerStack", ssq::Class::Ctor<BuildLayerStack()>());
571 const HSQUIRRELVM stackVm = stack.getHandle();
572 stack.addFunc("addTileLayer", [stackVm](BuildLayerStack* self, const std::string& id, bool enabled, float cellSize,
573 float height, const std::string& group) {
574 return eve::script::projectResult(stackVm, self->addTileLayer(id, enabled, cellSize, height, group));
575 });
576 stack.addFunc("addObjectLayer", [stackVm](BuildLayerStack* self, const std::string& id, bool enabled,
578 if (!layer)
580 DiagnosticCode::InvalidArgument, "object layer is null")));
581 return eve::script::projectResult(stackVm, self->addObjectLayer(id, enabled, *layer));
582 });
583 stack.addFunc("setEnabled", [stackVm](BuildLayerStack* self, const std::string& id, bool enabled) {
584 return eve::script::projectResult(stackVm, self->setEnabled(id, enabled));
585 });
586 stack.addFunc("clear", &BuildLayerStack::clear);
587 stack.addFunc("getLayerCount", [](BuildLayerStack* self) { return self->getLayerCount(); });
588 stack.addFunc("getLayerId", &BuildLayerStack::getLayerId);
589 stack.addFunc("getLayerType", &BuildLayerStack::getLayerType);
590 stack.addFunc("isLayerEnabled", [](BuildLayerStack* self, int index) { return self->isLayerEnabled(index); });
591 stack.addFunc("serializeDefinition", &BuildLayerStack::serializeDefinition);
592 stack.addFunc("deserializeDefinition", [stackVm](BuildLayerStack* self, const std::string& definition) {
593 return eve::script::projectResult(stackVm, self->deserializeDefinition(definition));
594 });
595 stack.addFunc("execute", [stackVm](BuildLayerStack* self, Grid2D* grid, PointSet* points) -> ssq::Table {
596 if (!grid || !points)
598 stackVm, Result<void>::failure(
599 Diagnostic::error(DiagnosticCode::InvalidArgument, "grid or points input is null"))
600 .status());
601 auto result = self->execute(*grid, *points);
602 if (!result.ok()) return eve::script::projectStatusResult(stackVm, result.status());
603 auto instance = eve::script::makeOwnedSquirrelInstance<BuildLayerExecution>(
604 stackVm, std::make_unique<BuildLayerExecution>(std::move(result).takeValue()));
605 if (!instance.ok()) return eve::script::projectStatusResult(stackVm, instance.status());
606 return eve::script::projectStatusResult(stackVm, Status::success(), std::move(instance).takeValue());
607 });
608 stack.addFunc(
609 "executeOriented",
610 [stackVm](BuildLayerStack* self, Grid2D* grid, PointSet* points, PointSet* orientation) -> ssq::Table {
611 if (!grid || !points || !orientation)
613 stackVm, Result<void>::failure(
614 Diagnostic::error(DiagnosticCode::InvalidArgument, "build-layer input is null"))
615 .status());
616 auto result = self->execute(*grid, *points, orientation);
617 if (!result.ok()) return eve::script::projectStatusResult(stackVm, result.status());
618 auto instance = eve::script::makeOwnedSquirrelInstance<BuildLayerExecution>(
619 stackVm, std::make_unique<BuildLayerExecution>(std::move(result).takeValue()));
620 if (!instance.ok()) return eve::script::projectStatusResult(stackVm, instance.status());
621 return eve::script::projectStatusResult(stackVm, Status::success(), std::move(instance).takeValue());
622 });
623
624 auto delta = table.addClass<IncrementalBuildDelta>(
625 "ProcgenIncrementalBuildDelta",
626 std::function<IncrementalBuildDelta*()>([]() -> IncrementalBuildDelta* { return nullptr; }), true);
627 const HSQUIRRELVM deltaVm = delta.getHandle();
628 delta.addFunc("getCount", [](IncrementalBuildDelta* self) { return self->getCount(); });
629 delta.addFunc("getClusterX", [](IncrementalBuildDelta* self, int index) { return self->getClusterX(index); });
630 delta.addFunc("getClusterZ", [](IncrementalBuildDelta* self, int index) { return self->getClusterZ(index); });
631 delta.addFunc("isRemoved", [](IncrementalBuildDelta* self, int index) { return self->isRemoved(index); });
632 delta.addFunc("getArtifacts", [deltaVm](IncrementalBuildDelta* self, int index) -> ssq::Table {
633 auto result = self->getArtifacts(index);
634 if (!result.ok()) return eve::script::projectStatusResult(deltaVm, result.status());
635 auto instance = eve::script::makeOwnedSquirrelInstance<BuildLayerExecution>(
636 deltaVm, std::make_unique<BuildLayerExecution>(std::move(result).takeValue()));
637 if (!instance.ok()) return eve::script::projectStatusResult(deltaVm, instance.status());
638 return eve::script::projectStatusResult(deltaVm, Status::success(), std::move(instance).takeValue());
639 });
640
641 auto incremental = table.addClass<IncrementalBuildExecutor>("ProcgenIncrementalBuildExecutor",
642 ssq::Class::Ctor<IncrementalBuildExecutor()>());
643 const HSQUIRRELVM incrementalVm = incremental.getHandle();
644 incremental.addFunc("clear", &IncrementalBuildExecutor::clear);
645 incremental.addFunc("getCachedClusterCount",
646 [](IncrementalBuildExecutor* self) { return self->getCachedClusterCount(); });
647 incremental.addFunc(
648 "getCachedArtifacts", [incrementalVm](IncrementalBuildExecutor* self, int x, int z) -> ssq::Table {
649 auto result = self->getCachedArtifacts(x, z);
650 if (!result.ok()) return eve::script::projectStatusResult(incrementalVm, result.status());
651 auto instance = eve::script::makeOwnedSquirrelInstance<BuildLayerExecution>(
652 incrementalVm, std::make_unique<BuildLayerExecution>(std::move(result).takeValue()));
653 if (!instance.ok()) return eve::script::projectStatusResult(incrementalVm, instance.status());
654 return eve::script::projectStatusResult(incrementalVm, Status::success(), std::move(instance).takeValue());
655 });
656 incremental.addFunc(
657 "update",
658 [incrementalVm](IncrementalBuildExecutor* self, BuildLayerStack* buildStack, Grid2D* grid, PointSet* points,
659 int clusterSizeCells, float cellSizeWorld) -> ssq::Table {
660 if (!buildStack || !grid || !points)
663 "incremental build input is null"))
664 .status());
665 auto result = self->update(*buildStack, *grid, *points, clusterSizeCells, cellSizeWorld);
666 if (!result.ok()) return eve::script::projectStatusResult(incrementalVm, result.status());
667 auto instance = eve::script::makeOwnedSquirrelInstance<IncrementalBuildDelta>(
668 incrementalVm, std::make_unique<IncrementalBuildDelta>(std::move(result).takeValue()));
669 if (!instance.ok()) return eve::script::projectStatusResult(incrementalVm, instance.status());
670 return eve::script::projectStatusResult(incrementalVm, Status::success(), std::move(instance).takeValue());
671 });
672 incremental.addFunc(
673 "updateOriented",
674 [incrementalVm](IncrementalBuildExecutor* self, BuildLayerStack* buildStack, Grid2D* grid, PointSet* points,
675 int clusterSizeCells, float cellSizeWorld, PointSet* orientation) -> ssq::Table {
676 if (!buildStack || !grid || !points || !orientation)
679 "incremental build input is null"))
680 .status());
681 auto result = self->update(*buildStack, *grid, *points, clusterSizeCells, cellSizeWorld, orientation);
682 if (!result.ok()) return eve::script::projectStatusResult(incrementalVm, result.status());
683 auto instance = eve::script::makeOwnedSquirrelInstance<IncrementalBuildDelta>(
684 incrementalVm, std::make_unique<IncrementalBuildDelta>(std::move(result).takeValue()));
685 if (!instance.ok()) return eve::script::projectStatusResult(incrementalVm, instance.status());
686 return eve::script::projectStatusResult(incrementalVm, Status::success(), std::move(instance).takeValue());
687 });
688}
689
690} // namespace eve::procgen
double z
double y
double x
ActionParameterOperation operation
Duration start
bool & active
std::string output
std::vector< QuestEvent > pending
float cx
Definition CardTypes.cpp:36
float cy
Definition CardTypes.cpp:37
int island
struct SQVM * HSQUIRRELVM
Stable, structured diagnostics shared by engine modules.
SQObjectPtr key
Definition ECS.cpp:155
EvpackChunkInput input
Definition Evpack.cpp:170
std::vector< FieldTarget > targets
wgpu::PopErrorScopeStatus status
bool border
std::uint32_t height
std::uint32_t width
float length
std::string to
std::string from
Poco::JSON::Object::Ptr result
double radius
Definition MeleeHit.cpp:42
OceanWakeSettings settings
OceanMeshSettings mesh
glm::dvec3 dx
std::shared_ptr< const OceanSprayFrame > previous
TileLayer * layer
std::array< PixelCell, kPixelChunkSize *kPixelChunkSize > cells
std::shared_ptr< const std::vector< glm::vec2 > > points
Object::Ptr value
float d
std::string slot
RoadLaneDirection direction
uint32_t semantic
ScriptStructure out
std::string_view source
std::map< std::array< int, 4 >, std::vector< const Subject * > > candidates
Definition Sensing.cpp:32
double current
float dy
Definition Shadow.cpp:151
bool occupied
Definition Shadow.cpp:155
int count
The single Squirrel projection for common Result, Status and Value.
Explicit Value/Owned/Borrowed semantics at the Squirrel boundary.
AbilityActivationGroup group
int spacing
Json object
int iterations
Definition TreeMesh.cpp:448
uint32_t seed
Definition TreeMesh.cpp:276
float step
Definition TreeMesh.cpp:451
double weight
uint32_t index
double oy
std::vector< char > inside
double ox
glm::vec3 point
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Definition Status.cpp:19
Immutable-by-convention result of one complete build-stack execution.
std::string getType(int index) const
Returns the type.
std::string getId(int index) const
Returns the id.
Ordered, versioned executor for procedural tile and object build layers.
std::string serializeDefinition() const
Serialize ordered definitions using EVPCG_BUILD_LAYERS schema version 1.
std::string getLayerId(int index) const
Returns the layer id.
std::string getLayerType(int index) const
Returns the layer type.
Intermediate 2D generation result. cells store semantic ids (see Semantic.h), not tile GIDs — convert...
Definition Grid2D.h:37
int getWidth() const
Returns the width.
Definition Grid2D.cpp:20
void resize(int width, int height)
Resize.
Definition Grid2D.cpp:13
int getHeight() const
Returns the height.
Definition Grid2D.cpp:21
Deterministic data-flow graph for grid generation and explicit grid-to-point composition.
Definition GridGraph.h:36
Result< void > setNodeFloat(std::string_view id, std::string key, float value)
Set one floating-point parameter declared by the node operation.
std::uint64_t revision() const noexcept
Monotonic authoring revision; successful mutations increment it.
Definition GridGraph.h:69
Result< GridGraphValue > execute(std::string_view outputId)
Validate and evaluate one output into an independent owning value.
std::string serializeDefinition() const
Serialize topology and scalar parameters using the versioned EVPCG grid schema.
Result< void > deserializeDefinition(std::string_view definition)
Atomically replace this graph from a versioned definition.
Result< void > connect(std::string_view fromId, std::string_view toId, int inputIndex=0)
Connect one node output to a typed input slot.
void clearCache()
Remove all cached node values while retaining topology and parameters.
Result< void > setNodeGrid(std::string_view id, const Grid2D &grid)
Assign an owning copy to a grid.input node.
Result< void > addNode(std::string id, std::string operation)
Add a reflected operation under a stable, non-empty node id.
Result< void > setNodePointSubgraph(std::string_view id, const PointGraph &graph, std::string inputNode, std::string outputNode)
Bind an owning PointGraph copy to a point.subgraph bridge.
Result< void > setNodeString(std::string_view id, std::string key, std::string value)
Set one string parameter declared by the node operation.
Result< void > validate(std::string_view outputId) const
Validate topology, required inputs and cross-graph bindings without evaluating values.
Result< void > setNodeInt(std::string_view id, std::string key, int value)
Set one integer parameter declared by the node operation.
Ordered changes required to synchronize a scene-side cluster cache.
Derived cluster cache that incrementally executes a BuildLayerStack.
CPU triangle mesh from procedural mesh recipes (e.g. marching cubes). Positions/normals are xyz-packe...
Definition MeshBuild.h:20
Typed procedural mesh graph composing grid, point and topology domains.
Definition MeshGraph.h:22
void clearCache()
Clears cache.
std::string serializeDefinition() const
Serialize topology and scalar parameters using the versioned EVPCG mesh schema.
Deterministic TileWorldCreator-style object build layer.
std::string serializeDefinition() const
Serialize all layer settings using the versioned EVPCG object-layer schema.
void clearChildRules()
Clears child rules.
EVENGINE_API_DOMAINS public API.
Definition PointGraph.h:67
Script-friendly collection of attributed 3D samples.
Definition PointSet.h:59
StateValue objects
Definition Snapshot.cpp:110
constexpr uint32_t Empty
Definition Semantic.h:12
Result< Grid2D > findPath(const Grid2D &navigation, const Grid2D &starts, const Grid2D &targets, int semantic)
Finds path.
Result< Grid2D > generate(std::string_view operation, const GenerateSettings &settings)
Generate.
Result< Grid2D > select(const Grid2D &input, std::string_view operation, int mode, int count, float weight, std::uint64_t seed, std::string_view rule)
Select.
void exposeGridMeshGraphs(ssq::Table &table)
Expose grid mesh graphs.
ssq::Table projectStatusResult(HSQUIRRELVM vm, const Status &status)
Project a checked native status that carries no payload.
ssq::Table projectResult(HSQUIRRELVM vm, Result< void > &&result)
Consume and project a void native Result using the common schema.
bool enabled