12double clampPermille(
double value) {
13 if (!std::isfinite(
value))
return 0.0;
14 return std::clamp(
value, 0.0, 1000.0);
17std::uint64_t splitmix64(std::uint64_t
value) {
18 value += 0x9e3779b97f4a7c15ULL;
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);
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;
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;
41 if (meterValue(needs, need.id) > 0.0) allLethalEmpty =
false;
43 return sawLethal && allLethalEmpty;
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;
53std::unique_ptr<GrowthWorld>& worldHolder() {
54 static std::unique_ptr<GrowthWorld> world = std::make_unique<GrowthWorld>();
65 if (organism) organism->release();
67 worldHolder() = std::make_unique<GrowthWorld>();
71 if (!(seconds > 0.0) || !std::isfinite(seconds)) {
73 "secondsPerSimDay must be finite and > 0",
74 "growth.world.secondsPerSimDay"));
76 secondsPerSimDay_ = seconds;
83 event.organismId = organism.
stableId();
85 event.detail = std::move(detail);
86 events_.
push(std::move(event));
96 if (
step.delta.nanoseconds() < 0) {
100 const double days =
step.delta.seconds() / secondsPerSimDay_;
105 if (!std::isfinite(days) || days < 0.0) {
107 "growth.world.advanceDays"));
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();
118 if (!organism || organism->
isDead())
continue;
119 applyDaySlice(*organism, slice, dayForHash);
121 dayFraction_ += slice;
123 if (dayFraction_ + 1e-12 >= 1.0) {
131void GrowthWorld::drainNeeds(
Organism& organism,
const SpeciesDef& species,
double days) {
132 auto& needs = *organism.vitalNeeds();
134 const double current = meterValue(needs, need.id);
135 needs.meters[need.id] = clampPermille(
current - need.drainPerDay * days);
137 if (anyLethalEmpty(needs, species)) {
138 organism.growth()->dead =
true;
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;
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()) {
157 if (
index >= 0 &&
index <
static_cast<int>(species.seasonMul.size())) {
158 mul = species.seasonMul[
static_cast<std::size_t
>(
index)];
160 mul = species.seasonMul.back();
163 if (organism.isDiseased()) mul *= organism.health()->diseaseGrowthMul;
164 if (!(mul > 0.0) || !std::isfinite(mul))
return 0.0;
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;
173 const double mul = growthMultiplier(organism, species);
174 if (mul <= 0.0)
return;
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;
186 growth.stageProgressDays = 0.0;
187 if (growth.stageIndex + 1 >=
static_cast<int>(species.stages.size())) {
188 growth.mature =
true;
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;
211 if (species.diseases.empty() || days <= 0.0)
return;
212 if (!isStressed(*organism.vitalNeeds(), species))
return;
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));
222 health.activeDiseaseId = disease.diseaseId;
223 health.diseaseDaysLeft = disease.durationDays;
224 health.diseaseGrowthMul = disease.growthMul;
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;
235 auto& produce = *organism.produce();
236 produce.daysSinceProduce += days;
237 while (produce.daysSinceProduce + 1e-12 >= species.produceIntervalDays) {
238 produce.daysSinceProduce -= species.produceIntervalDays;
243Result<void> GrowthWorld::spawnOffspring(Organism&
parent,
const SpeciesDef& species,
int count) {
245 const std::string offspringId = species.reproduction.offspringSpeciesId.empty()
247 : species.reproduction.offspringSpeciesId;
248 for (
int i = 0; i <
count; ++i) {
257 auto& growth = *
parent.growth();
258 if (species.reproduction.parentDiesOnBirth) {
261 }
else if (species.reproduction.parentResetsStagesOnBirth) {
262 growth.stageIndex = 0;
263 growth.stageProgressDays = 0.0;
264 growth.mature =
false;
265 growth.harvested =
false;
271void GrowthWorld::advanceReproduction(Organism& organism,
const SpeciesDef& species,
double days) {
272 auto& repro = *organism.reproduction();
273 const ReproductionDef& def = species.reproduction;
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;
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");
291 if (!organism.isMature() || organism.isDead())
return;
292 if (!(def.intervalDays > 0.0))
return;
294 repro.daysSinceReproduce += days;
295 while (repro.daysSinceReproduce + 1e-12 >= def.intervalDays && !organism.isDead()) {
296 repro.daysSinceReproduce -= def.intervalDays;
298 def.offspringCountMin + (def.offspringCountMax - def.offspringCountMin) / 2;
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;
306void GrowthWorld::applyDaySlice(Organism& organism,
double days, std::int64_t dayIndexForHash) {
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);
319 if (&carrier == &partner) {
325 "dead organisms cannot breed",
"growth.world.tryBreed"));
329 "both organisms must be mature",
"growth.world.tryBreed"));
339 "species reproduction.mode is not pair_gestation",
340 "growth.world.tryBreed"));
344 "growth.world.tryBreed"));
352 "a partner is already pregnant",
"growth.world.tryBreed"));
355 auto& repro = *carrier.reproduction();
356 repro.pregnant =
true;
357 repro.gestationProgressDays = 0.0;
358 repro.partnerStableId = partner.
stableId();
366 "dead organisms cannot reproduce",
"growth.world.tryReproduce"));
370 "organism must be mature",
"growth.world.tryReproduce"));
381 "species reproduction.mode is not a solo mode",
382 "growth.world.tryReproduce"));
384 organism.reproduction()->daysSinceReproduce = 0.0;
387 return spawnOffspring(organism, *species, std::max(1,
count));
Stable, structured diagnostics shared by engine modules.
const ColourScope * parent
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.
Move-only operation result carrying either a value or Status.
static Result success(T value)
Construct a successful result owning value.
static Result failure(Status status)
Construct a failed result from a structured status.
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.
static const std::vector< Organism * > & liveOrganisms()
Live organisms currently visible to Growth views.
static Result< Organism * > createOrganism(const std::string &speciesId)
Creates an organism bound to a registered species.
std::uint64_t stableId() const noexcept
Stable ECS id for event correlation.
const std::string & speciesId()
static const SpeciesDef * find(const std::string &id)
Looks up a species; nullptr when missing. @ownership Borrowed from the process-wide registry; caller ...
@ 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.
One queued lifecycle observation.
Named vital meter (water, radiation, ether, …) — not fixed to Earth biology.
Species reproduction parameters selected by ReproductionMode.
double gestationDays
PairGestation only.
bool partnerMustSameSpecies
Static species definition — fully data-driven life cycle.
ReproductionDef reproduction
std::string kindId
Free-form lifeform tag (plant, animal, xeno.crystal, …).