载入中...
搜索中...
未找到
ScriptComponentSnapshot.cpp
浏览该文件的文档.
2
3#include "common/Diagnostic.h"
4#include "common/ECS.h"
6#include "common/Value.h"
7
8#include <squirrel.h>
9#include <simplesquirrel/simplesquirrel.hpp>
10
11#include <algorithm>
12#include <cstdint>
13#include <map>
14#include <string>
15#include <utility>
16#include <vector>
17
18namespace eve {
19namespace {
20
22constexpr const char* kComponentsField = "components";
23constexpr const char* kEntityField = "entity";
24constexpr const char* kNameField = "name";
25constexpr const char* kVersionField = "version";
26constexpr const char* kFieldsField = "fields";
27
28constexpr std::uint64_t kSchemaVersion = 1;
29
30Result<void> snapshotFailure(DiagnosticCode code, std::string message, std::string path = {}) {
31 return Result<void>::failure(Diagnostic::error(code, std::move(message), std::move(path), {}, "ecs.snapshot"));
32}
33
35std::string entityIdText(std::uint64_t entityId) { return std::to_string(entityId); }
36
37Result<std::uint64_t> parseEntityId(const Value& value, std::size_t index) {
38 if (!value.isString())
40 DiagnosticCode::ParseError, "script component snapshot entity id must be a decimal string",
41 std::to_string(index), {}, "ecs.snapshot"));
42 const std::string& text = value.asString();
43 if (text.empty())
45 "script component snapshot entity id must not be empty",
46 std::to_string(index), {}, "ecs.snapshot"));
47 std::uint64_t parsed = 0;
48 for (const char digit : text) {
49 if (digit < '0' || digit > '9')
51 DiagnosticCode::ParseError, "script component snapshot entity id must be decimal digits only", text, {},
52 "ecs.snapshot"));
53 const std::uint64_t next = parsed * 10u + static_cast<std::uint64_t>(digit - '0');
54 if (next < parsed)
56 DiagnosticCode::ParseError, "script component snapshot entity id overflows", text, {}, "ecs.snapshot"));
57 parsed = next;
58 }
59 return Result<std::uint64_t>::success(parsed);
60}
61
62// 字段顺序不需要在这里做什么:`Value::Object` 是 `std::map`,序列化与哈希输入永远是字典序(跨进程
63// 稳定)。§9.63 那条"按声明顺序遍历"只对**直接遍历 `Value`** 的消费者(例如将来的编辑器列表)有意义,
64// 对 JSON/哈希不可观测——所以这里原样搬存储里那一份,既不排序也不丢字段。
65
66} // namespace
67
69 // `LogicalId` 的构造是私有的:只能经语法校验的解析入口拿到(命名空间必须小写开头)。
70 static const LogicalId schema = *LogicalId::parse("eve:script-components");
71 return schema;
72}
73
75 const SnapshotHashProvider& hashProvider) {
76 Value::Array components;
78 Value::Object item;
79 item.emplace(kEntityField, Value::string(entityIdText(entry.key.entityId)));
80 item.emplace(kNameField, Value::string(entry.key.name));
81 item.emplace(kVersionField, Value::integer(static_cast<std::int64_t>(entry.key.version.value())));
82 item.emplace(kFieldsField, entry.values);
83 components.push_back(Value::object(std::move(item)));
84 }
85
87 payload.emplace(kComponentsField, Value::array(std::move(components)));
89 SchemaVersion(kSchemaVersion), instanceId, revision, tick,
90 Value::object(std::move(payload)), hashProvider);
91}
92
95 return snapshotFailure(DiagnosticCode::InvalidArgument,
96 "snapshot does not belong to the script component store");
97 if (snapshot.schemaVersion.value() != kSchemaVersion)
98 return snapshotFailure(DiagnosticCode::UnknownVersion,
99 "script component snapshot version is not the current one", snapshot.schema.format());
100 auto verified = verifySnapshotEnvelope(snapshot, hashProvider);
101 if (!verified.ok()) return verified;
102
103 const Value* components = snapshot.payload.find(kComponentsField);
104 if (components == nullptr || !components->isArray())
105 return snapshotFailure(DiagnosticCode::ParseError, "script component snapshot has no components array");
106
107 // 先全部校验进候选表,**不碰**现有数据:恢复失败必须什么都不改(仓库规则:restore 不许留下
108 // 部分变更的可观测状态)。
109 std::map<ScriptComponentStoreKey, Value> candidate;
110 for (std::size_t index = 0; index < components->arraySize(); ++index) {
111 const Value& item = components->at(index);
112 if (!item.isObject())
113 return snapshotFailure(DiagnosticCode::ParseError, "script component snapshot entry must be an object",
114 std::to_string(index));
115 const Value* entity = item.find(kEntityField);
116 const Value* name = item.find(kNameField);
117 const Value* version = item.find(kVersionField);
118 const Value* fields = item.find(kFieldsField);
119 if (entity == nullptr || name == nullptr || version == nullptr || fields == nullptr)
120 return snapshotFailure(DiagnosticCode::ParseError,
121 "script component snapshot entry is missing a required field",
122 std::to_string(index));
123 if (!name->isString() || name->asString().empty())
124 return snapshotFailure(DiagnosticCode::ParseError, "script component snapshot entry has an empty name",
125 std::to_string(index));
126 if (!version->isInt64() || version->asInt() <= 0)
127 return snapshotFailure(DiagnosticCode::ParseError, "script component snapshot entry has an invalid version",
128 name->asString());
129 if (!fields->isObject())
130 return snapshotFailure(DiagnosticCode::ParseError,
131 "script component snapshot entry fields must be an object", name->asString());
132
133 auto entityId = parseEntityId(*entity, index);
134 if (!entityId.ok()) return Result<void>::failure(entityId.status());
135
136 const std::string componentName = name->asString();
137 const SchemaVersion componentVersion(static_cast<std::uint64_t>(version->asInt()));
138 const ScriptComponentRecord* record = findScriptComponent(componentName, componentVersion);
139 if (record == nullptr)
140 return snapshotFailure(DiagnosticCode::NotFound,
141 "snapshot describes a script component this build does not know",
142 componentName + "@" + std::to_string(componentVersion.value()));
143 // 未知字段策略:显式拒绝。字段集变过的旧载荷必须走迁移链,不能被静默收下——否则存储里会
144 // 出现没人声明的字段,序列化/编辑器都会看见它。
145 for (const auto& fieldEntry : *fields->getIf<Value::Object>()) {
146 const std::string& key = fieldEntry.first;
147 bool declared = false;
148 for (const std::string& field : record->fields) {
149 if (field == key) {
150 declared = true;
151 break;
152 }
153 }
154 if (!declared)
155 return snapshotFailure(DiagnosticCode::Unsupported,
156 "script component snapshot field is not in the current schema",
157 componentName + "." + key);
158 }
159
160 const ScriptComponentStoreKey key{entityId.value(), componentName, componentVersion};
161 if (candidate.find(key) != candidate.end())
162 return snapshotFailure(DiagnosticCode::Conflict, "script component snapshot has a duplicate entry",
163 componentName);
164 candidate.emplace(key, *fields);
165 }
166
167 std::vector<ScriptComponentStoreEntry> entries;
168 entries.reserve(candidate.size());
169 for (auto& [key, values] : candidate) entries.push_back(ScriptComponentStoreEntry{key, std::move(values)});
172}
173
175 const SnapshotHashProvider& hashProvider) {
176 auto envelope = snapshotScriptComponents(instanceId, revision, tick, hashProvider);
177 if (!envelope.ok()) return Result<std::string>::failure(envelope.status());
178 return std::move(envelope).andThen([](SnapshotEnvelope&& value) { return serializeSnapshotEnvelope(value); });
179}
180
182 auto parsed = parseSnapshotEnvelope(json, hashProvider);
183 if (!parsed.ok()) return Result<void>::failure(parsed.status());
184 return restoreScriptComponents(parsed.value(), hashProvider);
185}
186
188 if (entityInstance.getType() != ssq::Type::INSTANCE)
190 Diagnostic::error(DiagnosticCode::InvalidArgument, "script component inspection needs an entity instance",
191 {}, {}, "ecs.snapshot"));
192 HSQUIRRELVM vm = entityInstance.getHandle();
193 if (vm == nullptr)
195 Diagnostic::error(DiagnosticCode::InvalidArgument, "script component inspection needs a live script VM", {},
196 {}, "ecs.snapshot"));
197
198 // 实例上的 `_eid` 是实体身份,`_comps`(都是 `eve.Entity` 的声明槽位)是"这个实体有哪些
199 // 组件"的事实来源;每个组件实例上的 `_componentName`/`_componentVersion` 是它登记时的身份
200 // (§9.64 的控制槽位)。两步都用公开 sq API 读取,不碰 Squirrel 内部结构。
201 std::vector<std::pair<std::string, SchemaVersion>> identities;
202 std::uint64_t entityId = 0;
203 const SQInteger top = sq_gettop(vm);
204 sq_pushobject(vm, entityInstance.getRaw());
205
206 sq_pushstring(vm, "_eid", -1);
207 if (SQ_SUCCEEDED(sq_get(vm, -2))) {
208 SQInteger raw = 0;
209 if (SQ_SUCCEEDED(sq_getinteger(vm, -1, &raw)) && raw > 0) entityId = static_cast<std::uint64_t>(raw);
210 }
211 sq_settop(vm, top);
212
213 sq_pushobject(vm, entityInstance.getRaw());
214 sq_pushstring(vm, "_comps", -1);
215 if (SQ_FAILED(sq_get(vm, -2)) || sq_gettype(vm, -1) != OT_TABLE) {
216 sq_settop(vm, top);
218 }
219 sq_pushnull(vm); // 迭代游标
220 while (SQ_SUCCEEDED(sq_next(vm, -2))) {
221 // 栈:instance, comps, cursor, key, value
222 if (sq_gettype(vm, -1) == OT_INSTANCE) {
223 std::string name;
224 std::int64_t version = 0;
225 const auto readComponentSlot = [&](const char* slot, bool asText) -> bool {
226 const SQInteger inner = sq_gettop(vm);
227 sq_push(vm, -1); // 组件实例
228 sq_pushstring(vm, slot, -1);
229 const bool found = SQ_SUCCEEDED(sq_get(vm, -2));
230 bool ok = false;
231 if (found && asText) {
232 const SQChar* raw = nullptr;
233 ok = SQ_SUCCEEDED(sq_getstring(vm, -1, &raw)) && raw != nullptr;
234 if (ok) name = raw;
235 } else if (found) {
236 SQInteger raw = 0;
237 ok = SQ_SUCCEEDED(sq_getinteger(vm, -1, &raw));
238 if (ok) version = static_cast<std::int64_t>(raw);
239 }
240 sq_settop(vm, inner);
241 return ok;
242 };
243 if (readComponentSlot("_componentName", true) && !name.empty() &&
244 readComponentSlot("_componentVersion", false) && version > 0)
245 identities.emplace_back(name, SchemaVersion(static_cast<std::uint64_t>(version)));
246 }
247 sq_pop(vm, 2); // key, value
248 }
249 sq_settop(vm, top);
250
251 std::sort(identities.begin(), identities.end());
252 identities.erase(std::unique(identities.begin(), identities.end()), identities.end());
253
254 std::vector<ScriptComponentInstanceState> out;
255 out.reserve(identities.size());
256 for (const auto& [name, version] : identities) {
258 state.entityId = entityId;
259 state.name = name;
260 state.version = version;
262 state.generation = record != nullptr ? record->generation : Generation(0);
263
265 // 按声明的顺序收集(inspector 需要稳定顺序);存储里缺的字段给 null,让"有组件但缺数据"
266 // 在工具里可见。
267 const std::vector<std::string> fields = record != nullptr ? record->fields : std::vector<std::string>{};
268 for (const std::string& field : fields) {
269 const Value* value = stored != nullptr ? stored->find(field) : nullptr;
270 state.fields.emplace(field, value != nullptr ? *value : Value::null());
271 }
272 if (record == nullptr && stored != nullptr) {
273 if (const auto* object = stored->getIf<Value::Object>()) state.fields = *object;
274 }
275 out.push_back(std::move(state));
276 }
277 return Result<std::vector<ScriptComponentInstanceState>>::success(std::move(out));
278}
279
281 // 存储本身就是按 (实体, 名字, 版本) 排序的 `std::map`,所以按实体分组只需要顺序扫一遍。
283 Value::Array components;
284 std::uint64_t currentId = 0;
285 bool open = false;
286 const auto flush = [&]() {
287 if (!open) return;
288 entities.push_back(Value::object(
289 {{"id", Value::string(entityIdText(currentId))}, {"components", Value::array(std::move(components))}}));
290 components = Value::Array{};
291 open = false;
292 };
294 if (!open || entry.key.entityId != currentId) {
295 flush();
296 currentId = entry.key.entityId;
297 open = true;
298 }
299 const ScriptComponentRecord* record = findScriptComponent(entry.key.name, entry.key.version);
300 components.push_back(Value::object(
301 {{"name", Value::string(entry.key.name)},
302 {"version", Value::integer(static_cast<std::int64_t>(entry.key.version.value()))},
303 {"generation",
304 Value::integer(static_cast<std::int64_t>(record != nullptr ? record->generation.value() : 0))},
305 {"fields", entry.values}}));
306 }
307 flush();
308
309 return Value::object({{"entities", Value::array(std::move(entities))}}).toJson();
310}
311
312} // namespace eve
Value::Object payload
std::uint64_t revision
std::unordered_map< std::string, QuestRuntime > entries
struct SQVM * HSQUIRRELVM
Stable, structured diagnostics shared by engine modules.
HSQUIRRELVM vm
Definition ECS.cpp:38
SQObjectPtr key
Definition ECS.cpp:155
ScriptComponentRecord record
Definition ECS.cpp:228
std::string name
Definition ECS.cpp:154
std::vector< std::string > fields
Definition ECS.cpp:42
double raw
int instanceId
std::vector< std::uint8_t > stored
Definition Evpack.cpp:171
#define EVENGINE_API_FOUNDATION
每个链接组(link group)各自的导出宏。
Definition Export.h:106
std::string message
DiagnosticCode code
Snapshot snapshot
std::string path
Definition PlayHost.cpp:111
std::vector< ecs::EntityHandle > entities
std::set< std::string > values
std::set< std::string > identities
Object::Ptr value
const EntityFact * entity
std::string slot
bool found
脚本组件数据的持久化信封(方案文档实施顺序第 4 步 / J-3 的存档通路)。
脚本组件字段的引擎侧权威存储。
std::string text
ScriptStructure out
SimulationTick tick
uint32_t index
Owning, renderer-independent dynamic values.
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Human-readable, scoped identifier in the form namespace:name.
Definition Identity.h:414
static std::optional< LogicalId > parse(std::string_view text)
Parses a scoped logical name.
Definition Identity.cpp:37
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
The canonical owning dynamic value used by data-facing protocols.
Definition Value.h:31
std::map< std::string, Value > Object
Definition Value.h:34
bool isArray() const noexcept
Return true when this value is an array.
Definition Value.h:108
static Value string(std::string value)
Compatibility factory for a string value.
Definition Value.h:121
std::vector< Value > Array
Definition Value.h:33
static Value array(Array value)
Compatibility factory for an array value.
Definition Value.cpp:128
static Value integer(std::int64_t value)
Compatibility factory for an Int64 value.
Definition Value.h:115
std::size_t arraySize() const
Return the number of array elements.
Definition Value.cpp:220
bool isObject() const noexcept
Return true when this value is an object.
Definition Value.h:110
Value & at(std::size_t index)
Return a bounds-checked array element.
Definition Value.cpp:226
static Value object(Object value)
Compatibility factory for an object value.
Definition Value.cpp:129
Value * find(const std::string &key) noexcept
Return an object member, or nullptr when absent.
Definition Value.cpp:244
Id128 public API.
Definition Identity.h:111
constexpr std::uint64_t value() const noexcept
Returns the underlying value at an explicit protocol boundary.
SQInteger top
Definition Snapshot.cpp:115
constexpr HexDirection next(HexDirection d) noexcept
The next direction clockwise (NW wraps to NE).
Definition HexMetrics.h:76
Build metadata (engine git commit, build time, third-party version).
Definition Build.cpp:16
EVENGINE_API_FOUNDATION Result< std::string > scriptComponentStatesJson()
引擎侧脚本组件数据的**工具视图**(MCP eve_script_components 与诊断用)。
DiagnosticCode
Stable machine-readable diagnostic codes.
Definition Diagnostic.h:47
EVENGINE_API_FOUNDATION Result< std::string > serializeScriptComponentSnapshot(PersistentId instanceId, Revision revision, SimulationTick tick, const SnapshotHashProvider &hashProvider)
采集并序列化成确定性 JSON(存档写盘用)。 @cost 同 snapshotScriptComponents + 一次序列化。
const Value * findScriptComponentValues(const ScriptComponentStoreKey &key)
读一条组件数据。
void replaceScriptComponentValues(std::vector< ScriptComponentStoreEntry > entries)
用给定条目**整体替换**存储(恢复快照用)。
constexpr const char * kScriptComponentSnapshotType
脚本组件快照的稳定类型(SnapshotEnvelope::type)。
EVENGINE_API_FOUNDATION Result< void > restoreScriptComponents(const SnapshotEnvelope &snapshot, const SnapshotHashProvider &hashProvider)
用快照里的数据**整体替换**当前的脚本组件数据。
Result< SnapshotEnvelope > parseSnapshotEnvelope(std::string_view json, const SnapshotHashProvider &hashProvider)
Parse and verify an envelope from canonical or compatible JSON text.
Definition Snapshot.cpp:190
detail::StrongUint64< detail::SchemaVersionTag > SchemaVersion
Persistent data-format version; not a runtime replacement generation.
Result< std::string > serializeSnapshotEnvelope(const SnapshotEnvelope &snapshot)
Serialize an envelope as deterministic compact JSON.
Definition Snapshot.cpp:184
std::vector< ScriptComponentStoreEntry > scriptComponentStoreEntries()
列出存储里的全部条目,按 (实体, 组件名, 版本) 升序。
EVENGINE_API_FOUNDATION LogicalId scriptComponentSnapshotSchema()
脚本组件快照的 payload schema:eve:script-components 版本 1。
Result< SnapshotEnvelope > makeSnapshotEnvelope(std::string type, LogicalId schema, SchemaVersion schemaVersion, PersistentId instanceId, Revision revision, SimulationTick tick, Value payload, const SnapshotHashProvider &hashProvider)
Construct and seal a snapshot envelope.
Definition Snapshot.cpp:103
Result< void > verifySnapshotEnvelope(const SnapshotEnvelope &snapshot, const SnapshotHashProvider &hashProvider)
Verify an envelope's content hash without modifying it.
Definition Snapshot.cpp:63
const ScriptComponentRecord * findScriptComponent(const std::string &name, SchemaVersion version)
当前未退役的那条登记。
Definition ECS.cpp:1549
EVENGINE_API_FOUNDATION Result< std::vector< ScriptComponentInstanceState > > scriptComponentInstancesOf(const ssq::Object &entityInstance)
读一个脚本实体实例上挂着的全部**已登记**组件的状态。
std::function< Result< ContentId >(std::string_view canonicalInput)> SnapshotHashProvider
Injected content-digest implementation used by snapshots.
Definition Snapshot.h:36
EVENGINE_API_FOUNDATION Result< void > restoreScriptComponentSnapshotJson(std::string_view json, const SnapshotHashProvider &hashProvider)
从 JSON 解析、校验并恢复。
EVENGINE_API_FOUNDATION Result< SnapshotEnvelope > snapshotScriptComponents(PersistentId instanceId, Revision revision, SimulationTick tick, const SnapshotHashProvider &hashProvider)
把引擎侧的脚本组件数据封成一个快照信封。
一个脚本实体实例上某个组件的**当前状态**(供引擎工具读取)。
std::uint64_t entityId
脚本 VM 内的实体 id(实例上的 _eid)。
脚本组件注册表的一条记录。
Definition ECS.h:43
std::vector< std::string > fields
该代声明的字段名,**按声明顺序**(基类字段在前)。
Definition ECS.h:61
存储里的一条数据:键 + 一份字段对象。
一条脚本组件数据的键:实体 + 组件名 + 版本。
Stable outer format shared by persistence and cross-process snapshots.
Definition Snapshot.h:46