AnimatedModel.cpp 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "AnimatedModel.h"
  25. #include "Animation.h"
  26. #include "AnimationState.h"
  27. #include "Camera.h"
  28. #include "DebugRenderer.h"
  29. #include "Geometry.h"
  30. #include "IndexBuffer.h"
  31. #include "Log.h"
  32. #include "Material.h"
  33. #include "Octree.h"
  34. #include "OctreeQuery.h"
  35. #include "Profiler.h"
  36. #include "Renderer.h"
  37. #include "ReplicationUtils.h"
  38. #include "ResourceCache.h"
  39. #include "Scene.h"
  40. #include "VertexBuffer.h"
  41. #include <algorithm>
  42. #include "DebugNew.h"
  43. static bool compareAnimationOrder(AnimationState* lhs, AnimationState* rhs)
  44. {
  45. return lhs->getPriority() < rhs->getPriority();
  46. }
  47. AnimatedModel::AnimatedModel(Octant* octant, const std::string& name) :
  48. StaticModel(NODE_ANIMATEDMODEL, octant, name),
  49. mAnimationLodDistance(0.0f),
  50. mAnimationLodFrameNumber(M_MAX_UNSIGNED),
  51. mAnimationLodBias(1.0f),
  52. mAnimationLodTimer(0.0f),
  53. mAnimationDirty(true),
  54. mAnimationOrderDirty(true),
  55. mMorphsDirty(true),
  56. mLocalAnimation(false)
  57. {
  58. }
  59. AnimatedModel::~AnimatedModel()
  60. {
  61. removeAllAnimationStates();
  62. }
  63. void AnimatedModel::save(Serializer& dest)
  64. {
  65. // Write GeometryNode properties
  66. GeometryNode::save(dest);
  67. // Write StaticModel properties
  68. dest.writeStringHash(getResourceHash(mModel));
  69. dest.writeVLE(mMaterials.size());
  70. for (unsigned i = 0; i < mMaterials.size(); ++i)
  71. dest.writeStringHash(getResourceHash(mMaterials[i]));
  72. // Write skeletal animation properties
  73. dest.writeFloat(mAnimationLodBias);
  74. // If this is the predicted component save, and local animation is enabled, do not store animation data
  75. bool localAnimation = (isProxy()) && (mLocalAnimation) && (checkPrediction());
  76. if (!localAnimation)
  77. {
  78. dest.writeVLE(mAnimationStates.size());
  79. for (unsigned i = 0; i < mAnimationStates.size(); ++i)
  80. {
  81. AnimationState* state = mAnimationStates[i];
  82. state->save(dest);
  83. }
  84. // Write morph properties
  85. dest.writeVLE(mMorphs.size());
  86. for (unsigned i = 0; i < mMorphs.size(); ++i)
  87. dest.writeFloat(mMorphs[i].mWeight);
  88. }
  89. else
  90. {
  91. dest.writeVLE(0);
  92. dest.writeVLE(0);
  93. }
  94. }
  95. void AnimatedModel::load(Deserializer& source, ResourceCache* cache)
  96. {
  97. // Read GeometryNode properties
  98. GeometryNode::load(source, cache);
  99. // Read StaticModel properties
  100. // Note: can not use StaticModel::load() because we need to set the skeleton
  101. setModel(cache->getResource<Model>(source.readStringHash()));
  102. unsigned numMaterials = source.readVLE();
  103. for (unsigned i = 0; i < numMaterials; ++i)
  104. setMaterial(i, cache->getResource<Material>(source.readStringHash()));
  105. // Read skeletal animation properties
  106. // If this is the predicted component load, and local animation is enabled, do not overwrite the animations
  107. bool localAnimation = (isProxy()) && (mLocalAnimation) && (checkPrediction());
  108. mAnimationLodBias = source.readFloat();
  109. std::set<StringHash> processed;
  110. unsigned numAnimationStates = source.readVLE();
  111. for (unsigned i = 0; i < numAnimationStates; ++i)
  112. {
  113. StringHash animation = source.readStringHash();
  114. AnimationState* newState = addAnimationState(cache->getResource<Animation>(animation));
  115. newState->load(source);
  116. processed.insert(animation);
  117. }
  118. if (!localAnimation)
  119. removeExtraAnimations(processed);
  120. // Read morph properties
  121. unsigned numMorphs = source.readVLE();
  122. for (unsigned i = 0; i < numMorphs; ++i)
  123. setMorphWeight(i, source.readFloat());
  124. }
  125. void AnimatedModel::saveXML(XMLElement& dest)
  126. {
  127. // Write GeometryNode properties
  128. GeometryNode::saveXML(dest);
  129. // Write StaticModel properties
  130. XMLElement modelElem = dest.createChildElement("model");
  131. modelElem.setString("name", getResourceName(mModel));
  132. for (unsigned i = 0; i < mMaterials.size(); ++i)
  133. {
  134. XMLElement materialElem = dest.createChildElement("material");
  135. materialElem.setInt("index", i);
  136. materialElem.setString("name", getResourceName(mMaterials[i]));
  137. }
  138. // Write skeletal animation properties
  139. XMLElement lodElem = dest.getChildElement("lod");
  140. lodElem.setFloat("animlodbias", mAnimationLodBias);
  141. for (unsigned i = 0; i < mAnimationStates.size(); ++i)
  142. {
  143. XMLElement animationElem = dest.createChildElement("animation");
  144. mAnimationStates[i]->saveXML(animationElem);
  145. }
  146. // Write morph properties
  147. for (unsigned i = 0; i < mMorphs.size(); ++i)
  148. {
  149. XMLElement morphElem = dest.createChildElement("morph");
  150. morphElem.setInt("index", i);
  151. morphElem.setFloat("weight", mMorphs[i].mWeight);
  152. }
  153. }
  154. void AnimatedModel::loadXML(const XMLElement& source, ResourceCache* cache)
  155. {
  156. // Read GeometryNode properties
  157. GeometryNode::loadXML(source, cache);
  158. // Read StaticModel properties
  159. // Note: can not use StaticModel::loadXML() because we need to set the skeleton
  160. XMLElement modelElem = source.getChildElement("model");
  161. setModel(cache->getResource<Model>(modelElem.getString("name")));
  162. XMLElement materialElem = source.getChildElement("material");
  163. while (materialElem)
  164. {
  165. unsigned index = materialElem.getInt("index");
  166. setMaterial(index, cache->getResource<Material>(materialElem.getString("name")));
  167. materialElem = materialElem.getNextElement("material");
  168. }
  169. // Read skeletal animation properties
  170. XMLElement lodElem = source.getChildElement("lod");
  171. mAnimationLodBias = lodElem.getFloat("animlodbias");
  172. removeAllAnimationStates();
  173. XMLElement animationElem = source.getChildElement("animation");
  174. while (animationElem)
  175. {
  176. AnimationState* newState = addAnimationState(cache->getResource<Animation>(animationElem.getString("name")));
  177. newState->loadXML(animationElem);
  178. animationElem = animationElem.getNextElement("animation");
  179. }
  180. // Read morph properties
  181. XMLElement morphElem = source.getChildElement("morph");
  182. while (morphElem)
  183. {
  184. unsigned index = morphElem.getInt("index");
  185. setMorphWeight(index, morphElem.getFloat("weight"));
  186. morphElem = morphElem.getNextElement("morph");
  187. }
  188. }
  189. bool AnimatedModel::writeNetUpdate(Serializer& dest, Serializer& destRevision, Deserializer& baseRevision, const NetUpdateInfo& info)
  190. {
  191. // Write GeometryNode properties and see if there were any changes
  192. bool prevBits = GeometryNode::writeNetUpdate(dest, destRevision, baseRevision, info);
  193. // Build bitmask of changed properties
  194. unsigned char bits = 0;
  195. // Model
  196. checkStringHash(getResourceHash(mModel), baseRevision, bits, 1);
  197. // Materials
  198. unsigned numBaseMaterials = baseRevision.getSize() ? baseRevision.readVLE() : 0;
  199. if (mMaterials.size() != numBaseMaterials)
  200. bits |= 2;
  201. for (unsigned i = 0; i < numBaseMaterials; ++i)
  202. {
  203. if (i < mMaterials.size())
  204. checkStringHash(getResourceHash(mMaterials[i]), baseRevision, bits, 2);
  205. else
  206. baseRevision.readStringHash();
  207. }
  208. // Animation LOD bias
  209. checkFloat(mAnimationLodBias, baseRevision, bits, 4);
  210. // Animations
  211. unsigned numBaseAnimations = baseRevision.getSize() ? baseRevision.readVLE() : 0;
  212. if (mAnimationStates.size() != numBaseAnimations)
  213. bits |= 8;
  214. static std::vector<unsigned char> animBits;
  215. animBits.resize(mAnimationStates.size());
  216. // Assume that animations are new ie. require update of all fields
  217. for (unsigned i = 0; i < mAnimationStates.size(); ++i)
  218. animBits[i] = 1 | 2 | 4 | 8 | 16 | 32;
  219. for (unsigned i = 0; i < numBaseAnimations; ++i)
  220. {
  221. StringHash animation = baseRevision.readStringHash();
  222. StringHash startBone = baseRevision.readStringHash();
  223. bool looped = baseRevision.readBool();
  224. float weight = baseRevision.readFloat();
  225. float time = baseRevision.readFloat();
  226. int priority = baseRevision.readUByte();
  227. bool useNlerp = baseRevision.readBool();
  228. bool found = false;
  229. for (unsigned j = 0; j < mAnimationStates.size(); ++j)
  230. {
  231. AnimationState* state = mAnimationStates[j];
  232. if (state->getAnimation()->getNameHash() == animation)
  233. {
  234. // If animation exists in base state, update only the necessary properties
  235. found = true;
  236. animBits[j] = 0;
  237. if (startBone != state->getStartBone()->getNameHash())
  238. animBits[j] |= 1;
  239. if (looped != state->isLooped())
  240. animBits[j] |= 2;
  241. if (weight != state->getWeight())
  242. animBits[j] |= 4;
  243. if (time != state->getTime())
  244. animBits[j] |= 8;
  245. if (priority != state->getPriority())
  246. animBits[j] |= 16;
  247. if (useNlerp != state->getUseNlerp())
  248. animBits[j] |= 32;
  249. if (animBits[j])
  250. bits |= 8;
  251. break;
  252. }
  253. }
  254. // If not found, the number of animations has stayed same, but the animations are different
  255. if (!found)
  256. bits |= 8;
  257. }
  258. // Morphs
  259. unsigned numBaseMorphs = baseRevision.getSize() ? baseRevision.readVLE() : 0;
  260. if (mMorphs.size() != numBaseMorphs)
  261. bits |= 16;
  262. for (unsigned i = 0; i < numBaseMorphs; ++i)
  263. {
  264. if (i < mMorphs.size())
  265. checkUByte((unsigned char)(mMorphs[i].mWeight * 255.0f), baseRevision, bits, 16);
  266. else
  267. baseRevision.readUByte();
  268. }
  269. // Local animation flag
  270. checkBool(mLocalAnimation, false, baseRevision, bits, 32);
  271. // If local animation, do not send even if changed. It is slightly unoptimal to first check, then disable, but it ensures
  272. // that the base revision data stays the same (otherwise out of bounds reads might result when toggling local animation)
  273. if ((mLocalAnimation) && (checkPrediction(info.mConnection)))
  274. bits &= ~(8 | 16);
  275. // Update replication state fully, and network stream by delta
  276. dest.writeUByte(bits);
  277. writeStringHashDelta(getResourceHash(mModel), dest, destRevision, bits & 1);
  278. writeVLEDelta(mMaterials.size(), dest, destRevision, bits & 2);
  279. for (unsigned i = 0; i < mMaterials.size(); ++i)
  280. writeStringHashDelta(getResourceHash(mMaterials[i]), dest, destRevision, bits & 2);
  281. writeFloatDelta(mAnimationLodBias, dest, destRevision, bits & 4);
  282. // Write all animations to the base replication state
  283. destRevision.writeVLE(mAnimationStates.size());
  284. for (unsigned i = 0; i < mAnimationStates.size(); ++i)
  285. {
  286. AnimationState* state = mAnimationStates[i];
  287. destRevision.writeStringHash(state->getAnimation()->getNameHash());
  288. destRevision.writeStringHash(state->getStartBone()->getNameHash());
  289. destRevision.writeBool(state->isLooped());
  290. destRevision.writeFloat(state->getWeight());
  291. destRevision.writeFloat(state->getTime());
  292. destRevision.writeUByte(state->getPriority());
  293. destRevision.writeBool(state->getUseNlerp());
  294. }
  295. // Then write delta of animations to the net stream
  296. if (bits & 8)
  297. {
  298. dest.writeVLE(mAnimationStates.size());
  299. for (unsigned i = 0; i < mAnimationStates.size(); ++i)
  300. {
  301. AnimationState* state = mAnimationStates[i];
  302. dest.writeStringHash(state->getAnimation()->getNameHash());
  303. dest.writeUByte(animBits[i]);
  304. if (animBits[i] & 1)
  305. dest.writeStringHash(state->getStartBone()->getNameHash());
  306. if (animBits[i] & 2)
  307. dest.writeBool(state->isLooped());
  308. if (animBits[i] & 4)
  309. dest.writeUByte((unsigned char)(state->getWeight() * 255.0f));
  310. if (animBits[i] & 8)
  311. dest.writeUShort((unsigned short)(state->getTime() * 65535.0f / state->getAnimation()->getLength()));
  312. if (animBits[i] & 16)
  313. dest.writeUByte(state->getPriority());
  314. if (animBits[i] & 32)
  315. dest.writeBool(state->getUseNlerp());
  316. }
  317. }
  318. writeVLEDelta(mMorphs.size(), dest, destRevision, bits & 16);
  319. for (unsigned i = 0; i < mMorphs.size(); ++i)
  320. writeUByteDelta((unsigned char)(mMorphs[i].mWeight * 255.0f), dest, destRevision, bits & 16);
  321. writeBoolDelta(mLocalAnimation, dest, destRevision, bits & 32);
  322. return prevBits || (bits != 0);
  323. }
  324. void AnimatedModel::readNetUpdate(Deserializer& source, ResourceCache* cache, const NetUpdateInfo& info)
  325. {
  326. // Read GeometryNode properties
  327. GeometryNode::readNetUpdate(source, cache, info);
  328. unsigned char bits = source.readUByte();
  329. if (bits & 1)
  330. setModel(cache->getResource<Model>(source.readStringHash()));
  331. if (bits & 2)
  332. {
  333. unsigned numMaterials = source.readVLE();
  334. for (unsigned i = 0; i < numMaterials; ++i)
  335. setMaterial(i, cache->getResource<Material>(source.readStringHash()));
  336. }
  337. readFloatDelta(mAnimationLodBias, source, bits & 4);
  338. if (bits & 8)
  339. {
  340. unsigned numAnimations = source.readVLE();
  341. std::set<StringHash> processed;
  342. for (unsigned i = 0; i < numAnimations; ++i)
  343. {
  344. StringHash animation = source.readStringHash();
  345. unsigned char animBits = source.readUByte();
  346. processed.insert(animation);
  347. // Find the animation state. If not found, create new
  348. AnimationState* state = getAnimationState(animation);
  349. bool newState = false;
  350. if (!state)
  351. {
  352. state = addAnimationState(cache->getResource<Animation>(animation));
  353. newState = true;
  354. }
  355. if (state)
  356. {
  357. if (animBits & 1)
  358. state->setStartBone(mSkeleton.getBone(source.readStringHash()));
  359. if (animBits & 2)
  360. state->setLooped(source.readBool());
  361. if (animBits & 4)
  362. state->setWeight(source.readUByte() / 255.0f);
  363. if (animBits & 8)
  364. state->setTime(source.readUShort() * state->getAnimation()->getLength() / 65535.0f);
  365. if (animBits & 16)
  366. state->setPriority(source.readUByte());
  367. if (animBits & 32)
  368. state->setUseNlerp(source.readBool());
  369. // If state is new, interpolate directly to the end
  370. if (newState)
  371. state->interpolate(true, mEntity->getScene()->getInterpolationLerpFactor());
  372. }
  373. else
  374. {
  375. // If state could not be added, just read the data to avoid desyncing the stream
  376. if (animBits & 1)
  377. source.readStringHash();
  378. if (animBits & 2)
  379. source.readBool();
  380. if (animBits & 4)
  381. source.readUByte();
  382. if (animBits & 8)
  383. source.readUShort();
  384. if (animBits & 16)
  385. source.readUByte();
  386. if (animBits & 32)
  387. source.readBool();
  388. }
  389. }
  390. removeExtraAnimations(processed);
  391. }
  392. if (bits & 16)
  393. {
  394. unsigned numMorphs = source.readVLE();
  395. for (unsigned i = 0; i < numMorphs; ++i)
  396. setMorphWeight(i, source.readUByte() / 255.0f);
  397. }
  398. if (bits & 32)
  399. mLocalAnimation = source.readBool();
  400. }
  401. void AnimatedModel::interpolate(bool snapToEnd)
  402. {
  403. Node::interpolate(snapToEnd);
  404. float t = mEntity->getScene()->getInterpolationLerpFactor();
  405. for (std::vector<AnimationState*>::iterator i = mAnimationStates.begin(); i != mAnimationStates.end(); ++i)
  406. (*i)->interpolate(snapToEnd, t);
  407. }
  408. void AnimatedModel::processRayQuery(RayOctreeQuery& query, float initialDistance)
  409. {
  410. // If no bones or no bone-level testing, use the GeometryNode test
  411. if ((!mSkeleton.getNumBones()) || (query.mLevel < RAY_AABB))
  412. {
  413. GeometryNode::processRayQuery(query, initialDistance);
  414. return;
  415. }
  416. PROFILE(AnimatedModel_Raycast);
  417. const std::vector<SharedPtr<Bone> >& bones = mSkeleton.getBones();
  418. Sphere boneSphere;
  419. RayQueryLevel level = query.mLevel;
  420. for (unsigned i = 0; i < bones.size(); ++i)
  421. {
  422. Bone* bone = bones[i];
  423. unsigned collisionMask = bone->getCollisionMask();
  424. // Use hitbox if available
  425. if (collisionMask & BONECOLLISION_BOX)
  426. {
  427. // Do an initial crude test using the bone's AABB
  428. const Matrix4x3& transform = bone->getWorldTransform();
  429. const BoundingBox& box = bone->getBoundingBox();
  430. float distance = box.getTransformed(transform).getDistance(query.mRay);
  431. if (distance < query.mMaxDistance)
  432. {
  433. if (level == RAY_AABB)
  434. {
  435. RayQueryResult result;
  436. result.mNode = this;
  437. result.mDistance = distance;
  438. result.mSubObject = i;
  439. query.mResult.push_back(result);
  440. }
  441. else
  442. {
  443. // Follow with an OBB test if required
  444. Matrix4x3 inverse = transform.getInverse();
  445. Ray localRay(inverse * query.mRay.mOrigin, inverse * Vector4(query.mRay.mDirection, 0.0f));
  446. distance = box.getDistance(localRay);
  447. if (distance < query.mMaxDistance)
  448. {
  449. RayQueryResult result;
  450. result.mNode = this;
  451. result.mDistance = distance;
  452. result.mSubObject = i;
  453. query.mResult.push_back(result);
  454. }
  455. }
  456. }
  457. }
  458. else if (collisionMask & BONECOLLISION_SPHERE)
  459. {
  460. boneSphere.mCenter = bone->getWorldPosition();
  461. boneSphere.mRadius = bone->getRadius();
  462. float distance = boneSphere.getDistance(query.mRay);
  463. if (distance < query.mMaxDistance)
  464. {
  465. RayQueryResult result;
  466. result.mNode = this;
  467. result.mSubObject = i;
  468. result.mDistance = distance;
  469. query.mResult.push_back(result);
  470. }
  471. }
  472. }
  473. }
  474. void AnimatedModel::updateNode(const FrameInfo& frame)
  475. {
  476. // Update animation here
  477. if ((!mAnimationDirty) && (!mAnimationOrderDirty))
  478. return;
  479. // If node was invisible last frame, need to decide animation LOD distance here
  480. // If headless, retain the current animation distance (should be 0)
  481. if ((frame.mCamera) && (abs((int)frame.mFrameNumber - (int)mAnimationLodFrameNumber) > 1))
  482. {
  483. float distance = frame.mCamera->getDistance(getWorldPosition());
  484. // If distance is greater than draw distance, no need to update at all
  485. if ((mDrawDistance != 0.0f) && (distance > mDrawDistance))
  486. return;
  487. // Multiply the distance by a constant so that invisible nodes don't update that often
  488. static const Vector3 dotScale(1 / 3.0f, 1 / 3.0f, 1 / 3.0f);
  489. float scale = getWorldBoundingBox().getSize().dotProduct(dotScale);
  490. mAnimationLodDistance = frame.mCamera->getLodDistance(distance, scale, mLodBias) * ANIMATION_LOD_INVISIBLE_FACTOR;
  491. }
  492. updateAnimation(frame);
  493. }
  494. void AnimatedModel::updateDistance(const FrameInfo& frame)
  495. {
  496. mDistance = frame.mCamera->getDistance(getWorldPosition());
  497. static const Vector3 dotScale(1 / 3.0f, 1 / 3.0f, 1 / 3.0f);
  498. float scale = getWorldBoundingBox().getSize().dotProduct(dotScale);
  499. float newLodDistance = frame.mCamera->getLodDistance(mDistance, scale, mLodBias);
  500. // If model is rendered from several views, use the minimum LOD distance for animation LOD
  501. if (frame.mFrameNumber != mAnimationLodFrameNumber)
  502. {
  503. mAnimationLodDistance = newLodDistance;
  504. mAnimationLodFrameNumber = frame.mFrameNumber;
  505. }
  506. else
  507. mAnimationLodDistance = min(mAnimationLodDistance, newLodDistance);
  508. if (newLodDistance != mLodDistance)
  509. {
  510. mLodDistance = newLodDistance;
  511. mLodLevelsDirty = true;
  512. }
  513. }
  514. void AnimatedModel::updateGeometry(const FrameInfo& frame, Renderer* renderer)
  515. {
  516. if (mLodLevelsDirty)
  517. calculateLodLevels();
  518. if ((mMorphsDirty) && (mMorphs.size()))
  519. updateMorphs();
  520. if ((mSkeleton.getNumBones()) && (mSkeleton.getRootBone()->isSkinningDirty()))
  521. updateSkinning();
  522. }
  523. bool AnimatedModel::getVertexShaderParameter(unsigned batchIndex, VSParameter parameter, const float** data, unsigned* count)
  524. {
  525. if ((parameter == VSP_MODELSKINMATRICES) && (mSkinMatrices.size()))
  526. {
  527. // Check if model has per-geometry bone mappings
  528. if ((mGeometrySkinMatrices.size()) && (mGeometrySkinMatrices[batchIndex].size()))
  529. {
  530. *count = mGeometrySkinMatrices[batchIndex].size() * 12;
  531. *data = mGeometrySkinMatrices[batchIndex][0].getData();
  532. }
  533. // If not, use the global skin matrices
  534. else
  535. {
  536. *count = mSkinMatrices.size() * 12;
  537. *data = mSkinMatrices[0].getData();
  538. }
  539. return true;
  540. }
  541. return false;
  542. }
  543. void AnimatedModel::drawDebugGeometry(DebugRenderer* debug)
  544. {
  545. debug->addBoundingBox(getWorldBoundingBox(), Color(0.0f, 1.0f, 0.0f), false);
  546. debug->addSkeleton(mSkeleton, Color(0.75f, 0.75f, 0.75f), false);
  547. }
  548. bool AnimatedModel::setModel(Model* model)
  549. {
  550. if (model == mModel)
  551. return true;
  552. PROFILE(AnimatedModel_SetModel);
  553. if (!model)
  554. {
  555. LOGERROR("Null model for AnimatedModel");
  556. return false;
  557. }
  558. mModel = model;
  559. // Copy the subgeometry & LOD level structure
  560. setNumGeometries(model->getNumGeometries());
  561. const std::vector<std::vector<SharedPtr<Geometry> > >& geometries = model->getGeometries();
  562. for (unsigned i = 0; i < geometries.size(); ++i)
  563. mGeometries[i] = geometries[i];
  564. // Copy geometry bone mappings
  565. const std::vector<std::vector<unsigned> >& geometryBoneMappings = model->getGeometryBoneMappings();
  566. mGeometryBoneMappings.clear();
  567. for (unsigned i = 0; i < geometryBoneMappings.size(); ++i)
  568. mGeometryBoneMappings.push_back(geometryBoneMappings[i]);
  569. // Copy morphs
  570. mMorphVertexBuffers.clear();
  571. mMorphs.clear();
  572. const std::vector<ModelMorph>& morphs = model->getMorphs();
  573. for (unsigned i = 0; i < morphs.size(); ++i)
  574. {
  575. ModelMorph newMorph;
  576. newMorph.mName = morphs[i].mName;
  577. newMorph.mNameHash = morphs[i].mNameHash;
  578. newMorph.mWeight = 0.0f;
  579. newMorph.mBuffers = morphs[i].mBuffers;
  580. mMorphs.push_back(newMorph);
  581. }
  582. // If model has morphs, must clone all geometries & vertex buffers that refer to morphable vertex data
  583. if (morphs.size())
  584. {
  585. cloneGeometries();
  586. markMorphsDirty();
  587. }
  588. // Copy bounding box & skeleton
  589. setBoundingBox(model->getBoundingBox());
  590. setSkeleton(model->getSkeleton());
  591. return true;
  592. }
  593. AnimationState* AnimatedModel::addAnimationState(Animation* animation)
  594. {
  595. if (!animation)
  596. return 0;
  597. if (!mSkeleton.getNumBones())
  598. {
  599. LOGERROR("Animations can not be added to a model without skeleton");
  600. return 0;
  601. }
  602. // Check for not adding twice
  603. AnimationState* existing = getAnimationState(animation);
  604. if (existing)
  605. return existing;
  606. AnimationState* newState = new AnimationState(this, animation);
  607. mAnimationStates.push_back(newState);
  608. markAnimationOrderDirty();
  609. return newState;
  610. }
  611. void AnimatedModel::removeAnimationState(Animation* animation)
  612. {
  613. if (animation)
  614. removeAnimationState(animation->getNameHash());
  615. }
  616. void AnimatedModel::removeAnimationState(const std::string& animationName)
  617. {
  618. removeAnimationState(StringHash(animationName));
  619. }
  620. void AnimatedModel::removeAnimationState(StringHash animationNameHash)
  621. {
  622. for (std::vector<AnimationState*>::iterator i = mAnimationStates.begin(); i != mAnimationStates.end(); ++i)
  623. {
  624. AnimationState* state = *i;
  625. Animation* animation = state->getAnimation();
  626. // Check both the animation and the resource name
  627. if ((animation->getNameHash() == animationNameHash) || (animation->getAnimationNameHash() == animationNameHash))
  628. {
  629. // If animation is still interpolating, do not remove immediately, but set target weight to zero
  630. if ((isProxy()) && (state->isInterpolating()))
  631. state->setWeight(0.0f);
  632. else
  633. {
  634. delete state;
  635. mAnimationStates.erase(i);
  636. markAnimationDirty();
  637. }
  638. return;
  639. }
  640. }
  641. }
  642. void AnimatedModel::removeAnimationState(AnimationState* state)
  643. {
  644. for (std::vector<AnimationState*>::iterator i = mAnimationStates.begin(); i != mAnimationStates.end(); ++i)
  645. {
  646. if (*i == state)
  647. {
  648. // If animation is still interpolating, do not remove immediately, but set target weight to zero
  649. if ((isProxy()) && (state->isInterpolating()))
  650. state->setWeight(0.0f);
  651. else
  652. {
  653. delete state;
  654. mAnimationStates.erase(i);
  655. markAnimationDirty();
  656. }
  657. return;
  658. }
  659. }
  660. }
  661. void AnimatedModel::removeAllAnimationStates()
  662. {
  663. for (std::vector<AnimationState*>::iterator i = mAnimationStates.begin(); i != mAnimationStates.end(); ++i)
  664. delete *i;
  665. mAnimationStates.clear();
  666. markAnimationDirty();
  667. }
  668. void AnimatedModel::setAnimationLodBias(float bias)
  669. {
  670. mAnimationLodBias = max(bias, 0.0f);
  671. }
  672. void AnimatedModel::setMorphWeight(unsigned index, float weight)
  673. {
  674. if (index >= mMorphs.size())
  675. return;
  676. weight = clamp(weight, 0.0f, 1.0f);
  677. if (weight != mMorphs[index].mWeight)
  678. {
  679. mMorphs[index].mWeight = weight;
  680. markMorphsDirty();
  681. }
  682. }
  683. void AnimatedModel::setMorphWeight(const std::string& name, float weight)
  684. {
  685. weight = clamp(weight, 0.0f, 1.0f);
  686. for (std::vector<ModelMorph>::iterator i = mMorphs.begin(); i != mMorphs.end(); ++i)
  687. {
  688. if (i->mName == name)
  689. {
  690. if (weight != i->mWeight)
  691. {
  692. i->mWeight = weight;
  693. markMorphsDirty();
  694. }
  695. return;
  696. }
  697. }
  698. }
  699. void AnimatedModel::setMorphWeight(StringHash nameHash, float weight)
  700. {
  701. weight = clamp(weight, 0.0f, 1.0f);
  702. for (std::vector<ModelMorph>::iterator i = mMorphs.begin(); i != mMorphs.end(); ++i)
  703. {
  704. if (i->mNameHash == nameHash)
  705. {
  706. if (weight != i->mWeight)
  707. {
  708. i->mWeight = weight;
  709. markMorphsDirty();
  710. }
  711. return;
  712. }
  713. }
  714. }
  715. void AnimatedModel::resetMorphWeights()
  716. {
  717. for (std::vector<ModelMorph>::iterator i = mMorphs.begin(); i != mMorphs.end(); ++i)
  718. i->mWeight = 0.0f;
  719. markMorphsDirty();
  720. }
  721. void AnimatedModel::syncAnimation(AnimatedModel* srcNode)
  722. {
  723. if (!srcNode)
  724. return;
  725. // Make sure the animation proceeds at the same rate as in the source
  726. mAnimationLodBias = srcNode->mAnimationLodBias;
  727. mAnimationLodDistance = srcNode->mAnimationLodDistance;
  728. mAnimationLodFrameNumber = srcNode->mAnimationLodFrameNumber;
  729. const std::vector<AnimationState*>& srcStates = srcNode->getAnimationStates();
  730. std::set<Animation*> srcAnimations;
  731. for (unsigned i = 0; i < srcStates.size(); ++i)
  732. {
  733. AnimationState* src = srcStates[i];
  734. Animation* anim = src->getAnimation();
  735. srcAnimations.insert(anim);
  736. AnimationState* dest = getAnimationState(anim);
  737. if (!dest)
  738. dest = addAnimationState(anim);
  739. dest->sync(src);
  740. }
  741. // Check for extra states in destination and remove them
  742. if (mAnimationStates.size() > srcStates.size())
  743. {
  744. for (unsigned i = 0; i < mAnimationStates.size(); ++i)
  745. {
  746. AnimationState* state = mAnimationStates[i];
  747. if (srcAnimations.find(state->getAnimation()) == srcAnimations.end())
  748. removeAnimationState(state);
  749. }
  750. }
  751. }
  752. void AnimatedModel::syncMorphs(AnimatedModel* srcNode)
  753. {
  754. for (unsigned i = 0; i < mMorphs.size(); ++i)
  755. {
  756. float srcWeight = srcNode->getMorphWeight(mMorphs[i].mName);
  757. setMorphWeight(i, srcWeight);
  758. }
  759. }
  760. void AnimatedModel::setLocalAnimation(bool enable)
  761. {
  762. mLocalAnimation = enable;
  763. }
  764. float AnimatedModel::getMorphWeight(unsigned index) const
  765. {
  766. if (index >= mMorphs.size())
  767. return 0.0f;
  768. return mMorphs[index].mWeight;
  769. }
  770. float AnimatedModel::getMorphWeight(const std::string& name) const
  771. {
  772. for (std::vector<ModelMorph>::const_iterator i = mMorphs.begin(); i != mMorphs.end(); ++i)
  773. {
  774. if (i->mName == name)
  775. return i->mWeight;
  776. }
  777. return 0.0f;
  778. }
  779. float AnimatedModel::getMorphWeight(StringHash nameHash) const
  780. {
  781. for (std::vector<ModelMorph>::const_iterator i = mMorphs.begin(); i != mMorphs.end(); ++i)
  782. {
  783. if (i->mNameHash == nameHash)
  784. return i->mWeight;
  785. }
  786. return 0.0f;
  787. }
  788. AnimationState* AnimatedModel::getAnimationState(Animation* animation) const
  789. {
  790. for (std::vector<AnimationState*>::const_iterator i = mAnimationStates.begin(); i != mAnimationStates.end(); ++i)
  791. {
  792. if ((*i)->getAnimation() == animation)
  793. return *i;
  794. }
  795. return 0;
  796. }
  797. AnimationState* AnimatedModel::getAnimationState(const std::string& animationName) const
  798. {
  799. for (std::vector<AnimationState*>::const_iterator i = mAnimationStates.begin(); i != mAnimationStates.end(); ++i)
  800. {
  801. Animation* animation = (*i)->getAnimation();
  802. // Check both the animation and the resource name
  803. if ((animation->getName() == animationName) || (animation->getAnimationName() == animationName))
  804. return *i;
  805. }
  806. return 0;
  807. }
  808. AnimationState* AnimatedModel::getAnimationState(StringHash animationNameHash) const
  809. {
  810. for (std::vector<AnimationState*>::const_iterator i = mAnimationStates.begin(); i != mAnimationStates.end(); ++i)
  811. {
  812. Animation* animation = (*i)->getAnimation();
  813. // Check both the animation and the resource name
  814. if ((animation->getNameHash() == animationNameHash) || (animation->getAnimationNameHash() == animationNameHash))
  815. return *i;
  816. }
  817. return 0;
  818. }
  819. void AnimatedModel::setSkeleton(const Skeleton& skeleton)
  820. {
  821. PROFILE(AnimatedModel_SetSkeleton);
  822. removeAllAnimationStates();
  823. mSkeleton.define(skeleton.getBones());
  824. // Parent the root bone to the this node, so that objects can further be properly attached to bones
  825. Bone* rootBone = mSkeleton.getRootBone();
  826. if (rootBone)
  827. addChild(rootBone);
  828. // Reserve space for skinning matrices
  829. mSkinMatrices.resize(mSkeleton.getNumBones());
  830. refreshGeometryBoneMappings();
  831. }
  832. void AnimatedModel::onWorldBoundingBoxUpdate(BoundingBox& worldBoundingBox)
  833. {
  834. if (!mSkeleton.getNumBones())
  835. worldBoundingBox = mBoundingBox.getTransformed(getWorldTransform());
  836. else
  837. {
  838. // If has bones, update world bounding box based on them
  839. worldBoundingBox.mDefined = false;
  840. const std::vector<SharedPtr<Bone> >& bones = mSkeleton.getBones();
  841. for (std::vector<SharedPtr<Bone> >::const_iterator i = bones.begin(); i != bones.end(); ++i)
  842. {
  843. Bone* bone = *i;
  844. unsigned collisionMask = bone->getCollisionMask();
  845. // Use hitbox if available. If not, use only half of the sphere radius
  846. if (collisionMask & BONECOLLISION_BOX)
  847. worldBoundingBox.merge(bone->getBoundingBox().getTransformed(bone->getWorldTransform()));
  848. else if (collisionMask & BONECOLLISION_SPHERE)
  849. worldBoundingBox.merge(Sphere(bone->getWorldPosition(), bone->getRadius() * 0.5f));
  850. }
  851. }
  852. }
  853. void AnimatedModel::markAnimationDirty()
  854. {
  855. mAnimationDirty = true;
  856. // Mark for octree update, as animation is updated before octree reinsertion
  857. if (mOctant)
  858. mOctant->getRoot()->markNodeForUpdate(this);
  859. }
  860. void AnimatedModel::markAnimationOrderDirty()
  861. {
  862. mAnimationOrderDirty = true;
  863. // Mark for octree update, as animation is updated before octree reinsertion
  864. if (mOctant)
  865. mOctant->getRoot()->markNodeForUpdate(this);
  866. }
  867. void AnimatedModel::markMorphsDirty()
  868. {
  869. mMorphsDirty = true;
  870. }
  871. void AnimatedModel::cloneGeometries()
  872. {
  873. PROFILE(AnimatedModel_CloneGeometries);
  874. // Clone vertex buffers as necessary
  875. const std::vector<SharedPtr<VertexBuffer> >& originalVertexBuffers = mModel->getVertexBuffers();
  876. std::map<VertexBuffer*, SharedPtr<VertexBuffer> > clonedVertexBuffers;
  877. mMorphVertexBuffers.resize(originalVertexBuffers.size());
  878. for (unsigned i = 0; i < originalVertexBuffers.size(); ++i)
  879. {
  880. VertexBuffer* original = originalVertexBuffers[i];
  881. if (original->hasMorphRange())
  882. {
  883. SharedPtr<VertexBuffer> clone(new VertexBuffer(original->getRenderer()));
  884. clone->setSize(original->getVertexCount(), original->getElementMask());
  885. void* originalData = original->lock(0, original->getVertexCount(), LOCK_NORMAL);
  886. clone->setData(originalData);
  887. original->unlock();
  888. clone->setMorphRange(original->getMorphRangeStart(), original->getMorphRangeCount());
  889. clone->setMorphRangeResetData(original->getMorphRangeResetData());
  890. clonedVertexBuffers[original] = clone;
  891. mMorphVertexBuffers[i] = clone;
  892. }
  893. }
  894. // Geometries will always be cloned fully. They contain only references to buffer, so they are relatively light
  895. for (unsigned i = 0; i < mGeometries.size(); ++i)
  896. {
  897. for (unsigned j = 0; j < mGeometries[i].size(); ++j)
  898. {
  899. SharedPtr<Geometry> original = mGeometries[i][j];
  900. const std::vector<SharedPtr<VertexBuffer> >& originalBuffers = original->getVertexBuffers();
  901. SharedPtr<Geometry> clone(new Geometry());
  902. clone->setNumVertexBuffers(originalVertexBuffers.size());
  903. for (unsigned k = 0; k < originalVertexBuffers.size(); ++k)
  904. {
  905. VertexBuffer* originalBuffer = originalBuffers[k];
  906. if (clonedVertexBuffers.find(originalBuffer) != clonedVertexBuffers.end())
  907. clone->setVertexBuffer(k, clonedVertexBuffers[originalBuffer], original->getVertexElementMask(k));
  908. else
  909. clone->setVertexBuffer(k, originalBuffers[k], original->getVertexElementMask(k));
  910. }
  911. clone->setIndexBuffer(original->getIndexBuffer());
  912. clone->setDrawRange(original->getPrimitiveType(), original->getIndexStart(), original->getIndexCount());
  913. clone->setLodDistance(original->getLodDistance());
  914. mGeometries[i][j] = clone;
  915. }
  916. }
  917. }
  918. void AnimatedModel::refreshGeometryBoneMappings()
  919. {
  920. mGeometrySkinMatrices.clear();
  921. mGeometrySkinMatrixPtrs.clear();
  922. if (!mGeometryBoneMappings.size())
  923. return;
  924. // Check if all mappings are empty, then we do not need to use mapped skinning
  925. bool allEmpty = true;
  926. for (unsigned i = 0; i < mGeometryBoneMappings.size(); ++i)
  927. if (mGeometryBoneMappings[i].size())
  928. allEmpty = false;
  929. if (allEmpty)
  930. return;
  931. // Reserve space for per-geometry skinning matrices
  932. mGeometrySkinMatrices.resize(mGeometryBoneMappings.size());
  933. for (unsigned i = 0; i < mGeometryBoneMappings.size(); ++i)
  934. mGeometrySkinMatrices[i].resize(mGeometryBoneMappings[i].size());
  935. // Build original-to-skinindex matrix pointer mapping for fast copying
  936. // Note: at this point layout of mGeometrySkinMatrices cannot be modified or pointers become invalid
  937. mGeometrySkinMatrixPtrs.resize(mSkeleton.getNumBones());
  938. for (unsigned i = 0; i < mGeometryBoneMappings.size(); ++i)
  939. {
  940. for (unsigned j = 0; j < mGeometryBoneMappings[i].size(); ++j)
  941. mGeometrySkinMatrixPtrs[mGeometryBoneMappings[i][j]].push_back(&mGeometrySkinMatrices[i][j]);
  942. }
  943. }
  944. void AnimatedModel::updateAnimation(const FrameInfo& frame)
  945. {
  946. // If using animation LOD, accumulate time and see if it is time to update
  947. if ((mAnimationLodBias > 0.0f) && (mAnimationLodDistance > 0.0f))
  948. {
  949. mAnimationLodTimer += mAnimationLodBias * frame.mTimeStep * ANIMATION_LOD_BASESCALE;
  950. if (mAnimationLodTimer >= mAnimationLodDistance)
  951. mAnimationLodTimer = fmodf(mAnimationLodTimer, mAnimationLodDistance);
  952. else
  953. return;
  954. }
  955. PROFILE(AnimatedModel_UpdateAnimation);
  956. // Make sure animations are in ascending priority order
  957. if (mAnimationOrderDirty)
  958. {
  959. std::sort(mAnimationStates.begin(), mAnimationStates.end(), compareAnimationOrder);
  960. mAnimationOrderDirty = false;
  961. }
  962. // Reset skeleton, then apply all animations
  963. mSkeleton.reset();
  964. for (std::vector<AnimationState*>::iterator i = mAnimationStates.begin(); i != mAnimationStates.end(); ++i)
  965. (*i)->apply();
  966. // Animation has changed the bounding box: mark node for octree reinsertion
  967. VolumeNode::onMarkedDirty();
  968. mAnimationDirty = false;
  969. }
  970. void AnimatedModel::updateSkinning()
  971. {
  972. PROFILE(AnimatedModel_UpdateSkinning);
  973. // Note: the model's world transform will be baked in the skin matrices
  974. const std::vector<SharedPtr<Bone > >& bones = mSkeleton.getBones();
  975. // Skinning with global matrices only
  976. if (!mGeometrySkinMatrices.size())
  977. {
  978. for (unsigned i = 0; i < bones.size(); ++i)
  979. {
  980. Bone* bone = bones[i];
  981. if (bone->isSkinningDirty())
  982. {
  983. mSkinMatrices[i] = bone->getWorldTransform() * bone->getOffsetMatrix();
  984. bone->clearSkinningDirty();
  985. }
  986. }
  987. }
  988. // Skinning with per-geometry matrices
  989. else
  990. {
  991. for (unsigned i = 0; i < bones.size(); ++i)
  992. {
  993. Bone* bone = bones[i];
  994. if (bone->isSkinningDirty())
  995. {
  996. mSkinMatrices[i] = bone->getWorldTransform() * bone->getOffsetMatrix();
  997. // Copy the skin matrix to per-geometry matrices as needed
  998. for (unsigned j = 0; j < mGeometrySkinMatrixPtrs[i].size(); ++j)
  999. *mGeometrySkinMatrixPtrs[i][j] = mSkinMatrices[i];
  1000. bone->clearSkinningDirty();
  1001. }
  1002. }
  1003. }
  1004. }
  1005. void AnimatedModel::updateMorphs()
  1006. {
  1007. PROFILE(AnimatedModel_UpdateMorphs);
  1008. if (mMorphs.size())
  1009. {
  1010. // Reset the morph data range from all morphable vertex buffers, then apply morphs
  1011. for (unsigned i = 0; i < mMorphVertexBuffers.size(); ++i)
  1012. {
  1013. VertexBuffer* buffer = mMorphVertexBuffers[i];
  1014. if (buffer)
  1015. {
  1016. void* lockedMorphRange = buffer->lockMorphRange();
  1017. buffer->resetMorphRange(lockedMorphRange);
  1018. for (unsigned j = 0; j < mMorphs.size(); ++j)
  1019. {
  1020. if (mMorphs[j].mWeight > 0.0f)
  1021. {
  1022. std::map<unsigned, VertexBufferMorph>::iterator k = mMorphs[j].mBuffers.find(i);
  1023. if (k != mMorphs[j].mBuffers.end())
  1024. applyMorph(buffer, lockedMorphRange, k->second, mMorphs[j].mWeight);
  1025. }
  1026. }
  1027. buffer->unlock();
  1028. }
  1029. }
  1030. }
  1031. mMorphsDirty = false;
  1032. }
  1033. void AnimatedModel::applyMorph(VertexBuffer* buffer, void* lockedMorphRange, const VertexBufferMorph& morph, float weight)
  1034. {
  1035. unsigned elementMask = morph.mElementMask;
  1036. unsigned vertexCount = morph.mVertexCount;
  1037. unsigned normalOffset = buffer->getElementOffset(ELEMENT_NORMAL);
  1038. unsigned tangentOffset = buffer->getElementOffset(ELEMENT_TANGENT);
  1039. unsigned morphRangeStart = buffer->getMorphRangeStart();
  1040. unsigned vertexSize = buffer->getVertexSize();
  1041. unsigned char* srcData = morph.mMorphData;
  1042. unsigned char* destData = (unsigned char*)lockedMorphRange;
  1043. while (vertexCount--)
  1044. {
  1045. unsigned vertexIndex = *((unsigned*)srcData) - morphRangeStart;
  1046. srcData += sizeof(unsigned);
  1047. if (elementMask & MASK_POSITION)
  1048. {
  1049. float* dest = (float*)(destData + vertexIndex * vertexSize);
  1050. float* src = (float*)srcData;
  1051. dest[0] += src[0] * weight;
  1052. dest[1] += src[1] * weight;
  1053. dest[2] += src[2] * weight;
  1054. srcData += 3 * sizeof(float);
  1055. }
  1056. if (elementMask & MASK_NORMAL)
  1057. {
  1058. float* dest = (float*)(destData + vertexIndex * vertexSize + normalOffset);
  1059. float* src = (float*)srcData;
  1060. dest[0] += src[0] * weight;
  1061. dest[1] += src[1] * weight;
  1062. dest[2] += src[2] * weight;
  1063. srcData += 3 * sizeof(float);
  1064. }
  1065. if (elementMask & MASK_TANGENT)
  1066. {
  1067. float* dest = (float*)(destData + vertexIndex * vertexSize + tangentOffset);
  1068. float* src = (float*)srcData;
  1069. dest[0] += src[0] * weight;
  1070. dest[1] += src[1] * weight;
  1071. dest[2] += src[2] * weight;
  1072. srcData += 3 * sizeof(float);
  1073. }
  1074. }
  1075. }
  1076. void AnimatedModel::removeExtraAnimations(const std::set<StringHash>& animations)
  1077. {
  1078. bool removedAny = false;
  1079. for (std::vector<AnimationState*>::iterator i = mAnimationStates.begin(); i != mAnimationStates.end();)
  1080. {
  1081. AnimationState* state = *i;
  1082. if (animations.find(state->getAnimation()->getNameHash()) == animations.end())
  1083. {
  1084. // If animation is still interpolating, do not remove immediately, but set target weight to zero
  1085. if ((isProxy()) && (state->isInterpolating()))
  1086. {
  1087. state->setWeight(0.0f);
  1088. ++i;
  1089. }
  1090. else
  1091. {
  1092. delete state;
  1093. i = mAnimationStates.erase(i);
  1094. removedAny = true;
  1095. }
  1096. }
  1097. else
  1098. ++i;
  1099. }
  1100. if (removedAny)
  1101. markAnimationDirty();
  1102. }