AnimatedModel.cpp 46 KB

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