AnimatedModel.cpp 46 KB

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