载入中...
搜索中...
未找到
MaterialEditorModule.cpp
浏览该文件的文档.
2
3#include "common/Capability.h"
12
13#include <simplesquirrel/simplesquirrel.hpp>
14
15#include <cstdint>
16#include <limits>
17#include <stdexcept>
18#include <string_view>
19#include <typeindex>
20#include <vector>
21
22namespace eve::material_editor {
23namespace {
24
25const std::int64_t* integerField(const editor::EditorValue::Object& request, const char* key) {
26 const auto found = request.find(key);
27 return found == request.end() ? nullptr : found->second.getIf<std::int64_t>();
28}
29
30class AutomationMaterialAssetResolver final : public material_editing::IMaterialRuntimeAssetResolver {
31public:
32 editor::Result<graphics::Texture*> resolveTexture(const std::string& asset) const override {
33 return unresolved<graphics::Texture>(asset);
34 }
35 editor::Result<graphics::Shader*> resolveShader(const std::string& asset) const override {
36 return unresolved<graphics::Shader>(asset);
37 }
38
39private:
40 template <class T>
41 static editor::Result<T*> unresolved(const std::string& asset) {
42 return eve::editing::failed<T*>(
43 editor::EditorStatus::Unsupported, editor::RuleId("editor.automation.material-asset"),
44 "Automation binding cannot resolve material asset: " + asset);
45 }
46};
47
48graphics::Renderable3D* findRenderable(std::uint32_t id, std::uint32_t generation) {
49 ecs::EntityHandle handle{ecs::current(), std::type_index(typeid(graphics::Renderable3D)), id, generation};
50 return dynamic_cast<graphics::Renderable3D*>(ecs::try_get(handle));
51}
52
53editor::EditorValue runtimeMaterialSnapshot(const graphics::Renderable3D::MeshRenderer& renderer) {
54 material_editing::MaterialDocumentTarget defaults("material.runtime.seed");
55 editor::EditorValue snapshot = defaults.snapshotValue();
57 auto* properties = root ? root->at("properties").getIf<editor::EditorValue::Object>() : nullptr;
58 (*properties)["shading.tint"] = editor::EditorValue::Array{double(renderer.r), double(renderer.g),
59 double(renderer.b), double(renderer.a)};
60 (*properties)["shading.metallic"] = double(renderer.metallic);
61 (*properties)["shading.roughness"] = double(renderer.roughness);
62 (*properties)["parallax.scale"] = double(renderer.parallaxScale);
63 (*properties)["lighting.receive"] = renderer.receiveLight;
64 (*properties)["shadow.cast"] = renderer.castShadow;
65 (*properties)["shadow.receive"] = renderer.receiveShadow;
66 return snapshot;
67}
68
69} // namespace
70
72public:
73 std::vector<std::string_view> types() const override { return {"material", "material-renderable3d"}; }
74
76 const editor::TargetId& target, std::string_view type,
77 const editor::EditorValue::Object& request) override {
79 if (type == "material") {
80 owned.target = std::make_unique<material_editing::MaterialDocumentTarget>(target.value());
81 return eve::editing::applied<editor::AutomationOwnedTarget>(std::move(owned));
82 }
83 const auto* id = integerField(request, "entityId");
84 const auto* generation = integerField(request, "generation");
85 constexpr auto maxId = static_cast<std::int64_t>(std::numeric_limits<std::uint32_t>::max());
86 if (!id || !generation || *id < 0 || *generation < 0 || *id > maxId || *generation > maxId)
87 return eve::editing::failed<editor::AutomationOwnedTarget>(
88 editor::EditorStatus::Rejected, editor::RuleId("editor.automation.material-handle"),
89 "Live material target requires uint32 entityId and generation");
90 auto* renderable = findRenderable(static_cast<std::uint32_t>(*id), static_cast<std::uint32_t>(*generation));
91 if (!renderable)
92 return eve::editing::failed<editor::AutomationOwnedTarget>(
93 editor::EditorStatus::Conflict, editor::RuleId("editor.automation.material-stale"),
94 "Renderable3D handle is missing or stale");
95 auto renderer = renderable->meshRenderer();
96 if (renderer->material || renderer->texture || renderer->normalTexture || renderer->heightTexture ||
97 renderer->shader)
98 return eve::editing::failed<editor::AutomationOwnedTarget>(
99 editor::EditorStatus::Unsupported, editor::RuleId("editor.automation.material-assets"),
100 "Live material binding currently supports field-backed materials without asset overrides");
101 static const AutomationMaterialAssetResolver assets;
102 auto sink = std::make_shared<material_editing::Renderable3DMaterialRuntimeSink>(renderable, &assets);
103 auto publishing = std::make_unique<material_editing::MaterialPublishingTarget>(target.value(), sink.get());
104 auto loaded = publishing->authoringTarget().loadSnapshot(runtimeMaterialSnapshot(*renderer));
105 if (!loaded.ok()) {
107 }
108 owned.support = std::move(sink);
109 owned.target = std::move(publishing);
110 return eve::editing::applied<editor::AutomationOwnedTarget>(std::move(owned));
111 }
112};
113
115
117 auto* registry = eve::cap::query<editing::IEditingCommandRegistry>();
119 throw std::runtime_error("Failed to register material editing commands");
120 eve::cap::addListener<editor::IEditorAutomationTargetFactory>(factory_.get());
121}
122
124 eve::cap::removeListener<editor::IEditorAutomationTargetFactory>(factory_.get());
125 if (auto* registry = eve::cap::query<editing::IEditingCommandRegistry>())
126 registry->unregisterOwner("material_editing").ignore("material editor adapter shutdown");
127}
128
129namespace {
130class ScriptMaterialEditor {
131public:
132 explicit ScriptMaterialEditor(std::string id) : editor_(std::move(id)) {}
133 MaterialEditor& editor() { return editor_; }
134
135private:
136 MaterialEditor editor_;
137};
138} // namespace
139
140void MaterialEditorModule::expose(ssq::Table& table) {
141 auto module = table.addClass(name, MaterialEditorModule::create, false);
142 const editor::ScriptBind bind{table.getHandle(), "editor.material.squirrel"};
143 auto cls = editor::addScriptClass<ScriptMaterialEditor>(table, "MaterialEditor");
144 editor::registerEditorOwnedCreate<ScriptMaterialEditor, MaterialEditorModule>(module, bind,
145 "Material id is required");
146 editor::registerEditorWorkspace<ScriptMaterialEditor>(cls, bind, "Material editor and workspace are required");
147 editor::registerEditorHistory<ScriptMaterialEditor>(cls, bind, "Material editor is required");
148 cls.addFunc("set", [bind](ScriptMaterialEditor* self, const std::string& path, ssq::Object value) {
149 if (!self) return bind.fail(DiagnosticCode::InvalidArgument, "Material editor is required");
150 auto converted = script::valueFromSquirrel(value);
151 if (!converted.ok()) return editor::project(bind.vm(), converted, Value{});
152 return editor::project(bind.vm(), self->editor().setProperty(path, editing::toEditingValue(converted.value())));
153 });
154 cls.addFunc("patch", [bind](ScriptMaterialEditor* self, ssq::Object properties) {
155 if (!self) return bind.fail(DiagnosticCode::InvalidArgument, "Material editor is required");
156 auto converted = script::valueFromSquirrel(properties);
157 if (!converted.ok()) return editor::project(bind.vm(), converted, Value{});
158 auto patch = editing::toEditingValue(converted.value());
159 auto* object = patch.getIf<editing::Value::Object>();
160 if (!object) return bind.fail(DiagnosticCode::InvalidArgument, "Patch requires a path-to-value table");
161 return editor::project(bind.vm(), self->editor().setProperties(*object));
162 });
163 cls.addFunc("read", [bind](ScriptMaterialEditor* self, const std::string& path) {
164 if (!self) return bind.fail(DiagnosticCode::InvalidArgument, "Material editor is required");
165 auto result = self->editor().read(path);
166 return editor::project(bind.vm(), result, result.ok() ? editing::toPresentationValue(result.value()) : Value{});
167 });
168 cls.addFunc("schema", [bind](ScriptMaterialEditor* self) {
169 if (!self) return bind.fail(DiagnosticCode::InvalidArgument, "Material editor is required");
171 editing::toPresentationValue(self->editor().schema()));
172 });
173 cls.addFunc("snapshot", [bind](ScriptMaterialEditor* self) {
174 if (!self) return bind.fail(DiagnosticCode::InvalidArgument, "Material editor is required");
176 editing::toPresentationValue(self->editor().snapshot()));
177 });
178 cls.addFunc("restore", [bind](ScriptMaterialEditor* self, ssq::Object snapshot) {
179 if (!self) return bind.fail(DiagnosticCode::InvalidArgument, "Material editor is required");
180 auto converted = script::valueFromSquirrel(snapshot);
181 if (!converted.ok()) return editor::project(bind.vm(), converted, Value{});
182 return editor::project(bind.vm(), self->editor().restore(editing::toEditingValue(converted.value())));
183 });
184 cls.addFunc("toJson", [bind](ScriptMaterialEditor* self) {
185 if (!self) return bind.fail(DiagnosticCode::InvalidArgument, "Material editor is required");
187 Value(editor::editorValueToJson(self->editor().snapshot())));
188 });
189 cls.addFunc("fromJson", [bind](ScriptMaterialEditor* self, const std::string& json) {
190 if (!self) return bind.fail(DiagnosticCode::InvalidArgument, "Material editor is required");
191 auto parsed = editor::editorValueFromJson(json);
192 if (!parsed.ok()) return editor::project(bind.vm(), parsed, Value{});
193 return editor::project(bind.vm(), self->editor().restore(parsed.value()));
194 });
195}
196void MaterialEditorModule::expose(ssq::Class&) {}
197
198} // namespace eve::material_editor
LogicalId target
int root
Definition AnimSmr.cpp:119
ActiveSource owned
HSQOBJECT cls
Definition ECS.cpp:39
std::vector< Value > defaults
Definition ECS.cpp:49
SQObjectPtr key
Definition ECS.cpp:155
Generation generation
Definition ECS.cpp:40
const GltfImportRequest & request
std::map< std::string, PropertyRule > properties
std::string id
Poco::JSON::Object::Ptr result
Snapshot snapshot
#define Module_IMPL(ModuleName, newExpr)
Definition Module.h:27
std::shared_ptr< OceanRenderer > renderer
std::string path
Definition PlayHost.cpp:111
std::unordered_set< std::string > loaded
Definition Plugins.cpp:24
PrimitiveHandle handle
const eve::script::BindingContractRegistry & registry
Object::Ptr value
bool found
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
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Definition Status.cpp:19
UUID-backed identifier adapter for legacy textual boundaries.
Definition Identity.h:313
std::vector< Value > Array
std::map< std::string, Value > Object
Multi-provider extension point for domain-specific automation target creation.
editor::Result< editor::AutomationOwnedTarget > create(const editor::TargetId &target, std::string_view type, const editor::EditorValue::Object &request) override
Create a domain target from an automation request. @ownership Success transfers the target and any su...
std::vector< std::string_view > types() const override
Stable target type names this factory accepts.
Composition adapter that contributes material editing commands and automation targets.
~MaterialEditorModule() override
Material editor module.
std::variant< std::monostate, std::int64_t, double, std::string, bool > Value
Definition Database.h:27
eve::Value toPresentationValue(const Value &value)
To presentation value.
Value toEditingValue(const eve::Value &value)
To editing value.
eve::editing::Value EditorValue
Compatibility alias for the UI-independent authoring value tree.
Definition EditorValue.h:8
eve::editing::RuleId RuleId
Definition EditorIds.h:32
ssq::Table project(HSQUIRRELVM vm, const eve::Result< void > &result)
Project a completed editing result that has no payload.
editing::Result< void > registerEditingCommands(editing::IEditingCommandRegistry &registry)
Register Material-owned property commands with a generic editing host.
std::unordered_map< std::string, SkillDefinition > & table()
Definition Skill.cpp:73
ssq::Table projectStatusResult(HSQUIRRELVM vm, const Status &status)
Project a checked native status that carries no payload.
Result< Value > valueFromSquirrel(HSQUIRRELVM vm, SQInteger index, const SquirrelValueOptions &options)
Convert one Squirrel value into the canonical owning Value tree.
Target plus optional borrowed-dependency owner returned by an automation factory.
std::unique_ptr< IEditableTarget > target