AnimatedModel.cpp 37 KB

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