AnimatedModel.cpp 40 KB

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