AnimatedModel.cpp 40 KB

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