Animation.cpp 13 KB

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