AnimatedModel.cpp 37 KB

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