载入中...
搜索中...
未找到
Module.cpp
浏览该文件的文档.
1#include "common/Module.h"
3#include "common/Assert.h"
4#include "common/ECS.h"
5#include "common/Runtime.h"
7
8#include <simplesquirrel/simplesquirrel.hpp>
9#include <squirrel.h>
10
11#include <algorithm>
12#include <chrono>
13#include <cstdio>
14#include <cstring>
15#include <exception>
16#include <string>
17#include <vector>
18
19namespace eve
20{
21
23 static auto& modules() { return ModuleManager::inst().state_->registered_modules; }
24};
25
26namespace {
27
28bool eveRawHas(HSQUIRRELVM vm, SQInteger tableIdx, const char* key) {
29 if (tableIdx < 0) tableIdx = sq_gettop(vm) + tableIdx + 1;
30 sq_pushstring(vm, key, -1);
31 if (SQ_SUCCEEDED(sq_rawget(vm, tableIdx))) {
32 sq_pop(vm, 1);
33 return true;
34 }
35 return false;
36}
37
38ssq::Table eveTableFromStack(HSQUIRRELVM vm, SQInteger tableIdx) {
39 ssq::Object wrapped(vm);
40 sq_getstackobj(vm, tableIdx, &wrapped.getRaw());
41 sq_addref(vm, &wrapped.getRaw());
42 return ssq::Table(wrapped);
43}
44
45bool isPascalCaseName(const char* key) {
46 return key && key[0] >= 'A' && key[0] <= 'Z';
47}
48
49bool isScriptEcsName(const char* key) {
50 if (!key) return false;
51 return std::strcmp(key, "Component") == 0 || std::strcmp(key, "Entity") == 0 ||
52 std::strcmp(key, "EntityContainer") == 0 || std::strcmp(key, "System") == 0 ||
53 std::strcmp(key, "ShaderSystem") == 0 || std::strcmp(key, "view") == 0 ||
54 std::strcmp(key, "ecsReady") == 0;
55}
56
57void ensureScriptEcsInTable(ssq::Table& table) {
58 HSQUIRRELVM vm = table.getHandle();
59 sq_pushobject(vm, table.getRaw());
60 const bool hasSystem = eveRawHas(vm, -1, "System");
61 const bool ready = eveRawHas(vm, -1, "Component") && eveRawHas(vm, -1, "Entity") && hasSystem;
62 if (!ready && hasSystem) {
63 // The host-information module historically owns eve.System until the
64 // script ECS is injected. Remove that one namespace collision so the
65 // canonical script System class can be created exactly once.
66 sq_pushstring(vm, "System", -1);
67 sq_deleteslot(vm, -2, SQFalse);
68 }
69 sq_pop(vm, 1);
70 if (!ready) exposeECS(table);
71}
72
73template <typename Info>
74void runExposer(Info& info, ssq::Table& table, const char* name) {
75 if (info.exposed || !info.exposer) {
76 info.exposed = true;
77 return;
78 }
79 info.exposed = true;
80 const auto t0 = std::chrono::steady_clock::now();
81 info.exposer(table);
82 const double ms =
83 std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
84 if (ms >= 20.0)
85 std::fprintf(stderr, "[startup] bind %s: %.1f ms\n", name ? name : "?", ms);
86 flushPostEcsHooks(table);
87}
88
89void bindNamedModule(const std::string& name, ssq::Table& table) {
90 auto& modules = ModuleBindAccess::modules();
91 auto it = modules.find(name);
92 if (it == modules.end()) return;
93 runExposer(it->second, table, name.c_str());
94}
95
96void bindUntilKeyExists(HSQUIRRELVM vm, SQInteger tableIdx, const char* key, ssq::Table& table) {
97 if (eveRawHas(vm, tableIdx, key)) return;
98 auto& modules = ModuleBindAccess::modules();
99 std::vector<std::string> pending;
100 pending.reserve(modules.size());
101 for (auto& entry : modules) {
102 if (!entry.second.exposed && entry.second.exposer) pending.push_back(entry.first);
103 }
104 std::sort(pending.begin(), pending.end());
105 for (const std::string& name : pending) {
106 auto it = modules.find(name);
107 if (it == modules.end() || it->second.exposed) continue;
108 runExposer(it->second, table, name.c_str());
109 if (eveRawHas(vm, tableIdx, key)) return;
110 }
111 // A name can be provided by a post-ECS hook rather than by any module exposer
112 // (eve.SceneEntity is: the Scene module registers a hook at static-init that
113 // creates it). Hooks only run once the script ECS base exists -- flushPostEcsHooks
114 // is gated on it -- so a first lazy access to such a name scanned every module
115 // without ever injecting that base and then failed with "the index
116 // 'SceneEntity' does not exist", which is exactly the natural opening line
117 // `class MyThing extends eve.SceneEntity`. Inject the base script as the last
118 // step: every module has had its chance by now, so ensureScriptEcsInTable()'s
119 // precedence rules (it replaces a module-provided eve.System with the canonical
120 // one) are applied in the right order.
121 if (!eveRawHas(vm, tableIdx, key)) ensureScriptEcsInTable(table);
122}
123
124void bindOnDemand(HSQUIRRELVM vm, SQInteger tableIdx, const char* key) {
125 if (!key || eveRawHas(vm, tableIdx, key)) return;
126 ssq::Table table = eveTableFromStack(vm, tableIdx);
127 if (isScriptEcsName(key)) {
128 ensureScriptEcsInTable(table);
129 return;
130 }
131 bindNamedModule(key, table);
132 if (eveRawHas(vm, tableIdx, key)) return;
133 // Nested types (WindowSettings, PlacementWorld, …) live on a parent
134 // module's exposer. Scan remaining PascalCase misses only — lowercase
135 // optional keys such as "dev" must not pull in every native class.
136 if (isPascalCaseName(key)) bindUntilKeyExists(vm, tableIdx, key, table);
137}
138
139SQInteger eveTableGet(HSQUIRRELVM vm) {
140 if (sq_gettop(vm) < 2 || sq_gettype(vm, 2) != OT_STRING)
141 return sq_throwerror(vm, _SC("the index doesn't exist"));
142 const SQChar* key = nullptr;
143 if (SQ_FAILED(sq_getstring(vm, 2, &key)) || !key)
144 return sq_throwerror(vm, _SC("the index doesn't exist"));
145 const std::string name(key);
146 // Functions declared as `function eve::name` execute with the eve table as
147 // their environment. Preserve the historical root lookup of `eve` itself
148 // instead of treating it as a native-class miss in the lazy delegate.
149 if (name == "eve") {
150 sq_push(vm, 1);
151 return 1;
152 }
153 try {
154 bindOnDemand(vm, 1, name.c_str());
155 } catch (const std::exception& error) {
156 return sq_throwerror(vm, error.what());
157 }
158 sq_push(vm, 1);
159 sq_pushstring(vm, name.c_str(), static_cast<SQInteger>(name.size()));
160 if (SQ_FAILED(sq_rawget(vm, -2))) {
161 const std::string message = "the index '" + name + "' does not exist";
162 return sq_throwerror(vm, message.c_str());
163 }
164 return 1;
165}
166
167void installLazyClassGet(ssq::Table& eveTable) {
168 HSQUIRRELVM vm = eveTable.getHandle();
169 sq_pushobject(vm, eveTable.getRaw());
170 sq_newtable(vm);
171 sq_pushstring(vm, _SC("_get"), -1);
172 sq_newclosure(vm, &eveTableGet, 0);
173 sq_newslot(vm, -3, SQFalse);
174 sq_setdelegate(vm, -2);
175 sq_pop(vm, 1);
176}
177
178} // namespace
179
180
182 inst().state_->active_vm_ = &vm;
183 for (auto& entry : inst().state_->registered_modules) entry.second.exposed = false;
185
186 ssq::Table table;
187 // Runtime::initialize() guarantees expose() runs once, so addTable never
188 // sees an existing "eve" slot. Avoid find()+catch here: ASYNCIFY-wrapped
189 // frames can drop the catch and leak NotFoundException to the JS boundary.
190 table = vm.addTable("eve");
191 // Result/Status/Diagnostic projection is a common script contract, not a
192 // domain-module convenience. Expose it before module constructors run so
193 // every checked binding observes the same `eve.result` helper.
195 // Script-side provider publication is the same kind of common contract: it is
196 // how user script answers a native extension point, and it must exist before
197 // any module constructor declares a capability seam.
199 installLazyClassGet(table);
200 table.addFunc("_bindAllNativeClasses", []() { return ModuleManager::exposeAllForCompatibility(); });
201 table.addFunc("_ensureScriptECS", []() { return ModuleManager::ensureScriptEcs(); });
202}
203
205 inst().state_->active_runtime_ = &runtime;
207}
208
209void ModuleManager::expose(ssq::VM& vm) {
210 inst().state_->active_runtime_ = nullptr;
211 exposeVM(vm);
212}
213
214ssq::VM* ModuleManager::vm() { return inst().state_->active_vm_; }
215
217 Runtime* active = inst().state_->active_runtime_;
218 if (!active)
219 return -1;
220 int count = 0;
221 try {
222 auto scope = active->enter();
223 auto stack = active->guard();
224 ssq::Table table = active->table("eve");
225 for (auto& D : inst().state_->registered_modules) {
226 if (D.second.exposed || !D.second.exposer)
227 continue;
228 D.second.exposer(table);
229 D.second.exposed = true;
230 flushPostEcsHooks(table);
231 ++count;
232 }
233 } catch (...) {
234 return -1;
235 }
236 return count;
237}
238
239int ModuleManager::ensureScriptEcs() {
240 Runtime* active = inst().state_->active_runtime_;
241 if (!active) return -1;
242 try {
243 auto scope = active->enter();
244 auto stack = active->guard();
245 ssq::Table table = active->table("eve");
246 ensureScriptEcsInTable(table);
247 } catch (...) {
248 return -1;
249 }
250 return 0;
251}
252
253int ModuleManager::exposeAllForCompatibility() {
254 const int count = expose_pending();
255 if (count < 0) return count;
256 if (ensureScriptEcs() < 0) return -1;
257 return count;
258}
259
260} // namespace eve
bool & active
EVEngine assertion entry point, backed by zeroerr.
std::vector< QuestEvent > pending
struct SQVM * HSQUIRRELVM
HSQUIRRELVM vm
Definition ECS.cpp:38
SQObjectPtr key
Definition ECS.cpp:155
std::string name
Definition ECS.cpp:154
std::string message
JobScope scope
std::string error
Definition Package.cpp:174
int count
The single Squirrel projection for common Result, Status and Value.
static void exposeVM(ssq::VM &vm)
Expose vm.
Definition Module.cpp:181
static Runtime * runtime()
Active runtime associated with the last expose() call, or nullptr. @ownership Borrowed; the embedding...
static void expose(Runtime &runtime)
Installs the eve table and defers native class method bindings.
Definition Module.cpp:204
static int expose_pending()
Expose pending.
Definition Module.cpp:216
static ModuleManager & inst()
Singleton registry holding every registered engine module.
static ssq::VM * vm()
Script VM of the last expose call, including raw-VM embedders, or nullptr. @ownership Borrowed; Runti...
Definition Module.cpp:214
EVENGINE_API_FOUNDATION public API.
Definition Runtime.h:189
ssq::VM & vm() noexcept
Underlying SimpleSquirrel VM (requires a live, initialized runtime).
Definition Runtime.cpp:520
std::unordered_map< std::string, SkillDefinition > & table()
Definition Skill.cpp:73
void exposeProviderBindings(ssq::Table &eveTable)
Expose eve.provider: script-published providers and capability seams.
void exposeResultBindings(ssq::Table &eveTable)
Expose the common script helpers under eve.result.
Build metadata (engine git commit, build time, third-party version).
Definition Build.cpp:16
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
void flushPostEcsHooks(ssq::Table &table)
Run post-ECS hooks that were registered after exposeECS already ran.
Definition ECS.cpp:1650
static auto & modules()
Definition Module.cpp:23
glm::uvec4 info