AnimatedModel.cpp 50 KB

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