Animation.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. //
  2. // Copyright (c) 2008-2017 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 Atomic
  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. Atomic::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. Atomic::Sort(keyFrames_.Begin(), keyFrames_.End(), CompareKeyFrames);
  61. }
  62. void AnimationTrack::InsertKeyFrame(unsigned index, const AnimationKeyFrame& keyFrame)
  63. {
  64. keyFrames_.Insert(index, keyFrame);
  65. Atomic::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] : (AnimationKeyFrame*)0;
  78. }
  79. void AnimationTrack::GetKeyFrameIndex(float time, unsigned& index) const
  80. {
  81. if (time < 0.0f)
  82. time = 0.0f;
  83. if (index >= keyFrames_.Size())
  84. index = keyFrames_.Size() - 1;
  85. // Check for being too far ahead
  86. while (index && time < keyFrames_[index].time_)
  87. --index;
  88. // Check for being too far behind
  89. while (index < keyFrames_.Size() - 1 && time >= keyFrames_[index + 1].time_)
  90. ++index;
  91. }
  92. Animation::Animation(Context* context) :
  93. ResourceWithMetadata(context),
  94. length_(0.f)
  95. {
  96. }
  97. Animation::~Animation()
  98. {
  99. }
  100. void Animation::RegisterObject(Context* context)
  101. {
  102. context->RegisterFactory<Animation>();
  103. }
  104. bool Animation::BeginLoad(Deserializer& source)
  105. {
  106. unsigned memoryUse = sizeof(Animation);
  107. // Check ID
  108. if (source.ReadFileID() != "UANI")
  109. {
  110. ATOMIC_LOGERROR(source.GetName() + " is not a valid animation file");
  111. return false;
  112. }
  113. // Read name and length
  114. animationName_ = source.ReadString();
  115. animationNameHash_ = animationName_;
  116. length_ = source.ReadFloat();
  117. tracks_.Clear();
  118. unsigned tracks = source.ReadUInt();
  119. memoryUse += tracks * sizeof(AnimationTrack);
  120. // Read tracks
  121. for (unsigned i = 0; i < tracks; ++i)
  122. {
  123. AnimationTrack* newTrack = CreateTrack(source.ReadString());
  124. newTrack->channelMask_ = source.ReadUByte();
  125. unsigned keyFrames = source.ReadUInt();
  126. newTrack->keyFrames_.Resize(keyFrames);
  127. memoryUse += keyFrames * sizeof(AnimationKeyFrame);
  128. // Read keyframes of the track
  129. for (unsigned j = 0; j < keyFrames; ++j)
  130. {
  131. AnimationKeyFrame& newKeyFrame = newTrack->keyFrames_[j];
  132. newKeyFrame.time_ = source.ReadFloat();
  133. if (newTrack->channelMask_ & CHANNEL_POSITION)
  134. newKeyFrame.position_ = source.ReadVector3();
  135. if (newTrack->channelMask_ & CHANNEL_ROTATION)
  136. newKeyFrame.rotation_ = source.ReadQuaternion();
  137. if (newTrack->channelMask_ & CHANNEL_SCALE)
  138. newKeyFrame.scale_ = source.ReadVector3();
  139. }
  140. }
  141. // Optionally read triggers from an XML file
  142. ResourceCache* cache = GetSubsystem<ResourceCache>();
  143. String xmlName = ReplaceExtension(GetName(), ".xml");
  144. SharedPtr<XMLFile> file(cache->GetTempResource<XMLFile>(xmlName, false));
  145. if (file)
  146. {
  147. XMLElement rootElem = file->GetRoot();
  148. for (XMLElement triggerElem = rootElem.GetChild("trigger"); triggerElem; triggerElem = triggerElem.GetNext("trigger"))
  149. {
  150. if (triggerElem.HasAttribute("normalizedtime"))
  151. AddTrigger(triggerElem.GetFloat("normalizedtime"), true, triggerElem.GetVariant());
  152. else if (triggerElem.HasAttribute("time"))
  153. AddTrigger(triggerElem.GetFloat("time"), false, triggerElem.GetVariant());
  154. }
  155. LoadMetadataFromXML(rootElem);
  156. memoryUse += triggers_.Size() * sizeof(AnimationTriggerPoint);
  157. SetMemoryUse(memoryUse);
  158. return true;
  159. }
  160. // Optionally read triggers from a JSON file
  161. String jsonName = ReplaceExtension(GetName(), ".json");
  162. SharedPtr<JSONFile> jsonFile(cache->GetTempResource<JSONFile>(jsonName, false));
  163. if (jsonFile)
  164. {
  165. const JSONValue& rootVal = jsonFile->GetRoot();
  166. const JSONArray& triggerArray = rootVal.Get("triggers").GetArray();
  167. for (unsigned i = 0; i < triggerArray.Size(); i++)
  168. {
  169. const JSONValue& triggerValue = triggerArray.At(i);
  170. JSONValue normalizedTimeValue = triggerValue.Get("normalizedTime");
  171. if (!normalizedTimeValue.IsNull())
  172. AddTrigger(normalizedTimeValue.GetFloat(), true, triggerValue.GetVariant());
  173. else
  174. {
  175. JSONValue timeVal = triggerValue.Get("time");
  176. if (!timeVal.IsNull())
  177. AddTrigger(timeVal.GetFloat(), false, triggerValue.GetVariant());
  178. }
  179. }
  180. const JSONArray& metadataArray = rootVal.Get("metadata").GetArray();
  181. LoadMetadataFromJSON(metadataArray);
  182. memoryUse += triggers_.Size() * sizeof(AnimationTriggerPoint);
  183. SetMemoryUse(memoryUse);
  184. return true;
  185. }
  186. SetMemoryUse(memoryUse);
  187. return true;
  188. }
  189. bool Animation::Save(Serializer& dest) const
  190. {
  191. // Write ID, name and length
  192. dest.WriteFileID("UANI");
  193. dest.WriteString(animationName_);
  194. dest.WriteFloat(length_);
  195. // Write tracks
  196. dest.WriteUInt(tracks_.Size());
  197. for (HashMap<StringHash, AnimationTrack>::ConstIterator i = tracks_.Begin(); i != tracks_.End(); ++i)
  198. {
  199. const AnimationTrack& track = i->second_;
  200. dest.WriteString(track.name_);
  201. dest.WriteUByte(track.channelMask_);
  202. dest.WriteUInt(track.keyFrames_.Size());
  203. // Write keyframes of the track
  204. for (unsigned j = 0; j < track.keyFrames_.Size(); ++j)
  205. {
  206. const AnimationKeyFrame& keyFrame = track.keyFrames_[j];
  207. dest.WriteFloat(keyFrame.time_);
  208. if (track.channelMask_ & CHANNEL_POSITION)
  209. dest.WriteVector3(keyFrame.position_);
  210. if (track.channelMask_ & CHANNEL_ROTATION)
  211. dest.WriteQuaternion(keyFrame.rotation_);
  212. if (track.channelMask_ & CHANNEL_SCALE)
  213. dest.WriteVector3(keyFrame.scale_);
  214. }
  215. }
  216. // If triggers have been defined, write an XML file for them
  217. if (!triggers_.Empty() || HasMetadata())
  218. {
  219. File* destFile = dynamic_cast<File*>(&dest);
  220. if (destFile)
  221. {
  222. String xmlName = ReplaceExtension(destFile->GetName(), ".xml");
  223. SharedPtr<XMLFile> xml(new XMLFile(context_));
  224. XMLElement rootElem = xml->CreateRoot("animation");
  225. for (unsigned i = 0; i < triggers_.Size(); ++i)
  226. {
  227. XMLElement triggerElem = rootElem.CreateChild("trigger");
  228. triggerElem.SetFloat("time", triggers_[i].time_);
  229. triggerElem.SetVariant(triggers_[i].data_);
  230. }
  231. SaveMetadataToXML(rootElem);
  232. File xmlFile(context_, xmlName, FILE_WRITE);
  233. xml->Save(xmlFile);
  234. }
  235. else
  236. ATOMIC_LOGWARNING("Can not save animation trigger data when not saving into a file");
  237. }
  238. return true;
  239. }
  240. void Animation::SetAnimationName(const String& name)
  241. {
  242. animationName_ = name;
  243. animationNameHash_ = StringHash(name);
  244. }
  245. void Animation::SetLength(float length)
  246. {
  247. length_ = Max(length, 0.0f);
  248. }
  249. AnimationTrack* Animation::CreateTrack(const String& name)
  250. {
  251. /// \todo When tracks / keyframes are created dynamically, memory use is not updated
  252. StringHash nameHash(name);
  253. AnimationTrack* oldTrack = GetTrack(nameHash);
  254. if (oldTrack)
  255. return oldTrack;
  256. AnimationTrack& newTrack = tracks_[nameHash];
  257. newTrack.name_ = name;
  258. newTrack.nameHash_ = nameHash;
  259. return &newTrack;
  260. }
  261. bool Animation::RemoveTrack(const String& name)
  262. {
  263. HashMap<StringHash, AnimationTrack>::Iterator i = tracks_.Find(StringHash(name));
  264. if (i != tracks_.End())
  265. {
  266. tracks_.Erase(i);
  267. return true;
  268. }
  269. else
  270. return false;
  271. }
  272. void Animation::RemoveAllTracks()
  273. {
  274. tracks_.Clear();
  275. }
  276. void Animation::SetTrigger(unsigned index, const AnimationTriggerPoint& trigger)
  277. {
  278. if (index == triggers_.Size())
  279. AddTrigger(trigger);
  280. else if (index < triggers_.Size())
  281. {
  282. triggers_[index] = trigger;
  283. Sort(triggers_.Begin(), triggers_.End(), CompareTriggers);
  284. }
  285. }
  286. void Animation::AddTrigger(const AnimationTriggerPoint& trigger)
  287. {
  288. triggers_.Push(trigger);
  289. Sort(triggers_.Begin(), triggers_.End(), CompareTriggers);
  290. }
  291. void Animation::AddTrigger(float time, bool timeIsNormalized, const Variant& data)
  292. {
  293. AnimationTriggerPoint newTrigger;
  294. newTrigger.time_ = timeIsNormalized ? time * length_ : time;
  295. newTrigger.data_ = data;
  296. triggers_.Push(newTrigger);
  297. Sort(triggers_.Begin(), triggers_.End(), CompareTriggers);
  298. }
  299. void Animation::RemoveTrigger(unsigned index)
  300. {
  301. if (index < triggers_.Size())
  302. triggers_.Erase(index);
  303. }
  304. void Animation::RemoveAllTriggers()
  305. {
  306. triggers_.Clear();
  307. }
  308. void Animation::SetNumTriggers(unsigned num)
  309. {
  310. triggers_.Resize(num);
  311. }
  312. SharedPtr<Animation> Animation::Clone(const String& cloneName) const
  313. {
  314. SharedPtr<Animation> ret(new Animation(context_));
  315. ret->SetName(cloneName);
  316. ret->SetAnimationName(animationName_);
  317. ret->length_ = length_;
  318. ret->tracks_ = tracks_;
  319. ret->triggers_ = triggers_;
  320. ret->CopyMetadata(*this);
  321. ret->SetMemoryUse(GetMemoryUse());
  322. return ret;
  323. }
  324. AnimationTrack* Animation::GetTrack(unsigned index)
  325. {
  326. if (index >= GetNumTracks())
  327. return (AnimationTrack*) 0;
  328. int j = 0;
  329. for(HashMap<StringHash, AnimationTrack>::Iterator i = tracks_.Begin(); i != tracks_.End(); ++i)
  330. {
  331. if (j == index)
  332. return &i->second_;
  333. ++j;
  334. }
  335. return (AnimationTrack*) 0;
  336. }
  337. AnimationTrack* Animation::GetTrack(const String& name)
  338. {
  339. HashMap<StringHash, AnimationTrack>::Iterator i = tracks_.Find(StringHash(name));
  340. return i != tracks_.End() ? &i->second_ : (AnimationTrack*)0;
  341. }
  342. AnimationTrack* Animation::GetTrack(StringHash nameHash)
  343. {
  344. HashMap<StringHash, AnimationTrack>::Iterator i = tracks_.Find(nameHash);
  345. return i != tracks_.End() ? &i->second_ : (AnimationTrack*)0;
  346. }
  347. AnimationTriggerPoint* Animation::GetTrigger(unsigned index)
  348. {
  349. return index < triggers_.Size() ? &triggers_[index] : (AnimationTriggerPoint*)0;
  350. }
  351. // ATOMIC BEGIN
  352. /// Set all animation tracks.
  353. void Animation::SetTracks(const Vector<AnimationTrack>& tracks)
  354. {
  355. tracks_.Clear();
  356. for (Vector<AnimationTrack>::ConstIterator itr = tracks.Begin(); itr != tracks.End(); itr++)
  357. {
  358. tracks_[itr->name_] = *itr;
  359. }
  360. }
  361. // ATOMIC END
  362. }