载入中...
搜索中...
未找到
Run.cpp
浏览该文件的文档.
1#include "cmdline.h"
2#include "common/BootWarmup.h"
3#include "common/Capability.h"
4#include "common/CrashLog.h"
5#include "common/ECS.h"
6#include "common/EditorHost.h"
7#include "common/Module.h"
8#include "common/Runtime.h"
10#include "common/ScriptModule.h"
13#include "common/config.h"
16#include "graphics/Light.h"
18#include "scripts.h"
19#if EVENGINE_CMDLINE_DEVTOOLS && !defined(EVENGINE_ANDROID) && !defined(EVENGINE_IOS) && !defined(__EMSCRIPTEN__)
20#include "devtools/DevTool.hpp"
22#endif
23
24#include <simplesquirrel/simplesquirrel.hpp>
25#include <CLI11.hpp>
26#include <cstdint>
27#include <cstdlib>
28#include <cstdio>
29#include <ctime>
30#include <string>
31#include <vector>
32#include <filesystem>
33
34#if defined(__EMSCRIPTEN__)
35#include <emscripten.h>
36#include <squirrel.h>
37
38#include <algorithm>
39#include <cstring>
40#include <fstream>
41#include <sstream>
42
43#include "graphics/Graphics.h"
44
45namespace {
46// Global frame-loop state: the root script (load.nut) defines a global
47// eve_frame() function; emscripten_set_main_loop drives it per animation frame.
48ssq::VM* gFrameVm = nullptr;
49ssq::Function* gFrameFunc = nullptr;
50// Raw Squirrel handle for the browser playground bridges below. Set right
51// after load.nut finishes; Run() never returns (emscripten_set_main_loop with
52// simulateInfiniteLoop=1), so it stays valid for the page lifetime.
53HSQUIRRELVM gPlaygroundVm = nullptr;
54
55void webgpuFrameTick() {
56 if (!gFrameVm || !gFrameFunc || gFrameFunc->isEmpty()) return;
57 // First frame is presented by the browser, so the shell's loading overlay
58 // can be dismissed now (it covered the canvas until this point).
59 EM_ASM({ if (window.hideEVELoading) window.hideEVELoading(); });
60 bool keep = true;
61 try {
62 ssq::Object r = gFrameVm->callFunc(*gFrameFunc, *gFrameVm);
63 if (r.getType() == ssq::Type::BOOL) keep = r.toBool();
64 } catch (const std::exception& e) {
65 fprintf(stderr, "EVEngine: eve_frame error: %s\n", e.what());
66 keep = false;
67 }
68 if (!keep) emscripten_cancel_main_loop();
69}
70
71// ---------------------------------------------------------------------------
72// Playground bridge (browser only).
73//
74// The shell page (platform/webgpu/shell.html) calls these exported functions
75// to push a new main.nut into the running engine and trigger the same soft
76// hot-reload path used by the desktop file watcher (load.nut handle_change).
77// They run on the browser main thread only, so a single shared result buffer
78// is safe.
79// ---------------------------------------------------------------------------
80
81constexpr SQInteger kPlaygroundResultCap = 8192;
82char gPlaygroundResult[kPlaygroundResultCap];
83
84const char* setPlaygroundResult(const char* text) {
85 if (!text) text = "";
86 std::snprintf(gPlaygroundResult, kPlaygroundResultCap, "%s", text);
87 return gPlaygroundResult;
88}
89
90// Write /game/main.nut and soft-reload it (dofile + optional eve_reload hook).
91// The reload error path prints through the same channels as the desktop
92// watcher, so the page console shows compile/runtime errors.
93void playgroundApply(const char* source) {
94 if (!gPlaygroundVm || !source) return;
95 HSQUIRRELVM vm = gPlaygroundVm;
96 const SQInteger top = sq_gettop(vm);
97 try {
98 std::ofstream out("/game/main.nut", std::ios::binary | std::ios::trunc);
99 if (!out) {
100 std::fprintf(stderr, "playground: cannot open /game/main.nut for writing\n");
101 return;
102 }
103 out.write(source, static_cast<std::streamsize>(std::strlen(source)));
104 out.close();
105 } catch (const std::exception& e) {
106 std::fprintf(stderr, "playground: write /game/main.nut failed: %s\n", e.what());
107 return;
108 }
109 // Route through load.nut's handle_change("main.nut") so scripts are
110 // tracked and re-dofiled exactly like an on-disk change.
111 sq_pushroottable(vm);
112 sq_pushstring(vm, _SC("handle_change"), -1);
113 if (SQ_SUCCEEDED(sq_get(vm, -2))) { // [root, fn]
114 sq_remove(vm, -2); // [fn]
115 HSQOBJECT handleChange;
116 sq_getstackobj(vm, -1, &handleChange); // borrowed: still rooted by `top`
117 // The roottable is the receiver ("this"), "main.nut" the single argument. The
118 // result used to be dropped, so a failing reload left the page with no trace.
119 eve::script::callFunction(vm, handleChange, eve::script::rootTable, "main.nut");
120 }
121 sq_settop(vm, top);
122}
123
124// Evaluate one Squirrel snippet in the running VM (REPL). Returns the
125// stringified result, or a "compile error:" / "eval error:" message.
126const char* playgroundEval(const char* source) {
127 if (!gPlaygroundVm) return "engine not ready";
128 if (!source) return "";
129 HSQUIRRELVM vm = gPlaygroundVm;
130 const SQInteger top = sq_gettop(vm);
131 char errbuf[640];
132 // REPL semantics: expressions like `__pg.frames` should return their value.
133 // A bare expression statement yields null in Squirrel, so first try
134 // `return (...)`; if that does not compile (e.g. an assignment or a
135 // multi-statement block), fall back to executing the raw source.
136 const std::string wrapped = std::string("return (") + source + ");";
137 const char* evalSource = wrapped.c_str();
138 SQInteger evalLen = static_cast<SQInteger>(wrapped.size());
139 bool compileOk = SQ_SUCCEEDED(eve::script::ScriptCompiler::compileBuffer(
140 vm, evalSource, evalLen, _SC("playground_eval"), SQTrue));
141 if (!compileOk) {
142 sq_settop(vm, top);
143 compileOk = SQ_SUCCEEDED(eve::script::ScriptCompiler::compileBuffer(
144 vm, source, static_cast<SQInteger>(std::strlen(source)), _SC("playground_eval"), SQTrue));
145 }
146 if (!compileOk) {
147 const SQChar* msg = nullptr;
148 if (sq_gettype(vm, -1) == OT_STRING) sq_getstring(vm, -1, &msg);
149 std::snprintf(errbuf, sizeof(errbuf), "compile error: %s", msg ? msg : "unknown");
150 sq_settop(vm, top);
151 return setPlaygroundResult(errbuf);
152 }
153 sq_pushroottable(vm);
154 if (SQ_FAILED(sq_call(vm, 1, SQTrue, SQTrue))) {
155 const SQChar* msg = nullptr;
156 if (sq_gettype(vm, -1) == OT_STRING) sq_getstring(vm, -1, &msg);
157 std::snprintf(errbuf, sizeof(errbuf), "eval error: %s", msg ? msg : "unknown");
158 sq_settop(vm, top);
159 return setPlaygroundResult(errbuf);
160 }
161 if (sq_gettype(vm, -1) == OT_NULL) {
162 sq_settop(vm, top);
163 return setPlaygroundResult("null");
164 }
165 if (SQ_FAILED(sq_tostring(vm, -1))) {
166 sq_settop(vm, top);
167 return setPlaygroundResult("(unprintable result)");
168 }
169 const SQChar* result = nullptr;
170 if (SQ_FAILED(sq_getstring(vm, -1, &result)) || !result) {
171 sq_settop(vm, top);
172 return setPlaygroundResult("(unprintable result)");
173 }
174 const char* out = setPlaygroundResult(result);
175 sq_settop(vm, top);
176 return out;
177}
178
179// Read a file from the browser VFS (relative to /game, which is the CWD).
180const char* playgroundRead(const char* path) {
181 if (!gPlaygroundVm || !path) return "";
182 try {
183 std::ifstream in(path, std::ios::binary);
184 if (!in) return setPlaygroundResult("");
185 std::ostringstream ss;
186 ss << in.rdbuf();
187 const std::string text = ss.str();
188 const size_t n = std::min(text.size(), static_cast<size_t>(kPlaygroundResultCap - 1));
189 std::memcpy(gPlaygroundResult, text.data(), n);
190 gPlaygroundResult[n] = '\0';
191 return gPlaygroundResult;
192 } catch (...) {
193 return setPlaygroundResult("");
194 }
195}
196
197// Binary-safe VFS read (e.g. PNG screenshots): copies up to dstCap bytes into
198// the JS-provided buffer and returns the byte count written.
199int playgroundReadBytes(const char* path, void* dst, int dstCap) {
200 if (!gPlaygroundVm || !path || !dst || dstCap <= 0) return 0;
201 try {
202 std::ifstream in(path, std::ios::binary);
203 if (!in) return 0;
204 std::ostringstream ss;
205 ss << in.rdbuf();
206 const std::string text = ss.str();
207 const int n = std::min<int>(static_cast<int>(text.size()), dstCap);
208 std::memcpy(dst, text.data(), n);
209 return n;
210 } catch (...) {
211 return 0;
212 }
213}
214
215// Queue an async frame readback (PNG). The webgpu backend pumps it from
216// present() so we never sleep inside this JS-initiated call (ASYNCIFY).
217void playgroundCapture(const char* path) {
218 if (!gPlaygroundVm || !path) return;
219 auto* gfx = eve::ModuleManager::getInstance<eve::graphics::Graphics>("Graphics");
220 if (gfx) gfx->beginFrameReadback(path);
221}
222
223int playgroundReadbackStatus() {
224 if (!gPlaygroundVm) return 0;
225 auto* gfx = eve::ModuleManager::getInstance<eve::graphics::Graphics>("Graphics");
226 return gfx ? gfx->frameReadbackStatus() : 0;
227}
228
229// Pause/freeze game updates (eve_update) while the render keeps presenting.
230// load.nut's eve_frame checks the eve_playground_paused root flag.
231void playgroundSetPaused(int paused) {
232 if (!gPlaygroundVm) return;
233 HSQUIRRELVM vm = gPlaygroundVm;
234 const SQInteger top = sq_gettop(vm);
235 sq_pushroottable(vm);
236 sq_pushstring(vm, _SC("eve_playground_paused"), -1);
237 sq_pushbool(vm, paused != 0);
238 sq_newslot(vm, -3, SQFalse);
239 sq_settop(vm, top);
240}
241
242// Destroy the ECS entities demos create (renderables, lights, cameras) and
243// drop the playground state table, so applying a *different* demo (or pressing
244// "重置状态") starts from a clean scene instead of stacking entities.
245void playgroundResetScene() {
246 if (!gPlaygroundVm) return;
247 HSQUIRRELVM vm = gPlaygroundVm;
248 const SQInteger top = sq_gettop(vm);
249 try {
250 auto *table = ecs::current();
251 auto destroyAll = [&](auto *mgr) {
252 if (!mgr || !mgr->registy) return;
253 auto *reg = dynamic_cast<ecs::IRegistryComponentBuffer *>(mgr->registy);
254 if (!reg) return;
255 std::vector<ecs::Entity *> entities;
256 const uint32_t n = reg->entity_count();
257 entities.reserve(n);
258 for (uint32_t i = 0; i < n; ++i) {
259 if (ecs::Entity *e = reg->entity_at(i)) entities.push_back(e);
260 }
261 for (ecs::Entity *e : entities) ecs::DestroyEntity(e);
262 };
263 destroyAll(table->getManager<eve::graphics::Renderable3D>());
264 destroyAll(table->getManager<eve::graphics::Light3D>());
265 destroyAll(table->getManager<eve::graphics::Camera3D>());
266
267 sq_pushroottable(vm);
268 sq_pushstring(vm, _SC("__pg"), -1);
269 sq_deleteslot(vm, -2, SQFalse);
270 sq_settop(vm, top);
271 } catch (...) {
272 sq_settop(vm, top);
273 }
274}
275} // namespace
276
277extern "C" {
278
279EMSCRIPTEN_KEEPALIVE void eve_playground_apply(const char* source) { playgroundApply(source); }
280EMSCRIPTEN_KEEPALIVE const char* eve_playground_eval(const char* source) {
281 return playgroundEval(source);
282}
283EMSCRIPTEN_KEEPALIVE const char* eve_playground_read(const char* path) {
284 return playgroundRead(path);
285}
286EMSCRIPTEN_KEEPALIVE int eve_playground_read_bytes(const char* path, void* dst, int dstCap) {
287 return playgroundReadBytes(path, dst, dstCap);
288}
289EMSCRIPTEN_KEEPALIVE void eve_playground_capture(const char* path) { playgroundCapture(path); }
290EMSCRIPTEN_KEEPALIVE int eve_playground_readback_status() { return playgroundReadbackStatus(); }
291EMSCRIPTEN_KEEPALIVE void eve_playground_set_paused(int paused) { playgroundSetPaused(paused); }
292EMSCRIPTEN_KEEPALIVE void eve_playground_reset() { playgroundResetScene(); }
293
294} // extern "C"
295#endif
296
297#if defined(EVENGINE_ANDROID)
298#include <android/log.h>
299#define EVE_ANDROID_LOGE(...) __android_log_print(ANDROID_LOG_ERROR, "EVEngine", __VA_ARGS__)
300#elif defined(EVENGINE_IOS) || defined(__EMSCRIPTEN__)
301#include <cstdio>
302#define EVE_ANDROID_LOGE(...) do { fprintf(stderr, "EVEngine: "); fprintf(stderr, __VA_ARGS__); fprintf(stderr, "\n"); } while (0)
303#else
304#define EVE_ANDROID_LOGE(...) ((void)0)
305#endif
306
307using namespace std;
308
309namespace eve::cmd
310{
311
312struct RunArgs : Handler {
314 bool no_window = false, debug = false;
315 int dap_port = 0;
316 int mcp_port = 0;
317
318 void setup(CLI::App& app, std::shared_ptr<CLI::Formatter> formatter) override {
319 auto run = app.add_subcommand("run", "Run game under current path");
320 run->allow_extras()->formatter(formatter);
321 run->add_flag("--no-window", no_window, "Run script only, no window mode");
322 run->add_flag("--debug", debug, "debug mode (slicer + pause/breakpoints/snapshot/MCP)");
323 run->add_option("--dap-port", dap_port,
324 "Start Debug Adapter Protocol server on port (implies --debug)");
325 run->add_option("--mcp-port", mcp_port,
326 "Start Model Context Protocol server on port for AI agents (implies --debug)");
327 run->add_option("--dev-server", dev_server,
328 "Remote hot-reload dev server URL (eve dev), e.g. http://192.168.1.5:8765");
329 run->add_option("-l,--log", log_path, "log messages into a file");
330 run->add_option("-r,--root", root_path, "give a entry script instead of using the system default one");
331 }
332
333 int parse(CLI::App& app, Cmdline& cmd) override {
334 auto run = app.get_subcommand("run");
335 if (run->parsed() || cmd.getArgc() == 1) {
336 if (dap_port > 0 || mcp_port > 0) debug = true;
337 std::string current_path = cmd.get_remaining(run);
338 if (root_path != "") {
339 ifstream ifs(root_path);
340 if (!ifs) {
341 cerr << "Cannot open root script: " << root_path << endl;
342 return -1;
343 }
344 std::string load_root((istreambuf_iterator<char>(ifs)), (istreambuf_iterator<char>()));
345 return cmd.Run(current_path, load_root, debug, dap_port, mcp_port, dev_server);
346 } else {
347 // One root script for every platform: it binds whatever modules
348 // the build contains from eve.moduleList, and leaves the frame
349 // driver to eve.hostDrivesFrames.
350 return cmd.Run(current_path, load_content, debug, dap_port, mcp_port, dev_server);
351 }
352 }
353 return -1; // not handle
354 }
355};
356
358
359
360// create a new project
361int Cmdline::Run(std::string path, std::string root, bool debug, int dapPort, int mcpPort,
362 std::string devServer) {
363 std::fprintf(stderr, "[startup] Run() begins at process clock %.1f ms\n",
364 (double) std::clock() * 1000.0 / (double) CLOCKS_PER_SEC);
365#if !EVENGINE_CMDLINE_DEVTOOLS
366 if (debug || dapPort > 0 || mcpPort > 0) {
367 std::cerr << "eve run: debugging requires the devtools module" << std::endl;
368 return 4;
369 }
370#endif
371 // Overlap VkInstance creation with VM/script boot: the loader+ICD init is
372 // typically 100ms+ and does not need a window.
374 try {
375 // Resolve the game directory. A packaged game ships a game.eve archive next to
376 // the executable; we mount it into memory and run without extracting to disk.
377 std::string gameDir = path;
378 std::string archivePath;
379 eve::recordLogEvent("info", "eve run starting: " + (gameDir.empty() ? std::string(".") : gameDir));
380
381 {
382 std::error_code ec;
383 if (path.empty() || path == ".")
384 gameDir = std::filesystem::current_path(ec).string();
385 else
386 gameDir = std::filesystem::absolute(path, ec).string();
387 if (ec) gameDir = path;
388
389 std::filesystem::path gp(gameDir);
390 if (std::filesystem::is_regular_file(gp, ec) && gp.extension() == ".eve") {
391 // `eve run <path>.eve` — the archive itself is the game.
392 archivePath = gp.string();
393 gameDir = gp.parent_path().string();
394 } else {
395 std::filesystem::path bundled = gp / "game.eve";
396 if (std::filesystem::is_regular_file(bundled, ec))
397 archivePath = bundled.string();
398 }
399 }
400
401 // Switch to the game directory so relative plugin/asset paths resolve next to
402 // the executable (the packaged game's scripts live in the memory-mounted archive).
403 if (!gameDir.empty() && gameDir != ".") {
404 std::error_code ec;
405 std::filesystem::current_path(gameDir, ec);
406 if (ec) {
407 cerr << "Cannot chdir to game path '" << gameDir << "': " << ec.message() << endl;
408 EVE_ANDROID_LOGE("Cannot chdir to game path '%s': %s", gameDir.c_str(), ec.message().c_str());
409 return 2;
410 }
411 }
412
413 // Mount game source for PhysFS so relative watch/read resolve (hot reload).
414 {
415 auto *fs = eve::filesystem::Filesystem::create();
416 if (fs) {
417 if (!archivePath.empty()) {
418 // Read the packaged archive into memory and mount it there.
419 std::ifstream ifs(archivePath, std::ios::binary);
420 if (!ifs) {
421 cerr << "Cannot open game archive: " << archivePath << endl;
422 return 2;
423 }
424 std::vector<char> bytes((std::istreambuf_iterator<char>(ifs)),
425 std::istreambuf_iterator<char>());
426 if (bytes.empty() || !fs->setSourceFromMemory(bytes.data(), bytes.size())) {
427 cerr << "Failed to mount game archive from memory: " << archivePath << endl;
428 return 2;
429 }
430 } else {
431 std::error_code ec;
432 auto cwd = std::filesystem::current_path(ec);
433 if (!ec) {
434 // setSource only succeeds once; ignore failure if already mounted.
435 fs->setSource(cwd.string());
436 }
437 }
438 }
439 }
440
441 Runtime runtime(8192, ssq::Libs::ALL);
442 {
443 StartupStage stage("runtime: ModuleManager::expose");
444 runtime.initialize();
445 }
446#if EVENGINE_CMDLINE_DEVTOOLS && !defined(EVENGINE_ANDROID) && !defined(EVENGINE_IOS) && !defined(__EMSCRIPTEN__)
447 if (debug) {
449 dt.attach(runtime, /*sampleLocals=*/true);
450 dt.exposeScriptApi(runtime.vm());
451 if (dapPort > 0) {
452 const int bound = dt.startDap(static_cast<uint16_t>(dapPort));
453 if (bound > 0) {
454 cerr << "DAP listening on 127.0.0.1:" << bound << endl;
455 // Wait for the IDE to finish setBreakpoints / configurationDone
456 // before loading scripts, otherwise early breakpoints are missed
457 // and stack paths are not registered yet.
458 if (!dt.dap().waitUntilConfigured(15000))
459 cerr << "DAP: timed out waiting for client; starting anyway" << endl;
460 } else {
461 cerr << "Failed to start DAP server on port " << dapPort << endl;
462 }
463 }
464 if (mcpPort > 0) {
465 try {
466 dt.mcp().setGameRoot(std::filesystem::current_path().string());
467 } catch (...) {
468 }
469 const int bound = dt.startMcp(static_cast<uint16_t>(mcpPort));
470 if (bound > 0) {
471 cerr << "MCP listening on 127.0.0.1:" << bound
472 << " (newline JSON-RPC; use tools/eve-mcp for Cursor stdio)" << endl;
473 } else {
474 cerr << "Failed to start MCP server on port " << mcpPort << endl;
475 }
476 }
477 }
478#else
479 (void)debug;
480 (void)dapPort;
481 (void)mcpPort;
482#endif
483 // Embedded default demo (src/scripts/demo.nut); load.nut runs it when no main.nut.
484 {
485 ssq::Table eve = runtime.table("eve");
486 eve.set("demoScript", std::string(demo_content ? demo_content : ""));
487 eve.set("asyncScript", std::string(async_content ? async_content : ""));
488 // Route script-side milestones into the same crash/error log
489 // (eve.log) so a crash shows how far the boot sequence got.
490 eve.addFunc("log", [](const std::string& level, const std::string& msg) {
492 });
493 eve.addFunc("reloadScriptModule", [&runtime](const std::string& path) {
494 std::string canonical;
495 std::string error;
496 if (!eve::script::ScriptModuleResolver::canonicalize({"game:/main.nut", path}, canonical, error))
497 throw std::runtime_error(error);
498 return !runtime.scriptModules().reloadAffected(canonical).empty();
499 });
500 // Editor apps (`config.editorHost=true`) start the same MVVM host
501 // `eve mcp` uses, then C++ pumps EditorHost::frame after load.nut.
502 eve.addFunc("startEditorHost", [&runtime, gameDir]() {
503 auto* host = eve::cap::query<eve::IEditorHost>();
504 if (!host) return std::string("error: editor host unavailable");
505 host->start(runtime.vm(), gameDir, /*allowWindow=*/true);
506 host->exposeScriptApi(runtime.vm());
507 return std::string("ok");
508 });
509 // Scene-director authoring kit (src/scripts/scene_director.nut). Host
510 // games load it via `compilestring(eve.sceneDirectorScript)()`; the
511 // MCP tools auto-install it on demand.
512 eve.set("sceneDirectorScript", std::string(scene_director_content ? scene_director_content : ""));
513 eve.set("devServerArg", devServer);
514 const char* bench = std::getenv("EVE_BOOT_BENCH");
515 eve.set("packageCheck", std::getenv("EVE_PACKAGE_CHECK") != nullptr);
516 eve.set("bootBench", bench && bench[0] != '\0' && bench[0] != '0');
517#if defined(__EMSCRIPTEN__)
518 // The browser has no blocking loop; load.nut defines eve_frame and
519 // returns, and emscripten_set_main_loop drives it below.
520 eve.set("hostDrivesFrames", true);
521#else
522 eve.set("hostDrivesFrames", false);
523#endif
524 }
525 // The generated slot -> class table load.nut iterates over.
527 runtime.runSource(module_list_content, "module_list.nut");
528 {
529 ssq::Table eve = runtime.table("eve");
530 eve.set("moduleList", runtime.root().find("eve_modules"));
531 eve.set("moduleContract", runtime.root().find("eve_module_contract"));
532 }
533 // Name the embedded root so DAP stack frames map to load.nut (not "buffer").
534 // Route file/dofile/loadfile through PhysFS so a packaged game (mounted in
535 // memory) can load its scripts without extracting to disk.
537 std::fprintf(stderr, "[startup] load.nut begins at process clock %.1f ms\n",
538 (double) std::clock() * 1000.0 / (double) CLOCKS_PER_SEC);
539 runtime.runSource(std::move(root), "load.nut");
540 if (std::getenv("EVE_PACKAGE_CHECK")) {
541 if (runtime.root().find("_frame_count").toInt() < 30)
542 throw std::runtime_error("Package acceptance did not complete 30 frames");
543 std::cout << "[package-check] passed: 30 frames\n";
544 }
545#if !defined(EVENGINE_ANDROID) && !defined(EVENGINE_IOS) && !defined(__EMSCRIPTEN__)
546 bool editorHostDrive = false;
547 try {
548 editorHostDrive = runtime.root().find("config").toTable().find("editorHost").toBool();
549 } catch (...) {
550 }
551 if (editorHostDrive) {
552 auto* host = eve::cap::query<eve::IEditorHost>();
553 if (!host) {
554 std::cerr << "config.editorHost=true but the editor host is unavailable\n";
555 return 3;
556 }
557 if (!host->isWindowOpen()) {
558 std::cerr << "editor host did not open a window "
559 "(eve_init should call eve.host.applyEditor)\n";
560 return 3;
561 }
562 while (!host->exitRequested() && host->isWindowOpen()) host->frame();
563 host->stop();
564 }
565#endif
566#if defined(__EMSCRIPTEN__)
567 // Instead of a blocking while(running) Squirrel loop (which the browser
568 // never composites), drive the global eve_frame() function from an
569 // Emscripten requestAnimationFrame main loop. simulateInfiniteLoop=1
570 // keeps main() alive; `runtime` stays in scope because Run() never returns.
571 gFrameVm = &runtime.vm();
572 gFrameFunc = new ssq::Function(runtime.vm().find("eve_frame").toFunction());
573 gPlaygroundVm = runtime.handle();
574 // Let the shell page enable the editor once the engine VM is live
575 // (onRuntimeInitialized fires before main(), so it is not enough).
576 EM_ASM({ if (window.eveEngineReady) window.eveEngineReady(); });
577 emscripten_set_main_loop(&webgpuFrameTick, 0, /*simulateInfiniteLoop=*/1);
578#endif
579#if EVENGINE_CMDLINE_DEVTOOLS && !defined(EVENGINE_ANDROID) && !defined(EVENGINE_IOS) && !defined(__EMSCRIPTEN__)
580 if (debug) eve::dev::DevTool::instance().detach();
581#endif
582 return 0;
583 } catch (const std::exception& e) {
584 std::string what = e.what() ? e.what() : "unknown exception";
585 eve::recordLogEvent("error", "Run failed: " + what);
586#if EVENGINE_CMDLINE_DEVTOOLS && !defined(EVENGINE_ANDROID) && !defined(EVENGINE_IOS) && !defined(EVENGINE_WEBGPU)
587 if (debug) {
589 // The VM error hook and the Runtime error-handler sink (wired in
590 // DevTool::attach(Runtime&)) already slice script errors; only
591 // synthesize a report when none was produced (e.g. a native
592 // std::exception with no script involvement).
593 std::string report = dt.lastReport();
594 if (report.empty()) report = dt.notifyError(what);
595 cerr << report << endl;
596 dt.detach();
597 } else {
598 cerr << "Run failed: " << what << endl;
599 }
600#else
601 cerr << "Run failed: " << what << endl;
602#endif
603 EVE_ANDROID_LOGE("Run failed: %s", what.c_str());
604 return 3;
605 } catch (...) {
606 eve::recordLogEvent("error", "Run failed: unknown exception");
607#if EVENGINE_CMDLINE_DEVTOOLS && !defined(EVENGINE_ANDROID) && !defined(EVENGINE_IOS) && !defined(EVENGINE_WEBGPU)
608 if (debug) {
609 const std::string report =
610 eve::dev::DevTool::instance().notifyError("unknown exception");
611 cerr << report << endl;
613 } else {
614 cerr << "Run failed: unknown exception" << endl;
615 }
616#else
617 cerr << "Run failed: unknown exception" << endl;
618#endif
619 EVE_ANDROID_LOGE("Run failed: unknown exception");
620 return 3;
621 }
622}
623
624
625
626} // namespace eve
int root
Definition AnimSmr.cpp:119
struct SQVM * HSQUIRRELVM
Persistent, thread-safe record of engine crash and problem events.
HSQUIRRELVM vm
Definition ECS.cpp:38
glm::vec3 n
Definition Grass.cpp:63
double r
Poco::JSON::Object::Ptr result
std::uint64_t bytes
int level
double dt
gpgpu::Gpgpu & gp
Definition OnnxGpgpu.cpp:42
std::weak_ptr< Run > run
Definition OnnxGpgpu.cpp:25
std::string error
Definition Package.cpp:174
std::string path
Definition PlayHost.cpp:111
std::vector< ecs::EntityHandle > entities
#define EVE_ANDROID_LOGE(...)
Definition Run.cpp:304
std::string text
ScriptStructure out
std::string_view source
The single Squirrel projection for common Result, Status and Value.
UIHostHandle host
EVENGINE_API_FOUNDATION public API.
Definition Runtime.h:189
StartupStage public API.
命令行模块(eve.cmd):run / build / package / test / zip / dev-server 等子命令入口。
Definition cmdline.h:34
static std::string get_remaining(CLI::App *sub, std::string default_path=".")
子命令剩余位置参数。
Definition cmdline.cpp:80
unsigned getArgc()
Returns the argc.
Definition cmdline.h:84
int Run(std::string path, std::string root, bool debug=false, int dapPort=0, int mcpPort=0, std::string devServer="")
运行游戏(debug 时附加 DAP/MCP 端口)。
Definition Run.cpp:361
std::string notifyError(const std::string &errorMessage, const std::vector< std::string > &hintVars={})
Record an error; includes script slice and render-pipeline slice when enabled.
Definition DevTool.cpp:834
static DevTool & instance()
Definition DevTool.cpp:138
EVENGINE_API_BACKENDS public API.
Declarative 3D light. Collected by RenderSystem3D (max 8 per frame). type: "point" | "dir" | "spot" (...
Definition Light.h:190
EVENGINE_API_BACKENDS public API.
static SQRESULT compileBuffer(HSQUIRRELVM vm, const SQChar *source, SQInteger size, const SQChar *sourceName, SQBool raiseError)
Unified raw-VM entry used by REPL, debugger, MCP, and editor adapters.
static bool canonicalize(const ScriptModuleRequest &request, std::string &output, std::string &error)
Normalizes a logical module URI and rejects root traversal.
#define CMD_REG(name)
Definition cmdline.h:102
SQInteger top
Definition Snapshot.cpp:115
EVENGINE_API_FOUNDATION void startVulkanInstanceWarmup()
Kick off asynchronous VkInstance creation if a backend registered.
void installScriptFileApi(ssq::VM &vm)
用 PhysFS 版本覆盖 Squirrel 的 file / dofile / loadfile 全局, 使脚本与资源从已挂载的游戏源(真实目录或内存挂载的 .eve 归档)解析; PhysFS 中不...
Definition FileApi.cpp:219
std::unordered_map< std::string, SkillDefinition > & table()
Definition Skill.cpp:73
SQRESULT callFunction(HSQUIRRELVM vm, const HSQOBJECT &fn, const Receiver &receiver, Args &&... args)
Call a script function, deriving sq_call's parameter count from the pushes.
constexpr RootTable rootTable
WidgetDesc window(std::string title, std::vector< WidgetDesc > children, std::string id)
Top-level window widget with a title bar.
Definition Widget.cpp:326
Build metadata (engine git commit, build time, third-party version).
Definition Build.cpp:16
const char * async_content
const char * load_content
const char * module_list_content
const char * scene_director_content
void recordLogEvent(const std::string &level, const std::string &message)
Appends a timestamped event line to the crash/error log.
Definition CrashLog.cpp:70
const char * demo_content
One eve <subcommand> handler: CLI setup + argument parsing.
Definition cmdline.h:24
std::string dev_server
Definition Run.cpp:313
void setup(CLI::App &app, std::shared_ptr< CLI::Formatter > formatter) override
Registers options on the CLI11 sub-app.
Definition Run.cpp:318
std::string root_path
Definition Run.cpp:313
std::string log_path
Definition Run.cpp:313
int parse(CLI::App &app, Cmdline &cmd) override
Parses arguments and runs the command; returns the exit code.
Definition Run.cpp:333