AnimatedModel.cpp 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271
  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 "StringUtils.h"
  41. #include "VertexBuffer.h"
  42. #include <algorithm>
  43. #include "DebugNew.h"
  44. static bool compareAnimationOrder(AnimationState* lhs, AnimationState* rhs)
  45. {
  46. return lhs->getPriority() < rhs->getPriority();
  47. }
  48. AnimatedModel::AnimatedModel(Octant* octant, const std::string& name) :
  49. StaticModel(NODE_ANIMATEDMODEL, octant, name),
  50. mAnimationLodDistance(0.0f),
  51. mAnimationLodFrameNumber(M_MAX_UNSIGNED),
  52. mAnimationLodBias(1.0f),
  53. mAnimationLodTimer(0.0f),
  54. mAnimationDirty(true),
  55. mAnimationOrderDirty(true),
  56. mMorphsDirty(true),
  57. mLocalAnimation(false)
  58. {
  59. }
  60. AnimatedModel::~AnimatedModel()
  61. {
  62. removeAllAnimationStates();
  63. }
  64. void AnimatedModel::save(Serializer& dest)
  65. {
  66. // Write GeometryNode properties
  67. GeometryNode::save(dest);
  68. // Write StaticModel properties
  69. dest.writeStringHash(getResourceHash(mModel));
  70. dest.writeVLE(mMaterials.size());
  71. for (unsigned i = 0; i < mMaterials.size(); ++i)
  72. dest.writeStringHash(getResourceHash(mMaterials[i]));
  73. // Write skeletal animation properties
  74. dest.writeFloat(mAnimationLodBias);
  75. dest.writeVLE(mAnimationStates.size());
  76. for (unsigned i = 0; i < mAnimationStates.size(); ++i)
  77. {
  78. AnimationState* state = mAnimationStates[i];
  79. state->save(dest);
  80. }
  81. // Write morph properties
  82. dest.writeVLE(mMorphs.size());
  83. for (unsigned i = 0; i < mMorphs.size(); ++i)
  84. dest.writeFloat(mMorphs[i].mWeight);
  85. }
  86. void AnimatedModel::load(Deserializer& source, ResourceCache* cache)
  87. {
  88. // Read GeometryNode properties
  89. GeometryNode::load(source, cache);
  90. // Read StaticModel properties
  91. // Note: can not use StaticModel::load() because we need to set the skeleton
  92. setModel(cache->getResource<Model>(source.readStringHash()));
  93. unsigned numMaterials = source.readVLE();
  94. for (unsigned i = 0; i < numMaterials; ++i)
  95. setMaterial(i, cache->getResource<Material>(source.readStringHash()));
  96. // Read skeletal animation properties
  97. mAnimationLodBias = source.readFloat();
  98. std::set<StringHash> processed;
  99. unsigned numAnimationStates = source.readVLE();
  100. for (unsigned i = 0; i < numAnimationStates; ++i)
  101. {
  102. StringHash animation = source.readStringHash();
  103. AnimationState* newState = addAnimationState(cache->getResource<Animation>(animation));
  104. newState->load(source);
  105. processed.insert(animation);
  106. }
  107. removeExtraAnimations(processed);
  108. // Read morph properties
  109. unsigned numMorphs = source.readVLE();
  110. for (unsigned i = 0; i < numMorphs; ++i)
  111. setMorphWeight(i, source.readFloat());
  112. }
  113. void AnimatedModel::saveXML(XMLElement& dest)
  114. {
  115. // Write GeometryNode properties
  116. GeometryNode::saveXML(dest);
  117. // Write StaticModel properties
  118. XMLElement modelElem = dest.createChildElement("model");
  119. modelElem.setString("name", getResourceName(mModel));
  120. for (unsigned i = 0; i < mMaterials.size(); ++i)
  121. {
  122. XMLElement materialElem = dest.createChildElement("material");
  123. materialElem.setInt("index", i);
  124. materialElem.setString("name", getResourceName(mMaterials[i]));
  125. }
  126. // Write skeletal animation properties
  127. XMLElement lodElem = dest.getChildElement("lod");
  128. lodElem.setFloat("animlodbias", mAnimationLodBias);
  129. for (unsigned i = 0; i < mAnimationStates.size(); ++i)
  130. {
  131. XMLElement animationElem = dest.createChildElement("animation");
  132. mAnimationStates[i]->saveXML(animationElem);
  133. }
  134. // Write morph properties
  135. for (unsigned i = 0; i < mMorphs.size(); ++i)
  136. {
  137. XMLElement morphElem = dest.createChildElement("morph");
  138. morphElem.setInt("index", i);
  139. morphElem.setFloat("weight", mMorphs[i].mWeight);
  140. }
  141. }
  142. void AnimatedModel::loadXML(const XMLElement& source, ResourceCache* cache)
  143. {
  144. // Read GeometryNode properties
  145. GeometryNode::loadXML(source, cache);
  146. // Read StaticModel properties
  147. // Note: can not use StaticModel::loadXML() because we need to set the skeleton
  148. XMLElement modelElem = source.getChildElement("model");
  149. setModel(cache->getResource<Model>(modelElem.getString("name")));
  150. XMLElement materialElem = source.getChildElement("material");
  151. while (materialElem)
  152. {
  153. unsigned index = materialElem.getInt("index");
  154. setMaterial(index, cache->getResource<Material>(materialElem.getString("name")));
  155. materialElem = materialElem.getNextElement("material");
  156. }
  157. // Read skeletal animation properties
  158. XMLElement lodElem = source.getChildElement("lod");
  159. mAnimationLodBias = lodElem.getFloat("animlodbias");
  160. removeAllAnimationStates();
  161. XMLElement animationElem = source.getChildElement("animation");
  162. while (animationElem)
  163. {
  164. AnimationState* newState = addAnimationState(cache->getResource<Animation>(animationElem.getString("name")));
  165. newState->loadXML(animationElem);
  166. animationElem = animationElem.getNextElement("animation");
  167. }
  168. // Read morph properties
  169. XMLElement morphElem = source.getChildElement("morph");
  170. while (morphElem)
  171. {
  172. unsigned index = morphElem.getInt("index");
  173. setMorphWeight(index, morphElem.getFloat("weight"));
  174. morphElem = morphElem.getNextElement("morph");
  175. }
  176. }
  177. bool AnimatedModel::writeNetUpdate(Serializer& dest, Serializer& destRevision, Deserializer& baseRevision, const NetUpdateInfo& info)
  178. {
  179. // Write GeometryNode properties and see if there were any changes
  180. bool prevBits = GeometryNode::writeNetUpdate(dest, destRevision, baseRevision, info);
  181. // Build bitmask of changed properties
  182. unsigned char bits = 0;
  183. // Model
  184. checkStringHash(getResourceHash(mModel), baseRevision, bits, 1);
  185. // Materials
  186. unsigned numBaseMaterials = baseRevision.getSize() ? baseRevision.readVLE() : 0;
  187. if (mMaterials.size() != numBaseMaterials)
  188. bits |= 2;
  189. for (unsigned i = 0; i < numBaseMaterials; ++i)
  190. {
  191. if (i < mMaterials.size())
  192. checkStringHash(getResourceHash(mMaterials[i]), baseRevision, bits, 2);
  193. else
  194. baseRevision.readStringHash();
  195. }
  196. // Animation LOD bias
  197. checkFloat(mAnimationLodBias, baseRevision, bits, 4);
  198. // Animations
  199. unsigned numBaseAnimations = baseRevision.getSize() ? baseRevision.readVLE() : 0;
  200. unsigned enabledAnimations = 0;
  201. if (mAnimationStates.size() != numBaseAnimations)
  202. bits |= 8;
  203. static std::vector<unsigned char> animBits;
  204. animBits.resize(mAnimationStates.size());
  205. // Assume that animations are new ie. require update of all fields
  206. for (unsigned i = 0; i < mAnimationStates.size(); ++i)
  207. {
  208. if (mAnimationStates[i]->isEnabled())
  209. {
  210. animBits[i] = 1 | 2 | 4 | 8 | 16 | 32;
  211. ++enabledAnimations;
  212. }
  213. else
  214. animBits[i] = 0;
  215. }
  216. for (unsigned i = 0; i < numBaseAnimations; ++i)
  217. {
  218. StringHash animation = baseRevision.readStringHash();
  219. StringHash startBone = baseRevision.readStringHash();
  220. bool looped = baseRevision.readBool();
  221. float weight = baseRevision.readFloat();
  222. float time = baseRevision.readFloat();
  223. int priority = baseRevision.readUByte();
  224. bool useNlerp = baseRevision.readBool();
  225. bool found = false;
  226. for (unsigned j = 0; j < mAnimationStates.size(); ++j)
  227. {
  228. AnimationState* state = mAnimationStates[j];
  229. if (state->getAnimation()->getNameHash() == animation)
  230. {
  231. // If animation exists in base state, update only the necessary properties
  232. found = true;
  233. // If zero weight (disabled), do not update anything
  234. if (!state->isEnabled())
  235. continue;
  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. // If local animation, do not send even if changed. It is slightly unoptimal to first check, then disable, but it ensures
  270. // that the base revision data stays the same (otherwise out of bounds reads might result when toggling local animation)
  271. if (mLocalAnimation)
  272. bits &= ~(8 | 16);
  273. // Update replication state fully, and network stream by delta
  274. dest.writeUByte(bits);
  275. writeStringHashDelta(getResourceHash(mModel), dest, destRevision, bits & 1);
  276. writeVLEDelta(mMaterials.size(), dest, destRevision, bits & 2);
  277. for (unsigned i = 0; i < mMaterials.size(); ++i)
  278. writeStringHashDelta(getResourceHash(mMaterials[i]), dest, destRevision, bits & 2);
  279. writeFloatDelta(mAnimationLodBias, dest, destRevision, bits & 4);
  280. // Write all animations to the base replication state
  281. destRevision.writeVLE(mAnimationStates.size());
  282. for (unsigned i = 0; i < mAnimationStates.size(); ++i)
  283. {
  284. AnimationState* state = mAnimationStates[i];
  285. destRevision.writeStringHash(state->getAnimation()->getNameHash());
  286. destRevision.writeStringHash(state->getStartBone()->getNameHash());
  287. destRevision.writeBool(state->isLooped());
  288. destRevision.writeFloat(state->getWeight());
  289. destRevision.writeFloat(state->getTime());
  290. destRevision.writeUByte(state->getPriority());
  291. destRevision.writeBool(state->getUseNlerp());
  292. }
  293. // Then write delta of enabled animations to the net stream
  294. if (bits & 8)
  295. {
  296. dest.writeVLE(enabledAnimations);
  297. for (unsigned i = 0; i < mAnimationStates.size(); ++i)
  298. {
  299. AnimationState* state = mAnimationStates[i];
  300. if (!state->isEnabled())
  301. continue;
  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. return prevBits || (bits != 0);
  322. }
  323. void AnimatedModel::readNetUpdate(Deserializer& source, ResourceCache* cache, const NetUpdateInfo& info)
  324. {
  325. // Read GeometryNode properties
  326. GeometryNode::readNetUpdate(source, cache, info);
  327. unsigned char bits = source.readUByte();
  328. if (bits & 1)
  329. setModel(cache->getResource<Model>(source.readStringHash()));
  330. if (bits & 2)
  331. {
  332. unsigned numMaterials = source.readVLE();
  333. for (unsigned i = 0; i < numMaterials; ++i)
  334. setMaterial(i, cache->getResource<Material>(source.readStringHash()));
  335. }
  336. readFloatDelta(mAnimationLodBias, source, bits & 4);
  337. if (bits & 8)
  338. {
  339. unsigned numAnimations = source.readVLE();
  340. std::set<StringHash> processed;
  341. for (unsigned i = 0; i < numAnimations; ++i)
  342. {
  343. StringHash animation = source.readStringHash();
  344. unsigned char animBits = source.readUByte();
  345. processed.insert(animation);
  346. // Find the animation state. If not found, create new
  347. AnimationState* state = getAnimationState(animation);
  348. bool newState = false;
  349. if (!state)
  350. {
  351. state = addAnimationState(cache->getResource<Animation>(animation));
  352. newState = true;
  353. }
  354. if (state)
  355. {
  356. if (animBits & 1)
  357. state->setStartBone(mSkeleton.getBone(source.readStringHash()));
  358. if (animBits & 2)
  359. state->setLooped(source.readBool());
  360. if (animBits & 4)
  361. state->setWeight(source.readUByte() / 255.0f);
  362. if (animBits & 8)
  363. state->setTime(source.readUShort() * state->getAnimation()->getLength() / 65535.0f);
  364. if (animBits & 16)
  365. state->setPriority(source.readUByte());
  366. if (animBits & 32)
  367. state->setUseNlerp(source.readBool());
  368. // If state is new, interpolate directly to the end
  369. if (newState)
  370. state->interpolate(true, mEntity->getScene()->getInterpolationLerpFactor());
  371. }
  372. else
  373. {
  374. // If state could not be added, just read the data to avoid desyncing the stream
  375. if (animBits & 1)
  376. source.readStringHash();
  377. if (animBits & 2)
  378. source.readBool();
  379. if (animBits & 4)
  380. source.readUByte();
  381. if (animBits & 8)
  382. source.readUShort();
  383. if (animBits & 16)
  384. source.readUByte();
  385. if (animBits & 32)
  386. source.readBool();
  387. }
  388. }
  389. removeExtraAnimations(processed);
  390. }
  391. if (bits & 16)
  392. {
  393. unsigned numMorphs = source.readVLE();
  394. for (unsigned i = 0; i < numMorphs; ++i)
  395. setMorphWeight(i, source.readUByte() / 255.0f);
  396. }
  397. }
  398. void AnimatedModel::interpolate(bool snapToEnd)
  399. {
  400. Node::interpolate(snapToEnd);
  401. float t = mEntity->getScene()->getInterpolationLerpFactor();
  402. for (std::vector<AnimationState*>::iterator i = mAnimationStates.begin(); i != mAnimationStates.end(); ++i)
  403. (*i)->interpolate(snapToEnd, t);
  404. }
  405. void AnimatedModel::processRayQuery(RayOctreeQuery& query, float initialDistance)
  406. {
  407. // If no bones or no bone-level testing, use the GeometryNode test
  408. if ((!mSkeleton.getNumBones()) || (query.mLevel < RAY_AABB))
  409. {
  410. GeometryNode::processRayQuery(query, initialDistance);
  411. return;
  412. }
  413. PROFILE(AnimatedModel_Raycast);
  414. const std::vector<SharedPtr<Bone> >& bones = mSkeleton.getBones();
  415. Sphere boneSphere;
  416. RayQueryLevel level = query.mLevel;
  417. for (unsigned i = 0; i < bones.size(); ++i)
  418. {
  419. Bone* bone = bones[i];
  420. unsigned collisionMask = bone->getCollisionMask();
  421. // Use hitbox if available
  422. if (collisionMask & BONECOLLISION_BOX)
  423. {
  424. // Do an initial crude test using the bone's AABB
  425. const Matrix4x3& transform = bone->getWorldTransform();
  426. const BoundingBox& box = bone->getBoundingBox();
  427. float distance = box.getTransformed(transform).getDistance(query.mRay);
  428. if (distance < query.mMaxDistance)
  429. {
  430. if (level == RAY_AABB)
  431. {
  432. RayQueryResult result;
  433. result.mNode = this;
  434. result.mDistance = distance;
  435. result.mSubObject = i;
  436. query.mResult.push_back(result);
  437. }
  438. else
  439. {
  440. // Follow with an OBB test if required
  441. Matrix4x3 inverse = transform.getInverse();
  442. Ray localRay(inverse * query.mRay.mOrigin, inverse * Vector4(query.mRay.mDirection, 0.0f));
  443. distance = box.getDistance(localRay);
  444. if (distance < query.mMaxDistance)
  445. {
  446. RayQueryResult result;
  447. result.mNode = this;
  448. result.mDistance = distance;
  449. result.mSubObject = i;
  450. query.mResult.push_back(result);
  451. }
  452. }
  453. }
  454. }
  455. else if (collisionMask & BONECOLLISION_SPHERE)
  456. {
  457. boneSphere.mCenter = bone->getWorldPosition();
  458. boneSphere.mRadius = bone->getRadius();
  459. float distance = boneSphere.getDistance(query.mRay);
  460. if (distance < query.mMaxDistance)
  461. {
  462. RayQueryResult result;
  463. result.mNode = this;
  464. result.mSubObject = i;
  465. result.mDistance = distance;
  466. query.mResult.push_back(result);
  467. }
  468. }
  469. }
  470. }
  471. void AnimatedModel::updateNode(const FrameInfo& frame)
  472. {
  473. // Update animation here
  474. if ((!mAnimationDirty) && (!mAnimationOrderDirty))
  475. return;
  476. // If node was invisible last frame, need to decide animation LOD distance here
  477. // If headless, retain the current animation distance (should be 0)
  478. if ((frame.mCamera) && (abs((int)frame.mFrameNumber - (int)mAnimationLodFrameNumber) > 1))
  479. {
  480. float distance = frame.mCamera->getDistance(getWorldPosition());
  481. // If distance is greater than draw distance, no need to update at all
  482. if ((mDrawDistance != 0.0f) && (distance > mDrawDistance))
  483. return;
  484. // Multiply the distance by a constant so that invisible nodes don't update that often
  485. static const Vector3 dotScale(1 / 3.0f, 1 / 3.0f, 1 / 3.0f);
  486. float scale = getWorldBoundingBox().getSize().dotProduct(dotScale);
  487. mAnimationLodDistance = frame.mCamera->getLodDistance(distance, scale, mLodBias) * ANIMATION_LOD_INVISIBLE_FACTOR;
  488. LOGINFO("Invisible update");
  489. }
  490. else
  491. LOGINFO("Visible update");
  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. {
  954. // If animation order changed (animations added/removed), force always an immediate update
  955. if (!mAnimationOrderDirty)
  956. return;
  957. }
  958. }
  959. PROFILE(AnimatedModel_UpdateAnimation);
  960. // Make sure animations are in ascending priority order
  961. if (mAnimationOrderDirty)
  962. {
  963. std::sort(mAnimationStates.begin(), mAnimationStates.end(), compareAnimationOrder);
  964. mAnimationOrderDirty = false;
  965. }
  966. // Reset skeleton, then apply all animations
  967. mSkeleton.reset();
  968. for (std::vector<AnimationState*>::iterator i = mAnimationStates.begin(); i != mAnimationStates.end(); ++i)
  969. (*i)->apply();
  970. // Animation has changed the bounding box: mark node for octree reinsertion
  971. VolumeNode::onMarkedDirty();
  972. mAnimationDirty = false;
  973. }
  974. void AnimatedModel::updateSkinning()
  975. {
  976. PROFILE(AnimatedModel_UpdateSkinning);
  977. // Note: the model's world transform will be baked in the skin matrices. When preparing to render,
  978. // the model transform will then be set to identity
  979. const std::vector<SharedPtr<Bone > >& bones = mSkeleton.getBones();
  980. // Skinning with global matrices only
  981. if (!mGeometrySkinMatrices.size())
  982. {
  983. for (unsigned i = 0; i < bones.size(); ++i)
  984. {
  985. Bone* bone = bones[i];
  986. if (bone->isSkinningDirty())
  987. {
  988. mSkinMatrices[i] = bone->getWorldTransform() * bone->getOffsetMatrix();
  989. bone->clearSkinningDirty();
  990. }
  991. }
  992. }
  993. // Skinning with per-geometry matrices
  994. else
  995. {
  996. for (unsigned i = 0; i < bones.size(); ++i)
  997. {
  998. Bone* bone = bones[i];
  999. if (bone->isSkinningDirty())
  1000. {
  1001. mSkinMatrices[i] = bone->getWorldTransform() * bone->getOffsetMatrix();
  1002. // Copy the skin matrix to per-geometry matrices as needed
  1003. for (unsigned j = 0; j < mGeometrySkinMatrixPtrs[i].size(); ++j)
  1004. *mGeometrySkinMatrixPtrs[i][j] = mSkinMatrices[i];
  1005. bone->clearSkinningDirty();
  1006. }
  1007. }
  1008. }
  1009. }
  1010. void AnimatedModel::updateMorphs()
  1011. {
  1012. PROFILE(AnimatedModel_UpdateMorphs);
  1013. if (mMorphs.size())
  1014. {
  1015. // Reset the morph data range from all morphable vertex buffers, then apply morphs
  1016. for (unsigned i = 0; i < mMorphVertexBuffers.size(); ++i)
  1017. {
  1018. VertexBuffer* buffer = mMorphVertexBuffers[i];
  1019. if (buffer)
  1020. {
  1021. void* lockedMorphRange = buffer->lockMorphRange();
  1022. buffer->resetMorphRange(lockedMorphRange);
  1023. for (unsigned j = 0; j < mMorphs.size(); ++j)
  1024. {
  1025. if (mMorphs[j].mWeight > 0.0f)
  1026. {
  1027. std::map<unsigned, VertexBufferMorph>::iterator k = mMorphs[j].mBuffers.find(i);
  1028. if (k != mMorphs[j].mBuffers.end())
  1029. applyMorph(buffer, lockedMorphRange, k->second, mMorphs[j].mWeight);
  1030. }
  1031. }
  1032. buffer->unlock();
  1033. }
  1034. }
  1035. }
  1036. mMorphsDirty = false;
  1037. }
  1038. void AnimatedModel::applyMorph(VertexBuffer* buffer, void* lockedMorphRange, const VertexBufferMorph& morph, float weight)
  1039. {
  1040. unsigned elementMask = morph.mElementMask;
  1041. unsigned vertexCount = morph.mVertexCount;
  1042. unsigned normalOffset = buffer->getElementOffset(ELEMENT_NORMAL);
  1043. unsigned tangentOffset = buffer->getElementOffset(ELEMENT_TANGENT);
  1044. unsigned morphRangeStart = buffer->getMorphRangeStart();
  1045. unsigned vertexSize = buffer->getVertexSize();
  1046. unsigned char* srcData = morph.mMorphData;
  1047. unsigned char* destData = (unsigned char*)lockedMorphRange;
  1048. while (vertexCount--)
  1049. {
  1050. unsigned vertexIndex = *((unsigned*)srcData) - morphRangeStart;
  1051. srcData += sizeof(unsigned);
  1052. if (elementMask & MASK_POSITION)
  1053. {
  1054. float* dest = (float*)(destData + vertexIndex * vertexSize);
  1055. float* src = (float*)srcData;
  1056. dest[0] += src[0] * weight;
  1057. dest[1] += src[1] * weight;
  1058. dest[2] += src[2] * weight;
  1059. srcData += 3 * sizeof(float);
  1060. }
  1061. if (elementMask & MASK_NORMAL)
  1062. {
  1063. float* dest = (float*)(destData + vertexIndex * vertexSize + normalOffset);
  1064. float* src = (float*)srcData;
  1065. dest[0] += src[0] * weight;
  1066. dest[1] += src[1] * weight;
  1067. dest[2] += src[2] * weight;
  1068. srcData += 3 * sizeof(float);
  1069. }
  1070. if (elementMask & MASK_TANGENT)
  1071. {
  1072. float* dest = (float*)(destData + vertexIndex * vertexSize + tangentOffset);
  1073. float* src = (float*)srcData;
  1074. dest[0] += src[0] * weight;
  1075. dest[1] += src[1] * weight;
  1076. dest[2] += src[2] * weight;
  1077. srcData += 3 * sizeof(float);
  1078. }
  1079. }
  1080. }
  1081. void AnimatedModel::removeExtraAnimations(const std::set<StringHash>& animations)
  1082. {
  1083. bool removedAny = false;
  1084. for (std::vector<AnimationState*>::iterator i = mAnimationStates.begin(); i != mAnimationStates.end();)
  1085. {
  1086. AnimationState* state = *i;
  1087. if (animations.find(state->getAnimation()->getNameHash()) == animations.end())
  1088. {
  1089. // If animation is still interpolating, do not remove immediately, but set target weight to zero
  1090. if ((isProxy()) && (state->isInterpolating()))
  1091. {
  1092. state->setWeight(0.0f);
  1093. ++i;
  1094. }
  1095. else
  1096. {
  1097. delete state;
  1098. i = mAnimationStates.erase(i);
  1099. removedAny = true;
  1100. }
  1101. }
  1102. else
  1103. ++i;
  1104. }
  1105. if (removedAny)
  1106. markAnimationDirty();
  1107. }