AnimatedModel.cpp 47 KB

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