AnimatedModel.cpp 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255
  1. //
  2. // Copyright (c) 2008-2013 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "AnimatedModel.h"
  24. #include "Animation.h"
  25. #include "AnimationState.h"
  26. #include "Batch.h"
  27. #include "Camera.h"
  28. #include "Context.h"
  29. #include "DebugRenderer.h"
  30. #include "DrawableEvents.h"
  31. #include "Geometry.h"
  32. #include "Graphics.h"
  33. #include "IndexBuffer.h"
  34. #include "Log.h"
  35. #include "Material.h"
  36. #include "Octree.h"
  37. #include "Profiler.h"
  38. #include "ResourceCache.h"
  39. #include "ResourceEvents.h"
  40. #include "Scene.h"
  41. #include "Sort.h"
  42. #include "VertexBuffer.h"
  43. #include "DebugNew.h"
  44. namespace Urho3D
  45. {
  46. static bool CompareAnimationOrder(const SharedPtr<AnimationState>& lhs, const SharedPtr<AnimationState>& rhs)
  47. {
  48. return lhs->GetLayer() < rhs->GetLayer();
  49. }
  50. OBJECTTYPESTATIC(AnimatedModel);
  51. AnimatedModel::AnimatedModel(Context* context) :
  52. StaticModel(context),
  53. animationLodFrameNumber_(0),
  54. morphElementMask_(0),
  55. animationLodBias_(1.0f),
  56. animationLodTimer_(-1.0f),
  57. animationLodDistance_(0.0f),
  58. invisibleLodFactor_(0.0f),
  59. animationDirty_(false),
  60. animationOrderDirty_(false),
  61. morphsDirty_(false),
  62. skinningDirty_(true),
  63. isMaster_(true),
  64. loading_(false),
  65. assignBonesPending_(false)
  66. {
  67. }
  68. AnimatedModel::~AnimatedModel()
  69. {
  70. }
  71. void AnimatedModel::RegisterObject(Context* context)
  72. {
  73. context->RegisterFactory<AnimatedModel>();
  74. ACCESSOR_ATTRIBUTE(AnimatedModel, VAR_BOOL, "Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  75. ACCESSOR_ATTRIBUTE(AnimatedModel, VAR_RESOURCEREF, "Model", GetModelAttr, SetModelAttr, ResourceRef, ResourceRef(Model::GetTypeStatic()), AM_DEFAULT);
  76. REF_ACCESSOR_ATTRIBUTE(AnimatedModel, VAR_RESOURCEREFLIST, "Material", GetMaterialsAttr, SetMaterialsAttr, ResourceRefList, ResourceRefList(Material::GetTypeStatic()), AM_DEFAULT);
  77. ATTRIBUTE(AnimatedModel, VAR_BOOL, "Is Occluder", occluder_, false, AM_DEFAULT);
  78. ACCESSOR_ATTRIBUTE(AnimatedModel, VAR_BOOL, "Can Be Occluded", IsOccludee, SetOccludee, bool, true, AM_DEFAULT);
  79. ATTRIBUTE(AnimatedModel, VAR_BOOL, "Cast Shadows", castShadows_, false, AM_DEFAULT);
  80. ACCESSOR_ATTRIBUTE(AnimatedModel, VAR_FLOAT, "Draw Distance", GetDrawDistance, SetDrawDistance, float, 0.0f, AM_DEFAULT);
  81. ACCESSOR_ATTRIBUTE(AnimatedModel, VAR_FLOAT, "Shadow Distance", GetShadowDistance, SetShadowDistance, float, 0.0f, AM_DEFAULT);
  82. ACCESSOR_ATTRIBUTE(AnimatedModel, VAR_FLOAT, "LOD Bias", GetLodBias, SetLodBias, float, 1.0f, AM_DEFAULT);
  83. ACCESSOR_ATTRIBUTE(AnimatedModel, VAR_FLOAT, "Animation LOD Bias", GetAnimationLodBias, SetAnimationLodBias, float, 1.0f, AM_DEFAULT);
  84. ACCESSOR_ATTRIBUTE(AnimatedModel, VAR_FLOAT, "Invisible Anim LOD", GetInvisibleLodFactor, SetInvisibleLodFactor, float, 0.0f, AM_DEFAULT);
  85. COPY_BASE_ATTRIBUTES(AnimatedModel, Drawable);
  86. ACCESSOR_ATTRIBUTE(AnimatedModel, VAR_VARIANTVECTOR, "Bone Animation Enabled", GetBonesEnabledAttr, SetBonesEnabledAttr, VariantVector, Variant::emptyVariantVector, AM_FILE | AM_NOEDIT);
  87. ACCESSOR_ATTRIBUTE(AnimatedModel, VAR_VARIANTVECTOR, "Animation States", GetAnimationStatesAttr, SetAnimationStatesAttr, VariantVector, Variant::emptyVariantVector, AM_FILE);
  88. REF_ACCESSOR_ATTRIBUTE(AnimatedModel, VAR_BUFFER, "Morphs", GetMorphsAttr, SetMorphsAttr, PODVector<unsigned char>, Variant::emptyBuffer, AM_DEFAULT | AM_NOEDIT);
  89. }
  90. bool AnimatedModel::Load(Deserializer& source)
  91. {
  92. loading_ = true;
  93. bool success = Component::Load(source);
  94. loading_ = false;
  95. return success;
  96. }
  97. bool AnimatedModel::LoadXML(const XMLElement& source)
  98. {
  99. loading_ = true;
  100. bool success = Component::LoadXML(source);
  101. loading_ = false;
  102. return success;
  103. }
  104. void AnimatedModel::ApplyAttributes()
  105. {
  106. if (assignBonesPending_)
  107. AssignBoneNodes();
  108. }
  109. void AnimatedModel::ProcessRayQuery(const RayOctreeQuery& query, PODVector<RayQueryResult>& results)
  110. {
  111. // If no bones or no bone-level testing, use the Drawable test
  112. RayQueryLevel level = query.level_;
  113. if (level < RAY_AABB || !skeleton_.GetRootBone() || !skeleton_.GetRootBone()->node_)
  114. {
  115. Drawable::ProcessRayQuery(query, results);
  116. return;
  117. }
  118. // Check ray hit distance to AABB before proceeding with bone-level tests
  119. if (query.ray_.HitDistance(GetWorldBoundingBox()) > query.maxDistance_)
  120. return;
  121. const Vector<Bone>& bones = skeleton_.GetBones();
  122. Sphere boneSphere;
  123. for (unsigned i = 0; i < bones.Size(); ++i)
  124. {
  125. const Bone& bone = bones[i];
  126. if (!bone.node_)
  127. continue;
  128. float distance;
  129. // Use hitbox if available
  130. if (bone.collisionMask_ & BONECOLLISION_BOX)
  131. {
  132. // Do an initial crude test using the bone's AABB
  133. const BoundingBox& box = bone.boundingBox_;
  134. const Matrix3x4& transform = bone.node_->GetWorldTransform();
  135. distance = query.ray_.HitDistance(box.Transformed(transform));
  136. if (distance > query.maxDistance_)
  137. continue;
  138. if (level != RAY_AABB)
  139. {
  140. // Follow with an OBB test if required
  141. Matrix3x4 inverse = transform.Inverse();
  142. Ray localRay(inverse * query.ray_.origin_, inverse * Vector4(query.ray_.direction_, 0.0f));
  143. distance = localRay.HitDistance(box);
  144. if (distance > query.maxDistance_)
  145. continue;
  146. }
  147. }
  148. else if (bone.collisionMask_ & BONECOLLISION_SPHERE)
  149. {
  150. boneSphere.center_ = bone.node_->GetWorldPosition();
  151. boneSphere.radius_ = bone.radius_;
  152. distance = query.ray_.HitDistance(boneSphere);
  153. if (distance > query.maxDistance_)
  154. continue;
  155. }
  156. else
  157. continue;
  158. // If the code reaches here then we have a hit
  159. RayQueryResult result;
  160. result.drawable_ = this;
  161. result.node_ = node_;
  162. result.distance_ = distance;
  163. result.subObject_ = i;
  164. results.Push(result);
  165. }
  166. }
  167. void AnimatedModel::Update(const FrameInfo& frame)
  168. {
  169. // Update animation here
  170. if (!animationDirty_ && !animationOrderDirty_)
  171. return;
  172. // If node was invisible last frame, need to decide animation LOD distance here
  173. // If headless, retain the current animation distance (should be 0)
  174. if (frame.camera_ && abs((int)frame.frameNumber_ - (int)viewFrameNumber_) > 1)
  175. {
  176. if (invisibleLodFactor_ == 0.0f)
  177. return;
  178. float distance = frame.camera_->GetDistance(node_->GetWorldPosition());
  179. // If distance is greater than draw distance, no need to update at all
  180. if (drawDistance_ > 0.0f && distance > drawDistance_)
  181. return;
  182. // Multiply the distance by a constant so that invisible nodes don't update that often
  183. float scale = GetWorldBoundingBox().Size().DotProduct(DOT_SCALE);
  184. animationLodDistance_ = frame.camera_->GetLodDistance(distance, scale, lodBias_) * invisibleLodFactor_;
  185. }
  186. UpdateAnimation(frame);
  187. }
  188. void AnimatedModel::UpdateBatches(const FrameInfo& frame)
  189. {
  190. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  191. distance_ = frame.camera_->GetDistance(GetWorldBoundingBox().Center());
  192. // Note: per-geometry distances do not take skinning into account
  193. if (batches_.Size() > 1)
  194. {
  195. for (unsigned i = 0; i < batches_.Size(); ++i)
  196. {
  197. batches_[i].distance_ = frame.camera_->GetDistance(worldTransform * geometryData_[i].center_);
  198. batches_[i].worldTransform_ = &worldTransform;
  199. }
  200. }
  201. else if (batches_.Size() == 1)
  202. {
  203. batches_[0].distance_ = distance_;
  204. batches_[0].worldTransform_ = &worldTransform;
  205. }
  206. float scale = GetWorldBoundingBox().Size().DotProduct(DOT_SCALE);
  207. float newLodDistance = frame.camera_->GetLodDistance(distance_, scale, lodBias_);
  208. // If model is rendered from several views, use the minimum LOD distance for animation LOD
  209. if (frame.frameNumber_ != animationLodFrameNumber_)
  210. {
  211. animationLodDistance_ = newLodDistance;
  212. animationLodFrameNumber_ = frame.frameNumber_;
  213. }
  214. else
  215. animationLodDistance_ = Min(animationLodDistance_, newLodDistance);
  216. if (newLodDistance != lodDistance_)
  217. {
  218. lodDistance_ = newLodDistance;
  219. CalculateLodLevels();
  220. }
  221. }
  222. void AnimatedModel::UpdateGeometry(const FrameInfo& frame)
  223. {
  224. if (morphsDirty_)
  225. UpdateMorphs();
  226. if (skinningDirty_)
  227. UpdateSkinning();
  228. }
  229. UpdateGeometryType AnimatedModel::GetUpdateGeometryType()
  230. {
  231. if (morphsDirty_)
  232. return UPDATE_MAIN_THREAD;
  233. else if (skinningDirty_)
  234. return UPDATE_WORKER_THREAD;
  235. else
  236. return UPDATE_NONE;
  237. }
  238. void AnimatedModel::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  239. {
  240. if (debug && IsEnabledEffective())
  241. {
  242. debug->AddBoundingBox(GetWorldBoundingBox(), Color::GREEN, depthTest);
  243. debug->AddSkeleton(skeleton_, Color(0.75f, 0.75f, 0.75f), depthTest);
  244. }
  245. }
  246. void AnimatedModel::SetModel(Model* model, bool createBones)
  247. {
  248. if (!model || model == model_)
  249. return;
  250. // Unsubscribe from the reload event of previous model (if any), then subscribe to the new
  251. if (model_)
  252. UnsubscribeFromEvent(model_, E_RELOADFINISHED);
  253. if (model)
  254. SubscribeToEvent(model, E_RELOADFINISHED, HANDLER(AnimatedModel, HandleModelReloadFinished));
  255. model_ = model;
  256. // Copy the subgeometry & LOD level structure
  257. SetNumGeometries(model->GetNumGeometries());
  258. const Vector<Vector<SharedPtr<Geometry> > >& geometries = model->GetGeometries();
  259. const PODVector<Vector3>& geometryCenters = model->GetGeometryCenters();
  260. for (unsigned i = 0; i < geometries.Size(); ++i)
  261. {
  262. geometries_[i] = geometries[i];
  263. geometryData_[i].center_ = geometryCenters[i];
  264. }
  265. // Copy geometry bone mappings
  266. const Vector<PODVector<unsigned> >& geometryBoneMappings = model->GetGeometryBoneMappings();
  267. geometryBoneMappings_.Clear();
  268. geometryBoneMappings_.Reserve(geometryBoneMappings.Size());
  269. for (unsigned i = 0; i < geometryBoneMappings.Size(); ++i)
  270. geometryBoneMappings_.Push(geometryBoneMappings[i]);
  271. // Copy morphs. Note: morph vertex buffers will be created later on-demand
  272. morphVertexBuffers_.Clear();
  273. morphs_.Clear();
  274. const Vector<ModelMorph>& morphs = model->GetMorphs();
  275. morphs_.Reserve(morphs.Size());
  276. morphElementMask_ = 0;
  277. for (unsigned i = 0; i < morphs.Size(); ++i)
  278. {
  279. ModelMorph newMorph;
  280. newMorph.name_ = morphs[i].name_;
  281. newMorph.nameHash_ = morphs[i].nameHash_;
  282. newMorph.weight_ = 0.0f;
  283. newMorph.buffers_ = morphs[i].buffers_;
  284. for (HashMap<unsigned, VertexBufferMorph>::ConstIterator j = morphs[i].buffers_.Begin(); j != morphs[i].buffers_.End(); ++j)
  285. morphElementMask_ |= j->second_.elementMask_;
  286. morphs_.Push(newMorph);
  287. }
  288. // Copy bounding box & skeleton
  289. SetBoundingBox(model->GetBoundingBox());
  290. SetSkeleton(model->GetSkeleton(), createBones);
  291. ResetLodLevels();
  292. // Enable skinning in batches
  293. for (unsigned i = 0; i < batches_.Size(); ++i)
  294. {
  295. if (skinMatrices_.Size())
  296. {
  297. batches_[i].geometryType_ = GEOM_SKINNED;
  298. // Check if model has per-geometry bone mappings
  299. if (geometrySkinMatrices_.Size() && geometrySkinMatrices_[i].Size())
  300. {
  301. batches_[i].shaderData_ = geometrySkinMatrices_[i][0].Data();
  302. batches_[i].shaderDataSize_ = geometrySkinMatrices_[i].Size() * 12;
  303. }
  304. // If not, use the global skin matrices
  305. else
  306. {
  307. batches_[i].shaderData_ = skinMatrices_[0].Data();
  308. batches_[i].shaderDataSize_ = skinMatrices_.Size() * 12;
  309. }
  310. }
  311. else
  312. {
  313. batches_[i].geometryType_ = GEOM_STATIC;
  314. batches_[i].shaderData_ = 0;
  315. batches_[i].shaderDataSize_ = 0;
  316. }
  317. }
  318. MarkNetworkUpdate();
  319. }
  320. AnimationState* AnimatedModel::AddAnimationState(Animation* animation)
  321. {
  322. if (!isMaster_)
  323. {
  324. LOGERROR("Can not add animation state to non-master model");
  325. return 0;
  326. }
  327. if (!animation || !skeleton_.GetNumBones())
  328. return 0;
  329. // Check for not adding twice
  330. AnimationState* existing = GetAnimationState(animation);
  331. if (existing)
  332. return existing;
  333. SharedPtr<AnimationState> newState(new AnimationState(this, animation));
  334. animationStates_.Push(newState);
  335. MarkAnimationOrderDirty();
  336. return newState;
  337. }
  338. void AnimatedModel::RemoveAnimationState(Animation* animation)
  339. {
  340. if (animation)
  341. RemoveAnimationState(animation->GetNameHash());
  342. else
  343. {
  344. for (Vector<SharedPtr<AnimationState> >::Iterator i = animationStates_.Begin(); i != animationStates_.End(); ++i)
  345. {
  346. AnimationState* state = *i;
  347. if (!state->GetAnimation())
  348. {
  349. animationStates_.Erase(i);
  350. MarkAnimationDirty();
  351. return;
  352. }
  353. }
  354. }
  355. }
  356. void AnimatedModel::RemoveAnimationState(const String& animationName)
  357. {
  358. RemoveAnimationState(StringHash(animationName));
  359. }
  360. void AnimatedModel::RemoveAnimationState(StringHash animationNameHash)
  361. {
  362. for (Vector<SharedPtr<AnimationState> >::Iterator i = animationStates_.Begin(); i != animationStates_.End(); ++i)
  363. {
  364. AnimationState* state = *i;
  365. Animation* animation = state->GetAnimation();
  366. if (animation)
  367. {
  368. // Check both the animation and the resource name
  369. if (animation->GetNameHash() == animationNameHash || animation->GetAnimationNameHash() == animationNameHash)
  370. {
  371. animationStates_.Erase(i);
  372. MarkAnimationDirty();
  373. return;
  374. }
  375. }
  376. }
  377. }
  378. void AnimatedModel::RemoveAnimationState(AnimationState* state)
  379. {
  380. for (Vector<SharedPtr<AnimationState> >::Iterator i = animationStates_.Begin(); i != animationStates_.End(); ++i)
  381. {
  382. if (*i == state)
  383. {
  384. animationStates_.Erase(i);
  385. MarkAnimationDirty();
  386. return;
  387. }
  388. }
  389. }
  390. void AnimatedModel::RemoveAnimationState(unsigned index)
  391. {
  392. if (index < animationStates_.Size())
  393. {
  394. animationStates_.Erase(index);
  395. MarkAnimationDirty();
  396. }
  397. }
  398. void AnimatedModel::RemoveAllAnimationStates()
  399. {
  400. animationStates_.Clear();
  401. MarkAnimationDirty();
  402. }
  403. void AnimatedModel::SetAnimationLodBias(float bias)
  404. {
  405. animationLodBias_ = Max(bias, 0.0f);
  406. MarkNetworkUpdate();
  407. }
  408. void AnimatedModel::SetInvisibleLodFactor(float factor)
  409. {
  410. if (factor < 0.0f)
  411. factor = 0.0f;
  412. else if (factor != 0.0f && factor < 1.0f)
  413. factor = 1.0f;
  414. invisibleLodFactor_ = factor;
  415. MarkNetworkUpdate();
  416. }
  417. void AnimatedModel::SetMorphWeight(unsigned index, float weight)
  418. {
  419. if (index >= morphs_.Size())
  420. return;
  421. // If morph vertex buffers have not been created yet, create now
  422. if (weight > 0.0f && morphVertexBuffers_.Empty())
  423. CloneGeometries();
  424. weight = Clamp(weight, 0.0f, 1.0f);
  425. if (weight != morphs_[index].weight_)
  426. {
  427. morphs_[index].weight_ = weight;
  428. // For a master model, set the same morph weight on non-master models
  429. if (isMaster_)
  430. {
  431. PODVector<AnimatedModel*> models;
  432. GetComponents<AnimatedModel>(models);
  433. // Indexing might not be the same, so use the name hash instead
  434. for (unsigned i = 1; i < models.Size(); ++i)
  435. {
  436. if (!models[i]->isMaster_)
  437. models[i]->SetMorphWeight(morphs_[index].nameHash_, weight);
  438. }
  439. }
  440. MarkMorphsDirty();
  441. MarkNetworkUpdate();
  442. }
  443. }
  444. void AnimatedModel::SetMorphWeight(const String& name, float weight)
  445. {
  446. for (unsigned i = 0; i < morphs_.Size(); ++i)
  447. {
  448. if (morphs_[i].name_ == name)
  449. {
  450. SetMorphWeight(i, weight);
  451. return;
  452. }
  453. }
  454. }
  455. void AnimatedModel::SetMorphWeight(StringHash nameHash, float weight)
  456. {
  457. for (unsigned i = 0; i < morphs_.Size(); ++i)
  458. {
  459. if (morphs_[i].nameHash_ == nameHash)
  460. {
  461. SetMorphWeight(i, weight);
  462. return;
  463. }
  464. }
  465. }
  466. void AnimatedModel::ResetMorphWeights()
  467. {
  468. for (Vector<ModelMorph>::Iterator i = morphs_.Begin(); i != morphs_.End(); ++i)
  469. i->weight_ = 0.0f;
  470. // For a master model, reset weights on non-master models
  471. if (isMaster_)
  472. {
  473. PODVector<AnimatedModel*> models;
  474. GetComponents<AnimatedModel>(models);
  475. for (unsigned i = 1; i < models.Size(); ++i)
  476. {
  477. if (!models[i]->isMaster_)
  478. models[i]->ResetMorphWeights();
  479. }
  480. }
  481. MarkMorphsDirty();
  482. MarkNetworkUpdate();
  483. }
  484. float AnimatedModel::GetMorphWeight(unsigned index) const
  485. {
  486. return index < morphs_.Size() ? morphs_[index].weight_ : 0.0f;
  487. }
  488. float AnimatedModel::GetMorphWeight(const String& name) const
  489. {
  490. for (Vector<ModelMorph>::ConstIterator i = morphs_.Begin(); i != morphs_.End(); ++i)
  491. {
  492. if (i->name_ == name)
  493. return i->weight_;
  494. }
  495. return 0.0f;
  496. }
  497. float AnimatedModel::GetMorphWeight(StringHash nameHash) const
  498. {
  499. for (Vector<ModelMorph>::ConstIterator i = morphs_.Begin(); i != morphs_.End(); ++i)
  500. {
  501. if (i->nameHash_ == nameHash)
  502. return i->weight_;
  503. }
  504. return 0.0f;
  505. }
  506. AnimationState* AnimatedModel::GetAnimationState(Animation* animation) const
  507. {
  508. for (Vector<SharedPtr<AnimationState> >::ConstIterator i = animationStates_.Begin(); i != animationStates_.End(); ++i)
  509. {
  510. if ((*i)->GetAnimation() == animation)
  511. return *i;
  512. }
  513. return 0;
  514. }
  515. AnimationState* AnimatedModel::GetAnimationState(const String& animationName) const
  516. {
  517. return GetAnimationState(StringHash(animationName));
  518. }
  519. AnimationState* AnimatedModel::GetAnimationState(const char* animationName) const
  520. {
  521. return GetAnimationState(StringHash(animationName));
  522. }
  523. AnimationState* AnimatedModel::GetAnimationState(StringHash animationNameHash) const
  524. {
  525. for (Vector<SharedPtr<AnimationState> >::ConstIterator i = animationStates_.Begin(); i != animationStates_.End(); ++i)
  526. {
  527. Animation* animation = (*i)->GetAnimation();
  528. if (animation)
  529. {
  530. // Check both the animation and the resource name
  531. if (animation->GetNameHash() == animationNameHash || animation->GetAnimationNameHash() == animationNameHash)
  532. return *i;
  533. }
  534. }
  535. return 0;
  536. }
  537. AnimationState* AnimatedModel::GetAnimationState(unsigned index) const
  538. {
  539. return index < animationStates_.Size() ? animationStates_[index].Get() : 0;
  540. }
  541. void AnimatedModel::SetSkeleton(const Skeleton& skeleton, bool createBones)
  542. {
  543. if (!node_ && createBones)
  544. {
  545. LOGERROR("AnimatedModel not attached to a scene node, can not create bone nodes");
  546. return;
  547. }
  548. if (isMaster_)
  549. {
  550. // Check if bone structure has stayed compatible (reloading the model.) In that case retain the old bones and animations
  551. if (skeleton_.GetNumBones() == skeleton.GetNumBones())
  552. {
  553. Vector<Bone>& destBones = skeleton_.GetModifiableBones();
  554. const Vector<Bone>& srcBones = skeleton.GetBones();
  555. bool compatible = true;
  556. for (unsigned i = 0; i < destBones.Size(); ++i)
  557. {
  558. if (destBones[i].node_ && destBones[i].name_ == srcBones[i].name_ && destBones[i].parentIndex_ ==
  559. srcBones[i].parentIndex_)
  560. {
  561. // If compatible, just copy the values and retain the old node and animated status
  562. Node* boneNode = destBones[i].node_;
  563. bool animated = destBones[i].animated_;
  564. destBones[i] = srcBones[i];
  565. destBones[i].node_ = boneNode;
  566. destBones[i].animated_ = animated;
  567. }
  568. else
  569. {
  570. compatible = false;
  571. break;
  572. }
  573. }
  574. if (compatible)
  575. return;
  576. }
  577. RemoveAllAnimationStates();
  578. // Detach the rootbone of the previous model if any
  579. if (createBones)
  580. {
  581. Bone* rootBone = skeleton_.GetRootBone();
  582. if (rootBone)
  583. node_->RemoveChild(rootBone->node_);
  584. }
  585. skeleton_.Define(skeleton);
  586. // Remove collision information from dummy bones that do not affect skinning, to prevent them from being merged
  587. // to the bounding box
  588. Vector<Bone>& bones = skeleton_.GetModifiableBones();
  589. for (Vector<Bone>::Iterator i = bones.Begin(); i != bones.End(); ++i)
  590. {
  591. if (i->collisionMask_ & BONECOLLISION_BOX && i->boundingBox_.Size().Length() < M_EPSILON)
  592. i->collisionMask_ &= ~BONECOLLISION_BOX;
  593. if (i->collisionMask_ & BONECOLLISION_SPHERE && i->radius_ < M_EPSILON)
  594. i->collisionMask_ &= ~BONECOLLISION_SPHERE;
  595. }
  596. // Create scene nodes for the bones
  597. if (createBones)
  598. {
  599. for (Vector<Bone>::Iterator i = bones.Begin(); i != bones.End(); ++i)
  600. {
  601. // Create bones as local, as they are never to be directly synchronized over the network
  602. Node* boneNode = node_->CreateChild(i->name_, LOCAL);
  603. boneNode->AddListener(this);
  604. boneNode->SetTransform(i->initialPosition_, i->initialRotation_, i->initialScale_);
  605. i->node_ = boneNode;
  606. }
  607. for (unsigned i = 0; i < bones.Size(); ++i)
  608. {
  609. unsigned parentIndex = bones[i].parentIndex_;
  610. if (parentIndex != i && parentIndex < bones.Size())
  611. bones[parentIndex].node_->AddChild(bones[i].node_);
  612. }
  613. }
  614. MarkAnimationDirty();
  615. using namespace BoneHierarchyCreated;
  616. VariantMap eventData;
  617. eventData[P_NODE] = (void*)node_;
  618. node_->SendEvent(E_BONEHIERARCHYCREATED, eventData);
  619. }
  620. else
  621. {
  622. // For non-master models: use the bone nodes of the master model
  623. skeleton_.Define(skeleton);
  624. if (createBones)
  625. {
  626. Vector<Bone>& bones = skeleton_.GetModifiableBones();
  627. for (Vector<Bone>::Iterator i = bones.Begin(); i != bones.End(); ++i)
  628. {
  629. Node* boneNode = node_->GetChild(i->name_, true);
  630. if (boneNode)
  631. boneNode->AddListener(this);
  632. i->node_ = boneNode;
  633. }
  634. }
  635. }
  636. // Reserve space for skinning matrices
  637. skinMatrices_.Resize(skeleton_.GetNumBones());
  638. SetGeometryBoneMappings();
  639. assignBonesPending_ = !createBones;
  640. }
  641. void AnimatedModel::SetModelAttr(ResourceRef value)
  642. {
  643. ResourceCache* cache = GetSubsystem<ResourceCache>();
  644. // When loading a scene, set model without creating the bone nodes (will be assigned later during post-load)
  645. SetModel(cache->GetResource<Model>(value.id_), !loading_);
  646. }
  647. void AnimatedModel::SetBonesEnabledAttr(VariantVector value)
  648. {
  649. Vector<Bone>& bones = skeleton_.GetModifiableBones();
  650. for (unsigned i = 0; i < bones.Size() && i < value.Size(); ++i)
  651. bones[i].animated_ = value[i].GetBool();
  652. }
  653. void AnimatedModel::SetAnimationStatesAttr(VariantVector value)
  654. {
  655. ResourceCache* cache = GetSubsystem<ResourceCache>();
  656. RemoveAllAnimationStates();
  657. unsigned index = 0;
  658. unsigned numStates = index < value.Size() ? value[index++].GetUInt() : 0;
  659. animationStates_.Reserve(numStates);
  660. while (numStates--)
  661. {
  662. if (index + 5 < value.Size())
  663. {
  664. // Note: null animation is allowed here for editing
  665. const ResourceRef& animRef = value[index++].GetResourceRef();
  666. SharedPtr<AnimationState> newState(new AnimationState(this, cache->GetResource<Animation>(animRef.id_)));
  667. animationStates_.Push(newState);
  668. newState->SetStartBone(skeleton_.GetBone(value[index++].GetString()));
  669. newState->SetLooped(value[index++].GetBool());
  670. newState->SetWeight(value[index++].GetFloat());
  671. newState->SetTime(value[index++].GetFloat());
  672. newState->SetLayer(value[index++].GetInt());
  673. }
  674. else
  675. {
  676. // If not enough data, just add an empty animation state
  677. SharedPtr<AnimationState> newState(new AnimationState(this, 0));
  678. animationStates_.Push(newState);
  679. }
  680. }
  681. MarkAnimationOrderDirty();
  682. }
  683. void AnimatedModel::SetMorphsAttr(const PODVector<unsigned char>& value)
  684. {
  685. for (unsigned index = 0; index < value.Size(); ++index)
  686. SetMorphWeight(index, (float)value[index] / 255.0f);
  687. }
  688. ResourceRef AnimatedModel::GetModelAttr() const
  689. {
  690. return GetResourceRef(model_, Model::GetTypeStatic());
  691. }
  692. VariantVector AnimatedModel::GetBonesEnabledAttr() const
  693. {
  694. VariantVector ret;
  695. const Vector<Bone>& bones = skeleton_.GetBones();
  696. ret.Reserve(bones.Size());
  697. for (Vector<Bone>::ConstIterator i = bones.Begin(); i != bones.End(); ++i)
  698. ret.Push(i->animated_);
  699. return ret;
  700. }
  701. VariantVector AnimatedModel::GetAnimationStatesAttr() const
  702. {
  703. VariantVector ret;
  704. ret.Reserve(animationStates_.Size() * 6 + 1);
  705. ret.Push(animationStates_.Size());
  706. for (Vector<SharedPtr<AnimationState> >::ConstIterator i = animationStates_.Begin(); i != animationStates_.End(); ++i)
  707. {
  708. AnimationState* state = *i;
  709. Animation* animation = state->GetAnimation();
  710. Bone* startBone = state->GetStartBone();
  711. ret.Push(ResourceRef(Animation::GetTypeStatic(), animation ? animation->GetNameHash() : StringHash()));
  712. ret.Push(startBone ? startBone->name_ : String::EMPTY);
  713. ret.Push(state->IsLooped());
  714. ret.Push(state->GetWeight());
  715. ret.Push(state->GetTime());
  716. ret.Push((int)state->GetLayer());
  717. }
  718. return ret;
  719. }
  720. const PODVector<unsigned char>& AnimatedModel::GetMorphsAttr() const
  721. {
  722. attrBuffer_.Clear();
  723. for (Vector<ModelMorph>::ConstIterator i = morphs_.Begin(); i != morphs_.End(); ++i)
  724. attrBuffer_.WriteUByte((unsigned char)(i->weight_ * 255.0f));
  725. return attrBuffer_.GetBuffer();
  726. }
  727. void AnimatedModel::OnNodeSet(Node* node)
  728. {
  729. Drawable::OnNodeSet(node);
  730. // If this AnimatedModel is the first in the node, it is the master which controls animation & morphs
  731. isMaster_ = GetComponent<AnimatedModel>() == this;
  732. }
  733. void AnimatedModel::OnMarkedDirty(Node* node)
  734. {
  735. Drawable::OnMarkedDirty(node);
  736. // If the scene node or any of the bone nodes move, mark skinning dirty
  737. skinningDirty_ = true;
  738. }
  739. void AnimatedModel::OnWorldBoundingBoxUpdate()
  740. {
  741. if (!skeleton_.GetNumBones())
  742. worldBoundingBox_ = boundingBox_.Transformed(node_->GetWorldTransform());
  743. else
  744. {
  745. // If has bones, update world bounding box based on them
  746. worldBoundingBox_.defined_ = false;
  747. const Vector<Bone>& bones = skeleton_.GetBones();
  748. for (Vector<Bone>::ConstIterator i = bones.Begin(); i != bones.End(); ++i)
  749. {
  750. Node* boneNode = i->node_;
  751. if (!boneNode)
  752. continue;
  753. // Use hitbox if available. If not, use only half of the sphere radius
  754. if (i->collisionMask_ & BONECOLLISION_BOX)
  755. worldBoundingBox_.Merge(i->boundingBox_.Transformed(boneNode->GetWorldTransform()));
  756. else if (i->collisionMask_ & BONECOLLISION_SPHERE)
  757. worldBoundingBox_.Merge(Sphere(boneNode->GetWorldPosition(), i->radius_ * 0.5f));
  758. }
  759. }
  760. }
  761. void AnimatedModel::AssignBoneNodes()
  762. {
  763. assignBonesPending_ = false;
  764. if (!node_)
  765. return;
  766. // Find the bone nodes from the node hierarchy and add listeners
  767. Vector<Bone>& bones = skeleton_.GetModifiableBones();
  768. bool boneFound = false;
  769. for (Vector<Bone>::Iterator i = bones.Begin(); i != bones.End(); ++i)
  770. {
  771. Node* boneNode = node_->GetChild(i->name_, true);
  772. if (boneNode)
  773. {
  774. boneFound = true;
  775. boneNode->AddListener(this);
  776. }
  777. i->node_ = boneNode;
  778. }
  779. // If no bones found, this may be a prefab where the bone information was left out.
  780. // In that case reassign the skeleton now if possible
  781. if (!boneFound && model_)
  782. SetSkeleton(model_->GetSkeleton(), true);
  783. // Re-assign the same start bone to animations to get the proper bone node this time
  784. for (Vector<SharedPtr<AnimationState> >::Iterator i = animationStates_.Begin(); i != animationStates_.End(); ++i)
  785. {
  786. AnimationState* state = *i;
  787. state->SetStartBone(state->GetStartBone());
  788. }
  789. MarkAnimationDirty();
  790. }
  791. void AnimatedModel::MarkAnimationDirty()
  792. {
  793. if (isMaster_)
  794. {
  795. animationDirty_ = true;
  796. // Mark for pre-octree reinsertion update (threaded)
  797. MarkForUpdate();
  798. }
  799. }
  800. void AnimatedModel::MarkAnimationOrderDirty()
  801. {
  802. if (isMaster_)
  803. {
  804. animationOrderDirty_ = true;
  805. // Mark for pre-octree reinsertion update (threaded)
  806. MarkForUpdate();
  807. }
  808. }
  809. void AnimatedModel::MarkMorphsDirty()
  810. {
  811. morphsDirty_ = true;
  812. }
  813. void AnimatedModel::CloneGeometries()
  814. {
  815. const Vector<SharedPtr<VertexBuffer> >& originalVertexBuffers = model_->GetVertexBuffers();
  816. HashMap<VertexBuffer*, SharedPtr<VertexBuffer> > clonedVertexBuffers;
  817. morphVertexBuffers_.Resize(originalVertexBuffers.Size());
  818. for (unsigned i = 0; i < originalVertexBuffers.Size(); ++i)
  819. {
  820. VertexBuffer* original = originalVertexBuffers[i];
  821. if (model_->GetMorphRangeCount(i))
  822. {
  823. SharedPtr<VertexBuffer> clone(new VertexBuffer(context_));
  824. clone->SetShadowed(true);
  825. clone->SetSize(original->GetVertexCount(), morphElementMask_ & original->GetElementMask(), true);
  826. void* dest = clone->Lock(0, original->GetVertexCount());
  827. if (dest)
  828. {
  829. CopyMorphVertices(dest, original->GetShadowData(), original->GetVertexCount(), clone, original);
  830. clone->Unlock();
  831. }
  832. clonedVertexBuffers[original] = clone;
  833. morphVertexBuffers_[i] = clone;
  834. }
  835. else
  836. morphVertexBuffers_[i].Reset();
  837. }
  838. // Geometries will always be cloned fully. They contain only references to buffer, so they are relatively light
  839. for (unsigned i = 0; i < geometries_.Size(); ++i)
  840. {
  841. for (unsigned j = 0; j < geometries_[i].Size(); ++j)
  842. {
  843. SharedPtr<Geometry> original = geometries_[i][j];
  844. SharedPtr<Geometry> clone(new Geometry(context_));
  845. // Add an additional vertex stream into the clone, which supplies only the morphable vertex data, while the static
  846. // data comes from the original vertex buffer(s)
  847. const Vector<SharedPtr<VertexBuffer> >& originalBuffers = original->GetVertexBuffers();
  848. unsigned totalBuf = originalBuffers.Size();
  849. for (unsigned k = 0; k < originalBuffers.Size(); ++k)
  850. {
  851. VertexBuffer* originalBuffer = originalBuffers[k];
  852. if (clonedVertexBuffers.Contains(originalBuffer))
  853. ++totalBuf;
  854. }
  855. clone->SetNumVertexBuffers(totalBuf);
  856. unsigned l = 0;
  857. for (unsigned k = 0; k < originalBuffers.Size(); ++k)
  858. {
  859. VertexBuffer* originalBuffer = originalBuffers[k];
  860. unsigned originalMask = original->GetVertexElementMask(k);
  861. if (clonedVertexBuffers.Contains(originalBuffer))
  862. {
  863. VertexBuffer* clonedBuffer = clonedVertexBuffers[originalBuffer];
  864. clone->SetVertexBuffer(l++, originalBuffer, originalMask & ~clonedBuffer->GetElementMask());
  865. clone->SetVertexBuffer(l++, clonedBuffer, originalMask & clonedBuffer->GetElementMask());
  866. }
  867. else
  868. clone->SetVertexBuffer(l++, originalBuffer, originalMask);
  869. }
  870. clone->SetIndexBuffer(original->GetIndexBuffer());
  871. clone->SetDrawRange(original->GetPrimitiveType(), original->GetIndexStart(), original->GetIndexCount());
  872. clone->SetLodDistance(original->GetLodDistance());
  873. geometries_[i][j] = clone;
  874. }
  875. }
  876. // Make sure the rendering batches use the new cloned geometries
  877. ResetLodLevels();
  878. MarkMorphsDirty();
  879. }
  880. void AnimatedModel::CopyMorphVertices(void* destVertexData, void* srcVertexData, unsigned vertexCount, VertexBuffer* destBuffer, VertexBuffer* srcBuffer)
  881. {
  882. unsigned mask = destBuffer->GetElementMask() & srcBuffer->GetElementMask();
  883. unsigned normalOffset = srcBuffer->GetElementOffset(ELEMENT_NORMAL);
  884. unsigned tangentOffset = srcBuffer->GetElementOffset(ELEMENT_TANGENT);
  885. unsigned vertexSize = srcBuffer->GetVertexSize();
  886. float* dest = (float*)destVertexData;
  887. unsigned char* src = (unsigned char*)srcVertexData;
  888. while (vertexCount--)
  889. {
  890. if (mask & MASK_POSITION)
  891. {
  892. float* posSrc = (float*)src;
  893. *dest++ = posSrc[0];
  894. *dest++ = posSrc[1];
  895. *dest++ = posSrc[2];
  896. }
  897. if (mask & MASK_NORMAL)
  898. {
  899. float* normalSrc = (float*)(src + normalOffset);
  900. *dest++ = normalSrc[0];
  901. *dest++ = normalSrc[1];
  902. *dest++ = normalSrc[2];
  903. }
  904. if (mask & MASK_TANGENT)
  905. {
  906. float* tangentSrc = (float*)(src + tangentOffset);
  907. *dest++ = tangentSrc[0];
  908. *dest++ = tangentSrc[1];
  909. *dest++ = tangentSrc[2];
  910. *dest++ = tangentSrc[3];
  911. }
  912. src += vertexSize;
  913. }
  914. }
  915. void AnimatedModel::SetGeometryBoneMappings()
  916. {
  917. geometrySkinMatrices_.Clear();
  918. geometrySkinMatrixPtrs_.Clear();
  919. if (!geometryBoneMappings_.Size())
  920. return;
  921. // Check if all mappings are empty, then we do not need to use mapped skinning
  922. bool allEmpty = true;
  923. for (unsigned i = 0; i < geometryBoneMappings_.Size(); ++i)
  924. if (geometryBoneMappings_[i].Size())
  925. allEmpty = false;
  926. if (allEmpty)
  927. return;
  928. // Reserve space for per-geometry skinning matrices
  929. geometrySkinMatrices_.Resize(geometryBoneMappings_.Size());
  930. for (unsigned i = 0; i < geometryBoneMappings_.Size(); ++i)
  931. geometrySkinMatrices_[i].Resize(geometryBoneMappings_[i].Size());
  932. // Build original-to-skinindex matrix pointer mapping for fast copying
  933. // Note: at this point layout of geometrySkinMatrices_ cannot be modified or pointers become invalid
  934. geometrySkinMatrixPtrs_.Resize(skeleton_.GetNumBones());
  935. for (unsigned i = 0; i < geometryBoneMappings_.Size(); ++i)
  936. {
  937. for (unsigned j = 0; j < geometryBoneMappings_[i].Size(); ++j)
  938. geometrySkinMatrixPtrs_[geometryBoneMappings_[i][j]].Push(&geometrySkinMatrices_[i][j]);
  939. }
  940. }
  941. void AnimatedModel::UpdateAnimation(const FrameInfo& frame)
  942. {
  943. // If using animation LOD, accumulate time and see if it is time to update
  944. if (animationLodBias_ > 0.0f && animationLodDistance_ > 0.0f)
  945. {
  946. // Check for first time update
  947. if (animationLodTimer_ >= 0.0f)
  948. {
  949. animationLodTimer_ += animationLodBias_ * frame.timeStep_ * ANIMATION_LOD_BASESCALE;
  950. if (animationLodTimer_ >= animationLodDistance_)
  951. animationLodTimer_ = fmodf(animationLodTimer_, animationLodDistance_);
  952. else
  953. return;
  954. }
  955. else
  956. animationLodTimer_ = 0.0f;
  957. }
  958. // Make sure animations are in ascending priority order
  959. if (animationOrderDirty_)
  960. {
  961. Sort(animationStates_.Begin(), animationStates_.End(), CompareAnimationOrder);
  962. animationOrderDirty_ = false;
  963. }
  964. // Reset skeleton, then apply all animations
  965. skeleton_.Reset();
  966. for (Vector<SharedPtr<AnimationState> >::Iterator i = animationStates_.Begin(); i != animationStates_.End(); ++i)
  967. (*i)->Apply();
  968. // Animation has changed the bounding box: mark node for octree reinsertion
  969. Drawable::OnMarkedDirty(node_);
  970. // For optimization, recalculate world bounding box already here (during the threaded update)
  971. GetWorldBoundingBox();
  972. animationDirty_ = false;
  973. }
  974. void AnimatedModel::UpdateSkinning()
  975. {
  976. // Note: the model's world transform will be baked in the skin matrices
  977. const Vector<Bone>& bones = skeleton_.GetBones();
  978. // Use model's world transform in case a bone is missing
  979. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  980. // Skinning with global matrices only
  981. if (!geometrySkinMatrices_.Size())
  982. {
  983. for (unsigned i = 0; i < bones.Size(); ++i)
  984. {
  985. const Bone& bone = bones[i];
  986. if (bone.node_)
  987. skinMatrices_[i] = bone.node_->GetWorldTransform() * bone.offsetMatrix_;
  988. else
  989. skinMatrices_[i] = worldTransform;
  990. }
  991. }
  992. // Skinning with per-geometry matrices
  993. else
  994. {
  995. for (unsigned i = 0; i < bones.Size(); ++i)
  996. {
  997. const Bone& bone = bones[i];
  998. if (bone.node_)
  999. skinMatrices_[i] = bone.node_->GetWorldTransform() * bone.offsetMatrix_;
  1000. else
  1001. skinMatrices_[i] = worldTransform;
  1002. // Copy the skin matrix to per-geometry matrices as needed
  1003. for (unsigned j = 0; j < geometrySkinMatrixPtrs_[i].Size(); ++j)
  1004. *geometrySkinMatrixPtrs_[i][j] = skinMatrices_[i];
  1005. }
  1006. }
  1007. skinningDirty_ = false;
  1008. }
  1009. void AnimatedModel::UpdateMorphs()
  1010. {
  1011. Graphics* graphics = GetSubsystem<Graphics>();
  1012. if (!graphics)
  1013. return;
  1014. if (morphs_.Size())
  1015. {
  1016. // Reset the morph data range from all morphable vertex buffers, then apply morphs
  1017. for (unsigned i = 0; i < morphVertexBuffers_.Size(); ++i)
  1018. {
  1019. VertexBuffer* buffer = morphVertexBuffers_[i];
  1020. if (buffer)
  1021. {
  1022. VertexBuffer* originalBuffer = model_->GetVertexBuffers()[i];
  1023. unsigned morphStart = model_->GetMorphRangeStart(i);
  1024. unsigned morphCount = model_->GetMorphRangeCount(i);
  1025. void* dest = buffer->Lock(morphStart, morphCount);
  1026. if (dest)
  1027. {
  1028. // Reset morph range by copying data from the original vertex buffer
  1029. CopyMorphVertices(dest, originalBuffer->GetShadowData() + morphStart * originalBuffer->GetVertexSize(),
  1030. morphCount, buffer, originalBuffer);
  1031. for (unsigned j = 0; j < morphs_.Size(); ++j)
  1032. {
  1033. if (morphs_[j].weight_ > 0.0f)
  1034. {
  1035. HashMap<unsigned, VertexBufferMorph>::Iterator k = morphs_[j].buffers_.Find(i);
  1036. if (k != morphs_[j].buffers_.End())
  1037. ApplyMorph(buffer, dest, morphStart, k->second_, morphs_[j].weight_);
  1038. }
  1039. }
  1040. buffer->Unlock();
  1041. }
  1042. }
  1043. }
  1044. }
  1045. morphsDirty_ = false;
  1046. }
  1047. void AnimatedModel::ApplyMorph(VertexBuffer* buffer, void* destVertexData, unsigned morphRangeStart, const VertexBufferMorph& morph, float weight)
  1048. {
  1049. unsigned elementMask = morph.elementMask_ & buffer->GetElementMask();
  1050. unsigned vertexCount = morph.vertexCount_;
  1051. unsigned normalOffset = buffer->GetElementOffset(ELEMENT_NORMAL);
  1052. unsigned tangentOffset = buffer->GetElementOffset(ELEMENT_TANGENT);
  1053. unsigned vertexSize = buffer->GetVertexSize();
  1054. unsigned char* srcData = morph.morphData_;
  1055. unsigned char* destData = (unsigned char*)destVertexData;
  1056. while (vertexCount--)
  1057. {
  1058. unsigned vertexIndex = *((unsigned*)srcData) - morphRangeStart;
  1059. srcData += sizeof(unsigned);
  1060. if (elementMask & MASK_POSITION)
  1061. {
  1062. float* dest = (float*)(destData + vertexIndex * vertexSize);
  1063. float* src = (float*)srcData;
  1064. dest[0] += src[0] * weight;
  1065. dest[1] += src[1] * weight;
  1066. dest[2] += src[2] * weight;
  1067. srcData += 3 * sizeof(float);
  1068. }
  1069. if (elementMask & MASK_NORMAL)
  1070. {
  1071. float* dest = (float*)(destData + vertexIndex * vertexSize + normalOffset);
  1072. float* src = (float*)srcData;
  1073. dest[0] += src[0] * weight;
  1074. dest[1] += src[1] * weight;
  1075. dest[2] += src[2] * weight;
  1076. srcData += 3 * sizeof(float);
  1077. }
  1078. if (elementMask & MASK_TANGENT)
  1079. {
  1080. float* dest = (float*)(destData + vertexIndex * vertexSize + tangentOffset);
  1081. float* src = (float*)srcData;
  1082. dest[0] += src[0] * weight;
  1083. dest[1] += src[1] * weight;
  1084. dest[2] += src[2] * weight;
  1085. srcData += 3 * sizeof(float);
  1086. }
  1087. }
  1088. }
  1089. void AnimatedModel::HandleModelReloadFinished(StringHash eventType, VariantMap& eventData)
  1090. {
  1091. Model* currentModel = model_;
  1092. model_.Reset(); // Set null to allow to be re-set
  1093. SetModel(currentModel);
  1094. }
  1095. }