载入中...
搜索中...
未找到
ECS.cpp
浏览该文件的文档.
1#include "common/ECS.h"
5
6#include <simplesquirrel/simplesquirrel.hpp>
7
8// clang-format off
9// Squirrel internals: recovering a component schema's *declaration order* needs the class
10// member table and the field-index encoding (`_isfield` / `_member_idx`), which the public
11// API cannot express (it only exposes the hash-ordered member iteration of §10.17).
12// The order is load-bearing -- `sqpcheader.h` must come first and clang-format would sort
13// `sqclass.h` ahead of it -- and these have to follow `<simplesquirrel/simplesquirrel.hpp>`,
14// which brings in the public Squirrel types.
15#include "sqpcheader.h"
16#include "sqstring.h"
17#include "sqtable.h"
18#include "sqclass.h"
19#include "sqvm.h" // `_ss(vm)->_instance_default_delegate`(把默认委托装成类成员,见下)
20// clang-format on
21
22#include <algorithm>
23#include <cstdio>
24#include <cstring>
25#include <string>
26#include <unordered_map>
27#include <utility>
28#include <vector>
29
30namespace eve {
31namespace {
32
33// ---------------------------------------------------------------------------
34// Script component registry (name + version → Squirrel class, with generations)
35// ---------------------------------------------------------------------------
36
37struct ScriptComponentEntry {
38 HSQUIRRELVM vm = nullptr;
39 HSQOBJECT cls;
42 std::vector<std::string> fields;
49 std::vector<Value> defaults;
50 ScriptComponentEntry() { sq_resetobject(&cls); }
51 ScriptComponentEntry(HSQUIRRELVM v, HSQOBJECT o, Generation g, std::vector<std::string> f, std::vector<Value> d)
52 : vm(v), cls(o), generation(g), fields(std::move(f)), defaults(std::move(d)) {}
53};
54
58using ScriptComponentKey = std::pair<std::string, std::uint64_t>;
59using ScriptComponentMap = std::map<ScriptComponentKey, ScriptComponentEntry>;
60
61ScriptComponentMap& currentScriptComponents() {
62 static ScriptComponentMap m;
63 return m;
64}
65
68std::vector<ScriptComponentRecord>& retiredScriptComponents() {
69 static std::vector<ScriptComponentRecord> v;
70 return v;
71}
72
73int& nextEntityId() {
74 static int id = 1;
75 return id;
76}
77
78int allocEntityId() { return nextEntityId()++; }
79
80// 当前 VM 的 Squirrel 类对象 → 脚本 view() 收集函数。
81std::unordered_map<const void*, CppEntityViewFn>& cppEntityViews() {
82 static std::unordered_map<const void*, CppEntityViewFn> views;
83 return views;
84}
85
86std::vector<std::function<void(ssq::Table&)>>& postEcsHooks() {
87 static std::vector<std::function<void(ssq::Table&)>> hooks;
88 return hooks;
89}
90
91bool& ecsScriptInjected() {
92 static bool injected = false;
93 return injected;
94}
95
96size_t& postEcsHooksFlushed() {
97 static size_t n = 0;
98 return n;
99}
100
101// ---------------------------------------------------------------------------
102// Class helpers
103// ---------------------------------------------------------------------------
104
105bool isSubclassOf(HSQUIRRELVM vm, HSQOBJECT child, HSQOBJECT base) {
106 if (child._type != OT_CLASS || base._type != OT_CLASS) return false;
107 const SQInteger top = sq_gettop(vm);
108 sq_pushobject(vm, child);
109 for (int guard = 0; guard < 64; ++guard) {
110 if (sq_gettype(vm, -1) != OT_CLASS) break;
111 HSQOBJECT cur;
112 sq_getstackobj(vm, -1, &cur);
113 if (cur._unVal.pClass == base._unVal.pClass) {
114 sq_settop(vm, top);
115 return true;
116 }
117 if (SQ_FAILED(sq_getbase(vm, -1))) break;
118 sq_remove(vm, -2); // drop current, keep base
119 if (sq_gettype(vm, -1) != OT_CLASS) break;
120 }
121 sq_settop(vm, top);
122 return false;
123}
124
126void collectClassFields(HSQUIRRELVM vm, HSQOBJECT clsObj, HSQOBJECT outTable) {
127 const SQInteger top = sq_gettop(vm);
128 sq_pushobject(vm, outTable); // out
129 sq_pushobject(vm, clsObj); // out, cls
130 sq_pushnull(vm); // out, cls, iter
131 while (SQ_SUCCEEDED(sq_next(vm, -2))) {
132 // out, cls, iter, key, value
133 if (sq_gettype(vm, -2) == OT_STRING) {
134 const SQChar* key = nullptr;
135 sq_getstring(vm, -2, &key);
136 if (key && key[0] != '_') {
137 const SQObjectType vt = sq_gettype(vm, -1);
138 if (vt != OT_CLOSURE && vt != OT_NATIVECLOSURE && vt != OT_GENERATOR) {
139 sq_push(vm, -5); // out
140 sq_push(vm, -3); // key
141 sq_push(vm, -3); // value
142 sq_rawset(vm, -3);
143 sq_pop(vm, 1); // pop out
144 }
145 }
146 }
147 sq_pop(vm, 2); // key, value
148 }
149 sq_settop(vm, top);
150}
151
153struct DeclaredField {
154 std::string name;
155 SQObjectPtr key;
156};
157
170std::vector<DeclaredField> declaredFields(HSQOBJECT clsObj) {
171 std::vector<std::pair<SQInteger, DeclaredField>> ordered;
172 SQClass* klass = _class(clsObj);
173 if (klass == nullptr || klass->_members == nullptr) return {};
174
175 SQObjectPtr key;
176 SQObjectPtr value;
177 SQObjectPtr refpos; // `Next` 的游标是它自己返回的整数下标,不是 key(传 key 会命中 TranslateIndex 的断言)
178 SQInteger index = 0;
179 while ((index = klass->_members->Next(false, refpos, key, value)) != -1) {
180 refpos = SQObjectPtr(index);
181 if (sq_type(key) != OT_STRING || !_isfield(value)) continue;
182 const SQChar* name = _stringval(key);
183 if (name == nullptr || name[0] == '_') continue;
184 ordered.emplace_back(static_cast<SQInteger>(_member_idx(value)), DeclaredField{name, key});
185 }
186 std::sort(ordered.begin(), ordered.end(), [](const auto& a, const auto& b) { return a.first < b.first; });
187
188 std::vector<DeclaredField> out;
189 out.reserve(ordered.size());
190 for (auto& entry : ordered) out.push_back(std::move(entry.second));
191 return out;
192}
193
195std::vector<std::string> fieldNames(const std::vector<DeclaredField>& fields) {
196 std::vector<std::string> names;
197 names.reserve(fields.size());
198 for (const DeclaredField& field : fields) names.push_back(field.name);
199 return names;
200}
201
202ssq::Table inspectClassFields(ssq::Object clsObj) {
203 HSQUIRRELVM vm = clsObj.getHandle();
204 ssq::Table out(vm);
205 if (clsObj.getType() != ssq::Type::CLASS) return out;
206 collectClassFields(vm, clsObj.getRaw(), out.getRaw());
207 return out;
208}
209
211Result<Value> classFieldDefault(HSQUIRRELVM vm, HSQOBJECT clsObj, const std::string& field) {
212 const SQInteger top = sq_gettop(vm);
213 sq_pushobject(vm, clsObj);
214 sq_pushstring(vm, field.c_str(), static_cast<SQInteger>(field.size()));
215 if (SQ_FAILED(sq_get(vm, -2))) {
216 sq_settop(vm, top);
218 DiagnosticCode::NotFound, "component field default is not readable", field, {}, "ecs.component"));
219 }
220 const SQInteger valueIndex = sq_gettop(vm);
221 Result<Value> value = script::valueFromSquirrel(vm, valueIndex);
222 sq_settop(vm, top);
223 return value;
224}
225
227struct ScriptComponentSchema {
228 ScriptComponentRecord record;
230 const std::vector<Value>* defaults = nullptr;
231};
232
240bool schemaOfComponentClass(HSQOBJECT cls, ScriptComponentSchema* out) {
241 const SQClass* klass = _class(cls);
242 if (klass == nullptr) return false;
243 for (const auto& [key, entry] : currentScriptComponents()) {
244 if (_class(entry.cls) != klass) continue;
245 if (out != nullptr) {
246 out->record.name = key.first;
247 out->record.version = SchemaVersion(key.second);
248 out->record.generation = entry.generation;
249 out->record.retired = false;
250 out->record.fields = entry.fields;
251 out->defaults = &entry.defaults;
252 }
253 return true;
254 }
255 return false;
256}
257
258bool dropScriptComponentValues(std::uint64_t entityId) { return removeScriptComponentValues(entityId) > 0; }
259
260// ---------------------------------------------------------------------------
261// 已登记组件的字段接缝:`_get` / `_set` 把脚本字段读写接到引擎侧存储
262// ---------------------------------------------------------------------------
263
265bool instanceSlot(HSQUIRRELVM vm, SQInteger index, const char* name, HSQOBJECT* out) {
266 const SQInteger top = sq_gettop(vm);
267 const SQInteger self = index < 0 ? top + index + 1 : index;
268 sq_pushstring(vm, name, -1);
269 if (SQ_FAILED(sq_get(vm, self))) {
270 sq_settop(vm, top);
271 return false;
272 }
273 if (out != nullptr) sq_getstackobj(vm, -1, out);
274 sq_settop(vm, top);
275 return true;
276}
277
279bool instanceIdentity(HSQUIRRELVM vm, SQInteger index, ScriptComponentStoreKey* out) {
280 HSQOBJECT eid{};
281 HSQOBJECT name{};
282 HSQOBJECT version{};
283 if (!instanceSlot(vm, index, "_ownerEid", &eid) || sq_type(eid) != OT_INTEGER) return false;
284 if (!instanceSlot(vm, index, "_componentName", &name) || sq_type(name) != OT_STRING) return false;
285 if (!instanceSlot(vm, index, "_componentVersion", &version) || sq_type(version) != OT_INTEGER) return false;
286 if (_integer(eid) <= 0 || _stringval(name)[0] == '\0') return false;
287 out->entityId = static_cast<std::uint64_t>(_integer(eid));
288 out->name = _stringval(name);
289 out->version = SchemaVersion(static_cast<std::uint64_t>(_integer(version)));
290 return true;
291}
292
294std::string stackFieldName(HSQUIRRELVM vm, SQInteger index) {
295 const SQChar* text = nullptr;
296 if (SQ_FAILED(sq_getstring(vm, index, &text)) || text == nullptr) return {};
297 return text;
298}
299
301SQInteger scriptComponentFieldGet(HSQUIRRELVM vm) {
302 const SQInteger top = sq_gettop(vm);
303 ScriptComponentStoreKey key;
304 if (!instanceIdentity(vm, 1, &key)) return sq_throwerror(vm, _SC("component instance is not bound to an entity"));
305 if (sq_gettype(vm, 2) != OT_STRING) return sq_throwerror(vm, _SC("component field name must be a string"));
306
307 const std::string field = stackFieldName(vm, 2);
308 Result<Value> value = scriptComponentField(key, field);
309 if (!value.ok()) {
310 sq_settop(vm, top);
311 return sq_throwerror(vm, ("'" + field + "' is not a declared field of component '" + key.name + "'").c_str());
312 }
313 Result<void> pushed = script::pushValue(vm, value.value());
314 if (!pushed.ok()) {
315 sq_settop(vm, top);
316 return sq_throwerror(vm, pushed.status().describe().c_str());
317 }
318 return 1;
319}
320
322SQInteger scriptComponentFieldSet(HSQUIRRELVM vm) {
323 const SQInteger top = sq_gettop(vm);
324 ScriptComponentStoreKey key;
325 if (!instanceIdentity(vm, 1, &key)) return sq_throwerror(vm, _SC("component instance is not bound to an entity"));
326 if (sq_gettype(vm, 2) != OT_STRING) return sq_throwerror(vm, _SC("component field name must be a string"));
327
328 const std::string field = stackFieldName(vm, 2);
329 Result<Value> value = script::valueFromSquirrel(vm, 3);
330 if (!value.ok()) {
331 sq_settop(vm, top);
332 return sq_throwerror(vm, value.status().describe().c_str());
333 }
334 Result<void> written = setScriptComponentField(key, field, std::move(value).takeValue());
335 if (!written.ok()) {
336 sq_settop(vm, top);
337 return sq_throwerror(vm, ("'" + field + "' is not a declared field of component '" + key.name + "'").c_str());
338 }
339 sq_settop(vm, top);
340 sq_push(vm, 3);
341 return 1;
342}
343
345bool classDefinesFieldSeam(HSQOBJECT clsObj) {
346 SQClass* klass = _class(clsObj);
347 if (klass == nullptr) return false;
348 return sq_type(klass->_metamethods[MT_GET]) != OT_NULL || sq_type(klass->_metamethods[MT_SET]) != OT_NULL;
349}
350
352void installInstanceDelegateMembers(HSQUIRRELVM vm, HSQOBJECT clsObj);
353
363Result<void> installComponentFieldSeam(HSQUIRRELVM vm, HSQOBJECT clsObj, const std::vector<DeclaredField>& fields) {
364 if (classDefinesFieldSeam(clsObj))
367 "component class defines _get/_set itself; the engine field seam needs those two names",
368 {}, {}, "ecs.component"));
369
370 const SQInteger top = sq_gettop(vm);
371 sq_pushobject(vm, clsObj);
372 const auto install = [&](const char* name, SQFUNCTION fn) {
373 sq_pushstring(vm, name, -1);
374 sq_newclosure(vm, fn, 0);
375 sq_newslot(vm, -3, SQFalse);
376 };
377 install("_get", scriptComponentFieldGet);
378 install("_set", scriptComponentFieldSet);
379
380 if (_class(clsObj) != nullptr) {
381 for (const DeclaredField& field : fields) _class(clsObj)->_members->Remove(field.key);
382 }
383 installInstanceDelegateMembers(vm, clsObj);
384 sq_settop(vm, top);
386}
387
399void installInstanceDelegateMembers(HSQUIRRELVM vm, HSQOBJECT clsObj) {
400 SQClass* klass = _class(clsObj);
401 if (klass == nullptr) return;
402 SQTable* delegates = _table(_ss(vm)->_instance_default_delegate);
403 if (delegates == nullptr) return;
404
405 SQObjectPtr key;
406 SQObjectPtr value;
407 SQObjectPtr refpos;
408 SQInteger index = 0;
409 while ((index = delegates->Next(false, refpos, key, value)) != -1) {
410 refpos = SQObjectPtr(index);
411 if (sq_type(key) != OT_STRING || sq_type(value) != OT_NATIVECLOSURE) continue;
412 klass->NewSlot(_ss(vm), key, value, false);
413 }
414}
415
430ssq::Object bindComponentValues(std::uint64_t entityId, ssq::Object instance) {
431 HSQUIRRELVM vm = instance.getHandle();
432 ssq::Object none(vm);
433 if (instance.getType() != ssq::Type::INSTANCE) return none;
434
435 // 类对象只**借用**:实例自己持有类引用(`SQInstance::SQInstance` 里 `__ObjAddRef(_class)`),
436 // 所以查完注册表、把类弹出栈之后,注册表里那份引用仍然有效。
437 const SQInteger top = sq_gettop(vm);
438 sq_pushobject(vm, instance.getRaw());
439 HSQOBJECT cls{};
440 if (SQ_FAILED(sq_getclass(vm, -1))) {
441 sq_settop(vm, top);
442 return none;
443 }
444 sq_getstackobj(vm, -1, &cls);
445
446 ScriptComponentSchema schema;
447 const bool known = schemaOfComponentClass(cls, &schema);
448 sq_settop(vm, top);
449 if (!known) return none;
450
451 const ScriptComponentStoreKey key{entityId, schema.record.name, schema.record.version};
452 const auto stamp = [&](const char* name, const auto& push) {
453 const SQInteger inner = sq_gettop(vm);
454 sq_pushobject(vm, instance.getRaw());
455 sq_pushstring(vm, name, -1);
456 push();
457 sq_rawset(vm, -3); // raw:`_set` 是字段接缝,控制槽位不能从那里走
458 sq_settop(vm, inner);
459 };
460 stamp("_ownerEid", [&] { sq_pushinteger(vm, static_cast<SQInteger>(entityId)); });
461 stamp("_componentName", [&] { sq_pushstring(vm, schema.record.name.c_str(), -1); });
462 stamp("_componentVersion", [&] { sq_pushinteger(vm, static_cast<SQInteger>(schema.record.version.value())); });
463
464 if (findScriptComponentValues(key) == nullptr) {
466 const std::vector<Value>& declared = *schema.defaults;
467 const std::vector<std::string>& fields = schema.record.fields;
468 for (std::size_t i = 0; i < fields.size(); ++i)
469 values.emplace(fields[i], i < declared.size() ? declared[i] : Value::null());
471 .ignore("a component whose values cannot be stored would silently lose its data if this succeeded");
472 }
473
474 ssq::Array names(vm);
475 for (const std::string& field : schema.record.fields) names.push(field);
476 return names;
477}
478
479bool scriptIsSubclass(ssq::Object child, ssq::Object base) {
480 if (child.getType() != ssq::Type::CLASS || base.getType() != ssq::Type::CLASS) return false;
481 return isSubclassOf(child.getHandle(), child.getRaw(), base.getRaw());
482}
483
484ssq::Object getClassBase(ssq::Object cls) {
485 HSQUIRRELVM vm = cls.getHandle();
486 ssq::Object ret(vm);
487 if (cls.getType() != ssq::Type::CLASS) return ret;
488 const SQInteger top = sq_gettop(vm);
489 sq_pushobject(vm, cls.getRaw());
490 if (SQ_FAILED(sq_getbase(vm, -1)) || sq_gettype(vm, -1) != OT_CLASS) {
491 sq_settop(vm, top);
492 return ret;
493 }
494 sq_getstackobj(vm, -1, &ret.getRaw());
495 sq_addref(vm, &ret.getRaw());
496 sq_settop(vm, top);
497 return ret;
498}
499
500// ---------------------------------------------------------------------------
501// Injected Squirrel runtime
502// ---------------------------------------------------------------------------
503
504const char* kEcsScript = R"SQ(
505// Script ECS: define Component / Entity classes, create instances, view & System.
506// Mirrors ECS.hpp's class + component model for Squirrel game logic.
507
508if (!("Number" in eve)) eve.Number <- "number"
509if (!("Boolean" in eve)) eve.Boolean <- "boolean"
510if (!("String" in eve)) eve.String <- "string"
511
512eve._ecsTypes <- {} // EntityClass -> { cls, instances }
513
514// --- 性能缓存(万级实体稳态零分配) ---
515// view 结果缓存:create/destroy 时按类链失效;C++ 桥接类(_cppHasView=true)不缓存。
516eve._ecsViewCache <- {} // EntityClass -> array
517eve._ecsSlotsCache <- {} // EntityClass -> { fieldName = ComponentClass }
518eve._ecsFieldSlotsCache <- {} // EntityClass -> { fieldName = true }:只有这些槽位有真实字段
519eve._ecsCompDefaults <- {} // ComponentClass -> { fieldName = resolvedDefault }
520eve._ecsRevision <- 0 // increments on script entity structural changes
521
522function eve::_ecsResolveMarker(v) {
523 if (v == this.Number || v == "number") return 0.0
524 if (v == this.Boolean || v == "boolean") return false
525 if (v == this.String || v == "string") return ""
526 return v
527}
528
529function eve::_ecsIsComponentClass(obj) {
530 if (typeof obj != "class") return false
531 return this.isSubclass(obj, this.Component)
532}
533
534// 解析"类型标记"(`x = eve.Number` → `0.0`):只处理**当前值本身是标记**的字段,其它字段
535// 一律不碰,所以这个函数可以重复跑(实例化、热重载迁移都调它),不会覆盖已有数据。
536//
537// `declared` 是引擎侧给的字段名数组(登记组件)或 null(未登记组件)。登记组件的声明默认值
538// 已经按 schema 落在引擎侧存储里,`c[name]` 走 `_get` 读到的就是它;未登记组件从类声明读。
539// 两种组件因此共用同一段解析,标记规则仍然只有这一处实现(§9.64.4)。
540function eve::_ecsResolveComponentMarkers(compClass, c, declared) {
541 local fields = {}
542 if (declared != null) {
543 foreach (name in declared) fields[name] <- true
544 } else {
545 fields = this.inspectClassFields(compClass)
546 }
547 local resolved = {}
548 foreach (name, val in fields) {
549 local cur = null
550 try { cur = c[name] } catch (e) { cur = null }
551 if (cur == this.Number || cur == this.Boolean || cur == this.String
552 || cur == "number" || cur == "boolean" || cur == "string") {
553 c[name] = this._ecsResolveMarker(cur)
554 resolved[name] <- c[name]
555 }
556 }
557 return resolved
558}
559
560function eve::_ecsInstantiateComponent(compClass, ownerEid = 0) {
561 local c = compClass()
562 // 先盖归属、按 schema 建引擎侧数据条目,**再**写默认值:已登记组件的字段槽位在登记时就被摘掉、
563 // `_set` 已装好,所以下面那些 `c[name] = val` 实际上是**写进引擎存储**,必须有个已绑定的条目
564 // 接着(顺序反了就会报 "not bound to an entity")。
565 // 返回值是这一代的字段名(声明顺序):槽位摘掉之后 `inspectClassFields` 什么也看不到,
566 // 而"类型标记"还得按声明顺序解析。未登记组件返回 null。
567 local declared = eve._ecsBindComponentValues(ownerEid, c)
568 if (compClass in this._ecsCompDefaults) {
569 foreach (name, val in this._ecsCompDefaults[compClass]) c[name] = val
570 } else {
571 this._ecsCompDefaults[compClass] <- this._ecsResolveComponentMarkers(compClass, c, declared)
572 }
573 return c
574}
575
576function eve::_ecsCollectSlots(cls) {
577 if (cls in this._ecsSlotsCache) return this._ecsSlotsCache[cls]
578 // { fieldName = ComponentClass } walking base classes (Entity → … → cls).
579 local slots = {}
580 local cur = cls
581 local guard = 0
582 while (cur != null && guard < 64) {
583 if (!this.isSubclass(cur, this.Entity)) break
584
585 local declared = null
586 try { declared = cur.components } catch (e) { declared = null }
587 if (typeof declared == "table") {
588 foreach (k, v in declared) {
589 if (!(k in slots) && this._ecsIsComponentClass(v))
590 slots[k] <- v
591 }
592 }
593
594 local fields = this.inspectClassFields(cur)
595 foreach (k, v in fields) {
596 if (k == "components") continue
597 if (!(k in slots) && this._ecsIsComponentClass(v))
598 slots[k] <- v
599 }
600
601 cur = this.getClassBase(cur)
602 guard += 1
603 }
604 this._ecsSlotsCache[cls] <- slots
605 return slots
606}
607
608// 哪些槽位在实体类里有**真实字段**(`pos = Pos` 或 `pos = null`),哪些只是登记在
609// `static components` 表里。判据是"这个类有没有声明同名的非函数成员",而不是"它的值
610// 是不是组件类"——`static components = { pos = Pos }` + `pos = null` 这种写法里字段值
611// 是 null,但字段确实存在、可以赋值。
612//
613// 只有有字段的槽位能用 `e.pos` 访问:Squirrel 拒绝对 class 实例新建槽位,所以
614// `e[name] = c` 对未声明的键会抛 "the index 'name' does not exist"(`=` 编译成
615// _OP_SET;只有 `<-` 才是 new-slot 操作码,报的是另一句
616// "class instances do not support the new slot operator")。
617function eve::_ecsCollectFieldSlots(cls) {
618 if (cls in this._ecsFieldSlotsCache) return this._ecsFieldSlotsCache[cls]
619 local fields = {}
620 local cur = cls
621 local guard = 0
622 while (cur != null && guard < 64) {
623 if (!this.isSubclass(cur, this.Entity)) break
624 foreach (k, v in this.inspectClassFields(cur)) {
625 if (k == "components") continue
626 if (!(k in fields)) fields[k] <- true
627 }
628 cur = this.getClassBase(cur)
629 guard += 1
630 }
631 this._ecsFieldSlotsCache[cls] <- fields
632 return fields
633}
634
635function eve::_ecsInvalidateViews(cls) {
636 local cur = cls
637 local guard = 0
638 while (cur != null && guard < 64) {
639 if (cur in this._ecsViewCache) delete this._ecsViewCache[cur]
640 if (!this.isSubclass(cur, this.Entity)) break
641 cur = this.getClassBase(cur)
642 guard += 1
643 }
644}
645
646function eve::_ecsEnsureType(cls) {
647 if (cls in this._ecsTypes) return this._ecsTypes[cls]
648 local info = { cls = cls, instances = [] }
649 this._ecsTypes[cls] <- info
650 return info
651}
652
653function eve::_ecsRegisterInstance(entity, cls) {
654 this._ecsEnsureType(cls).instances.push(entity)
655 this._ecsRevision += 1
656 this._ecsInvalidateViews(cls)
657}
658
659function eve::_ecsUnregisterInstance(entity, cls) {
660 if (!(cls in this._ecsTypes)) return
661 local arr = this._ecsTypes[cls].instances
662 for (local i = arr.len() - 1; i >= 0; --i) {
663 if (arr[i] == entity) {
664 // O(1) swap-remove(顺序不保证);视图缓存随后失效重建
665 local last = arr.len() - 1
666 if (i != last) arr[i] = arr[last]
667 arr.pop()
668 this._ecsRevision += 1
669 break
670 }
671 }
672 this._ecsInvalidateViews(cls)
673}
674
675function eve::_ecsCollectInstances(cls, out) {
676 foreach (key, info in this._ecsTypes) {
677 if (info.cls == cls || this.isSubclass(info.cls, cls)) {
678 foreach (e in info.instances) {
679 if (e != null && e.isAlive()) out.push(e)
680 }
681 }
682 }
683 // 稳定顺序:按实体 id 升序(= 创建顺序)。
684 //
685 // `_ecsUnregisterInstance` 用 swap-remove 保持 O(1) 销毁,所以 instances 数组本身的
686 // 顺序在删除后会变——实测 [1,2,3,4] 删掉 2 得到 [1,4,3]。而 GPU System 按**视图顺序**
687 // 把实体打包成 buffer 的行,回读时又按同一顺序写回(`unpackEcsFloats(ents, …)`),
688 // `requestUploadRange/requestReadbackRange(first, count)` 更是直接按行号寻址:顺序一变,
689 // "第 i 行是哪个实体"就变了,回读的值会落到另一个实体上。
690 //
691 // id 由 `eve.allocEntityId()` 单调分配且**不复用**,所以按 id 排序给出一个跨子类也
692 // 成立的全序;`_ecsTypes` 的散列遍历顺序因此不再影响结果。排序只发生在缓存重建时
693 // (结构性变更后第一次取视图),每帧取视图仍然是 O(n) 拷贝。
694 out.sort(function(a, b) { return a._eid - b._eid })
695}
696
697// ---------------------------------------------------------------------------
698// 热重载迁移(方案文档实施顺序第 3 步)
699// ---------------------------------------------------------------------------
700
701// 未登记组件的字段只存在实例槽位里,换实例就会丢:把旧实例**声明过的**字段值搬到新实例上。
702// 枚举类而不是实例——实例不可枚举(`foreach (k, v in instance)` 抛 "_nexti failed"),类可枚举;
703// 而 `fresh[name] = old[name]` 对新类声明过的成员成功、对没声明的抛错,正是这里要的过滤
704// (与 `load.nut` 的 `migrate_instance` 同一套理由)。
705//
706// 已登记组件的字段槽位在登记时就被摘掉了,所以 `inspectClassFields(旧类)` 是空表、这里什么也
707// 不搬——那些数据本来就在引擎侧存储里,按 (实体, 名字, 版本) 寻址,换代时由 C++ 侧对齐 schema。
708function eve::_ecsCopyDeclaredFields(old, fresh) {
709 if (typeof old != "instance") return 0
710 local declared = null
711 try { declared = this.inspectClassFields(old.getclass()) } catch (e) { return 0 }
712 local copied = 0
713 foreach (name, value in declared) {
714 try { fresh[name] = old[name]; copied += 1 } catch (e) { }
715 }
716 return copied
717}
718
719// 把一个实体的一个组件槽位换到**新代类**的实例上。返回 false 表示换不了(调用方据此报出来)。
720function eve::_ecsRepointComponent(e, slotName, oldComp, compClass, fieldSlots) {
721 local fresh = compClass()
722 local declared = eve._ecsBindComponentValues(e._eid, fresh)
723 if (declared == null && typeof oldComp == "instance" && oldComp._componentName != "") {
724 // 旧实例是**已登记**组件的实例,而新类不是同一身份的登记(登记没跟着换代):
725 // 接管过去只会得到一个读不了字段的实例,宁可留着旧的并报出来。
726 return false
727 }
728 if (!(compClass in this._ecsCompDefaults)) {
729 this._ecsCompDefaults[compClass] <- this._ecsResolveComponentMarkers(compClass, fresh, declared)
730 } else if (declared != null) {
731 // 已登记组件:默认值在引擎侧存储里,这里**不能**把缓存默认值写回去——那会把迁移
732 // 保留下来的旧值冲掉。只补新字段的类型标记。
733 this._ecsResolveComponentMarkers(compClass, fresh, declared)
734 } else {
735 foreach (name, val in this._ecsCompDefaults[compClass]) fresh[name] = val
736 }
737 if (declared == null) this._ecsCopyDeclaredFields(oldComp, fresh)
738 e._comps[slotName] = fresh
739 if (slotName in fieldSlots) e[slotName] = fresh
740 return true
741}
742
759function eve::_ecsMigrateAfterReload(oldBindings, rootTable) {
760 local replacements = {};
761 if (rootTable == null) return { entities = 0, components = 0, unresolved = 0 };
762 foreach (name, oldClass in oldBindings) {
763 if (typeof oldClass != "class" || !(name in rootTable)) continue;
764 local newClass = rootTable[name];
765 if (typeof newClass != "class" || newClass == oldClass) continue;
766 if (!this.isSubclass(newClass, this.Component) && !this.isSubclass(newClass, this.Entity)) continue;
767 replacements[oldClass] <- newClass;
768 }
769
770 // 第 1 步:换键。旧项一律删掉,否则热重载每来一次就多一组看不见的实例(§9.42.5 第 5 点)。
771 foreach (oldClass, newClass in replacements) {
772 if (oldClass in this._ecsTypes) {
773 this._ecsTypes[newClass] <- this._ecsTypes[oldClass];
774 this._ecsTypes[newClass].cls = newClass;
775 delete this._ecsTypes[oldClass];
776 }
777 if (oldClass in this._ecsViewCache) delete this._ecsViewCache[oldClass];
778 if (oldClass in this._ecsSlotsCache) delete this._ecsSlotsCache[oldClass];
779 if (oldClass in this._ecsFieldSlotsCache) delete this._ecsFieldSlotsCache[oldClass];
780 if (oldClass in this._ecsCompDefaults) delete this._ecsCompDefaults[oldClass];
781 }
782
783 // 第 2 步:接实例。
784 local entities = 0;
785 local components = 0;
786 local unresolved = 0;
787 foreach (etype, info in this._ecsTypes) {
788 local slots = this._ecsCollectSlots(etype); // 按新类重算:它引用的是新组件类
789 local fieldSlots = this._ecsCollectFieldSlots(etype);
790 foreach (e in info.instances) {
791 if (e == null || !e.isAlive()) continue;
792 e._etype = etype;
793 e._slots = slots;
794 foreach (slotName, compClass in slots) {
795 if (!(slotName in e._comps)) continue;
796 local old = e._comps[slotName];
797 if (old == null) continue;
798 if (compClass in replacements) {
799 // 实体类没被重写:槽位还指向**旧**组件类,引擎改不了类的字段默认值。
800 unresolved += 1;
801 continue;
802 }
803 if (typeof old == "instance" && old.getclass() == compClass) continue;
804 if (this._ecsRepointComponent(e, slotName, old, compClass, fieldSlots)) components += 1;
805 else unresolved += 1;
806 }
807 entities += 1;
808 }
809 this._ecsInvalidateViews(etype);
810 }
811 if (entities > 0) this._ecsRevision += 1;
812 return { entities = entities, components = components, unresolved = unresolved };
813}
814
815eve.Component <- class {
816 // 引擎侧数据条目的归属。必须是**已声明**成员:Squirrel 的实例只能写已声明槽位,而
817 // `_get`/`_set` 要靠它们找到"这份数据属于哪个实体的哪个组件"。`_` 前缀保证它们
818 // 不会被当成组件字段收进 schema(见 declaredInstanceFields 的过滤)。
819 _ownerEid = 0
820 _componentName = ""
821 _componentVersion = 0
822
823 constructor() {
824 _ownerEid = 0
825 _componentName = ""
826 _componentVersion = 0
827 }
828}
829
830eve.Entity <- class {
831 _eid = 0
832 _alive = false
833 _etype = null
834 _slots = null
835 _comps = null
836
837 constructor() {
838 _eid = 0
839 _alive = false
840 _etype = null
841 _slots = null
842 _comps = null
843 }
844
845 static function create() {
846 local e = this()
847 e._etype = this
848 e._eid = eve.allocEntityId()
849 e._alive = true
850 e._slots = eve._ecsCollectSlots(this)
851 e._comps = {}
852 local fieldSlots = eve._ecsCollectFieldSlots(this)
853 foreach (name, compClass in e._slots) {
854 // 传实体 id:已登记组件据此盖归属、建引擎侧数据条目(见 `_ecsInstantiateComponent`)。
855 local c = eve._ecsInstantiateComponent(compClass, e._eid)
856 e._comps[name] <- c
857 // 已声明的槽位(`pos = Pos`)同时写进实体字段,于是 `e.pos` 与
858 // `e.getComponent(Pos)` 是**同一个对象**,两条路径读写一致(实测,见 §9.38)。
859 // 只登记在 `static components` 表里、没有同名字段的槽位没有字段可写,它只
860 // 能经 getComponent()/hasComponent() 访问。这里因此按"是否真实字段"分流,
861 // 而不是用 try/catch 把真正的失败吞掉。
862 if (name in fieldSlots) e[name] = c
863 }
864 eve._ecsRegisterInstance(e, this)
865 return e
866 }
867
868 // Declare a component slot on this entity class (optional sugar).
869 static function component(name, compClass) {
870 if (!("components" in this) || typeof this.components != "table")
871 this.components <- {}
872 this.components[name] <- compClass
873 return this
874 }
875
876 function getId() { return _eid }
877 function isAlive() { return _alive }
878
879 function getComponent(compClass) {
880 if (_slots == null || _comps == null) return null
881 foreach (name, cls in _slots) {
882 if (cls == compClass) {
883 if (name in _comps) return _comps[name]
884 return null
885 }
886 }
887 return null
888 }
889
890 function hasComponent(compClass) {
891 return getComponent(compClass) != null
892 }
893
894 function destroy() {
895 if (!_alive) return
896 _alive = false
897 if (_etype != null) eve._ecsUnregisterInstance(this, _etype)
898 // 组件状态一并释放。留着它的话,销毁后的实体仍然可读可写、却对任何 view 无效
899 // (静默 no-op),而且每个组件对象都被这个已销毁的实体继续引用着。
900 // 两条引用都要清:`_comps` 是槽位表,已声明字段槽位是 `e.pos` 那条路。只清前者
901 // 会让 `e.pos` 继续指向一个活着的组件实例,于是对已销毁实体写 `e.pos.x = 1`
902 // 会静默改一个孤儿——正是上面要避免的状态。`this[name] = null` 对**已声明**成员
903 // 是普通赋值,实测不抛("会抛"的旧结论是把 `<-` 的行为记到了 `=` 上,见 §9.38)。
904 if (_slots != null && _etype != null) {
905 local fieldSlots = eve._ecsCollectFieldSlots(_etype)
906 foreach (name, compClass in _slots) {
907 if (name in fieldSlots) this[name] = null
908 }
909 }
910 _comps = null
911 // 引擎侧的组件数据也要清:它是权威存储,留着就是"销毁后仍可读"的孤儿数据。
912 eve._ecsDropComponentValues(_eid)
913 }
914}
915
916// Historical name from early game examples
917eve.EntityContainer <- eve.Entity
918
919eve.System <- class {
920 _query = null
921
922 constructor(query = null) {
923 _query = query
924 }
925
926 function setQuery(query) { _query = query }
927
928 function entities() {
929 if (_query == null) return []
930 if (typeof _query == "array") {
931 local out = []
932 foreach (q in _query) {
933 foreach (e in eve.view(q)) out.push(e)
934 }
935 return out
936 }
937 return eve.view(_query)
938 }
939
940 function update(dt) {}
941}
942
943// GPU-backed System: pack float component fields → SSBO → compute shader → unpack.
944// Requires eve.Gpgpu / eve.EcsShaderSystem (gpgpu module). Push constants:
945// pc.data[0] = dt, pc.data[1] = entityCount. Each bindFields() maps one binding.
946eve.ShaderSystem <- class extends eve.System {
947 _gpu = null
948 _backend = null
949 _bindings = null
950 _readback = true
951 _localSize = 64
952
953 constructor(query = null, gpu = null, glsl = null, localSize = 64) {
954 base.constructor(query)
955 _bindings = []
956 _readback = true
957 _localSize = localSize
958 if (gpu != null) setGpgpu(gpu)
959 if (gpu != null && glsl != null) setShaderSource(glsl)
960 }
961
962 function setGpgpu(gpu) {
963 _gpu = gpu
964 if (_backend == null) {
965 if (!("EcsShaderSystem" in eve))
966 throw "eve.ShaderSystem requires gpgpu module (eve.EcsShaderSystem)"
967 _backend = eve.EcsShaderSystem()
968 }
969 _backend.setGpgpu(gpu)
970 _backend.setLocalSize(_localSize)
971 return this
972 }
973
974 function setShaderSource(glsl) {
975 if (_backend == null) throw "eve.ShaderSystem.setShaderSource: call setGpgpu first"
976 _backend.setShaderSource(glsl)
977 return this
978 }
979
980 function setLocalSize(n) {
981 _localSize = n
982 if (_backend != null) _backend.setLocalSize(n)
983 return this
984 }
985
986 function setReadback(enabled) {
987 _readback = enabled
988 return this
989 }
990
991 // binding: SSBO index; slot: entity component field name; fields: ["x","y",...]
992 // uploadEachUpdate=false keeps the buffer GPU-resident after its initial upload.
993 // readback=false leaves results resident until requestReadback() is called.
994 function bindFields(binding, slot, fields, uploadEachUpdate = true, readback = null) {
995 _bindings.push({ binding = binding, slot = slot, fields = fields,
996 uploadEachUpdate = uploadEachUpdate,
997 readback = readback, uploadedRevision = -1,
998 uploadRequested = false, readbackRequested = false,
999 uploadFirst = 0, uploadCount = 0,
1000 readbackFirst = 0, readbackCount = 0,
1001 source = null, sourceBinding = -1,
1002 initializeFromCpu = true, schema = null })
1003 return this
1004 }
1005
1006 // Typed binding schema: { slot, fields, scalar="f32", access="read_write" }.
1007 // write-only bindings allocate storage without an unnecessary CPU upload.
1008 function bindSchema(binding, schema, uploadEachUpdate = false, readback = false) {
1009 if (typeof schema != "table" || !("slot" in schema) || !("fields" in schema))
1010 throw "eve.ShaderSystem.bindSchema: schema requires slot and fields"
1011 if (typeof schema.slot != "string" || typeof schema.fields != "array" ||
1012 schema.fields.len() <= 0)
1013 throw "eve.ShaderSystem.bindSchema: invalid slot or fields"
1014 foreach (field in schema.fields)
1015 if (typeof field != "string")
1016 throw "eve.ShaderSystem.bindSchema: every field must be a string"
1017 local scalar = "scalar" in schema ? schema.scalar : "f32"
1018 if (scalar != "f32")
1019 throw "eve.ShaderSystem.bindSchema: only f32 is currently supported"
1020 local access = "access" in schema ? schema.access : "read_write"
1021 if (access != "read" && access != "write" && access != "read_write")
1022 throw "eve.ShaderSystem.bindSchema: access must be read, write, or read_write"
1023 local normalized = { slot = schema.slot, fields = schema.fields,
1024 scalar = scalar, access = access,
1025 strideFloats = schema.fields.len() }
1026 _bindings.push({ binding = binding, slot = schema.slot, fields = schema.fields,
1027 uploadEachUpdate = access == "write" ? false : uploadEachUpdate,
1028 readback = readback, uploadedRevision = -1,
1029 uploadRequested = false, readbackRequested = false,
1030 uploadFirst = 0, uploadCount = 0,
1031 readbackFirst = 0, readbackCount = 0,
1032 source = null, sourceBinding = -1,
1033 initializeFromCpu = access != "write", schema = normalized })
1034 return this
1035 }
1036
1037 function getBindingSchema(binding) {
1038 foreach (b in _bindings) if (b.binding == binding) return b.schema
1039 return null
1040 }
1041
1042 // Generate backend declaration boilerplate; the kernel body remains explicit.
1043 function shaderDeclarations(language = "glsl") {
1044 local out = ""
1045 foreach (b in _bindings) {
1046 if (b.schema == null) continue
1047 if (language == "glsl") {
1048 local qualifier = b.schema.access == "read" ? "readonly " :
1049 b.schema.access == "write" ? "writeonly " : ""
1050 out += "layout(set = 0, binding = " + b.binding + ") " + qualifier +
1051 "buffer EcsBinding" + b.binding + " { float data[]; } ecs" +
1052 b.binding + ";\n"
1053 } else if (language == "wgsl") {
1054 local access = b.schema.access == "read" ? "read" : "read_write"
1055 out += "@group(0) @binding(" + b.binding + ") var<storage, " + access +
1056 "> ecs" + b.binding + " : array<f32>;\n"
1057 } else {
1058 throw "eve.ShaderSystem.shaderDeclarations: language must be glsl or wgsl"
1059 }
1060 }
1061 return out
1062 }
1063
1064 // Reuse another ShaderSystem's resident buffer without a CPU round trip.
1065 // The source system is retained and must be prepared before this consumer.
1066 function bindSharedFields(binding, sourceSystem, sourceBinding, slot, fields,
1067 readback = false) {
1068 if (sourceSystem == null)
1069 throw "eve.ShaderSystem.bindSharedFields: source system is null"
1070 _bindings.push({ binding = binding, slot = slot, fields = fields,
1071 uploadEachUpdate = false, readback = readback,
1072 uploadedRevision = -1, uploadRequested = false,
1073 readbackRequested = false, uploadFirst = 0, uploadCount = 0,
1074 readbackFirst = 0, readbackCount = 0,
1075 source = sourceSystem, sourceBinding = sourceBinding,
1076 initializeFromCpu = false, schema = null })
1077 return this
1078 }
1079
1080 function setBindingUpload(binding, enabled) {
1081 foreach (b in _bindings) if (b.binding == binding) b.uploadEachUpdate = enabled
1082 return this
1083 }
1084
1085 function setBindingReadback(binding, enabled) {
1086 foreach (b in _bindings) if (b.binding == binding) b.readback = enabled
1087 return this
1088 }
1089
1090 // Re-upload CPU component values on the next update. binding < 0 selects all.
1091 function requestUpload(binding = -1) {
1092 foreach (b in _bindings) {
1093 if ((binding < 0 || b.binding == binding) && b.source == null) {
1094 b.uploadRequested = true
1095 b.uploadFirst = 0
1096 b.uploadCount = -1
1097 }
1098 }
1099 return this
1100 }
1101
1102 // Re-upload a stable contiguous entity range. Repeated requests are coalesced.
1103 function requestUploadRange(binding, firstEntity, entityCount) {
1104 if (firstEntity < 0 || entityCount <= 0)
1105 throw "eve.ShaderSystem.requestUploadRange: invalid entity range"
1106 foreach (b in _bindings) {
1107 if (b.binding != binding) continue
1108 if (b.source != null)
1109 throw "eve.ShaderSystem.requestUploadRange: shared binding is GPU-owned"
1110 if (!b.uploadRequested || b.uploadCount == 0) {
1111 b.uploadFirst = firstEntity
1112 b.uploadCount = entityCount
1113 } else if (b.uploadCount >= 0) {
1114 local oldEnd = b.uploadFirst + b.uploadCount
1115 local newEnd = firstEntity + entityCount
1116 local end = oldEnd > newEnd ? oldEnd : newEnd
1117 b.uploadFirst = b.uploadFirst < firstEntity ? b.uploadFirst : firstEntity
1118 b.uploadCount = end - b.uploadFirst
1119 }
1120 b.uploadRequested = true
1121 }
1122 return this
1123 }
1124
1125 // Read GPU values back after the next update. binding < 0 selects all.
1126 function requestReadback(binding = -1) {
1127 foreach (b in _bindings) {
1128 if (binding < 0 || b.binding == binding) {
1129 b.readbackRequested = true
1130 b.readbackFirst = 0
1131 b.readbackCount = -1
1132 }
1133 }
1134 return this
1135 }
1136
1137 // Read back a stable contiguous entity range. Repeated requests are coalesced.
1138 function requestReadbackRange(binding, firstEntity, entityCount) {
1139 if (firstEntity < 0 || entityCount <= 0)
1140 throw "eve.ShaderSystem.requestReadbackRange: invalid entity range"
1141 foreach (b in _bindings) {
1142 if (b.binding != binding) continue
1143 if (!b.readbackRequested || b.readbackCount == 0) {
1144 b.readbackFirst = firstEntity
1145 b.readbackCount = entityCount
1146 } else if (b.readbackCount >= 0) {
1147 local oldEnd = b.readbackFirst + b.readbackCount
1148 local newEnd = firstEntity + entityCount
1149 local end = oldEnd > newEnd ? oldEnd : newEnd
1150 b.readbackFirst = b.readbackFirst < firstEntity ? b.readbackFirst : firstEntity
1151 b.readbackCount = end - b.readbackFirst
1152 }
1153 b.readbackRequested = true
1154 }
1155 return this
1156 }
1157
1158 function setFloat(index, value) {
1159 if (_backend != null) _backend.setFloat(index, value)
1160 return this
1161 }
1162
1163 function getBackend() { return _backend }
1164
1165 // Register renderer resources and submit a standard 80-byte GpuInstance binding
1166 // without copying the instance stream back through the CPU.
1167 function setGpuDrivenEnabled(enabled) {
1168 if (_gpu == null) throw "eve.ShaderSystem.setGpuDrivenEnabled: call setGpgpu first"
1169 _gpu.setGpuDrivenEnabled(enabled)
1170 return this
1171 }
1172
1173 function gpuDrivenMeshRecord(mesh) {
1174 if (_gpu == null) throw "eve.ShaderSystem.gpuDrivenMeshRecord: call setGpgpu first"
1175 return _gpu.gpuDrivenMeshRecord(mesh)
1176 }
1177
1178 function gpuDrivenMaterialRecord(material) {
1179 if (_gpu == null)
1180 throw "eve.ShaderSystem.gpuDrivenMaterialRecord: call setGpgpu first"
1181 return _gpu.gpuDrivenMaterialRecord(material)
1182 }
1183
1184 function submitResidentInstances(binding, buckets, instanceCount = -1,
1185 offsetBytes = 0) {
1186 if (_gpu == null || _backend == null)
1187 throw "eve.ShaderSystem.submitResidentInstances: call setGpgpu first"
1188 local buffer = _backend.getBuffer(binding)
1189 if (buffer == null)
1190 throw "eve.ShaderSystem.submitResidentInstances: binding has no buffer"
1191 if (instanceCount < 0) instanceCount = entities().len()
1192 return _gpu.submitResidentInstances(buffer, buckets, instanceCount, offsetBytes)
1193 }
1194
1195 function _prepareGpuBatch() {
1196 if (_backend == null || _gpu == null) return
1197 if (!("packEcsFloats" in eve) || !("unpackEcsFloats" in eve)) return
1198
1199 local ents = entities()
1200 local n = ents.len()
1201 if (n <= 0) return null
1202
1203 foreach (b in _bindings) {
1204 local floatsPer = b.fields.len()
1205 if (floatsPer <= 0) continue
1206 if (b.source != null) {
1207 local sourceBackend = b.source.getBackend()
1208 local sourceBuffer = sourceBackend == null ? null :
1209 sourceBackend.getBuffer(b.sourceBinding)
1210 if (sourceBuffer == null)
1211 throw "eve.ShaderSystem shared source must be prepared before consumer"
1212 if (sourceBuffer.getSize() < n * floatsPer * 4)
1213 throw "eve.ShaderSystem shared buffer is smaller than consumer view"
1214 _backend.attachBuffer(b.binding, sourceBuffer)
1215 continue
1216 }
1217 local buf = _backend.ensureBuffer(b.binding, n * floatsPer)
1218 local structureChanged = b.uploadedRevision != eve._ecsRevision
1219 local fullUpload = (structureChanged && (b.initializeFromCpu || b.uploadRequested)) ||
1220 b.uploadEachUpdate ||
1221 (b.uploadRequested && b.uploadCount < 0)
1222 if (fullUpload) {
1223 eve.packEcsFloats(ents, b.slot, b.fields, buf)
1224 b.uploadedRevision = eve._ecsRevision
1225 b.uploadRequested = false
1226 b.uploadCount = 0
1227 } else if (structureChanged) {
1228 // Output-only schema: capacity/order changed, but the shader is
1229 // authoritative and promises to initialize every accessed record.
1230 b.uploadedRevision = eve._ecsRevision
1231 } else if (b.uploadRequested) {
1232 if (!("packEcsFloatsRange" in eve))
1233 throw "eve.ShaderSystem.requestUploadRange requires gpgpu range packing"
1234 eve.packEcsFloatsRange(ents, b.slot, b.fields, buf,
1235 b.uploadFirst, b.uploadCount)
1236 b.uploadRequested = false
1237 b.uploadCount = 0
1238 }
1239 }
1240 return { entities = ents, count = n }
1241 }
1242
1243 function _completeGpuBatch(batch) {
1244 if (batch == null) return
1245 local ents = batch.entities
1246 local n = batch.count
1247 foreach (b in _bindings) {
1248 local shouldReadback = b.readback == null ? _readback : b.readback
1249 if (shouldReadback || (b.readbackRequested && b.readbackCount < 0)) {
1250 local floatsPer = b.fields.len()
1251 if (floatsPer <= 0) continue
1252 local buf = _backend.getBuffer(b.binding)
1253 eve.unpackEcsFloats(ents, b.slot, b.fields, buf, n)
1254 b.readbackRequested = false
1255 b.readbackCount = 0
1256 } else if (b.readbackRequested) {
1257 if (!("unpackEcsFloatsRange" in eve))
1258 throw "eve.ShaderSystem.requestReadbackRange requires gpgpu range unpacking"
1259 local buf = _backend.getBuffer(b.binding)
1260 eve.unpackEcsFloatsRange(ents, b.slot, b.fields, buf,
1261 b.readbackFirst, b.readbackCount)
1262 b.readbackRequested = false
1263 b.readbackCount = 0
1264 }
1265 }
1266 }
1267
1268 // Record into a shared GpuSequence. Call completeRecorded(batch) after submit().
1269 function record(sequence, dt) {
1270 if (sequence == null) throw "eve.ShaderSystem.record: sequence is null"
1271 local batch = _prepareGpuBatch()
1272 if (batch != null) _backend.recordDispatch(sequence, batch.count, dt)
1273 return batch
1274 }
1275
1276 function completeRecorded(batch) {
1277 _completeGpuBatch(batch)
1278 return this
1279 }
1280
1281 function update(dt) {
1282 local batch = _prepareGpuBatch()
1283 if (batch == null) return
1284 _backend.dispatch(batch.count, dt)
1285 _completeGpuBatch(batch)
1286 }
1287}
1288
1289function eve::view(entityClass) {
1290 if (entityClass == null) return []
1291 // C++ 桥接类的实体在脚本外增删(无法通知脚本),不缓存,每次新鲜收集
1292 local cppBacked = false
1293 if ("_cppHasView" in this) cppBacked = this._cppHasView(entityClass)
1294
1295 // 每次调用都返回**新数组**:缓存只保存脚本侧收集结果(遍历 _ecsTypes 才是贵的
1296 // 那一步),绝不外借。否则调用方 sort/pop/append 自己的视图就会污染其他使用者。
1297 local out = []
1298 if (cppBacked) {
1299 this._ecsCollectInstances(entityClass, out)
1300 } else {
1301 if (!(entityClass in this._ecsViewCache)) {
1302 local collected = []
1303 this._ecsCollectInstances(entityClass, collected)
1304 this._ecsViewCache[entityClass] <- collected
1305 }
1306 local cached = this._ecsViewCache[entityClass]
1307 local count = cached.len()
1308 out.resize(count)
1309 for (local i = 0; i < count; ++i) out[i] = cached[i]
1310 }
1311 if ("_cppCollect" in this) this._cppCollect(entityClass, out)
1312 // No sort here. Entities appended by a registered C++ collector
1313 // (registerCppEntityView) are not `eve.Entity` instances and have no `_eid`; sorting them
1314 // threw "the index '_eid' does not exist" (caught by ECS.script.cppCreatedEntitiesVisible).
1315 // The collector owns their order; the id-ordered contract covers script instances, which
1316 // `_ecsCollectInstances` already sorted.
1317 return out
1318}
1319
1320function eve::ecsReady() {
1321 // This function is installed only after the complete ECS script has run.
1322 // Avoid probing the delegated eve table here: Squirrel's `in` lookup may
1323 // invoke its lazy _get handler and turn a readiness query into an error.
1324 return true
1325}
1326)SQ";
1327
1328void injectEcsScript(ssq::Table& eveTable) {
1329 HSQUIRRELVM vm = eveTable.getHandle();
1330 const SQInteger top = sq_gettop(vm);
1331 if (SQ_FAILED(sq_compilebuffer(vm, kEcsScript,
1332 static_cast<SQInteger>(std::strlen(kEcsScript)),
1333 "ecs.nut", SQTrue))) {
1334 sq_settop(vm, top);
1335 const script::ScriptErrorContext ctx = script::captureCompileError(vm);
1336 std::fprintf(stderr, "EVEngine: ECS bootstrap script failed to compile: %s\n",
1337 ctx.empty() ? "unknown error" : ctx.message.c_str());
1338 return;
1339 }
1340 sq_pushroottable(vm);
1341 if (SQ_FAILED(sq_call(vm, 1, SQFalse, SQTrue))) {
1342 const script::ScriptErrorContext ctx = script::takeLastScriptError(vm);
1343 std::fprintf(stderr, "EVEngine: ECS bootstrap script failed to run: %s\n",
1344 ctx.empty() ? "unknown error"
1345 : script::formatScriptError(ctx).c_str());
1346 }
1347 sq_settop(vm, top);
1348}
1349
1355void cppCollect(ssq::Class cls, ssq::Array out) {
1356 HSQUIRRELVM vm = cls.getHandle();
1357 const SQInteger top = sq_gettop(vm);
1358 sq_pushobject(vm, cls.getRaw());
1359 for (int guard = 0; guard < 64; ++guard) {
1360 if (sq_gettype(vm, -1) != OT_CLASS)
1361 break;
1362 HSQOBJECT cur;
1363 sq_getstackobj(vm, -1, &cur);
1364 auto it = cppEntityViews().find(cur._unVal.pClass);
1365 if (it != cppEntityViews().end()) {
1366 sq_settop(vm, top);
1367 it->second(out);
1368 return;
1369 }
1370 if (SQ_FAILED(sq_getbase(vm, -1)))
1371 break;
1372 sq_remove(vm, -2); // drop current class, keep base
1373 }
1374 sq_settop(vm, top);
1375}
1376
1382bool cppHasView(ssq::Object cls) {
1383 if (cls.getType() != ssq::Type::CLASS) return false;
1384 HSQUIRRELVM vm = cls.getHandle();
1385 const SQInteger top = sq_gettop(vm);
1386 sq_pushobject(vm, cls.getRaw());
1387 for (int guard = 0; guard < 64; ++guard) {
1388 if (sq_gettype(vm, -1) != OT_CLASS) break;
1389 HSQOBJECT cur;
1390 sq_getstackobj(vm, -1, &cur);
1391 if (cppEntityViews().find(cur._unVal.pClass) != cppEntityViews().end()) {
1392 sq_settop(vm, top);
1393 return true;
1394 }
1395 if (SQ_FAILED(sq_getbase(vm, -1))) break;
1396 sq_remove(vm, -2); // drop current class, keep base
1397 }
1398 sq_settop(vm, top);
1399 return false;
1400}
1401
1402} // namespace
1403
1404Result<Value> readScriptComponentField(const ssq::Object& instance, const std::string& field) {
1405 if (instance.getType() != ssq::Type::INSTANCE)
1407 "component field access needs a component instance", field, {},
1408 "ecs.component"));
1409 HSQUIRRELVM vm = instance.getHandle();
1410 if (vm == nullptr)
1412 "component field access needs a live script VM", field, {},
1413 "ecs.component"));
1414
1415 const SQInteger top = sq_gettop(vm);
1416 sq_pushobject(vm, instance.getRaw());
1417
1418 ScriptComponentStoreKey key;
1419 if (instanceIdentity(vm, -1, &key)) { // 登记过:字段在引擎侧存储里
1420 Result<Value> stored = scriptComponentField(key, field);
1421 sq_settop(vm, top);
1422 return stored;
1423 }
1424
1425 // 没登记(或登记了但没绑定实体):槽位语义,直接读实例成员。这里的 `sq_get` 对实例其实也会
1426 // 兜底跑 `_get`(`FallBackGet` 的 OT_INSTANCE 分支),但未登记组件的类上根本没装那个元方法;
1427 // 直读槽位既是最便宜的,也不依赖"谁装了什么"。
1428 sq_pushstring(vm, field.c_str(), static_cast<SQInteger>(field.size()));
1429 if (SQ_FAILED(sq_get(vm, -2))) {
1430 sq_settop(vm, top);
1432 DiagnosticCode::NotFound, "script component instance has no such field", field, {}, "ecs.component"));
1433 }
1434 Result<Value> slot = script::valueFromSquirrel(vm, -1);
1435 sq_settop(vm, top);
1436 return slot;
1437}
1438
1439Result<void> writeScriptComponentField(const ssq::Object& instance, const std::string& field, const Value& value) {
1440 if (instance.getType() != ssq::Type::INSTANCE)
1442 "component field access needs a component instance", field, {},
1443 "ecs.component"));
1444 HSQUIRRELVM vm = instance.getHandle();
1445 if (vm == nullptr)
1447 "component field access needs a live script VM", field, {},
1448 "ecs.component"));
1449
1450 const SQInteger top = sq_gettop(vm);
1451 sq_pushobject(vm, instance.getRaw());
1452
1453 ScriptComponentStoreKey key;
1454 if (instanceIdentity(vm, -1, &key)) { // 登记过:写引擎侧存储(脚本侧下一次读就看见)
1455 Result<void> written = setScriptComponentField(key, field, value);
1456 sq_settop(vm, top);
1457 return written;
1458 }
1459
1460 sq_pushstring(vm, field.c_str(), static_cast<SQInteger>(field.size()));
1461 Result<void> pushed = script::pushValue(vm, value);
1462 if (!pushed.ok()) {
1463 sq_settop(vm, top);
1464 return pushed;
1465 }
1466 // `sq_set`(而非 `sq_rawset`):失败时只返回 SQ_ERROR,不会顺手把 VM 的 last-error 也设上,
1467 // 调用方拿到的是一条干净的 `NotFound`。
1468 if (SQ_FAILED(sq_set(vm, -3))) {
1469 sq_settop(vm, top);
1471 DiagnosticCode::NotFound, "script component instance has no such field", field, {}, "ecs.component"));
1472 }
1473 sq_settop(vm, top);
1475}
1476
1477Result<void> registerScriptComponent(const std::string& name, SchemaVersion version, const ssq::Object& cls) {
1478 if (name.empty())
1480 DiagnosticCode::InvalidArgument, "script component name must not be empty", {}, {}, "ecs.component"));
1481 if (version.isZero())
1483 "script component version must be a positive integer", name, {},
1484 "ecs.component"));
1485 if (cls.getType() != ssq::Type::CLASS)
1487 "eve.component needs a class, not a value or instance", name, {},
1488 "ecs.component"));
1489
1490 HSQUIRRELVM vm = cls.getHandle();
1491 HSQOBJECT o = cls.getRaw();
1492 sq_addref(vm, &o);
1493
1494 // 登记时读出这一代声明的字段(按声明顺序):它既是组件的 schema,也是"取走字段槽位、
1495 // 让引擎成为权威存储"要用的清单——必须先读出来,才能安全地摘掉。
1496 const std::vector<DeclaredField> fields = declaredFields(o);
1497 const std::vector<std::string> names = fieldNames(fields);
1498
1499 // 声明默认值也是 schema 的一部分,而且**只能在摘槽位之前**读:摘掉之后类和实例上都没有它了,
1500 // 而建引擎侧数据条目、以及将来热重载迁移换代都要按这个默认值来。
1501 std::vector<Value> defaults;
1502 defaults.reserve(names.size());
1503 for (const std::string& field : names) {
1504 Result<Value> value = classFieldDefault(vm, o, field);
1505 defaults.push_back(value.ok() ? std::move(value).takeValue() : Value::null());
1506 }
1507
1508 // 摘槽位 + 装 `_get`/`_set`:从这一刻起这个组件的字段读写都进引擎侧存储。用户类自己
1509 // 定义了 `_get`/`_set` 时这里返回 AlreadyExists,且**不做任何改动**(不覆盖、不摘槽位)。
1510 Result<void> seam = installComponentFieldSeam(vm, o, fields);
1511 if (!seam.ok()) {
1512 sq_release(vm, &o);
1513 return seam;
1514 }
1515
1516 auto& current = currentScriptComponents();
1517 const auto key = ScriptComponentKey{name, version.value()};
1518 auto found = current.find(key);
1519 if (found == current.end()) {
1520 current.emplace(key, ScriptComponentEntry(vm, o, Generation(1), names, std::move(defaults)));
1522 }
1523
1524 // Same name and version again: hot reload redefined the class. Record the retired
1525 // generation (metadata only) and advance the counter, so a caller can tell that the
1526 // identity it holds refers to an older generation of the same component. The retired
1527 // row keeps the *previous* field list: migration needs to know which fields it moves.
1528 const Generation previous = found->second.generation;
1529 retiredScriptComponents().push_back(ScriptComponentRecord{name, version, previous, true, found->second.fields});
1530 const auto next = previous.incremented();
1531 if (!next)
1533 "script component generation counter is exhausted", name, {},
1534 "ecs.component"));
1535 // 同名同版本再登记 = 热重载换了一代:已存在的字段数据要按**新 schema** 对齐——两代都有的
1536 // 字段保留旧值、新代新增的字段补声明默认值、旧代删掉的字段丢弃。少了这一步,脚本改一次
1537 // 类定义就会出现两种静默错误:新加的字段永远读不到(存储里没有它),被删掉的字段一直留着
1538 // 并被序列化/编辑器看见。字段数据按 (实体, 名字, 版本) 寻址,所以换代时能就地迁移。
1540
1541 // Only release a reference belonging to *this* VM: a stale entry from another VM must
1542 // not be released, because that VM may already be destroyed and sq_release() would
1543 // dereference its freed RefTable (measured access violation, plan doc §9.49).
1544 if (found->second.vm == vm) sq_release(found->second.vm, &found->second.cls);
1545 found->second = ScriptComponentEntry(vm, o, *next, names, std::move(defaults));
1547}
1548
1550 static ScriptComponentRecord scratch;
1551 const auto& current = currentScriptComponents();
1552 const auto found = current.find(ScriptComponentKey{name, version.value()});
1553 if (found == current.end()) return nullptr;
1554 scratch = ScriptComponentRecord{found->first.first, version, found->second.generation, false, found->second.fields};
1555 return &scratch;
1556}
1557
1558std::vector<ScriptComponentRecord> scriptComponentRecords() {
1559 std::vector<ScriptComponentRecord> out;
1560 out.reserve(currentScriptComponents().size() + retiredScriptComponents().size());
1561 for (const auto& [key, entry] : currentScriptComponents())
1562 out.push_back(
1563 ScriptComponentRecord{key.first, SchemaVersion(key.second), entry.generation, false, entry.fields});
1564 for (const ScriptComponentRecord& retired : retiredScriptComponents()) out.push_back(retired);
1565 std::sort(out.begin(), out.end(), [](const ScriptComponentRecord& a, const ScriptComponentRecord& b) {
1566 if (a.name != b.name) return a.name < b.name;
1567 if (a.version != b.version) return a.version < b.version;
1568 return a.generation < b.generation;
1569 });
1570 return out;
1571}
1572
1574 const auto& current = currentScriptComponents();
1575 const auto found = current.find(ScriptComponentKey{name, version.value()});
1576 if (found == current.end())
1577 return Result<ScriptComponentDeclaredSchema>::failure(Diagnostic::error(
1578 DiagnosticCode::NotFound, "script component is not registered in this VM", name, {}, "ecs.component"));
1579
1581 out.name = found->first.first;
1582 out.version = version;
1583 out.generation = found->second.generation;
1584 out.fields = found->second.fields;
1585 out.defaults = found->second.defaults;
1587}
1588
1589void exposeECS(ssq::Table& table) {
1590 table.set("Number", std::string("number"));
1591 table.set("Boolean", std::string("boolean"));
1592 table.set("String", std::string("string"));
1593 // ecsReady / view / Entity / Component are provided by the injected script.
1594
1595 table.addFunc("inspectClassFields", inspectClassFields);
1596 table.addFunc("isSubclass", scriptIsSubclass);
1597 table.addFunc("getClassBase", getClassBase);
1598 table.addFunc("allocEntityId", allocEntityId);
1599 table.addFunc("_cppHasView", cppHasView);
1600 // `eve.component(name, version, cls)` registers the component's *identity*. It is
1601 // optional today (classes keep working unregistered), but it is what lets a hot
1602 // reload match a redefined class to the instances created by the previous one.
1603 table.addFunc("component", [vm = table.getHandle()](std::string name, int version, ssq::Object cls) {
1604 return script::projectResult(
1605 vm, registerScriptComponent(name, SchemaVersion(static_cast<std::uint64_t>(version)), cls));
1606 });
1607 table.addFunc("_cppCollect", std::function<void(ssq::Class, ssq::Array)>(cppCollect));
1608 // 已登记组件在引擎侧的数据:实例化时盖归属、按 schema 建条目(`_ecsBindComponentValues`),
1609 // 销毁实体时一并清掉。返回这一代的**字段名数组**,未登记时返回 null——脚本侧据此保持
1610 // 纯槽位语义,并在槽位已被摘掉的情况下仍能按声明顺序解析类型标记。
1611 table.addFunc("_ecsBindComponentValues",
1612 [](std::uint64_t entityId, ssq::Object instance) { return bindComponentValues(entityId, instance); });
1613 table.addFunc("_ecsDropComponentValues",
1614 [](std::uint64_t entityId) { return dropScriptComponentValues(entityId); });
1615
1616 injectEcsScript(table);
1617
1618 ecsScriptInjected() = true;
1619 // A new VM re-runs every hook (SceneEntity class, …) against this table.
1620 postEcsHooksFlushed() = 0;
1621 flushPostEcsHooks(table);
1622}
1623
1625 // Class identities belong to one VM. Clear them when a new eve table is
1626 // prepared, before any lazy/native exposer registers the next VM's classes.
1627 cppEntityViews().clear();
1628 // Script component registrations (eve.component) hold a Squirrel reference
1629 // into the VM that made them. By the time the next table is prepared that VM
1630 // is already destroyed, so the entries must be dropped **without** releasing:
1631 // sq_release() on a destroyed VM is a use-after-free (see the plan doc §9.49).
1632 // The retired-generation history is per VM too: generations count reloads of one
1633 // VM's script, so a new VM starts with no identity history.
1634 currentScriptComponents().clear();
1635 retiredScriptComponents().clear();
1636 // 引擎侧组件数据同样属于"一个 VM 的脚本世界":新 VM 从空开始。
1638 ecsScriptInjected() = false;
1639 postEcsHooksFlushed() = 0;
1640}
1641
1643 cppEntityViews()[cls.getRaw()._unVal.pClass] = std::move(fn);
1644}
1645
1647 postEcsHooks().push_back(std::move(fn));
1648}
1649
1650void flushPostEcsHooks(ssq::Table& table) {
1651 if (!ecsScriptInjected()) return;
1652 auto& hooks = postEcsHooks();
1653 auto& n = postEcsHooksFlushed();
1654 while (n < hooks.size()) {
1655 try {
1656 hooks[n](table);
1657 } catch (...) {
1658 // A failing module hook must not break VM exposure.
1659 }
1660 ++n;
1661 }
1662}
1663
1664void exposeECSToVM(ssq::VM& vm) {
1665 try {
1666 ssq::Table eveTable(vm.find("eve"));
1667 exposeECS(eveTable);
1668 } catch (...) {
1669 }
1670}
1671
1672} // namespace eve
double m[16]
std::vector< std::unique_ptr< ScriptClimbingEventSink > > retired
struct SQVM * HSQUIRRELVM
HSQUIRRELVM vm
Definition ECS.cpp:38
HSQOBJECT cls
Definition ECS.cpp:39
std::vector< Value > defaults
Definition ECS.cpp:49
SQObjectPtr key
Definition ECS.cpp:155
Generation generation
Definition ECS.cpp:40
ScriptComponentRecord record
Definition ECS.cpp:228
std::string name
Definition ECS.cpp:154
std::vector< std::string > fields
Definition ECS.cpp:42
std::vector< std::uint8_t > stored
Definition Evpack.cpp:171
std::string message
tensor::Graph g
Definition GpuGraph.cpp:7
glm::vec3 n
Definition Grass.cpp:63
bool seam
float v
std::int32_t second
bool ordered
std::string id
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
std::shared_ptr< const OceanSprayFrame > previous
float f
std::string script
Definition PlayHost.cpp:117
std::set< std::string > values
Object::Ptr value
float d
std::string slot
bool found
脚本组件字段的引擎侧权威存储。
std::string text
ScriptStructure out
size_t end
double current
The single Squirrel projection for common Result, Status and Value.
Heightmap stamp
float size
Definition TreeMesh.cpp:158
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
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Definition Status.cpp:19
static Value null()
Compatibility factory for a null value.
Definition Value.h:113
std::map< std::string, Value > Object
Definition Value.h:34
static Value object(Object value)
Compatibility factory for an object value.
Definition Value.cpp:129
SQInteger top
Definition Snapshot.cpp:115
const Value * field(const Value &value, const char *key)
Borrow an optional object field.
std::variant< std::monostate, std::int64_t, double, std::string, bool > Value
Definition Database.h:27
constexpr HexDirection next(HexDirection d) noexcept
The next direction clockwise (NW wraps to NE).
Definition HexMetrics.h:76
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...
std::string formatScriptError(const ScriptErrorContext &ctx)
Formats a context into a human-readable multi-line report.
ScriptErrorContext takeLastScriptError(HSQUIRRELVM vm)
Consumes and clears the last recorded error for a VM.
Result< void > pushValue(HSQUIRRELVM vm, const Value &value, const SquirrelValueOptions &options)
Push a canonical Value into the active Squirrel VM.
ScriptErrorContext captureCompileError(HSQUIRRELVM vm)
Captures the last compilation error recorded by the VM.
Result< Value > valueFromSquirrel(HSQUIRRELVM vm, SQInteger index, const SquirrelValueOptions &options)
Convert one Squirrel value into the canonical owning Value tree.
Build metadata (engine git commit, build time, third-party version).
Definition Build.cpp:16
std::size_t removeScriptComponentValues(std::uint64_t entityId)
实体销毁时清掉它的全部组件数据。
void exposeECSToVM(ssq::VM &vm)
在 ModuleManager::expose 之后调用;保证 eve.Component 等不被其它模块覆盖。
Definition ECS.cpp:1664
const Value * findScriptComponentValues(const ScriptComponentStoreKey &key)
读一条组件数据。
detail::StrongUint64< detail::GenerationTag > Generation
Registry/object replacement generation used to reject stale handles.
Definition Generation.h:13
Result< ScriptComponentDeclaredSchema > scriptComponentDeclaredSchema(const std::string &name, SchemaVersion version)
读一条已登记组件的声明 schema(字段名 + 声明默认值)。
Definition ECS.cpp:1573
Result< void > setScriptComponentValues(const ScriptComponentStoreKey &key, Value values)
写入一条组件的引擎侧数据(创建实体、或迁移到新代时调用)。
void exposeECS(ssq::Table &table)
脚本侧 ECS:Entity / Component / System / ShaderSystem / view(见 ECS.cpp)。 C++ 游戏实体仍直接用 ECS....
Definition ECS.cpp:1589
void prepareEcsScriptInjection()
Resets per-VM script injection bookkeeping before a new VM is exposed.
Definition ECS.cpp:1624
EVENGINE_API_FOUNDATION Result< Value > readScriptComponentField(const ssq::Object &instance, const std::string &field)
读一个脚本组件实例的字段,**不关心这个字段存在哪**。
void registerPostEcsHook(PostEcsHook fn)
Registers post ecs hook.
Definition ECS.cpp:1646
detail::StrongUint64< detail::SchemaVersionTag > SchemaVersion
Persistent data-format version; not a runtime replacement generation.
std::function< void(ssq::Table &table)> PostEcsHook
在脚本 ECS 基类(eve.Component / eve.Entity / eve.System)注入之后执行的回调。 模块用它注入"extends eve.Entity"的脚本基类(例如 eve....
Definition ECS.h:176
void flushPostEcsHooks(ssq::Table &table)
Run post-ECS hooks that were registered after exposeECS already ran.
Definition ECS.cpp:1650
std::function< void(ssq::Array &out)> CppEntityViewFn
C++ 实体 → 脚本 eve.view() 桥接。 用 registerCppEntityView(cls, fn) 登记脚本类的收集函数; 脚本 eve.view(cls) 沿类链找到登记的 C++...
Definition ECS.h:167
Result< void > setScriptComponentField(const ScriptComponentStoreKey &key, const std::string &field, Value value)
写一个字段(脚本侧的写入与原生侧的写入都走这里)。
void clearScriptComponentStore()
换 VM 时清空:脚本世界连同它的组件数据一起消失。
void registerCppEntityView(const ssq::Class &cls, CppEntityViewFn fn)
Registers cpp entity view.
Definition ECS.cpp:1642
std::vector< ScriptComponentRecord > scriptComponentRecords()
当前 VM 的全部登记(含 retired 历史),按名字、版本、代际排序。 @cost 一次拷贝;仅供编辑器/诊断/测试等非热路径使用。
Definition ECS.cpp:1558
EVENGINE_API_FOUNDATION Result< void > writeScriptComponentField(const ssq::Object &instance, const std::string &field, const Value &value)
写一个脚本组件实例的字段,归属规则见 readScriptComponentField。
void reconcileScriptComponentValues(const std::string &name, SchemaVersion version, const std::vector< std::string > &fields, const std::vector< Value > &defaults)
把某个组件(名字 + 版本)在**所有实体**上的数据重建到新 schema 上(热重载换代)。
Result< Value > scriptComponentField(const ScriptComponentStoreKey &key, const std::string &field)
读一个字段。
Result< void > registerScriptComponent(const std::string &name, SchemaVersion version, const ssq::Object &cls)
登记一个脚本组件:eve.component(name, version, cls) 的 C++ 侧。
const ScriptComponentRecord * findScriptComponent(const std::string &name, SchemaVersion version)
当前未退役的那条登记。
Definition ECS.cpp:1549
SettlementPipeline::Stage fn
一条已登记组件的**声明 schema**:字段名与它们的声明默认值。
Definition ECS.h:101
std::string name
组件名。
Definition ECS.h:103
脚本组件注册表的一条记录。
Definition ECS.h:43
Generation generation
代际:同名同版本每次重新登记 +1。
Definition ECS.h:49