AnimatedModel.cpp 53 KB

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