AnimatedModel.cpp 46 KB

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