载入中...
搜索中...
未找到
Growth.cpp
浏览该文件的文档.
1#include "growth/Growth.h"
2
3#include "common/Diagnostic.h"
5#include "common/Time.h"
6#include "common/Value.h"
7
8#include <cmath>
9#include <simplesquirrel/simplesquirrel.hpp>
10
11namespace eve::growth {
12
14
16
18
19bool Growth::hasSpecies(const std::string& id) const { return SpeciesRegistry::has(id); }
20
22
24
28
32
34
36
38 if (!std::isfinite(seconds) || seconds < 0.0) {
40 "seconds must be finite and >= 0", "growth.stepSeconds"));
41 }
42 auto delta = Duration::fromSeconds(seconds);
43 if (!delta) return Result<void>::failure(delta.status());
45 step.delta = std::move(delta).takeValue();
48}
49
50std::int64_t Growth::dayIndex() const { return GrowthWorld::instance().calendar().dayIndex(); }
51
52std::int64_t Growth::year() const { return GrowthWorld::instance().calendar().year(); }
53
54std::string Growth::seasonName() const { return GrowthWorld::instance().calendar().seasonId(); }
55
56Result<Organism*> Growth::spawn(const std::string& speciesId) { return Organism::createOrganism(speciesId); }
57
58Result<Organism*> Growth::plant(const std::string& speciesId) {
59 auto organism = Organism::createOrganism(speciesId);
60 if (!organism) return organism;
61 Organism* created = organism.value();
62 if (created->kindId() != "plant") {
65 Diagnostic::error(DiagnosticCode::InvalidArgument, "species is not a plant", "growth.plant"));
66 }
67 return organism;
68}
69
70Result<Organism*> Growth::spawnAnimal(const std::string& speciesId) {
71 auto organism = Organism::createOrganism(speciesId);
72 if (!organism) return organism;
73 Organism* created = organism.value();
74 if (created->kindId() != "animal") {
77 Diagnostic::error(DiagnosticCode::InvalidArgument, "species is not an animal", "growth.spawnAnimal"));
78 }
79 return organism;
80}
81
83 if (!carrier || !partner) {
85 Diagnostic::error(DiagnosticCode::InvalidArgument, "breed partners must not be null", "growth.tryBreed"));
86 }
87 return GrowthWorld::instance().tryBreed(*carrier, *partner);
88}
89
91 if (!organism) {
93 Diagnostic::error(DiagnosticCode::InvalidArgument, "organism must not be null", "growth.tryReproduce"));
94 }
95 return GrowthWorld::instance().tryReproduce(*organism);
96}
97
99
101
102std::string Growth::eventKind(int index) const {
103 const GrowthEvent* event = GrowthWorld::instance().events().at(index);
104 if (!event) return {};
105 return GrowthEventLog::kindName(event->kind);
106}
107
108std::uint64_t Growth::eventOrganismId(int index) const {
109 const GrowthEvent* event = GrowthWorld::instance().events().at(index);
110 return event ? event->organismId : 0;
111}
112
113std::string Growth::eventSpeciesId(int index) const {
114 const GrowthEvent* event = GrowthWorld::instance().events().at(index);
115 return event ? event->speciesId : std::string{};
116}
117
118std::string Growth::eventDetail(int index) const {
119 const GrowthEvent* event = GrowthWorld::instance().events().at(index);
120 return event ? event->detail : std::string{};
121}
122
127
128void Growth::expose(ssq::Table& table) {
129 auto cls = table.addClass(name, Growth::create, false);
130 expose(cls);
131
132 auto organism =
133 table.addClass<Organism>("Organism", std::function<Organism*()>([]() -> Organism* { return nullptr; }), false);
134 organism.addFunc("destroy", &Organism::destroy);
135 organism.addFunc("speciesId", &Organism::speciesId);
136 organism.addFunc("stageIndex", &Organism::stageIndex);
137 organism.addFunc("stageId", &Organism::stageId);
138 // SSQ has no double marshalling — project meters/progress as float (same pattern as RPG xp).
139 organism.addFunc("stageProgressDays", [](Organism* self) -> float {
140 return self ? static_cast<float>(self->stageProgressDays()) : 0.f;
141 });
142 organism.addFunc("isMature", &Organism::isMature);
143 organism.addFunc("isDead", &Organism::isDead);
144 organism.addFunc("isHarvested", &Organism::isHarvested);
145 organism.addFunc("isDiseased", &Organism::isDiseased);
146 organism.addFunc("isPregnant", &Organism::isPregnant);
147 organism.addFunc("diseaseId", &Organism::diseaseId);
148 organism.addFunc("waterPermille", [](Organism* self) -> float {
149 return self ? static_cast<float>(self->waterPermille()) : 0.f;
150 });
151 organism.addFunc("foodPermille", [](Organism* self) -> float {
152 return self ? static_cast<float>(self->foodPermille()) : 0.f;
153 });
154 organism.addFunc("fertilityPermille", [](Organism* self) -> float {
155 return self ? static_cast<float>(self->fertilityPermille()) : 0.f;
156 });
157 organism.addFunc("kindId", [](Organism* self) { return self ? self->kindId() : std::string{}; });
158 organism.addFunc("kindName", [](Organism* self) { return self ? self->kindId() : std::string{}; });
159 organism.addFunc("needPermille", [](Organism* self, const std::string& needId) -> float {
160 return self ? static_cast<float>(self->needPermille(needId)) : 0.f;
161 });
162 organism.addFunc("refillNeed", [vm = organism.getHandle()](Organism* self, const std::string& needId, float amount) {
163 if (!self) {
166 Diagnostic::error(DiagnosticCode::InvalidArgument, "organism is null", "growth.organism")));
167 }
168 return eve::script::projectResult(vm, self->refillNeed(needId, static_cast<double>(amount)));
169 });
170 organism.addFunc("waterBy", [vm = organism.getHandle()](Organism* self, float amount) {
171 if (!self) {
174 Diagnostic::error(DiagnosticCode::InvalidArgument, "organism is null", "growth.organism")));
175 }
176 return eve::script::projectResult(vm, self->waterBy(static_cast<double>(amount)));
177 });
178 organism.addFunc("feed", [vm = organism.getHandle()](Organism* self, float amount) {
179 if (!self) {
182 Diagnostic::error(DiagnosticCode::InvalidArgument, "organism is null", "growth.organism")));
183 }
184 return eve::script::projectResult(vm, self->feed(static_cast<double>(amount)));
185 });
186 organism.addFunc("fertilize", [vm = organism.getHandle()](Organism* self, float amount) {
187 if (!self) {
190 Diagnostic::error(DiagnosticCode::InvalidArgument, "organism is null", "growth.organism")));
191 }
192 return eve::script::projectResult(vm, self->fertilize(static_cast<double>(amount)));
193 });
194 organism.addFunc("harvest", [vm = organism.getHandle()](Organism* self) {
195 if (!self) {
197 vm,
198 Result<std::vector<YieldReceipt>>::failure(
199 Diagnostic::error(DiagnosticCode::InvalidArgument, "organism is null", "growth.organism")),
200 [](std::vector<YieldReceipt>) { return eve::Value(); });
201 }
202 return eve::script::projectResult(vm, self->harvest(), [](std::vector<YieldReceipt> yields) {
203 eve::Value::Array rows;
204 rows.reserve(yields.size());
205 for (YieldReceipt& line : yields) {
206 eve::Value::Object row;
207 row.emplace("itemId", eve::Value(std::move(line.itemId)));
208 row.emplace("count", eve::Value(static_cast<std::int64_t>(line.count)));
209 rows.emplace_back(eve::Value(std::move(row)));
210 }
211 return eve::Value(std::move(rows));
212 });
213 });
214}
215
216void Growth::expose(ssq::Class& cls) {
217 cls.addFunc("registerSpeciesFromJson", [vm = cls.getHandle()](Growth* self, const std::string& json) {
218 auto projector = [](int count) { return eve::Value(static_cast<std::int64_t>(count)); };
219 if (!self) {
222 DiagnosticCode::InvalidArgument, "growth module is null", "growth")),
223 projector);
224 }
225 return eve::script::projectResult(vm, self->registerSpeciesFromJson(json), projector);
226 });
227 cls.addFunc("clearSpecies", &Growth::clearSpecies);
228 cls.addFunc("hasSpecies", &Growth::hasSpecies);
229 cls.addFunc("speciesCount", &Growth::speciesCount);
230 cls.addFunc("setDaysPerSeason", [vm = cls.getHandle()](Growth* self, int days) {
231 if (!self) {
234 Diagnostic::error(DiagnosticCode::InvalidArgument, "growth module is null", "growth")));
235 }
236 return eve::script::projectResult(vm, self->setDaysPerSeason(days));
237 });
238 cls.addFunc("setSeasonLayoutFromJson", [vm = cls.getHandle()](Growth* self, const std::string& json) {
239 if (!self) {
242 Diagnostic::error(DiagnosticCode::InvalidArgument, "growth module is null", "growth")));
243 }
244 return eve::script::projectResult(vm, self->setSeasonLayoutFromJson(json));
245 });
246 cls.addFunc("setSecondsPerSimDay", [vm = cls.getHandle()](Growth* self, float seconds) {
247 if (!self) {
250 Diagnostic::error(DiagnosticCode::InvalidArgument, "growth module is null", "growth")));
251 }
252 return eve::script::projectResult(vm, self->setSecondsPerSimDay(static_cast<double>(seconds)));
253 });
254 cls.addFunc("setRngSeed", [](Growth* self, int seed) {
255 if (self) self->setRngSeed(static_cast<std::uint64_t>(seed));
256 });
257 cls.addFunc("advanceDays", [vm = cls.getHandle()](Growth* self, float days) {
258 if (!self) {
261 Diagnostic::error(DiagnosticCode::InvalidArgument, "growth module is null", "growth")));
262 }
263 return eve::script::projectResult(vm, self->advanceDays(static_cast<double>(days)));
264 });
265 cls.addFunc("stepSeconds", [vm = cls.getHandle()](Growth* self, float seconds) {
266 if (!self) {
269 Diagnostic::error(DiagnosticCode::InvalidArgument, "growth module is null", "growth")));
270 }
271 return eve::script::projectResult(vm, self->stepSeconds(static_cast<double>(seconds)));
272 });
273 cls.addFunc("dayIndex", &Growth::dayIndex);
274 cls.addFunc("year", &Growth::year);
275 cls.addFunc("seasonName", &Growth::seasonName);
276 // ECS organism pointers match RPGActor: return borrowed instances; script calls destroy().
277 cls.addFunc("spawn", [](Growth* self, const std::string& speciesId) -> Organism* {
278 if (!self) return nullptr;
279 auto created = self->spawn(speciesId);
280 if (!created) return nullptr;
281 return created.value();
282 });
283 cls.addFunc("plant", [](Growth* self, const std::string& speciesId) -> Organism* {
284 if (!self) return nullptr;
285 auto created = self->plant(speciesId);
286 if (!created) return nullptr;
287 return created.value();
288 });
289 cls.addFunc("spawnAnimal", [](Growth* self, const std::string& speciesId) -> Organism* {
290 if (!self) return nullptr;
291 auto created = self->spawnAnimal(speciesId);
292 if (!created) return nullptr;
293 return created.value();
294 });
295 cls.addFunc("tryBreed", [vm = cls.getHandle()](Growth* self, Organism* carrier, Organism* partner) {
296 if (!self) {
299 Diagnostic::error(DiagnosticCode::InvalidArgument, "growth module is null", "growth")));
300 }
301 return eve::script::projectResult(vm, self->tryBreed(carrier, partner));
302 });
303 cls.addFunc("tryReproduce", [vm = cls.getHandle()](Growth* self, Organism* organism) {
304 if (!self) {
307 Diagnostic::error(DiagnosticCode::InvalidArgument, "growth module is null", "growth")));
308 }
309 return eve::script::projectResult(vm, self->tryReproduce(organism));
310 });
311 cls.addFunc("clearEvents", &Growth::clearEvents);
312 cls.addFunc("eventCount", &Growth::eventCount);
313 cls.addFunc("eventKind", &Growth::eventKind);
314 cls.addFunc("eventOrganismId", [](Growth* self, int index) -> int64_t {
315 return self ? static_cast<int64_t>(self->eventOrganismId(index)) : int64_t{0};
316 });
317 cls.addFunc("eventSpeciesId", &Growth::eventSpeciesId);
318 cls.addFunc("eventDetail", &Growth::eventDetail);
319 cls.addFunc("resetWorld", &Growth::resetWorld);
320}
321
322} // namespace eve::growth
Stable, structured diagnostics shared by engine modules.
HSQUIRRELVM vm
Definition ECS.cpp:38
HSQOBJECT cls
Definition ECS.cpp:39
std::string name
Definition ECS.cpp:154
int rows
#define Module_IMPL(ModuleName, newExpr)
Definition Module.h:27
int created
The single Squirrel projection for common Result, Status and Value.
Common time values and an injectable deterministic simulation clock.
uint32_t seed
Definition TreeMesh.cpp:276
float step
Definition TreeMesh.cpp:451
uint32_t index
Owning, renderer-independent dynamic values.
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
static Result< Duration > fromSeconds(double seconds)
Convert finite seconds to the nearest nanosecond.
Definition Time.cpp:17
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
The canonical owning dynamic value used by data-facing protocols.
Definition Value.h:31
static constexpr StrongUint64 zero() noexcept
Returns the zero value for this strong type.
Result< void > setSeasonLayoutFromJson(std::string_view json)
Parses [{"id":"bloom","days":40},…] and applies setSeasonLayout. @cost Cheap JSON parse of a small ar...
std::string seasonId() const
Current season id string (never empty when layout is valid).
std::int64_t year() const noexcept
0-based year from dayIndex / yearLength.
Result< void > setDaysPerSeason(int days) noexcept
Sets every slot's day count (keeps current ids). Positive only.
std::int64_t dayIndex() const noexcept
Absolute simulation day index (0-based).
const GrowthEvent * at(int index) const
Borrowed event at index, or nullptr when out of range. @ownership Borrowed from this log; caller must...
static const char * kindName(GrowthEventKind kind) noexcept
Stable English spelling for an event kind.
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.
GrowthEventLog & events() noexcept
Result< void > setSecondsPerSimDay(double seconds) noexcept
Seconds of SimulationStep.delta that equal one simulation day.
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).
void setRngSeed(std::uint64_t seed) noexcept
Deterministic seed for disease / yield hash streams.
GrowthCalendar & calendar() noexcept
Result< void > step(const SimulationStep &step)
Converts a fixed SimulationStep into fractional sim days and advances. @cost Linear in live organism ...
Farm growth module facade (eve.Growth): species registry + world step.
Definition Growth.h:19
Result< Organism * > spawn(const std::string &speciesId)
Spawns any registered species (plant, animal, or custom lifeform).
Definition Growth.cpp:56
Result< void > setSecondsPerSimDay(double seconds)
Definition Growth.cpp:29
void setRngSeed(std::uint64_t seed)
Definition Growth.cpp:33
Result< void > advanceDays(double days)
Definition Growth.cpp:35
std::string eventDetail(int index) const
Definition Growth.cpp:118
void resetWorld()
Resets calendar, events, and species for demos/tests.
Definition Growth.cpp:123
int eventCount() const
Definition Growth.cpp:100
Result< int > registerSpeciesFromJson(const std::string &json)
Registers species from a JSON object or array.
Definition Growth.cpp:15
std::string eventSpeciesId(int index) const
Definition Growth.cpp:113
std::int64_t year() const
Definition Growth.cpp:52
void clearSpecies()
Clears species (tests / demos).
Definition Growth.cpp:17
Result< Organism * > plant(const std::string &speciesId)
Convenience: spawn when species.kindId == "plant".
Definition Growth.cpp:58
Result< void > tryReproduce(Organism *organism)
Solo reproduction for self_bud / fission / spore_burst species.
Definition Growth.cpp:90
Result< Organism * > spawnAnimal(const std::string &speciesId)
Convenience: spawn when species.kindId == "animal".
Definition Growth.cpp:70
Result< void > setSeasonLayoutFromJson(const std::string &json)
Configures a custom season layout from JSON (alien year cycles). @cost Cheap: parses a small season t...
Definition Growth.cpp:25
std::uint64_t eventOrganismId(int index) const
Definition Growth.cpp:108
bool hasSpecies(const std::string &id) const
Definition Growth.cpp:19
Result< void > stepSeconds(double seconds)
Definition Growth.cpp:37
std::string eventKind(int index) const
Definition Growth.cpp:102
Result< void > setDaysPerSeason(int days)
Definition Growth.cpp:23
int speciesCount() const
Definition Growth.cpp:21
std::int64_t dayIndex() const
Definition Growth.cpp:50
std::string seasonName() const
Definition Growth.cpp:54
Result< void > tryBreed(Organism *carrier, Organism *partner)
Definition Growth.cpp:82
Growth short-root entity for any configured lifeform.
Definition Organism.h:29
std::string diseaseId()
Definition Organism.cpp:88
void release() override
Definition Organism.h:33
static Result< Organism * > createOrganism(const std::string &speciesId)
Creates an organism bound to a registered species.
Definition Organism.cpp:25
std::string stageId()
Definition Organism.cpp:68
const std::string & speciesId()
Definition Organism.cpp:60
void destroy()
Script destroy entry (aliases release).
Definition Organism.cpp:175
static int count()
Number of registered species.
Definition Species.cpp:546
static void clear()
Clears the table (tests).
Definition Species.cpp:550
static Result< int > loadFromJson(std::string_view json)
Parses a JSON object or array of species and registers each.
Definition Species.cpp:508
static bool has(const std::string &id)
True when id is registered.
Definition Species.cpp:548
ssq::Table projectResult(HSQUIRRELVM vm, Result< void > &&result)
Consume and project a void native Result using the common schema.
One deterministic fixed-step emitted by SimulationClock.
Definition Time.h:158
Duration delta
Fixed simulation duration for this step.
Definition Time.h:162
One queued lifecycle observation.