AnimatedModel.cpp 45 KB

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