AnimatedModel.cpp 53 KB

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