AnimatedModel.cpp 40 KB

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