2
0

AnimatedModel.cpp 49 KB

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