AnimatedModel.cpp 39 KB

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