AnimatedModel.cpp 38 KB

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