AnimatedModel.cpp 37 KB

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