载入中...
搜索中...
未找到
HexSphereMap.cpp
浏览该文件的文档.
1// eve-hot-path
3
4#include "common/Diagnostic.h"
5
6#include <algorithm>
7#include <cmath>
8#include <cstddef>
9#include <string>
10#include <utility>
11
12namespace eve::hexmap {
13namespace {
14
16[[nodiscard]]
17[[nodiscard]] constexpr std::int32_t clampInt(std::int32_t value, std::int32_t low, std::int32_t high) noexcept {
18 return value < low ? low : (value > high ? high : value);
19}
20
22[[nodiscard]] constexpr std::int32_t layerIndex(std::int32_t feature) noexcept {
23 return feature == 0 ? 0 : (feature == 1 ? 1 : 2);
24}
25
26[[nodiscard]] float dot3(HexVec3 a, HexVec3 b) noexcept { return a.x * b.x + a.y * b.y + a.z * b.z; }
27
28[[nodiscard]] float length3(HexVec3 a) noexcept { return std::sqrt(dot3(a, a)); }
29
37[[nodiscard]] bool raySphereSpan(HexVec3 origin, HexVec3 direction, float radius, float& enter,
38 float& exit) noexcept {
39 const float b = dot3(origin, direction);
40 const float c = dot3(origin, origin) - radius * radius;
41 const float discriminant = b * b - c;
42 if (discriminant < 0.f) return false;
43 const float root = std::sqrt(discriminant);
44 enter = -b - root;
45 exit = -b + root;
46 return exit > 0.f;
47}
48
49} // namespace
50
51// --- construction -----------------------------------------------------------
52
53Result<void> HexSphereMap::reset(std::int32_t subdivision, float radius, std::uint32_t seed) {
54 if (subdivision < 0 || subdivision > kMaxHexSphereSubdivision)
56 Diagnostic::error(DiagnosticCode::InvalidArgument, "subdivision level is out of range", "hexmap.sphere"));
57 if (!std::isfinite(radius) || radius <= 0.f) return Result<void>::failure(
58 Diagnostic::error(DiagnosticCode::InvalidArgument, "sphere radius must be finite and positive", "hexmap.sphere"));
59
61 if (!built.ok()) return Result<void>::failure(built.status());
62
63 topology_ = std::move(built).takeValue();
64 sphereRadius_ = radius;
65 elevationStep_ = radius * kDefaultElevationRatio;
66 noise_.reset(seed);
67 HexCellData initial{};
68 initial.values = initial.values.withElevation(0).withWaterLevel(0);
69 cells_.assign(static_cast<std::size_t>(topology_.cellCount()), initial);
70 cellDirty_.assign(cells_.size(), 0u);
71 dirtyQueue_.clear();
72 dirtyHead_ = 0;
73 revision_ = 0;
75 return Result<void>::success();
76}
77
79 elevationStep_ = step;
80 ++revision_;
81}
82
83// --- geometry ---------------------------------------------------------------
84
86 if (!contains(cell)) return sphereRadius_;
87 return sphereRadius_ + static_cast<float>(elevation(cell)) * elevationStep_;
88}
89
90float HexSphereMap::cellSpacing() const noexcept {
91 const std::int32_t count = cellCount();
92 if (count < 2) return 0.f;
93 // Mean area per cell is `4 * pi / count` of the sphere, so the mean spacing of a
94 // hexagonal packing of that area is the square root of it.
95 return sphereRadius_ * std::sqrt(4.f * 3.14159265358979f / static_cast<float>(count));
96}
97
99 return topology_.direction(cell) * surfaceRadius(cell);
100}
101
103 return topology_.direction(cell) * sphereRadius_;
104}
105
107 if (!contains(a) || !contains(b)) return HexEdgeType::Flat;
108 if (topology_.directionOf(a, b) < 0) return HexEdgeType::Flat;
109 return edgeType(elevation(a), elevation(b));
110}
111
112// --- cell access ------------------------------------------------------------
113
115 if (!contains(cell)) return nullptr;
116 return &cells_[static_cast<std::size_t>(cell)];
117}
118
119HexCellData* HexSphereMap::mutableCell(HexSphereCell cell) noexcept {
120 if (!contains(cell)) return nullptr;
121 return &cells_[static_cast<std::size_t>(cell)];
122}
123
124std::int32_t HexSphereMap::elevation(HexSphereCell c) const noexcept {
125 const HexCellData* data = cellAt(c);
126 return data ? data->values.elevation() : 0;
127}
128std::int32_t HexSphereMap::waterLevel(HexSphereCell c) const noexcept {
129 const HexCellData* data = cellAt(c);
130 return data ? data->values.waterLevel() : 0;
131}
132std::int32_t HexSphereMap::terrainType(HexSphereCell c) const noexcept {
133 const HexCellData* data = cellAt(c);
134 return data ? data->values.terrainType() : 0;
135}
136std::int32_t HexSphereMap::urbanLevel(HexSphereCell c) const noexcept {
137 const HexCellData* data = cellAt(c);
138 return data ? data->values.urbanLevel() : 0;
139}
140std::int32_t HexSphereMap::farmLevel(HexSphereCell c) const noexcept {
141 const HexCellData* data = cellAt(c);
142 return data ? data->values.farmLevel() : 0;
143}
144std::int32_t HexSphereMap::plantLevel(HexSphereCell c) const noexcept {
145 const HexCellData* data = cellAt(c);
146 return data ? data->values.plantLevel() : 0;
147}
148std::int32_t HexSphereMap::specialIndex(HexSphereCell c) const noexcept {
149 const HexCellData* data = cellAt(c);
150 return data ? data->values.specialIndex() : 0;
151}
153 const HexCellData* data = cellAt(c);
154 return data && data->values.isUnderwater();
155}
157 const HexCellData* data = cellAt(c);
158 return data && data->flags.hasRiver();
159}
161 const HexCellData* data = cellAt(c);
162 return data && data->flags.hasRoad();
163}
164bool HexSphereMap::hasRiverThrough(HexSphereCell c, std::int32_t direction) const noexcept {
165 const HexCellData* data = cellAt(c);
166 if (!data || direction < 0 || direction >= kHexDirectionCount) return false;
167 return data->flags.hasRiverThrough(static_cast<HexDirection>(direction));
168}
170 const HexCellData* data = cellAt(c);
171 return data && data->flags.isWalled();
172}
174 const HexCellData* data = cellAt(c);
175 return data && data->flags.isExplored();
176}
178 const HexCellData* data = cellAt(c);
179 return data && data->flags.isExplorable();
180}
182 const HexCellData* data = cellAt(c);
183 return data ? data->values : HexValues{};
184}
186 const HexCellData* data = cellAt(c);
187 return data ? data->flags : HexFlags{};
188}
189
190// --- picking ----------------------------------------------------------------
191
193 if (empty())
195 Diagnostic::error(DiagnosticCode::NotFound, "hex sphere map is empty", "hexmap.sphere.pick"));
196 const float directionLength = length3(rayDirection);
197 if (!(directionLength > 1e-6f))
199 "ray direction must be non-zero",
200 "hexmap.sphere.pick"));
201 const HexVec3 direction = rayDirection * (1.f / directionLength);
202
203 // The surface is a step function of direction, so the ray is marched against
204 // the bounding sphere and then bisected. Intersecting a single sphere and
205 // refining would return the far-side cell whenever the camera sits between
206 // the surface and that bounding sphere, which is exactly the low-orbit case
207 // this map exists for.
208 const float boundingRadius =
209 sphereRadius_ + static_cast<float>(HexMetrics::kMaxElevation) * elevationStep_;
210 float enter = 0.f;
211 float exit = 0.f;
212 if (!raySphereSpan(rayOrigin, direction, boundingRadius, enter, exit))
214 Diagnostic::error(DiagnosticCode::NotFound, "ray misses the hex planet", "hexmap.sphere.pick"));
215
216 const float marchStep = std::max(boundingRadius * 0.01f, 1e-4f);
217 float tInside = 0.f;
219 for (float t = std::max(0.f, enter); t <= exit + marchStep; t += marchStep) {
220 const HexVec3 point = rayOrigin + direction * t;
221 const float span = length3(point);
222 if (span <= 1e-6f) continue;
223 const HexSphereCell cell = topology_.cellAt(point);
224 if (cell == kNoHexSphereCell) continue;
225 if (span <= surfaceRadius(cell)) {
226 hit = cell;
227 tInside = t;
228 break;
229 }
230 }
231 if (hit == kNoHexSphereCell)
233 DiagnosticCode::NotFound, "ray never reached the hex planet surface", "hexmap.sphere.pick"));
234
235 // Bisect between the last sample above the surface and the first one below it.
236 float tOutside = std::max(std::max(0.f, enter), tInside - marchStep);
237 for (std::int32_t iteration = 0; iteration < 24; ++iteration) {
238 const float middle = 0.5f * (tOutside + tInside);
239 const HexVec3 point = rayOrigin + direction * middle;
240 const float span = length3(point);
241 if (span <= 1e-6f) break;
242 const HexSphereCell cell = topology_.cellAt(point);
243 if (cell == kNoHexSphereCell) break;
244 if (span <= surfaceRadius(cell)) {
245 hit = cell;
246 tInside = middle;
247 } else {
248 tOutside = middle;
249 }
250 }
252}
253
254// --- neighbourhood queries --------------------------------------------------
255
257 if (!contains(a) || !contains(b)) return kNoHexSphereCell;
258 if (a == b) return 0;
259
260 std::vector<std::uint8_t> visited(cells_.size(), 0u);
261 std::vector<HexSphereCell> frontier;
262 std::vector<HexSphereCell> next;
263 frontier.push_back(a);
264 visited[static_cast<std::size_t>(a)] = 1u;
265
266 std::int32_t depth = 0;
267 while (!frontier.empty()) {
268 ++depth;
269 next.clear();
270 for (const HexSphereCell cell : frontier) {
271 const std::int32_t count = topology_.neighborCount(cell);
272 for (std::int32_t d = 0; d < count; ++d) {
273 const HexSphereCell neighbour = topology_.neighbor(cell, d);
274 if (neighbour == kNoHexSphereCell) continue;
275 if (visited[static_cast<std::size_t>(neighbour)]) continue;
276 if (neighbour == b) return depth;
277 visited[static_cast<std::size_t>(neighbour)] = 1u;
278 next.push_back(neighbour);
279 }
280 }
281 frontier.swap(next);
282 }
283 // The neighbour graph of a sphere is connected, so this is unreachable.
284 return kNoHexSphereCell;
285}
286
288 std::vector<HexSphereCell>& out) const {
289 out.clear();
290 if (!contains(center) || radius < 0) return;
291
292 std::vector<std::uint8_t> visited(cells_.size(), 0u);
293 out.push_back(center);
294 visited[static_cast<std::size_t>(center)] = 1u;
295
296 std::size_t head = 0;
297 for (std::int32_t step = 0; step < radius; ++step) {
298 const std::size_t levelEnd = out.size();
299 for (; head < levelEnd; ++head) {
300 const HexSphereCell cell = out[head];
301 const std::int32_t count = topology_.neighborCount(cell);
302 for (std::int32_t d = 0; d < count; ++d) {
303 const HexSphereCell neighbour = topology_.neighbor(cell, d);
304 if (neighbour == kNoHexSphereCell) continue;
305 if (visited[static_cast<std::size_t>(neighbour)]) continue;
306 visited[static_cast<std::size_t>(neighbour)] = 1u;
307 out.push_back(neighbour);
308 }
309 }
310 }
311}
312
313// --- dirty tracking ---------------------------------------------------------
314
315void HexSphereMap::markCellDirty(HexSphereCell cell) noexcept {
316 if (!contains(cell)) return;
317 if (cellDirty_[static_cast<std::size_t>(cell)]) return;
318 cellDirty_[static_cast<std::size_t>(cell)] = 1u;
319 dirtyQueue_.push_back(cell);
320}
321
323 if (!contains(cell)) return;
324 markCellDirty(cell);
325 const std::int32_t count = topology_.neighborCount(cell);
326 for (std::int32_t d = 0; d < count; ++d) markCellDirty(topology_.neighbor(cell, d));
327}
328
330 dirtyQueue_.clear();
331 dirtyHead_ = 0;
332 cellDirty_.assign(cells_.size(), 0u);
333 dirtyQueue_.reserve(cells_.size());
334 for (std::size_t i = 0; i < cells_.size(); ++i) {
335 cellDirty_[i] = 1u;
336 dirtyQueue_.push_back(static_cast<HexSphereCell>(i));
337 }
338}
339
340std::int32_t HexSphereMap::takeDirtyCell() noexcept {
341 while (dirtyHead_ < dirtyQueue_.size()) {
342 const HexSphereCell cell = dirtyQueue_[dirtyHead_++];
343 if (!contains(cell)) continue;
344 if (!cellDirty_[static_cast<std::size_t>(cell)]) continue;
345 cellDirty_[static_cast<std::size_t>(cell)] = 0u;
346 if (dirtyHead_ >= 4096u && dirtyHead_ * 2u >= dirtyQueue_.size()) {
347 dirtyQueue_.erase(dirtyQueue_.begin(),
348 dirtyQueue_.begin() + static_cast<std::ptrdiff_t>(dirtyHead_));
349 dirtyHead_ = 0u;
350 }
351 return cell;
352 }
353 dirtyQueue_.clear();
354 dirtyHead_ = 0u;
355 return kNoHexSphereCell;
356}
357
358// --- cell authoring ---------------------------------------------------------
359
360void HexSphereMap::refreshCellDependents(HexSphereCell cell) noexcept {
361 ++revision_;
362 markCellDirtyAndNeighbors(cell);
363}
364
365void HexSphereMap::validateRivers(HexSphereCell cell) noexcept {
366 const HexCellData* data = cellAt(cell);
367 if (!data || !data->flags.hasRiver()) return;
368 // A river may only leave a cell that is at least as high as its neighbour,
369 // unless the cell itself is a lake at exactly its own elevation.
370 const std::int32_t fromElevation = elevation(cell);
371 const std::int32_t fromWater = waterLevel(cell);
372 const std::int32_t count = neighborCount(cell);
373 for (std::int32_t d = 0; d < count; ++d) {
374 if (!data->flags.hasRiverOut(static_cast<HexDirection>(d))) continue;
375 const HexSphereCell neighbour = topology_.neighbor(cell, d);
376 if (neighbour == kNoHexSphereCell) continue;
377 const bool canFlow = fromElevation >= elevation(neighbour) || fromWater == fromElevation;
378 if (!canFlow) {
379 removeRiver(cell).ignore("river validation must keep the map consistent");
380 return;
381 }
382 }
383}
384
386 HexCellData* data = mutableCell(c);
387 if (!data) return Result<void>::failure(
388 Diagnostic::error(DiagnosticCode::InvalidArgument, "cell is outside the hex sphere map", "hexmap.sphere"));
389 const std::int32_t clamped = clampInt(value, HexMetrics::kMinElevation, HexMetrics::kMaxElevation);
390 if (data->values.elevation() == clamped) return Result<void>::success();
391 data->values = data->values.withElevation(clamped);
392
393 // Roads cannot span a difference of more than one elevation step.
394 bool hasInvalidRoad = false;
395 const std::int32_t count = neighborCount(c);
396 for (std::int32_t d = 0; d < count && !hasInvalidRoad; ++d) {
397 if (!data->flags.hasRoad(static_cast<HexDirection>(d))) continue;
398 const HexSphereCell neighbour = topology_.neighbor(c, d);
399 if (neighbour == kNoHexSphereCell) continue;
400 const std::int32_t delta = elevation(neighbour) - clamped;
401 if (delta > 1 || delta < -1) hasInvalidRoad = true;
402 }
403 if (hasInvalidRoad) removeRoads(c).ignore("elevation change must drop invalid roads");
404 refreshCellDependents(c);
405 validateRivers(c);
406 for (std::int32_t d = 0; d < count; ++d) {
407 const HexSphereCell neighbour = topology_.neighbor(c, d);
408 if (neighbour != kNoHexSphereCell) validateRivers(neighbour);
409 }
410 return Result<void>::success();
411}
412
414 HexCellData* data = mutableCell(c);
415 if (!data) return Result<void>::failure(
416 Diagnostic::error(DiagnosticCode::InvalidArgument, "cell is outside the hex sphere map", "hexmap.sphere"));
417 const std::int32_t clamped = clampInt(value, 0, HexMetrics::kMaxElevation);
418 if (data->values.waterLevel() == clamped) return Result<void>::success();
419 data->values = data->values.withWaterLevel(clamped);
420 refreshCellDependents(c);
421 validateRivers(c);
422 return Result<void>::success();
423}
424
426 HexCellData* data = mutableCell(c);
427 if (!data) return Result<void>::failure(
428 Diagnostic::error(DiagnosticCode::InvalidArgument, "cell is outside the hex sphere map", "hexmap.sphere"));
429 data->values = data->values.withTerrainType(clampTerrainType(value));
430 ++revision_;
431 return Result<void>::success();
432}
433
435 HexCellData* data = mutableCell(c);
436 if (!data) return Result<void>::failure(
437 Diagnostic::error(DiagnosticCode::InvalidArgument, "cell is outside the hex sphere map", "hexmap.sphere"));
438 data->values = data->values.withUrbanLevel(clampInt(value, 0, 3));
439 refreshCellDependents(c);
440 return Result<void>::success();
441}
442
444 HexCellData* data = mutableCell(c);
445 if (!data) return Result<void>::failure(
446 Diagnostic::error(DiagnosticCode::InvalidArgument, "cell is outside the hex sphere map", "hexmap.sphere"));
447 data->values = data->values.withFarmLevel(clampInt(value, 0, 3));
448 refreshCellDependents(c);
449 return Result<void>::success();
450}
451
453 HexCellData* data = mutableCell(c);
454 if (!data) return Result<void>::failure(
455 Diagnostic::error(DiagnosticCode::InvalidArgument, "cell is outside the hex sphere map", "hexmap.sphere"));
456 data->values = data->values.withPlantLevel(clampInt(value, 0, 3));
457 refreshCellDependents(c);
458 return Result<void>::success();
459}
460
462 HexCellData* data = mutableCell(c);
463 if (!data) return Result<void>::failure(
464 Diagnostic::error(DiagnosticCode::InvalidArgument, "cell is outside the hex sphere map", "hexmap.sphere"));
465 if (data->flags.hasRiver()) return Result<void>::success();
466 data->values = data->values.withSpecialIndex(clampInt(index, 0, 3));
467 removeRoads(c).ignore("special features replace roads");
468 refreshCellDependents(c);
469 return Result<void>::success();
470}
471
473 HexCellData* data = mutableCell(c);
474 if (!data) return Result<void>::failure(
475 Diagnostic::error(DiagnosticCode::InvalidArgument, "cell is outside the hex sphere map", "hexmap.sphere"));
476 data->flags = data->flags.withWalled(walled);
477 refreshCellDependents(c);
478 return Result<void>::success();
479}
480
482 HexCellData* data = mutableCell(c);
483 if (!data) return Result<void>::failure(
484 Diagnostic::error(DiagnosticCode::InvalidArgument, "cell is outside the hex sphere map", "hexmap.sphere"));
485 data->flags = data->flags.withExplored(explored);
486 // Fog state changes do not alter geometry, so the cells stay clean: only the
487 // revision is bumped so a renderer can tell that the visible set changed.
488 ++revision_;
489 return Result<void>::success();
490}
491
493 HexCellData* data = mutableCell(c);
494 if (!data) return Result<void>::failure(
495 Diagnostic::error(DiagnosticCode::InvalidArgument, "cell is outside the hex sphere map", "hexmap.sphere"));
496 data->flags = data->flags.withExplorable(explorable);
497 ++revision_;
498 return Result<void>::success();
499}
500
502 HexCellData* data = mutableCell(c);
503 if (!data) return Result<void>::failure(
504 Diagnostic::error(DiagnosticCode::InvalidArgument, "cell is outside the hex sphere map", "hexmap.sphere"));
505 data->values = values;
506 data->flags = flags;
507 refreshCellDependents(c);
508 return Result<void>::success();
509}
510
512 HexCellData* data = mutableCell(c);
513 if (!data) return Result<void>::failure(
514 Diagnostic::error(DiagnosticCode::InvalidArgument, "cell is outside the hex sphere map", "hexmap.sphere"));
515 if (direction < 0 || direction >= neighborCount(c))
517 Diagnostic::error(DiagnosticCode::InvalidArgument, "river direction is not an edge of the cell", "hexmap.sphere"));
518 const HexSphereCell neighbour = topology_.neighbor(c, direction);
519 if (neighbour == kNoHexSphereCell) return Result<void>::failure(
520 Diagnostic::error(DiagnosticCode::InvalidArgument, "river direction has no neighbour", "hexmap.sphere"));
521 const std::int32_t back = topology_.oppositeDirection(c, direction);
522 if (back < 0) return Result<void>::failure(
523 Diagnostic::error(DiagnosticCode::InvalidArgument, "river direction has no opposite edge", "hexmap.sphere"));
524
525 const auto out = static_cast<HexDirection>(direction);
526 const auto in = static_cast<HexDirection>(back);
527 if (data->flags.hasAnyRiverOut() && data->flags.hasRiverOut(out)) return Result<void>::success();
528 if (elevation(c) < elevation(neighbour) && waterLevel(c) != elevation(c))
530 Diagnostic::error(DiagnosticCode::InvalidArgument, "a river cannot flow uphill", "hexmap.sphere"));
531
532 // Drop only the links this call replaces, mirroring the reference cell's
533 // `RemoveOutgoingRiver` + same-edge `RemoveIncomingRiver`. Calling the full
534 // `removeRiver` here also erased the *incoming* link from the upstream cell,
535 // so carving a channel step by step wiped the step behind it and only the
536 // last edge survived.
537 const std::int32_t count = neighborCount(c);
538 for (std::int32_t d = 0; d < count; ++d) {
539 const auto previous = static_cast<HexDirection>(d);
540 if (!data->flags.hasRiverOut(previous)) continue;
541 data->flags = data->flags.withoutRiverOut(previous);
542 const HexSphereCell previousCell = topology_.neighbor(c, d);
543 const std::int32_t previousBack = topology_.oppositeDirection(c, d);
544 if (previousCell != kNoHexSphereCell && previousBack >= 0) {
545 HexCellData* previousData = mutableCell(previousCell);
546 if (previousData) previousData->flags = previousData->flags.withoutRiverIn(static_cast<HexDirection>(previousBack));
547 refreshCellDependents(previousCell);
548 }
549 }
550
551 data = mutableCell(c);
552 // A river may not leave and enter through the same edge.
553 if (data->flags.hasRiverIn(out)) {
554 data->flags = data->flags.withoutRiverIn(out);
555 HexCellData* other = mutableCell(neighbour);
556 if (other) other->flags = other->flags.withoutRiverOut(in);
557 }
558
559 data = mutableCell(c);
560 data->flags = data->flags.withRiverOut(out).withoutRoad(out);
561 data->values = data->values.withSpecialIndex(0);
562 HexCellData* other = mutableCell(neighbour);
563 other->flags = other->flags.withRiverIn(in).withoutRoad(in);
564 other->values = other->values.withSpecialIndex(0);
565 refreshCellDependents(c);
566 refreshCellDependents(neighbour);
567 return Result<void>::success();
568}
569
571 HexCellData* data = mutableCell(c);
572 if (!data) return Result<void>::failure(
573 Diagnostic::error(DiagnosticCode::InvalidArgument, "cell is outside the hex sphere map", "hexmap.sphere"));
574 if (!data->flags.hasRiver()) return Result<void>::success();
575 for (std::int32_t d = 0; d < kHexDirectionCount; ++d) {
576 const auto direction = static_cast<HexDirection>(d);
577 data->flags = data->flags.withoutRiverIn(direction).withoutRiverOut(direction);
578 }
579 const std::int32_t count = neighborCount(c);
580 for (std::int32_t d = 0; d < count; ++d) {
581 const HexSphereCell neighbour = topology_.neighbor(c, d);
582 const std::int32_t back = topology_.oppositeDirection(c, d);
583 if (neighbour == kNoHexSphereCell || back < 0) continue;
584 const auto in = static_cast<HexDirection>(back);
585 HexCellData* other = mutableCell(neighbour);
586 if (other) other->flags = other->flags.withoutRiverIn(in).withoutRiverOut(in);
587 refreshCellDependents(neighbour);
588 }
589 refreshCellDependents(c);
590 return Result<void>::success();
591}
592
594 HexCellData* data = mutableCell(c);
595 if (!data) return Result<void>::failure(
596 Diagnostic::error(DiagnosticCode::InvalidArgument, "cell is outside the hex sphere map", "hexmap.sphere"));
597 if (direction < 0 || direction >= neighborCount(c))
599 Diagnostic::error(DiagnosticCode::InvalidArgument, "road direction is not an edge of the cell", "hexmap.sphere"));
600 const HexSphereCell neighbour = topology_.neighbor(c, direction);
601 if (neighbour == kNoHexSphereCell) return Result<void>::failure(
602 Diagnostic::error(DiagnosticCode::InvalidArgument, "road direction has no neighbour", "hexmap.sphere"));
603 const std::int32_t back = topology_.oppositeDirection(c, direction);
604 if (back < 0) return Result<void>::failure(
605 Diagnostic::error(DiagnosticCode::InvalidArgument, "road direction has no opposite edge", "hexmap.sphere"));
606
607 const auto out = static_cast<HexDirection>(direction);
608 const auto in = static_cast<HexDirection>(back);
609 if (data->flags.hasRoad(out)) return Result<void>::success();
610 if (data->flags.hasRiverThrough(out)) return Result<void>::success();
611 if (data->flags.hasRiver() && !data->flags.hasRiverBeginOrEnd()) {
612 // A road may only join a river at a begin or end cell.
613 return Result<void>::success();
614 }
615 HexCellData* other = mutableCell(neighbour);
616 if (other->values.specialIndex() != 0 || data->values.specialIndex() != 0) return Result<void>::success();
617 if (other->flags.hasRiverThrough(in)) return Result<void>::success();
618 const std::int32_t delta = elevation(neighbour) - elevation(c);
619 if (delta > 1 || delta < -1) return Result<void>::success();
620
621 data->flags = data->flags.withRoad(out);
622 other->flags = other->flags.withRoad(in);
623 refreshCellDependents(c);
624 refreshCellDependents(neighbour);
625 return Result<void>::success();
626}
627
629 HexCellData* data = mutableCell(c);
630 if (!data) return Result<void>::failure(
631 Diagnostic::error(DiagnosticCode::InvalidArgument, "cell is outside the hex sphere map", "hexmap.sphere"));
632 if (!data->flags.hasRoad()) return Result<void>::success();
633 data->flags = data->flags.without(HexFlags::roadMask());
634 const std::int32_t count = neighborCount(c);
635 for (std::int32_t d = 0; d < count; ++d) {
636 const HexSphereCell neighbour = topology_.neighbor(c, d);
637 const std::int32_t back = topology_.oppositeDirection(c, d);
638 if (neighbour == kNoHexSphereCell || back < 0) continue;
639 HexCellData* other = mutableCell(neighbour);
640 if (other) other->flags = other->flags.withoutRoad(static_cast<HexDirection>(back));
641 refreshCellDependents(neighbour);
642 }
643 refreshCellDependents(c);
644 return Result<void>::success();
645}
646
647// --- brush authoring --------------------------------------------------------
648
651 Diagnostic::error(DiagnosticCode::InvalidArgument, "brush centre is outside the hex sphere map", "hexmap.sphere"));
652 if (radius < 0) return Result<void>::failure(
653 Diagnostic::error(DiagnosticCode::InvalidArgument, "brush radius must be non-negative", "hexmap.sphere"));
654 std::vector<HexSphereCell> cells;
656 for (const HexSphereCell cell : cells) {
657 const std::int32_t next = elevation(cell) + delta;
658 setElevation(cell, next).ignore("brush elevation edit clamps per cell");
659 }
660 return Result<void>::success();
661}
662
665 Diagnostic::error(DiagnosticCode::InvalidArgument, "brush centre is outside the hex sphere map", "hexmap.sphere"));
666 if (radius < 0) return Result<void>::failure(
667 Diagnostic::error(DiagnosticCode::InvalidArgument, "brush radius must be non-negative", "hexmap.sphere"));
668 std::vector<HexSphereCell> cells;
670 for (const HexSphereCell cell : cells)
671 setWaterLevel(cell, waterLevel(cell) + delta).ignore("brush water edit clamps per cell");
672 return Result<void>::success();
673}
674
675Result<void> HexSphereMap::editTerrainType(HexSphereCell center, std::int32_t radius, std::int32_t terrainType) {
677 Diagnostic::error(DiagnosticCode::InvalidArgument, "brush centre is outside the hex sphere map", "hexmap.sphere"));
678 if (radius < 0) return Result<void>::failure(
679 Diagnostic::error(DiagnosticCode::InvalidArgument, "brush radius must be non-negative", "hexmap.sphere"));
680 std::vector<HexSphereCell> cells;
682 for (const HexSphereCell cell : cells)
683 setTerrainType(cell, terrainType).ignore("brush terrain edit clamps per cell");
684 return Result<void>::success();
685}
686
688 std::int32_t delta) {
690 Diagnostic::error(DiagnosticCode::InvalidArgument, "brush centre is outside the hex sphere map", "hexmap.sphere"));
691 if (radius < 0) return Result<void>::failure(
692 Diagnostic::error(DiagnosticCode::InvalidArgument, "brush radius must be non-negative", "hexmap.sphere"));
693 std::vector<HexSphereCell> cells;
695 const std::int32_t layer = layerIndex(feature);
696 for (const HexSphereCell cell : cells) {
697 const HexCellData* data = cellAt(cell);
698 if (!data || data->flags.hasRiver()) continue;
699 if (data->values.specialIndex() != 0) continue;
700 const std::int32_t current = layer == 0 ? data->values.urbanLevel()
701 : layer == 1 ? data->values.farmLevel()
702 : data->values.plantLevel();
703 const std::int32_t next = clampInt(current + delta, 0, 3);
704 if (layer == 0)
705 setUrbanLevel(cell, next).ignore("brush urban edit clamps per cell");
706 else if (layer == 1)
707 setFarmLevel(cell, next).ignore("brush farm edit clamps per cell");
708 else
709 setPlantLevel(cell, next).ignore("brush plant edit clamps per cell");
710 }
711 return Result<void>::success();
712}
713
714} // namespace eve::hexmap
int root
Definition AnimSmr.cpp:119
Stable, structured diagnostics shared by engine modules.
float u
Definition Grass.cpp:233
std::int32_t waterLevel
Editable spherical hex map over an icosahedral hex topology.
std::int32_t c
float elevation
MeleePoint3 b
Definition MeleeHit.cpp:41
double radius
Definition MeleeHit.cpp:42
MeleePoint3 a
Definition MeleeHit.cpp:40
glm::dvec3 origin
glm::dvec2 center
std::shared_ptr< const OceanSprayFrame > previous
TileLayer * layer
std::array< PixelCell, kPixelChunkSize *kPixelChunkSize > cells
bool hit
std::set< std::string > values
Object::Ptr value
float d
float t
RoadLaneDirection direction
ScriptStructure out
double current
int count
Cell cell
uint32_t seed
Definition TreeMesh.cpp:276
float step
Definition TreeMesh.cpp:451
std::uint32_t depth
uint32_t index
glm::vec3 point
uint32_t flags
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
void ignore(std::string_view reason={}) const noexcept
Explicitly discard this result after documenting the reason.
Definition Result.h:571
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
Packed boolean cell state (roads, rivers, walls, exploration).
Definition HexCell.h:123
constexpr HexFlags withoutRoad(HexDirection d) const noexcept
Without road.
Definition HexCell.h:200
constexpr bool hasRiverThrough(HexDirection d) const noexcept
Whether a river enters and/or leaves through d.
Definition HexCell.h:172
constexpr HexFlags withoutRiverIn(HexDirection d) const noexcept
Without river in.
Definition HexCell.h:207
constexpr HexFlags withRoad(HexDirection d) const noexcept
With road.
Definition HexCell.h:198
constexpr HexFlags withoutRiverOut(HexDirection d) const noexcept
Without river out.
Definition HexCell.h:217
constexpr HexFlags withRiverIn(HexDirection d) const noexcept
With river in.
Definition HexCell.h:202
static constexpr HexFlags roadMask() noexcept
Mask of every road bit.
Definition HexCell.h:237
static constexpr int kMinElevation
Minimum editable elevation.
Definition HexMetrics.h:160
static constexpr int kMaxElevation
Maximum editable elevation.
Definition HexMetrics.h:162
void reset(std::uint32_t seed) noexcept
Reseeds the field.
Definition HexNoise.h:35
std::int32_t urbanLevel(HexSphereCell c) const noexcept
std::int32_t waterLevel(HexSphereCell c) const noexcept
float cellSpacing() const noexcept
Mean centre-to-centre distance between neighbouring cells, in world units.
HexVec3 cellGroundPosition(HexSphereCell cell) const noexcept
World-space centre of the cell at radius, ignoring elevation.
void setElevationStep(float step) noexcept
Sets the radial world distance of one elevation level.
std::int32_t subdivision() const noexcept
The subdivision level this map was built at.
bool hasRiver(HexSphereCell c) const noexcept
Result< void > editTerrainType(HexSphereCell center, std::int32_t radius, std::int32_t terrainType)
Paints a terrain palette index over a hex brush.
Result< void > addRoad(HexSphereCell c, std::int32_t direction)
Adds a road through direction when both cells can carry one.
Result< void > editWaterLevel(HexSphereCell center, std::int32_t radius, std::int32_t delta)
Applies additive water-level change over a hex brush.
bool hasRiverThrough(HexSphereCell c, std::int32_t direction) const noexcept
std::uint32_t seed() const noexcept
The seed this map was built with.
Result< void > setExplorable(HexSphereCell c, bool explorable)
Sets whether a cell may ever be explored.
Result< void > removeRiver(HexSphereCell c)
Removes every river connection of the cell and its neighbours.
Result< void > setWaterLevel(HexSphereCell c, std::int32_t waterLevel)
Sets a cell's water level, clamped to [0, kMaxElevation].
bool isExplored(HexSphereCell c) const noexcept
Whether a cell has ever been seen by a viewer (the fog-of-war latch).
bool hasRoad(HexSphereCell c) const noexcept
std::int32_t takeDirtyCell() noexcept
Pops the next dirty cell.
bool isWalled(HexSphereCell c) const noexcept
bool isExplorable(HexSphereCell c) const noexcept
Whether a cell may ever be revealed by a viewer.
std::int32_t elevation(HexSphereCell c) const noexcept
Result< void > setFarmLevel(HexSphereCell c, std::int32_t level)
Sets a cell's farm level, clamped to [0, 3].
void collectBrush(HexSphereCell center, std::int32_t radius, std::vector< HexSphereCell > &out) const
Enumerates the cells within radius steps of center into out.
std::int32_t farmLevel(HexSphereCell c) const noexcept
Result< void > setUrbanLevel(HexSphereCell c, std::int32_t level)
Sets a cell's urban level, clamped to [0, 3].
void markCellDirtyAndNeighbors(HexSphereCell cell) noexcept
Marks one cell and its direct neighbours dirty.
Result< void > editElevation(HexSphereCell center, std::int32_t radius, std::int32_t delta)
Raises or lowers every cell within radius steps of center.
Result< void > setExplored(HexSphereCell c, bool explored)
Sets the explored (fog-of-war) latch of a cell.
void markAllDirty() noexcept
Marks every cell dirty.
bool empty() const noexcept
Whether the map holds any cell.
Result< void > setElevation(HexSphereCell c, std::int32_t elevation)
Sets a cell's elevation, clamped to the editable range, and refreshes dependents.
HexFlags flags(HexSphereCell c) const noexcept
Full packed flag record of a cell (zero when out of range).
Result< void > removeRoads(HexSphereCell c)
Removes every road of the cell and its neighbours.
Result< void > setOutgoingRiver(HexSphereCell c, std::int32_t direction)
Forces a river to leave the cell through direction, mirroring the neighbour.
std::int32_t distance(HexSphereCell a, HexSphereCell b) const
Number of edges between two cells, or kNoHexSphereCell when either is invalid.
HexValues values(HexSphereCell c) const noexcept
Full packed value record of a cell (zero when out of range).
std::int32_t plantLevel(HexSphereCell c) const noexcept
Result< void > setTerrainType(HexSphereCell c, std::int32_t terrainType)
Sets a cell's terrain palette index, clamped to the palette range.
const HexCellData * cellAt(HexSphereCell cell) const noexcept
Cell record by id, or null when out of range. @ownership Borrowed; the map owns the record....
float surfaceRadius(HexSphereCell cell) const noexcept
Radius of the cell's surface: sphereRadius + elevation * elevationStep.
HexEdgeType edgeTypeTo(HexSphereCell a, HexSphereCell b) const noexcept
Relationship between two adjacent cells; Flat when not adjacent.
Result< void > setWalled(HexSphereCell c, bool walled)
Sets whether a cell is walled.
std::int32_t cellCount() const noexcept
Number of cells (10 * f^2 + 2).
std::int32_t terrainType(HexSphereCell c) const noexcept
std::int32_t neighborCount(HexSphereCell cell) const noexcept
Number of edges of cell (5 or 6), or 0 when out of range.
Result< void > reset(std::int32_t subdivision, float radius, std::uint32_t seed)
Replaces the map with a new sphere of 10 * 4^subdivision + 2 cells.
Result< void > setCellState(HexSphereCell c, HexValues values, HexFlags flags)
Writes a complete cell record verbatim.
HexVec3 cellPosition(HexSphereCell cell) const noexcept
World-space centre of the cell's surface.
Result< void > setPlantLevel(HexSphereCell c, std::int32_t level)
Sets a cell's plant level, clamped to [0, 3].
Result< HexSphereCell > pickCell(HexVec3 rayOrigin, HexVec3 rayDirection) const
Finds the cell under a world-space ray.
static constexpr float kDefaultElevationRatio
Ratio of the default radial elevation step to the sphere radius.
Result< void > setSpecialIndex(HexSphereCell c, std::int32_t index)
Sets a cell's special-feature index; ignored while the cell carries a river.
std::int32_t specialIndex(HexSphereCell c) const noexcept
Result< void > editFeatureLevel(HexSphereCell center, std::int32_t radius, std::int32_t feature, std::int32_t delta)
Applies additive change to one feature level (0 urban, 1 farm, 2 plant).
bool isUnderwater(HexSphereCell c) const noexcept
bool contains(HexSphereCell cell) const noexcept
Whether cell is a valid id of this map.
std::int32_t neighborCount(HexSphereCell cell) const noexcept
Number of edges of cell (5 or 6), or 0 when out of range.
std::int32_t oppositeDirection(HexSphereCell cell, std::int32_t direction) const noexcept
Edge index of cell's edge towards its neighbour across direction.
std::int32_t cellCount() const noexcept
Number of cells (10 * f^2 + 2).
HexSphereCell neighbor(HexSphereCell cell, std::int32_t direction) const noexcept
Neighbour of cell across edge direction.
static Result< HexSphereTopology > build(std::int32_t subdivision)
Builds the topology of one subdivision level.
HexSphereCell cellAt(HexVec3 unitDirection) const noexcept
The cell whose centre direction is nearest to unitDirection.
Packed numeric cell state.
Definition HexCell.h:38
constexpr HexValues withSpecialIndex(std::int32_t value) const noexcept
With special index.
Definition HexCell.h:96
constexpr HexValues withElevation(std::int32_t value) const noexcept
Definition HexCell.h:76
constexpr std::int32_t specialIndex() const noexcept
Special index.
Definition HexCell.h:61
constexpr HexValues withWaterLevel(std::int32_t value) const noexcept
With water level.
Definition HexCell.h:80
float length3(float x, float y, float z)
constexpr std::int32_t kHexDirectionCount
Number of hex edges / facing directions.
Definition HexMetrics.h:62
constexpr HexEdgeType edgeType(int elevation1, int elevation2) noexcept
The relationship between two elevations (single-step changes are slopes).
Definition HexMetrics.h:96
constexpr std::int32_t kMaxHexSphereSubdivision
Largest supported subdivision level; 10 * 4^7 + 2 = 163842 cells.
HexEdgeType
Relationship between two neighbouring cells of different elevation.
Definition HexMetrics.h:93
constexpr HexSphereCell kNoHexSphereCell
Returned by a spherical cell query that has no answer.
constexpr HexDirection next(HexDirection d) noexcept
The next direction clockwise (NW wraps to NE).
Definition HexMetrics.h:76
std::int32_t HexSphereCell
Dense identifier of one cell of a spherical hex topology.
constexpr std::int32_t clampTerrainType(std::int32_t index) noexcept
Terrain type index clamped into the supported palette range.
Definition HexCell.h:24
HexDirection
Hex facing directions, counter-clockwise from north-east.
Definition HexMetrics.h:59
One cell of the hex map: packed values plus packed flags.
Definition HexCell.h:244
Minimal 3-component float vector used by the hex mesh builders.
Definition HexMetrics.h:18