Animation.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. // Copyright (c) 2008-2023 the Urho3D project
  2. // License: MIT
  3. #include "../Precompiled.h"
  4. #include "../Base/Utils.h"
  5. #include "../Container/Sort.h"
  6. #include "../Core/Context.h"
  7. #include "../Core/Profiler.h"
  8. #include "../Graphics/Animation.h"
  9. #include "../IO/Deserializer.h"
  10. #include "../IO/FileSystem.h"
  11. #include "../IO/Log.h"
  12. #include "../IO/Serializer.h"
  13. #include "../Resource/JSONFile.h"
  14. #include "../Resource/ResourceCache.h"
  15. #include "../Resource/XMLFile.h"
  16. #include "../DebugNew.h"
  17. namespace Urho3D
  18. {
  19. inline bool CompareTriggers(AnimationTriggerPoint& lhs, AnimationTriggerPoint& rhs)
  20. {
  21. return lhs.time_ < rhs.time_;
  22. }
  23. inline bool CompareKeyFrames(AnimationKeyFrame& lhs, AnimationKeyFrame& rhs)
  24. {
  25. return lhs.time_ < rhs.time_;
  26. }
  27. void AnimationTrack::SetKeyFrame(i32 index, const AnimationKeyFrame& keyFrame)
  28. {
  29. assert(index >= 0);
  30. if (index < keyFrames_.Size())
  31. {
  32. keyFrames_[index] = keyFrame;
  33. Urho3D::Sort(keyFrames_.Begin(), keyFrames_.End(), CompareKeyFrames);
  34. }
  35. else if (index == keyFrames_.Size())
  36. AddKeyFrame(keyFrame);
  37. }
  38. void AnimationTrack::AddKeyFrame(const AnimationKeyFrame& keyFrame)
  39. {
  40. bool needSort = keyFrames_.Size() ? keyFrames_.Back().time_ > keyFrame.time_ : false;
  41. keyFrames_.Push(keyFrame);
  42. if (needSort)
  43. Urho3D::Sort(keyFrames_.Begin(), keyFrames_.End(), CompareKeyFrames);
  44. }
  45. void AnimationTrack::InsertKeyFrame(i32 index, const AnimationKeyFrame& keyFrame)
  46. {
  47. assert(index >= 0);
  48. keyFrames_.Insert(index, keyFrame);
  49. Urho3D::Sort(keyFrames_.Begin(), keyFrames_.End(), CompareKeyFrames);
  50. }
  51. void AnimationTrack::RemoveKeyFrame(i32 index)
  52. {
  53. assert(index >= 0);
  54. keyFrames_.Erase(index);
  55. }
  56. void AnimationTrack::RemoveAllKeyFrames()
  57. {
  58. keyFrames_.Clear();
  59. }
  60. AnimationKeyFrame* AnimationTrack::GetKeyFrame(i32 index)
  61. {
  62. assert(index >= 0);
  63. return index < keyFrames_.Size() ? &keyFrames_[index] : nullptr;
  64. }
  65. bool AnimationTrack::GetKeyFrameIndex(float time, i32& index) const
  66. {
  67. if (keyFrames_.Empty())
  68. return false;
  69. if (time < 0.0f)
  70. time = 0.0f;
  71. if (index >= keyFrames_.Size())
  72. index = keyFrames_.Size() - 1;
  73. // Check for being too far ahead
  74. while (index && time < keyFrames_[index].time_)
  75. --index;
  76. // Check for being too far behind
  77. while (index < keyFrames_.Size() - 1 && time >= keyFrames_[index + 1].time_)
  78. ++index;
  79. return true;
  80. }
  81. Animation::Animation(Context* context) :
  82. ResourceWithMetadata(context),
  83. length_(0.f)
  84. {
  85. }
  86. Animation::~Animation() = default;
  87. void Animation::RegisterObject(Context* context)
  88. {
  89. context->RegisterFactory<Animation>();
  90. }
  91. bool Animation::BeginLoad(Deserializer& source)
  92. {
  93. unsigned memoryUse = sizeof(Animation);
  94. // Check ID
  95. if (source.ReadFileID() != "UANI")
  96. {
  97. URHO3D_LOGERROR(source.GetName() + " is not a valid animation file");
  98. return false;
  99. }
  100. // Read name and length
  101. animationName_ = source.ReadString();
  102. animationNameHash_ = animationName_;
  103. length_ = source.ReadFloat();
  104. tracks_.Clear();
  105. unsigned tracks = source.ReadU32();
  106. memoryUse += tracks * sizeof(AnimationTrack);
  107. // Read tracks
  108. for (unsigned i = 0; i < tracks; ++i)
  109. {
  110. AnimationTrack* newTrack = CreateTrack(source.ReadString());
  111. newTrack->channelMask_ = AnimationChannels(source.ReadU8());
  112. unsigned keyFrames = source.ReadU32();
  113. newTrack->keyFrames_.Resize(keyFrames);
  114. memoryUse += keyFrames * sizeof(AnimationKeyFrame);
  115. // Read keyframes of the track
  116. for (unsigned j = 0; j < keyFrames; ++j)
  117. {
  118. AnimationKeyFrame& newKeyFrame = newTrack->keyFrames_[j];
  119. newKeyFrame.time_ = source.ReadFloat();
  120. if (!!(newTrack->channelMask_ & AnimationChannels::Position))
  121. newKeyFrame.position_ = source.ReadVector3();
  122. if (!!(newTrack->channelMask_ & AnimationChannels::Rotation))
  123. newKeyFrame.rotation_ = source.ReadQuaternion();
  124. if (!!(newTrack->channelMask_ & AnimationChannels::Scale))
  125. newKeyFrame.scale_ = source.ReadVector3();
  126. }
  127. }
  128. // Optionally read triggers from an XML file
  129. ResourceCache* cache = GetSubsystem<ResourceCache>();
  130. String xmlName = ReplaceExtension(GetName(), ".xml");
  131. SharedPtr<XMLFile> file(cache->GetTempResource<XMLFile>(xmlName, false));
  132. if (file)
  133. {
  134. XMLElement rootElem = file->GetRoot();
  135. for (XMLElement triggerElem = rootElem.GetChild("trigger"); triggerElem; triggerElem = triggerElem.GetNext("trigger"))
  136. {
  137. if (triggerElem.HasAttribute("normalizedtime"))
  138. AddTrigger(triggerElem.GetFloat("normalizedtime"), true, triggerElem.GetVariant());
  139. else if (triggerElem.HasAttribute("time"))
  140. AddTrigger(triggerElem.GetFloat("time"), false, triggerElem.GetVariant());
  141. }
  142. LoadMetadataFromXML(rootElem);
  143. memoryUse += triggers_.Size() * sizeof(AnimationTriggerPoint);
  144. SetMemoryUse(memoryUse);
  145. return true;
  146. }
  147. // Optionally read triggers from a JSON file
  148. String jsonName = ReplaceExtension(GetName(), ".json");
  149. SharedPtr<JSONFile> jsonFile(cache->GetTempResource<JSONFile>(jsonName, false));
  150. if (jsonFile)
  151. {
  152. const JSONValue& rootVal = jsonFile->GetRoot();
  153. const JSONArray& triggerArray = rootVal.Get("triggers").GetArray();
  154. for (const JSONValue& triggerValue : triggerArray)
  155. {
  156. JSONValue normalizedTimeValue = triggerValue.Get("normalizedTime");
  157. if (!normalizedTimeValue.IsNull())
  158. AddTrigger(normalizedTimeValue.GetFloat(), true, triggerValue.GetVariant());
  159. else
  160. {
  161. JSONValue timeVal = triggerValue.Get("time");
  162. if (!timeVal.IsNull())
  163. AddTrigger(timeVal.GetFloat(), false, triggerValue.GetVariant());
  164. }
  165. }
  166. const JSONArray& metadataArray = rootVal.Get("metadata").GetArray();
  167. LoadMetadataFromJSON(metadataArray);
  168. memoryUse += triggers_.Size() * sizeof(AnimationTriggerPoint);
  169. SetMemoryUse(memoryUse);
  170. return true;
  171. }
  172. SetMemoryUse(memoryUse);
  173. return true;
  174. }
  175. bool Animation::Save(Serializer& dest) const
  176. {
  177. // Write ID, name and length
  178. dest.WriteFileID("UANI");
  179. dest.WriteString(animationName_);
  180. dest.WriteFloat(length_);
  181. // Write tracks
  182. dest.WriteU32(tracks_.Size());
  183. for (HashMap<StringHash, AnimationTrack>::ConstIterator i = tracks_.Begin(); i != tracks_.End(); ++i)
  184. {
  185. const AnimationTrack& track = i->second_;
  186. dest.WriteString(track.name_);
  187. dest.WriteU8(ToU8(track.channelMask_));
  188. dest.WriteU32(track.keyFrames_.Size());
  189. // Write keyframes of the track
  190. for (const AnimationKeyFrame& keyFrame : track.keyFrames_)
  191. {
  192. dest.WriteFloat(keyFrame.time_);
  193. if (!!(track.channelMask_ & AnimationChannels::Position))
  194. dest.WriteVector3(keyFrame.position_);
  195. if (!!(track.channelMask_ & AnimationChannels::Rotation))
  196. dest.WriteQuaternion(keyFrame.rotation_);
  197. if (!!(track.channelMask_ & AnimationChannels::Scale))
  198. dest.WriteVector3(keyFrame.scale_);
  199. }
  200. }
  201. // If triggers have been defined, write an XML file for them
  202. if (!triggers_.Empty() || HasMetadata())
  203. {
  204. File* destFile = dynamic_cast<File*>(&dest);
  205. if (destFile)
  206. {
  207. String xmlName = ReplaceExtension(destFile->GetName(), ".xml");
  208. SharedPtr<XMLFile> xml(new XMLFile(context_));
  209. XMLElement rootElem = xml->CreateRoot("animation");
  210. for (const AnimationTriggerPoint& trigger : triggers_)
  211. {
  212. XMLElement triggerElem = rootElem.CreateChild("trigger");
  213. triggerElem.SetFloat("time", trigger.time_);
  214. triggerElem.SetVariant(trigger.data_);
  215. }
  216. SaveMetadataToXML(rootElem);
  217. File xmlFile(context_, xmlName, FILE_WRITE);
  218. xml->Save(xmlFile);
  219. }
  220. else
  221. URHO3D_LOGWARNING("Can not save animation trigger data when not saving into a file");
  222. }
  223. return true;
  224. }
  225. void Animation::SetAnimationName(const String& name)
  226. {
  227. animationName_ = name;
  228. animationNameHash_ = StringHash(name);
  229. }
  230. void Animation::SetLength(float length)
  231. {
  232. length_ = Max(length, 0.0f);
  233. }
  234. AnimationTrack* Animation::CreateTrack(const String& name)
  235. {
  236. /// \todo When tracks / keyframes are created dynamically, memory use is not updated
  237. StringHash nameHash(name);
  238. AnimationTrack* oldTrack = GetTrack(nameHash);
  239. if (oldTrack)
  240. return oldTrack;
  241. AnimationTrack& newTrack = tracks_[nameHash];
  242. newTrack.name_ = name;
  243. newTrack.nameHash_ = nameHash;
  244. return &newTrack;
  245. }
  246. bool Animation::RemoveTrack(const String& name)
  247. {
  248. HashMap<StringHash, AnimationTrack>::Iterator i = tracks_.Find(StringHash(name));
  249. if (i != tracks_.End())
  250. {
  251. tracks_.Erase(i);
  252. return true;
  253. }
  254. else
  255. return false;
  256. }
  257. void Animation::RemoveAllTracks()
  258. {
  259. tracks_.Clear();
  260. }
  261. void Animation::SetTrigger(i32 index, const AnimationTriggerPoint& trigger)
  262. {
  263. assert(index >= 0);
  264. if (index == triggers_.Size())
  265. AddTrigger(trigger);
  266. else if (index < triggers_.Size())
  267. {
  268. triggers_[index] = trigger;
  269. Sort(triggers_.Begin(), triggers_.End(), CompareTriggers);
  270. }
  271. }
  272. void Animation::AddTrigger(const AnimationTriggerPoint& trigger)
  273. {
  274. triggers_.Push(trigger);
  275. Sort(triggers_.Begin(), triggers_.End(), CompareTriggers);
  276. }
  277. void Animation::AddTrigger(float time, bool timeIsNormalized, const Variant& data)
  278. {
  279. AnimationTriggerPoint newTrigger;
  280. newTrigger.time_ = timeIsNormalized ? time * length_ : time;
  281. newTrigger.data_ = data;
  282. triggers_.Push(newTrigger);
  283. Sort(triggers_.Begin(), triggers_.End(), CompareTriggers);
  284. }
  285. void Animation::RemoveTrigger(i32 index)
  286. {
  287. assert(index >= 0);
  288. if (index < triggers_.Size())
  289. triggers_.Erase(index);
  290. }
  291. void Animation::RemoveAllTriggers()
  292. {
  293. triggers_.Clear();
  294. }
  295. void Animation::SetNumTriggers(i32 num)
  296. {
  297. assert(num >= 0);
  298. triggers_.Resize(num);
  299. }
  300. SharedPtr<Animation> Animation::Clone(const String& cloneName) const
  301. {
  302. SharedPtr<Animation> ret(new Animation(context_));
  303. ret->SetName(cloneName);
  304. ret->SetAnimationName(animationName_);
  305. ret->length_ = length_;
  306. ret->tracks_ = tracks_;
  307. ret->triggers_ = triggers_;
  308. ret->CopyMetadata(*this);
  309. ret->SetMemoryUse(GetMemoryUse());
  310. return ret;
  311. }
  312. AnimationTrack* Animation::GetTrack(i32 index)
  313. {
  314. assert(index >= 0);
  315. if (index >= GetNumTracks())
  316. return nullptr;
  317. int j = 0;
  318. for(HashMap<StringHash, AnimationTrack>::Iterator i = tracks_.Begin(); i != tracks_.End(); ++i)
  319. {
  320. if (j == index)
  321. return &i->second_;
  322. ++j;
  323. }
  324. return nullptr;
  325. }
  326. AnimationTrack* Animation::GetTrack(const String& name)
  327. {
  328. HashMap<StringHash, AnimationTrack>::Iterator i = tracks_.Find(StringHash(name));
  329. return i != tracks_.End() ? &i->second_ : nullptr;
  330. }
  331. AnimationTrack* Animation::GetTrack(StringHash nameHash)
  332. {
  333. HashMap<StringHash, AnimationTrack>::Iterator i = tracks_.Find(nameHash);
  334. return i != tracks_.End() ? &i->second_ : nullptr;
  335. }
  336. AnimationTriggerPoint* Animation::GetTrigger(i32 index)
  337. {
  338. assert(index >= 0);
  339. return index < triggers_.Size() ? &triggers_[index] : nullptr;
  340. }
  341. }