载入中...
搜索中...
未找到
EditorMaterialPreview.cpp
浏览该文件的文档.
2#include <cmath>
3#include <iterator>
4#include <set>
5#include <utility>
7
8// EditorMaterialPreview.cpp
9namespace eve::editor {
10namespace {
11
12std::vector<EditorDiagnostic> validateSettings(const MaterialPreviewSettings& settings) {
13 std::vector<EditorDiagnostic> diagnostics;
14 const auto error = [&](const char* rule, std::string message) {
16 DiagnosticSeverity::Error, std::move(message)));
17 };
18 static const std::set<std::string> geometries{"sphere", "cube", "plane", "custom"};
19 if (!geometries.contains(settings.geometry))
20 error("editor.material.preview-geometry", "Material preview geometry is unsupported: " + settings.geometry);
21 if (settings.geometry == "custom" && settings.customMeshAsset.empty())
22 error("editor.material.preview-mesh-required", "Custom material preview requires a mesh asset");
23 if (settings.width < 16 || settings.height < 16 || settings.width > 4096 || settings.height > 4096)
24 error("editor.material.preview-resolution", "Material preview resolution must be between 16 and 4096");
25 if (settings.distance <= 0.0)
26 error("editor.material.preview-distance", "Material preview camera distance must be positive");
27 return diagnostics;
28}
29
30} // namespace
31
34 if (document.empty())
35 return eve::editing::failed<TaskId>(EditorStatus::Rejected, RuleId("editor.material.preview-document"),
36 "Material preview document id is required");
37 auto diagnostics = material.validate();
38 auto settingsDiagnostics = validateSettings(settings);
39 diagnostics.insert(diagnostics.end(), std::make_move_iterator(settingsDiagnostics.begin()),
40 std::make_move_iterator(settingsDiagnostics.end()));
41 for (const EditorDiagnostic& diagnostic : diagnostics)
42 if (diagnostic.severity() == DiagnosticSeverity::Error)
43 return Result<TaskId>::failure(Status(EditorStatus::Rejected, std::move(diagnostics)));
44 const TaskId task("material-preview-" + std::to_string(++sequence_));
46 request.sceneId = StableId(task.value() + ":isolated-scene");
47 request.document = document;
48 request.documentRevision = material.revision();
49 request.material = material.snapshotValue();
50 request.settings = std::move(settings);
52 rendered.diagnostics.insert(rendered.diagnostics.begin(), diagnostics.begin(), diagnostics.end());
53 if (rendered.status == EditorStatus::Applied && rendered.artifact.empty()) {
54 rendered.status = EditorStatus::Failed;
55 rendered.diagnostics.push_back(
56 eve::editing::ruleDiagnostic(DiagnosticCode::Failed, RuleId("editor.material.preview-artifact-required"),
57 DiagnosticSeverity::Error, "Preview renderer succeeded without an artifact"));
58 }
59 tasks_.emplace(task, Task{document, request.documentRevision, std::move(rendered)});
60 return eve::editing::applied<TaskId>(task);
61}
62
64 const auto found = tasks_.find(task);
65 if (found == tasks_.end())
66 return eve::editing::failed<MaterialPreviewRenderResult>(EditorStatus::NotFound,
67 RuleId("editor.material.preview-task-not-found"),
68 "Material preview task was not found");
69 return eve::editing::applied<MaterialPreviewRenderResult>(found->second.result);
70}
71
72Result<void> MaterialPreviewService::publish(const DocumentId& document, Revision currentRevision, const TaskId& task) {
73 const auto found = tasks_.find(task);
74 if (found == tasks_.end())
75 return eve::editing::failed<void>(EditorStatus::NotFound, RuleId("editor.material.preview-task-not-found"),
76 "Material preview task was not found");
77 if (found->second.document != document)
78 return eve::editing::failed<void>(EditorStatus::Rejected, RuleId("editor.material.preview-document-mismatch"),
79 "Material preview belongs to another document");
80 if (found->second.revision != currentRevision)
81 return eve::editing::failed<void>(EditorStatus::Conflict, RuleId("editor.material.preview-stale"),
82 "Material changed after the preview was rendered");
83 if (found->second.result.status != EditorStatus::Applied || found->second.result.artifact.empty()) {
84 const EditorStatus status =
85 found->second.result.status == EditorStatus::Applied ? EditorStatus::Failed : found->second.result.status;
86 return Result<void>::failure(Status(status, found->second.result.diagnostics));
87 }
88 published_[document] = found->second.result.artifact;
89 return eve::editing::applied<void>();
90}
91
92std::string MaterialPreviewService::publishedArtifact(const DocumentId& document) const {
93 const auto found = published_.find(document);
94 return found == published_.end() ? std::string{} : found->second;
95}
96
97} // namespace eve::editor
98
99// EditorMaterialStudio.cpp
100namespace eve::editor {
101namespace {
102
103Result<void> noStudioChange() { return eve::editing::noOp(); }
104
105} // namespace
106
108 IEditorTransactionBackend& transactions,
110 : document_(std::move(document)),
111 target_(target),
112 transactions_(transactions),
113 previews_(previews),
114 renderer_(renderer) {}
115
117 settings_ = std::move(settings);
118 previewDirty_ = true;
119 return eve::editing::applied<void>();
120}
121
123 if (activeProperty_ || transactions_.active())
124 return eve::editing::failed<void>(EditorStatus::Conflict, RuleId("editor.material.studio-interaction-active"),
125 "Finish or cancel the active material edit first");
126 const auto selection = selectionFor(target_.authoringTarget());
127 const auto descriptor = target_.authoringTarget().schema(selection).find(path);
128 if (!descriptor)
129 return eve::editing::failed<void>(EditorStatus::NotFound, RuleId("editor.material.studio-property"),
130 "Material property is not present in the schema: " + path.value());
131 draft_ = std::make_unique<MaterialDocumentTarget>(target_.authoringTarget());
132 activeProperty_ = std::move(path);
133 finalValue_.reset();
134 diagnostics_.clear();
135 return eve::editing::applied<void>();
136}
137
139 if (!draft_ || !activeProperty_)
140 return eve::editing::failed<void>(EditorStatus::Rejected, RuleId("editor.material.studio-no-interaction"),
141 "Begin a material interaction before updating it");
142 auto operation = draft_->makeSet(selectionFor(*draft_), *activeProperty_, value, PropertySetMode::Absolute);
143 if (!operation.ok()) {
144 diagnostics_ = operation.diagnostics();
145 return Result<void>::failure(operation.status());
146 }
147 auto applied = draft_->applyDomainOperation(operation.value());
148 if (!applied.ok()) {
149 diagnostics_ = applied.diagnostics();
150 return applied;
151 }
152 finalValue_ = std::move(value);
153 diagnostics_ = draft_->validate();
154 previewDirty_ = true;
155 return eve::editing::applied<void>();
156}
157
159 if (!draft_ || !activeProperty_ || !finalValue_)
160 return eve::editing::failed<TransactionReceipt>(EditorStatus::Rejected,
161 RuleId("editor.material.studio-no-final-value"),
162 "The material interaction has no value to commit");
163 auto operation = target_.authoringTarget().makeSet(selectionFor(target_.authoringTarget()), *activeProperty_,
164 *finalValue_, PropertySetMode::Absolute);
165 if (!operation.ok()) return Result<TransactionReceipt>::failure(operation.status());
166 TransactionSpec specification;
167 specification.id = TransactionId("material-studio-" + std::to_string(++transactionSequence_));
168 specification.label = "Edit material " + activeProperty_->value();
169 specification.target = TargetId(target_.targetId());
170 specification.baseRevision = target_.revision();
171 specification.mergeKey = operation.value().mergeKey;
172 auto begun = transactions_.begin(std::move(specification));
173 if (!begun.ok())
174 return eve::editing::failed<TransactionReceipt>(begun.code(), RuleId("editor.material.studio-begin"),
175 "Could not begin the material transaction");
176 auto appended = transactions_.append(std::move(operation).takeValue());
177 if (!appended.ok()) {
178 [[maybe_unused]] auto discarded = transactions_.discard();
179 return eve::editing::failed<TransactionReceipt>(appended.code(), RuleId("editor.material.studio-append"),
180 "Could not append the material edit");
181 }
182 auto previewed = transactions_.preview();
183 if (!previewed.ok()) {
184 [[maybe_unused]] auto discarded = transactions_.discard();
185 return eve::editing::failed<TransactionReceipt>(previewed.code(), RuleId("editor.material.studio-preflight"),
186 "Material transaction preflight failed");
187 }
188 auto committed = transactions_.commit();
189 if (!committed.ok()) return committed;
190 clearInteraction();
191 previewDirty_ = true;
192 return committed;
193}
194
196 if (!draft_) return noStudioChange();
197 clearInteraction();
198 previewDirty_ = true;
199 diagnostics_ = target_.authoringTarget().validate();
200 return eve::editing::applied<void>();
201}
202
203Result<void> MaterialStudioController::tick(std::uint64_t monotonicMilliseconds) {
204 if (!previewDirty_) return noStudioChange();
205 if (hasPreviewTimestamp_ && monotonicMilliseconds < lastPreviewMilliseconds_)
206 return eve::editing::failed<void>(EditorStatus::Rejected, RuleId("editor.material.studio-time-regressed"),
207 "Material preview time must be monotonic");
208 if (hasPreviewTimestamp_ && monotonicMilliseconds - lastPreviewMilliseconds_ < previewIntervalMilliseconds_)
209 return noStudioChange();
210 auto rendered = refreshPreview();
211 if (rendered.ok()) {
212 lastPreviewMilliseconds_ = monotonicMilliseconds;
213 hasPreviewTimestamp_ = true;
214 }
215 return rendered;
216}
217
219 return renderPreview(draft_ ? *draft_ : target_.authoringTarget());
220}
221
223 if (!std::isfinite(framesPerSecond) || framesPerSecond < 1.0 || framesPerSecond > 240.0)
224 return eve::editing::failed<void>(EditorStatus::Rejected, RuleId("editor.material.studio-preview-rate"),
225 "Material preview rate must be between 1 and 240 Hz");
226 previewIntervalMilliseconds_ = static_cast<std::uint64_t>(std::ceil(1000.0 / framesPerSecond));
227 return eve::editing::applied<void>();
228}
229
232 result.interactionActive = draft_ != nullptr;
233 result.previewDirty = previewDirty_;
234 result.activeProperty = activeProperty_.value_or(PropertyPath{});
235 result.documentRevision = target_.revision();
236 result.previewRevision = previewRevision_;
237 result.previewArtifact = previewArtifact_;
238 result.diagnostics = diagnostics_;
239 return result;
240}
241
242SelectionSnapshot MaterialStudioController::selectionFor(const MaterialDocumentTarget& material) const {
243 SelectionSnapshot selection;
244 selection.channel = "asset";
245 SelectionItem item;
246 item.domain = SelectionDomain::Asset;
247 item.target = TargetId(material.targetId());
248 item.item = StableId(material.targetId().value());
249 item.type = "graphics.material";
250 selection.items.push_back(item);
251 selection.primary = item;
252 return selection;
253}
254
255Result<void> MaterialStudioController::renderPreview(const MaterialDocumentTarget& material) {
256 auto task = previews_.render(document_, material, settings_, renderer_);
257 if (!task.ok()) {
258 diagnostics_ = task.diagnostics();
259 return eve::editing::failed<void>(task.code(), RuleId("editor.material.studio-preview"),
260 "Material preview request was rejected");
261 }
262 auto result = previews_.result(task.value());
263 if (!result.ok()) {
264 diagnostics_ = result.diagnostics();
265 return eve::editing::failed<void>(result.code(), RuleId("editor.material.studio-preview-result"),
266 "Material preview result is unavailable");
267 }
268 auto published = previews_.publish(document_, material.revision(), task.value());
269 diagnostics_ = result.value().diagnostics;
270 if (!published.ok()) {
271 diagnostics_.insert(diagnostics_.end(), published.diagnostics().begin(), published.diagnostics().end());
272 return published;
273 }
274 previewArtifact_ = result.value().artifact;
275 previewRevision_ = material.revision();
276 previewDirty_ = false;
277 return eve::editing::applied<void>();
278}
279
280void MaterialStudioController::clearInteraction() {
281 draft_.reset();
282 activeProperty_.reset();
283 finalValue_.reset();
284}
285
286} // namespace eve::editor
LogicalId target
ActionParameterOperation operation
std::string descriptor
bool committed
bool applied
std::string message
const GltfImportRequest & request
wgpu::PopErrorScopeStatus status
Poco::JSON::Object::Ptr result
OceanWakeSettings settings
std::shared_ptr< OceanRenderer > renderer
std::string error
Definition Package.cpp:174
std::array< uint32_t, 16 > material
std::string path
Definition PlayHost.cpp:111
Object::Ptr value
bool found
A structured explanation of a failed, degraded, or noteworthy result.
Definition Diagnostic.h:94
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
Structured status and zero or more diagnostics for an operation.
Definition Status.h:70
UUID-backed identifier adapter for legacy textual boundaries.
Definition Identity.h:313
const std::string & value() const noexcept
Returns the exact legacy or canonical compatibility spelling.
Definition Identity.h:365
bool empty() const noexcept
True when no compatibility spelling has been assigned.
Definition Identity.h:377
Dotted property path (layout.size) compared and persisted as text.
Definition EditingIds.h:78
Deterministic owning value tree shared by authoring hosts.
Transaction boundary consumed by editor property and other UI models.
virtual Result< void > discard()=0
Discard pending work after reverting any provisional preview.
virtual Result< TransactionReceipt > commit()=0
Publish the pending transaction and retain it for undo.
virtual Result< void > append(DomainOperation operation)=0
Append a serializable operation to the pending transaction.
virtual bool active() const noexcept=0
Whether a transaction is currently pending.
virtual Result< EditorDryRunReport > preview()=0
Validate the pending transaction without publishing target state.
virtual Result< TransactionId > begin(TransactionSpec specification)=0
Begin an explicit transaction without mutating its target.
Host boundary that owns creation and teardown of an isolated preview scene.
Revision-safe material preview request and publication service.
std::string publishedArtifact(const DocumentId &document) const
Return the most recently published artifact for a document.
Result< MaterialPreviewRenderResult > result(const TaskId &task) const
Return one immutable render result.
Result< TaskId > render(const DocumentId &document, const MaterialDocumentTarget &material, MaterialPreviewSettings settings, IMaterialPreviewRenderer &renderer)
Validate and render a material snapshot in a unique isolated scene.
Result< void > publish(const DocumentId &document, Revision currentRevision, const TaskId &task)
Publish only a successful result matching the current document revision.
Result< void > beginInteraction(PropertyPath path)
Start one coalesced property gesture from the current live document revision.
Result< TransactionReceipt > commitInteraction()
Atomically publish the final draft value as one undoable transaction.
MaterialStudioController(DocumentId document, MaterialPublishingTarget &target, IEditorTransactionBackend &transactions, MaterialPreviewService &previews, IMaterialPreviewRenderer &renderer)
Material studio controller.
Result< void > setPreviewSettings(MaterialPreviewSettings settings)
Replace preview geometry, camera, resolution, and environment settings.
Result< void > tick(std::uint64_t monotonicMilliseconds)
Render a dirty preview when the injected monotonic time reaches the rate limit.
MaterialStudioState state() const
Return an owning snapshot suitable for any developer or in-game UI host.
Result< void > setPreviewRate(double framesPerSecond)
Set the maximum preview rate; valid range is 1 to 240 Hz.
Result< void > updateInteraction(EditorValue value)
Update the owned draft and mark its isolated preview dirty.
Result< void > refreshPreview()
Force an isolated preview of the current draft or live document.
Result< void > cancelInteraction()
Abandon the draft without changing the live material.
UI-neutral, serializable material authoring target.
PropertySchema schema(const SelectionSnapshot &selection) const override
Schema.
std::vector< EditorDiagnostic > validate() const
Validate cross-field authoring rules without mutating the target.
Result< DomainOperation > makeSet(const SelectionSnapshot &selection, const PropertyPath &path, const EditorValue &value, PropertySetMode mode) const override
Make set.
Candidate-first material operation target with live commit/undo publication.
std::uint64_t revision() const override
Revision.
MaterialDocumentTarget & authoringTarget()
Mutable authoring document used by property inspectors.
TargetId targetId() const override
Target id.
Diagnostic ruleDiagnostic(eve::DiagnosticCode code, RuleId rule, DiagnosticSeverity severity, std::string message)
Build an owning common diagnostic carrying an open editing rule identity.
Result< void > noOp(std::vector< Diagnostic > diagnostics={})
Construct a successful void result for an operation that made no change.
eve::editing::StableId StableId
Definition EditorIds.h:36
material_editing::MaterialDocumentTarget MaterialDocumentTarget
eve::editing::TargetId TargetId
Definition EditorIds.h:29
eve::editing::RuleId RuleId
Definition EditorIds.h:32
eve::editing::TransactionId TransactionId
Definition EditorIds.h:34
eve::editing::Revision Revision
StatusCode
Stable outcome category for an operation.
Definition Status.h:28
PropertyDescriptorLookup find(const PropertyPath &path) const
Finds find.
SelectionItem public API.
SelectionSnapshot public API.
std::vector< SelectionItem > items
std::optional< SelectionItem > primary
TransactionSpec public API.
Immutable request passed to a renderer-owned isolated preview scene.
Renderer output referenced by a stable artifact rather than GPU pointers.
std::vector< EditorDiagnostic > diagnostics
Camera, mesh and environment settings for an isolated material preview.
Observable state for a host-rendered real-time material studio.