AnimatedModel.cpp 43 KB

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