载入中...
搜索中...
未找到
ActionPreviewProfile.cpp
浏览该文件的文档.
2
3#include <algorithm>
4#include <cctype>
5#include <fstream>
6#include <map>
7#include <utility>
8
9namespace eve::editor {
10namespace {
11
12template <class T>
13Result<T> invalid(std::string message, std::string path) {
15}
16
17Result<void> invalid(std::string message, std::string path) {
19}
20
21const Value* field(const Value& value, std::string_view name) { return value.find(std::string(name)); }
22
23Result<std::string> stringField(const Value& value, std::string_view name, std::string path) {
24 const Value* member = field(value, name);
25 if (!member || !member->isString()) return invalid<std::string>("expected string field", std::move(path));
26 return Result<std::string>::success(member->asString());
27}
28
29Result<bool> boolField(const Value& value, std::string_view name, std::string path) {
30 const Value* member = field(value, name);
31 if (!member || !member->isBool()) return invalid<bool>("expected boolean field", std::move(path));
32 return Result<bool>::success(member->asBool());
33}
34
35Result<std::int64_t> intField(const Value& value, std::string_view name, std::string path) {
36 const Value* member = field(value, name);
37 if (!member || !member->isInt64()) return invalid<std::int64_t>("expected integer field", std::move(path));
39}
40
41bool validUri(std::string_view uri) {
42 if (uri.empty()) return true;
43 const auto scheme = uri.find("://");
44 return scheme != std::string_view::npos && scheme != 0 && scheme + 3 < uri.size();
45}
46
47std::string normalizedBone(std::string_view name) {
48 std::string normalized;
49 normalized.reserve(name.size());
50 for (const unsigned char character : name)
51 if (std::isalnum(character)) normalized.push_back(static_cast<char>(std::tolower(character)));
52 return normalized;
53}
54
55Result<void> validateSkeleton(const ActionPreviewSkeleton& skeleton, std::string path) {
56 if (skeleton.bones.empty()) return invalid("skeleton has no bones", std::move(path));
57 for (std::size_t index = 0; index < skeleton.bones.size(); ++index) {
58 const auto& bone = skeleton.bones[index];
59 if (bone.name.empty()) return invalid("skeleton bone name is empty", path + ".bones[" + std::to_string(index) + "]");
60 if (bone.parent < -1 || bone.parent >= static_cast<int>(index))
61 return invalid("skeleton parent must precede its child", path + ".bones[" + std::to_string(index) + "].parent");
62 }
63 return Result<void>::success();
64}
65
66ActionPreviewCompatibility compareSkeletons(const ActionPreviewSkeleton& target,
67 const ActionPreviewSkeleton& candidate) {
68 if (target.bones.size() != candidate.bones.size()) return ActionPreviewCompatibility::Incompatible;
69 bool exact = true;
70 std::map<std::string, std::string> targetParents;
71 for (std::size_t index = 0; index < target.bones.size(); ++index) {
72 const auto& bone = target.bones[index];
73 const std::string parent = bone.parent < 0 ? std::string{} : normalizedBone(target.bones[bone.parent].name);
74 targetParents.emplace(normalizedBone(bone.name), parent);
75 }
76 for (std::size_t index = 0; index < candidate.bones.size(); ++index) {
77 const auto& bone = candidate.bones[index];
78 const std::string normalized = normalizedBone(bone.name);
79 const std::string parent = bone.parent < 0 ? std::string{} : normalizedBone(candidate.bones[bone.parent].name);
80 const auto found = targetParents.find(normalized);
81 if (found == targetParents.end() || found->second != parent) return ActionPreviewCompatibility::Incompatible;
82 exact = exact && target.bones[index].name == bone.name && target.bones[index].parent == bone.parent;
83 }
85}
86
87} // namespace
88
89std::string_view actionPreviewShadingName(ActionPreviewShading shading) noexcept {
90 switch (shading) {
91 case ActionPreviewShading::Lit: return "lit";
92 case ActionPreviewShading::Unlit: return "unlit";
93 }
94 return "lit";
95}
96
98 if (actionAsset.format().empty()) return invalid("preview profile requires an action asset", "actionAssetGuid");
99 const std::pair<std::string_view, std::string_view> uris[] = {
100 {previewModelUri, "previewModelUri"}, {baseMotionUri, "baseMotionUri"},
101 {animationProfileUri, "animationProfileUri"}, {boneMaskUri, "boneMaskUri"}};
102 for (const auto& [uri, path] : uris)
103 if (!validUri(uri)) return invalid("preview resource must use a canonical URI", std::string(path));
104 return Result<void>::success();
105}
106
108 auto valid = validate();
109 if (!valid) return Result<Value>::failure(valid.status());
111 object["schema"] = std::string(kActionPreviewProfileSchemaId);
112 object["schemaVersion"] = static_cast<std::int64_t>(kActionPreviewProfileSchemaVersion);
113 object["actionAssetGuid"] = actionAsset.format();
114 object["previewModelUri"] = previewModelUri;
115 object["baseMotionUri"] = baseMotionUri;
116 object["animationProfileUri"] = animationProfileUri;
117 object["boneMaskUri"] = boneMaskUri;
118 object["showRootMotion"] = showRootMotion;
119 object["footIk"] = footIk;
120 object["showGrid"] = showGrid;
121 object["showSkeleton"] = showSkeleton;
122 object["showJointNames"] = showJointNames;
123 object["shading"] = std::string(actionPreviewShadingName(shading));
124 return Result<Value>::success(Value(std::move(object)));
125}
126
128 if (!value.isObject()) return invalid<ActionPreviewProfile>("expected preview profile object", "$");
129 auto schema = stringField(value, "schema", "schema");
130 auto version = intField(value, "schemaVersion", "schemaVersion");
131 if (!schema) return Result<ActionPreviewProfile>::failure(schema.status());
133 if (schema.value() != kActionPreviewProfileSchemaId)
134 return invalid<ActionPreviewProfile>("unexpected preview profile schema", "schema");
135 if (version.value() != static_cast<std::int64_t>(kActionPreviewProfileSchemaVersion))
136 return invalid<ActionPreviewProfile>("unsupported preview profile schema version", "schemaVersion");
137
138 auto asset = stringField(value, "actionAssetGuid", "actionAssetGuid");
139 auto model = stringField(value, "previewModelUri", "previewModelUri");
140 auto motion = stringField(value, "baseMotionUri", "baseMotionUri");
141 auto animationProfile = stringField(value, "animationProfileUri", "animationProfileUri");
142 auto mask = stringField(value, "boneMaskUri", "boneMaskUri");
143 auto rootMotion = boolField(value, "showRootMotion", "showRootMotion");
144 auto footIkValue = boolField(value, "footIk", "footIk");
145 auto grid = boolField(value, "showGrid", "showGrid");
146 auto skeleton = boolField(value, "showSkeleton", "showSkeleton");
147 auto names = boolField(value, "showJointNames", "showJointNames");
148 auto shadingValue = stringField(value, "shading", "shading");
149 if (!asset) return Result<ActionPreviewProfile>::failure(asset.status());
151 if (!motion) return Result<ActionPreviewProfile>::failure(motion.status());
152 if (!animationProfile) return Result<ActionPreviewProfile>::failure(animationProfile.status());
153 if (!mask) return Result<ActionPreviewProfile>::failure(mask.status());
154 if (!rootMotion) return Result<ActionPreviewProfile>::failure(rootMotion.status());
155 if (!footIkValue) return Result<ActionPreviewProfile>::failure(footIkValue.status());
156 if (!grid) return Result<ActionPreviewProfile>::failure(grid.status());
157 if (!skeleton) return Result<ActionPreviewProfile>::failure(skeleton.status());
158 if (!names) return Result<ActionPreviewProfile>::failure(names.status());
159 if (!shadingValue) return Result<ActionPreviewProfile>::failure(shadingValue.status());
160
161 ActionPreviewProfile profile;
162 profile.actionAsset = AssetGuid(std::move(asset).takeValue());
163 profile.previewModelUri = std::move(model).takeValue();
164 profile.baseMotionUri = std::move(motion).takeValue();
165 profile.animationProfileUri = std::move(animationProfile).takeValue();
166 profile.boneMaskUri = std::move(mask).takeValue();
167 profile.showRootMotion = rootMotion.value();
168 profile.footIk = footIkValue.value();
169 profile.showGrid = grid.value();
170 profile.showSkeleton = skeleton.value();
171 profile.showJointNames = names.value();
172 if (shadingValue.value() == "lit") profile.shading = ActionPreviewShading::Lit;
173 else if (shadingValue.value() == "unlit") profile.shading = ActionPreviewShading::Unlit;
174 else return invalid<ActionPreviewProfile>("unknown preview shading mode", "shading");
175 auto valid = profile.validate();
177 return Result<ActionPreviewProfile>::success(std::move(profile));
178}
179
181 if (!profileDiagnostics.empty()) return false;
182 return std::none_of(sections.begin(), sections.end(), [](const auto& section) {
183 return section.compatibility == ActionPreviewCompatibility::Incompatible ||
184 section.compatibility == ActionPreviewCompatibility::Unsupported;
185 });
186}
187
189 const action::ActionTimeline& timeline, const ActionPreviewProfile& profile,
191 auto timelineValid = timeline.validate();
192 if (!timelineValid) return Result<ActionPreviewCompatibilityReport>::failure(timelineValid.status());
193 auto profileValid = profile.validate();
194 if (!profileValid) return Result<ActionPreviewCompatibilityReport>::failure(profileValid.status());
195
197 if (!provider) {
198 report.profileDiagnostics.push_back(Diagnostic::error(
199 DiagnosticCode::Unsupported, "animation/model preview asset provider is not available", "provider"));
200 for (const auto& section : timeline.animationSections)
201 report.sections.push_back({section.id, ActionPreviewCompatibility::Unsupported,
203 "skeleton compatibility was not evaluated", "provider")}});
205 }
206
207 if (profile.previewModelUri.empty() && timeline.animationSections.empty()) {
208 report.profileDiagnostics.push_back(Diagnostic::error(
209 DiagnosticCode::NotFound, "preview requires a model or at least one animation section", "previewModelUri"));
211 }
212 Result<ActionPreviewSkeleton> target = profile.previewModelUri.empty()
213 ? provider->animationSkeleton(timeline.animationSections.front().animationUri)
214 : provider->modelSkeleton(profile.previewModelUri);
216 auto targetValid = validateSkeleton(target.value(), "targetSkeleton");
217 if (!targetValid) return Result<ActionPreviewCompatibilityReport>::failure(targetValid.status());
218 if (!profile.boneMaskUri.empty()) {
219 auto mask = provider->validateBoneMask(profile.boneMaskUri, target.value());
220 if (!mask) {
221 if (!mask.status().diagnostics().empty())
222 report.profileDiagnostics.push_back(mask.status().diagnostics().front());
223 else
224 report.profileDiagnostics.push_back(Diagnostic::error(
225 DiagnosticCode::Conflict, "preview bone mask is incompatible with the target skeleton",
226 "boneMaskUri"));
227 }
228 }
229
230 for (const auto& section : timeline.animationSections) {
231 ActionPreviewSectionDiagnostic projected;
232 projected.sectionId = section.id;
233 auto skeleton = provider->animationSkeleton(section.animationUri);
234 if (!skeleton) {
235 projected.compatibility = ActionPreviewCompatibility::Incompatible;
236 projected.diagnostics = skeleton.status().diagnostics();
237 report.sections.push_back(std::move(projected));
238 continue;
239 }
240 auto valid = validateSkeleton(skeleton.value(), "animationSkeleton");
241 if (!valid) {
242 projected.compatibility = ActionPreviewCompatibility::Incompatible;
243 projected.diagnostics = valid.status().diagnostics();
244 report.sections.push_back(std::move(projected));
245 continue;
246 }
247 projected.compatibility = compareSkeletons(target.value(), skeleton.value());
248 if (projected.compatibility == ActionPreviewCompatibility::Retargetable)
249 projected.diagnostics.push_back(Diagnostic::warning(
250 DiagnosticCode::Conflict, "animation skeleton requires normalized-name retargeting", "animationUri"));
251 else if (projected.compatibility == ActionPreviewCompatibility::Incompatible)
252 projected.diagnostics.push_back(Diagnostic::error(
253 DiagnosticCode::Conflict, "animation skeleton is incompatible with the preview target", "animationUri"));
254 report.sections.push_back(std::move(projected));
255 }
257}
258
259ActionPreviewProfileStore::ActionPreviewProfileStore(std::filesystem::path projectRoot)
260 : projectRoot_(std::move(projectRoot)) {}
261
262std::filesystem::path ActionPreviewProfileStore::pathFor(const AssetGuid& actionAsset) const {
263 std::string filename = actionAsset.format();
264 for (char& character : filename)
265 if (!std::isalnum(static_cast<unsigned char>(character)) && character != '-' && character != '_')
266 character = '_';
267 return projectRoot_ / ".eve" / "action-preview" / (filename + ".json");
268}
269
271 auto encoded = profile.toValue();
272 if (!encoded) return Result<void>::failure(encoded.status());
273 auto json = encoded.value().toJson();
274 if (!json) return Result<void>::failure(json.status());
275
276 const auto destination = pathFor(profile.actionAsset);
277 const auto temporary = std::filesystem::path(destination.string() + ".tmp");
278 std::error_code error;
279 std::filesystem::create_directories(destination.parent_path(), error);
280 if (error)
282 DiagnosticCode::Failed, "could not create action preview sidecar directory", destination.string()));
283 {
284 std::ofstream output(temporary, std::ios::binary | std::ios::trunc);
285 if (!output)
287 DiagnosticCode::Failed, "could not open action preview sidecar temporary file", temporary.string()));
288 output << json.value();
289 output.flush();
290 if (!output)
292 DiagnosticCode::Failed, "could not write action preview sidecar", temporary.string()));
293 }
294 std::filesystem::rename(temporary, destination, error);
295 if (error) {
296 std::error_code removeError;
297 std::filesystem::remove(destination, removeError);
298 error.clear();
299 std::filesystem::rename(temporary, destination, error);
300 }
301 if (error)
303 DiagnosticCode::Failed, "could not atomically replace action preview sidecar", destination.string()));
305}
306
308 const auto source = pathFor(actionAsset);
309 std::ifstream input(source, std::ios::binary);
310 if (!input)
312 Diagnostic::error(DiagnosticCode::NotFound, "action preview sidecar was not found", source.string()));
313 std::string json((std::istreambuf_iterator<char>(input)), std::istreambuf_iterator<char>());
314 if (!input.good() && !input.eof())
316 Diagnostic::error(DiagnosticCode::Failed, "could not read action preview sidecar", source.string()));
317 auto value = Value::fromJson(json);
319 auto profile = ActionPreviewProfile::fromValue(value.value());
320 if (!profile) return profile;
321 if (profile.value().actionAsset != actionAsset)
322 return invalid<ActionPreviewProfile>("preview sidecar asset identity does not match its filename",
323 "actionAssetGuid");
324 return profile;
325}
326
327} // namespace eve::editor
LogicalId target
Versioned action-editor preview settings and skeleton diagnostics.
std::string output
int mask
std::string name
Definition ECS.cpp:154
EvpackChunkInput input
Definition Evpack.cpp:170
std::string message
const ColourScope * parent
std::uint32_t bone
bool valid
std::string error
Definition Package.cpp:174
std::string path
Definition PlayHost.cpp:111
std::string uri
Object::Ptr value
glm::mat4 model
bool found
std::string_view source
Json object
float(ui::Theme::* member)[4]
uint32_t index
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
static Diagnostic warning(DiagnosticCode code, std::string message, std::string path={})
Construct a warning diagnostic.
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
UUID-backed identifier adapter for legacy textual boundaries.
Definition Identity.h:313
const std::string & format() const noexcept
Returns the compatibility spelling; use canonicalFormat at persistence boundaries.
Definition Identity.h:368
The canonical owning dynamic value used by data-facing protocols.
Definition Value.h:31
static Result< Value > fromJson(std::string_view json)
Parse one strict JSON value into an owning Value.
Definition Value.cpp:177
std::map< std::string, Value > Object
Definition Value.h:34
EVENGINE_API_EDITORS Result< ActionPreviewCompatibilityReport > analyze(const action::ActionTimeline &timeline, const ActionPreviewProfile &profile, IActionPreviewAssetProvider *provider) const
Analyze every animation section against the selected model or first animation anchor.
EVENGINE_API_EDITORS Result< ActionPreviewProfile > load(const AssetGuid &actionAsset) const
Load and validate one profile without modifying caller state on failure.
EVENGINE_API_EDITORS Result< void > save(const ActionPreviewProfile &profile) const
Atomically validate and save one profile under .eve/action-preview.
EVENGINE_API_EDITORS std::filesystem::path pathFor(const AssetGuid &actionAsset) const
Return the stable sidecar path for diagnostics and file watching.
Optional provider implemented by an animation/model authoring integration.
const Value * field(const Value &value, const char *key)
Borrow an optional object field.
std::variant< std::monostate, std::int64_t, double, std::string, bool > Value
Definition Database.h:27
std::string_view actionPreviewShadingName(ActionPreviewShading shading) noexcept
Stable protocol spelling for a shading option.
constexpr std::string_view kActionPreviewProfileSchemaId
ActionPreviewCompatibility
Severity of one animation section's compatibility with the preview target.
ActionPreviewShading
Renderer-neutral shading preference persisted only for editor preview.
constexpr std::uint64_t kActionPreviewProfileSchemaVersion
eve::editing::AssetGuid AssetGuid
Definition EditorIds.h:39
Status invalid(const char *message)
Canonical action timeline asset shared by runtime and editor.
Result< void > validate() const
Validate ids, ranges, uniqueness and deterministic ordering.
std::vector< ActionAnimationSection > animationSections
Complete compatibility report suitable for timeline decoration and tooltips.
std::vector< ActionPreviewSectionDiagnostic > sections
EVENGINE_API_EDITORS bool canPreview() const noexcept
True when no section or profile diagnostic prevents preview.
Asset-specific editor state kept outside the runtime action timeline.
EVENGINE_API_EDITORS Result< void > validate() const
Validate stable identity, URI spelling and enum state.
static EVENGINE_API_EDITORS Result< ActionPreviewProfile > fromValue(const Value &value)
Decode and validate a sidecar transactionally.
EVENGINE_API_EDITORS Result< Value > toValue() const
Encode the canonical sidecar value.