AnimatedModel.cpp 39 KB

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