AnimatedModel.cpp 43 KB

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