载入中...
搜索中...
未找到
GrowthSystem.cpp
浏览该文件的文档.
2
3#include "common/Diagnostic.h"
4
5#include <algorithm>
6#include <cmath>
7#include <memory>
8
9namespace eve::growth {
10namespace {
11
12double clampPermille(double value) {
13 if (!std::isfinite(value)) return 0.0;
14 return std::clamp(value, 0.0, 1000.0);
15}
16
17std::uint64_t splitmix64(std::uint64_t value) {
18 value += 0x9e3779b97f4a7c15ULL;
19 value = (value ^ (value >> 30)) * 0xbf58476d1ce4e5b9ULL;
20 value = (value ^ (value >> 27)) * 0x94d049bb133111ebULL;
21 return value ^ (value >> 31);
22}
23
24double unitHash(std::uint64_t seed, std::uint64_t stream, std::uint64_t key) {
25 const std::uint64_t mixed = splitmix64(seed ^ (stream + 0x9e3779b97f4a7c15ULL) ^ key);
26 return static_cast<double>(mixed >> 11) * (1.0 / 9007199254740992.0); // [0,1)
27}
28
29double meterValue(const Organism::VitalNeeds& needs, const std::string& id) {
30 auto it = needs.meters.find(id);
31 if (it == needs.meters.end()) return 0.0;
32 return it->second;
33}
34
35bool anyLethalEmpty(const Organism::VitalNeeds& needs, const SpeciesDef& species) {
36 bool sawLethal = false;
37 bool allLethalEmpty = true;
38 for (const NeedMeterDef& need : species.needs) {
39 if (!need.lethalWhenEmpty) continue;
40 sawLethal = true;
41 if (meterValue(needs, need.id) > 0.0) allLethalEmpty = false;
42 }
43 return sawLethal && allLethalEmpty;
44}
45
46bool isStressed(const Organism::VitalNeeds& needs, const SpeciesDef& species) {
47 for (const NeedMeterDef& need : species.needs) {
48 if (meterValue(needs, need.id) < need.minPermille) return true;
49 }
50 return false;
51}
52
53std::unique_ptr<GrowthWorld>& worldHolder() {
54 static std::unique_ptr<GrowthWorld> world = std::make_unique<GrowthWorld>();
55 return world;
56}
57
58} // namespace
59
60GrowthWorld& GrowthWorld::instance() { return *worldHolder(); }
61
63 std::vector<Organism*> batch = Organism::liveOrganisms();
64 for (Organism* organism : batch) {
65 if (organism) organism->release();
66 }
67 worldHolder() = std::make_unique<GrowthWorld>();
68}
69
71 if (!(seconds > 0.0) || !std::isfinite(seconds)) {
73 "secondsPerSimDay must be finite and > 0",
74 "growth.world.secondsPerSimDay"));
75 }
76 secondsPerSimDay_ = seconds;
77 return Result<void>::success();
78}
79
80void GrowthWorld::emit(GrowthEventKind kind, Organism& organism, std::string detail) {
81 GrowthEvent event;
82 event.kind = kind;
83 event.organismId = organism.stableId();
84 event.speciesId = organism.speciesId();
85 event.detail = std::move(detail);
86 events_.push(std::move(event));
87}
88
90 calendar_.reset();
91 events_.clear();
92 dayFraction_ = 0.0;
93}
94
96 if (step.delta.nanoseconds() < 0) {
98 DiagnosticCode::InvalidArgument, "SimulationStep.delta must be non-negative", "growth.world.step"));
99 }
100 const double days = step.delta.seconds() / secondsPerSimDay_;
101 return advanceDays(days);
102}
103
105 if (!std::isfinite(days) || days < 0.0) {
106 return Result<void>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument, "days must be finite and >= 0",
107 "growth.world.advanceDays"));
108 }
109 if (days == 0.0) return Result<void>::success();
110
111 double remaining = days;
112 while (remaining > 0.0) {
113 const double toEdge = 1.0 - dayFraction_;
114 const double slice = remaining < toEdge ? remaining : toEdge;
115 const std::int64_t dayForHash = calendar_.dayIndex();
116 std::vector<Organism*> batch = Organism::liveOrganisms();
117 for (Organism* organism : batch) {
118 if (!organism || organism->isDead()) continue;
119 applyDaySlice(*organism, slice, dayForHash);
120 }
121 dayFraction_ += slice;
122 remaining -= slice;
123 if (dayFraction_ + 1e-12 >= 1.0) {
124 dayFraction_ = 0.0;
125 calendar_.advanceWholeDays(1);
126 }
127 }
128 return Result<void>::success();
129}
130
131void GrowthWorld::drainNeeds(Organism& organism, const SpeciesDef& species, double days) {
132 auto& needs = *organism.vitalNeeds();
133 for (const NeedMeterDef& need : species.needs) {
134 const double current = meterValue(needs, need.id);
135 needs.meters[need.id] = clampPermille(current - need.drainPerDay * days);
136 }
137 if (anyLethalEmpty(needs, species)) {
138 organism.growth()->dead = true;
139 emit(GrowthEventKind::Died, organism, "neglect");
140 }
141}
142
143double GrowthWorld::growthMultiplier(Organism& organism, const SpeciesDef& species) {
144 if (organism.isDead()) return 0.0;
145 const auto& needs = *organism.vitalNeeds();
146 for (const NeedMeterDef& need : species.needs) {
147 if (need.requiredForGrowth && meterValue(needs, need.id) < need.minPermille) return 0.0;
148 }
149
150 double mul = 1.0;
151 const std::string seasonId = calendar_.seasonId();
152 if (!species.seasonMulById.empty()) {
153 auto it = species.seasonMulById.find(seasonId);
154 if (it != species.seasonMulById.end()) mul = it->second;
155 } else if (!species.seasonMul.empty()) {
156 const int index = calendar_.seasonIndex();
157 if (index >= 0 && index < static_cast<int>(species.seasonMul.size())) {
158 mul = species.seasonMul[static_cast<std::size_t>(index)];
159 } else {
160 mul = species.seasonMul.back();
161 }
162 }
163 if (organism.isDiseased()) mul *= organism.health()->diseaseGrowthMul;
164 if (!(mul > 0.0) || !std::isfinite(mul)) return 0.0;
165 return mul;
166}
167
168void GrowthWorld::advanceGrowth(Organism& organism, const SpeciesDef& species, double days) {
169 auto& growth = *organism.growth();
170 if (growth.dead || growth.mature || growth.harvested) return;
171 if (growth.stageIndex < 0 || growth.stageIndex >= static_cast<int>(species.stages.size())) return;
172
173 const double mul = growthMultiplier(organism, species);
174 if (mul <= 0.0) return;
175
176 double remaining = days * mul;
177 while (remaining > 0.0 && !growth.mature && !growth.dead) {
178 const GrowthStageDef& stage = species.stages[static_cast<std::size_t>(growth.stageIndex)];
179 const double need = stage.durationDays - growth.stageProgressDays;
180 if (remaining + 1e-12 < need) {
181 growth.stageProgressDays += remaining;
182 remaining = 0.0;
183 break;
184 }
185 remaining -= need;
186 growth.stageProgressDays = 0.0;
187 if (growth.stageIndex + 1 >= static_cast<int>(species.stages.size())) {
188 growth.mature = true;
189 emit(GrowthEventKind::Matured, organism, stage.id);
190 break;
191 }
192 ++growth.stageIndex;
193 emit(GrowthEventKind::StageChanged, organism, species.stages[static_cast<std::size_t>(growth.stageIndex)].id);
194 }
195}
196
197void GrowthWorld::advanceDisease(Organism& organism, const SpeciesDef& species, double days,
198 std::int64_t dayIndexForHash) {
199 auto& health = *organism.health();
200 if (!health.activeDiseaseId.empty()) {
201 health.diseaseDaysLeft -= days;
202 if (health.diseaseDaysLeft <= 0.0) {
203 health.activeDiseaseId.clear();
204 health.diseaseDaysLeft = 0.0;
205 health.diseaseGrowthMul = 1.0;
206 emit(GrowthEventKind::Cured, organism, {});
207 }
208 return;
209 }
210
211 if (species.diseases.empty() || days <= 0.0) return;
212 if (!isStressed(*organism.vitalNeeds(), species)) return;
213
214 const double resist = std::clamp(species.baseDiseaseResist, 0.0, 1.0);
215 for (std::size_t i = 0; i < species.diseases.size(); ++i) {
216 const DiseaseSusceptibility& disease = species.diseases[i];
217 const double chance = std::clamp(disease.chancePerDay * days * (1.0 - resist), 0.0, 1.0);
218 const double roll = unitHash(
219 rngSeed_, 0xD15EA5EULL,
220 organism.stableId() ^ (static_cast<std::uint64_t>(dayIndexForHash) << 8) ^ static_cast<std::uint64_t>(i));
221 if (roll < chance) {
222 health.activeDiseaseId = disease.diseaseId;
223 health.diseaseDaysLeft = disease.durationDays;
224 health.diseaseGrowthMul = disease.growthMul;
225 emit(GrowthEventKind::Diseased, organism, disease.diseaseId);
226 break;
227 }
228 }
229}
230
231void GrowthWorld::advanceProduce(Organism& organism, const SpeciesDef& species, double days) {
232 if (!organism.isMature() || organism.isDead()) return;
233 if (species.produceIntervalDays <= 0.0 || species.produceYield.empty()) return;
234
235 auto& produce = *organism.produce();
236 produce.daysSinceProduce += days;
237 while (produce.daysSinceProduce + 1e-12 >= species.produceIntervalDays) {
238 produce.daysSinceProduce -= species.produceIntervalDays;
239 emit(GrowthEventKind::Produced, organism, species.produceYield.front().itemId);
240 }
241}
242
243Result<void> GrowthWorld::spawnOffspring(Organism& parent, const SpeciesDef& species, int count) {
244 if (count <= 0) return Result<void>::success();
245 const std::string offspringId = species.reproduction.offspringSpeciesId.empty()
246 ? species.id
247 : species.reproduction.offspringSpeciesId;
248 for (int i = 0; i < count; ++i) {
249 auto child = Organism::createOrganism(offspringId);
250 if (!child) {
251 emit(GrowthEventKind::Died, parent, "offspring_failed");
252 return Result<void>::failure(child.status());
253 }
254 emit(GrowthEventKind::Offspring, *child.value(), offspringId);
255 }
256
257 auto& growth = *parent.growth();
258 if (species.reproduction.parentDiesOnBirth) {
259 growth.dead = true;
260 emit(GrowthEventKind::Died, parent, "fission");
261 } else if (species.reproduction.parentResetsStagesOnBirth) {
262 growth.stageIndex = 0;
263 growth.stageProgressDays = 0.0;
264 growth.mature = false;
265 growth.harvested = false;
266 emit(GrowthEventKind::StageChanged, parent, species.stages.front().id);
267 }
268 return Result<void>::success();
269}
270
271void GrowthWorld::advanceReproduction(Organism& organism, const SpeciesDef& species, double days) {
272 auto& repro = *organism.reproduction();
273 const ReproductionDef& def = species.reproduction;
274
275 if (def.mode == ReproductionMode::PairGestation) {
276 if (!repro.pregnant) return;
277 repro.gestationProgressDays += days;
278 if (repro.gestationProgressDays + 1e-12 < def.gestationDays) return;
279 repro.pregnant = false;
280 repro.gestationProgressDays = 0.0;
281 const int count =
282 def.offspringCountMin + (def.offspringCountMax - def.offspringCountMin) / 2;
283 spawnOffspring(organism, species, std::max(1, count))
284 .ignore("gestation completion already emitted offspring_failed on error");
285 return;
286 }
287
288 if (def.mode != ReproductionMode::SelfBud && def.mode != ReproductionMode::Fission &&
290 return;
291 if (!organism.isMature() || organism.isDead()) return;
292 if (!(def.intervalDays > 0.0)) return;
293
294 repro.daysSinceReproduce += days;
295 while (repro.daysSinceReproduce + 1e-12 >= def.intervalDays && !organism.isDead()) {
296 repro.daysSinceReproduce -= def.intervalDays;
297 const int count =
298 def.offspringCountMin + (def.offspringCountMax - def.offspringCountMin) / 2;
299 emit(GrowthEventKind::Bred, organism, "auto:" + species.kindId);
300 spawnOffspring(organism, species, std::max(1, count))
301 .ignore("interval reproduction already emitted offspring_failed on error");
302 if (organism.isDead() || def.parentResetsStagesOnBirth) break;
303 }
304}
305
306void GrowthWorld::applyDaySlice(Organism& organism, double days, std::int64_t dayIndexForHash) {
307 const SpeciesDef* species = SpeciesRegistry::find(organism.speciesId());
308 if (!species || organism.isDead()) return;
309 drainNeeds(organism, *species, days);
310 if (organism.isDead()) return;
311 advanceDisease(organism, *species, days, dayIndexForHash);
312 if (organism.isDead()) return;
313 advanceGrowth(organism, *species, days);
314 advanceProduce(organism, *species, days);
315 advanceReproduction(organism, *species, days);
316}
317
319 if (&carrier == &partner) {
321 DiagnosticCode::InvalidArgument, "cannot breed an organism with itself", "growth.world.tryBreed"));
322 }
323 if (carrier.isDead() || partner.isDead()) {
325 "dead organisms cannot breed", "growth.world.tryBreed"));
326 }
327 if (!carrier.isMature() || !partner.isMature()) {
329 "both organisms must be mature", "growth.world.tryBreed"));
330 }
331 const SpeciesDef* species = SpeciesRegistry::find(carrier.speciesId());
332 if (!species) {
334 Diagnostic::error(DiagnosticCode::NotFound, "unknown species", "growth.world.tryBreed"));
335 }
336 const ReproductionDef& def = species->reproduction;
339 "species reproduction.mode is not pair_gestation",
340 "growth.world.tryBreed"));
341 }
342 if (def.partnerMustSameSpecies && carrier.speciesId() != partner.speciesId()) {
343 return Result<void>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument, "partners must share a species",
344 "growth.world.tryBreed"));
345 }
346 if (!(def.gestationDays > 0.0)) {
348 Diagnostic::error(DiagnosticCode::InvalidArgument, "species cannot breed", "growth.world.tryBreed"));
349 }
350 if (carrier.isPregnant() || partner.isPregnant()) {
352 "a partner is already pregnant", "growth.world.tryBreed"));
353 }
354
355 auto& repro = *carrier.reproduction();
356 repro.pregnant = true;
357 repro.gestationProgressDays = 0.0;
358 repro.partnerStableId = partner.stableId();
359 emit(GrowthEventKind::Bred, carrier, partner.speciesId());
360 return Result<void>::success();
361}
362
364 if (organism.isDead()) {
366 "dead organisms cannot reproduce", "growth.world.tryReproduce"));
367 }
368 if (!organism.isMature()) {
370 "organism must be mature", "growth.world.tryReproduce"));
371 }
372 const SpeciesDef* species = SpeciesRegistry::find(organism.speciesId());
373 if (!species) {
375 Diagnostic::error(DiagnosticCode::NotFound, "unknown species", "growth.world.tryReproduce"));
376 }
377 const ReproductionDef& def = species->reproduction;
381 "species reproduction.mode is not a solo mode",
382 "growth.world.tryReproduce"));
383 }
384 organism.reproduction()->daysSinceReproduce = 0.0;
385 emit(GrowthEventKind::Bred, organism, "forced:" + species->kindId);
386 const int count = def.offspringCountMin + (def.offspringCountMax - def.offspringCountMin) / 2;
387 return spawnOffspring(organism, *species, std::max(1, count));
388}
389
390} // namespace eve::growth
Stable, structured diagnostics shared by engine modules.
SQObjectPtr key
Definition ECS.cpp:155
const ColourScope * parent
Object::Ptr value
std::string kind
double current
int count
uint32_t seed
Definition TreeMesh.cpp:276
float step
Definition TreeMesh.cpp:451
uint32_t index
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
std::string seasonId() const
Current season id string (never empty when layout is valid).
void reset() noexcept
Resets to day 0 (tests).
int seasonIndex() const noexcept
Index into seasonLayout() for the current day.
std::int64_t dayIndex() const noexcept
Absolute simulation day index (0-based).
void advanceWholeDays(std::int64_t days) noexcept
Advances the calendar by whole simulation days (truncated toward zero).
void push(GrowthEvent event)
Owner of calendar, RNG seed, and the sole simulation advance path.
Result< void > advanceDays(double days)
Advances every live organism by simulation days (may be fractional). @cost Linear in organism count ×...
static GrowthWorld & instance()
Process-wide world used by Organism helpers and the Growth module.
Result< void > setSecondsPerSimDay(double seconds) noexcept
Seconds of SimulationStep.delta that equal one simulation day.
void resetForTests()
Clears organisms' world-facing bookkeeping used by tests (events + calendar).
Result< void > tryBreed(Organism &carrier, Organism &partner)
Starts pair_gestation on carrier when both partners satisfy the species rules. @cost Cheap validation...
Result< void > tryReproduce(Organism &organism)
Triggers a solo reproduction pulse for self_bud / fission / spore_burst.
static void resetInstance()
Replaces process instance with a fresh world (tests).
Result< void > step(const SimulationStep &step)
Converts a fixed SimulationStep into fractional sim days and advances. @cost Linear in live organism ...
Growth short-root entity for any configured lifeform.
Definition Organism.h:29
static const std::vector< Organism * > & liveOrganisms()
Live organisms currently visible to Growth views.
Definition Organism.cpp:52
static Result< Organism * > createOrganism(const std::string &speciesId)
Creates an organism bound to a registered species.
Definition Organism.cpp:25
std::uint64_t stableId() const noexcept
Stable ECS id for event correlation.
Definition Organism.cpp:171
const std::string & speciesId()
Definition Organism.cpp:60
static const SpeciesDef * find(const std::string &id)
Looks up a species; nullptr when missing. @ownership Borrowed from the process-wide registry; caller ...
Definition Species.cpp:540
@ PairGestation
Two parents; carrier gestates then spawns offspring.
@ Fission
Single parent splits; optional parent death or stage reset.
@ SporeBurst
Periodic offspring bursts without a partner.
@ SelfBud
Single mature parent; interval then spawn (alien budding).
GrowthEventKind
Kind of a deterministic growth lifecycle event.
ShapeState * child(const JPH::Body &body, const JPH::SubShapeID &id)
Resolves a native child record for a synchronous callback or query. @ownership Borrowed from the worl...
Vec3 mul(Vec3 a, float scale)
One deterministic fixed-step emitted by SimulationClock.
Definition Time.h:158
One queued lifecycle observation.
Named vital meter (water, radiation, ether, …) — not fixed to Earth biology.
Definition Species.h:35
Species reproduction parameters selected by ReproductionMode.
Definition Species.h:53
double gestationDays
PairGestation only.
Definition Species.h:55
ReproductionMode mode
Definition Species.h:54
Static species definition — fully data-driven life cycle.
Definition Species.h:81
ReproductionDef reproduction
Definition Species.h:103
std::string kindId
Free-form lifeform tag (plant, animal, xeno.crystal, …).
Definition Species.h:85