AnimatedModel.cpp 50 KB

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