载入中...
搜索中...
未找到
VegetationFieldGizmo.cpp
浏览该文件的文档.
2#include <algorithm>
3#include <cmath>
4#include <new>
7
8// VegetationFieldGizmo.cpp
9namespace eve::graphics_editing {
10namespace {
11
12Result<editing::GizmoSnapshot> failure(StatusCode code, DiagnosticCode diagnostic, std::string message,
13 std::string path = {}) {
15 Status(code, {Diagnostic::error(diagnostic, std::move(message), std::move(path), {},
16 "graphics_editing.vegetation_field_gizmo")}));
17}
18
19std::array<double, 4> channelColor(graphics::VegetationChannel channel, float opacity) {
20 const double alpha = std::clamp(double(opacity), 0.2, 1.0);
21 switch (channel) {
22 case graphics::VegetationChannel::Color: return {0.2, 0.85, 0.35, alpha};
23 case graphics::VegetationChannel::Extras: return {1.0, 0.55, 0.1, alpha};
24 case graphics::VegetationChannel::Motion: return {0.2, 0.65, 1.0, alpha};
25 case graphics::VegetationChannel::Vertex: return {0.75, 0.35, 1.0, alpha};
26 }
27 return {1.0, 1.0, 1.0, alpha};
28}
29
30} // namespace
31
33 const graphics::VegetationField& field,
34 std::size_t maximumElements) const {
35 if (target.empty() || maximumElements == 0 || maximumElements > 100000)
37 "Vegetation field gizmo requires a target and a bounded element budget", "request");
38 if (field.revision() != expectedRevision)
40 "Vegetation field changed before gizmo generation", "revision");
41 auto elements = field.snapshotElements();
43 if (field.revision() != expectedRevision)
45 "Vegetation field changed while gizmo generation was reading it", "revision");
46 if (elements.value().size() > maximumElements)
48 "Vegetation field exceeds the gizmo element budget", "elements");
49 try {
52 result.target = std::move(target);
53 result.targetRevision = expectedRevision;
54 result.primitives.reserve(elements.value().size());
55 for (std::size_t i = 0; i < elements.value().size(); ++i) {
56 const auto& element = elements.value()[i];
58 primitive.id = "vegetation-field-" + std::to_string(i);
59 primitive.kind = element.shape == graphics::VegetationShape::Box ? "obb" : "ellipsoid";
60 primitive.position = {element.center.x, element.center.y, element.center.z};
61 primitive.size = {element.extents.x * 2.0, element.extents.y * 2.0, element.extents.z * 2.0};
62 primitive.color = channelColor(element.channel, element.opacity);
63 primitive.yaw = element.yaw;
64 primitive.dashed = !element.mask.pixels.empty();
65 result.primitives.push_back(std::move(primitive));
66 }
68 } catch (const std::bad_alloc&) {
69 return failure(StatusCode::Failed, DiagnosticCode::Failed, "Vegetation field gizmo allocation failed");
70 }
71}
72
73} // namespace eve::graphics_editing
74
75// VegetationFieldTarget.cpp
76namespace eve::graphics_editing {
77namespace {
78editing::Value vec3(glm::vec3 value) { return editing::Value::Array{value.x, value.y, value.z}; }
79
80bool readVec3(const editing::Value& value, glm::vec3& output) {
81 const auto* array = value.getIf<editing::Value::Array>();
82 if (!array || array->size() != 3) return false;
83 for (std::size_t index = 0; index < 3; ++index) {
84 const auto* number = (*array)[index].getIf<double>();
85 if (!number || !std::isfinite(*number)) return false;
86 output[static_cast<int>(index)] = static_cast<float>(*number);
87 }
88 return true;
89}
90
91const editing::Value* field(const editing::Value& value, const char* key) {
92 const auto* object = value.getIf<editing::Value::Object>();
93 if (!object) return nullptr;
94 const auto found = object->find(key);
95 return found == object->end() ? nullptr : &found->second;
96}
97
98editing::Value transformValue(const editing::StableId& id, const graphics::VegetationElement& element) {
100 {"id", id.value()}, {"center", vec3(element.center)}, {"extents", vec3(element.extents)}, {"yaw", element.yaw}};
101}
102
103editing::PropertyDescriptor property(std::string path, editing::PropertyType type, editing::Value defaultValue,
104 double minimum, double maximum, const char* units = "") {
105 editing::PropertyDescriptor result;
106 result.path = editing::PropertyPath(path);
107 result.displayNameKey = "editor.vegetation-field." + path;
108 result.descriptionKey = result.displayNameKey + ".description";
109 result.category = "vegetation-field-transform";
110 result.type = type;
112 result.defaultValue = std::move(defaultValue);
113 result.numeric.minimum = minimum;
114 result.numeric.maximum = maximum;
115 result.numeric.units = units;
116 return result;
117}
118} // namespace
119
120VegetationFieldTarget::VegetationFieldTarget(std::string id, graphics::VegetationField* field,
121 graphics::VegetationGlobals globals, std::vector<Entry> entries,
122 std::uint64_t fieldRevision)
123 : id_(std::move(id)),
124 field_(field),
125 globals_(globals),
126 entries_(std::move(entries)),
127 fieldRevision_(fieldRevision) {}
128
130 std::string id, graphics::VegetationField& fieldValue) {
131 if (id.empty())
132 return editing::failed<std::unique_ptr<VegetationFieldTarget>>(
133 editing::Status::Rejected, editing::RuleId("editor.vegetation-field.empty-id"),
134 "Vegetation field target ID is empty");
135 const auto revision = fieldValue.revision();
136 auto elements = fieldValue.snapshotElements();
137 if (!elements.ok()) return editing::Result<std::unique_ptr<VegetationFieldTarget>>::failure(elements.status());
138 std::vector<Entry> entries;
139 try {
140 entries.reserve(elements.value().size());
141 for (std::size_t index = 0; index < elements.value().size(); ++index)
142 entries.push_back(
143 {editing::StableId("element-" + std::to_string(index + 1)), std::move(elements.value()[index])});
144 return editing::applied<std::unique_ptr<VegetationFieldTarget>>(
145 std::unique_ptr<VegetationFieldTarget>(new VegetationFieldTarget(
146 std::move(id), &fieldValue, fieldValue.globalValues(), std::move(entries), revision)));
147 } catch (const std::bad_alloc&) {
148 return editing::failed<std::unique_ptr<VegetationFieldTarget>>(
149 editing::Status::Failed, editing::RuleId("editor.vegetation-field.allocation"),
150 "Vegetation field target allocation failed");
151 }
152}
153
154editing::TargetDescriptor VegetationFieldTarget::describe() const {
155 return {targetId(),
156 "vegetation-field",
157 revision_,
158 false,
159 {editing::CapabilityId("eve.editor.target.vegetation-field-properties")}};
160}
161
162void* VegetationFieldTarget::queryCapability(const editing::CapabilityId& capability) {
163 return capability == editing::CapabilityId("eve.editor.target.vegetation-field-properties")
164 ? static_cast<editing::IPropertyProvider*>(this)
165 : nullptr;
166}
167
168const VegetationFieldTarget::Entry* VegetationFieldTarget::selected(const editing::SelectionSnapshot& selection) const {
169 if (selection.items.size() != 1 || selection.items.front().target != targetId()) return nullptr;
170 const auto& item = selection.items.front().item;
171 const auto found =
172 std::find_if(entries_.begin(), entries_.end(), [&](const Entry& entry) { return entry.id == item; });
173 return found == entries_.end() ? nullptr : &*found;
174}
175
176VegetationFieldTarget::Entry* VegetationFieldTarget::selected(const std::string& id) {
177 const auto found =
178 std::find_if(entries_.begin(), entries_.end(), [&](const Entry& entry) { return entry.id.value() == id; });
179 return found == entries_.end() ? nullptr : &*found;
180}
181
182eve::Result<eve::Revision> VegetationFieldTarget::currentRevision(const editing::SelectionSnapshot& selection) const {
183 if (!selected(selection) || (field_ && field_->revision() != fieldRevision_))
185 eve::DiagnosticCode::Conflict, "Vegetation field selection or runtime revision is stale",
186 "editor.vegetation-field.selection"));
188}
189
190editing::PropertySchema VegetationFieldTarget::schema(const editing::SelectionSnapshot&) const {
192 result.typeId = "vegetation-field.element";
193 result.properties = {
194 property("element.center", editing::PropertyType::Vec3, vec3({0.f, 0.f, 0.f}), -1000000, 1000000, "m"),
195 property("element.extents", editing::PropertyType::Vec3, vec3({1.f, 1.f, 1.f}), 0.0001, 1000000, "m"),
196 property("element.yaw", editing::PropertyType::Float, 0.0, -1000000, 1000000, "rad")};
197 return result;
198}
199
200editing::PropertyReadResult VegetationFieldTarget::read(const editing::SelectionSnapshot& selection,
201 const editing::PropertyPath& path) const {
202 const Entry* entry = selected(selection);
203 if (!entry || !schema(selection).find(path)) return {};
204 if (path == editing::PropertyPath("element.center"))
205 return {editing::PropertyReadState::Value, vec3(entry->value.center), {}};
206 if (path == editing::PropertyPath("element.extents"))
207 return {editing::PropertyReadState::Value, vec3(entry->value.extents), {}};
208 return {editing::PropertyReadState::Value, entry->value.yaw, {}};
209}
210
211editing::Result<editing::DomainOperation> VegetationFieldTarget::replacement(const Entry& before, const Entry& after,
212 std::string propertyName) const {
214 operation.type = "vegetation-field.element.transform.v1";
215 operation.inverseType = operation.type;
216 operation.target = targetId();
217 operation.payload = transformValue(after.id, after.value);
218 operation.inverse = transformValue(before.id, before.value);
219 operation.hasInverse = true;
220 operation.affectedObjects.push_back({targetId(), after.id.value(), revision_});
221 if (!propertyName.empty()) operation.affectedProperties.push_back(propertyName);
222 operation.mergeKey = "vegetation-field:" + id_ + ":" + after.id.value() + ":transform";
223 return editing::applied<editing::DomainOperation>(std::move(operation));
224}
225
226editing::Result<editing::DomainOperation> VegetationFieldTarget::makeTransform(
227 const editing::SelectionSnapshot& selection, glm::vec3 center, glm::vec3 extents, float yaw) const {
228 const Entry* before = selected(selection);
229 if (!before || (field_ && field_->revision() != fieldRevision_))
230 return editing::failed<editing::DomainOperation>(editing::Status::Conflict,
231 editing::RuleId("editor.vegetation-field.stale"),
232 "Vegetation field transform targets stale state");
233 Entry after = *before;
234 after.value.center = center;
235 after.value.extents = extents;
236 after.value.yaw = yaw;
238 std::vector<graphics::VegetationElement> values;
239 values.reserve(entries_.size());
240 for (const Entry& entry : entries_) values.push_back(entry.id == after.id ? after.value : entry.value);
241 const auto valid = validator.replace(globals_, values);
243 return replacement(*before, after, {});
244}
245
246editing::Result<editing::DomainOperation> VegetationFieldTarget::makeSet(const editing::SelectionSnapshot& selection,
248 const editing::Value& value,
249 editing::PropertySetMode mode) const {
250 if (mode == editing::PropertySetMode::Reset) return makeReset(selection, path);
251 const Entry* before = selected(selection);
252 const auto descriptor = schema(selection).find(path);
253 if (!before || !descriptor || mode != editing::PropertySetMode::Absolute)
254 return editing::failed<editing::DomainOperation>(editing::Status::Rejected,
255 editing::RuleId("editor.vegetation-field.property"),
256 "Vegetation field property edit is invalid");
257 Entry after = *before;
258 if (path == editing::PropertyPath("element.center")) {
259 if (!readVec3(value, after.value.center))
260 return editing::failed<editing::DomainOperation>(editing::Status::Rejected,
261 editing::RuleId("editor.vegetation-field.center"),
262 "Vegetation field center must be a finite vec3");
263 } else if (path == editing::PropertyPath("element.extents")) {
264 if (!readVec3(value, after.value.extents))
265 return editing::failed<editing::DomainOperation>(editing::Status::Rejected,
266 editing::RuleId("editor.vegetation-field.extents"),
267 "Vegetation field extents must be a finite vec3");
268 } else {
269 const auto* number = value.getIf<double>();
270 if (!number || !std::isfinite(*number))
271 return editing::failed<editing::DomainOperation>(editing::Status::Rejected,
272 editing::RuleId("editor.vegetation-field.yaw"),
273 "Vegetation field yaw must be finite");
274 after.value.yaw = static_cast<float>(*number);
275 }
277 std::vector<graphics::VegetationElement> values;
278 values.reserve(entries_.size());
279 for (const Entry& entry : entries_) values.push_back(entry.id == after.id ? after.value : entry.value);
280 const auto valid = validator.replace(globals_, values);
282 return replacement(*before, after, path.value());
283}
284
285editing::Result<editing::DomainOperation> VegetationFieldTarget::makeReset(const editing::SelectionSnapshot& selection,
286 const editing::PropertyPath& path) const {
287 const auto descriptor = schema(selection).find(path);
288 if (!descriptor)
289 return editing::failed<editing::DomainOperation>(editing::Status::Unsupported,
290 editing::RuleId("editor.vegetation-field.property"),
291 "Unknown vegetation field property");
292 return makeSet(selection, path, descriptor->defaultValue, editing::PropertySetMode::Absolute);
293}
294
295editing::Result<void> VegetationFieldTarget::validateAndPublish(const std::vector<Entry>& entries) {
296 std::vector<graphics::VegetationElement> values;
297 try {
298 values.reserve(entries.size());
299 for (const Entry& entry : entries) values.push_back(entry.value);
300 } catch (const std::bad_alloc&) {
301 return editing::failed<void>(editing::Status::Failed, editing::RuleId("editor.vegetation-field.allocation"),
302 "Vegetation field publication allocation failed");
303 }
304 if (!field_) {
305 graphics::VegetationField validator;
306 const auto result = validator.replace(globals_, values);
307 return result.ok() ? editing::applied<void>() : editing::Result<void>::failure(result.status());
308 }
309 if (field_->revision() != fieldRevision_)
310 return editing::failed<void>(editing::Status::Conflict,
311 editing::RuleId("editor.vegetation-field.runtime-stale"),
312 "Vegetation field changed outside this editor target");
313 const auto result = field_->replace(globals_, values);
314 if (!result.ok()) return editing::Result<void>::failure(result.status());
315 fieldRevision_ = field_->revision();
316 return editing::applied<void>();
317}
318
319editing::Result<void> VegetationFieldTarget::applyDomainOperation(const editing::DomainOperation& operation) {
320 if (operation.target != targetId() || operation.type != "vegetation-field.element.transform.v1")
321 return editing::failed<void>(editing::Status::Rejected, editing::RuleId("editor.vegetation-field.operation"),
322 "Vegetation field operation mismatch");
323 const auto* idValue = field(operation.payload, "id");
324 const auto* id = idValue ? idValue->getIf<std::string>() : nullptr;
325 Entry* current = id ? selected(*id) : nullptr;
326 if (!current)
327 return editing::failed<void>(editing::Status::NotFound, editing::RuleId("editor.vegetation-field.element"),
328 "Vegetation field element was not found");
329 Entry replacementEntry = *current;
330 const auto* center = field(operation.payload, "center");
331 const auto* extents = field(operation.payload, "extents");
332 if (!center || !extents || !readVec3(*center, replacementEntry.value.center) ||
333 !readVec3(*extents, replacementEntry.value.extents))
334 return editing::failed<void>(editing::Status::Rejected, editing::RuleId("editor.vegetation-field.transform"),
335 "Vegetation field transform payload is invalid");
336 const auto* yawValue = field(operation.payload, "yaw");
337 const auto* yaw = yawValue ? yawValue->getIf<double>() : nullptr;
338 if (!yaw || !std::isfinite(*yaw))
339 return editing::failed<void>(editing::Status::Rejected, editing::RuleId("editor.vegetation-field.transform"),
340 "Vegetation field transform payload is invalid");
341 replacementEntry.value.yaw = static_cast<float>(*yaw);
342 auto candidate = entries_;
343 *std::find_if(candidate.begin(), candidate.end(), [&](const Entry& entry) { return entry.id == current->id; }) =
344 std::move(replacementEntry);
345 auto published = validateAndPublish(candidate);
346 if (!published.ok()) return published;
347 entries_ = std::move(candidate);
348 ++revision_;
349 dirty_.include(0, 0);
350 return editing::applied<void>();
351}
352
353std::unique_ptr<editing::IDomainOperationTarget> VegetationFieldTarget::cloneDomainState() const {
354 auto clone = std::unique_ptr<VegetationFieldTarget>(new VegetationFieldTarget(*this));
355 clone->field_ = nullptr;
356 return clone;
357}
358
359editing::Result<void> VegetationFieldTarget::commitDomainState(
360 std::unique_ptr<editing::IDomainOperationTarget> candidate) {
361 auto* typed = dynamic_cast<VegetationFieldTarget*>(candidate.get());
362 if (!typed || typed->id_ != id_ || !field_)
363 return editing::failed<void>(editing::Status::Conflict, editing::RuleId("editor.vegetation-field.candidate"),
364 "Vegetation field candidate does not match this target");
365 auto published = validateAndPublish(typed->entries_);
366 if (!published.ok()) return published;
367 globals_ = typed->globals_;
368 entries_ = std::move(typed->entries_);
369 revision_ = typed->revision_;
370 dirty_.include(typed->dirty_);
371 return editing::applied<void>();
372}
373
374std::vector<editing::StableId> VegetationFieldTarget::elementIds() const {
375 std::vector<editing::StableId> result;
376 result.reserve(entries_.size());
377 for (const Entry& entry : entries_) result.push_back(entry.id);
378 return result;
379}
380
381} // namespace eve::graphics_editing
LogicalId target
ActionParameterOperation operation
std::string selected
std::string output
std::string descriptor
std::unordered_map< std::string, QuestRuntime > entries
float yaw
Definition BushMesh.cpp:37
SQObjectPtr key
Definition ECS.cpp:155
std::string message
DiagnosticCode code
float maximum[3]
float minimum[3]
wgpu::PopErrorScopeStatus status
std::string id
Poco::JSON::Object::Ptr result
double defaultValue
bool valid
glm::dvec2 center
std::string path
Definition PlayHost.cpp:111
std::uint32_t targetId
std::set< std::string > values
Object::Ptr value
double number
bool found
double current
std::string element
std::size_t elements
std::vector< UnitCandidate > units
float opacity
float size
Definition TreeMesh.cpp:158
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
UUID-backed identifier adapter for legacy textual boundaries.
Definition Identity.h:313
UI-independent property access for an immutable selection snapshot.
Dotted property path (layout.size) compared and persisted as text.
Definition EditingIds.h:78
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.
Backend-independent, owning vegetation influence field. Single writer; concurrent const evaluation is...
Result< std::vector< VegetationElement > > snapshotElements() const
Return an owning, priority-ordered element snapshot for revision-safe editor previews.
Result< void > replace(const VegetationGlobals &globals, std::span< const VegetationElement > elements)
Validate and atomically replace the entire field; failure preserves prior state.
VegetationGlobals globalValues() const
Return detached global defaults; concurrent reads require no writer. No callbacks.
uint64_t revision() const
Monotonic successful-publication revision for derived render snapshots.
Result< editing::GizmoSnapshot > build(std::string target, std::uint64_t expectedRevision, const graphics::VegetationField &field, std::size_t maximumElements=10000) const
Build one immutable gizmo from the field's owning element snapshot.
Owning editor document whose runtime projection is one VegetationField. Element IDs remain stable whi...
std::uint64_t revision() const override
Revision.
static editing::Result< std::unique_ptr< VegetationFieldTarget > > create(std::string id, graphics::VegetationField &field)
Import a complete runtime field into a new authoring target.
const Value * field(const Value &value, const char *key)
Borrow an optional object field.
PropertyType
PropertyType public API.
StrongId< StableIdTag > StableId
Definition EditingIds.h:64
StrongId< RuleIdTag > RuleId
Definition EditingIds.h:60
PropertySetMode
PropertySetMode public API.
eve::StatusCode Status
StrongId< CapabilityIdTag > CapabilityId
Definition EditingIds.h:61
VegetationChannel
Independent vegetation field channels; values use linear color and world units.
DiagnosticCode
Stable machine-readable diagnostic codes.
Definition Diagnostic.h:47
StatusCode
Stable outcome category for an operation.
Definition Status.h:28
DomainOperation public API.
Renderer-neutral wire primitive for authoring viewport overlays.
std::array< double, 3 > size
std::array< double, 3 > position
std::array< double, 4 > color
Immutable revision-tagged overlay snapshot consumed by any viewport renderer.
PropertyReadResult public API.
EVENGINE_API_PLATFORM public API.
SelectionSnapshot public API.
std::vector< SelectionItem > items
Stable discovery metadata exposed by every editable target.