载入中...
搜索中...
未找到
SceneAuthoringDocument.cpp
浏览该文件的文档.
3
4#include <array>
5#include <cmath>
6#include <set>
7
8namespace eve::scene_editing {
9namespace {
10using namespace eve::editing;
11const Value* field(const Value& value, const char* key) {
12 const auto* object = value.getIf<Value::Object>();
13 if (!object) return nullptr;
14 const auto it = object->find(key);
15 return it == object->end() ? nullptr : &it->second;
16}
17bool number(const Value& value, double& out) {
18 if (const auto* v = value.getIf<double>())
19 out = *v;
20 else if (const auto* v = value.getIf<std::int64_t>())
21 out = static_cast<double>(*v);
22 else
23 return false;
24 return std::isfinite(out);
25}
26bool vector(const Value* value, int count) {
27 const auto* a = value ? value->getIf<Value::Array>() : nullptr;
28 if (!a || a->size() != static_cast<std::size_t>(count)) return false;
29 for (const auto& v : *a) {
30 double out;
31 if (!number(v, out)) return false;
32 }
33 return true;
34}
35Result<void> validate(const std::string& section, const Value& value) {
36 const auto reject = [](const char* text) {
37 return failed<void>(Status::Rejected, RuleId("scene.authoring.schema"), text);
38 };
39 const auto* object = value.getIf<Value::Object>();
40 if (!object) return reject("Authoring payload must be an object");
41 if (object->empty() && section != "sources") return applied<void>();
42 std::set<std::string> keys;
43 if (section == "sources")
44 keys = {"kind", "seed", "mesh_params", "path", "revision", "tint",
45 "roughness", "metallic", "visible", "cast_shadow", "receive_shadow"};
46 else if (section == "camera")
47 keys = {"eye", "target", "up", "fov", "near", "far", "exposure", "ambient"};
48 else if (section == "lighting")
49 keys = {"background", "direction", "color"};
50 else
51 return reject("Unknown authoring payload section");
52 for (const auto& [key, entry] : *object) {
53 if (!keys.contains(key)) return reject("Unknown authoring payload field");
54 if (key == "kind" || key == "path" || key == "revision") {
55 const auto* text = entry.getIf<std::string>();
56 if (!text || text->empty()) return reject("Source identifiers must be nonempty strings");
57 } else if (key == "seed") {
58 if (!entry.getIf<std::int64_t>()) return reject("Seed must be an integer");
59 } else if (key == "mesh_params") {
60 const auto* params = entry.getIf<Value::Object>();
61 if (!params) return reject("Mesh parameters must be an object");
62 for (const auto& [name, parameter] : *params) {
63 (void)name;
64 double numeric;
65 if (!parameter.getIf<std::string>() && !number(parameter, numeric))
66 return reject("Recipe parameters must be finite numbers or strings");
67 }
68 } else if (key == "visible" || key == "cast_shadow" || key == "receive_shadow") {
69 if (!entry.getIf<bool>()) return reject("Presentation flags must be booleans");
70 } else if (key == "eye" || key == "target" || key == "up" || key == "ambient" || key == "tint" ||
71 key == "direction" || key == "background" || key == "color") {
72 if (!vector(&entry, 3)) return reject("Vectors require three finite numbers");
73 } else {
74 double numeric;
75 if (!number(entry, numeric)) return reject("Scalar must be finite");
76 if ((key == "roughness" || key == "metallic") && (numeric < 0 || numeric > 1))
77 return reject("Material scalars must be in [0,1]");
78 if (key == "fov" && (numeric <= 0 || numeric >= 179)) return reject("Vertical FOV must be in (0,179)");
79 if ((key == "near" || key == "far") && numeric <= 0) return reject("Clip distances must be positive");
80 }
81 }
82 if (section == "sources") {
83 const auto* kind = field(value, "kind");
84 if (!kind) return reject("Source kind is required");
85 if (*kind->getIf<std::string>() == "asset" && (!field(value, "path") || !field(value, "revision")))
86 return reject("Imported sources require a path and immutable revision");
87 } else if (section == "camera") {
88 for (const auto* key : {"eye", "target", "up", "fov", "near", "far", "exposure", "ambient"})
89 if (!field(value, key)) return reject("Camera payload must contain all camera fields");
90 double nearClip, farClip;
91 if (!number(*field(value, "near"), nearClip) || !number(*field(value, "far"), farClip) || nearClip >= farClip)
92 return reject("Far clip must exceed near clip");
93 const auto components = [&](const char* key) {
94 const auto& a = *field(value, key)->getIf<Value::Array>();
95 std::array<double, 3> out{};
96 for (std::size_t i = 0; i < 3; ++i) number(a[i], out[i]);
97 return out;
98 };
99 const auto eye = components("eye"), target = components("target"), up = components("up");
100 const double x = target[0] - eye[0], y = target[1] - eye[1], z = target[2] - eye[2];
101 const double cx = y * up[2] - z * up[1], cy = z * up[0] - x * up[2], cz = x * up[1] - y * up[0];
102 if (cx * cx + cy * cy + cz * cz < 1e-12) return reject("Camera basis is degenerate");
103 } else {
104 for (const auto* key : {"background", "direction", "color"})
105 if (!field(value, key)) return reject("Lighting requires background, direction and color");
106 double lengthSquared = 0;
107 for (const auto& component : *field(value, "direction")->getIf<Value::Array>()) {
108 double numeric;
109 number(component, numeric);
110 lengthSquared += numeric * numeric;
111 }
112 if (lengthSquared < 1e-12) return reject("Light direction is degenerate");
113 }
114 return applied<void>();
115}
116} // namespace
118 : SceneTargetBase(std::move(id), "scene-authoring") {}
120 return EditorValue::Object{{"schemaId", "eve.scene.authoring"},
121 {"schemaVersion", 4},
122 {"relations", relations_},
123 {"hierarchy", SceneTargetBase::snapshotValue()},
124 {"sources", sources_},
125 {"camera", camera_},
126 {"lighting", lighting_}};
127}
129 const auto reject = [](const char* text) {
130 return editing::failed<DomainOperation>(editing::Status::Rejected, editing::RuleId("scene.authoring.restore"),
131 text);
132 };
133 const auto* root = snapshot.getIf<EditorValue::Object>();
134 if (!root) return reject("Authoring snapshot must be an object");
135 for (const auto* key : {"schemaId", "schemaVersion", "hierarchy", "sources", "camera", "lighting"})
136 if (!root->contains(key)) return reject("Missing authoring field");
137 const auto* schema = root->at("schemaId").getIf<std::string>();
138 const auto* version = root->at("schemaVersion").getIf<std::int64_t>();
139 const auto* sources = root->at("sources").getIf<EditorValue::Object>();
140 if (!schema || *schema != "eve.scene.authoring" || !version || (*version != 1 && *version != 2 && *version != 3 && *version != 4) ||
141 !sources || root->size() != (*version == 1 ? 6u : 7u) || (*version >= 2 && !root->contains("relations")))
142 return reject("Unsupported authoring schema");
143 SceneDocumentTarget hierarchy("validate");
144 auto restored = hierarchy.makeRestore(root->at("hierarchy"));
145 if (!restored.ok()) return Result<DomainOperation>::failure(restored.status());
146 auto applied = hierarchy.applyDomainOperation(restored.value());
147 if (!applied.ok()) return Result<DomainOperation>::failure(applied.status());
148 for (const auto& [id, source] : *sources) {
149 if (id.empty()) return reject("Source id must be nonempty");
150 auto valid = validate("sources", source);
151 if (!valid.ok()) return Result<DomainOperation>::failure(valid.status());
152 }
153 for (const auto* key : {"camera", "lighting"}) {
154 auto valid = validate(key, root->at(key));
155 if (!valid.ok()) return Result<DomainOperation>::failure(valid.status());
156 }
157 auto canonical = snapshot;
158 auto& fields = *canonical.getIf<EditorValue::Object>();
159 if (*version == 1) {
160 fields["schemaVersion"] = 4;
161 fields["relations"] = EditorValue::Array{};
162 }
163 fields["schemaVersion"] = 4;
164 if (*version < 3 && fields.at("relations").getIf<EditorValue::Array>())
165 for (const auto& relation : *fields.at("relations").getIf<EditorValue::Array>()) {
166 const auto* item = relation.getIf<EditorValue::Object>();
167 if (item && item->contains("region")) return reject("Region relations require authoring schema v3");
168 }
169 if (*version < 4 && fields.at("relations").getIf<EditorValue::Array>())
170 for (const auto& relation : *fields.at("relations").getIf<EditorValue::Array>()) {
171 const auto* item = relation.getIf<EditorValue::Object>();
172 if (item && item->contains("type") && item->at("type") == EditorValue("projected_overlap"))
173 return reject("Projected overlap requires authoring schema v4");
174 }
175 auto relations = parseSceneRelations(fields.at("relations"), hierarchy);
176 if (!relations.ok()) return Result<DomainOperation>::failure(relations.status());
178 operation.type = operation.inverseType = "scene.authoring.restore.v1";
179 operation.target = targetId();
180 operation.payload = std::move(canonical);
181 operation.inverse = snapshotValue();
182 operation.hasInverse = true;
183 return editing::applied<DomainOperation>(std::move(operation));
184}
185Result<DomainOperation> SceneAuthoringDocumentTarget::makePayload(const std::string& section, const std::string& key,
186 const EditorValue& payload) const {
187 if (section != "relations") {
188 auto valid = validate(section, payload);
189 if (!valid.ok()) return Result<DomainOperation>::failure(valid.status());
190 }
191 if (section == "sources" && key.empty())
192 return editing::failed<DomainOperation>(editing::Status::Rejected, editing::RuleId("scene.authoring.source-id"),
193 "Source requires object identity");
194 auto candidate = snapshotValue();
195 auto& values = *candidate.getIf<EditorValue::Object>();
196 if (section == "sources")
197 (*values.at(section).getIf<EditorValue::Object>())[key] = payload;
198 else
199 values[section] = payload;
200 return makeRestore(candidate);
201}
203 if (operation.type != "scene.authoring.restore.v1") return SceneTargetBase::applyDomainOperation(operation);
204 if (operation.target != targetId())
205 return editing::failed<void>(editing::Status::Rejected, editing::RuleId("scene.authoring.target"),
206 "Authoring target mismatch");
207 auto valid = makeRestore(operation.payload);
208 if (!valid.ok()) return Result<void>::failure(valid.status());
209 const auto& values = *valid.value().payload.getIf<EditorValue::Object>();
210 // Prepare all owning copies before changing the hierarchy.
211 auto relations = *values.at("relations").getIf<EditorValue::Array>();
212 auto sources = *values.at("sources").getIf<EditorValue::Object>();
213 auto camera = values.at("camera"), lighting = values.at("lighting");
214 SceneDocumentTarget hierarchy("candidate");
215 auto restore = hierarchy.makeRestore(values.at("hierarchy"));
216 if (!restore.ok()) return Result<void>::failure(restore.status());
217 auto loaded = hierarchy.applyDomainOperation(restore.value());
218 if (!loaded.ok()) return loaded;
219 auto currentRestore = SceneTargetBase::makeRestore(values.at("hierarchy"));
220 if (!currentRestore.ok()) return Result<void>::failure(currentRestore.status());
221 // Base planning uses virtual snapshotValue for the inverse; this operation is only applied,
222 // never retained. The complete authoring operation above is the history entry.
223 auto changed = SceneTargetBase::applyDomainOperation(currentRestore.value());
224 if (!changed.ok()) return changed;
225 relations_ = std::move(relations);
226 sources_ = std::move(sources);
227 camera_ = std::move(camera);
228 lighting_ = std::move(lighting);
229 return editing::applied<void>();
230}
231std::unique_ptr<IDomainOperationTarget> SceneAuthoringDocumentTarget::cloneDomainState() const {
232 return std::make_unique<SceneAuthoringDocumentTarget>(*this);
233}
234Result<void> SceneAuthoringDocumentTarget::commitDomainState(std::unique_ptr<IDomainOperationTarget> candidate) {
235 auto* document = dynamic_cast<SceneAuthoringDocumentTarget*>(candidate.get());
236 if (!document || document->targetId() != targetId())
237 return editing::failed<void>(editing::Status::Rejected, editing::RuleId("scene.authoring.candidate"),
238 "Invalid authoring candidate");
239 auto relations = std::move(document->relations_);
240 auto sources = std::move(document->sources_);
241 auto camera = std::move(document->camera_), lighting = std::move(document->lighting_);
242 auto committed = SceneTargetBase::commitDomainState(std::move(candidate));
243 if (!committed.ok()) return committed;
244 relations_ = std::move(relations);
245 sources_ = std::move(sources);
246 camera_ = std::move(camera);
247 lighting_ = std::move(lighting);
248 return editing::applied<void>();
249}
251 auto deletion = SceneTargetBase::makeDelete(id);
252 if (!deletion.ok()) return deletion;
253 SceneDocumentTarget hierarchy("delete-candidate");
254 auto restore = hierarchy.makeRestore(SceneTargetBase::snapshotValue());
255 if (!restore.ok()) return Result<DomainOperation>::failure(restore.status());
256 auto loaded = hierarchy.applyDomainOperation(restore.value());
257 if (!loaded.ok()) return Result<DomainOperation>::failure(loaded.status());
258 auto remove = hierarchy.makeDelete(id);
259 if (!remove.ok()) return Result<DomainOperation>::failure(remove.status());
260 auto removed = hierarchy.applyDomainOperation(remove.value());
261 if (!removed.ok()) return Result<DomainOperation>::failure(removed.status());
262 auto snapshot = snapshotValue();
263 auto& root = *snapshot.getIf<EditorValue::Object>();
264 root["hierarchy"] = hierarchy.snapshotValue();
265 EditorValue::Array retained;
266 for (const auto& relation : relations_) {
267 const auto& entry = *relation.getIf<EditorValue::Object>();
268 if (*entry.at("subject").getIf<std::string>() != id.value() &&
269 (!entry.contains("reference") || *entry.at("reference").getIf<std::string>() != id.value()))
270 retained.push_back(relation);
271 }
272 root["relations"] = std::move(retained);
273 return makeRestore(snapshot);
274}
276 for (const std::string section : {"sources", "camera", "lighting", "relations"}) {
278 descriptor.id = editing::CommandId("scene.authoring." + section + ".set.v1");
279 descriptor.ownerModule = "scene_editing";
280 descriptor.displayName = "Author scene " + section;
281 descriptor.category = "Scene";
282 descriptor.automationAllowed = true;
283 auto registered = registry.registerPlannedCommand(
285 auto* target = dynamic_cast<SceneAuthoringDocumentTarget*>(&value);
286 if (!target)
287 return editing::failed<editing::CommandPlan>(editing::Status::Unsupported,
288 editing::RuleId("scene.authoring.document-required"),
289 "An authoring document target is required");
290 const auto* keyValue = field(request.payload, "object");
291 const auto* key = keyValue ? keyValue->getIf<std::string>() : nullptr;
292 const auto* payload = field(request.payload, "value");
293 const auto* fields = request.payload.getIf<EditorValue::Object>();
294 if (!fields || fields->size() != (section == "sources" ? 2u : 1u) || !payload ||
295 (section == "sources" && (!key || key->empty())))
296 return editing::failed<editing::CommandPlan>(editing::Status::Rejected,
297 editing::RuleId("scene.authoring.command-payload"),
298 "Expected value and source object identity");
299 auto operation = target->makePayload(section, key ? *key : "", *payload);
302 plan.operations.push_back(std::move(operation.value()));
303 return editing::applied<editing::CommandPlan>(std::move(plan));
304 });
305 if (!registered.ok()) return registered;
306 }
308 descriptor.id = editing::CommandId("scene.authoring.spawn.v1");
309 descriptor.ownerModule = "scene_editing";
310 descriptor.displayName = "Create authored asset instance";
311 descriptor.category = "Scene";
312 descriptor.automationAllowed = true;
313 return registry.registerPlannedCommand(
314 std::move(descriptor),
316 auto* target = dynamic_cast<SceneAuthoringDocumentTarget*>(&value);
317 const auto* idValue = field(request.payload, "object");
318 const auto* id = idValue ? idValue->getIf<std::string>() : nullptr;
319 const auto* source = field(request.payload, "source");
320 const auto* fields = request.payload.getIf<EditorValue::Object>();
321 if (!target || !id || !source || !fields)
322 return editing::failed<editing::CommandPlan>(editing::Status::Rejected,
323 editing::RuleId("scene.authoring.spawn"),
324 "Authoring target, object and source are required");
325 for (const auto& [key, entry] : *fields) {
326 (void)entry;
327 if (key != "object" && key != "source" && key != "position" && key != "rotation" && key != "scale" &&
328 key != "parent")
329 return editing::failed<editing::CommandPlan>(editing::Status::Rejected,
330 editing::RuleId("scene.authoring.spawn-field"),
331 "Unknown spawn field");
332 }
334 create.id = ObjectId(*id);
335 create.name = *id;
336 if (const auto* parent = field(request.payload, "parent")) {
337 const auto* text = parent->getIf<std::string>();
338 if (!text)
339 return editing::failed<editing::CommandPlan>(editing::Status::Rejected,
340 editing::RuleId("scene.authoring.spawn-parent"),
341 "Parent must be an object id");
342 create.parent = ObjectId(*text);
343 }
344 const auto assign = [&](const char* key, double& x, double& y, double& z) {
345 const auto* entry = field(request.payload, key);
346 if (!entry) return true;
347 if (!vector(entry, 3)) return false;
348 const auto& values = *entry->getIf<Value::Array>();
349 return number(values[0], x) && number(values[1], y) && number(values[2], z);
350 };
351 auto& t = create.transform;
352 if (!assign("position", t.x, t.y, t.z) || !assign("rotation", t.rotationX, t.rotationY, t.rotationZ) ||
353 !assign("scale", t.scaleX, t.scaleY, t.scaleZ))
354 return editing::failed<editing::CommandPlan>(editing::Status::Rejected,
355 editing::RuleId("scene.authoring.spawn-vector"),
356 "TRS requires finite triples");
357 auto operation = target->makeCreate(create);
359 auto candidate = *target;
360 auto created = candidate.applyDomainOperation(operation.value());
361 if (!created.ok()) return Result<editing::CommandPlan>::failure(created.status());
362 auto defined = candidate.makePayload("sources", *id, *source);
363 if (!defined.ok()) return Result<editing::CommandPlan>::failure(defined.status());
364 auto applied = candidate.applyDomainOperation(defined.value());
365 if (!applied.ok()) return Result<editing::CommandPlan>::failure(applied.status());
366 auto restore = target->makeRestore(candidate.snapshotValue());
367 if (!restore.ok()) return Result<editing::CommandPlan>::failure(restore.status());
369 plan.operations.push_back(std::move(restore.value()));
370 return editing::applied<editing::CommandPlan>(std::move(plan));
371 });
372}
373} // namespace eve::scene_editing
double z
double y
double x
LogicalId target
ActionParameterOperation operation
Value::Object payload
int root
Definition AnimSmr.cpp:119
std::string descriptor
float cx
Definition CardTypes.cpp:36
float cy
Definition CardTypes.cpp:37
bool changed
bool committed
bool applied
SQObjectPtr key
Definition ECS.cpp:155
std::string name
Definition ECS.cpp:154
std::vector< std::string > fields
Definition ECS.cpp:42
const GltfImportRequest & request
float camera[2]
float v
HexVec3 up
const ColourScope * parent
std::string relation
std::string id
Snapshot snapshot
std::vector< RecipeParam > params
bool valid
MeleePoint3 a
Definition MeleeHit.cpp:40
std::vector< std::pair< std::uint64_t, OceanBoatReceipt > > sources
std::unordered_set< std::string > loaded
Definition Plugins.cpp:24
std::set< std::string > values
const eve::script::BindingContractRegistry & registry
Object::Ptr value
float t
std::string parameter
glm::vec3 eye
Lighting3DPack lighting
double number
int created
int removed
std::string text
ScriptStructure out
std::string_view source
std::string kind
int count
Json object
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
UUID-backed identifier adapter for legacy textual boundaries.
Definition Identity.h:313
IEditableTarget public API.
Lower-layer registration boundary implemented by an editor or runtime editing host.
Deterministic owning value tree shared by authoring hosts.
std::vector< Value > Array
std::map< std::string, Value > Object
const T * getIf() const
Return an immediately borrowed typed value.
Declarative authoring composition: hierarchy plus source and presentation payloads....
Result< DomainOperation > makeRestore(const EditorValue &snapshot) const override
Validate a complete candidate before producing a reversible replacement.
Result< void > applyDomainOperation(const DomainOperation &operation) override
Apply an operation on this owner thread; failures preserve state.
std::unique_ptr< IDomainOperationTarget > cloneDomainState() const override
Clone an isolated transaction candidate, owning all values. @cost Linear copy per transaction.
Result< DomainOperation > makePayload(const std::string &section, const std::string &key, const EditorValue &payload) const
Plan one source/camera/lighting payload change; missing sources may be defined.
Result< DomainOperation > makeDelete(const editing::ObjectId &id) const override
Delete a leaf and its relations as one reversible document transaction. @cost Linear document copy pe...
Result< void > commitDomainState(std::unique_ptr< IDomainOperationTarget > candidate) override
Atomically publish a validated candidate of the same target identity.
EditorValue snapshotValue() const override
Copy all authored values into an owning versioned snapshot. @cost Linear copy per save/edit inspectio...
SceneAuthoringDocumentTarget(std::string id)
Create an empty authoring document with a stable target identity.
Authoring scene-document backend exposing the standard scene capabilities.
Shared in-memory scene target implementation for document/runtime adapters.
Definition SceneTarget.h:86
Result< DomainOperation > makeDelete(const ObjectId &id) const override
Make delete.
Result< void > applyDomainOperation(const DomainOperation &operation) override
Applies domain operation.
virtual Result< DomainOperation > makeRestore(const EditorValue &snapshot) const
Plan atomic replacement of hierarchy/TRS from a versioned snapshot.
TargetId targetId() const override
Target id.
Definition SceneTarget.h:94
EditorValue snapshotValue() const override
Capture deterministic scene content for document persistence.
Result< void > commitDomainState(std::unique_ptr< IDomainOperationTarget > candidate) override
Commits domain state.
const Value * field(const Value &value, const char *key)
Borrow an optional object field.
float lengthSquared(Vec3 value)
Length squared.
StrongId< ObjectIdTag > ObjectId
Definition EditingIds.h:65
StrongId< RuleIdTag > RuleId
Definition EditingIds.h:60
StrongId< CommandIdTag > CommandId
Definition EditingIds.h:58
void keys(const Value &value, std::initializer_list< const char * > names)
editing::Result< std::vector< SceneRelation > > parseSceneRelations(const editing::Value &value, const ISceneHierarchyEditTarget &hierarchy)
Strictly decode physical and visual relations and validate all referenced objects.
Result< void > registerAuthoringDocumentCommands(editing::IEditingCommandRegistry &registry)
Register authored source creation and camera/lighting payload commands.
void validate(const RuntimeTensor &v)
Validate.
CommandPlan public API.
CommandRequest public API.
DomainOperation public API.
Domain-owned metadata for one planned editing command.
Request used to create a scene object in either backend.
Definition SceneTarget.h:27