AnimatedModel.cpp 36 KB

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