AnimatedModel.cpp 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376
  1. //
  2. // Copyright (c) 2008-2015 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../Core/Context.h"
  24. #include "../Core/Profiler.h"
  25. #include "../Atomic3D/AnimatedModel.h"
  26. #include "../Atomic3D/Animation.h"
  27. #include "../Atomic3D/AnimationState.h"
  28. #include "../Graphics/Batch.h"
  29. #include "../Graphics/Camera.h"
  30. #include "../Graphics/DebugRenderer.h"
  31. #include "../Graphics/DrawableEvents.h"
  32. #include "../Graphics/Geometry.h"
  33. #include "../Graphics/Graphics.h"
  34. #include "../Graphics/IndexBuffer.h"
  35. #include "../Graphics/Material.h"
  36. #include "../Graphics/Octree.h"
  37. #include "../Graphics/VertexBuffer.h"
  38. #include "../IO/Log.h"
  39. #include "../Resource/ResourceCache.h"
  40. #include "../Resource/ResourceEvents.h"
  41. #include "../Scene/Scene.h"
  42. #include "../DebugNew.h"
  43. namespace Atomic
  44. {
  45. extern const char* GEOMETRY_CATEGORY;
  46. static bool CompareAnimationOrder(const SharedPtr<AnimationState>& lhs, const SharedPtr<AnimationState>& rhs)
  47. {
  48. return lhs->GetLayer() < rhs->GetLayer();
  49. }
  50. static const unsigned MAX_ANIMATION_STATES = 256;
  51. bool AnimatedModel::boneCreationEnabled_ = true;
  52. AnimatedModel::AnimatedModel(Context* context) :
  53. StaticModel(context),
  54. animationLodFrameNumber_(0),
  55. morphElementMask_(0),
  56. animationLodBias_(1.0f),
  57. animationLodTimer_(-1.0f),
  58. animationLodDistance_(0.0f),
  59. updateInvisible_(false),
  60. animationDirty_(false),
  61. animationOrderDirty_(false),
  62. morphsDirty_(false),
  63. skinningDirty_(true),
  64. boneBoundingBoxDirty_(true),
  65. isMaster_(true),
  66. loading_(false),
  67. assignBonesPending_(false),
  68. forceAnimationUpdate_(false)
  69. {
  70. }
  71. AnimatedModel::~AnimatedModel()
  72. {
  73. // When being destroyed, remove the bone hierarchy if appropriate (last AnimatedModel in the node)
  74. Bone* rootBone = skeleton_.GetRootBone();
  75. if (rootBone && rootBone->node_)
  76. {
  77. Node* parent = rootBone->node_->GetParent();
  78. if (parent && !parent->GetComponent<AnimatedModel>())
  79. RemoveRootBone();
  80. }
  81. }
  82. void AnimatedModel::RegisterObject(Context* context)
  83. {
  84. context->RegisterFactory<AnimatedModel>(GEOMETRY_CATEGORY);
  85. ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  86. MIXED_ACCESSOR_ATTRIBUTE("Model", GetModelAttr, SetModelAttr, ResourceRef, ResourceRef(Model::GetTypeStatic()), AM_DEFAULT);
  87. ACCESSOR_ATTRIBUTE("Material", GetMaterialsAttr, SetMaterialsAttr, ResourceRefList, ResourceRefList(Material::GetTypeStatic()),
  88. AM_DEFAULT);
  89. ATTRIBUTE("Is Occluder", bool, occluder_, false, AM_DEFAULT);
  90. ACCESSOR_ATTRIBUTE("Can Be Occluded", IsOccludee, SetOccludee, bool, true, AM_DEFAULT);
  91. ATTRIBUTE("Cast Shadows", bool, castShadows_, false, AM_DEFAULT);
  92. ACCESSOR_ATTRIBUTE("Update When Invisible", GetUpdateInvisible, SetUpdateInvisible, bool, false, AM_DEFAULT);
  93. ACCESSOR_ATTRIBUTE("Draw Distance", GetDrawDistance, SetDrawDistance, float, 0.0f, AM_DEFAULT);
  94. ACCESSOR_ATTRIBUTE("Shadow Distance", GetShadowDistance, SetShadowDistance, float, 0.0f, AM_DEFAULT);
  95. ACCESSOR_ATTRIBUTE("LOD Bias", GetLodBias, SetLodBias, float, 1.0f, AM_DEFAULT);
  96. ACCESSOR_ATTRIBUTE("Animation LOD Bias", GetAnimationLodBias, SetAnimationLodBias, float, 1.0f, AM_DEFAULT);
  97. COPY_BASE_ATTRIBUTES(Drawable);
  98. MIXED_ACCESSOR_ATTRIBUTE("Bone Animation Enabled", GetBonesEnabledAttr, SetBonesEnabledAttr, VariantVector,
  99. Variant::emptyVariantVector, AM_FILE | AM_NOEDIT);
  100. MIXED_ACCESSOR_ATTRIBUTE("Animation States", GetAnimationStatesAttr, SetAnimationStatesAttr, VariantVector,
  101. Variant::emptyVariantVector, AM_FILE);
  102. ACCESSOR_ATTRIBUTE("Morphs", GetMorphsAttr, SetMorphsAttr, PODVector<unsigned char>, Variant::emptyBuffer,
  103. AM_DEFAULT | AM_NOEDIT);
  104. }
  105. bool AnimatedModel::Load(Deserializer& source, bool setInstanceDefault)
  106. {
  107. loading_ = true;
  108. bool success = Component::Load(source, setInstanceDefault);
  109. loading_ = false;
  110. return success;
  111. }
  112. bool AnimatedModel::LoadXML(const XMLElement& source, bool setInstanceDefault)
  113. {
  114. loading_ = true;
  115. bool success = Component::LoadXML(source, setInstanceDefault);
  116. loading_ = false;
  117. return success;
  118. }
  119. void AnimatedModel::ApplyAttributes()
  120. {
  121. if (assignBonesPending_)
  122. AssignBoneNodes();
  123. }
  124. void AnimatedModel::ProcessRayQuery(const RayOctreeQuery& query, PODVector<RayQueryResult>& results)
  125. {
  126. // If no bones or no bone-level testing, use the StaticModel test
  127. RayQueryLevel level = query.level_;
  128. if (level < RAY_TRIANGLE || !skeleton_.GetNumBones() || !boneCreationEnabled_)
  129. {
  130. StaticModel::ProcessRayQuery(query, results);
  131. return;
  132. }
  133. // Check ray hit distance to AABB before proceeding with bone-level tests
  134. if (query.ray_.HitDistance(GetWorldBoundingBox()) >= query.maxDistance_)
  135. return;
  136. const Vector<Bone>& bones = skeleton_.GetBones();
  137. Sphere boneSphere;
  138. for (unsigned i = 0; i < bones.Size(); ++i)
  139. {
  140. const Bone& bone = bones[i];
  141. if (!bone.node_)
  142. continue;
  143. float distance;
  144. // Use hitbox if available
  145. if (bone.collisionMask_ & BONECOLLISION_BOX)
  146. {
  147. // Do an initial crude test using the bone's AABB
  148. const BoundingBox& box = bone.boundingBox_;
  149. const Matrix3x4& transform = bone.node_->GetWorldTransform();
  150. distance = query.ray_.HitDistance(box.Transformed(transform));
  151. if (distance >= query.maxDistance_)
  152. continue;
  153. if (level != RAY_AABB)
  154. {
  155. // Follow with an OBB test if required
  156. Matrix3x4 inverse = transform.Inverse();
  157. Ray localRay = query.ray_.Transformed(inverse);
  158. distance = localRay.HitDistance(box);
  159. if (distance >= query.maxDistance_)
  160. continue;
  161. }
  162. }
  163. else if (bone.collisionMask_ & BONECOLLISION_SPHERE)
  164. {
  165. boneSphere.center_ = bone.node_->GetWorldPosition();
  166. boneSphere.radius_ = bone.radius_;
  167. distance = query.ray_.HitDistance(boneSphere);
  168. if (distance >= query.maxDistance_)
  169. continue;
  170. }
  171. else
  172. continue;
  173. // If the code reaches here then we have a hit
  174. RayQueryResult result;
  175. result.position_ = query.ray_.origin_ + distance * query.ray_.direction_;
  176. result.normal_ = -query.ray_.direction_;
  177. result.distance_ = distance;
  178. result.drawable_ = this;
  179. result.node_ = node_;
  180. result.subObject_ = i;
  181. results.Push(result);
  182. }
  183. }
  184. void AnimatedModel::Update(const FrameInfo& frame)
  185. {
  186. // If node was invisible last frame, need to decide animation LOD distance here
  187. // If headless, retain the current animation distance (should be 0)
  188. if (frame.camera_ && abs((int)frame.frameNumber_ - (int)viewFrameNumber_) > 1)
  189. {
  190. // First check for no update at all when invisible. In that case reset LOD timer to ensure update
  191. // next time the model is in view
  192. if (!updateInvisible_)
  193. {
  194. if (animationDirty_)
  195. {
  196. animationLodTimer_ = -1.0f;
  197. forceAnimationUpdate_ = true;
  198. }
  199. return;
  200. }
  201. float distance = frame.camera_->GetDistance(node_->GetWorldPosition());
  202. // If distance is greater than draw distance, no need to update at all
  203. if (drawDistance_ > 0.0f && distance > drawDistance_)
  204. return;
  205. float scale = GetWorldBoundingBox().Size().DotProduct(DOT_SCALE);
  206. animationLodDistance_ = frame.camera_->GetLodDistance(distance, scale, lodBias_);
  207. }
  208. if (animationDirty_ || animationOrderDirty_)
  209. UpdateAnimation(frame);
  210. else if (boneBoundingBoxDirty_)
  211. UpdateBoneBoundingBox();
  212. }
  213. void AnimatedModel::UpdateBatches(const FrameInfo& frame)
  214. {
  215. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  216. const BoundingBox& worldBoundingBox = GetWorldBoundingBox();
  217. distance_ = frame.camera_->GetDistance(worldBoundingBox.Center());
  218. // Note: per-geometry distances do not take skinning into account. Especially in case of a ragdoll they may be
  219. // much off base if the node's own transform is not updated
  220. if (batches_.Size() == 1)
  221. batches_[0].distance_ = distance_;
  222. else
  223. {
  224. for (unsigned i = 0; i < batches_.Size(); ++i)
  225. batches_[i].distance_ = frame.camera_->GetDistance(worldTransform * geometryData_[i].center_);
  226. }
  227. // Use a transformed version of the model's bounding box instead of world bounding box for LOD scale
  228. // determination so that animation does not change the scale
  229. BoundingBox transformedBoundingBox = boundingBox_.Transformed(worldTransform);
  230. float scale = transformedBoundingBox.Size().DotProduct(DOT_SCALE);
  231. float newLodDistance = frame.camera_->GetLodDistance(distance_, scale, lodBias_);
  232. // If model is rendered from several views, use the minimum LOD distance for animation LOD
  233. if (frame.frameNumber_ != animationLodFrameNumber_)
  234. {
  235. animationLodDistance_ = newLodDistance;
  236. animationLodFrameNumber_ = frame.frameNumber_;
  237. }
  238. else
  239. animationLodDistance_ = Min(animationLodDistance_, newLodDistance);
  240. if (newLodDistance != lodDistance_)
  241. {
  242. lodDistance_ = newLodDistance;
  243. CalculateLodLevels();
  244. }
  245. }
  246. void AnimatedModel::UpdateGeometry(const FrameInfo& frame)
  247. {
  248. // Late update in case the model came into view and animation was dirtied in the meanwhile
  249. if (forceAnimationUpdate_)
  250. {
  251. UpdateAnimation(frame);
  252. forceAnimationUpdate_ = false;
  253. }
  254. if (morphsDirty_)
  255. UpdateMorphs();
  256. if (skinningDirty_)
  257. UpdateSkinning();
  258. }
  259. UpdateGeometryType AnimatedModel::GetUpdateGeometryType()
  260. {
  261. if (morphsDirty_ || forceAnimationUpdate_)
  262. return UPDATE_MAIN_THREAD;
  263. else if (skinningDirty_)
  264. return UPDATE_WORKER_THREAD;
  265. else
  266. return UPDATE_NONE;
  267. }
  268. void AnimatedModel::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  269. {
  270. if (debug && IsEnabledEffective())
  271. {
  272. debug->AddBoundingBox(GetWorldBoundingBox(), Color::GREEN, depthTest);
  273. debug->AddSkeleton(skeleton_, Color(0.75f, 0.75f, 0.75f), depthTest);
  274. }
  275. }
  276. void AnimatedModel::SetModel(Model* model, bool createBones)
  277. {
  278. if (model == model_)
  279. return;
  280. // Unsubscribe from the reload event of previous model (if any), then subscribe to the new
  281. if (model_)
  282. UnsubscribeFromEvent(model_, E_RELOADFINISHED);
  283. model_ = model;
  284. if (model)
  285. {
  286. SubscribeToEvent(model, E_RELOADFINISHED, HANDLER(AnimatedModel, HandleModelReloadFinished));
  287. // Copy the subgeometry & LOD level structure
  288. SetNumGeometries(model->GetNumGeometries());
  289. const Vector<Vector<SharedPtr<Geometry> > >& geometries = model->GetGeometries();
  290. const PODVector<Vector3>& geometryCenters = model->GetGeometryCenters();
  291. for (unsigned i = 0; i < geometries.Size(); ++i)
  292. {
  293. geometries_[i] = geometries[i];
  294. geometryData_[i].center_ = geometryCenters[i];
  295. }
  296. // Copy geometry bone mappings
  297. const Vector<PODVector<unsigned> >& geometryBoneMappings = model->GetGeometryBoneMappings();
  298. geometryBoneMappings_.Clear();
  299. geometryBoneMappings_.Reserve(geometryBoneMappings.Size());
  300. for (unsigned i = 0; i < geometryBoneMappings.Size(); ++i)
  301. geometryBoneMappings_.Push(geometryBoneMappings[i]);
  302. // Copy morphs. Note: morph vertex buffers will be created later on-demand
  303. morphVertexBuffers_.Clear();
  304. morphs_.Clear();
  305. const Vector<ModelMorph>& morphs = model->GetMorphs();
  306. morphs_.Reserve(morphs.Size());
  307. morphElementMask_ = 0;
  308. for (unsigned i = 0; i < morphs.Size(); ++i)
  309. {
  310. ModelMorph newMorph;
  311. newMorph.name_ = morphs[i].name_;
  312. newMorph.nameHash_ = morphs[i].nameHash_;
  313. newMorph.weight_ = 0.0f;
  314. newMorph.buffers_ = morphs[i].buffers_;
  315. for (HashMap<unsigned, VertexBufferMorph>::ConstIterator j = morphs[i].buffers_.Begin();
  316. j != morphs[i].buffers_.End(); ++j)
  317. morphElementMask_ |= j->second_.elementMask_;
  318. morphs_.Push(newMorph);
  319. }
  320. // Copy bounding box & skeleton
  321. SetBoundingBox(model->GetBoundingBox());
  322. // Initial bone bounding box is just the one stored in the model
  323. boneBoundingBox_ = boundingBox_;
  324. boneBoundingBoxDirty_ = true;
  325. SetSkeleton(model->GetSkeleton(), createBones);
  326. ResetLodLevels();
  327. // Enable skinning in batches
  328. for (unsigned i = 0; i < batches_.Size(); ++i)
  329. {
  330. if (skinMatrices_.Size())
  331. {
  332. batches_[i].geometryType_ = GEOM_SKINNED;
  333. // Check if model has per-geometry bone mappings
  334. if (geometrySkinMatrices_.Size() && geometrySkinMatrices_[i].Size())
  335. {
  336. batches_[i].worldTransform_ = &geometrySkinMatrices_[i][0];
  337. batches_[i].numWorldTransforms_ = geometrySkinMatrices_[i].Size();
  338. }
  339. // If not, use the global skin matrices
  340. else
  341. {
  342. batches_[i].worldTransform_ = &skinMatrices_[0];
  343. batches_[i].numWorldTransforms_ = skinMatrices_.Size();
  344. }
  345. }
  346. else
  347. {
  348. batches_[i].geometryType_ = GEOM_STATIC;
  349. batches_[i].worldTransform_ = &node_->GetWorldTransform();
  350. batches_[i].numWorldTransforms_ = 1;
  351. }
  352. }
  353. }
  354. else
  355. {
  356. RemoveRootBone(); // Remove existing root bone if any
  357. SetNumGeometries(0);
  358. geometryBoneMappings_.Clear();
  359. morphVertexBuffers_.Clear();
  360. morphs_.Clear();
  361. morphElementMask_ = 0;
  362. SetBoundingBox(BoundingBox());
  363. SetSkeleton(Skeleton(), false);
  364. }
  365. MarkNetworkUpdate();
  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. else
  390. {
  391. for (Vector<SharedPtr<AnimationState> >::Iterator i = animationStates_.Begin(); i != animationStates_.End(); ++i)
  392. {
  393. AnimationState* state = *i;
  394. if (!state->GetAnimation())
  395. {
  396. animationStates_.Erase(i);
  397. MarkAnimationDirty();
  398. return;
  399. }
  400. }
  401. }
  402. }
  403. void AnimatedModel::RemoveAnimationState(const String& animationName)
  404. {
  405. RemoveAnimationState(StringHash(animationName));
  406. }
  407. void AnimatedModel::RemoveAnimationState(StringHash animationNameHash)
  408. {
  409. for (Vector<SharedPtr<AnimationState> >::Iterator i = animationStates_.Begin(); i != animationStates_.End(); ++i)
  410. {
  411. AnimationState* state = *i;
  412. Animation* animation = state->GetAnimation();
  413. if (animation)
  414. {
  415. // Check both the animation and the resource name
  416. if (animation->GetNameHash() == animationNameHash || animation->GetAnimationNameHash() == animationNameHash)
  417. {
  418. animationStates_.Erase(i);
  419. MarkAnimationDirty();
  420. return;
  421. }
  422. }
  423. }
  424. }
  425. void AnimatedModel::RemoveAnimationState(AnimationState* state)
  426. {
  427. for (Vector<SharedPtr<AnimationState> >::Iterator i = animationStates_.Begin(); i != animationStates_.End(); ++i)
  428. {
  429. if (*i == state)
  430. {
  431. animationStates_.Erase(i);
  432. MarkAnimationDirty();
  433. return;
  434. }
  435. }
  436. }
  437. void AnimatedModel::RemoveAnimationState(unsigned index)
  438. {
  439. if (index < animationStates_.Size())
  440. {
  441. animationStates_.Erase(index);
  442. MarkAnimationDirty();
  443. }
  444. }
  445. void AnimatedModel::RemoveAllAnimationStates()
  446. {
  447. if (animationStates_.Size())
  448. {
  449. animationStates_.Clear();
  450. MarkAnimationDirty();
  451. }
  452. }
  453. void AnimatedModel::SetAnimationLodBias(float bias)
  454. {
  455. animationLodBias_ = Max(bias, 0.0f);
  456. MarkNetworkUpdate();
  457. }
  458. void AnimatedModel::SetUpdateInvisible(bool enable)
  459. {
  460. updateInvisible_ = enable;
  461. MarkNetworkUpdate();
  462. }
  463. void AnimatedModel::SetMorphWeight(unsigned index, float weight)
  464. {
  465. if (index >= morphs_.Size())
  466. return;
  467. // If morph vertex buffers have not been created yet, create now
  468. if (weight > 0.0f && morphVertexBuffers_.Empty())
  469. CloneGeometries();
  470. weight = Clamp(weight, 0.0f, 1.0f);
  471. if (weight != morphs_[index].weight_)
  472. {
  473. morphs_[index].weight_ = weight;
  474. // For a master model, set the same morph weight on non-master models
  475. if (isMaster_)
  476. {
  477. PODVector<AnimatedModel*> models;
  478. GetComponents<AnimatedModel>(models);
  479. // Indexing might not be the same, so use the name hash instead
  480. for (unsigned i = 1; i < models.Size(); ++i)
  481. {
  482. if (!models[i]->isMaster_)
  483. models[i]->SetMorphWeight(morphs_[index].nameHash_, weight);
  484. }
  485. }
  486. MarkMorphsDirty();
  487. MarkNetworkUpdate();
  488. }
  489. }
  490. void AnimatedModel::SetMorphWeight(const String& name, float weight)
  491. {
  492. for (unsigned i = 0; i < morphs_.Size(); ++i)
  493. {
  494. if (morphs_[i].name_ == name)
  495. {
  496. SetMorphWeight(i, weight);
  497. return;
  498. }
  499. }
  500. }
  501. void AnimatedModel::SetMorphWeight(StringHash nameHash, float weight)
  502. {
  503. for (unsigned i = 0; i < morphs_.Size(); ++i)
  504. {
  505. if (morphs_[i].nameHash_ == nameHash)
  506. {
  507. SetMorphWeight(i, weight);
  508. return;
  509. }
  510. }
  511. }
  512. void AnimatedModel::ResetMorphWeights()
  513. {
  514. for (Vector<ModelMorph>::Iterator i = morphs_.Begin(); i != morphs_.End(); ++i)
  515. i->weight_ = 0.0f;
  516. // For a master model, reset weights on non-master models
  517. if (isMaster_)
  518. {
  519. PODVector<AnimatedModel*> models;
  520. GetComponents<AnimatedModel>(models);
  521. for (unsigned i = 1; i < models.Size(); ++i)
  522. {
  523. if (!models[i]->isMaster_)
  524. models[i]->ResetMorphWeights();
  525. }
  526. }
  527. MarkMorphsDirty();
  528. MarkNetworkUpdate();
  529. }
  530. float AnimatedModel::GetMorphWeight(unsigned index) const
  531. {
  532. return index < morphs_.Size() ? morphs_[index].weight_ : 0.0f;
  533. }
  534. float AnimatedModel::GetMorphWeight(const String& name) const
  535. {
  536. for (Vector<ModelMorph>::ConstIterator i = morphs_.Begin(); i != morphs_.End(); ++i)
  537. {
  538. if (i->name_ == name)
  539. return i->weight_;
  540. }
  541. return 0.0f;
  542. }
  543. float AnimatedModel::GetMorphWeight(StringHash nameHash) const
  544. {
  545. for (Vector<ModelMorph>::ConstIterator i = morphs_.Begin(); i != morphs_.End(); ++i)
  546. {
  547. if (i->nameHash_ == nameHash)
  548. return i->weight_;
  549. }
  550. return 0.0f;
  551. }
  552. AnimationState* AnimatedModel::GetAnimationState(Animation* animation) const
  553. {
  554. for (Vector<SharedPtr<AnimationState> >::ConstIterator i = animationStates_.Begin(); i != animationStates_.End(); ++i)
  555. {
  556. if ((*i)->GetAnimation() == animation)
  557. return *i;
  558. }
  559. return 0;
  560. }
  561. AnimationState* AnimatedModel::GetAnimationState(const String& animationName) const
  562. {
  563. return GetAnimationState(StringHash(animationName));
  564. }
  565. AnimationState* AnimatedModel::GetAnimationState(StringHash animationNameHash) const
  566. {
  567. for (Vector<SharedPtr<AnimationState> >::ConstIterator i = animationStates_.Begin(); i != animationStates_.End(); ++i)
  568. {
  569. Animation* animation = (*i)->GetAnimation();
  570. if (animation)
  571. {
  572. // Check both the animation and the resource name
  573. if (animation->GetNameHash() == animationNameHash || animation->GetAnimationNameHash() == animationNameHash)
  574. return *i;
  575. }
  576. }
  577. return 0;
  578. }
  579. AnimationState* AnimatedModel::GetAnimationState(unsigned index) const
  580. {
  581. return index < animationStates_.Size() ? animationStates_[index].Get() : 0;
  582. }
  583. void AnimatedModel::SetSkeleton(const Skeleton& skeleton, bool createBones)
  584. {
  585. if (!node_ && createBones)
  586. {
  587. LOGERROR("AnimatedModel not attached to a scene node, can not create bone nodes");
  588. return;
  589. }
  590. if (createBones && !boneCreationEnabled_)
  591. createBones = false;
  592. if (isMaster_)
  593. {
  594. // Check if bone structure has stayed compatible (reloading the model.) In that case retain the old bones and animations
  595. if (skeleton_.GetNumBones() == skeleton.GetNumBones())
  596. {
  597. Vector<Bone>& destBones = skeleton_.GetModifiableBones();
  598. const Vector<Bone>& srcBones = skeleton.GetBones();
  599. bool compatible = true;
  600. for (unsigned i = 0; i < destBones.Size(); ++i)
  601. {
  602. if (destBones[i].node_ && destBones[i].name_ == srcBones[i].name_ && destBones[i].parentIndex_ ==
  603. srcBones[i].parentIndex_)
  604. {
  605. // If compatible, just copy the values and retain the old node and animated status
  606. Node* boneNode = destBones[i].node_;
  607. bool animated = destBones[i].animated_;
  608. destBones[i] = srcBones[i];
  609. destBones[i].node_ = boneNode;
  610. destBones[i].animated_ = animated;
  611. }
  612. else
  613. {
  614. compatible = false;
  615. break;
  616. }
  617. }
  618. if (compatible)
  619. return;
  620. }
  621. RemoveAllAnimationStates();
  622. // Detach the rootbone of the previous model if any
  623. if (createBones)
  624. RemoveRootBone();
  625. skeleton_.Define(skeleton);
  626. // Remove collision information from dummy bones that do not affect skinning, to prevent them from being merged
  627. // to the bounding box
  628. Vector<Bone>& bones = skeleton_.GetModifiableBones();
  629. for (Vector<Bone>::Iterator i = bones.Begin(); i != bones.End(); ++i)
  630. {
  631. if (i->collisionMask_ & BONECOLLISION_BOX && i->boundingBox_.Size().Length() < M_EPSILON)
  632. i->collisionMask_ &= ~BONECOLLISION_BOX;
  633. if (i->collisionMask_ & BONECOLLISION_SPHERE && i->radius_ < M_EPSILON)
  634. i->collisionMask_ &= ~BONECOLLISION_SPHERE;
  635. }
  636. // Create scene nodes for the bones
  637. if (createBones)
  638. {
  639. for (Vector<Bone>::Iterator i = bones.Begin(); i != bones.End(); ++i)
  640. {
  641. // Create bones as local, as they are never to be directly synchronized over the network
  642. Node* boneNode = node_->CreateChild(i->name_, LOCAL);
  643. boneNode->AddListener(this);
  644. boneNode->SetTransform(i->initialPosition_, i->initialRotation_, i->initialScale_);
  645. i->node_ = boneNode;
  646. }
  647. for (unsigned i = 0; i < bones.Size(); ++i)
  648. {
  649. unsigned parentIndex = bones[i].parentIndex_;
  650. if (parentIndex != i && parentIndex < bones.Size())
  651. bones[parentIndex].node_->AddChild(bones[i].node_);
  652. }
  653. }
  654. using namespace BoneHierarchyCreated;
  655. VariantMap& eventData = GetEventDataMap();
  656. eventData[P_NODE] = node_;
  657. node_->SendEvent(E_BONEHIERARCHYCREATED, eventData);
  658. }
  659. else
  660. {
  661. // For non-master models: use the bone nodes of the master model
  662. skeleton_.Define(skeleton);
  663. if (createBones)
  664. {
  665. Vector<Bone>& bones = skeleton_.GetModifiableBones();
  666. for (Vector<Bone>::Iterator i = bones.Begin(); i != bones.End(); ++i)
  667. {
  668. Node* boneNode = node_->GetChild(i->name_, true);
  669. if (boneNode)
  670. boneNode->AddListener(this);
  671. i->node_ = boneNode;
  672. }
  673. }
  674. }
  675. // Reserve space for skinning matrices
  676. skinMatrices_.Resize(skeleton_.GetNumBones());
  677. SetGeometryBoneMappings();
  678. assignBonesPending_ = !createBones;
  679. }
  680. void AnimatedModel::SetModelAttr(const ResourceRef& value)
  681. {
  682. ResourceCache* cache = GetSubsystem<ResourceCache>();
  683. // When loading a scene, set model without creating the bone nodes (will be assigned later during post-load)
  684. SetModel(cache->GetResource<Model>(value.name_), !loading_);
  685. }
  686. void AnimatedModel::SetBonesEnabledAttr(const VariantVector& value)
  687. {
  688. Vector<Bone>& bones = skeleton_.GetModifiableBones();
  689. for (unsigned i = 0; i < bones.Size() && i < value.Size(); ++i)
  690. bones[i].animated_ = value[i].GetBool();
  691. }
  692. void AnimatedModel::SetAnimationStatesAttr(const VariantVector& value)
  693. {
  694. ResourceCache* cache = GetSubsystem<ResourceCache>();
  695. RemoveAllAnimationStates();
  696. unsigned index = 0;
  697. unsigned numStates = index < value.Size() ? value[index++].GetUInt() : 0;
  698. // Prevent negative or overly large value being assigned from the editor
  699. if (numStates > M_MAX_INT)
  700. numStates = 0;
  701. if (numStates > MAX_ANIMATION_STATES)
  702. numStates = MAX_ANIMATION_STATES;
  703. animationStates_.Reserve(numStates);
  704. while (numStates--)
  705. {
  706. if (index + 5 < value.Size())
  707. {
  708. // Note: null animation is allowed here for editing
  709. const ResourceRef& animRef = value[index++].GetResourceRef();
  710. SharedPtr<AnimationState> newState(new AnimationState(this, cache->GetResource<Animation>(animRef.name_)));
  711. animationStates_.Push(newState);
  712. newState->SetStartBone(skeleton_.GetBone(value[index++].GetString()));
  713. newState->SetLooped(value[index++].GetBool());
  714. newState->SetWeight(value[index++].GetFloat());
  715. newState->SetTime(value[index++].GetFloat());
  716. newState->SetLayer((unsigned char)value[index++].GetInt());
  717. }
  718. else
  719. {
  720. // If not enough data, just add an empty animation state
  721. SharedPtr<AnimationState> newState(new AnimationState(this, 0));
  722. animationStates_.Push(newState);
  723. }
  724. }
  725. if (animationStates_.Size())
  726. {
  727. MarkAnimationDirty();
  728. MarkAnimationOrderDirty();
  729. }
  730. }
  731. void AnimatedModel::SetMorphsAttr(const PODVector<unsigned char>& value)
  732. {
  733. for (unsigned index = 0; index < value.Size(); ++index)
  734. SetMorphWeight(index, (float)value[index] / 255.0f);
  735. }
  736. ResourceRef AnimatedModel::GetModelAttr() const
  737. {
  738. return GetResourceRef(model_, Model::GetTypeStatic());
  739. }
  740. VariantVector AnimatedModel::GetBonesEnabledAttr() const
  741. {
  742. VariantVector ret;
  743. const Vector<Bone>& bones = skeleton_.GetBones();
  744. ret.Reserve(bones.Size());
  745. for (Vector<Bone>::ConstIterator i = bones.Begin(); i != bones.End(); ++i)
  746. ret.Push(i->animated_);
  747. return ret;
  748. }
  749. VariantVector AnimatedModel::GetAnimationStatesAttr() const
  750. {
  751. VariantVector ret;
  752. ret.Reserve(animationStates_.Size() * 6 + 1);
  753. ret.Push(animationStates_.Size());
  754. for (Vector<SharedPtr<AnimationState> >::ConstIterator i = animationStates_.Begin(); i != animationStates_.End(); ++i)
  755. {
  756. AnimationState* state = *i;
  757. Animation* animation = state->GetAnimation();
  758. Bone* startBone = state->GetStartBone();
  759. ret.Push(GetResourceRef(animation, Animation::GetTypeStatic()));
  760. ret.Push(startBone ? startBone->name_ : String::EMPTY);
  761. ret.Push(state->IsLooped());
  762. ret.Push(state->GetWeight());
  763. ret.Push(state->GetTime());
  764. ret.Push((int)state->GetLayer());
  765. }
  766. return ret;
  767. }
  768. const PODVector<unsigned char>& AnimatedModel::GetMorphsAttr() const
  769. {
  770. attrBuffer_.Clear();
  771. for (Vector<ModelMorph>::ConstIterator i = morphs_.Begin(); i != morphs_.End(); ++i)
  772. attrBuffer_.WriteUByte((unsigned char)(i->weight_ * 255.0f));
  773. return attrBuffer_.GetBuffer();
  774. }
  775. void AnimatedModel::OnNodeSet(Node* node)
  776. {
  777. Drawable::OnNodeSet(node);
  778. if (node)
  779. {
  780. // If this AnimatedModel is the first in the node, it is the master which controls animation & morphs
  781. isMaster_ = GetComponent<AnimatedModel>() == this;
  782. }
  783. }
  784. void AnimatedModel::OnMarkedDirty(Node* node)
  785. {
  786. Drawable::OnMarkedDirty(node);
  787. // If the scene node or any of the bone nodes move, mark skinning and the bone bounding box dirty
  788. if (skeleton_.GetNumBones())
  789. {
  790. skinningDirty_ = true;
  791. boneBoundingBoxDirty_ = true;
  792. }
  793. }
  794. void AnimatedModel::OnWorldBoundingBoxUpdate()
  795. {
  796. if (isMaster_)
  797. {
  798. // Note: do not update bone bounding box here, instead do it in either of the threaded updates
  799. worldBoundingBox_ = boneBoundingBox_.Transformed(node_->GetWorldTransform());
  800. }
  801. else
  802. {
  803. // Non-master animated models get the bounding box from the master
  804. /// \todo If it's a skinned attachment that does not cover the whole body, it will have unnecessarily large bounds
  805. AnimatedModel* master = node_->GetComponent<AnimatedModel>();
  806. // Check if we've become the new master model in case the original was deleted
  807. if (master == this)
  808. isMaster_ = true;
  809. if (master)
  810. worldBoundingBox_ = master->GetWorldBoundingBox();
  811. }
  812. }
  813. void AnimatedModel::AssignBoneNodes()
  814. {
  815. assignBonesPending_ = false;
  816. if (!node_ || !boneCreationEnabled_)
  817. return;
  818. // Find the bone nodes from the node hierarchy and add listeners
  819. Vector<Bone>& bones = skeleton_.GetModifiableBones();
  820. bool boneFound = false;
  821. for (Vector<Bone>::Iterator i = bones.Begin(); i != bones.End(); ++i)
  822. {
  823. Node* boneNode = node_->GetChild(i->name_, true);
  824. if (boneNode)
  825. {
  826. boneFound = true;
  827. boneNode->AddListener(this);
  828. }
  829. i->node_ = boneNode;
  830. }
  831. // If no bones found, this may be a prefab where the bone information was left out.
  832. // In that case reassign the skeleton now if possible
  833. if (!boneFound && model_)
  834. {
  835. // ATOMIC: instead of calling SetSkeleton which does significant initialization
  836. // create the bone nodes here (which also avoids a bone init issue)
  837. // SetSkeleton(model_->GetSkeleton(), true);
  838. for (Vector<Bone>::Iterator i = bones.Begin(); i != bones.End(); ++i)
  839. {
  840. // Create bones as local, as they are never to be directly synchronized over the network
  841. Node* boneNode = node_->CreateChild(i->name_, LOCAL);
  842. boneNode->AddListener(this);
  843. boneNode->SetTransform(i->initialPosition_, i->initialRotation_, i->initialScale_);
  844. i->node_ = boneNode;
  845. }
  846. for (unsigned i = 0; i < bones.Size(); ++i)
  847. {
  848. unsigned parentIndex = bones[i].parentIndex_;
  849. if (parentIndex != i && parentIndex < bones.Size())
  850. bones[parentIndex].node_->AddChild(bones[i].node_);
  851. }
  852. }
  853. // Re-assign the same start bone to animations to get the proper bone node this time
  854. for (Vector<SharedPtr<AnimationState> >::Iterator i = animationStates_.Begin(); i != animationStates_.End(); ++i)
  855. {
  856. AnimationState* state = *i;
  857. state->SetStartBone(state->GetStartBone());
  858. }
  859. }
  860. void AnimatedModel::RemoveRootBone()
  861. {
  862. Bone* rootBone = skeleton_.GetRootBone();
  863. if (rootBone && rootBone->node_)
  864. rootBone->node_->Remove();
  865. }
  866. void AnimatedModel::MarkAnimationDirty()
  867. {
  868. if (isMaster_)
  869. {
  870. animationDirty_ = true;
  871. MarkForUpdate();
  872. }
  873. }
  874. void AnimatedModel::MarkAnimationOrderDirty()
  875. {
  876. if (isMaster_)
  877. {
  878. animationOrderDirty_ = true;
  879. MarkForUpdate();
  880. }
  881. }
  882. void AnimatedModel::MarkMorphsDirty()
  883. {
  884. morphsDirty_ = true;
  885. }
  886. void AnimatedModel::CloneGeometries()
  887. {
  888. const Vector<SharedPtr<VertexBuffer> >& originalVertexBuffers = model_->GetVertexBuffers();
  889. HashMap<VertexBuffer*, SharedPtr<VertexBuffer> > clonedVertexBuffers;
  890. morphVertexBuffers_.Resize(originalVertexBuffers.Size());
  891. for (unsigned i = 0; i < originalVertexBuffers.Size(); ++i)
  892. {
  893. VertexBuffer* original = originalVertexBuffers[i];
  894. if (model_->GetMorphRangeCount(i))
  895. {
  896. SharedPtr<VertexBuffer> clone(new VertexBuffer(context_));
  897. clone->SetShadowed(true);
  898. clone->SetSize(original->GetVertexCount(), morphElementMask_ & original->GetElementMask(), true);
  899. void* dest = clone->Lock(0, original->GetVertexCount());
  900. if (dest)
  901. {
  902. CopyMorphVertices(dest, original->GetShadowData(), original->GetVertexCount(), clone, original);
  903. clone->Unlock();
  904. }
  905. clonedVertexBuffers[original] = clone;
  906. morphVertexBuffers_[i] = clone;
  907. }
  908. else
  909. morphVertexBuffers_[i].Reset();
  910. }
  911. // Geometries will always be cloned fully. They contain only references to buffer, so they are relatively light
  912. for (unsigned i = 0; i < geometries_.Size(); ++i)
  913. {
  914. for (unsigned j = 0; j < geometries_[i].Size(); ++j)
  915. {
  916. SharedPtr<Geometry> original = geometries_[i][j];
  917. SharedPtr<Geometry> clone(new Geometry(context_));
  918. // Add an additional vertex stream into the clone, which supplies only the morphable vertex data, while the static
  919. // data comes from the original vertex buffer(s)
  920. const Vector<SharedPtr<VertexBuffer> >& originalBuffers = original->GetVertexBuffers();
  921. unsigned totalBuf = originalBuffers.Size();
  922. for (unsigned k = 0; k < originalBuffers.Size(); ++k)
  923. {
  924. VertexBuffer* originalBuffer = originalBuffers[k];
  925. if (clonedVertexBuffers.Contains(originalBuffer))
  926. ++totalBuf;
  927. }
  928. clone->SetNumVertexBuffers(totalBuf);
  929. unsigned l = 0;
  930. for (unsigned k = 0; k < originalBuffers.Size(); ++k)
  931. {
  932. VertexBuffer* originalBuffer = originalBuffers[k];
  933. unsigned originalMask = original->GetVertexElementMask(k);
  934. if (clonedVertexBuffers.Contains(originalBuffer))
  935. {
  936. VertexBuffer* clonedBuffer = clonedVertexBuffers[originalBuffer];
  937. clone->SetVertexBuffer(l++, originalBuffer, originalMask & ~clonedBuffer->GetElementMask());
  938. clone->SetVertexBuffer(l++, clonedBuffer, originalMask & clonedBuffer->GetElementMask());
  939. }
  940. else
  941. clone->SetVertexBuffer(l++, originalBuffer, originalMask);
  942. }
  943. clone->SetIndexBuffer(original->GetIndexBuffer());
  944. clone->SetDrawRange(original->GetPrimitiveType(), original->GetIndexStart(), original->GetIndexCount());
  945. clone->SetLodDistance(original->GetLodDistance());
  946. geometries_[i][j] = clone;
  947. }
  948. }
  949. // Make sure the rendering batches use the new cloned geometries
  950. ResetLodLevels();
  951. MarkMorphsDirty();
  952. }
  953. void AnimatedModel::CopyMorphVertices(void* destVertexData, void* srcVertexData, unsigned vertexCount, VertexBuffer* destBuffer,
  954. VertexBuffer* srcBuffer)
  955. {
  956. unsigned mask = destBuffer->GetElementMask() & srcBuffer->GetElementMask();
  957. unsigned normalOffset = srcBuffer->GetElementOffset(ELEMENT_NORMAL);
  958. unsigned tangentOffset = srcBuffer->GetElementOffset(ELEMENT_TANGENT);
  959. unsigned vertexSize = srcBuffer->GetVertexSize();
  960. float* dest = (float*)destVertexData;
  961. unsigned char* src = (unsigned char*)srcVertexData;
  962. while (vertexCount--)
  963. {
  964. if (mask & MASK_POSITION)
  965. {
  966. float* posSrc = (float*)src;
  967. dest[0] = posSrc[0];
  968. dest[1] = posSrc[1];
  969. dest[2] = posSrc[2];
  970. dest += 3;
  971. }
  972. if (mask & MASK_NORMAL)
  973. {
  974. float* normalSrc = (float*)(src + normalOffset);
  975. dest[0] = normalSrc[0];
  976. dest[1] = normalSrc[1];
  977. dest[2] = normalSrc[2];
  978. dest += 3;
  979. }
  980. if (mask & MASK_TANGENT)
  981. {
  982. float* tangentSrc = (float*)(src + tangentOffset);
  983. dest[0] = tangentSrc[0];
  984. dest[1] = tangentSrc[1];
  985. dest[2] = tangentSrc[2];
  986. dest[3] = tangentSrc[3];
  987. dest += 4;
  988. }
  989. src += vertexSize;
  990. }
  991. }
  992. void AnimatedModel::SetGeometryBoneMappings()
  993. {
  994. geometrySkinMatrices_.Clear();
  995. geometrySkinMatrixPtrs_.Clear();
  996. if (!geometryBoneMappings_.Size())
  997. return;
  998. // Check if all mappings are empty, then we do not need to use mapped skinning
  999. bool allEmpty = true;
  1000. for (unsigned i = 0; i < geometryBoneMappings_.Size(); ++i)
  1001. if (geometryBoneMappings_[i].Size())
  1002. allEmpty = false;
  1003. if (allEmpty)
  1004. return;
  1005. // Reserve space for per-geometry skinning matrices
  1006. geometrySkinMatrices_.Resize(geometryBoneMappings_.Size());
  1007. for (unsigned i = 0; i < geometryBoneMappings_.Size(); ++i)
  1008. geometrySkinMatrices_[i].Resize(geometryBoneMappings_[i].Size());
  1009. // Build original-to-skinindex matrix pointer mapping for fast copying
  1010. // Note: at this point layout of geometrySkinMatrices_ cannot be modified or pointers become invalid
  1011. geometrySkinMatrixPtrs_.Resize(skeleton_.GetNumBones());
  1012. for (unsigned i = 0; i < geometryBoneMappings_.Size(); ++i)
  1013. {
  1014. for (unsigned j = 0; j < geometryBoneMappings_[i].Size(); ++j)
  1015. geometrySkinMatrixPtrs_[geometryBoneMappings_[i][j]].Push(&geometrySkinMatrices_[i][j]);
  1016. }
  1017. }
  1018. void AnimatedModel::UpdateAnimation(const FrameInfo& frame)
  1019. {
  1020. // If using animation LOD, accumulate time and see if it is time to update
  1021. if (animationLodBias_ > 0.0f && animationLodDistance_ > 0.0f)
  1022. {
  1023. // Perform the first update always regardless of LOD timer
  1024. if (animationLodTimer_ >= 0.0f)
  1025. {
  1026. animationLodTimer_ += animationLodBias_ * frame.timeStep_ * ANIMATION_LOD_BASESCALE;
  1027. if (animationLodTimer_ >= animationLodDistance_)
  1028. animationLodTimer_ = fmodf(animationLodTimer_, animationLodDistance_);
  1029. else
  1030. return;
  1031. }
  1032. else
  1033. animationLodTimer_ = 0.0f;
  1034. }
  1035. // Make sure animations are in ascending priority order
  1036. if (animationOrderDirty_)
  1037. {
  1038. Sort(animationStates_.Begin(), animationStates_.End(), CompareAnimationOrder);
  1039. animationOrderDirty_ = false;
  1040. }
  1041. // Reset skeleton, apply all animations, calculate bones' bounding box. Make sure this is only done for the master model
  1042. // (first AnimatedModel in a node)
  1043. if (isMaster_)
  1044. {
  1045. skeleton_.ResetSilent();
  1046. for (Vector<SharedPtr<AnimationState> >::Iterator i = animationStates_.Begin(); i != animationStates_.End(); ++i)
  1047. (*i)->Apply();
  1048. // Skeleton reset and animations apply the node transforms "silently" to avoid repeated marking dirty. Mark dirty now
  1049. node_->MarkDirty();
  1050. // Calculate new bone bounding box
  1051. UpdateBoneBoundingBox();
  1052. }
  1053. animationDirty_ = false;
  1054. }
  1055. void AnimatedModel::UpdateBoneBoundingBox()
  1056. {
  1057. if (skeleton_.GetNumBones())
  1058. {
  1059. // The bone bounding box is in local space, so need the node's inverse transform
  1060. boneBoundingBox_.defined_ = false;
  1061. Matrix3x4 inverseNodeTransform = node_->GetWorldTransform().Inverse();
  1062. const Vector<Bone>& bones = skeleton_.GetBones();
  1063. for (Vector<Bone>::ConstIterator i = bones.Begin(); i != bones.End(); ++i)
  1064. {
  1065. Node* boneNode = i->node_;
  1066. if (!boneNode)
  1067. continue;
  1068. // Use hitbox if available. If not, use only half of the sphere radius
  1069. /// \todo The sphere radius should be multiplied with bone scale
  1070. if (i->collisionMask_ & BONECOLLISION_BOX)
  1071. boneBoundingBox_.Merge(i->boundingBox_.Transformed(inverseNodeTransform * boneNode->GetWorldTransform()));
  1072. else if (i->collisionMask_ & BONECOLLISION_SPHERE)
  1073. boneBoundingBox_.Merge(Sphere(inverseNodeTransform * boneNode->GetWorldPosition(), i->radius_ * 0.5f));
  1074. }
  1075. }
  1076. boneBoundingBoxDirty_ = false;
  1077. worldBoundingBoxDirty_ = true;
  1078. }
  1079. void AnimatedModel::UpdateSkinning()
  1080. {
  1081. // Note: the model's world transform will be baked in the skin matrices
  1082. const Vector<Bone>& bones = skeleton_.GetBones();
  1083. // Use model's world transform in case a bone is missing
  1084. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  1085. // Skinning with global matrices only
  1086. if (!geometrySkinMatrices_.Size())
  1087. {
  1088. for (unsigned i = 0; i < bones.Size(); ++i)
  1089. {
  1090. const Bone& bone = bones[i];
  1091. if (bone.node_)
  1092. skinMatrices_[i] = bone.node_->GetWorldTransform() * bone.offsetMatrix_;
  1093. else
  1094. skinMatrices_[i] = worldTransform;
  1095. }
  1096. }
  1097. // Skinning with per-geometry matrices
  1098. else
  1099. {
  1100. for (unsigned i = 0; i < bones.Size(); ++i)
  1101. {
  1102. const Bone& bone = bones[i];
  1103. if (bone.node_)
  1104. skinMatrices_[i] = bone.node_->GetWorldTransform() * bone.offsetMatrix_;
  1105. else
  1106. skinMatrices_[i] = worldTransform;
  1107. // Copy the skin matrix to per-geometry matrices as needed
  1108. for (unsigned j = 0; j < geometrySkinMatrixPtrs_[i].Size(); ++j)
  1109. *geometrySkinMatrixPtrs_[i][j] = skinMatrices_[i];
  1110. }
  1111. }
  1112. skinningDirty_ = false;
  1113. }
  1114. void AnimatedModel::UpdateMorphs()
  1115. {
  1116. Graphics* graphics = GetSubsystem<Graphics>();
  1117. if (!graphics)
  1118. return;
  1119. if (morphs_.Size())
  1120. {
  1121. // Reset the morph data range from all morphable vertex buffers, then apply morphs
  1122. for (unsigned i = 0; i < morphVertexBuffers_.Size(); ++i)
  1123. {
  1124. VertexBuffer* buffer = morphVertexBuffers_[i];
  1125. if (buffer)
  1126. {
  1127. VertexBuffer* originalBuffer = model_->GetVertexBuffers()[i];
  1128. unsigned morphStart = model_->GetMorphRangeStart(i);
  1129. unsigned morphCount = model_->GetMorphRangeCount(i);
  1130. void* dest = buffer->Lock(morphStart, morphCount);
  1131. if (dest)
  1132. {
  1133. // Reset morph range by copying data from the original vertex buffer
  1134. CopyMorphVertices(dest, originalBuffer->GetShadowData() + morphStart * originalBuffer->GetVertexSize(),
  1135. morphCount, buffer, originalBuffer);
  1136. for (unsigned j = 0; j < morphs_.Size(); ++j)
  1137. {
  1138. if (morphs_[j].weight_ > 0.0f)
  1139. {
  1140. HashMap<unsigned, VertexBufferMorph>::Iterator k = morphs_[j].buffers_.Find(i);
  1141. if (k != morphs_[j].buffers_.End())
  1142. ApplyMorph(buffer, dest, morphStart, k->second_, morphs_[j].weight_);
  1143. }
  1144. }
  1145. buffer->Unlock();
  1146. }
  1147. }
  1148. }
  1149. }
  1150. morphsDirty_ = false;
  1151. }
  1152. void AnimatedModel::ApplyMorph(VertexBuffer* buffer, void* destVertexData, unsigned morphRangeStart, const VertexBufferMorph& morph,
  1153. float weight)
  1154. {
  1155. unsigned elementMask = morph.elementMask_ & buffer->GetElementMask();
  1156. unsigned vertexCount = morph.vertexCount_;
  1157. unsigned normalOffset = buffer->GetElementOffset(ELEMENT_NORMAL);
  1158. unsigned tangentOffset = buffer->GetElementOffset(ELEMENT_TANGENT);
  1159. unsigned vertexSize = buffer->GetVertexSize();
  1160. unsigned char* srcData = morph.morphData_;
  1161. unsigned char* destData = (unsigned char*)destVertexData;
  1162. while (vertexCount--)
  1163. {
  1164. unsigned vertexIndex = *((unsigned*)srcData) - morphRangeStart;
  1165. srcData += sizeof(unsigned);
  1166. if (elementMask & MASK_POSITION)
  1167. {
  1168. float* dest = (float*)(destData + vertexIndex * vertexSize);
  1169. float* src = (float*)srcData;
  1170. dest[0] += src[0] * weight;
  1171. dest[1] += src[1] * weight;
  1172. dest[2] += src[2] * weight;
  1173. srcData += 3 * sizeof(float);
  1174. }
  1175. if (elementMask & MASK_NORMAL)
  1176. {
  1177. float* dest = (float*)(destData + vertexIndex * vertexSize + normalOffset);
  1178. float* src = (float*)srcData;
  1179. dest[0] += src[0] * weight;
  1180. dest[1] += src[1] * weight;
  1181. dest[2] += src[2] * weight;
  1182. srcData += 3 * sizeof(float);
  1183. }
  1184. if (elementMask & MASK_TANGENT)
  1185. {
  1186. float* dest = (float*)(destData + vertexIndex * vertexSize + tangentOffset);
  1187. float* src = (float*)srcData;
  1188. dest[0] += src[0] * weight;
  1189. dest[1] += src[1] * weight;
  1190. dest[2] += src[2] * weight;
  1191. srcData += 3 * sizeof(float);
  1192. }
  1193. }
  1194. }
  1195. void AnimatedModel::HandleModelReloadFinished(StringHash eventType, VariantMap& eventData)
  1196. {
  1197. Model* currentModel = model_;
  1198. model_.Reset(); // Set null to allow to be re-set
  1199. SetModel(currentModel);
  1200. }
  1201. void AnimatedModel::SetBoneCreationEnabled(bool enabled)
  1202. {
  1203. boneCreationEnabled_ = enabled;
  1204. }
  1205. }