AnimatedModel.cpp 44 KB

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