AnimatedModel.cpp 40 KB

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