AnimatedModel.cpp 44 KB

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