载入中...
搜索中...
未找到
GameWorldContext.cpp
浏览该文件的文档.
2
3#include "common/Capability.h"
8
9#include <squirrel.h>
10
11#include <algorithm>
12#include <filesystem>
13#include <fstream>
14#include <set>
15#include <sstream>
16#include <utility>
17
18namespace eve::dev {
19namespace {
20
21Value g_runtimeWorld;
22bool g_hasRuntimeWorld = false;
23
24Result<void> knownFields(const Value::Object& object, const std::set<std::string>& allowed,
25 std::string_view path) {
26 for (const auto& [name, value] : object) {
27 (void)value;
28 if (!allowed.contains(name))
30 Diagnostic::error(DiagnosticCode::ParseError, "unknown world field",
31 std::string(path) + "." + name));
32 }
33 return Result<void>::success();
34}
35
36Result<std::vector<std::string>> stringArray(const Value& value, std::string path) {
37 const auto* array = value.getIf<Value::Array>();
38 if (!array)
39 return Result<std::vector<std::string>>::failure(
40 Diagnostic::error(DiagnosticCode::ParseError, "world array must contain strings", path));
41 std::vector<std::string> out;
42 out.reserve(array->size());
43 for (std::size_t index = 0; index < array->size(); ++index) {
44 if (!(*array)[index].isString())
45 return Result<std::vector<std::string>>::failure(Diagnostic::error(
46 DiagnosticCode::ParseError, "world array entry must be a string",
47 path + "." + std::to_string(index)));
48 out.push_back((*array)[index].asString());
49 }
50 return Result<std::vector<std::string>>::success(std::move(out));
51}
52
53Result<std::string> optionalStringField(const Value::Object& object, std::string_view name,
54 std::string_view path, std::string* out) {
55 const auto found = object.find(std::string(name));
56 if (found == object.end()) return Result<std::string>::success(std::string{});
57 if (!found->second.isString())
59 DiagnosticCode::ParseError, "world field must be a string",
60 std::string(path) + "." + std::string(name)));
61 *out = found->second.asString();
63}
64
65Value encodeStrings(const std::vector<std::string>& values) {
66 Value::Array array;
67 array.reserve(values.size());
68 for (const auto& value : values) array.emplace_back(value);
69 return Value(std::move(array));
70}
71
72std::vector<std::string> uniqueSorted(std::vector<std::string> values) {
73 std::sort(values.begin(), values.end());
74 values.erase(std::unique(values.begin(), values.end()), values.end());
75 return values;
76}
77
78Result<Value> readRootMember(HSQUIRRELVM vm, const char* name) {
80 DiagnosticCode::NotFound, "no VM attached", "vm"));
81 const SQInteger top = sq_gettop(vm);
82 sq_pushroottable(vm);
83 sq_pushstring(vm, name, -1);
84 if (SQ_FAILED(sq_get(vm, -2))) {
85 sq_settop(vm, top);
87 Diagnostic::error(DiagnosticCode::NotFound, std::string(name) + " missing", name));
88 }
89 script::SquirrelValueOptions options;
90 options.maxDepth = 8;
91 options.maxElements = 4096;
92 options.source = name;
94 sq_settop(vm, top);
95 return value;
96}
97
98void appendStringArrayField(const Value::Object& object, const char* key,
99 std::vector<std::string>* out) {
100 const auto found = object.find(key);
101 if (found == object.end() || !found->second.isArray()) return;
102 for (const auto& entry : *found->second.getIf<Value::Array>()) {
103 if (entry.isString() && !entry.asString().empty()) out->push_back(entry.asString());
104 }
105}
106
107} // namespace
108
110 const auto* object = world.getIf<Value::Object>();
111 if (!object)
113 Diagnostic::error(DiagnosticCode::ParseError, "world must be an object", "world"));
114 auto known = knownFields(*object,
115 {"dimensions", "genre", "perspective", "summary", "systems", "tags", "title"},
116 "world");
117 if (!known) return Result<Value>::failure(known.status());
118
119 Value::Object normalized;
120 std::string title;
121 std::string summary;
122 std::string dimensions;
123 std::string perspective;
124 auto titleResult = optionalStringField(*object, "title", "world", &title);
125 if (!titleResult) return Result<Value>::failure(titleResult.status());
126 auto summaryResult = optionalStringField(*object, "summary", "world", &summary);
127 if (!summaryResult) return Result<Value>::failure(summaryResult.status());
128 auto dimensionsResult = optionalStringField(*object, "dimensions", "world", &dimensions);
129 if (!dimensionsResult) return Result<Value>::failure(dimensionsResult.status());
130 auto perspectiveResult = optionalStringField(*object, "perspective", "world", &perspective);
131 if (!perspectiveResult) return Result<Value>::failure(perspectiveResult.status());
132
133 if (!dimensions.empty() && dimensions != "2d" && dimensions != "3d" && dimensions != "hybrid")
135 DiagnosticCode::ParseError, "world.dimensions must be 2d, 3d, or hybrid", "world.dimensions"));
136
137 if (!title.empty()) normalized.emplace("title", Value(std::move(title)));
138 if (!summary.empty()) normalized.emplace("summary", Value(std::move(summary)));
139 if (!dimensions.empty()) normalized.emplace("dimensions", Value(std::move(dimensions)));
140 if (!perspective.empty()) normalized.emplace("perspective", Value(std::move(perspective)));
141
142 for (const char* key : {"genre", "tags", "systems"}) {
143 const auto found = object->find(key);
144 if (found == object->end()) continue;
145 auto array = stringArray(found->second, std::string("world.") + key);
146 if (!array) return Result<Value>::failure(array.status());
147 normalized.emplace(key, encodeStrings(uniqueSorted(std::move(array).takeValue())));
148 }
149
150 const bool hasIdentity = normalized.contains("title") || normalized.contains("summary") ||
151 normalized.contains("genre") || normalized.contains("systems");
152 if (!hasIdentity)
155 "world requires at least one of title, summary, genre, or systems", "world"));
156
157 return Result<Value>::success(Value(std::move(normalized)));
158}
159
161 auto parsed = parseWorldObject(world);
162 if (!parsed) return Result<void>::failure(parsed.status());
163 g_runtimeWorld = std::move(parsed).takeValue();
164 g_hasRuntimeWorld = true;
165 return Result<void>::success();
166}
167
169 g_runtimeWorld = Value{};
170 g_hasRuntimeWorld = false;
171}
172
173bool hasWorldContext() noexcept { return g_hasRuntimeWorld; }
174
175const Value* runtimeWorldContext() noexcept {
176 return g_hasRuntimeWorld ? &g_runtimeWorld : nullptr;
177}
178
180 const Value* runtime = runtimeWorldContext();
181 const bool hasRuntime = runtime && runtime->isObject();
182
183 // Title / systems already live on the VM config table for nearly every game.
184 // publishWorldContext is only needed for narrative fields (summary, genre, …)
185 // or to override title; module lists stay at the snapshot root.
186 Value world;
187 std::string source = "none";
188 if (hasRuntime) {
189 source = "runtime";
190 const auto* published = runtime->getIf<Value::Object>();
191 Value::Object merged = published ? *published : Value::Object{};
192 if (!merged.contains("title") && !input.configTitle.empty())
193 merged.emplace("title", Value(input.configTitle));
194 world = Value(std::move(merged));
195 } else if (!input.configTitle.empty()) {
196 world = Value(Value::Object{{"title", Value(input.configTitle)}});
197 source = "config";
198 }
199
200 Value::Object snapshot{{"schemaId", Value(std::string(kGameWorldSchemaId))},
201 {"schemaVersion", Value(kGameWorldSchemaVersion)},
202 {"source", Value(std::move(source))},
203 {"contractLoaded", Value(input.contractLoaded)},
204 {"domains", encodeStrings(uniqueSorted(input.domains))},
205 {"configuredModules", encodeStrings(uniqueSorted(input.configuredModules))},
206 {"liveModules", encodeStrings(uniqueSorted(input.liveModules))}};
207 if (!input.contractId.empty()) snapshot.emplace("contractId", Value(input.contractId));
208 if (!input.gameRoot.empty()) snapshot.emplace("gameRoot", Value(input.gameRoot));
209 if (!input.configTitle.empty()) snapshot.emplace("configTitle", Value(input.configTitle));
210 if (world.isObject()) snapshot.emplace("world", std::move(world));
211 else snapshot.emplace("world", Value{});
212 return Result<Value>::success(Value(std::move(snapshot)));
213}
214
216 auto config = readRootMember(vm, "config");
217 if (!config || !config.value().isObject()) {
218 if (config) config.ignore();
219 return {};
220 }
221 const auto* object = config.value().getIf<Value::Object>();
222 const auto found = object->find("title");
223 std::string title;
224 if (found != object->end() && found->second.isString()) title = found->second.asString();
225 config.ignore();
226 return title;
227}
228
229std::vector<std::string> readConfiguredModules(HSQUIRRELVM vm) {
230 std::vector<std::string> modules;
231 auto config = readRootMember(vm, "config");
232 if (!config || !config.value().isObject()) {
233 if (config) config.ignore();
234 return modules;
235 }
236 const auto* object = config.value().getIf<Value::Object>();
237 appendStringArrayField(*object, "modules", &modules);
238 appendStringArrayField(*object, "optionalModules", &modules);
239 config.ignore();
240 return uniqueSorted(std::move(modules));
241}
242
243std::vector<std::string> readLiveModules(HSQUIRRELVM vm) {
244 std::vector<std::string> live;
245 if (!vm) return live;
246
247 const SQInteger top = sq_gettop(vm);
248 sq_pushroottable(vm);
249 sq_pushstring(vm, _SC("eve"), -1);
250 if (SQ_FAILED(sq_get(vm, -2)) || sq_gettype(vm, -1) != OT_TABLE) {
251 sq_settop(vm, top);
252 return live;
253 }
254 sq_pushstring(vm, _SC("moduleList"), -1);
255 if (SQ_FAILED(sq_get(vm, -2)) || sq_gettype(vm, -1) != OT_ARRAY) {
256 sq_settop(vm, top);
257 return live;
258 }
259
260 const SQInteger count = sq_getsize(vm, -1);
261 for (SQInteger index = 0; index < count; ++index) {
262 sq_pushinteger(vm, index);
263 if (SQ_FAILED(sq_get(vm, -2)) || sq_gettype(vm, -1) != OT_TABLE) {
264 if (sq_gettop(vm) > top + 3) sq_poptop(vm);
265 continue;
266 }
267 sq_pushstring(vm, _SC("slot"), -1);
268 std::string slotName;
269 if (SQ_SUCCEEDED(sq_get(vm, -2))) {
270 if (sq_gettype(vm, -1) == OT_STRING) {
271 const SQChar* slot = nullptr;
272 sq_getstring(vm, -1, &slot);
273 if (slot) slotName = slot;
274 }
275 sq_poptop(vm); // slot value
276 } else {
277 sq_poptop(vm); // unused key
278 }
279 sq_poptop(vm); // module entry
280 if (slotName.empty()) continue;
281
282 sq_pushroottable(vm);
283 sq_pushstring(vm, slotName.c_str(), -1);
284 const bool present = SQ_SUCCEEDED(sq_get(vm, -2)) && sq_gettype(vm, -1) == OT_INSTANCE;
285 sq_settop(vm, top + 3); // keep root / eve / moduleList
286 if (present) live.push_back(std::move(slotName));
287 }
288 sq_settop(vm, top);
289 return uniqueSorted(std::move(live));
290}
291
296 input.configTitle = readConfigTitle(vm);
297 input.configuredModules = readConfiguredModules(vm);
298 input.liveModules = readLiveModules(vm);
299 eve::cap::forEach<IGameplayControlProvider>([&](auto* candidate) {
300 if (candidate) input.domains.emplace_back(candidate->gameplayDomain());
301 });
302
303 // Play contract id is optional Discover metadata only — never world authority.
304 std::filesystem::path root = input.gameRoot;
305 if (root.empty()) {
306 std::error_code ec;
307 root = std::filesystem::current_path(ec);
308 if (!ec) input.gameRoot = root.string();
309 }
310 const auto path = root / "game.agent.json";
311 std::error_code ec;
312 if (std::filesystem::is_regular_file(path, ec)) {
313 std::ifstream in(path, std::ios::binary);
314 if (in) {
315 std::ostringstream contents;
316 contents << in.rdbuf();
317 auto parsed = Value::fromJson(contents.str());
318 if (parsed && parsed.value().isObject()) {
319 input.contractLoaded = true;
320 const auto* object = parsed.value().getIf<Value::Object>();
321 const auto id = object->find("id");
322 if (id != object->end() && id->second.isString()) input.contractId = id->second.asString();
323 } else if (parsed) {
324 parsed.ignore();
325 } else {
326 // Malformed Play contract must not block runtime world Discover.
327 parsed.ignore();
328 }
329 }
330 }
332}
333
334} // namespace eve::dev
int root
Definition AnimSmr.cpp:119
std::vector< std::unique_ptr< ScriptClimbingEventSink > > live
struct SQVM * HSQUIRRELVM
std::string title
HSQUIRRELVM vm
Definition ECS.cpp:38
SQObjectPtr key
Definition ECS.cpp:155
std::string name
Definition ECS.cpp:154
EvpackChunkInput input
Definition Evpack.cpp:170
Runtime game-world Discover snapshot for MCP / Play Host.
Host-neutral player-equivalent command and observation protocol.
std::int32_t second
bool present
std::string id
Snapshot snapshot
std::string path
Definition PlayHost.cpp:111
std::set< std::string > values
Object::Ptr value
std::string slot
bool found
ScriptStructure out
std::string_view source
size_t end
const SquirrelValueOptions & options
int count
The single Squirrel projection for common Result, Status and Value.
Json object
uint32_t index
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
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
The canonical owning dynamic value used by data-facing protocols.
Definition Value.h:31
static Result< Value > fromJson(std::string_view json)
Parse one strict JSON value into an owning Value.
Definition Value.cpp:177
std::map< std::string, Value > Object
Definition Value.h:34
std::vector< Value > Array
Definition Value.h:33
HSQUIRRELVM vm() const
Definition Debugger.hpp:96
static Debugger & instance()
Definition Debugger.cpp:387
const std::string & gameRoot() const
Definition McpServer.hpp:67
static McpServer & instance()
SQInteger top
Definition Snapshot.cpp:115
Value stringArray(const std::vector< std::string > &values)
std::variant< std::monostate, std::int64_t, double, std::string, bool > Value
Definition Database.h:27
std::vector< std::string > readConfiguredModules(HSQUIRRELVM vm)
Read config.modules / optionalModules from the attached VM root.
Result< Value > buildGameWorldSnapshot(const GameWorldSnapshotInput &input)
Assemble runtime world brief plus live system lists.
constexpr std::int64_t kGameWorldSchemaVersion
Schema version for the game-world snapshot.
constexpr std::string_view kGameWorldSchemaId
Schema id for the game-world snapshot returned to agents.
std::string readConfigTitle(HSQUIRRELVM vm)
Read config.title from the attached VM root.
Result< Value > liveGameWorldSnapshot()
Build the Discover snapshot against the live engine.
void clearWorldContext()
Drop the runtime world brief (soft restart with script reload).
std::vector< std::string > readLiveModules(HSQUIRRELVM vm)
List instantiated module slots declared in eve.moduleList.
Result< Value > parseWorldObject(const Value &world)
Validate one runtime-published world object.
const Value * runtimeWorldContext() noexcept
Current runtime brief, or null when none is published. @ownership Borrowed; valid until the next publ...
Result< void > publishWorldContext(Value world)
Replace the runtime world brief published by the live game script.
bool hasWorldContext() noexcept
Whether a runtime brief is currently published.
Result< Value > valueFromSquirrel(HSQUIRRELVM vm, SQInteger index, const SquirrelValueOptions &options)
Convert one Squirrel value into the canonical owning Value tree.
enum EVENGINE_API_FOUNDATION Array
OT_ARRAY (editable via Runtime array APIs / ReflectedPropertyModel).
Definition Runtime.h:120
Inputs used to assemble one Discover snapshot. @ownership Callers own the pointed-to Values; they are...
std::string gameRoot
Absolute or relative game root reported to agents.