AnimatedModel.cpp 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520
  1. //
  2. // Copyright (c) 2008-2016 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 "../Core/Context.h"
  24. #include "../Core/Profiler.h"
  25. #include "../Graphics/AnimatedModel.h"
  26. #include "../Graphics/Animation.h"
  27. #include "../Graphics/AnimationState.h"
  28. #include "../Graphics/Batch.h"
  29. #include "../Graphics/Camera.h"
  30. #include "../Graphics/DebugRenderer.h"
  31. #include "../Graphics/DrawableEvents.h"
  32. #include "../Graphics/Geometry.h"
  33. #include "../Graphics/Graphics.h"
  34. #include "../Graphics/IndexBuffer.h"
  35. #include "../Graphics/Material.h"
  36. #include "../Graphics/Octree.h"
  37. #include "../Graphics/VertexBuffer.h"
  38. #include "../IO/Log.h"
  39. #include "../Resource/ResourceCache.h"
  40. #include "../Resource/ResourceEvents.h"
  41. #include "../Scene/Scene.h"
  42. #include "../DebugNew.h"
  43. namespace Atomic
  44. {
  45. extern const char* GEOMETRY_CATEGORY;
  46. static bool CompareAnimationOrder(const SharedPtr<AnimationState>& lhs, const SharedPtr<AnimationState>& rhs)
  47. {
  48. return lhs->GetLayer() < rhs->GetLayer();
  49. }
  50. static const unsigned MAX_ANIMATION_STATES = 256;
  51. AnimatedModel::AnimatedModel(Context* context) :
  52. StaticModel(context),
  53. animationLodFrameNumber_(0),
  54. morphElementMask_(0),
  55. animationLodBias_(1.0f),
  56. animationLodTimer_(-1.0f),
  57. animationLodDistance_(0.0f),
  58. updateInvisible_(false),
  59. animationDirty_(false),
  60. animationOrderDirty_(false),
  61. morphsDirty_(false),
  62. skinningDirty_(true),
  63. boneBoundingBoxDirty_(true),
  64. isMaster_(true),
  65. loading_(false),
  66. assignBonesPending_(false),
  67. forceAnimationUpdate_(false)
  68. {
  69. }
  70. AnimatedModel::~AnimatedModel()
  71. {
  72. // When being destroyed, remove the bone hierarchy if appropriate (last AnimatedModel in the node)
  73. Bone* rootBone = skeleton_.GetRootBone();
  74. if (rootBone && rootBone->node_)
  75. {
  76. Node* parent = rootBone->node_->GetParent();
  77. if (parent && !parent->GetComponent<AnimatedModel>())
  78. RemoveRootBone();
  79. }
  80. }
  81. void AnimatedModel::RegisterObject(Context* context)
  82. {
  83. context->RegisterFactory<AnimatedModel>(GEOMETRY_CATEGORY);
  84. ATOMIC_ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  85. ATOMIC_MIXED_ACCESSOR_ATTRIBUTE("Model", GetModelAttr, SetModelAttr, ResourceRef, ResourceRef(Model::GetTypeStatic()), AM_DEFAULT);
  86. ATOMIC_ACCESSOR_ATTRIBUTE("Material", GetMaterialsAttr, SetMaterialsAttr, ResourceRefList, ResourceRefList(Material::GetTypeStatic()),
  87. AM_DEFAULT);
  88. ATOMIC_ATTRIBUTE("Is Occluder", bool, occluder_, false, AM_DEFAULT);
  89. ATOMIC_ACCESSOR_ATTRIBUTE("Can Be Occluded", IsOccludee, SetOccludee, bool, true, AM_DEFAULT);
  90. ATOMIC_ATTRIBUTE("Cast Shadows", bool, castShadows_, false, AM_DEFAULT);
  91. ATOMIC_ACCESSOR_ATTRIBUTE("Update When Invisible", GetUpdateInvisible, SetUpdateInvisible, bool, false, AM_DEFAULT);
  92. ATOMIC_ACCESSOR_ATTRIBUTE("Draw Distance", GetDrawDistance, SetDrawDistance, float, 0.0f, AM_DEFAULT);
  93. ATOMIC_ACCESSOR_ATTRIBUTE("Shadow Distance", GetShadowDistance, SetShadowDistance, float, 0.0f, AM_DEFAULT);
  94. ATOMIC_ACCESSOR_ATTRIBUTE("LOD Bias", GetLodBias, SetLodBias, float, 1.0f, AM_DEFAULT);
  95. ATOMIC_ACCESSOR_ATTRIBUTE("Animation LOD Bias", GetAnimationLodBias, SetAnimationLodBias, float, 1.0f, AM_DEFAULT);
  96. ATOMIC_COPY_BASE_ATTRIBUTES(Drawable);
  97. ATOMIC_MIXED_ACCESSOR_ATTRIBUTE("Bone Animation Enabled", GetBonesEnabledAttr, SetBonesEnabledAttr, VariantVector,
  98. Variant::emptyVariantVector, AM_FILE | AM_NOEDIT);
  99. ATOMIC_MIXED_ACCESSOR_ATTRIBUTE("Animation States", GetAnimationStatesAttr, SetAnimationStatesAttr, VariantVector,
  100. Variant::emptyVariantVector, AM_FILE);
  101. ATOMIC_ACCESSOR_ATTRIBUTE("Morphs", GetMorphsAttr, SetMorphsAttr, PODVector<unsigned char>, Variant::emptyBuffer,
  102. AM_DEFAULT | AM_NOEDIT);
  103. // ATOMIC BEGIN
  104. ATOMIC_ACCESSOR_ATTRIBUTE("Geometry Enabled", GetGeometryEnabledAttr, SetGeometryEnabledAttr, VariantVector,
  105. Variant::emptyVariantVector, AM_FILE | AM_NOEDIT);
  106. // ATOMIC END
  107. }
  108. bool AnimatedModel::Load(Deserializer& source, bool setInstanceDefault)
  109. {
  110. loading_ = true;
  111. bool success = Component::Load(source, setInstanceDefault);
  112. loading_ = false;
  113. return success;
  114. }
  115. bool AnimatedModel::LoadXML(const XMLElement& source, bool setInstanceDefault)
  116. {
  117. loading_ = true;
  118. bool success = Component::LoadXML(source, setInstanceDefault);
  119. loading_ = false;
  120. return success;
  121. }
  122. bool AnimatedModel::LoadJSON(const JSONValue& source, bool setInstanceDefault)
  123. {
  124. loading_ = true;
  125. bool success = Component::LoadJSON(source, setInstanceDefault);
  126. loading_ = false;
  127. return success;
  128. }
  129. void AnimatedModel::ApplyAttributes()
  130. {
  131. if (assignBonesPending_)
  132. {
  133. AssignBoneNodes();
  134. // ATOMIC BEGIN
  135. // initialize skinning matrices in batches
  136. for (unsigned i = 0; i < batches_.Size(); ++i)
  137. {
  138. if (skinMatrices_.Size())
  139. {
  140. batches_[i].geometryType_ = GEOM_SKINNED;
  141. // Check if model has per-geometry bone mappings
  142. if (geometrySkinMatrices_.Size() && geometrySkinMatrices_[i].Size())
  143. {
  144. batches_[i].worldTransform_ = &geometrySkinMatrices_[i][0];
  145. batches_[i].numWorldTransforms_ = geometrySkinMatrices_[i].Size();
  146. }
  147. // If not, use the global skin matrices
  148. else
  149. {
  150. batches_[i].worldTransform_ = &skinMatrices_[0];
  151. batches_[i].numWorldTransforms_ = skinMatrices_.Size();
  152. }
  153. }
  154. else
  155. {
  156. batches_[i].geometryType_ = GEOM_STATIC;
  157. batches_[i].worldTransform_ = &node_->GetWorldTransform();
  158. batches_[i].numWorldTransforms_ = 1;
  159. }
  160. }
  161. // ATOMIC END
  162. }
  163. }
  164. void AnimatedModel::ProcessRayQuery(const RayOctreeQuery& query, PODVector<RayQueryResult>& results)
  165. {
  166. // If no bones or no bone-level testing, use the StaticModel test
  167. RayQueryLevel level = query.level_;
  168. // ATOMIC BEGIN
  169. if ((level < RAY_TRIANGLE || !skeleton_.GetNumBones()) || context_->GetEditorContext())
  170. {
  171. StaticModel::ProcessRayQuery(query, results);
  172. return;
  173. }
  174. // ATOMIC END
  175. // Check ray hit distance to AABB before proceeding with bone-level tests
  176. if (query.ray_.HitDistance(GetWorldBoundingBox()) >= query.maxDistance_)
  177. return;
  178. const Vector<Bone>& bones = skeleton_.GetBones();
  179. Sphere boneSphere;
  180. for (unsigned i = 0; i < bones.Size(); ++i)
  181. {
  182. const Bone& bone = bones[i];
  183. if (!bone.node_)
  184. continue;
  185. float distance;
  186. // Use hitbox if available
  187. if (bone.collisionMask_ & BONECOLLISION_BOX)
  188. {
  189. // Do an initial crude test using the bone's AABB
  190. const BoundingBox& box = bone.boundingBox_;
  191. const Matrix3x4& transform = bone.node_->GetWorldTransform();
  192. distance = query.ray_.HitDistance(box.Transformed(transform));
  193. if (distance >= query.maxDistance_)
  194. continue;
  195. if (level != RAY_AABB)
  196. {
  197. // Follow with an OBB test if required
  198. Matrix3x4 inverse = transform.Inverse();
  199. Ray localRay = query.ray_.Transformed(inverse);
  200. distance = localRay.HitDistance(box);
  201. if (distance >= query.maxDistance_)
  202. continue;
  203. }
  204. }
  205. else if (bone.collisionMask_ & BONECOLLISION_SPHERE)
  206. {
  207. boneSphere.center_ = bone.node_->GetWorldPosition();
  208. boneSphere.radius_ = bone.radius_;
  209. distance = query.ray_.HitDistance(boneSphere);
  210. if (distance >= query.maxDistance_)
  211. continue;
  212. }
  213. else
  214. continue;
  215. // If the code reaches here then we have a hit
  216. RayQueryResult result;
  217. result.position_ = query.ray_.origin_ + distance * query.ray_.direction_;
  218. result.normal_ = -query.ray_.direction_;
  219. result.distance_ = distance;
  220. result.drawable_ = this;
  221. result.node_ = node_;
  222. result.subObject_ = i;
  223. results.Push(result);
  224. }
  225. }
  226. void AnimatedModel::Update(const FrameInfo& frame)
  227. {
  228. // If node was invisible last frame, need to decide animation LOD distance here
  229. // If headless, retain the current animation distance (should be 0)
  230. if (frame.camera_ && abs((int)frame.frameNumber_ - (int)viewFrameNumber_) > 1)
  231. {
  232. // First check for no update at all when invisible. In that case reset LOD timer to ensure update
  233. // next time the model is in view
  234. if (!updateInvisible_)
  235. {
  236. if (animationDirty_)
  237. {
  238. animationLodTimer_ = -1.0f;
  239. forceAnimationUpdate_ = true;
  240. }
  241. return;
  242. }
  243. float distance = frame.camera_->GetDistance(node_->GetWorldPosition());
  244. // If distance is greater than draw distance, no need to update at all
  245. if (drawDistance_ > 0.0f && distance > drawDistance_)
  246. return;
  247. float scale = GetWorldBoundingBox().Size().DotProduct(DOT_SCALE);
  248. animationLodDistance_ = frame.camera_->GetLodDistance(distance, scale, lodBias_);
  249. }
  250. if (animationDirty_ || animationOrderDirty_)
  251. UpdateAnimation(frame);
  252. else if (boneBoundingBoxDirty_)
  253. UpdateBoneBoundingBox();
  254. }
  255. void AnimatedModel::UpdateBatches(const FrameInfo& frame)
  256. {
  257. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  258. const BoundingBox& worldBoundingBox = GetWorldBoundingBox();
  259. distance_ = frame.camera_->GetDistance(worldBoundingBox.Center());
  260. // Note: per-geometry distances do not take skinning into account. Especially in case of a ragdoll they may be
  261. // much off base if the node's own transform is not updated
  262. if (batches_.Size() == 1)
  263. batches_[0].distance_ = distance_;
  264. else
  265. {
  266. for (unsigned i = 0; i < batches_.Size(); ++i)
  267. batches_[i].distance_ = frame.camera_->GetDistance(worldTransform * geometryData_[i].center_);
  268. }
  269. // Use a transformed version of the model's bounding box instead of world bounding box for LOD scale
  270. // determination so that animation does not change the scale
  271. BoundingBox transformedBoundingBox = boundingBox_.Transformed(worldTransform);
  272. float scale = transformedBoundingBox.Size().DotProduct(DOT_SCALE);
  273. float newLodDistance = frame.camera_->GetLodDistance(distance_, scale, lodBias_);
  274. // If model is rendered from several views, use the minimum LOD distance for animation LOD
  275. if (frame.frameNumber_ != animationLodFrameNumber_)
  276. {
  277. animationLodDistance_ = newLodDistance;
  278. animationLodFrameNumber_ = frame.frameNumber_;
  279. }
  280. else
  281. animationLodDistance_ = Min(animationLodDistance_, newLodDistance);
  282. if (newLodDistance != lodDistance_)
  283. {
  284. lodDistance_ = newLodDistance;
  285. CalculateLodLevels();
  286. }
  287. // ATOMIC BEGIN
  288. // Handle mesh hiding
  289. if (geometryDisabled_)
  290. {
  291. for (unsigned i = 0; i < batches_.Size(); ++i)
  292. {
  293. SourceBatch* batch = &batches_[i];
  294. StaticModelGeometryData* data = &geometryData_[i];
  295. if (batch->geometry_)
  296. data->batchGeometry_ = batch->geometry_;
  297. if (data->enabled_ && !batch->geometry_)
  298. {
  299. batch->geometry_ = data->batchGeometry_;
  300. }
  301. else if (!data->enabled_ && batch->geometry_)
  302. {
  303. data->batchGeometry_ = batch->geometry_;
  304. batch->geometry_ = 0;
  305. }
  306. }
  307. }
  308. // ATOMIC END
  309. }
  310. void AnimatedModel::UpdateGeometry(const FrameInfo& frame)
  311. {
  312. // Late update in case the model came into view and animation was dirtied in the meanwhile
  313. if (forceAnimationUpdate_)
  314. {
  315. UpdateAnimation(frame);
  316. forceAnimationUpdate_ = false;
  317. }
  318. if (morphsDirty_)
  319. UpdateMorphs();
  320. if (skinningDirty_)
  321. UpdateSkinning();
  322. }
  323. UpdateGeometryType AnimatedModel::GetUpdateGeometryType()
  324. {
  325. if (morphsDirty_ || forceAnimationUpdate_)
  326. return UPDATE_MAIN_THREAD;
  327. else if (skinningDirty_)
  328. return UPDATE_WORKER_THREAD;
  329. else
  330. return UPDATE_NONE;
  331. }
  332. void AnimatedModel::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  333. {
  334. if (debug && IsEnabledEffective())
  335. {
  336. debug->AddBoundingBox(GetWorldBoundingBox(), Color::GREEN, depthTest);
  337. debug->AddSkeleton(skeleton_, Color(0.75f, 0.75f, 0.75f), depthTest);
  338. }
  339. }
  340. void AnimatedModel::SetModel(Model* model, bool createBones)
  341. {
  342. if (model == model_)
  343. return;
  344. // Unsubscribe from the reload event of previous model (if any), then subscribe to the new
  345. if (model_)
  346. UnsubscribeFromEvent(model_, E_RELOADFINISHED);
  347. model_ = model;
  348. if (model)
  349. {
  350. SubscribeToEvent(model, E_RELOADFINISHED, ATOMIC_HANDLER(AnimatedModel, HandleModelReloadFinished));
  351. // Copy the subgeometry & LOD level structure
  352. SetNumGeometries(model->GetNumGeometries());
  353. const Vector<Vector<SharedPtr<Geometry> > >& geometries = model->GetGeometries();
  354. const PODVector<Vector3>& geometryCenters = model->GetGeometryCenters();
  355. for (unsigned i = 0; i < geometries.Size(); ++i)
  356. {
  357. geometries_[i] = geometries[i];
  358. geometryData_[i].center_ = geometryCenters[i];
  359. // ATOMIC BEGIN
  360. geometryData_[i].enabled_ = true;
  361. geometryData_[i].batchGeometry_ = 0;
  362. // ATOMIC END
  363. }
  364. // Copy geometry bone mappings
  365. const Vector<PODVector<unsigned> >& geometryBoneMappings = model->GetGeometryBoneMappings();
  366. geometryBoneMappings_.Clear();
  367. geometryBoneMappings_.Reserve(geometryBoneMappings.Size());
  368. for (unsigned i = 0; i < geometryBoneMappings.Size(); ++i)
  369. geometryBoneMappings_.Push(geometryBoneMappings[i]);
  370. // Copy morphs. Note: morph vertex buffers will be created later on-demand
  371. morphVertexBuffers_.Clear();
  372. morphs_.Clear();
  373. const Vector<ModelMorph>& morphs = model->GetMorphs();
  374. morphs_.Reserve(morphs.Size());
  375. morphElementMask_ = 0;
  376. for (unsigned i = 0; i < morphs.Size(); ++i)
  377. {
  378. ModelMorph newMorph;
  379. newMorph.name_ = morphs[i].name_;
  380. newMorph.nameHash_ = morphs[i].nameHash_;
  381. newMorph.weight_ = 0.0f;
  382. newMorph.buffers_ = morphs[i].buffers_;
  383. for (HashMap<unsigned, VertexBufferMorph>::ConstIterator j = morphs[i].buffers_.Begin();
  384. j != morphs[i].buffers_.End(); ++j)
  385. morphElementMask_ |= j->second_.elementMask_;
  386. morphs_.Push(newMorph);
  387. }
  388. // Copy bounding box & skeleton
  389. SetBoundingBox(model->GetBoundingBox());
  390. // Initial bone bounding box is just the one stored in the model
  391. boneBoundingBox_ = boundingBox_;
  392. boneBoundingBoxDirty_ = true;
  393. SetSkeleton(model->GetSkeleton(), createBones);
  394. ResetLodLevels();
  395. // Enable skinning in batches
  396. for (unsigned i = 0; i < batches_.Size(); ++i)
  397. {
  398. if (skinMatrices_.Size())
  399. {
  400. batches_[i].geometryType_ = GEOM_SKINNED;
  401. // Check if model has per-geometry bone mappings
  402. if (geometrySkinMatrices_.Size() && geometrySkinMatrices_[i].Size())
  403. {
  404. batches_[i].worldTransform_ = &geometrySkinMatrices_[i][0];
  405. batches_[i].numWorldTransforms_ = geometrySkinMatrices_[i].Size();
  406. }
  407. // If not, use the global skin matrices
  408. else
  409. {
  410. batches_[i].worldTransform_ = &skinMatrices_[0];
  411. batches_[i].numWorldTransforms_ = skinMatrices_.Size();
  412. }
  413. }
  414. else
  415. {
  416. batches_[i].geometryType_ = GEOM_STATIC;
  417. batches_[i].worldTransform_ = &node_->GetWorldTransform();
  418. batches_[i].numWorldTransforms_ = 1;
  419. }
  420. }
  421. }
  422. else
  423. {
  424. RemoveRootBone(); // Remove existing root bone if any
  425. SetNumGeometries(0);
  426. geometryBoneMappings_.Clear();
  427. morphVertexBuffers_.Clear();
  428. morphs_.Clear();
  429. morphElementMask_ = 0;
  430. SetBoundingBox(BoundingBox());
  431. SetSkeleton(Skeleton(), false);
  432. }
  433. MarkNetworkUpdate();
  434. }
  435. AnimationState* AnimatedModel::AddAnimationState(Animation* animation)
  436. {
  437. if (!isMaster_)
  438. {
  439. ATOMIC_LOGERROR("Can not add animation state to non-master model");
  440. return 0;
  441. }
  442. if (!animation || !skeleton_.GetNumBones())
  443. return 0;
  444. // Check for not adding twice
  445. AnimationState* existing = GetAnimationState(animation);
  446. if (existing)
  447. return existing;
  448. SharedPtr<AnimationState> newState(new AnimationState(this, animation));
  449. animationStates_.Push(newState);
  450. MarkAnimationOrderDirty();
  451. return newState;
  452. }
  453. void AnimatedModel::RemoveAnimationState(Animation* animation)
  454. {
  455. if (animation)
  456. RemoveAnimationState(animation->GetNameHash());
  457. else
  458. {
  459. for (Vector<SharedPtr<AnimationState> >::Iterator i = animationStates_.Begin(); i != animationStates_.End(); ++i)
  460. {
  461. AnimationState* state = *i;
  462. if (!state->GetAnimation())
  463. {
  464. animationStates_.Erase(i);
  465. MarkAnimationDirty();
  466. return;
  467. }
  468. }
  469. }
  470. }
  471. void AnimatedModel::RemoveAnimationState(const String& animationName)
  472. {
  473. RemoveAnimationState(StringHash(animationName));
  474. }
  475. void AnimatedModel::RemoveAnimationState(StringHash animationNameHash)
  476. {
  477. for (Vector<SharedPtr<AnimationState> >::Iterator i = animationStates_.Begin(); i != animationStates_.End(); ++i)
  478. {
  479. AnimationState* state = *i;
  480. Animation* animation = state->GetAnimation();
  481. if (animation)
  482. {
  483. // Check both the animation and the resource name
  484. if (animation->GetNameHash() == animationNameHash || animation->GetAnimationNameHash() == animationNameHash)
  485. {
  486. animationStates_.Erase(i);
  487. MarkAnimationDirty();
  488. return;
  489. }
  490. }
  491. }
  492. }
  493. void AnimatedModel::RemoveAnimationState(AnimationState* state)
  494. {
  495. for (Vector<SharedPtr<AnimationState> >::Iterator i = animationStates_.Begin(); i != animationStates_.End(); ++i)
  496. {
  497. if (*i == state)
  498. {
  499. animationStates_.Erase(i);
  500. MarkAnimationDirty();
  501. return;
  502. }
  503. }
  504. }
  505. void AnimatedModel::RemoveAnimationState(unsigned index)
  506. {
  507. if (index < animationStates_.Size())
  508. {
  509. animationStates_.Erase(index);
  510. MarkAnimationDirty();
  511. }
  512. }
  513. void AnimatedModel::RemoveAllAnimationStates()
  514. {
  515. if (animationStates_.Size())
  516. {
  517. animationStates_.Clear();
  518. MarkAnimationDirty();
  519. }
  520. }
  521. void AnimatedModel::SetAnimationLodBias(float bias)
  522. {
  523. animationLodBias_ = Max(bias, 0.0f);
  524. MarkNetworkUpdate();
  525. }
  526. void AnimatedModel::SetUpdateInvisible(bool enable)
  527. {
  528. updateInvisible_ = enable;
  529. MarkNetworkUpdate();
  530. }
  531. void AnimatedModel::SetMorphWeight(unsigned index, float weight)
  532. {
  533. if (index >= morphs_.Size())
  534. return;
  535. // If morph vertex buffers have not been created yet, create now
  536. if (weight > 0.0f && morphVertexBuffers_.Empty())
  537. CloneGeometries();
  538. weight = Clamp(weight, 0.0f, 1.0f);
  539. if (weight != morphs_[index].weight_)
  540. {
  541. morphs_[index].weight_ = weight;
  542. // For a master model, set the same morph weight on non-master models
  543. if (isMaster_)
  544. {
  545. PODVector<AnimatedModel*> models;
  546. GetComponents<AnimatedModel>(models);
  547. // Indexing might not be the same, so use the name hash instead
  548. for (unsigned i = 1; i < models.Size(); ++i)
  549. {
  550. if (!models[i]->isMaster_)
  551. models[i]->SetMorphWeight(morphs_[index].nameHash_, weight);
  552. }
  553. }
  554. MarkMorphsDirty();
  555. MarkNetworkUpdate();
  556. }
  557. }
  558. void AnimatedModel::SetMorphWeight(const String& name, float weight)
  559. {
  560. for (unsigned i = 0; i < morphs_.Size(); ++i)
  561. {
  562. if (morphs_[i].name_ == name)
  563. {
  564. SetMorphWeight(i, weight);
  565. return;
  566. }
  567. }
  568. }
  569. void AnimatedModel::SetMorphWeight(StringHash nameHash, float weight)
  570. {
  571. for (unsigned i = 0; i < morphs_.Size(); ++i)
  572. {
  573. if (morphs_[i].nameHash_ == nameHash)
  574. {
  575. SetMorphWeight(i, weight);
  576. return;
  577. }
  578. }
  579. }
  580. void AnimatedModel::ResetMorphWeights()
  581. {
  582. for (Vector<ModelMorph>::Iterator i = morphs_.Begin(); i != morphs_.End(); ++i)
  583. i->weight_ = 0.0f;
  584. // For a master model, reset weights on non-master models
  585. if (isMaster_)
  586. {
  587. PODVector<AnimatedModel*> models;
  588. GetComponents<AnimatedModel>(models);
  589. for (unsigned i = 1; i < models.Size(); ++i)
  590. {
  591. if (!models[i]->isMaster_)
  592. models[i]->ResetMorphWeights();
  593. }
  594. }
  595. MarkMorphsDirty();
  596. MarkNetworkUpdate();
  597. }
  598. Node* AnimatedModel::GetSkeletonBoneNode(const String & boneName)
  599. {
  600. Bone* bone = skeleton_.GetBone(boneName);
  601. return (bone) ? bone->node_ : NULL;
  602. }
  603. float AnimatedModel::GetMorphWeight(unsigned index) const
  604. {
  605. return index < morphs_.Size() ? morphs_[index].weight_ : 0.0f;
  606. }
  607. float AnimatedModel::GetMorphWeight(const String& name) const
  608. {
  609. for (Vector<ModelMorph>::ConstIterator i = morphs_.Begin(); i != morphs_.End(); ++i)
  610. {
  611. if (i->name_ == name)
  612. return i->weight_;
  613. }
  614. return 0.0f;
  615. }
  616. float AnimatedModel::GetMorphWeight(StringHash nameHash) const
  617. {
  618. for (Vector<ModelMorph>::ConstIterator i = morphs_.Begin(); i != morphs_.End(); ++i)
  619. {
  620. if (i->nameHash_ == nameHash)
  621. return i->weight_;
  622. }
  623. return 0.0f;
  624. }
  625. AnimationState* AnimatedModel::GetAnimationState(Animation* animation) const
  626. {
  627. for (Vector<SharedPtr<AnimationState> >::ConstIterator i = animationStates_.Begin(); i != animationStates_.End(); ++i)
  628. {
  629. if ((*i)->GetAnimation() == animation)
  630. return *i;
  631. }
  632. return 0;
  633. }
  634. AnimationState* AnimatedModel::GetAnimationState(const String& animationName) const
  635. {
  636. return GetAnimationState(StringHash(animationName));
  637. }
  638. AnimationState* AnimatedModel::GetAnimationState(StringHash animationNameHash) const
  639. {
  640. for (Vector<SharedPtr<AnimationState> >::ConstIterator i = animationStates_.Begin(); i != animationStates_.End(); ++i)
  641. {
  642. Animation* animation = (*i)->GetAnimation();
  643. if (animation)
  644. {
  645. // Check both the animation and the resource name
  646. if (animation->GetNameHash() == animationNameHash || animation->GetAnimationNameHash() == animationNameHash)
  647. return *i;
  648. }
  649. }
  650. return 0;
  651. }
  652. AnimationState* AnimatedModel::GetAnimationState(unsigned index) const
  653. {
  654. return index < animationStates_.Size() ? animationStates_[index].Get() : 0;
  655. }
  656. void AnimatedModel::SetSkeleton(const Skeleton& skeleton, bool createBones)
  657. {
  658. if (!node_ && createBones)
  659. {
  660. ATOMIC_LOGERROR("AnimatedModel not attached to a scene node, can not create bone nodes");
  661. return;
  662. }
  663. // ATOMIC BEGIN
  664. // We don't create bones in editor for now until can address prefabs using temporary flag
  665. // ie. prefab and bone nodes should use tags
  666. bool dontCreateBonesHack = context_->GetEditorContext();
  667. // ATOMIC END
  668. if (isMaster_)
  669. {
  670. // Check if bone structure has stayed compatible (reloading the model.) In that case retain the old bones and animations
  671. if (skeleton_.GetNumBones() == skeleton.GetNumBones())
  672. {
  673. Vector<Bone>& destBones = skeleton_.GetModifiableBones();
  674. const Vector<Bone>& srcBones = skeleton.GetBones();
  675. bool compatible = true;
  676. for (unsigned i = 0; i < destBones.Size(); ++i)
  677. {
  678. if (destBones[i].node_ && destBones[i].name_ == srcBones[i].name_ && destBones[i].parentIndex_ ==
  679. srcBones[i].parentIndex_)
  680. {
  681. // If compatible, just copy the values and retain the old node and animated status
  682. Node* boneNode = destBones[i].node_;
  683. bool animated = destBones[i].animated_;
  684. destBones[i] = srcBones[i];
  685. destBones[i].node_ = boneNode;
  686. destBones[i].animated_ = animated;
  687. }
  688. else
  689. {
  690. compatible = false;
  691. break;
  692. }
  693. }
  694. if (compatible)
  695. return;
  696. }
  697. RemoveAllAnimationStates();
  698. // Detach the rootbone of the previous model if any
  699. if (createBones)
  700. RemoveRootBone();
  701. skeleton_.Define(skeleton);
  702. // Merge bounding boxes from non-master models
  703. FinalizeBoneBoundingBoxes();
  704. Vector<Bone>& bones = skeleton_.GetModifiableBones();
  705. // ATOMIC BEGIN
  706. // Create scene nodes for the bones
  707. if (createBones && !dontCreateBonesHack)
  708. {
  709. // ATOMIC END
  710. for (Vector<Bone>::Iterator i = bones.Begin(); i != bones.End(); ++i)
  711. {
  712. // Create bones as local, as they are never to be directly synchronized over the network
  713. Node* boneNode = node_->CreateChild(i->name_, LOCAL);
  714. boneNode->AddListener(this);
  715. boneNode->SetTransform(i->initialPosition_, i->initialRotation_, i->initialScale_);
  716. // Copy the model component's temporary status
  717. boneNode->SetTemporary(IsTemporary());
  718. i->node_ = boneNode;
  719. }
  720. for (unsigned i = 0; i < bones.Size(); ++i)
  721. {
  722. unsigned parentIndex = bones[i].parentIndex_;
  723. if (parentIndex != i && parentIndex < bones.Size())
  724. bones[parentIndex].node_->AddChild(bones[i].node_);
  725. }
  726. }
  727. using namespace BoneHierarchyCreated;
  728. VariantMap& eventData = GetEventDataMap();
  729. eventData[P_NODE] = node_;
  730. node_->SendEvent(E_BONEHIERARCHYCREATED, eventData);
  731. }
  732. else
  733. {
  734. // For non-master models: use the bone nodes of the master model
  735. skeleton_.Define(skeleton);
  736. // Instruct the master model to refresh (merge) its bone bounding boxes
  737. AnimatedModel* master = node_->GetComponent<AnimatedModel>();
  738. if (master && master != this)
  739. master->FinalizeBoneBoundingBoxes();
  740. // ATOMIC BEGIN
  741. if (createBones && !dontCreateBonesHack)
  742. {
  743. // ATOMIC END
  744. Vector<Bone>& bones = skeleton_.GetModifiableBones();
  745. for (Vector<Bone>::Iterator i = bones.Begin(); i != bones.End(); ++i)
  746. {
  747. Node* boneNode = node_->GetChild(i->name_, true);
  748. if (boneNode)
  749. boneNode->AddListener(this);
  750. i->node_ = boneNode;
  751. }
  752. }
  753. }
  754. // Reserve space for skinning matrices
  755. skinMatrices_.Resize(skeleton_.GetNumBones());
  756. SetGeometryBoneMappings();
  757. assignBonesPending_ = !createBones;
  758. }
  759. void AnimatedModel::SetModelAttr(const ResourceRef& value)
  760. {
  761. ResourceCache* cache = GetSubsystem<ResourceCache>();
  762. // When loading a scene, set model without creating the bone nodes (will be assigned later during post-load)
  763. SetModel(cache->GetResource<Model>(value.name_), !loading_);
  764. }
  765. void AnimatedModel::SetBonesEnabledAttr(const VariantVector& value)
  766. {
  767. Vector<Bone>& bones = skeleton_.GetModifiableBones();
  768. for (unsigned i = 0; i < bones.Size() && i < value.Size(); ++i)
  769. bones[i].animated_ = value[i].GetBool();
  770. }
  771. void AnimatedModel::SetAnimationStatesAttr(const VariantVector& value)
  772. {
  773. ResourceCache* cache = GetSubsystem<ResourceCache>();
  774. RemoveAllAnimationStates();
  775. unsigned index = 0;
  776. unsigned numStates = index < value.Size() ? value[index++].GetUInt() : 0;
  777. // Prevent negative or overly large value being assigned from the editor
  778. if (numStates > M_MAX_INT)
  779. numStates = 0;
  780. if (numStates > MAX_ANIMATION_STATES)
  781. numStates = MAX_ANIMATION_STATES;
  782. animationStates_.Reserve(numStates);
  783. while (numStates--)
  784. {
  785. if (index + 5 < value.Size())
  786. {
  787. // Note: null animation is allowed here for editing
  788. const ResourceRef& animRef = value[index++].GetResourceRef();
  789. SharedPtr<AnimationState> newState(new AnimationState(this, cache->GetResource<Animation>(animRef.name_)));
  790. animationStates_.Push(newState);
  791. newState->SetStartBone(skeleton_.GetBone(value[index++].GetString()));
  792. newState->SetLooped(value[index++].GetBool());
  793. newState->SetWeight(value[index++].GetFloat());
  794. newState->SetTime(value[index++].GetFloat());
  795. newState->SetLayer((unsigned char)value[index++].GetInt());
  796. }
  797. else
  798. {
  799. // If not enough data, just add an empty animation state
  800. SharedPtr<AnimationState> newState(new AnimationState(this, 0));
  801. animationStates_.Push(newState);
  802. }
  803. }
  804. if (animationStates_.Size())
  805. {
  806. MarkAnimationDirty();
  807. MarkAnimationOrderDirty();
  808. }
  809. }
  810. void AnimatedModel::SetMorphsAttr(const PODVector<unsigned char>& value)
  811. {
  812. for (unsigned index = 0; index < value.Size(); ++index)
  813. SetMorphWeight(index, (float)value[index] / 255.0f);
  814. }
  815. ResourceRef AnimatedModel::GetModelAttr() const
  816. {
  817. return GetResourceRef(model_, Model::GetTypeStatic());
  818. }
  819. VariantVector AnimatedModel::GetBonesEnabledAttr() const
  820. {
  821. VariantVector ret;
  822. const Vector<Bone>& bones = skeleton_.GetBones();
  823. ret.Reserve(bones.Size());
  824. for (Vector<Bone>::ConstIterator i = bones.Begin(); i != bones.End(); ++i)
  825. ret.Push(i->animated_);
  826. return ret;
  827. }
  828. VariantVector AnimatedModel::GetAnimationStatesAttr() const
  829. {
  830. VariantVector ret;
  831. ret.Reserve(animationStates_.Size() * 6 + 1);
  832. ret.Push(animationStates_.Size());
  833. for (Vector<SharedPtr<AnimationState> >::ConstIterator i = animationStates_.Begin(); i != animationStates_.End(); ++i)
  834. {
  835. AnimationState* state = *i;
  836. Animation* animation = state->GetAnimation();
  837. Bone* startBone = state->GetStartBone();
  838. ret.Push(GetResourceRef(animation, Animation::GetTypeStatic()));
  839. ret.Push(startBone ? startBone->name_ : String::EMPTY);
  840. ret.Push(state->IsLooped());
  841. ret.Push(state->GetWeight());
  842. ret.Push(state->GetTime());
  843. ret.Push((int)state->GetLayer());
  844. }
  845. return ret;
  846. }
  847. const PODVector<unsigned char>& AnimatedModel::GetMorphsAttr() const
  848. {
  849. attrBuffer_.Clear();
  850. for (Vector<ModelMorph>::ConstIterator i = morphs_.Begin(); i != morphs_.End(); ++i)
  851. attrBuffer_.WriteUByte((unsigned char)(i->weight_ * 255.0f));
  852. return attrBuffer_.GetBuffer();
  853. }
  854. void AnimatedModel::UpdateBoneBoundingBox()
  855. {
  856. if (skeleton_.GetNumBones())
  857. {
  858. // The bone bounding box is in local space, so need the node's inverse transform
  859. boneBoundingBox_.Clear();
  860. Matrix3x4 inverseNodeTransform = node_->GetWorldTransform().Inverse();
  861. const Vector<Bone>& bones = skeleton_.GetBones();
  862. for (Vector<Bone>::ConstIterator i = bones.Begin(); i != bones.End(); ++i)
  863. {
  864. Node* boneNode = i->node_;
  865. if (!boneNode)
  866. continue;
  867. // Use hitbox if available. If not, use only half of the sphere radius
  868. /// \todo The sphere radius should be multiplied with bone scale
  869. if (i->collisionMask_ & BONECOLLISION_BOX)
  870. boneBoundingBox_.Merge(i->boundingBox_.Transformed(inverseNodeTransform * boneNode->GetWorldTransform()));
  871. else if (i->collisionMask_ & BONECOLLISION_SPHERE)
  872. boneBoundingBox_.Merge(Sphere(inverseNodeTransform * boneNode->GetWorldPosition(), i->radius_ * 0.5f));
  873. }
  874. }
  875. boneBoundingBoxDirty_ = false;
  876. worldBoundingBoxDirty_ = true;
  877. }
  878. void AnimatedModel::OnNodeSet(Node* node)
  879. {
  880. Drawable::OnNodeSet(node);
  881. if (node)
  882. {
  883. // If this AnimatedModel is the first in the node, it is the master which controls animation & morphs
  884. isMaster_ = GetComponent<AnimatedModel>() == this;
  885. }
  886. }
  887. void AnimatedModel::OnMarkedDirty(Node* node)
  888. {
  889. Drawable::OnMarkedDirty(node);
  890. // If the scene node or any of the bone nodes move, mark skinning dirty
  891. if (skeleton_.GetNumBones())
  892. {
  893. skinningDirty_ = true;
  894. // Bone bounding box doesn't need to be marked dirty when only the base scene node moves
  895. if (node != node_)
  896. boneBoundingBoxDirty_ = true;
  897. }
  898. }
  899. void AnimatedModel::OnWorldBoundingBoxUpdate()
  900. {
  901. if (isMaster_)
  902. {
  903. // Note: do not update bone bounding box here, instead do it in either of the threaded updates
  904. worldBoundingBox_ = boneBoundingBox_.Transformed(node_->GetWorldTransform());
  905. }
  906. else
  907. {
  908. // Non-master animated models get the bounding box from the master
  909. /// \todo If it's a skinned attachment that does not cover the whole body, it will have unnecessarily large bounds
  910. AnimatedModel* master = node_->GetComponent<AnimatedModel>();
  911. // Check if we've become the new master model in case the original was deleted
  912. if (master == this)
  913. isMaster_ = true;
  914. if (master)
  915. worldBoundingBox_ = master->GetWorldBoundingBox();
  916. }
  917. }
  918. void AnimatedModel::AssignBoneNodes()
  919. {
  920. assignBonesPending_ = false;
  921. if (!node_)
  922. return;
  923. // Find the bone nodes from the node hierarchy and add listeners
  924. Vector<Bone>& bones = skeleton_.GetModifiableBones();
  925. bool boneFound = false;
  926. for (Vector<Bone>::Iterator i = bones.Begin(); i != bones.End(); ++i)
  927. {
  928. Node* boneNode = node_->GetChild(i->name_, true);
  929. if (boneNode)
  930. {
  931. boneFound = true;
  932. boneNode->AddListener(this);
  933. }
  934. i->node_ = boneNode;
  935. }
  936. // If no bones found, this may be a prefab where the bone information was left out.
  937. // In that case reassign the skeleton now if possible
  938. if (!boneFound && model_)
  939. SetSkeleton(model_->GetSkeleton(), true);
  940. // Re-assign the same start bone to animations to get the proper bone node this time
  941. for (Vector<SharedPtr<AnimationState> >::Iterator i = animationStates_.Begin(); i != animationStates_.End(); ++i)
  942. {
  943. AnimationState* state = *i;
  944. state->SetStartBone(state->GetStartBone());
  945. }
  946. }
  947. void AnimatedModel::FinalizeBoneBoundingBoxes()
  948. {
  949. Vector<Bone>& bones = skeleton_.GetModifiableBones();
  950. PODVector<AnimatedModel*> models;
  951. GetComponents<AnimatedModel>(models);
  952. if (models.Size() > 1)
  953. {
  954. // Reset first to the model resource's original bone bounding information if available (should be)
  955. if (model_)
  956. {
  957. const Vector<Bone>& modelBones = model_->GetSkeleton().GetBones();
  958. for (unsigned i = 0; i < bones.Size() && i < modelBones.Size(); ++i)
  959. {
  960. bones[i].collisionMask_ = modelBones[i].collisionMask_;
  961. bones[i].radius_ = modelBones[i].radius_;
  962. bones[i].boundingBox_ = modelBones[i].boundingBox_;
  963. }
  964. }
  965. // Get matching bones from all non-master models and merge their bone bounding information
  966. // to prevent culling errors (master model may not have geometry in all bones, or the bounds are smaller)
  967. for (PODVector<AnimatedModel*>::Iterator i = models.Begin(); i != models.End(); ++i)
  968. {
  969. if ((*i) == this)
  970. continue;
  971. Skeleton& otherSkeleton = (*i)->GetSkeleton();
  972. for (Vector<Bone>::Iterator j = bones.Begin(); j != bones.End(); ++j)
  973. {
  974. Bone* otherBone = otherSkeleton.GetBone(j->nameHash_);
  975. if (otherBone)
  976. {
  977. if (otherBone->collisionMask_ & BONECOLLISION_SPHERE)
  978. {
  979. j->collisionMask_ |= BONECOLLISION_SPHERE;
  980. j->radius_ = Max(j->radius_, otherBone->radius_);
  981. }
  982. if (otherBone->collisionMask_ & BONECOLLISION_BOX)
  983. {
  984. j->collisionMask_ |= BONECOLLISION_BOX;
  985. if (j->boundingBox_.Defined())
  986. j->boundingBox_.Merge(otherBone->boundingBox_);
  987. else
  988. j->boundingBox_.Define(otherBone->boundingBox_);
  989. }
  990. }
  991. }
  992. }
  993. }
  994. // Remove collision information from dummy bones that do not affect skinning, to prevent them from being merged
  995. // to the bounding box and making it artificially large
  996. for (Vector<Bone>::Iterator i = bones.Begin(); i != bones.End(); ++i)
  997. {
  998. if (i->collisionMask_ & BONECOLLISION_BOX && i->boundingBox_.Size().Length() < M_EPSILON)
  999. i->collisionMask_ &= ~BONECOLLISION_BOX;
  1000. if (i->collisionMask_ & BONECOLLISION_SPHERE && i->radius_ < M_EPSILON)
  1001. i->collisionMask_ &= ~BONECOLLISION_SPHERE;
  1002. }
  1003. }
  1004. void AnimatedModel::RemoveRootBone()
  1005. {
  1006. Bone* rootBone = skeleton_.GetRootBone();
  1007. if (rootBone && rootBone->node_)
  1008. rootBone->node_->Remove();
  1009. }
  1010. void AnimatedModel::MarkAnimationDirty()
  1011. {
  1012. if (isMaster_)
  1013. {
  1014. animationDirty_ = true;
  1015. MarkForUpdate();
  1016. }
  1017. }
  1018. void AnimatedModel::MarkAnimationOrderDirty()
  1019. {
  1020. if (isMaster_)
  1021. {
  1022. animationOrderDirty_ = true;
  1023. MarkForUpdate();
  1024. }
  1025. }
  1026. void AnimatedModel::MarkMorphsDirty()
  1027. {
  1028. morphsDirty_ = true;
  1029. }
  1030. void AnimatedModel::CloneGeometries()
  1031. {
  1032. const Vector<SharedPtr<VertexBuffer> >& originalVertexBuffers = model_->GetVertexBuffers();
  1033. HashMap<VertexBuffer*, SharedPtr<VertexBuffer> > clonedVertexBuffers;
  1034. morphVertexBuffers_.Resize(originalVertexBuffers.Size());
  1035. for (unsigned i = 0; i < originalVertexBuffers.Size(); ++i)
  1036. {
  1037. VertexBuffer* original = originalVertexBuffers[i];
  1038. if (model_->GetMorphRangeCount(i))
  1039. {
  1040. SharedPtr<VertexBuffer> clone(new VertexBuffer(context_));
  1041. clone->SetShadowed(true);
  1042. clone->SetSize(original->GetVertexCount(), morphElementMask_ & original->GetElementMask(), true);
  1043. void* dest = clone->Lock(0, original->GetVertexCount());
  1044. if (dest)
  1045. {
  1046. CopyMorphVertices(dest, original->GetShadowData(), original->GetVertexCount(), clone, original);
  1047. clone->Unlock();
  1048. }
  1049. clonedVertexBuffers[original] = clone;
  1050. morphVertexBuffers_[i] = clone;
  1051. }
  1052. else
  1053. morphVertexBuffers_[i].Reset();
  1054. }
  1055. // Geometries will always be cloned fully. They contain only references to buffer, so they are relatively light
  1056. for (unsigned i = 0; i < geometries_.Size(); ++i)
  1057. {
  1058. for (unsigned j = 0; j < geometries_[i].Size(); ++j)
  1059. {
  1060. SharedPtr<Geometry> original = geometries_[i][j];
  1061. SharedPtr<Geometry> clone(new Geometry(context_));
  1062. // Add an additional vertex stream into the clone, which supplies only the morphable vertex data, while the static
  1063. // data comes from the original vertex buffer(s)
  1064. const Vector<SharedPtr<VertexBuffer> >& originalBuffers = original->GetVertexBuffers();
  1065. unsigned totalBuf = originalBuffers.Size();
  1066. for (unsigned k = 0; k < originalBuffers.Size(); ++k)
  1067. {
  1068. VertexBuffer* originalBuffer = originalBuffers[k];
  1069. if (clonedVertexBuffers.Contains(originalBuffer))
  1070. ++totalBuf;
  1071. }
  1072. clone->SetNumVertexBuffers(totalBuf);
  1073. unsigned l = 0;
  1074. for (unsigned k = 0; k < originalBuffers.Size(); ++k)
  1075. {
  1076. VertexBuffer* originalBuffer = originalBuffers[k];
  1077. if (clonedVertexBuffers.Contains(originalBuffer))
  1078. {
  1079. VertexBuffer* clonedBuffer = clonedVertexBuffers[originalBuffer];
  1080. clone->SetVertexBuffer(l++, originalBuffer);
  1081. // Specify the morph buffer at a greater index to override the model's original positions/normals/tangents
  1082. clone->SetVertexBuffer(l++, clonedBuffer);
  1083. }
  1084. else
  1085. clone->SetVertexBuffer(l++, originalBuffer);
  1086. }
  1087. clone->SetIndexBuffer(original->GetIndexBuffer());
  1088. clone->SetDrawRange(original->GetPrimitiveType(), original->GetIndexStart(), original->GetIndexCount());
  1089. clone->SetLodDistance(original->GetLodDistance());
  1090. geometries_[i][j] = clone;
  1091. }
  1092. }
  1093. // Make sure the rendering batches use the new cloned geometries
  1094. ResetLodLevels();
  1095. MarkMorphsDirty();
  1096. }
  1097. void AnimatedModel::CopyMorphVertices(void* destVertexData, void* srcVertexData, unsigned vertexCount, VertexBuffer* destBuffer,
  1098. VertexBuffer* srcBuffer)
  1099. {
  1100. unsigned mask = destBuffer->GetElementMask() & srcBuffer->GetElementMask();
  1101. unsigned normalOffset = srcBuffer->GetElementOffset(SEM_NORMAL);
  1102. unsigned tangentOffset = srcBuffer->GetElementOffset(SEM_TANGENT);
  1103. unsigned vertexSize = srcBuffer->GetVertexSize();
  1104. float* dest = (float*)destVertexData;
  1105. unsigned char* src = (unsigned char*)srcVertexData;
  1106. while (vertexCount--)
  1107. {
  1108. if (mask & MASK_POSITION)
  1109. {
  1110. float* posSrc = (float*)src;
  1111. dest[0] = posSrc[0];
  1112. dest[1] = posSrc[1];
  1113. dest[2] = posSrc[2];
  1114. dest += 3;
  1115. }
  1116. if (mask & MASK_NORMAL)
  1117. {
  1118. float* normalSrc = (float*)(src + normalOffset);
  1119. dest[0] = normalSrc[0];
  1120. dest[1] = normalSrc[1];
  1121. dest[2] = normalSrc[2];
  1122. dest += 3;
  1123. }
  1124. if (mask & MASK_TANGENT)
  1125. {
  1126. float* tangentSrc = (float*)(src + tangentOffset);
  1127. dest[0] = tangentSrc[0];
  1128. dest[1] = tangentSrc[1];
  1129. dest[2] = tangentSrc[2];
  1130. dest[3] = tangentSrc[3];
  1131. dest += 4;
  1132. }
  1133. src += vertexSize;
  1134. }
  1135. }
  1136. void AnimatedModel::SetGeometryBoneMappings()
  1137. {
  1138. geometrySkinMatrices_.Clear();
  1139. geometrySkinMatrixPtrs_.Clear();
  1140. if (!geometryBoneMappings_.Size())
  1141. return;
  1142. // Check if all mappings are empty, then we do not need to use mapped skinning
  1143. bool allEmpty = true;
  1144. for (unsigned i = 0; i < geometryBoneMappings_.Size(); ++i)
  1145. if (geometryBoneMappings_[i].Size())
  1146. allEmpty = false;
  1147. if (allEmpty)
  1148. return;
  1149. // Reserve space for per-geometry skinning matrices
  1150. geometrySkinMatrices_.Resize(geometryBoneMappings_.Size());
  1151. for (unsigned i = 0; i < geometryBoneMappings_.Size(); ++i)
  1152. geometrySkinMatrices_[i].Resize(geometryBoneMappings_[i].Size());
  1153. // Build original-to-skinindex matrix pointer mapping for fast copying
  1154. // Note: at this point layout of geometrySkinMatrices_ cannot be modified or pointers become invalid
  1155. geometrySkinMatrixPtrs_.Resize(skeleton_.GetNumBones());
  1156. for (unsigned i = 0; i < geometryBoneMappings_.Size(); ++i)
  1157. {
  1158. for (unsigned j = 0; j < geometryBoneMappings_[i].Size(); ++j)
  1159. geometrySkinMatrixPtrs_[geometryBoneMappings_[i][j]].Push(&geometrySkinMatrices_[i][j]);
  1160. }
  1161. }
  1162. void AnimatedModel::UpdateAnimation(const FrameInfo& frame)
  1163. {
  1164. // If using animation LOD, accumulate time and see if it is time to update
  1165. if (animationLodBias_ > 0.0f && animationLodDistance_ > 0.0f)
  1166. {
  1167. // Perform the first update always regardless of LOD timer
  1168. if (animationLodTimer_ >= 0.0f)
  1169. {
  1170. animationLodTimer_ += animationLodBias_ * frame.timeStep_ * ANIMATION_LOD_BASESCALE;
  1171. if (animationLodTimer_ >= animationLodDistance_)
  1172. animationLodTimer_ = fmodf(animationLodTimer_, animationLodDistance_);
  1173. else
  1174. return;
  1175. }
  1176. else
  1177. animationLodTimer_ = 0.0f;
  1178. }
  1179. // Make sure animations are in ascending priority order
  1180. if (animationOrderDirty_)
  1181. {
  1182. Sort(animationStates_.Begin(), animationStates_.End(), CompareAnimationOrder);
  1183. animationOrderDirty_ = false;
  1184. }
  1185. // Reset skeleton, apply all animations, calculate bones' bounding box. Make sure this is only done for the master model
  1186. // (first AnimatedModel in a node)
  1187. if (isMaster_)
  1188. {
  1189. skeleton_.ResetSilent();
  1190. for (Vector<SharedPtr<AnimationState> >::Iterator i = animationStates_.Begin(); i != animationStates_.End(); ++i)
  1191. (*i)->Apply();
  1192. // Skeleton reset and animations apply the node transforms "silently" to avoid repeated marking dirty. Mark dirty now
  1193. node_->MarkDirty();
  1194. // Calculate new bone bounding box
  1195. UpdateBoneBoundingBox();
  1196. }
  1197. animationDirty_ = false;
  1198. }
  1199. void AnimatedModel::UpdateSkinning()
  1200. {
  1201. // Note: the model's world transform will be baked in the skin matrices
  1202. const Vector<Bone>& bones = skeleton_.GetBones();
  1203. // Use model's world transform in case a bone is missing
  1204. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  1205. // Skinning with global matrices only
  1206. if (!geometrySkinMatrices_.Size())
  1207. {
  1208. for (unsigned i = 0; i < bones.Size(); ++i)
  1209. {
  1210. const Bone& bone = bones[i];
  1211. if (bone.node_)
  1212. skinMatrices_[i] = bone.node_->GetWorldTransform() * bone.offsetMatrix_;
  1213. else
  1214. skinMatrices_[i] = worldTransform;
  1215. }
  1216. }
  1217. // Skinning with per-geometry matrices
  1218. else
  1219. {
  1220. for (unsigned i = 0; i < bones.Size(); ++i)
  1221. {
  1222. const Bone& bone = bones[i];
  1223. if (bone.node_)
  1224. skinMatrices_[i] = bone.node_->GetWorldTransform() * bone.offsetMatrix_;
  1225. else
  1226. skinMatrices_[i] = worldTransform;
  1227. // Copy the skin matrix to per-geometry matrices as needed
  1228. for (unsigned j = 0; j < geometrySkinMatrixPtrs_[i].Size(); ++j)
  1229. *geometrySkinMatrixPtrs_[i][j] = skinMatrices_[i];
  1230. }
  1231. }
  1232. skinningDirty_ = false;
  1233. }
  1234. void AnimatedModel::UpdateMorphs()
  1235. {
  1236. Graphics* graphics = GetSubsystem<Graphics>();
  1237. if (!graphics)
  1238. return;
  1239. if (morphs_.Size())
  1240. {
  1241. // Reset the morph data range from all morphable vertex buffers, then apply morphs
  1242. for (unsigned i = 0; i < morphVertexBuffers_.Size(); ++i)
  1243. {
  1244. VertexBuffer* buffer = morphVertexBuffers_[i];
  1245. if (buffer)
  1246. {
  1247. VertexBuffer* originalBuffer = model_->GetVertexBuffers()[i];
  1248. unsigned morphStart = model_->GetMorphRangeStart(i);
  1249. unsigned morphCount = model_->GetMorphRangeCount(i);
  1250. void* dest = buffer->Lock(morphStart, morphCount);
  1251. if (dest)
  1252. {
  1253. // Reset morph range by copying data from the original vertex buffer
  1254. CopyMorphVertices(dest, originalBuffer->GetShadowData() + morphStart * originalBuffer->GetVertexSize(),
  1255. morphCount, buffer, originalBuffer);
  1256. for (unsigned j = 0; j < morphs_.Size(); ++j)
  1257. {
  1258. if (morphs_[j].weight_ > 0.0f)
  1259. {
  1260. HashMap<unsigned, VertexBufferMorph>::Iterator k = morphs_[j].buffers_.Find(i);
  1261. if (k != morphs_[j].buffers_.End())
  1262. ApplyMorph(buffer, dest, morphStart, k->second_, morphs_[j].weight_);
  1263. }
  1264. }
  1265. buffer->Unlock();
  1266. }
  1267. }
  1268. }
  1269. }
  1270. morphsDirty_ = false;
  1271. }
  1272. void AnimatedModel::ApplyMorph(VertexBuffer* buffer, void* destVertexData, unsigned morphRangeStart, const VertexBufferMorph& morph,
  1273. float weight)
  1274. {
  1275. unsigned elementMask = morph.elementMask_ & buffer->GetElementMask();
  1276. unsigned vertexCount = morph.vertexCount_;
  1277. unsigned normalOffset = buffer->GetElementOffset(SEM_NORMAL);
  1278. unsigned tangentOffset = buffer->GetElementOffset(SEM_TANGENT);
  1279. unsigned vertexSize = buffer->GetVertexSize();
  1280. unsigned char* srcData = morph.morphData_;
  1281. unsigned char* destData = (unsigned char*)destVertexData;
  1282. while (vertexCount--)
  1283. {
  1284. unsigned vertexIndex = *((unsigned*)srcData) - morphRangeStart;
  1285. srcData += sizeof(unsigned);
  1286. if (elementMask & MASK_POSITION)
  1287. {
  1288. float* dest = (float*)(destData + vertexIndex * vertexSize);
  1289. float* src = (float*)srcData;
  1290. dest[0] += src[0] * weight;
  1291. dest[1] += src[1] * weight;
  1292. dest[2] += src[2] * weight;
  1293. srcData += 3 * sizeof(float);
  1294. }
  1295. if (elementMask & MASK_NORMAL)
  1296. {
  1297. float* dest = (float*)(destData + vertexIndex * vertexSize + normalOffset);
  1298. float* src = (float*)srcData;
  1299. dest[0] += src[0] * weight;
  1300. dest[1] += src[1] * weight;
  1301. dest[2] += src[2] * weight;
  1302. srcData += 3 * sizeof(float);
  1303. }
  1304. if (elementMask & MASK_TANGENT)
  1305. {
  1306. float* dest = (float*)(destData + vertexIndex * vertexSize + tangentOffset);
  1307. float* src = (float*)srcData;
  1308. dest[0] += src[0] * weight;
  1309. dest[1] += src[1] * weight;
  1310. dest[2] += src[2] * weight;
  1311. srcData += 3 * sizeof(float);
  1312. }
  1313. }
  1314. }
  1315. void AnimatedModel::HandleModelReloadFinished(StringHash eventType, VariantMap& eventData)
  1316. {
  1317. Model* currentModel = model_;
  1318. model_.Reset(); // Set null to allow to be re-set
  1319. SetModel(currentModel);
  1320. }
  1321. }