AnimatedModel.cpp 46 KB

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