载入中...
搜索中...
未找到
FileApi.cpp
浏览该文件的文档.
2
3#include "common/Module.h"
4#include "common/Runtime.h"
7
8#include <simplesquirrel/simplesquirrel.hpp>
9#include <squirrel.h>
10
11#include <cstring>
12#include <fstream>
13#include <iterator>
14#include <string>
15
16#include "physfs/physfs.h"
17
18namespace eve {
19namespace filesystem {
20namespace physfs {
21namespace {
22
23bool readViaPhysFS(const char* path, std::string& out) {
24 if (!PHYSFS_isInit() || !PHYSFS_exists(path)) return false;
25 PHYSFS_file* f = PHYSFS_openRead(path);
26 if (!f) return false;
27 const PHYSFS_uint64 len = PHYSFS_fileLength(f);
28 out.resize(static_cast<size_t>(len));
29 if (len > 0 && PHYSFS_readBytes(f, out.data(), len) != static_cast<PHYSFS_sint64>(len)) {
30 PHYSFS_close(f);
31 out.clear();
32 return false;
33 }
34 PHYSFS_close(f);
35 return true;
36}
37
38bool readViaOS(const char* path, std::string& out) {
39 std::ifstream ifs(path, std::ios::binary);
40 if (!ifs) return false;
41 out.assign(std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>());
42 return true;
43}
44
45bool readFileContent(const char* path, std::string& out) {
46 if (readViaPhysFS(path, out) && !out.empty()) return true;
47 out.clear();
48 return readViaOS(path, out);
49}
50
51// `load.nut` loads the game with `dofile("main.nut")`. A raw `sq_compilebuffer`
52// compiles `import` edges but never instantiates them, so the import opcode
53// fails with "module was not instantiated". Give the chunk a `game:/` URI and
54// run the same ScriptCompiler + instantiate path EditorHost uses.
55std::string scriptUriFromPath(const char* path) {
56 std::string uri = path ? path : "";
57 for (char& ch : uri) {
58 if (ch == '\\') ch = '/';
59 }
60 const size_t scheme = uri.find(":/");
61 const bool drive = uri.size() >= 2 && uri[1] == ':';
62 if (scheme != std::string::npos && !drive) return uri;
63 while (uri.rfind("./", 0) == 0) uri.erase(0, 2);
64 while (!uri.empty() && uri.front() == '/') uri.erase(0, 1);
65 return "game:/" + uri;
66}
67
68// Shared implementation of dofile (execute) and loadfile (return closure).
69SQInteger compileAndMaybeRun(HSQUIRRELVM vm, bool run) {
70 const SQChar* path = nullptr;
71 if (SQ_FAILED(sq_getstring(vm, 2, &path)) || !path)
72 return sq_throwerror(vm, "expected a script filename");
73
74 std::string content;
75 if (!readFileContent(path, content))
76 return sq_throwerror(vm, "cannot open script");
77
78 // Squirrel's sq_readscripfile skips a UTF-8 BOM; sq_compilebuffer does not.
79 if (content.size() >= 3 && (unsigned char)content[0] == 0xEF &&
80 (unsigned char)content[1] == 0xBB && (unsigned char)content[2] == 0xBF)
81 content.erase(0, 3);
82
83 const std::string uri = scriptUriFromPath(path);
84 if (SQ_FAILED(eve::script::ScriptCompiler::compileBuffer(vm, content.c_str(),
85 static_cast<SQInteger>(content.size()),
86 uri.c_str(), SQTrue)))
87 return SQ_ERROR;
88
90 if (!rt) rt = ModuleManager::runtime();
91 if (rt) {
92 try {
93 rt->scriptModules().instantiateDependencies(uri);
94 } catch (const std::exception& error) {
95 sq_pop(vm, 1);
96 return sq_throwerror(vm, error.what());
97 }
98 }
99
100 if (!run) return 1; // leave the closure on the stack
101
102 sq_pushroottable(vm);
103 // `return SQ_ERROR` is the correct Squirrel native convention here, not a swallowed
104 // failure: the inner call already raised, so SQVM::CallNative re-raises `_lasterror`
105 // and the script's `catch` receives the original message. Reporting it through
106 // eve::script::reportScriptCallFailure() would print it twice and would consume the
107 // context before the VM re-raises. The plan doc listed this site as "reports too
108 // little"; reading the VM settled that it reports the whole error.
109 if (SQ_FAILED(sq_call(vm, 1, SQFalse, SQTrue))) return SQ_ERROR;
110 sq_pop(vm, 1);
111 return 0;
112}
113
114SQInteger sq_dofile(HSQUIRRELVM vm) { return compileAndMaybeRun(vm, true); }
115SQInteger sq_loadfile(HSQUIRRELVM vm) { return compileAndMaybeRun(vm, false); }
116
117// --- file() handle: a lightweight PhysFS-backed file table ---
118
119bool getThisStr(HSQUIRRELVM vm, const SQChar* field, std::string& out) {
120 sq_pushstring(vm, field, -1);
121 if (SQ_SUCCEEDED(sq_get(vm, 1))) {
122 const SQChar* s = nullptr;
123 if (SQ_SUCCEEDED(sq_getstring(vm, -1, &s)) && s) out = s;
124 sq_pop(vm, 1);
125 return !out.empty();
126 }
127 return false;
128}
129
130SQInteger sq_f_close(HSQUIRRELVM vm) {
131 sq_pushnull(vm);
132 return 1;
133}
134
135SQInteger sq_f_read(HSQUIRRELVM vm) {
136 std::string data;
137 if (!getThisStr(vm, _SC("_data"), data)) return sq_throwerror(vm, "file not readable");
138 sq_pushstring(vm, data.c_str(), static_cast<SQInteger>(data.size()));
139 return 1;
140}
141
142SQInteger sq_f_getSize(HSQUIRRELVM vm) {
143 std::string data;
144 if (!getThisStr(vm, _SC("_data"), data)) return sq_throwerror(vm, "file not readable");
145 sq_pushinteger(vm, static_cast<SQInteger>(data.size()));
146 return 1;
147}
148
149SQInteger sq_f_isEOF(HSQUIRRELVM vm) {
150 sq_pushbool(vm, SQTrue);
151 return 1;
152}
153
154SQInteger sq_f_tell(HSQUIRRELVM vm) {
155 sq_pushinteger(vm, 0);
156 return 1;
157}
158
159SQInteger sq_f_seek(HSQUIRRELVM vm) {
160 sq_pushbool(vm, SQTrue);
161 return 1;
162}
163
164SQInteger sq_f_getFilename(HSQUIRRELVM vm) {
165 std::string path;
166 getThisStr(vm, _SC("_path"), path);
167 sq_pushstring(vm, path.c_str(), static_cast<SQInteger>(path.size()));
168 return 1;
169}
170
171SQInteger sq_file(HSQUIRRELVM vm) {
172 const SQChar* path = nullptr;
173 const SQChar* mode = nullptr;
174 if (SQ_FAILED(sq_getstring(vm, 2, &path)) || SQ_FAILED(sq_getstring(vm, 3, &mode)))
175 return sq_throwerror(vm, "file: expected (path, mode)");
176
177 std::string m(mode ? mode : "");
178 const bool writing = m.find('w') != std::string::npos || m.find('a') != std::string::npos;
179
180 std::string content;
181 if (!writing) {
182 // A missing file must fail here, otherwise `file_exists()` (which tries
183 // file(path, "r")) returns an empty handle and reports true.
184 if (!readFileContent(path, content))
185 return sq_throwerror(vm, "cannot open file");
186 }
187
188 sq_newtable(vm); // the handle table (becomes 'this')
189 // Squirrel 的 sq_newslot(-3) 需要 [table, key, value] 三层栈;
190 // 只推一个值会把目标错指到调用帧的 mode 参数上(非表对象会被静默跳过),
191 // 导致句柄永远没有 _path/_data,read()/getSize() 报 "file not readable"。
192 sq_pushstring(vm, "_path", -1); // key
193 sq_pushstring(vm, path, -1); // value
194 sq_newslot(vm, -3, SQFalse);
195 sq_pushstring(vm, "_data", -1); // key
196 sq_pushstring(vm, content.c_str(), static_cast<SQInteger>(content.size())); // value
197 sq_newslot(vm, -3, SQFalse);
198
199 struct { const SQChar* name; SQFUNCTION fn; } methods[] = {
200 {_SC("close"), sq_f_close},
201 {_SC("read"), sq_f_read},
202 {_SC("readString"), sq_f_read},
203 {_SC("getSize"), sq_f_getSize},
204 {_SC("isEOF"), sq_f_isEOF},
205 {_SC("tell"), sq_f_tell},
206 {_SC("seek"), sq_f_seek},
207 {_SC("getFilename"), sq_f_getFilename},
208 };
209 for (const auto& mth : methods) {
210 sq_pushstring(vm, mth.name, -1);
211 sq_newclosure(vm, mth.fn, 0);
212 sq_newslot(vm, -3, SQFalse);
213 }
214 return 1;
215}
216
217} // namespace
218
219void installScriptFileApi(ssq::VM& vm) {
220 HSQUIRRELVM h = vm.getHandle();
221 const SQInteger top = sq_gettop(h);
222
223 struct { const SQChar* name; SQFUNCTION fn; } globals[] = {
224 {_SC("dofile"), sq_dofile},
225 {_SC("loadfile"), sq_loadfile},
226 {_SC("file"), sq_file},
227 };
228 for (const auto& g : globals) {
229 sq_pushroottable(h);
230 sq_pushstring(h, g.name, -1);
231 sq_newclosure(h, g.fn, 0);
232 sq_newslot(h, -3, SQTrue);
233 sq_pop(h, 1);
234 }
235
236 sq_settop(h, top);
237}
238
239} // namespace physfs
240} // namespace filesystem
241} // namespace eve
double m[16]
const std::string & s
struct SQVM * HSQUIRRELVM
HSQUIRRELVM vm
Definition ECS.cpp:38
std::string name
Definition ECS.cpp:154
tensor::Graph g
Definition GpuGraph.cpp:7
int h
std::weak_ptr< Run > run
Definition OnnxGpgpu.cpp:25
std::string error
Definition Package.cpp:174
float f
std::string path
Definition PlayHost.cpp:111
std::string uri
std::map< std::string, const Contract * > methods
ScriptStructure out
static Runtime * runtime()
Active runtime associated with the last expose() call, or nullptr. @ownership Borrowed; the embedding...
static Runtime * current() noexcept
The runtime currently at the top of this thread's runtime stack, or nullptr.
Definition Runtime.cpp:536
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.
SQInteger top
Definition Snapshot.cpp:115
void installScriptFileApi(ssq::VM &vm)
用 PhysFS 版本覆盖 Squirrel 的 file / dofile / loadfile 全局, 使脚本与资源从已挂载的游戏源(真实目录或内存挂载的 .eve 归档)解析; PhysFS 中不...
Definition FileApi.cpp:219
Build metadata (engine git commit, build time, third-party version).
Definition Build.cpp:16
SettlementPipeline::Stage fn