CSkinnedMesh.cpp 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648
  1. // Copyright (C) 2002-2012 Nikolaus Gebhardt
  2. // This file is part of the "Irrlicht Engine".
  3. // For conditions of distribution and use, see copyright notice in irrlicht.h
  4. #include "IrrCompileConfig.h"
  5. #ifdef _IRR_COMPILE_WITH_SKINNED_MESH_SUPPORT_
  6. #include "CSkinnedMesh.h"
  7. #include "CBoneSceneNode.h"
  8. #include "IAnimatedMeshSceneNode.h"
  9. #include "os.h"
  10. #include "irrMap.h"
  11. namespace irr
  12. {
  13. namespace scene
  14. {
  15. //! constructor
  16. CSkinnedMesh::CSkinnedMesh()
  17. : SkinningBuffers(0), AnimationFrames(0.f), FramesPerSecond(25.f),
  18. LastAnimatedFrame(-1), SkinnedLastFrame(false),
  19. InterpolationMode(EIM_LINEAR),
  20. HasAnimation(false), PreparedForSkinning(false),
  21. AnimateNormals(true), HardwareSkinning(false), m_total_joints(0),
  22. m_current_joint(0)
  23. {
  24. #ifdef _DEBUG
  25. setDebugName("CSkinnedMesh");
  26. #endif
  27. SkinningBuffers=&LocalBuffers;
  28. }
  29. //! destructor
  30. CSkinnedMesh::~CSkinnedMesh()
  31. {
  32. for (u32 i=0; i<AllJoints.size(); ++i)
  33. delete AllJoints[i];
  34. for (u32 j=0; j<LocalBuffers.size(); ++j)
  35. {
  36. if (LocalBuffers[j])
  37. LocalBuffers[j]->drop();
  38. }
  39. }
  40. //! returns the amount of frames in milliseconds.
  41. //! If the amount is 1, it is a static (=non animated) mesh.
  42. u32 CSkinnedMesh::getFrameCount() const
  43. {
  44. return core::floor32(AnimationFrames);
  45. }
  46. //! Gets the default animation speed of the animated mesh.
  47. /** \return Amount of frames per second. If the amount is 0, it is a static, non animated mesh. */
  48. f32 CSkinnedMesh::getAnimationSpeed() const
  49. {
  50. return FramesPerSecond;
  51. }
  52. //! Gets the frame count of the animated mesh.
  53. /** \param fps Frames per second to play the animation with. If the amount is 0, it is not animated.
  54. The actual speed is set in the scene node the mesh is instantiated in.*/
  55. void CSkinnedMesh::setAnimationSpeed(f32 fps)
  56. {
  57. FramesPerSecond=fps;
  58. }
  59. //! returns the animated mesh based on a detail level. 0 is the lowest, 255 the highest detail. Note, that some Meshes will ignore the detail level.
  60. IMesh* CSkinnedMesh::getMesh(s32 frame, s32 detailLevel, s32 startFrameLoop, s32 endFrameLoop)
  61. {
  62. const bool is_hw_skinning_before = HardwareSkinning;
  63. if (is_hw_skinning_before)
  64. HardwareSkinning = false;
  65. //animate(frame,startFrameLoop, endFrameLoop);
  66. if (frame==-1)
  67. return this;
  68. animateMesh((f32)frame, 1.0f);
  69. skinMesh();
  70. if (is_hw_skinning_before)
  71. HardwareSkinning = true;
  72. return this;
  73. }
  74. //--------------------------------------------------------------------------
  75. // Keyframe Animation
  76. //--------------------------------------------------------------------------
  77. //! Animates this mesh's joints based on frame input
  78. //! blend: {0-old position, 1-New position}
  79. void CSkinnedMesh::animateMesh(f32 frame, f32 blend)
  80. {
  81. if (HardwareSkinning && LastAnimatedFrame==frame)
  82. {
  83. SkinnedLastFrame=false;
  84. return;
  85. }
  86. if (!HasAnimation || LastAnimatedFrame==frame)
  87. return;
  88. LastAnimatedFrame=frame;
  89. SkinnedLastFrame=false;
  90. if (blend<=0.f)
  91. return; //No need to animate
  92. for (u32 i=0; i<AllJoints.size(); ++i)
  93. {
  94. //The joints can be animated here with no input from their
  95. //parents, but for setAnimationMode extra checks are needed
  96. //to their parents
  97. SJoint *joint = AllJoints[i];
  98. const core::vector3df oldPosition = joint->Animatedposition;
  99. const core::vector3df oldScale = joint->Animatedscale;
  100. const core::quaternion oldRotation = joint->Animatedrotation;
  101. core::vector3df position = oldPosition;
  102. core::vector3df scale = oldScale;
  103. core::quaternion rotation = oldRotation;
  104. getFrameData(frame, joint,
  105. position, joint->positionHint,
  106. scale, joint->scaleHint,
  107. rotation, joint->rotationHint);
  108. if (blend==1.0f)
  109. {
  110. //No blending needed
  111. joint->Animatedposition = position;
  112. joint->Animatedscale = scale;
  113. joint->Animatedrotation = rotation;
  114. }
  115. else
  116. {
  117. //Blend animation
  118. joint->Animatedposition = core::lerp(oldPosition, position, blend);
  119. joint->Animatedscale = core::lerp(oldScale, scale, blend);
  120. joint->Animatedrotation.slerp(oldRotation, rotation, blend);
  121. }
  122. }
  123. //Note:
  124. //LocalAnimatedMatrix needs to be built at some point, but this function may be called lots of times for
  125. //one render (to play two animations at the same time) LocalAnimatedMatrix only needs to be built once.
  126. //a call to buildAllLocalAnimatedMatrices is needed before skinning the mesh, and before the user gets the joints to move
  127. //----------------
  128. // Temp!
  129. buildAllLocalAnimatedMatrices();
  130. //-----------------
  131. updateBoundingBox();
  132. }
  133. void CSkinnedMesh::buildAllLocalAnimatedMatrices()
  134. {
  135. for (u32 i=0; i<AllJoints.size(); ++i)
  136. {
  137. SJoint *joint = AllJoints[i];
  138. //Could be faster:
  139. if (joint->UseAnimationFrom &&
  140. (joint->UseAnimationFrom->PositionKeys.size() ||
  141. joint->UseAnimationFrom->ScaleKeys.size() ||
  142. joint->UseAnimationFrom->RotationKeys.size() ))
  143. {
  144. joint->GlobalSkinningSpace=false;
  145. // IRR_TEST_BROKEN_QUATERNION_USE: TODO - switched to getMatrix_transposed instead of getMatrix for downward compatibility.
  146. // Not tested so far if this was correct or wrong before quaternion fix!
  147. joint->Animatedrotation.getMatrix_transposed(joint->LocalAnimatedMatrix);
  148. // --- joint->LocalAnimatedMatrix *= joint->Animatedrotation.getMatrix() ---
  149. f32 *m1 = joint->LocalAnimatedMatrix.pointer();
  150. core::vector3df &Pos = joint->Animatedposition;
  151. m1[0] += Pos.X*m1[3];
  152. m1[1] += Pos.Y*m1[3];
  153. m1[2] += Pos.Z*m1[3];
  154. m1[4] += Pos.X*m1[7];
  155. m1[5] += Pos.Y*m1[7];
  156. m1[6] += Pos.Z*m1[7];
  157. m1[8] += Pos.X*m1[11];
  158. m1[9] += Pos.Y*m1[11];
  159. m1[10] += Pos.Z*m1[11];
  160. m1[12] += Pos.X*m1[15];
  161. m1[13] += Pos.Y*m1[15];
  162. m1[14] += Pos.Z*m1[15];
  163. // -----------------------------------
  164. if (joint->ScaleKeys.size())
  165. {
  166. /*
  167. core::matrix4 scaleMatrix;
  168. scaleMatrix.setScale(joint->Animatedscale);
  169. joint->LocalAnimatedMatrix *= scaleMatrix;
  170. */
  171. // -------- joint->LocalAnimatedMatrix *= scaleMatrix -----------------
  172. core::matrix4& mat = joint->LocalAnimatedMatrix;
  173. mat[0] *= joint->Animatedscale.X;
  174. mat[1] *= joint->Animatedscale.X;
  175. mat[2] *= joint->Animatedscale.X;
  176. mat[3] *= joint->Animatedscale.X;
  177. mat[4] *= joint->Animatedscale.Y;
  178. mat[5] *= joint->Animatedscale.Y;
  179. mat[6] *= joint->Animatedscale.Y;
  180. mat[7] *= joint->Animatedscale.Y;
  181. mat[8] *= joint->Animatedscale.Z;
  182. mat[9] *= joint->Animatedscale.Z;
  183. mat[10] *= joint->Animatedscale.Z;
  184. mat[11] *= joint->Animatedscale.Z;
  185. // -----------------------------------
  186. }
  187. }
  188. else
  189. {
  190. joint->LocalAnimatedMatrix=joint->LocalMatrix;
  191. }
  192. }
  193. SkinnedLastFrame=false;
  194. }
  195. void CSkinnedMesh::buildAllGlobalAnimatedMatrices(SJoint *joint, SJoint *parentJoint)
  196. {
  197. if (!joint)
  198. {
  199. for (u32 i=0; i<RootJoints.size(); ++i)
  200. buildAllGlobalAnimatedMatrices(RootJoints[i], 0);
  201. return;
  202. }
  203. else
  204. {
  205. // Find global matrix...
  206. if (!parentJoint || joint->GlobalSkinningSpace)
  207. joint->GlobalAnimatedMatrix = joint->LocalAnimatedMatrix;
  208. else
  209. joint->GlobalAnimatedMatrix = parentJoint->GlobalAnimatedMatrix * joint->LocalAnimatedMatrix;
  210. }
  211. for (u32 j=0; j<joint->Children.size(); ++j)
  212. buildAllGlobalAnimatedMatrices(joint->Children[j], joint);
  213. }
  214. void CSkinnedMesh::getFrameData(f32 frame, SJoint *joint,
  215. core::vector3df &position, s32 &positionHint,
  216. core::vector3df &scale, s32 &scaleHint,
  217. core::quaternion &rotation, s32 &rotationHint)
  218. {
  219. s32 foundPositionIndex = -1;
  220. s32 foundScaleIndex = -1;
  221. s32 foundRotationIndex = -1;
  222. if (joint->UseAnimationFrom)
  223. {
  224. const core::array<SPositionKey> &PositionKeys=joint->UseAnimationFrom->PositionKeys;
  225. const core::array<SScaleKey> &ScaleKeys=joint->UseAnimationFrom->ScaleKeys;
  226. const core::array<SRotationKey> &RotationKeys=joint->UseAnimationFrom->RotationKeys;
  227. if (PositionKeys.size())
  228. {
  229. foundPositionIndex = -1;
  230. //Test the Hints...
  231. if (positionHint>=0 && (u32)positionHint < PositionKeys.size())
  232. {
  233. //check this hint
  234. if (positionHint>0 && PositionKeys[positionHint].frame>=frame && PositionKeys[positionHint-1].frame<frame )
  235. foundPositionIndex=positionHint;
  236. else if (positionHint+1 < (s32)PositionKeys.size())
  237. {
  238. //check the next index
  239. if ( PositionKeys[positionHint+1].frame>=frame &&
  240. PositionKeys[positionHint+0].frame<frame)
  241. {
  242. positionHint++;
  243. foundPositionIndex=positionHint;
  244. }
  245. }
  246. }
  247. //The hint test failed, do a full scan...
  248. if (foundPositionIndex==-1)
  249. {
  250. for (u32 i=0; i<PositionKeys.size(); ++i)
  251. {
  252. if (PositionKeys[i].frame >= frame) //Keys should to be sorted by frame
  253. {
  254. foundPositionIndex=i;
  255. positionHint=i;
  256. break;
  257. }
  258. }
  259. }
  260. //Do interpolation...
  261. if (foundPositionIndex!=-1)
  262. {
  263. if (InterpolationMode==EIM_CONSTANT || foundPositionIndex==0)
  264. {
  265. position = PositionKeys[foundPositionIndex].position;
  266. }
  267. else if (InterpolationMode==EIM_LINEAR)
  268. {
  269. const SPositionKey& KeyA = PositionKeys[foundPositionIndex];
  270. const SPositionKey& KeyB = PositionKeys[foundPositionIndex-1];
  271. const f32 fd1 = frame - KeyA.frame;
  272. const f32 fd2 = KeyB.frame - frame;
  273. position = ((KeyB.position-KeyA.position)/(fd1+fd2))*fd1 + KeyA.position;
  274. }
  275. }
  276. }
  277. //------------------------------------------------------------
  278. if (ScaleKeys.size())
  279. {
  280. foundScaleIndex = -1;
  281. //Test the Hints...
  282. if (scaleHint>=0 && (u32)scaleHint < ScaleKeys.size())
  283. {
  284. //check this hint
  285. if (scaleHint>0 && ScaleKeys[scaleHint].frame>=frame && ScaleKeys[scaleHint-1].frame<frame )
  286. foundScaleIndex=scaleHint;
  287. else if (scaleHint+1 < (s32)ScaleKeys.size())
  288. {
  289. //check the next index
  290. if ( ScaleKeys[scaleHint+1].frame>=frame &&
  291. ScaleKeys[scaleHint+0].frame<frame)
  292. {
  293. scaleHint++;
  294. foundScaleIndex=scaleHint;
  295. }
  296. }
  297. }
  298. //The hint test failed, do a full scan...
  299. if (foundScaleIndex==-1)
  300. {
  301. for (u32 i=0; i<ScaleKeys.size(); ++i)
  302. {
  303. if (ScaleKeys[i].frame >= frame) //Keys should to be sorted by frame
  304. {
  305. foundScaleIndex=i;
  306. scaleHint=i;
  307. break;
  308. }
  309. }
  310. }
  311. //Do interpolation...
  312. if (foundScaleIndex!=-1)
  313. {
  314. if (InterpolationMode==EIM_CONSTANT || foundScaleIndex==0)
  315. {
  316. scale = ScaleKeys[foundScaleIndex].scale;
  317. }
  318. else if (InterpolationMode==EIM_LINEAR)
  319. {
  320. const SScaleKey& KeyA = ScaleKeys[foundScaleIndex];
  321. const SScaleKey& KeyB = ScaleKeys[foundScaleIndex-1];
  322. const f32 fd1 = frame - KeyA.frame;
  323. const f32 fd2 = KeyB.frame - frame;
  324. scale = ((KeyB.scale-KeyA.scale)/(fd1+fd2))*fd1 + KeyA.scale;
  325. }
  326. }
  327. }
  328. //-------------------------------------------------------------
  329. if (RotationKeys.size())
  330. {
  331. foundRotationIndex = -1;
  332. //Test the Hints...
  333. if (rotationHint>=0 && (u32)rotationHint < RotationKeys.size())
  334. {
  335. //check this hint
  336. if (rotationHint>0 && RotationKeys[rotationHint].frame>=frame && RotationKeys[rotationHint-1].frame<frame )
  337. foundRotationIndex=rotationHint;
  338. else if (rotationHint+1 < (s32)RotationKeys.size())
  339. {
  340. //check the next index
  341. if ( RotationKeys[rotationHint+1].frame>=frame &&
  342. RotationKeys[rotationHint+0].frame<frame)
  343. {
  344. rotationHint++;
  345. foundRotationIndex=rotationHint;
  346. }
  347. }
  348. }
  349. //The hint test failed, do a full scan...
  350. if (foundRotationIndex==-1)
  351. {
  352. for (u32 i=0; i<RotationKeys.size(); ++i)
  353. {
  354. if (RotationKeys[i].frame >= frame) //Keys should be sorted by frame
  355. {
  356. foundRotationIndex=i;
  357. rotationHint=i;
  358. break;
  359. }
  360. }
  361. }
  362. //Do interpolation...
  363. if (foundRotationIndex!=-1)
  364. {
  365. if (InterpolationMode==EIM_CONSTANT || foundRotationIndex==0)
  366. {
  367. rotation = RotationKeys[foundRotationIndex].rotation;
  368. }
  369. else if (InterpolationMode==EIM_LINEAR)
  370. {
  371. const SRotationKey& KeyA = RotationKeys[foundRotationIndex];
  372. const SRotationKey& KeyB = RotationKeys[foundRotationIndex-1];
  373. const f32 fd1 = frame - KeyA.frame;
  374. const f32 fd2 = KeyB.frame - frame;
  375. const f32 t = fd1/(fd1+fd2);
  376. /*
  377. f32 t = 0;
  378. if (KeyA.frame!=KeyB.frame)
  379. t = (frame-KeyA.frame) / (KeyB.frame - KeyA.frame);
  380. */
  381. rotation.slerp(KeyA.rotation, KeyB.rotation, t);
  382. }
  383. }
  384. }
  385. }
  386. }
  387. //--------------------------------------------------------------------------
  388. // Software Skinning
  389. //--------------------------------------------------------------------------
  390. //! Preforms a software skin on this mesh based of joint positions
  391. void CSkinnedMesh::skinMesh(f32 strength, SkinningCallback sc, int offset)
  392. {
  393. if (!HasAnimation || SkinnedLastFrame)
  394. return;
  395. //----------------
  396. // This is marked as "Temp!". A shiny dubloon to whomever can tell me why.
  397. buildAllGlobalAnimatedMatrices();
  398. //-----------------
  399. SkinnedLastFrame=true;
  400. m_current_joint = 0;
  401. if (HardwareSkinning)
  402. {
  403. for (u32 i = 0; i < RootJoints.size(); i++)
  404. skinJoint(RootJoints[i], 0, strength, sc, offset);
  405. }
  406. else
  407. {
  408. //Software skin....
  409. u32 i;
  410. //rigid animation
  411. for (i=0; i<AllJoints.size(); ++i)
  412. {
  413. for (u32 j=0; j<AllJoints[i]->AttachedMeshes.size(); ++j)
  414. {
  415. SSkinMeshBuffer* Buffer=(*SkinningBuffers)[ AllJoints[i]->AttachedMeshes[j] ];
  416. Buffer->Transformation=AllJoints[i]->GlobalAnimatedMatrix;
  417. }
  418. }
  419. //clear skinning helper array
  420. for (i=0; i<Vertices_Moved.size(); ++i)
  421. for (u32 j=0; j<Vertices_Moved[i].size(); ++j)
  422. Vertices_Moved[i][j]=false;
  423. //skin starting with the root joints
  424. for (i=0; i<RootJoints.size(); ++i)
  425. skinJoint(RootJoints[i], 0, strength);
  426. for (i=0; i<SkinningBuffers->size(); ++i)
  427. (*SkinningBuffers)[i]->setDirty(EBT_VERTEX);
  428. }
  429. updateBoundingBox();
  430. }
  431. void CSkinnedMesh::skinJoint(SJoint *joint, SJoint *parentJoint, f32 strength,
  432. SkinningCallback sc, int offset)
  433. {
  434. if (joint->Weights.size())
  435. {
  436. //Find this joints pull on vertices...
  437. core::matrix4 jointVertexPull(core::matrix4::EM4CONST_NOTHING);
  438. jointVertexPull.setbyproduct(joint->GlobalAnimatedMatrix, joint->GlobalInversedMatrix);
  439. if (HardwareSkinning)
  440. {
  441. if (sc != NULL) sc(jointVertexPull, m_current_joint, offset);
  442. m_current_joint++;
  443. }
  444. else
  445. {
  446. core::vector3df thisVertexMove, thisNormalMove;
  447. core::array<scene::SSkinMeshBuffer*> &buffersUsed=*SkinningBuffers;
  448. //Skin Vertices Positions and Normals...
  449. for (u32 i=0; i<joint->Weights.size(); ++i)
  450. {
  451. SWeight& weight = joint->Weights[i];
  452. // Pull this vertex...
  453. jointVertexPull.transformVect(thisVertexMove, weight.StaticPos);
  454. if (AnimateNormals)
  455. jointVertexPull.rotateVect(thisNormalMove, weight.StaticNormal);
  456. // Apply animation strength
  457. if(strength != 1.f)
  458. {
  459. thisVertexMove = core::lerp(weight.StaticPos, thisVertexMove, strength);
  460. if(AnimateNormals)
  461. thisNormalMove = core::lerp(weight.StaticNormal, thisNormalMove, strength);
  462. }
  463. if (! (*(weight.Moved)) )
  464. {
  465. *(weight.Moved) = true;
  466. buffersUsed[weight.buffer_id]->getVertex(weight.vertex_id)->Pos = thisVertexMove * weight.strength;
  467. if (AnimateNormals)
  468. buffersUsed[weight.buffer_id]->getVertex(weight.vertex_id)->Normal = thisNormalMove * weight.strength;
  469. //*(weight._Pos) = thisVertexMove * weight.strength;
  470. }
  471. else
  472. {
  473. buffersUsed[weight.buffer_id]->getVertex(weight.vertex_id)->Pos += thisVertexMove * weight.strength;
  474. if (AnimateNormals)
  475. buffersUsed[weight.buffer_id]->getVertex(weight.vertex_id)->Normal += thisNormalMove * weight.strength;
  476. //*(weight._Pos) += thisVertexMove * weight.strength;
  477. }
  478. buffersUsed[weight.buffer_id]->boundingBoxNeedsRecalculated();
  479. }
  480. }
  481. }
  482. //Skin all children
  483. for (u32 j=0; j<joint->Children.size(); ++j)
  484. skinJoint(joint->Children[j], joint, strength, sc, offset);
  485. }
  486. E_ANIMATED_MESH_TYPE CSkinnedMesh::getMeshType() const
  487. {
  488. return EAMT_SKINNED;
  489. }
  490. //! Gets joint count.
  491. u32 CSkinnedMesh::getJointCount() const
  492. {
  493. return AllJoints.size();
  494. }
  495. //! Gets the name of a joint.
  496. const c8* CSkinnedMesh::getJointName(u32 number) const
  497. {
  498. if (number >= AllJoints.size())
  499. return 0;
  500. return AllJoints[number]->Name.c_str();
  501. }
  502. //! Gets a joint number from its name
  503. s32 CSkinnedMesh::getJointNumber(const c8* name) const
  504. {
  505. for (u32 i=0; i<AllJoints.size(); ++i)
  506. {
  507. if (AllJoints[i]->Name == name)
  508. return i;
  509. }
  510. return -1;
  511. }
  512. //! returns amount of mesh buffers.
  513. u32 CSkinnedMesh::getMeshBufferCount() const
  514. {
  515. return LocalBuffers.size();
  516. }
  517. //! returns pointer to a mesh buffer
  518. IMeshBuffer* CSkinnedMesh::getMeshBuffer(u32 nr) const
  519. {
  520. if (nr < LocalBuffers.size())
  521. return LocalBuffers[nr];
  522. else
  523. return 0;
  524. }
  525. //! Returns pointer to a mesh buffer which fits a material
  526. IMeshBuffer* CSkinnedMesh::getMeshBuffer(const video::SMaterial &material) const
  527. {
  528. for (u32 i=0; i<LocalBuffers.size(); ++i)
  529. {
  530. if (LocalBuffers[i]->getMaterial() == material)
  531. return LocalBuffers[i];
  532. }
  533. return 0;
  534. }
  535. //! returns an axis aligned bounding box
  536. const core::aabbox3d<f32>& CSkinnedMesh::getBoundingBox() const
  537. {
  538. return BoundingBox;
  539. }
  540. //! set user axis aligned bounding box
  541. void CSkinnedMesh::setBoundingBox( const core::aabbox3df& box)
  542. {
  543. BoundingBox = box;
  544. }
  545. //! sets a flag of all contained materials to a new value
  546. void CSkinnedMesh::setMaterialFlag(video::E_MATERIAL_FLAG flag, bool newvalue)
  547. {
  548. for (u32 i=0; i<LocalBuffers.size(); ++i)
  549. LocalBuffers[i]->Material.setFlag(flag,newvalue);
  550. }
  551. //! set the hardware mapping hint, for driver
  552. void CSkinnedMesh::setHardwareMappingHint(E_HARDWARE_MAPPING newMappingHint,
  553. E_BUFFER_TYPE buffer)
  554. {
  555. for (u32 i=0; i<LocalBuffers.size(); ++i)
  556. LocalBuffers[i]->setHardwareMappingHint(newMappingHint, buffer);
  557. }
  558. //! flags the meshbuffer as changed, reloads hardware buffers
  559. void CSkinnedMesh::setDirty(E_BUFFER_TYPE buffer)
  560. {
  561. for (u32 i=0; i<LocalBuffers.size(); ++i)
  562. LocalBuffers[i]->setDirty(buffer);
  563. }
  564. //! uses animation from another mesh
  565. bool CSkinnedMesh::useAnimationFrom(const ISkinnedMesh *mesh)
  566. {
  567. bool unmatched=false;
  568. for(u32 i=0;i<AllJoints.size();++i)
  569. {
  570. SJoint *joint=AllJoints[i];
  571. joint->UseAnimationFrom=0;
  572. if (joint->Name=="")
  573. unmatched=true;
  574. else
  575. {
  576. for(u32 j=0;j<mesh->getAllJoints().size();++j)
  577. {
  578. SJoint *otherJoint=mesh->getAllJoints()[j];
  579. if (joint->Name==otherJoint->Name)
  580. {
  581. joint->UseAnimationFrom=otherJoint;
  582. }
  583. }
  584. if (!joint->UseAnimationFrom)
  585. unmatched=true;
  586. }
  587. }
  588. checkForAnimation();
  589. return !unmatched;
  590. }
  591. //!Update Normals when Animating
  592. //!False= Don't animate them, faster
  593. //!True= Update normals (default)
  594. void CSkinnedMesh::updateNormalsWhenAnimating(bool on)
  595. {
  596. AnimateNormals = on;
  597. }
  598. //!Sets Interpolation Mode
  599. void CSkinnedMesh::setInterpolationMode(E_INTERPOLATION_MODE mode)
  600. {
  601. InterpolationMode = mode;
  602. }
  603. core::array<scene::SSkinMeshBuffer*> &CSkinnedMesh::getMeshBuffers()
  604. {
  605. return LocalBuffers;
  606. }
  607. core::array<CSkinnedMesh::SJoint*> &CSkinnedMesh::getAllJoints()
  608. {
  609. return AllJoints;
  610. }
  611. const core::array<CSkinnedMesh::SJoint*> &CSkinnedMesh::getAllJoints() const
  612. {
  613. return AllJoints;
  614. }
  615. //! (This feature is not implementated in irrlicht yet)
  616. bool CSkinnedMesh::setHardwareSkinning(bool on)
  617. {
  618. if (HardwareSkinning!=on)
  619. {
  620. if (on)
  621. toStaticPose();
  622. HardwareSkinning=on;
  623. }
  624. return HardwareSkinning;
  625. }
  626. void CSkinnedMesh::toStaticPose()
  627. {
  628. for (u32 i=0; i<AllJoints.size(); ++i)
  629. {
  630. SJoint *joint=AllJoints[i];
  631. for (u32 j=0; j<joint->Weights.size(); ++j)
  632. {
  633. const u16 buffer_id=joint->Weights[j].buffer_id;
  634. const u32 vertex_id=joint->Weights[j].vertex_id;
  635. LocalBuffers[buffer_id]->getVertex(vertex_id)->Pos = joint->Weights[j].StaticPos;
  636. LocalBuffers[buffer_id]->getVertex(vertex_id)->Normal = joint->Weights[j].StaticNormal;
  637. LocalBuffers[buffer_id]->boundingBoxNeedsRecalculated();
  638. }
  639. }
  640. }
  641. void CSkinnedMesh::calculateGlobalMatrices(SJoint *joint,SJoint *parentJoint)
  642. {
  643. if (!joint && parentJoint) // bit of protection from endless loops
  644. return;
  645. //Go through the root bones
  646. if (!joint)
  647. {
  648. for (u32 i=0; i<RootJoints.size(); ++i)
  649. calculateGlobalMatrices(RootJoints[i],0);
  650. return;
  651. }
  652. if (!parentJoint)
  653. joint->GlobalMatrix = joint->LocalMatrix;
  654. else
  655. joint->GlobalMatrix = parentJoint->GlobalMatrix * joint->LocalMatrix;
  656. joint->LocalAnimatedMatrix=joint->LocalMatrix;
  657. joint->GlobalAnimatedMatrix=joint->GlobalMatrix;
  658. if (joint->GlobalInversedMatrix.isIdentity())//might be pre calculated
  659. {
  660. joint->GlobalInversedMatrix = joint->GlobalMatrix;
  661. joint->GlobalInversedMatrix.makeInverse(); // slow
  662. }
  663. for (u32 j=0; j<joint->Children.size(); ++j)
  664. calculateGlobalMatrices(joint->Children[j],joint);
  665. SkinnedLastFrame=false;
  666. }
  667. void CSkinnedMesh::checkForAnimation()
  668. {
  669. u32 i,j;
  670. //Check for animation...
  671. HasAnimation = false;
  672. for(i=0;i<AllJoints.size();++i)
  673. {
  674. if (AllJoints[i]->UseAnimationFrom)
  675. {
  676. if (AllJoints[i]->UseAnimationFrom->PositionKeys.size() ||
  677. AllJoints[i]->UseAnimationFrom->ScaleKeys.size() ||
  678. AllJoints[i]->UseAnimationFrom->RotationKeys.size() )
  679. {
  680. HasAnimation = true;
  681. break;
  682. }
  683. }
  684. }
  685. //meshes with weights, are still counted as animated for ragdolls, etc
  686. if (!HasAnimation)
  687. {
  688. for(i=0;i<AllJoints.size();++i)
  689. {
  690. if (AllJoints[i]->Weights.size())
  691. {
  692. HasAnimation = true;
  693. break;
  694. }
  695. }
  696. }
  697. if (HasAnimation)
  698. {
  699. //--- Find the length of the animation ---
  700. AnimationFrames=0;
  701. for(i=0;i<AllJoints.size();++i)
  702. {
  703. if (AllJoints[i]->UseAnimationFrom)
  704. {
  705. if (AllJoints[i]->UseAnimationFrom->PositionKeys.size())
  706. if (AllJoints[i]->UseAnimationFrom->PositionKeys.getLast().frame > AnimationFrames)
  707. AnimationFrames=AllJoints[i]->UseAnimationFrom->PositionKeys.getLast().frame;
  708. if (AllJoints[i]->UseAnimationFrom->ScaleKeys.size())
  709. if (AllJoints[i]->UseAnimationFrom->ScaleKeys.getLast().frame > AnimationFrames)
  710. AnimationFrames=AllJoints[i]->UseAnimationFrom->ScaleKeys.getLast().frame;
  711. if (AllJoints[i]->UseAnimationFrom->RotationKeys.size())
  712. if (AllJoints[i]->UseAnimationFrom->RotationKeys.getLast().frame > AnimationFrames)
  713. AnimationFrames=AllJoints[i]->UseAnimationFrom->RotationKeys.getLast().frame;
  714. }
  715. }
  716. }
  717. if (HasAnimation && !PreparedForSkinning)
  718. {
  719. PreparedForSkinning=true;
  720. //check for bugs:
  721. for(i=0; i < AllJoints.size(); ++i)
  722. {
  723. SJoint *joint = AllJoints[i];
  724. for (j=0; j<joint->Weights.size(); ++j)
  725. {
  726. const u16 buffer_id=joint->Weights[j].buffer_id;
  727. const u32 vertex_id=joint->Weights[j].vertex_id;
  728. //check for invalid ids
  729. if (buffer_id>=LocalBuffers.size())
  730. {
  731. os::Printer::log("Skinned Mesh: Weight buffer id too large", ELL_WARNING);
  732. joint->Weights[j].buffer_id = joint->Weights[j].vertex_id =0;
  733. }
  734. else if (vertex_id>=LocalBuffers[buffer_id]->getVertexCount())
  735. {
  736. os::Printer::log("Skinned Mesh: Weight vertex id too large", ELL_WARNING);
  737. joint->Weights[j].buffer_id = joint->Weights[j].vertex_id =0;
  738. }
  739. }
  740. }
  741. //An array used in skinning
  742. for (i=0; i<Vertices_Moved.size(); ++i)
  743. for (j=0; j<Vertices_Moved[i].size(); ++j)
  744. Vertices_Moved[i][j] = false;
  745. // For skinning: cache weight values for speed
  746. for (i=0; i<AllJoints.size(); ++i)
  747. {
  748. SJoint *joint = AllJoints[i];
  749. for (j=0; j<joint->Weights.size(); ++j)
  750. {
  751. const u16 buffer_id=joint->Weights[j].buffer_id;
  752. const u32 vertex_id=joint->Weights[j].vertex_id;
  753. joint->Weights[j].Moved = &Vertices_Moved[buffer_id] [vertex_id];
  754. joint->Weights[j].StaticPos = LocalBuffers[buffer_id]->getVertex(vertex_id)->Pos;
  755. joint->Weights[j].StaticNormal = LocalBuffers[buffer_id]->getVertex(vertex_id)->Normal;
  756. //joint->Weights[j]._Pos=&Buffers[buffer_id]->getVertex(vertex_id)->Pos;
  757. }
  758. }
  759. // normalize weights
  760. normalizeWeights();
  761. }
  762. SkinnedLastFrame=false;
  763. }
  764. //! called by loader after populating with mesh and bone data
  765. void CSkinnedMesh::finalize()
  766. {
  767. u32 i;
  768. // Make sure we recalc the next frame
  769. LastAnimatedFrame=-1;
  770. SkinnedLastFrame=false;
  771. //calculate bounding box
  772. for (i=0; i<LocalBuffers.size(); ++i)
  773. {
  774. LocalBuffers[i]->recalculateBoundingBox();
  775. }
  776. if (AllJoints.size() || RootJoints.size())
  777. {
  778. // populate AllJoints or RootJoints, depending on which is empty
  779. if (!RootJoints.size())
  780. {
  781. for(u32 CheckingIdx=0; CheckingIdx < AllJoints.size(); ++CheckingIdx)
  782. {
  783. bool foundParent=false;
  784. for(i=0; i < AllJoints.size(); ++i)
  785. {
  786. for(u32 n=0; n < AllJoints[i]->Children.size(); ++n)
  787. {
  788. if (AllJoints[i]->Children[n] == AllJoints[CheckingIdx])
  789. foundParent=true;
  790. }
  791. }
  792. if (!foundParent)
  793. RootJoints.push_back(AllJoints[CheckingIdx]);
  794. }
  795. }
  796. else
  797. {
  798. AllJoints=RootJoints;
  799. }
  800. }
  801. for(i=0; i < AllJoints.size(); ++i)
  802. {
  803. AllJoints[i]->UseAnimationFrom=AllJoints[i];
  804. }
  805. //Set array sizes...
  806. for (i=0; i<LocalBuffers.size(); ++i)
  807. {
  808. Vertices_Moved.push_back( core::array<bool>() );
  809. Vertices_Moved[i].set_used(LocalBuffers[i]->getVertexCount());
  810. }
  811. //Todo: optimise keys here...
  812. checkForAnimation();
  813. if (HasAnimation)
  814. {
  815. //--- optimize and check keyframes ---
  816. for(i=0;i<AllJoints.size();++i)
  817. {
  818. core::array<SPositionKey> &PositionKeys =AllJoints[i]->PositionKeys;
  819. core::array<SScaleKey> &ScaleKeys = AllJoints[i]->ScaleKeys;
  820. core::array<SRotationKey> &RotationKeys = AllJoints[i]->RotationKeys;
  821. if (PositionKeys.size()>2)
  822. {
  823. for(u32 j=0;j<PositionKeys.size()-2;++j)
  824. {
  825. if (PositionKeys[j].position == PositionKeys[j+1].position && PositionKeys[j+1].position == PositionKeys[j+2].position)
  826. {
  827. PositionKeys.erase(j+1); //the middle key is unneeded
  828. --j;
  829. }
  830. }
  831. }
  832. if (PositionKeys.size()>1)
  833. {
  834. for(u32 j=0;j<PositionKeys.size()-1;++j)
  835. {
  836. if (PositionKeys[j].frame >= PositionKeys[j+1].frame) //bad frame, unneed and may cause problems
  837. {
  838. PositionKeys.erase(j+1);
  839. --j;
  840. }
  841. }
  842. }
  843. if (ScaleKeys.size()>2)
  844. {
  845. for(u32 j=0;j<ScaleKeys.size()-2;++j)
  846. {
  847. if (ScaleKeys[j].scale == ScaleKeys[j+1].scale && ScaleKeys[j+1].scale == ScaleKeys[j+2].scale)
  848. {
  849. ScaleKeys.erase(j+1); //the middle key is unneeded
  850. --j;
  851. }
  852. }
  853. }
  854. if (ScaleKeys.size()>1)
  855. {
  856. for(u32 j=0;j<ScaleKeys.size()-1;++j)
  857. {
  858. if (ScaleKeys[j].frame >= ScaleKeys[j+1].frame) //bad frame, unneed and may cause problems
  859. {
  860. ScaleKeys.erase(j+1);
  861. --j;
  862. }
  863. }
  864. }
  865. if (RotationKeys.size()>2)
  866. {
  867. for(u32 j=0;j<RotationKeys.size()-2;++j)
  868. {
  869. if (RotationKeys[j].rotation == RotationKeys[j+1].rotation && RotationKeys[j+1].rotation == RotationKeys[j+2].rotation)
  870. {
  871. RotationKeys.erase(j+1); //the middle key is unneeded
  872. --j;
  873. }
  874. }
  875. }
  876. if (RotationKeys.size()>1)
  877. {
  878. for(u32 j=0;j<RotationKeys.size()-1;++j)
  879. {
  880. if (RotationKeys[j].frame >= RotationKeys[j+1].frame) //bad frame, unneed and may cause problems
  881. {
  882. RotationKeys.erase(j+1);
  883. --j;
  884. }
  885. }
  886. }
  887. //Fill empty keyframe areas
  888. if (PositionKeys.size())
  889. {
  890. SPositionKey *Key;
  891. Key=&PositionKeys[0];//getFirst
  892. if (Key->frame!=0)
  893. {
  894. PositionKeys.push_front(*Key);
  895. Key=&PositionKeys[0];//getFirst
  896. Key->frame=0;
  897. }
  898. Key=&PositionKeys.getLast();
  899. if (Key->frame!=AnimationFrames)
  900. {
  901. PositionKeys.push_back(*Key);
  902. Key=&PositionKeys.getLast();
  903. Key->frame=AnimationFrames;
  904. }
  905. }
  906. if (ScaleKeys.size())
  907. {
  908. SScaleKey *Key;
  909. Key=&ScaleKeys[0];//getFirst
  910. if (Key->frame!=0)
  911. {
  912. ScaleKeys.push_front(*Key);
  913. Key=&ScaleKeys[0];//getFirst
  914. Key->frame=0;
  915. }
  916. Key=&ScaleKeys.getLast();
  917. if (Key->frame!=AnimationFrames)
  918. {
  919. ScaleKeys.push_back(*Key);
  920. Key=&ScaleKeys.getLast();
  921. Key->frame=AnimationFrames;
  922. }
  923. }
  924. if (RotationKeys.size())
  925. {
  926. SRotationKey *Key;
  927. Key=&RotationKeys[0];//getFirst
  928. if (Key->frame!=0)
  929. {
  930. RotationKeys.push_front(*Key);
  931. Key=&RotationKeys[0];//getFirst
  932. Key->frame=0;
  933. }
  934. Key=&RotationKeys.getLast();
  935. if (Key->frame!=AnimationFrames)
  936. {
  937. RotationKeys.push_back(*Key);
  938. Key=&RotationKeys.getLast();
  939. Key->frame=AnimationFrames;
  940. }
  941. }
  942. }
  943. }
  944. //Needed for animation and skinning...
  945. calculateGlobalMatrices(0,0);
  946. //animateMesh(0, 1);
  947. //buildAllLocalAnimatedMatrices();
  948. //buildAllGlobalAnimatedMatrices();
  949. //rigid animation for non animated meshes
  950. for (i=0; i<AllJoints.size(); ++i)
  951. {
  952. for (u32 j=0; j<AllJoints[i]->AttachedMeshes.size(); ++j)
  953. {
  954. SSkinMeshBuffer* Buffer=(*SkinningBuffers)[ AllJoints[i]->AttachedMeshes[j] ];
  955. Buffer->Transformation=AllJoints[i]->GlobalAnimatedMatrix;
  956. }
  957. }
  958. //calculate bounding box
  959. if (LocalBuffers.empty())
  960. BoundingBox.reset(0,0,0);
  961. else
  962. {
  963. irr::core::aabbox3df bb(LocalBuffers[0]->BoundingBox);
  964. LocalBuffers[0]->Transformation.transformBoxEx(bb);
  965. BoundingBox.reset(bb);
  966. for (u32 j=1; j<LocalBuffers.size(); ++j)
  967. {
  968. bb = LocalBuffers[j]->BoundingBox;
  969. LocalBuffers[j]->Transformation.transformBoxEx(bb);
  970. BoundingBox.addInternalBox(bb);
  971. }
  972. }
  973. }
  974. void CSkinnedMesh::updateBoundingBox(void)
  975. {
  976. if(HardwareSkinning || !SkinningBuffers)
  977. return;
  978. core::array<SSkinMeshBuffer*> & buffer = *SkinningBuffers;
  979. BoundingBox.reset(0,0,0);
  980. if (!buffer.empty())
  981. {
  982. for (u32 j=0; j<buffer.size(); ++j)
  983. {
  984. buffer[j]->recalculateBoundingBox();
  985. core::aabbox3df bb = buffer[j]->BoundingBox;
  986. buffer[j]->Transformation.transformBoxEx(bb);
  987. BoundingBox.addInternalBox(bb);
  988. }
  989. }
  990. }
  991. scene::SSkinMeshBuffer *CSkinnedMesh::addMeshBuffer()
  992. {
  993. scene::SSkinMeshBuffer *buffer=new scene::SSkinMeshBuffer();
  994. LocalBuffers.push_back(buffer);
  995. return buffer;
  996. }
  997. CSkinnedMesh::SJoint *CSkinnedMesh::addJoint(SJoint *parent)
  998. {
  999. SJoint *joint=new SJoint;
  1000. AllJoints.push_back(joint);
  1001. if (!parent)
  1002. {
  1003. //Add root joints to array in finalize()
  1004. }
  1005. else
  1006. {
  1007. //Set parent (Be careful of the mesh loader also setting the parent)
  1008. parent->Children.push_back(joint);
  1009. }
  1010. return joint;
  1011. }
  1012. CSkinnedMesh::SPositionKey *CSkinnedMesh::addPositionKey(SJoint *joint)
  1013. {
  1014. if (!joint)
  1015. return 0;
  1016. joint->PositionKeys.push_back(SPositionKey());
  1017. return &joint->PositionKeys.getLast();
  1018. }
  1019. CSkinnedMesh::SScaleKey *CSkinnedMesh::addScaleKey(SJoint *joint)
  1020. {
  1021. if (!joint)
  1022. return 0;
  1023. joint->ScaleKeys.push_back(SScaleKey());
  1024. return &joint->ScaleKeys.getLast();
  1025. }
  1026. CSkinnedMesh::SRotationKey *CSkinnedMesh::addRotationKey(SJoint *joint)
  1027. {
  1028. if (!joint)
  1029. return 0;
  1030. joint->RotationKeys.push_back(SRotationKey());
  1031. return &joint->RotationKeys.getLast();
  1032. }
  1033. CSkinnedMesh::SWeight *CSkinnedMesh::addWeight(SJoint *joint)
  1034. {
  1035. if (!joint)
  1036. return 0;
  1037. joint->Weights.push_back(SWeight());
  1038. return &joint->Weights.getLast();
  1039. }
  1040. bool CSkinnedMesh::isStatic()
  1041. {
  1042. return !HasAnimation;
  1043. }
  1044. void CSkinnedMesh::normalizeWeights()
  1045. {
  1046. // note: unsure if weights ids are going to be used.
  1047. // Normalise the weights on bones....
  1048. u32 i,j;
  1049. core::array< core::array<f32> > verticesTotalWeight;
  1050. verticesTotalWeight.reallocate(LocalBuffers.size());
  1051. for (i=0; i<LocalBuffers.size(); ++i)
  1052. {
  1053. verticesTotalWeight.push_back(core::array<f32>());
  1054. verticesTotalWeight[i].set_used(LocalBuffers[i]->getVertexCount());
  1055. }
  1056. for (i=0; i<verticesTotalWeight.size(); ++i)
  1057. for (j=0; j<verticesTotalWeight[i].size(); ++j)
  1058. verticesTotalWeight[i][j] = 0;
  1059. for (i=0; i<AllJoints.size(); ++i)
  1060. {
  1061. SJoint *joint=AllJoints[i];
  1062. for (j=0; j<joint->Weights.size(); ++j)
  1063. {
  1064. if (joint->Weights[j].strength<=0)//Check for invalid weights
  1065. {
  1066. joint->Weights.erase(j);
  1067. --j;
  1068. }
  1069. else
  1070. {
  1071. verticesTotalWeight[joint->Weights[j].buffer_id] [joint->Weights[j].vertex_id] += joint->Weights[j].strength;
  1072. }
  1073. }
  1074. }
  1075. for (i=0; i<AllJoints.size(); ++i)
  1076. {
  1077. SJoint *joint=AllJoints[i];
  1078. for (j=0; j< joint->Weights.size(); ++j)
  1079. {
  1080. const f32 total = verticesTotalWeight[joint->Weights[j].buffer_id] [joint->Weights[j].vertex_id];
  1081. if (total != 0 && total != 1)
  1082. joint->Weights[j].strength /= total;
  1083. }
  1084. }
  1085. }
  1086. void CSkinnedMesh::recoverJointsFromMesh(core::array<IBoneSceneNode*> &jointChildSceneNodes)
  1087. {
  1088. for (u32 i=0; i<AllJoints.size(); ++i)
  1089. {
  1090. IBoneSceneNode* node=jointChildSceneNodes[i];
  1091. SJoint *joint=AllJoints[i];
  1092. node->setPosition(joint->LocalAnimatedMatrix.getTranslation());
  1093. node->setRotation(joint->LocalAnimatedMatrix.getRotationDegrees());
  1094. node->setScale(joint->LocalAnimatedMatrix.getScale());
  1095. node->positionHint=joint->positionHint;
  1096. node->scaleHint=joint->scaleHint;
  1097. node->rotationHint=joint->rotationHint;
  1098. node->updateAbsolutePosition();
  1099. }
  1100. }
  1101. void CSkinnedMesh::transferJointsToMesh(const core::array<IBoneSceneNode*> &jointChildSceneNodes)
  1102. {
  1103. for (u32 i=0; i<AllJoints.size(); ++i)
  1104. {
  1105. const IBoneSceneNode* const node=jointChildSceneNodes[i];
  1106. SJoint *joint=AllJoints[i];
  1107. joint->LocalAnimatedMatrix.setRotationDegrees(node->getRotation());
  1108. joint->LocalAnimatedMatrix.setTranslation(node->getPosition());
  1109. joint->LocalAnimatedMatrix *= core::matrix4().setScale(node->getScale());
  1110. joint->positionHint=node->positionHint;
  1111. joint->scaleHint=node->scaleHint;
  1112. joint->rotationHint=node->rotationHint;
  1113. joint->GlobalSkinningSpace=(node->getSkinningSpace()==EBSS_GLOBAL);
  1114. }
  1115. // Make sure we recalc the next frame
  1116. LastAnimatedFrame=-1;
  1117. SkinnedLastFrame=false;
  1118. }
  1119. void CSkinnedMesh::transferOnlyJointsHintsToMesh(const core::array<IBoneSceneNode*> &jointChildSceneNodes)
  1120. {
  1121. for (u32 i=0; i<AllJoints.size(); ++i)
  1122. {
  1123. const IBoneSceneNode* const node=jointChildSceneNodes[i];
  1124. SJoint *joint=AllJoints[i];
  1125. joint->positionHint=node->positionHint;
  1126. joint->scaleHint=node->scaleHint;
  1127. joint->rotationHint=node->rotationHint;
  1128. }
  1129. SkinnedLastFrame=false;
  1130. }
  1131. void CSkinnedMesh::addJoints(core::array<IBoneSceneNode*> &jointChildSceneNodes,
  1132. IAnimatedMeshSceneNode* node, ISceneManager* smgr)
  1133. {
  1134. //Create new joints
  1135. for (u32 i=0; i<AllJoints.size(); ++i)
  1136. {
  1137. jointChildSceneNodes.push_back(new CBoneSceneNode(0, smgr, 0, i, AllJoints[i]->Name.c_str()));
  1138. }
  1139. //Match up parents
  1140. for (u32 i=0; i<jointChildSceneNodes.size(); ++i)
  1141. {
  1142. const SJoint* const joint=AllJoints[i]; //should be fine
  1143. s32 parentID=-1;
  1144. for (u32 j=0;(parentID==-1)&&(j<AllJoints.size());++j)
  1145. {
  1146. if (i!=j)
  1147. {
  1148. const SJoint* const parentTest=AllJoints[j];
  1149. for (u32 n=0; n<parentTest->Children.size(); ++n)
  1150. {
  1151. if (parentTest->Children[n]==joint)
  1152. {
  1153. parentID=j;
  1154. break;
  1155. }
  1156. }
  1157. }
  1158. }
  1159. IBoneSceneNode* bone=jointChildSceneNodes[i];
  1160. if (parentID!=-1)
  1161. bone->setParent(jointChildSceneNodes[parentID]);
  1162. else
  1163. bone->setParent(node);
  1164. bone->drop();
  1165. }
  1166. SkinnedLastFrame=false;
  1167. }
  1168. bool CSkinnedMesh::sortJointInfluenceFunc(const JointInfluence& a,
  1169. const JointInfluence& b)
  1170. {
  1171. return a.weight > b.weight;
  1172. }
  1173. void CSkinnedMesh::convertForSkinning()
  1174. {
  1175. if (HardwareSkinning) return;
  1176. setHardwareSkinning(true);
  1177. WeightInfluence wi;
  1178. for (u32 b = 0; b < LocalBuffers.size(); b++)
  1179. {
  1180. if (LocalBuffers[b])
  1181. LocalBuffers[b]->convertForSkinning();
  1182. wi.push_back(core::array<core::array<JointInfluence> > ());
  1183. for (u32 i = 0; i < LocalBuffers[b]->getVertexCount(); i++)
  1184. wi[b].push_back(core::array<JointInfluence>());
  1185. }
  1186. size_t idx = 0;
  1187. for (u32 i = 0; i < RootJoints.size(); i++)
  1188. computeWeightInfluence(RootJoints[i], idx, wi);
  1189. for (u32 b = 0; b < LocalBuffers.size(); b++)
  1190. {
  1191. if (LocalBuffers[b])
  1192. {
  1193. const u32 total = wi[b].size();
  1194. _IRR_DEBUG_BREAK_IF(LocalBuffers[b]->getVertexCount() != total);
  1195. for (u32 i = 0; i < total; i++)
  1196. {
  1197. core::array<JointInfluence> this_influence;
  1198. core::array<JointInfluence> reported_weight = wi[b][i];
  1199. reported_weight.sort(sortJointInfluenceFunc);
  1200. float remaining_weight = 1.0f;
  1201. for (u32 j = 0; j < 4; j++)
  1202. {
  1203. JointInfluence influence;
  1204. if (reported_weight.size() > j)
  1205. influence = reported_weight[j];
  1206. else
  1207. {
  1208. influence.joint_idx = -100000;
  1209. influence.weight = remaining_weight;
  1210. }
  1211. remaining_weight -= influence.weight;
  1212. this_influence.push_back(influence);
  1213. }
  1214. LocalBuffers[b]->Vertices_SkinnedMesh[i].m_joint_idx1 = this_influence[0].joint_idx;
  1215. LocalBuffers[b]->Vertices_SkinnedMesh[i].m_joint_idx2 = this_influence[1].joint_idx;
  1216. LocalBuffers[b]->Vertices_SkinnedMesh[i].m_joint_idx3 = this_influence[2].joint_idx;
  1217. LocalBuffers[b]->Vertices_SkinnedMesh[i].m_joint_idx4 = this_influence[3].joint_idx;
  1218. LocalBuffers[b]->Vertices_SkinnedMesh[i].m_weight1 = this_influence[0].weight;
  1219. LocalBuffers[b]->Vertices_SkinnedMesh[i].m_weight2 = this_influence[1].weight;
  1220. LocalBuffers[b]->Vertices_SkinnedMesh[i].m_weight3 = this_influence[2].weight;
  1221. LocalBuffers[b]->Vertices_SkinnedMesh[i].m_weight4 = this_influence[3].weight;
  1222. }
  1223. }
  1224. }
  1225. SkinnedLastFrame = false;
  1226. skinMesh();
  1227. m_total_joints = m_current_joint;
  1228. }
  1229. void CSkinnedMesh::computeWeightInfluence(SJoint *joint, size_t &index, WeightInfluence& wi)
  1230. {
  1231. if (!joint->Weights.empty())
  1232. {
  1233. for (u32 i = 0; i < joint->Weights.size(); i++)
  1234. {
  1235. SWeight& weight = joint->Weights[i];
  1236. JointInfluence tmp;
  1237. tmp.joint_idx = index;
  1238. tmp.weight = weight.strength;
  1239. wi[weight.buffer_id][weight.vertex_id].push_back(tmp);
  1240. }
  1241. index++;
  1242. }
  1243. for (u32 j = 0; j < joint->Children.size(); j++)
  1244. computeWeightInfluence(joint->Children[j], index, wi);
  1245. }
  1246. void CSkinnedMesh::convertMeshToTangents(bool(*predicate)(IMeshBuffer*))
  1247. {
  1248. bool recalculate_animation = false;
  1249. toStaticPose();
  1250. for (u32 b = 0; b < LocalBuffers.size(); b++)
  1251. {
  1252. bool recalculate_joints = false;
  1253. core::map<u32, u32> vert_loc_map;
  1254. SSkinMeshBuffer* ssmb = LocalBuffers[b];
  1255. if (ssmb)
  1256. {
  1257. if (!predicate(ssmb)) continue;
  1258. recalculate_joints = true;
  1259. recalculate_animation = true;
  1260. core::map<video::S3DVertexTangents, u32> vert_map;
  1261. core::array<u16> tmp_indices;
  1262. for (u32 i = 0; i < ssmb->Indices.size(); i++)
  1263. {
  1264. u32 vert_location = 0;
  1265. const u32 cur_ver_loc = ssmb->Indices[i];
  1266. const video::S3DVertex& v_old = ssmb->Vertices_Standard[cur_ver_loc];
  1267. video::S3DVertexTangents v(v_old.Pos, v_old.Normal, v_old.Color, v_old.TCoords);
  1268. core::map<video::S3DVertexTangents, u32>::Node *n = vert_map.find(v);
  1269. if (n)
  1270. {
  1271. vert_location = n->getValue();
  1272. }
  1273. else
  1274. {
  1275. vert_location = ssmb->Vertices_Tangents.size();
  1276. ssmb->Vertices_Tangents.push_back(v);
  1277. vert_map.insert(v, vert_location);
  1278. }
  1279. vert_loc_map[cur_ver_loc] = vert_location;
  1280. tmp_indices.push_back(vert_location);
  1281. }
  1282. const s32 index_count = tmp_indices.size();
  1283. u16* idx = tmp_indices.pointer();
  1284. video::S3DVertexTangents* v = ssmb->Vertices_Tangents.pointer();
  1285. core::vector3df local_normal;
  1286. for (s32 i = 0; i < index_count; i += 3)
  1287. {
  1288. calculateTangents(
  1289. local_normal,
  1290. v[idx[i+0]].Tangent,
  1291. v[idx[i+0]].Binormal,
  1292. v[idx[i+0]].Pos,
  1293. v[idx[i+1]].Pos,
  1294. v[idx[i+2]].Pos,
  1295. v[idx[i+0]].TCoords,
  1296. v[idx[i+1]].TCoords,
  1297. v[idx[i+2]].TCoords);
  1298. calculateTangents(
  1299. local_normal,
  1300. v[idx[i+1]].Tangent,
  1301. v[idx[i+1]].Binormal,
  1302. v[idx[i+1]].Pos,
  1303. v[idx[i+2]].Pos,
  1304. v[idx[i+0]].Pos,
  1305. v[idx[i+1]].TCoords,
  1306. v[idx[i+2]].TCoords,
  1307. v[idx[i+0]].TCoords);
  1308. calculateTangents(
  1309. local_normal,
  1310. v[idx[i+2]].Tangent,
  1311. v[idx[i+2]].Binormal,
  1312. v[idx[i+2]].Pos,
  1313. v[idx[i+0]].Pos,
  1314. v[idx[i+1]].Pos,
  1315. v[idx[i+2]].TCoords,
  1316. v[idx[i+0]].TCoords,
  1317. v[idx[i+1]].TCoords);
  1318. }
  1319. ssmb->Indices = tmp_indices;
  1320. ssmb->Vertices_Standard.clear();
  1321. ssmb->VertexType = video::EVT_TANGENTS;
  1322. }
  1323. if (recalculate_joints)
  1324. {
  1325. Vertices_Moved[b].set_used(ssmb->getVertexCount());
  1326. for (u32 i = 0; i < AllJoints.size(); i++)
  1327. {
  1328. SJoint *joint = AllJoints[i];
  1329. for (u32 j = 0; j <joint->Weights.size(); j++)
  1330. {
  1331. if (joint->Weights[j].buffer_id == b)
  1332. {
  1333. core::map<u32, u32>::Node *n =
  1334. vert_loc_map.find(joint->Weights[j].vertex_id);
  1335. if (n)
  1336. {
  1337. joint->Weights[j].vertex_id = n->getValue();
  1338. }
  1339. }
  1340. }
  1341. }
  1342. }
  1343. }
  1344. if (recalculate_animation)
  1345. {
  1346. PreparedForSkinning = false;
  1347. checkForAnimation();
  1348. }
  1349. }
  1350. void CSkinnedMesh::calculateTangents(
  1351. core::vector3df& normal,
  1352. core::vector3df& tangent,
  1353. core::vector3df& binormal,
  1354. core::vector3df& vt1, core::vector3df& vt2, core::vector3df& vt3, // vertices
  1355. core::vector2df& tc1, core::vector2df& tc2, core::vector2df& tc3) // texture coords
  1356. {
  1357. core::vector3df v1 = vt1 - vt2;
  1358. core::vector3df v2 = vt3 - vt1;
  1359. normal = v2.crossProduct(v1);
  1360. normal.normalize();
  1361. // binormal
  1362. f32 deltaX1 = tc1.X - tc2.X;
  1363. f32 deltaX2 = tc3.X - tc1.X;
  1364. binormal = (v1 * deltaX2) - (v2 * deltaX1);
  1365. binormal.normalize();
  1366. // tangent
  1367. f32 deltaY1 = tc1.Y - tc2.Y;
  1368. f32 deltaY2 = tc3.Y - tc1.Y;
  1369. tangent = (v1 * deltaY2) - (v2 * deltaY1);
  1370. tangent.normalize();
  1371. // adjust
  1372. core::vector3df txb = tangent.crossProduct(binormal);
  1373. if (txb.dotProduct(normal) < 0.0f)
  1374. {
  1375. tangent *= -1.0f;
  1376. binormal *= -1.0f;
  1377. }
  1378. }
  1379. } // end namespace scene
  1380. } // end namespace irr
  1381. #endif // _IRR_COMPILE_WITH_SKINNED_MESH_SUPPORT_