载入中...
搜索中...
未找到
SpineSkeletonData.cpp
浏览该文件的文档.
2
3#include "common/Exception.h"
4#include "common/Module.h"
5#include "data/DataModule.h"
6#include "data/JsonDocument.h"
9
10#include <Poco/Dynamic/Var.h>
11#include <Poco/JSON/Array.h>
12#include <Poco/JSON/Object.h>
13
14#include <algorithm>
15#include <cmath>
16#include <cstdio>
17#include <memory>
18
19namespace eve::animation {
20namespace {
21
22float asFloat(const Poco::Dynamic::Var &v, float fallback = 0.f) {
23 try {
24 if (v.isEmpty()) return fallback;
25 return v.convert<float>();
26 } catch (...) {
27 return fallback;
28 }
29}
30
31std::string asString(const Poco::Dynamic::Var &v, const std::string &fallback = {}) {
32 try {
33 if (v.isEmpty()) return fallback;
34 return v.convert<std::string>();
35 } catch (...) {
36 return fallback;
37 }
38}
39
40bool keyStepped(Poco::JSON::Object::Ptr obj) {
41 if (!obj || !obj->has("curve")) return false;
42 const std::string curve = asString(obj->get("curve"));
43 if (curve == "stepped") return true;
44 if (curve == "linear") return false;
45 throw Exception("SpineSkeletonData: unsupported Bezier curve in timeline key at time %g",
46 asFloat(obj->get("time")));
47
48}
49
50} // namespace
51
52
53void SpineSkeletonData::checkBone(int index) const {
54 if (index < 0 || index >= getBoneCount())
55 throw Exception("SpineSkeletonData: bone index %d out of range", index);
56}
57void SpineSkeletonData::checkSlot(int index) const {
58 if (index < 0 || index >= getSlotCount())
59 throw Exception("SpineSkeletonData: slot index %d out of range", index);
60}
61void SpineSkeletonData::checkSkin(int index) const {
62 if (index < 0 || index >= getSkinCount())
63 throw Exception("SpineSkeletonData: skin index %d out of range", index);
64}
65void SpineSkeletonData::checkAnim(int index) const {
66 if (index < 0 || index >= getAnimationCount())
67 throw Exception("SpineSkeletonData: animation index %d out of range", index);
68}
69
71 spineVersion_.clear();
72 bones_.clear();
73 slots_.clear();
74 skins_.clear();
75 anims_.clear();
76 boneByName_.clear();
77 slotByName_.clear();
78 skinByName_.clear();
79 animByName_.clear();
80 defaultSkin_ = -1;
81}
82
83int SpineSkeletonData::findBone(const std::string &name) const {
84 auto it = boneByName_.find(name);
85 return it == boneByName_.end() ? -1 : it->second;
86}
87int SpineSkeletonData::findSlot(const std::string &name) const {
88 auto it = slotByName_.find(name);
89 return it == slotByName_.end() ? -1 : it->second;
90}
91int SpineSkeletonData::findSkin(const std::string &name) const {
92 auto it = skinByName_.find(name);
93 return it == skinByName_.end() ? -1 : it->second;
94}
95int SpineSkeletonData::findAnimation(const std::string &name) const {
96 auto it = animByName_.find(name);
97 return it == animByName_.end() ? -1 : it->second;
98}
99
100std::string SpineSkeletonData::getBoneName(int index) const {
101 checkBone(index);
102 return bones_[static_cast<size_t>(index)].name;
103}
105 checkBone(index);
106 return bones_[static_cast<size_t>(index)].parent;
107}
109 checkBone(index);
110 return bones_[static_cast<size_t>(index)].x;
111}
113 checkBone(index);
114 return bones_[static_cast<size_t>(index)].y;
115}
117 checkBone(index);
118 return bones_[static_cast<size_t>(index)].rotation;
119}
121 checkBone(index);
122 return bones_[static_cast<size_t>(index)].scaleX;
123}
125 checkBone(index);
126 return bones_[static_cast<size_t>(index)].scaleY;
127}
128
129std::string SpineSkeletonData::getSlotName(int index) const {
130 checkSlot(index);
131 return slots_[static_cast<size_t>(index)].name;
132}
134 checkSlot(index);
135 return slots_[static_cast<size_t>(index)].bone;
136}
138 checkSlot(index);
139 return slots_[static_cast<size_t>(index)].attachment;
140}
141
142std::string SpineSkeletonData::getSkinName(int index) const {
143 checkSkin(index);
144 return skins_[static_cast<size_t>(index)].name;
145}
147 checkAnim(index);
148 return anims_[static_cast<size_t>(index)].name;
149}
151 checkAnim(index);
152 return anims_[static_cast<size_t>(index)].duration;
153}
154
156 int skinIndex, int slotIndex, const std::string &name) const {
157 if (skinIndex < 0 || skinIndex >= getSkinCount()) return nullptr;
158 if (name.empty()) return nullptr;
159 const SkinData &sk = skins_[static_cast<size_t>(skinIndex)];
160 auto sit = sk.attachments.find(slotIndex);
161 if (sit == sk.attachments.end()) return nullptr;
162 auto ait = sit->second.find(name);
163 if (ait == sit->second.end()) return nullptr;
164 return &ait->second;
165}
166
167bool SpineSkeletonData::loadFromFile(const std::string &path, std::string *error) {
168 if (path.empty()) {
169 if (error) *error = "empty path";
170 return false;
171 }
172 auto *fs = eve::ModuleManager::getInstance<eve::filesystem::Filesystem>("Filesystem");
173 if (!fs) fs = eve::filesystem::Filesystem::create();
174 std::unique_ptr<eve::filesystem::FileData> data;
175 try {
176 data.reset(fs->read(path));
177 } catch (...) {
178 if (error) *error = "read failed: " + path;
179 return false;
180 }
181 if (!data || data->getSize() == 0) {
182 if (error) *error = "empty file: " + path;
183 return false;
184 }
185 std::string text(static_cast<const char *>(data->getData()),
186 static_cast<size_t>(data->getSize()));
187 return loadFromJson(text, error);
188}
189
190bool SpineSkeletonData::loadFromJson(const std::string &json, std::string *error) {
191 clear();
192 if (error) error->clear();
193 auto *dm = eve::data::DataModule::create();
194 std::string err;
195 std::unique_ptr<data::JsonDocument> doc(dm->decodeJson(json, &err));
196 if (!doc || !doc->isObject()) {
197 if (error) *error = err.empty() ? "invalid json" : err;
198 return false;
199 }
200 Poco::JSON::Object::Ptr root = doc->object();
201
202 try {
203 auto rejectUnsupported = [](const std::string &context) {
204 const std::string message = "SpineSkeletonData: unsupported " + context +
205 "; region attachments and basic bone/attachment timelines only; "
206 "use the official spine-cpp runtime for full support";
207 // Script loaders and module factories do not expose the error out parameter.
208 throw Exception("%s", message.c_str());
209 };
210 for (const char *feature : {"ik", "transform", "path", "physics"}) {
211 if (root->has(feature) && root->isArray(feature) && root->getArray(feature)->size() > 0)
212 rejectUnsupported(std::string("constraint '") + feature + "'");
213 }
214 if (root->has("skeleton")) {
215 auto skel = root->getObject("skeleton");
216 if (skel) spineVersion_ = asString(skel->get("spine"));
217 }
218
219 // Bones
220 if (root->has("bones")) {
221 auto arr = root->getArray("bones");
222 if (arr) {
223 for (size_t i = 0; i < arr->size(); ++i) {
224 auto obj = arr->getObject(static_cast<unsigned>(i));
225 if (!obj) continue;
226 BoneData b;
227 b.name = asString(obj->get("name"));
228 if (b.name.empty()) continue;
229 if (asFloat(obj->get("shearX")) != 0.f || asFloat(obj->get("shearY")) != 0.f)
230 rejectUnsupported("shear in bone '" + b.name + "'");
231 for (const char *mode : {"transform", "inherit"})
232 if (obj->has(mode) && asString(obj->get(mode)) != "normal")
233 rejectUnsupported(std::string(mode) + " mode in bone '" + b.name + "'");
234 if (obj->has("parent")) {
235 std::string parent = asString(obj->get("parent"));
236 b.parent = findBone(parent);
237 if (b.parent < 0) {
238 if (error) *error = "unknown bone parent: " + parent;
239 clear();
240 return false;
241 }
242 }
243 b.x = asFloat(obj->get("x"));
244 b.y = asFloat(obj->get("y"));
245 b.rotation = asFloat(obj->get("rotation"));
246 b.scaleX = obj->has("scaleX") ? asFloat(obj->get("scaleX"), 1.f) : 1.f;
247 b.scaleY = obj->has("scaleY") ? asFloat(obj->get("scaleY"), 1.f) : 1.f;
248 boneByName_[b.name] = static_cast<int>(bones_.size());
249 bones_.push_back(std::move(b));
250 }
251 }
252 }
253 if (bones_.empty()) {
254 BoneData rootBone;
255 rootBone.name = "root";
256 boneByName_["root"] = 0;
257 bones_.push_back(rootBone);
258 }
259
260 // Slots
261 if (root->has("slots")) {
262 auto arr = root->getArray("slots");
263 if (arr) {
264 for (size_t i = 0; i < arr->size(); ++i) {
265 auto obj = arr->getObject(static_cast<unsigned>(i));
266 if (!obj) continue;
267 SlotData s;
268 s.name = asString(obj->get("name"));
269 std::string boneName = asString(obj->get("bone"));
270 s.bone = findBone(boneName);
271 if (s.bone < 0)
272 throw Exception("SpineSkeletonData: unknown bone '%s' in slot '%s'",
273 boneName.c_str(), s.name.c_str());
274 if (obj->has("color") && asString(obj->get("color")) != "ffffffff")
275 rejectUnsupported("color in slot '" + s.name + "'");
276 if (obj->has("dark")) rejectUnsupported("dark color in slot '" + s.name + "'");
277 if (obj->has("blend") && asString(obj->get("blend")) != "normal")
278 rejectUnsupported("blend mode in slot '" + s.name + "'");
279 if (obj->has("attachment")) s.attachment = asString(obj->get("attachment"));
280 slotByName_[s.name] = static_cast<int>(slots_.size());
281 slots_.push_back(std::move(s));
282 }
283 }
284 }
285
286 auto parseRegion = [&](const std::string &attName, Poco::JSON::Object::Ptr att)
289 r.name = attName;
290 r.path = att->has("path") ? asString(att->get("path")) : attName;
291 r.x = asFloat(att->get("x"));
292 r.y = asFloat(att->get("y"));
293 r.rotation = asFloat(att->get("rotation"));
294 r.width = asFloat(att->get("width"));
295 r.height = asFloat(att->get("height"));
296 r.scaleX = att->has("scaleX") ? asFloat(att->get("scaleX"), 1.f) : 1.f;
297 r.scaleY = att->has("scaleY") ? asFloat(att->get("scaleY"), 1.f) : 1.f;
298 return r;
299 };
300
301 auto addSkinAttachments = [&](SkinData &skin, Poco::JSON::Object::Ptr attachmentsRoot) {
302 if (!attachmentsRoot) return;
303 // Format A (3.8+): attachments: { slot: { att: {...} } }
304 // Format B (older skins object): same without wrapper
305 for (const auto &slotName : attachmentsRoot->getNames()) {
306 int slotIndex = findSlot(slotName);
307 if (slotIndex < 0)
308 throw Exception("SpineSkeletonData: unknown slot '%s' in skin '%s'",
309 slotName.c_str(), skin.name.c_str());
310 auto slotObj = attachmentsRoot->getObject(slotName);
311 if (!slotObj) continue;
312 for (const auto &attName : slotObj->getNames()) {
313 auto attObj = slotObj->getObject(attName);
314 if (!attObj) continue;
315 // Never report success after discarding an attachment.
316 std::string type = attObj->has("type") ? asString(attObj->get("type")) : "region";
317 if (!type.empty() && type != "region")
318 rejectUnsupported("attachment type '" + type + "' in skin '" + skin.name +
319 "', slot '" + slotName + "', attachment '" + attName + "'");
320 if (attObj->has("color") && asString(attObj->get("color")) != "ffffffff")
321 rejectUnsupported("color in attachment '" + attName + "' of slot '" + slotName + "'");
322 if (attObj->has("sequence")) rejectUnsupported("sequence in attachment '" + attName + "'");
323 skin.attachments[slotIndex][attName] = parseRegion(attName, attObj);
324 }
325 }
326 };
327
328 // Skins — array form (3.8+) or object form
329 if (root->has("skins")) {
330 if (root->isArray("skins")) {
331 auto arr = root->getArray("skins");
332 for (size_t i = 0; i < arr->size(); ++i) {
333 auto obj = arr->getObject(static_cast<unsigned>(i));
334 if (!obj) continue;
336 skin.name = asString(obj->get("name"));
337 if (skin.name.empty()) skin.name = "default";
338 if (obj->has("attachments"))
339 addSkinAttachments(skin, obj->getObject("attachments"));
340 skinByName_[skin.name] = static_cast<int>(skins_.size());
341 skins_.push_back(std::move(skin));
342 }
343 } else {
344 auto obj = root->getObject("skins");
345 if (obj) {
346 for (const auto &skinName : obj->getNames()) {
348 skin.name = skinName;
349 addSkinAttachments(skin, obj->getObject(skinName));
350 skinByName_[skin.name] = static_cast<int>(skins_.size());
351 skins_.push_back(std::move(skin));
352 }
353 }
354 }
355 }
356 if (skins_.empty()) {
358 skin.name = "default";
359 skinByName_["default"] = 0;
360 skins_.push_back(skin);
361 }
362 defaultSkin_ = findSkin("default");
363 if (defaultSkin_ < 0) defaultSkin_ = 0;
364
365 // Animations
366 if (root->has("animations")) {
367 auto animsObj = root->getObject("animations");
368 if (animsObj) {
369 for (const auto &animName : animsObj->getNames()) {
370 auto animObj = animsObj->getObject(animName);
371 if (!animObj) continue;
372 for (const char *feature : {"ik", "transform", "paths", "physics", "deform", "ffd",
373 "drawOrder", "draworder", "events", "attachments"}) {
374 if (!animObj->has(feature)) continue;
375 const bool nonempty = animObj->isArray(feature)
376 ? animObj->getArray(feature)->size() > 0
377 : animObj->getObject(feature) && animObj->getObject(feature)->size() > 0;
378 if (nonempty)
379 rejectUnsupported("timeline '" + std::string(feature) + "' in animation '" +
380 animName + "'");
381 }
382 AnimationData anim;
383 anim.name = animName;
384 float maxT = 0.f;
385
386 if (animObj->has("bones")) {
387 auto bonesObj = animObj->getObject("bones");
388 if (bonesObj) {
389 for (const auto &boneName : bonesObj->getNames()) {
390 int bi = findBone(boneName);
391 if (bi < 0)
392 throw Exception("SpineSkeletonData: unknown bone '%s' in animation '%s'",
393 boneName.c_str(), animName.c_str());
394 auto btObj = bonesObj->getObject(boneName);
395 if (!btObj) continue;
396 for (const auto &timeline : btObj->getNames())
397 if (timeline != "rotate" && timeline != "translate" && timeline != "scale")
398 rejectUnsupported("bone timeline '" + timeline + "' for bone '" +
399 boneName + "' in animation '" + animName + "'");
400 BoneTimeline bt;
401 bt.boneIndex = bi;
402
403 if (btObj->has("rotate")) {
404 auto arr = btObj->getArray("rotate");
405 if (arr) {
406 for (size_t i = 0; i < arr->size(); ++i) {
407 auto k = arr->getObject(static_cast<unsigned>(i));
408 if (!k) continue;
409 FloatKey fk;
410 fk.time = asFloat(k->get("time"));
411 fk.value = asFloat(k->get("value"),
412 asFloat(k->get("angle")));
413 fk.stepped = keyStepped(k);
414 maxT = std::max(maxT, fk.time);
415 bt.rotate.push_back(fk);
416 }
417 }
418 }
419 if (btObj->has("translate")) {
420 auto arr = btObj->getArray("translate");
421 if (arr) {
422 for (size_t i = 0; i < arr->size(); ++i) {
423 auto k = arr->getObject(static_cast<unsigned>(i));
424 if (!k) continue;
425 TranslateKey tk;
426 tk.time = asFloat(k->get("time"));
427 tk.x = asFloat(k->get("x"));
428 tk.y = asFloat(k->get("y"));
429 tk.stepped = keyStepped(k);
430 maxT = std::max(maxT, tk.time);
431 bt.translate.push_back(tk);
432 }
433 }
434 }
435 if (btObj->has("scale")) {
436 auto arr = btObj->getArray("scale");
437 if (arr) {
438 for (size_t i = 0; i < arr->size(); ++i) {
439 auto k = arr->getObject(static_cast<unsigned>(i));
440 if (!k) continue;
441 ScaleKey sk;
442 sk.time = asFloat(k->get("time"));
443 sk.x = k->has("x") ? asFloat(k->get("x"), 1.f) : 1.f;
444 sk.y = k->has("y") ? asFloat(k->get("y"), 1.f) : 1.f;
445 sk.stepped = keyStepped(k);
446 maxT = std::max(maxT, sk.time);
447 bt.scale.push_back(sk);
448 }
449 }
450 }
451 anim.bones.push_back(std::move(bt));
452 }
453 }
454 }
455
456 if (animObj->has("slots")) {
457 auto slotsObj = animObj->getObject("slots");
458 if (slotsObj) {
459 for (const auto &slotName : slotsObj->getNames()) {
460 int si = findSlot(slotName);
461 if (si < 0)
462 throw Exception("SpineSkeletonData: unknown slot '%s' in animation '%s'",
463 slotName.c_str(), animName.c_str());
464 auto stObj = slotsObj->getObject(slotName);
465 if (!stObj) continue;
466 for (const auto &timeline : stObj->getNames())
467 if (timeline != "attachment")
468 rejectUnsupported("slot timeline '" + timeline + "' for slot '" +
469 slotName + "' in animation '" + animName + "'");
470 SlotTimeline st;
471 st.slotIndex = si;
472 if (stObj->has("attachment")) {
473 auto arr = stObj->getArray("attachment");
474 if (arr) {
475 for (size_t i = 0; i < arr->size(); ++i) {
476 auto k = arr->getObject(static_cast<unsigned>(i));
477 if (!k) continue;
478 AttachmentKey ak;
479 ak.time = asFloat(k->get("time"));
480 ak.name = k->has("name") ? asString(k->get("name")) : "";
481 maxT = std::max(maxT, ak.time);
482 st.attachment.push_back(ak);
483 }
484 }
485 }
486 anim.slots.push_back(std::move(st));
487 }
488 }
489 }
490
491 anim.duration = maxT;
492 animByName_[anim.name] = static_cast<int>(anims_.size());
493 anims_.push_back(std::move(anim));
494 }
495 }
496 }
497 } catch (const std::exception &ex) {
498 std::fprintf(stderr, "%s\n", ex.what());
499 if (error) *error = ex.what();
500 clear();
501 return false;
502 }
503
504 return true;
505}
506
507} // namespace eve::animation
508
double y
double x
float duration
int root
Definition AnimSmr.cpp:119
const std::string & s
std::string name
Definition ECS.cpp:154
std::string message
double r
float v
const ColourScope * parent
std::array< float, 4 > rotation
std::uint32_t bone
MeleePoint3 b
Definition MeleeHit.cpp:41
std::string error
Definition Package.cpp:174
std::string path
Definition PlayHost.cpp:111
std::string text
Heightmap curve
uint32_t index
const VegetationPresetContext & context
EVENGINE_API_FOUNDATION public API.
Definition Exception.h:13
float getAnimationDuration(int index) const
Returns the animation duration.
int getSlotBone(int index) const
Returns the slot bone.
int getSkinCount() const
Returns the skin count.
float getBoneScaleX(int index) const
Returns the bone scale x.
bool loadFromFile(const std::string &path, std::string *error=nullptr)
Loads from file.
int findSkin(const std::string &name) const
Finds skin.
std::string getSkinName(int index) const
Returns the skin name.
bool loadFromJson(const std::string &json, std::string *error=nullptr)
Loads from json.
const RegionAttachment * findAttachment(int skinIndex, int slotIndex, const std::string &name) const
int getBoneParent(int index) const
Returns the bone parent.
float getBoneX(int index) const
Returns the bone x.
int findAnimation(const std::string &name) const
Finds animation.
float getBoneScaleY(int index) const
Returns the bone scale y.
std::string getSlotAttachment(int index) const
Returns the slot attachment.
int getBoneCount() const
Returns the bone count.
std::string getSlotName(int index) const
Returns the slot name.
int findSlot(const std::string &name) const
Finds slot.
std::string getBoneName(int index) const
Returns the bone name.
const SkinData & skin(int i) const
std::string getAnimationName(int index) const
Returns the animation name.
int getAnimationCount() const
Returns the animation count.
float getBoneRotation(int index) const
Returns the bone rotation.
int getSlotCount() const
Returns the slot count.
float getBoneY(int index) const
Returns the bone y.
int findBone(const std::string &name) const
Finds bone.