llik.cpp 80 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984
  1. /**
  2. * @file llik.cpp
  3. * @brief Implementation of LLIK::Solver class and related helpers.
  4. *
  5. * $LicenseInfo:firstyear=2021&license=viewergpl$
  6. *
  7. * Copyright (c) 2021, Linden Research, Inc.
  8. *
  9. * Second Life Viewer Source Code
  10. * The source code in this file ("Source Code") is provided by Linden Lab
  11. * to you under the terms of the GNU General Public License, version 2.0
  12. * ("GPL"), unless you have obtained a separate licensing agreement
  13. * ("Other License"), formally executed by you and Linden Lab. Terms of
  14. * the GPL can be found in doc/GPL-license.txt in this distribution, or
  15. * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
  16. *
  17. * There are special exceptions to the terms and conditions of the GPL as
  18. * it is applied to this Source Code. View the full text of the exception
  19. * in the file doc/FLOSS-exception.txt in this software distribution, or
  20. * online at
  21. * http://secondlifegrid.net/programs/open_source/licensing/flossexception
  22. *
  23. * By copying, modifying or distributing this software, you acknowledge
  24. * that you have read and understood your obligations described above,
  25. * and agree to abide by those obligations.
  26. *
  27. * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
  28. * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
  29. * COMPLETENESS OR PERFORMANCE.
  30. * $/LicenseInfo$
  31. */
  32. #include <algorithm>
  33. #include <sstream>
  34. #include "linden_common.h"
  35. #include "llik.h"
  36. #include "lldir.h"
  37. #include "lljoint.h"
  38. #include "llsdserialize.h"
  39. #include "hbxxh.h"
  40. static const std::string NULL_CONSTRAINT_NAME("NULL_CONSTRAINT");
  41. static const std::string SIMPLE_CONE_NAME("SIMPLE_CONE");
  42. static const std::string TWIST_LIMITED_CONE_NAME("TWIST_LIMITED_CONE");
  43. static const std::string ELBOW_NAME("ELBOW");
  44. static const std::string KNEE_NAME("KNEE");
  45. static const std::string ACUTE_ELLIPSOIDAL_NAME("ACUTE_ELLIPSOIDAL_CONE");
  46. static const std::string DOUBLE_LIMITED_HINGE_NAME("DOUBLE_LIMITED_HINGE");
  47. static const std::string UNKNOWN_CONSTRAINT_NAME("UNKNOWN_CONSTRAINT");
  48. namespace LLIK
  49. {
  50. // Utility function for truncating angle to range: [0, F_TWO_PI[
  51. static F32 remove_multiples_of_two_pi(F32 angle)
  52. {
  53. return angle - F_TWO_PI * (S32)(angle / F_TWO_PI);
  54. }
  55. // Utility function for clamping angle limits in range [-PI, PI]. Note:
  56. // arguments are passed by reference and modified as side-effect
  57. static void compute_angle_limits(F32& min_angle, F32& max_angle)
  58. {
  59. max_angle = remove_multiples_of_two_pi(max_angle);
  60. if (max_angle > F_PI)
  61. {
  62. max_angle -= F_TWO_PI;
  63. }
  64. min_angle = remove_multiples_of_two_pi(min_angle);
  65. if (min_angle > F_PI)
  66. {
  67. min_angle -= F_TWO_PI;
  68. }
  69. if (min_angle > max_angle)
  70. {
  71. F32 temp = min_angle;
  72. min_angle = max_angle;
  73. max_angle = temp;
  74. }
  75. }
  76. // Utility function for clamping angle between two limits. Consider angle
  77. // limits: min_angle and max_angle with axis out of the page. There exists an
  78. // "invalid bisector" angle which splits the invalid zone between the that
  79. // which is closest to mMinBend or mMaxBend.
  80. //
  81. // max_angle
  82. // `
  83. // `
  84. // `
  85. // (o)--------> 0
  86. // .-' `
  87. // .-' `
  88. // .-' `
  89. // invalid_bisector min_angle
  90. //
  91. static F32 compute_clamped_angle(F32 angle, F32 min_angle, F32 max_angle)
  92. {
  93. F32 invalid_bisector = max_angle +
  94. 0.5f * (F_TWO_PI - (max_angle - min_angle));
  95. if ((angle > max_angle && angle < invalid_bisector) ||
  96. angle < invalid_bisector - F_TWO_PI)
  97. {
  98. return max_angle;
  99. }
  100. return min_angle;
  101. }
  102. ///////////////////////////////////////////////////////////////////////////////
  103. // LLIK::Constraint class
  104. ///////////////////////////////////////////////////////////////////////////////
  105. Constraint::Constraint(ConstraintType type, const LLSD& parameters)
  106. : mType(type)
  107. {
  108. mForward = LLVector3(parameters["forward_axis"]);
  109. mForward.normalize();
  110. }
  111. //virtual
  112. LLSD Constraint::asLLSD() const
  113. {
  114. LLSD data = LLSD::emptyMap();
  115. data["forward_axis"] = mForward.getValue();
  116. data["type"] = typeToName();
  117. return data;
  118. }
  119. //virtual
  120. U64 Constraint::getHash() const
  121. {
  122. return HBXXH64::digest((const void*)this, sizeof(Constraint));
  123. }
  124. bool Constraint::enforce(Joint& joint) const
  125. {
  126. const LLQuaternion& local_rot = joint.getLocalRot();
  127. LLQuaternion adjusted_loc_rot = computeAdjustedLocalRot(local_rot);
  128. if (!LLQuaternion::almost_equal(adjusted_loc_rot, local_rot))
  129. {
  130. joint.setLocalRot(adjusted_loc_rot);
  131. return true;
  132. }
  133. return false;
  134. }
  135. LLQuaternion Constraint::minimizeTwist(const LLQuaternion& j_loc_rot) const
  136. {
  137. // Default behavior of minimizeTwist() is to compute the shortest rotation
  138. // that produces the same swing.
  139. LLVector3 joint_forward = mForward * j_loc_rot;
  140. LLVector3 swing_axis = mForward % joint_forward;
  141. LLQuaternion new_local_rot = LLQuaternion::DEFAULT;
  142. constexpr F32 MIN_AXIS_LENGTH = 1.0e-5f;
  143. if (swing_axis.length() > MIN_AXIS_LENGTH)
  144. {
  145. F32 swing_angle = acosf(mForward * joint_forward);
  146. new_local_rot.setAngleAxis(swing_angle, swing_axis);
  147. }
  148. return new_local_rot;
  149. }
  150. const std::string& Constraint::typeToName() const
  151. {
  152. switch (mType)
  153. {
  154. case Constraint::NULL_CONSTRAINT:
  155. return NULL_CONSTRAINT_NAME;
  156. case Constraint::SIMPLE_CONE_CONSTRAINT:
  157. return SIMPLE_CONE_NAME;
  158. case Constraint::TWIST_LIMITED_CONE_CONSTRAINT:
  159. return TWIST_LIMITED_CONE_NAME;
  160. case Constraint::ELBOW_CONSTRAINT:
  161. return ELBOW_NAME;
  162. case Constraint::KNEE_CONSTRAINT:
  163. return KNEE_NAME;
  164. case Constraint::ACUTE_ELLIPSOIDAL_CONE_CONSTRAINT:
  165. return ACUTE_ELLIPSOIDAL_NAME;
  166. case Constraint::DOUBLE_LIMITED_HINGE_CONSTRAINT:
  167. return DOUBLE_LIMITED_HINGE_NAME;
  168. default:
  169. return UNKNOWN_CONSTRAINT_NAME;
  170. }
  171. }
  172. ///////////////////////////////////////////////////////////////////////////////
  173. // LLIK::SimpleCone class
  174. ///////////////////////////////////////////////////////////////////////////////
  175. SimpleCone::SimpleCone(const LLVector3& forward, F32 max_angle)
  176. {
  177. mType = SIMPLE_CONE_CONSTRAINT;
  178. mForward = forward;
  179. mForward.normalize();
  180. mMaxAngle = fabsf(max_angle);
  181. mCosConeAngle = cosf(mMaxAngle);
  182. mSinConeAngle = sinf(mMaxAngle);
  183. }
  184. SimpleCone::SimpleCone(const LLSD& parameters)
  185. : Constraint(Constraint::SIMPLE_CONE_CONSTRAINT, parameters)
  186. {
  187. mMaxAngle = fabsf(F32(parameters["max_angle"].asReal()) * DEG_TO_RAD);
  188. mCosConeAngle = cosf(mMaxAngle);
  189. mSinConeAngle = sinf(mMaxAngle);
  190. }
  191. //virtual
  192. LLSD SimpleCone::asLLSD() const
  193. {
  194. LLSD data = Constraint::asLLSD();
  195. data["max_angle"] = mMaxAngle * RAD_TO_DEG;
  196. return data;
  197. }
  198. //virtual
  199. U64 SimpleCone::getHash() const
  200. {
  201. return HBXXH64::digest((const void*)this, sizeof(SimpleCone));
  202. }
  203. LLQuaternion SimpleCone::computeAdjustedLocalRot(const LLQuaternion& j_loc_rot) const
  204. {
  205. LLVector3 joint_forward = mForward * j_loc_rot;
  206. F32 forward_component = joint_forward * mForward;
  207. if (forward_component < mCosConeAngle)
  208. {
  209. // The joint's version of mForward lies outside the cone, so we project
  210. // it onto the surface of the cone...
  211. // projection = (forward_part) + (orthogonal_part)
  212. LLVector3 perp = joint_forward - forward_component * mForward;
  213. perp.normalize();
  214. LLVector3 new_j_forw = mCosConeAngle * mForward + mSinConeAngle * perp;
  215. // ... then compute the adjusted rotation
  216. LLQuaternion adjustment;
  217. adjustment.shortestArc(joint_forward, new_j_forw);
  218. LLQuaternion adjusted_loc_rot = j_loc_rot * adjustment;
  219. adjusted_loc_rot.normalize();
  220. return adjusted_loc_rot;
  221. }
  222. return j_loc_rot;
  223. }
  224. ///////////////////////////////////////////////////////////////////////////////
  225. // LLIK::TwistLimitedCone class
  226. ///////////////////////////////////////////////////////////////////////////////
  227. TwistLimitedCone::TwistLimitedCone(const LLVector3& forward,
  228. F32 cone_angle, F32 min_twist,
  229. F32 max_twist)
  230. : mConeAngle(cone_angle)
  231. {
  232. mType = TWIST_LIMITED_CONE_CONSTRAINT;
  233. mForward = forward;
  234. mForward.normalize();
  235. mCosConeAngle = cosf(cone_angle);
  236. mSinConeAngle = sinf(cone_angle);
  237. mMinTwist = min_twist;
  238. mMaxTwist = max_twist;
  239. compute_angle_limits(mMinTwist, mMaxTwist);
  240. }
  241. TwistLimitedCone::TwistLimitedCone(const LLSD& parameters)
  242. : Constraint(Constraint::TWIST_LIMITED_CONE_CONSTRAINT, parameters)
  243. {
  244. mConeAngle = parameters["cone_angle"].asReal() * DEG_TO_RAD;
  245. mCosConeAngle = cosf(mConeAngle);
  246. mSinConeAngle = sinf(mConeAngle);
  247. mMinTwist = parameters["min_twist"].asReal() * DEG_TO_RAD;
  248. mMaxTwist = parameters["max_twist"].asReal() * DEG_TO_RAD;
  249. compute_angle_limits(mMinTwist, mMaxTwist);
  250. }
  251. //virtual
  252. LLSD TwistLimitedCone::asLLSD() const
  253. {
  254. LLSD data = Constraint::asLLSD();
  255. data["cone_angle"] = mConeAngle * RAD_TO_DEG;
  256. data["min_twist"] = mMinTwist * RAD_TO_DEG;
  257. data["max_twist"] = mMaxTwist * RAD_TO_DEG;
  258. return data;
  259. }
  260. //virtual
  261. U64 TwistLimitedCone::getHash() const
  262. {
  263. return HBXXH64::digest((const void*)this, sizeof(TwistLimitedCone));
  264. }
  265. LLQuaternion TwistLimitedCone::computeAdjustedLocalRot(const LLQuaternion& j_loc_rot) const
  266. {
  267. LLVector3 joint_forward = mForward * j_loc_rot;
  268. LLQuaternion adjusted_loc_rot = j_loc_rot;
  269. F32 forward_component = joint_forward * mForward;
  270. if (forward_component < mCosConeAngle)
  271. {
  272. // The joint's version of mForward lies outside the cone, so we project
  273. // it onto the surface of the cone...
  274. // projection = forward_part + orthogonal_part
  275. LLVector3 perp = joint_forward - forward_component * mForward;
  276. perp.normalize();
  277. LLVector3 new_j_forw = mCosConeAngle * mForward + mSinConeAngle * perp;
  278. // ... then compute the adjusted rotation
  279. LLQuaternion adjustment;
  280. adjustment.shortestArc(joint_forward, new_j_forw);
  281. adjusted_loc_rot = j_loc_rot * adjustment;
  282. }
  283. // Rotate mForward by adjusted_loc_rot
  284. joint_forward = mForward * adjusted_loc_rot;
  285. forward_component = joint_forward * mForward;
  286. // Compute two axes perpendicular to joint_forward: perp_x and perp_y
  287. LLVector3 perp_x = mForward % joint_forward;
  288. F32 perp_length = perp_x.length();
  289. constexpr F32 MIN_PERP_LENGTH = 1.0e-3f;
  290. if (perp_length < MIN_PERP_LENGTH)
  291. {
  292. perp_x = LLVector3::y_axis % mForward;
  293. perp_length = perp_x.length();
  294. if (perp_length < MIN_PERP_LENGTH)
  295. {
  296. perp_x = mForward % LLVector3::x_axis;
  297. }
  298. }
  299. perp_x.normalize();
  300. LLVector3 perp_y = joint_forward % perp_x;
  301. // The components of joint_perp on each direction allow us to compute twist
  302. // angle
  303. LLVector3 joint_perp = perp_x * adjusted_loc_rot;
  304. F32 twist = atan2f(joint_perp * perp_y, joint_perp * perp_x);
  305. // Clamp twist within bounds
  306. if (twist > mMaxTwist || twist < mMinTwist)
  307. {
  308. twist = compute_clamped_angle(twist, mMinTwist, mMaxTwist);
  309. joint_perp -= (joint_perp * joint_forward) * joint_forward;
  310. LLVector3 new_joint_perp = cosf(twist) * perp_x + sinf(twist) * perp_y;
  311. LLQuaternion adjustment;
  312. adjustment.shortestArc(joint_perp, new_joint_perp);
  313. adjusted_loc_rot = adjusted_loc_rot * adjustment;
  314. }
  315. adjusted_loc_rot.normalize();
  316. return adjusted_loc_rot;
  317. }
  318. LLQuaternion TwistLimitedCone::minimizeTwist(const LLQuaternion& j_loc_rot) const
  319. {
  320. // Compute the swing and combine with default twist
  321. // which is the midpoint of the twist range.
  322. LLQuaternion mid_twist;
  323. mid_twist.setAngleAxis(0.5f * (mMinTwist + mMaxTwist), mForward);
  324. // j_loc_rot = mid_twist * swing
  325. LLQuaternion new_local_rot = mid_twist;
  326. LLVector3 joint_forward = mForward * j_loc_rot;
  327. LLVector3 swing_axis = mForward % joint_forward;
  328. constexpr F32 MIN_SWING_AXIS_LENGTH = 1.0e-3f;
  329. if (swing_axis.length() > MIN_SWING_AXIS_LENGTH)
  330. {
  331. LLQuaternion swing;
  332. F32 swing_angle = acosf(mForward * joint_forward);
  333. swing.setAngleAxis(swing_angle, swing_axis);
  334. new_local_rot = mid_twist * swing;
  335. }
  336. return new_local_rot;
  337. }
  338. ///////////////////////////////////////////////////////////////////////////////
  339. // LLIK::ElbowConstraint class
  340. ///////////////////////////////////////////////////////////////////////////////
  341. ElbowConstraint::ElbowConstraint(const LLVector3& forward_axis,
  342. const LLVector3& pivot_axis,
  343. F32 min_bend, F32 max_bend,
  344. F32 min_twist, F32 max_twist)
  345. {
  346. mType = ELBOW_CONSTRAINT;
  347. mForward = forward_axis;
  348. mForward.normalize();
  349. mPivotAxis = mForward % (pivot_axis % mForward);
  350. mPivotAxis.normalize();
  351. mLeft = mPivotAxis % mForward;
  352. mMinBend = min_bend;
  353. mMaxBend = max_bend;
  354. compute_angle_limits(mMinBend, mMaxBend);
  355. mMinTwist = min_twist;
  356. mMaxTwist = max_twist;
  357. compute_angle_limits(mMinTwist, mMaxTwist);
  358. }
  359. ElbowConstraint::ElbowConstraint(const LLSD& parameters)
  360. : Constraint(Constraint::ELBOW_CONSTRAINT, parameters)
  361. {
  362. mPivotAxis = mForward % (LLVector3(parameters["pivot_axis"]) % mForward);
  363. mPivotAxis.normalize();
  364. mLeft = mPivotAxis % mForward;
  365. mMinBend = parameters["min_bend"].asReal() * DEG_TO_RAD;
  366. mMaxBend = parameters["max_bend"].asReal() * DEG_TO_RAD;
  367. compute_angle_limits(mMinBend, mMaxBend);
  368. mMinTwist = parameters["min_twist"].asReal() * DEG_TO_RAD;
  369. mMaxTwist = parameters["max_twist"].asReal() * DEG_TO_RAD;
  370. compute_angle_limits(mMinTwist, mMaxTwist);
  371. }
  372. //virtual
  373. LLSD ElbowConstraint::asLLSD() const
  374. {
  375. LLSD data = Constraint::asLLSD();
  376. data["pivot_axis"] = mPivotAxis.getValue();
  377. data["min_bend"] = mMinBend * RAD_TO_DEG;
  378. data["max_bend"] = mMaxBend * RAD_TO_DEG;
  379. data["min_twist"] = mMinTwist * RAD_TO_DEG;
  380. data["max_twist"] = mMaxTwist * RAD_TO_DEG;
  381. return data;
  382. }
  383. //virtual
  384. U64 ElbowConstraint::getHash() const
  385. {
  386. return HBXXH64::digest((const void*)this, sizeof(ElbowConstraint));
  387. }
  388. LLQuaternion ElbowConstraint::computeAdjustedLocalRot(const LLQuaternion& j_loc_rot) const
  389. {
  390. // Rotate mForward into joint-frame
  391. LLVector3 joint_forward = mForward * j_loc_rot;
  392. // Compute adjustment required to move joint_forward back into hinge plane
  393. LLVector3 proj_j_forw = joint_forward -
  394. (joint_forward * mPivotAxis) * mPivotAxis;
  395. LLQuaternion adjustment;
  396. adjustment.shortestArc(joint_forward, proj_j_forw);
  397. LLQuaternion adjusted_loc_rot = j_loc_rot * adjustment;
  398. // Measure twist
  399. LLVector3 twisted_pivot = mPivotAxis * adjusted_loc_rot;
  400. F32 cos_part = twisted_pivot * mPivotAxis;
  401. F32 sin_part = (mLeft * adjusted_loc_rot) * mPivotAxis;
  402. F32 twist = atan2f(sin_part, cos_part);
  403. LLVector3 new_j_forw = mForward * adjusted_loc_rot;
  404. if (twist < mMinTwist || twist > mMaxTwist)
  405. {
  406. // adjust twist
  407. twist = compute_clamped_angle(twist, mMinTwist, mMaxTwist);
  408. LLVector3 swung_left_axis = mPivotAxis % new_j_forw;
  409. LLVector3 new_twisted_pivot = cosf(twist) * mPivotAxis -
  410. sinf(twist) * swung_left_axis;
  411. adjustment.shortestArc(twisted_pivot, new_twisted_pivot);
  412. adjusted_loc_rot = adjusted_loc_rot * adjustment;
  413. new_j_forw = mForward * adjusted_loc_rot;
  414. }
  415. // Measure bend
  416. F32 bend = atan2f(new_j_forw * mLeft, new_j_forw * mForward);
  417. if (bend > mMaxBend || bend < mMinBend)
  418. {
  419. // Adjust bend
  420. bend = compute_clamped_angle(bend, mMinBend, mMaxBend);
  421. new_j_forw = cosf(bend) * mForward + sinf(bend) * mLeft;
  422. adjustment.shortestArc(joint_forward, new_j_forw);
  423. adjusted_loc_rot = adjusted_loc_rot * adjustment;
  424. }
  425. adjusted_loc_rot.normalize();
  426. return adjusted_loc_rot;
  427. }
  428. LLQuaternion ElbowConstraint::minimizeTwist(const LLQuaternion& j_loc_rot) const
  429. {
  430. // Assume all swing is really just bend about mPivotAxis and twist is
  431. // centered in the valid twist range. If bend_angle is outside the limits
  432. // then we check both +/- bend_angle and pick the one closest to the
  433. // allowed range. This comes down to a simple question: which is closer to
  434. // the midpoint of the bend range ?
  435. LLVector3 joint_forward = mForward * j_loc_rot;
  436. F32 fdot = joint_forward * mForward;
  437. LLVector3 perp_part = joint_forward - fdot * mForward;
  438. F32 bend_angle = atan2f(perp_part.length(), fdot);
  439. if (bend_angle < mMinBend || bend_angle > mMaxBend)
  440. {
  441. F32 alt_bend_angle = - bend_angle;
  442. F32 mid_bend = 0.5f * (mMinBend + mMaxBend);
  443. if (fabsf(alt_bend_angle - mid_bend) < fabsf(bend_angle - mid_bend))
  444. {
  445. bend_angle = alt_bend_angle;
  446. }
  447. }
  448. LLQuaternion bend;
  449. bend.setAngleAxis(bend_angle, mPivotAxis);
  450. LLQuaternion mid_twist;
  451. mid_twist.setAngleAxis(0.5f * (mMinTwist + mMaxTwist), mForward);
  452. return mid_twist * bend;
  453. }
  454. ///////////////////////////////////////////////////////////////////////////////
  455. // LLIK::KneeConstraint class
  456. ///////////////////////////////////////////////////////////////////////////////
  457. KneeConstraint::KneeConstraint(const LLVector3& forward_axis,
  458. const LLVector3& pivot_axis,
  459. F32 min_bend, F32 max_bend)
  460. {
  461. mType = KNEE_CONSTRAINT;
  462. mForward = forward_axis;
  463. mForward.normalize();
  464. mPivotAxis = mForward % (pivot_axis % mForward);
  465. mPivotAxis.normalize();
  466. mLeft = mPivotAxis % mForward;
  467. mMinBend = min_bend;
  468. mMaxBend = max_bend;
  469. compute_angle_limits(mMinBend, mMaxBend);
  470. }
  471. KneeConstraint::KneeConstraint(const LLSD& parameters)
  472. : Constraint(Constraint::KNEE_CONSTRAINT, parameters)
  473. {
  474. mPivotAxis = mForward % (LLVector3(parameters["pivot_axis"]) % mForward);
  475. mPivotAxis.normalize();
  476. mLeft = mPivotAxis % mForward;
  477. mMinBend = parameters["min_bend"].asReal() * DEG_TO_RAD;
  478. mMaxBend = parameters["max_bend"].asReal() * DEG_TO_RAD;
  479. compute_angle_limits(mMinBend, mMaxBend);
  480. }
  481. //virtual
  482. LLSD KneeConstraint::asLLSD() const
  483. {
  484. LLSD data = Constraint::asLLSD();
  485. data["pivot_axis"] = mPivotAxis.getValue();
  486. data["min_bend"] = mMinBend * RAD_TO_DEG;
  487. data["max_bend"] = mMaxBend * RAD_TO_DEG;
  488. return data;
  489. }
  490. //virtual
  491. U64 KneeConstraint::getHash() const
  492. {
  493. return HBXXH64::digest((const void*)this, sizeof(KneeConstraint));
  494. }
  495. LLQuaternion KneeConstraint::computeAdjustedLocalRot(const LLQuaternion& j_loc_rot) const
  496. {
  497. // Rotate mPivotAxis into joint-frame
  498. LLVector3 joint_axis = mPivotAxis * j_loc_rot;
  499. LLQuaternion adjustment;
  500. adjustment.shortestArc(joint_axis, mPivotAxis);
  501. LLQuaternion adjusted_loc_rot = j_loc_rot * adjustment;
  502. // rotate mForward into joint-frame
  503. LLVector3 joint_forward = mForward * adjusted_loc_rot;
  504. LLVector3 new_j_forw = joint_forward;
  505. // compute angle between mForward and new_j_forw
  506. F32 bend = atan2f(new_j_forw * mLeft, new_j_forw * mForward);
  507. if (bend > mMaxBend || bend < mMinBend)
  508. {
  509. bend = compute_clamped_angle(bend, mMinBend, mMaxBend);
  510. new_j_forw = cosf(bend) * mForward + sinf(bend) * mLeft;
  511. adjustment.shortestArc(joint_forward, new_j_forw);
  512. adjusted_loc_rot = adjusted_loc_rot * adjustment;
  513. }
  514. adjusted_loc_rot.normalize();
  515. return adjusted_loc_rot;
  516. }
  517. LLQuaternion KneeConstraint::minimizeTwist(const LLQuaternion& j_loc_rot) const
  518. {
  519. // Assume all swing is really just bend about mPivotAxis.
  520. // If bend_angle is outside the limits then we check both +/- bend_angle and pick
  521. // the one closest to the allowed range. This comes down to a simple question:
  522. // which is closer to the midpoint of the bend range?
  523. LLVector3 joint_forward = mForward * j_loc_rot;
  524. F32 fdot = joint_forward * mForward;
  525. LLVector3 perp_part = joint_forward - fdot * mForward;
  526. F32 bend_angle = atan2f(perp_part.length(), fdot);
  527. if (bend_angle < mMinBend || bend_angle > mMaxBend)
  528. {
  529. F32 alt_bend_angle = - bend_angle;
  530. F32 mid_bend = 0.5f * (mMinBend + mMaxBend);
  531. if (fabsf(alt_bend_angle - mid_bend) < fabsf(bend_angle - mid_bend))
  532. {
  533. bend_angle = alt_bend_angle;
  534. }
  535. }
  536. LLQuaternion bend;
  537. bend.setAngleAxis(bend_angle, mPivotAxis);
  538. return bend;
  539. }
  540. ///////////////////////////////////////////////////////////////////////////////
  541. // AcuteEllipsoidalCone class
  542. ///////////////////////////////////////////////////////////////////////////////
  543. AcuteEllipsoidalCone::AcuteEllipsoidalCone(const LLVector3& forward_axis,
  544. const LLVector3& up_axis,
  545. F32 forward, F32 up, F32 left,
  546. F32 down, F32 right)
  547. : mXForward(forward),
  548. mXUp(up),
  549. mXDown(down),
  550. mXLeft(left),
  551. mXRight(right)
  552. {
  553. mType = ACUTE_ELLIPSOIDAL_CONE_CONSTRAINT;
  554. mUp = up_axis;
  555. mUp.normalize();
  556. mForward = (mUp % forward_axis) % mUp;
  557. mForward.normalize();
  558. mLeft = mUp % mForward; // already normalized
  559. // Divide everything by 'foward' and take make sure they are positive.
  560. // This normalizes the forward component (adjacent side) of all the
  561. // triangles to have length=1.0, which is important for our trigonometry
  562. // math later.
  563. //
  564. // up left |
  565. // | / | /
  566. // |/ |/
  567. // @------------------+
  568. // 1.0 /|
  569. // |
  570. up = fabsf(up / forward);
  571. left = fabsf(left / forward);
  572. down = fabsf(down / forward);
  573. right = fabsf(right / forward);
  574. // These are the indices of the directions and quadrants.
  575. // With 'forward' pointing into the page.
  576. // up
  577. // |
  578. // 1 | 0
  579. // |
  580. // left ------(x)------ right
  581. // |
  582. // 2 | 3
  583. // |
  584. // down
  585. //
  586. // When projecting vectors onto the ellipsoidal surface we will always
  587. // scale the left-axis into the frame in which the ellipsoid is circular.
  588. // We cache the necessary scale coefficients now:
  589. //
  590. mQuadrantScales[0] = up / right;
  591. mQuadrantScales[1] = up / left;
  592. mQuadrantScales[2] = down / left;
  593. mQuadrantScales[3] = down / right;
  594. // When determining whether a direction is inside or outside the
  595. // ellipsoid we will need the cosine and cotangent of the cone angles in
  596. // the scaled frames. We cache them now:
  597. // cosine = adjacent / hypotenuse
  598. // cotangent = adjacent / opposite
  599. mQuadrantCosAngles[0] = 1.f / sqrtf(up * up + 1.f);
  600. mQuadrantCotAngles[0] = 1.f / up;
  601. mQuadrantCosAngles[1] = mQuadrantCosAngles[0];
  602. mQuadrantCotAngles[1] = mQuadrantCotAngles[0];
  603. mQuadrantCosAngles[2] = 1.f / sqrtf(down * down + 1.f);
  604. mQuadrantCotAngles[2] = 1.f / down;
  605. mQuadrantCosAngles[3] = mQuadrantCosAngles[2];
  606. mQuadrantCotAngles[3] = mQuadrantCotAngles[2];
  607. }
  608. AcuteEllipsoidalCone::AcuteEllipsoidalCone(const LLSD& parameters)
  609. : Constraint(Constraint::ACUTE_ELLIPSOIDAL_CONE_CONSTRAINT, parameters)
  610. {
  611. mUp = LLVector3(parameters["up_axis"]);
  612. mUp.normalize();
  613. mForward = (mUp % mForward) % mUp;
  614. mForward.normalize();
  615. mLeft = mUp % mForward; // already normalized
  616. mXForward = parameters["forward"].asReal();
  617. mXUp = parameters["up"].asReal();
  618. mXDown = parameters["down"].asReal();
  619. mXLeft = parameters["left"].asReal();
  620. mXRight = parameters["right"].asReal();
  621. F32 up = fabsf(mXUp / mXForward);
  622. F32 left = fabsf(mXLeft / mXForward);
  623. F32 down = fabsf(mXDown / mXForward);
  624. F32 right = fabsf(mXRight / mXForward);
  625. mQuadrantScales[0] = up / right;
  626. mQuadrantScales[1] = up / left;
  627. mQuadrantScales[2] = down / left;
  628. mQuadrantScales[3] = down / right;
  629. mQuadrantCosAngles[0] = 1.f / sqrtf(up * up + 1.f);
  630. mQuadrantCotAngles[0] = 1.f / up;
  631. mQuadrantCosAngles[1] = mQuadrantCosAngles[0];
  632. mQuadrantCotAngles[1] = mQuadrantCotAngles[0];
  633. mQuadrantCosAngles[2] = 1.f / sqrtf(down * down + 1.f);
  634. mQuadrantCotAngles[2] = 1.f / down;
  635. mQuadrantCosAngles[3] = mQuadrantCosAngles[2];
  636. mQuadrantCotAngles[3] = mQuadrantCotAngles[2];
  637. }
  638. //virtual
  639. LLSD AcuteEllipsoidalCone::asLLSD() const
  640. {
  641. LLSD data = Constraint::asLLSD();
  642. data["up_axis"] = mUp.getValue();
  643. data["forward"] = mXForward;
  644. data["down"] = mXDown;
  645. data["left"] = mXLeft;
  646. data["right"] = mXRight;
  647. return data;
  648. }
  649. //virtual
  650. U64 AcuteEllipsoidalCone::getHash() const
  651. {
  652. return HBXXH64::digest((const void*)this, sizeof(AcuteEllipsoidalCone));
  653. }
  654. LLQuaternion AcuteEllipsoidalCone::computeAdjustedLocalRot(const LLQuaternion& j_loc_rot) const
  655. {
  656. // Rotate mForward into joint-frame
  657. LLVector3 joint_forward = mForward * j_loc_rot;
  658. // joint_forward is normalized
  659. // Determine its quadrant
  660. F32 up_component = joint_forward * mUp;
  661. F32 left_component = joint_forward * mLeft;
  662. U32 q = 0;
  663. if (up_component < 0.f)
  664. {
  665. if (left_component < 0.f)
  666. {
  667. q = 2;
  668. }
  669. else
  670. {
  671. q = 3;
  672. }
  673. }
  674. else if (left_component < 0.f)
  675. {
  676. q = 1;
  677. }
  678. // Scale left axis to frame in which ellipse is a circle
  679. F32 scaled_left_comp = left_component * mQuadrantScales[q];
  680. // Reassemble in scaled frame
  681. F32 forward_component = joint_forward * mForward;
  682. LLVector3 new_j_forw = forward_component * mForward + up_component * mUp +
  683. scaled_left_comp * mLeft;
  684. // new_j_forw is not normalized
  685. // which means we must adjust its the forward_component when
  686. // checking for violation in scaled frame
  687. if (forward_component / new_j_forw.length() < mQuadrantCosAngles[q])
  688. {
  689. // joint violates constraint --> project onto cone
  690. //
  691. // violates projected
  692. // + +
  693. // . /|
  694. // . / |
  695. // . // |
  696. // .// |
  697. // @---+----
  698. // `
  699. // `
  700. //
  701. // Orthogonal components remain unchanged but we need to compute
  702. // a corrected forward_component (adjacent leg of the right triangle)
  703. // in the scaled frame. We can use the formula:
  704. // adjacent = opposite * cos(angle) / sin(angle)
  705. // adjacent = opposite * cot(angle)
  706. //
  707. F32 orthogonal_component = sqrtf(scaled_left_comp * scaled_left_comp +
  708. up_component * up_component);
  709. forward_component = orthogonal_component * mQuadrantCotAngles[q];
  710. // Re-assemble the projected direction in the non-scaled frame:
  711. new_j_forw = forward_component * mForward + up_component * mUp +
  712. left_component * mLeft;
  713. // new_j_forw is not normalized, but it doesn't matter
  714. // Compute adjusted_loc_rot
  715. LLQuaternion adjustment;
  716. adjustment.shortestArc(joint_forward, new_j_forw);
  717. LLQuaternion adjusted_loc_rot = j_loc_rot * adjustment;
  718. adjusted_loc_rot.normalize();
  719. return adjusted_loc_rot;
  720. }
  721. return j_loc_rot;
  722. }
  723. ///////////////////////////////////////////////////////////////////////////////
  724. // LLIK::DoubleLimitedHinge class
  725. ///////////////////////////////////////////////////////////////////////////////
  726. DoubleLimitedHinge::DoubleLimitedHinge(const LLVector3& forward_axis,
  727. const LLVector3& up_axis,
  728. F32 min_yaw, F32 max_yaw,
  729. F32 min_pitch, F32 max_pitch)
  730. {
  731. mType = DOUBLE_LIMITED_HINGE_CONSTRAINT;
  732. mForward = forward_axis;
  733. mForward.normalize();
  734. mUp = mForward % (up_axis % mForward);
  735. mUp.normalize();
  736. mLeft = mUp % mForward;
  737. mMinYaw = min_yaw;
  738. mMaxYaw = max_yaw;
  739. compute_angle_limits(mMinYaw, mMaxYaw);
  740. // Keep pitch in range [-PI/2, PI/2]
  741. F32 HALF_PI = 0.5f * F_PI;
  742. mMinPitch = remove_multiples_of_two_pi(min_pitch);
  743. if (mMinPitch > HALF_PI)
  744. {
  745. mMinPitch = HALF_PI;
  746. }
  747. else if (mMinPitch < -HALF_PI)
  748. {
  749. mMinPitch = -HALF_PI;
  750. }
  751. mMaxPitch = remove_multiples_of_two_pi(max_pitch);
  752. if (mMaxPitch > HALF_PI)
  753. {
  754. mMaxPitch = HALF_PI;
  755. }
  756. else if (mMaxPitch < -HALF_PI)
  757. {
  758. mMaxPitch = -HALF_PI;
  759. }
  760. if (mMinPitch > mMaxPitch)
  761. {
  762. F32 temp = mMinPitch;
  763. mMinPitch = mMaxPitch;
  764. mMaxPitch = temp;
  765. }
  766. }
  767. DoubleLimitedHinge::DoubleLimitedHinge(const LLSD& parameters)
  768. : Constraint(Constraint::DOUBLE_LIMITED_HINGE_CONSTRAINT, parameters)
  769. {
  770. mUp = mForward % (LLVector3(parameters["up_axis"]) % mForward);
  771. mUp.normalize();
  772. mLeft = mUp % mForward;
  773. mMinYaw = parameters["min_yaw"].asReal() * DEG_TO_RAD;
  774. mMaxYaw = parameters["max_yaw"].asReal() * DEG_TO_RAD;
  775. compute_angle_limits(mMinYaw, mMaxYaw);
  776. // Keep pitch in range [-PI/2, PI/2]
  777. F32 HALF_PI = 0.5f * F_PI;
  778. F32 min_pitch = parameters["min_pitch"].asReal() * DEG_TO_RAD;
  779. mMinPitch = remove_multiples_of_two_pi(min_pitch);
  780. if (mMinPitch > HALF_PI)
  781. {
  782. mMinPitch = HALF_PI;
  783. }
  784. else if (mMinPitch < -HALF_PI)
  785. {
  786. mMinPitch = -HALF_PI;
  787. }
  788. F32 max_pitch = parameters["max_pitch"].asReal() * DEG_TO_RAD;
  789. mMaxPitch = remove_multiples_of_two_pi(max_pitch);
  790. if (mMaxPitch > HALF_PI)
  791. {
  792. mMaxPitch = HALF_PI;
  793. }
  794. else if (mMaxPitch < -HALF_PI)
  795. {
  796. mMaxPitch = -HALF_PI;
  797. }
  798. if (mMinPitch > mMaxPitch)
  799. {
  800. F32 temp = mMinPitch;
  801. mMinPitch = mMaxPitch;
  802. mMaxPitch = temp;
  803. }
  804. }
  805. //virtual
  806. LLSD DoubleLimitedHinge::asLLSD() const
  807. {
  808. LLSD data = Constraint::asLLSD();
  809. data["up_axis"] = mUp.getValue();
  810. data["min_yaw"] = mMinYaw * RAD_TO_DEG;
  811. data["max_yaw"] = mMaxYaw * RAD_TO_DEG;
  812. data["min_pitch"] = mMinPitch * RAD_TO_DEG;
  813. data["max_pitch"] = mMaxPitch * RAD_TO_DEG;
  814. return data;
  815. }
  816. //virtual
  817. U64 DoubleLimitedHinge::getHash() const
  818. {
  819. return HBXXH64::digest((const void*)this, sizeof(DoubleLimitedHinge));
  820. }
  821. LLQuaternion DoubleLimitedHinge::computeAdjustedLocalRot(const LLQuaternion& j_loc_rot) const
  822. {
  823. // Twist: eliminate twist by adjusting the rotated mLeft axis to remain in
  824. // horizontal plane
  825. LLVector3 joint_left = mLeft * j_loc_rot;
  826. LLQuaternion adjustment;
  827. adjustment.shortestArc(joint_left, joint_left - (joint_left * mUp) * mUp);
  828. LLQuaternion adjusted_loc_rot = j_loc_rot * adjustment;
  829. LLVector3 joint_forward = mForward * adjusted_loc_rot;
  830. // Yaw
  831. F32 up_component = joint_forward * mUp;
  832. LLVector3 horizontal_axis = joint_forward - up_component * mUp;
  833. F32 yaw = atan2f(horizontal_axis * mLeft, horizontal_axis * mForward);
  834. if (yaw > mMaxYaw || yaw < mMinYaw)
  835. {
  836. yaw = compute_clamped_angle(yaw, mMinYaw, mMaxYaw);
  837. horizontal_axis = cosf(yaw) * mForward + sinf(yaw) * mLeft;
  838. }
  839. else
  840. {
  841. horizontal_axis.normalize();
  842. }
  843. // Pitch. Note: the minus-sign in the "opposite" (sin) term here is because
  844. // our pitch-axis is mLeft and according to the right-hand-rule positive
  845. // pitch drops the forward axis down.
  846. F32 horiz_comp = sqrtf(llmax(1.f - up_component * up_component, 0.f));
  847. F32 pitch = atan2f(-up_component, horiz_comp);
  848. if (pitch > mMaxPitch || pitch < mMinPitch)
  849. {
  850. pitch = compute_clamped_angle(pitch, mMinPitch, mMaxPitch);
  851. up_component = -sinf(pitch);
  852. horiz_comp = sqrtf(llmax(1.f - up_component * up_component, 0.f));
  853. }
  854. LLVector3 new_j_forw = horiz_comp * horizontal_axis + up_component * mUp;
  855. new_j_forw.normalize();
  856. if (dist_vec(joint_forward, new_j_forw) > 1.0e-3f)
  857. {
  858. // Compute adjusted_loc_rot
  859. adjustment.shortestArc(joint_forward, new_j_forw);
  860. adjusted_loc_rot = adjusted_loc_rot * adjustment;
  861. }
  862. adjusted_loc_rot.normalize();
  863. return adjusted_loc_rot;
  864. }
  865. // Eliminates twist by adjusting the rotated mLeft axis to remain in horizontal
  866. // plane
  867. LLQuaternion DoubleLimitedHinge::minimizeTwist(const LLQuaternion& j_loc_rot) const
  868. {
  869. LLVector3 joint_left = mLeft * j_loc_rot;
  870. LLQuaternion adjustment;
  871. adjustment.shortestArc(joint_left, joint_left - (joint_left * mUp) * mUp);
  872. LLQuaternion adjusted_loc_rot = j_loc_rot * adjustment;
  873. adjusted_loc_rot.normalize();
  874. return adjusted_loc_rot;
  875. }
  876. ///////////////////////////////////////////////////////////////////////////////
  877. // LLIK::Joint::Config sub-class
  878. ///////////////////////////////////////////////////////////////////////////////
  879. void Joint::Config::updateFrom(const Config& other_config)
  880. {
  881. if (mFlags == other_config.mFlags)
  882. {
  883. *this = other_config; // other_config updates everything
  884. }
  885. else // Find and apply all parameters in other_config
  886. {
  887. if (other_config.hasLocalPos())
  888. {
  889. setLocalPos(other_config.mLocalPos);
  890. }
  891. if (other_config.hasLocalRot())
  892. {
  893. setLocalRot(other_config.mLocalRot);
  894. }
  895. if (other_config.hasTargetPos())
  896. {
  897. setTargetPos(other_config.mTargetPos);
  898. }
  899. if (other_config.hasTargetRot())
  900. {
  901. setTargetRot(other_config.mTargetRot);
  902. }
  903. if (other_config.hasLocalScale())
  904. {
  905. setLocalScale(other_config.mLocalScale);
  906. }
  907. if (other_config.constraintIsDisabled())
  908. {
  909. disableConstraint();
  910. }
  911. }
  912. }
  913. ///////////////////////////////////////////////////////////////////////////////
  914. // LLIK::Joint class
  915. ///////////////////////////////////////////////////////////////////////////////
  916. Joint::Joint(LLJoint* info_ptr)
  917. : mInfoPtr(info_ptr),
  918. mID(info_ptr->getJointNum()),
  919. mConfig(NULL),
  920. mConfigFlags(0),
  921. mIkFlags(0)
  922. {
  923. resetFromInfo();
  924. }
  925. void Joint::resetFromInfo()
  926. {
  927. const LLVector3& scale = mInfoPtr->getScale();
  928. mLocalPos = mInfoPtr->getPosition().scaledVec(scale);
  929. mBone = mInfoPtr->getEnd().scaledVec(scale);
  930. mLocalPosLength = mLocalPos.length();
  931. // This is correct: we do NOT store info scale in mLocalScale which
  932. // represents Puppetry's tweak on top of whatever is set in the info.
  933. mLocalScale.set(1.f, 1.f, 1.f);
  934. }
  935. void Joint::addChild(const ptr_t& child)
  936. {
  937. if (child)
  938. {
  939. mChildren.push_back(child);
  940. }
  941. }
  942. void Joint::setTargetPos(const LLVector3& pos)
  943. {
  944. if (hasPosTarget())
  945. {
  946. // *HACK: cast mConfig to non-const pointer so we can modify it
  947. Config* config = const_cast<Config*>(mConfig);
  948. config->setTargetPos(pos);
  949. }
  950. }
  951. void Joint::setParent(const ptr_t& parent)
  952. {
  953. mParent = parent;
  954. if (!mParent)
  955. {
  956. // The root's local orientation is never updated by the IK algorithm.
  957. // Whatever orientation it has at the start of IK will be its final,
  958. // which is why we flag it as "locked". This also simplifies logic
  959. // elsewhere: in a few places we assume any non-locked Joint has a parent.
  960. mIkFlags = IK_FLAG_LOCAL_ROT_LOCKED;
  961. }
  962. reset();
  963. }
  964. void Joint::reset()
  965. {
  966. resetFromInfo();
  967. // Note: we do not bother to enforce localRotLocked() here because any call
  968. // to reset() is expected to be outside the Solver IK iterations.
  969. mLocalRot = LLQuaternion::DEFAULT;
  970. if (mParent)
  971. {
  972. mPos = mParent->mPos + mLocalPos * mParent->mRot;
  973. mRot = mParent->mRot;
  974. }
  975. else
  976. {
  977. mPos = mLocalPos;
  978. mRot = mLocalRot;
  979. }
  980. }
  981. void Joint::relaxRot(F32 blend_factor)
  982. {
  983. if (!localRotLocked())
  984. {
  985. mLocalRot = lerp(blend_factor, mLocalRot, LLQuaternion::DEFAULT);
  986. }
  987. if (mParent)
  988. {
  989. // We always re-compute world-frame transform because parent may have
  990. // relaxed.
  991. mRot = mLocalRot * mParent->mRot;
  992. mRot.normalize();
  993. mPos = mParent->mPos + mLocalPos * mParent->mRot;
  994. }
  995. else
  996. {
  997. mRot = mLocalRot;
  998. mPos = mLocalPos;
  999. }
  1000. }
  1001. void Joint::resetRecursively()
  1002. {
  1003. reset();
  1004. for (auto& child : mChildren)
  1005. {
  1006. child->resetRecursively();
  1007. }
  1008. }
  1009. void Joint::relaxRotationsRecursively(F32 blend_factor)
  1010. {
  1011. blend_factor = llclamp(blend_factor, 0.f, 1.f);
  1012. relaxRot(blend_factor);
  1013. for (auto& child : mChildren)
  1014. {
  1015. if (child->isActive())
  1016. {
  1017. child->relaxRotationsRecursively(blend_factor);
  1018. }
  1019. }
  1020. }
  1021. F32 Joint::recursiveComputeLongestChainLength(F32 length) const
  1022. {
  1023. length += mLocalPosLength;
  1024. F32 longest_length = length;
  1025. if (mChildren.empty())
  1026. {
  1027. longest_length += mBone.length();
  1028. }
  1029. else
  1030. {
  1031. for (const auto& child : mChildren)
  1032. {
  1033. F32 child_len = child->recursiveComputeLongestChainLength(length);
  1034. if (child_len > longest_length)
  1035. {
  1036. longest_length = child_len;
  1037. }
  1038. }
  1039. }
  1040. return longest_length;
  1041. }
  1042. LLVector3 Joint::computeEndTargetPos() const
  1043. {
  1044. // Note: we expect this Joint has either: a target, or at least one
  1045. // active child
  1046. if (hasPosTarget())
  1047. {
  1048. return mConfig->getTargetPos();
  1049. }
  1050. LLVector3 target_pos;
  1051. S32 num_active_children = 0;
  1052. for (const auto& child : mChildren)
  1053. {
  1054. if (child->isActive())
  1055. {
  1056. target_pos += child->mPos;
  1057. ++num_active_children;
  1058. }
  1059. }
  1060. if (!num_active_children)
  1061. {
  1062. llwarns_sparse << "No active children !" << llendl;
  1063. return target_pos;
  1064. }
  1065. return (1.f / F32(num_active_children)) * target_pos;
  1066. }
  1067. LLVector3 Joint::computeWorldTipOffset() const
  1068. {
  1069. LLVector3 offset = mPos;
  1070. if (mParent)
  1071. {
  1072. offset -= mParent->mPos + mLocalPos * mParent->mRot;
  1073. }
  1074. return offset;
  1075. }
  1076. void Joint::updateEndInward()
  1077. {
  1078. // Note: during FABRIK we DO NOT enforce constraints.
  1079. if (hasRotTarget())
  1080. {
  1081. mRot = mConfig->getTargetRot();
  1082. if (hasPosTarget())
  1083. {
  1084. mPos = mConfig->getTargetPos() - mBone * mRot;
  1085. }
  1086. }
  1087. else
  1088. {
  1089. std::vector<LLVector3> local_targets, world_targets;
  1090. collectTargetPositions(local_targets, world_targets);
  1091. size_t num_targets = local_targets.size();
  1092. if (num_targets == 1)
  1093. {
  1094. // Special handling for the most common num_targets == 1 case
  1095. // compute mPos
  1096. LLVector3 bone_dir = world_targets[0] - mPos;
  1097. bone_dir.normalize();
  1098. mPos = world_targets[0] - (local_targets[0].length() * bone_dir);
  1099. // Compute new mRot
  1100. LLVector3 old_bone = local_targets[0] * mRot;
  1101. LLQuaternion adjustment;
  1102. adjustment.shortestArc(old_bone, bone_dir);
  1103. mRot = mRot * adjustment;
  1104. mRot.normalize();
  1105. }
  1106. else
  1107. {
  1108. LLVector3 new_pos;
  1109. // Origin in quaternion space
  1110. LLQuaternion avg_adjustment(0.f, 0.f, 0.f, 0.f);
  1111. for (size_t i = 0; i < num_targets; ++i)
  1112. {
  1113. // mPos
  1114. LLVector3 new_bone = world_targets[i] - mPos;
  1115. new_bone.normalize();
  1116. new_bone *= local_targets[i].length();
  1117. new_pos += world_targets[i] - new_bone;
  1118. // mRot
  1119. LLVector3 old_bone = local_targets[i] * mRot;
  1120. LLQuaternion adjustment;
  1121. adjustment.shortestArc(old_bone, new_bone);
  1122. if (adjustment.mQ[VW] < 0.f)
  1123. {
  1124. // Negate to keep all arithmetic on the same hypersphere
  1125. avg_adjustment = avg_adjustment - adjustment;
  1126. }
  1127. else
  1128. {
  1129. avg_adjustment = avg_adjustment + adjustment;
  1130. }
  1131. }
  1132. if (mParent && mParent->isActive())
  1133. {
  1134. // Compute mPos
  1135. mPos = new_pos / (F32)(num_targets);
  1136. }
  1137. // Compute mRot
  1138. avg_adjustment.normalize();
  1139. mRot = mRot * avg_adjustment;
  1140. mRot.normalize();
  1141. }
  1142. }
  1143. // Note: mLocalRot will be updated later when we know mParent's location
  1144. // Now that we know mRot --> update children mLocalRot
  1145. for (auto& child : mChildren)
  1146. {
  1147. if (child->isActive())
  1148. {
  1149. child->updateLocalRot();
  1150. }
  1151. }
  1152. }
  1153. void Joint::updateEndOutward()
  1154. {
  1155. // Note: during FABRIK we DO NOT enforce constraints.
  1156. // mParent is expected to be non-null.
  1157. mPos = mParent->mPos + mLocalPos * mParent->mRot;
  1158. // mRot
  1159. if (localRotLocked())
  1160. {
  1161. mRot = mLocalRot * mParent->mRot;
  1162. return;
  1163. }
  1164. if (hasRotTarget())
  1165. {
  1166. mRot = mConfig->getTargetRot();
  1167. if (hasPosTarget())
  1168. {
  1169. mPos = mConfig->getTargetPos() - mBone * mRot;
  1170. }
  1171. }
  1172. else
  1173. {
  1174. std::vector<LLVector3> local_targets, world_targets;
  1175. collectTargetPositions(local_targets, world_targets);
  1176. size_t num_targets = local_targets.size();
  1177. if (num_targets == 1)
  1178. {
  1179. // Special handling for the most common num_targets == 1 case
  1180. LLVector3 new_bone = world_targets[0] - mPos;
  1181. LLVector3 old_bone = local_targets[0] * mRot;
  1182. LLQuaternion adjustment;
  1183. adjustment.shortestArc(old_bone, new_bone);
  1184. mRot = mRot * adjustment;
  1185. }
  1186. else
  1187. {
  1188. // Origin in quaternion space
  1189. LLQuaternion avg_adjustment(0.f, 0.f, 0.f, 0.f);
  1190. LLQuaternion adjustment;
  1191. for (size_t i = 0; i < num_targets; ++i)
  1192. {
  1193. LLVector3 new_bone = world_targets[i] - mPos;
  1194. LLVector3 old_bone = local_targets[i] * mRot;
  1195. adjustment.shortestArc(old_bone, new_bone);
  1196. if (adjustment.mQ[VW] < 0.f)
  1197. {
  1198. // Negate to keep all Quaternion arithmetic on one
  1199. // hypersphere
  1200. avg_adjustment = avg_adjustment - adjustment;
  1201. }
  1202. else
  1203. {
  1204. avg_adjustment = avg_adjustment + adjustment;
  1205. }
  1206. }
  1207. avg_adjustment.normalize();
  1208. mRot = mRot * avg_adjustment;
  1209. }
  1210. mRot.normalize();
  1211. }
  1212. updateLocalRot();
  1213. }
  1214. // This Joint's child is specified in argument in case this Joint has multiple
  1215. // children.
  1216. void Joint::updateInward(const Joint::ptr_t& child)
  1217. {
  1218. // Note: during FABRIK we DO NOT enforce constraints. mParent is expected
  1219. // to be non-null.
  1220. // Compute mPos
  1221. LLVector3 old_pos = mPos;
  1222. LLVector3 bone_dir = child->mPos - old_pos;
  1223. bone_dir.normalize();
  1224. mPos = child->mPos - child->mLocalPosLength * bone_dir;
  1225. // Compute mRot
  1226. LLVector3 old_bone = child->mLocalPos * mRot;
  1227. LLQuaternion adjustment;
  1228. adjustment.shortestArc(old_bone, bone_dir);
  1229. mRot = mRot * adjustment;
  1230. mRot.normalize();
  1231. // Compute child->mLocalRot
  1232. child->updateLocalRot();
  1233. // this->mLocalRot will be updated later
  1234. }
  1235. void Joint::updatePosAndRotFromParent()
  1236. {
  1237. if (mParent)
  1238. {
  1239. mPos = mParent->mPos + mLocalPos * mParent->mRot;
  1240. mRot = mLocalRot * mParent->mRot;
  1241. mRot.normalize();
  1242. }
  1243. }
  1244. void Joint::updateOutward()
  1245. {
  1246. // Note: during FABRIK we DO NOT enforce constraints.
  1247. // mParent is expected to be non-null.
  1248. LLVector3 old_end_pos = mPos + mBone * mRot;
  1249. // mPos
  1250. mPos = mParent->mPos + mLocalPos * mParent->mRot;
  1251. // mRot
  1252. LLVector3 new_bone = old_end_pos - mPos;
  1253. LLVector3 old_bone = mBone * mRot;
  1254. LLQuaternion dQ;
  1255. dQ.shortestArc(old_bone, new_bone);
  1256. mRot = mRot * dQ;
  1257. mRot.normalize();
  1258. updateLocalRot();
  1259. }
  1260. void Joint::applyLocalRot()
  1261. {
  1262. if (!mParent)
  1263. {
  1264. return;
  1265. }
  1266. if (hasRotTarget())
  1267. {
  1268. // Apply backpressure by lerping toward new_rot
  1269. LLQuaternion new_rot = mLocalRot * mParent->mRot;
  1270. constexpr F32 WORLD_ROT_TARGET_BACKPRESSURE_COEF = 0.5f;
  1271. mRot = lerp(WORLD_ROT_TARGET_BACKPRESSURE_COEF,
  1272. mConfig->getTargetRot(), new_rot);
  1273. // Recompute mLocalRot
  1274. LLQuaternion inv_parent_rot = mParent->mRot;
  1275. inv_parent_rot.transpose();
  1276. mLocalRot = mRot * inv_parent_rot;
  1277. mLocalRot.normalize();
  1278. }
  1279. else
  1280. {
  1281. mRot = mLocalRot * mParent->mRot;
  1282. mRot.normalize();
  1283. }
  1284. }
  1285. void Joint::updateLocalRot()
  1286. {
  1287. if (!localRotLocked())
  1288. {
  1289. // mPos and mRot are expected to be correct and mParent is expected to
  1290. // be valid
  1291. LLQuaternion inv_parent_rot = mParent->mRot;
  1292. inv_parent_rot.transpose();
  1293. mLocalRot = mRot * inv_parent_rot;
  1294. mLocalRot.normalize();
  1295. }
  1296. }
  1297. LLQuaternion Joint::computeParentRot() const
  1298. {
  1299. // Formula is:
  1300. // mRot = mLocalRot * mParent->mRot
  1301. // Solving for mParent->mRot gives:
  1302. // mParent->mRot = mLocalRotInv * mRot
  1303. LLQuaternion q = mLocalRot;
  1304. q.transpose();
  1305. q = q * mRot;
  1306. q.normalize();
  1307. return q;
  1308. }
  1309. void Joint::updateChildLocalRots() const
  1310. {
  1311. // Now that we know mRot we can update the childrens' mLocalRot
  1312. for (const Joint::ptr_t& child : mChildren)
  1313. {
  1314. if (child->isActive())
  1315. {
  1316. child->updateLocalRot();
  1317. }
  1318. }
  1319. }
  1320. void Joint::lockLocalRot(const LLQuaternion& local_rot)
  1321. {
  1322. mLocalRot = local_rot;
  1323. mIkFlags |= IK_FLAG_LOCAL_ROT_LOCKED;
  1324. activate();
  1325. if (!mParent)
  1326. {
  1327. mRot = local_rot;
  1328. }
  1329. }
  1330. bool Joint::enforceConstraint()
  1331. {
  1332. if (localRotLocked())
  1333. {
  1334. // A fixed mLocalRot is effectively like a fixed Constraint so we
  1335. // always return 'true' here: the Constraint is in effect and mRot may
  1336. // have been optimistically modified but mLocalRot was not.
  1337. return true;
  1338. }
  1339. if (mConstraint && !hasDisabledConstraint())
  1340. {
  1341. return mConstraint->enforce(*this);
  1342. }
  1343. return false;
  1344. }
  1345. void Joint::updateWorldTransformsRecursively()
  1346. {
  1347. updatePosAndRotFromParent();
  1348. for (Joint::ptr_t& child : mChildren)
  1349. {
  1350. if (child->isActive())
  1351. {
  1352. child->updateWorldTransformsRecursively();
  1353. }
  1354. }
  1355. }
  1356. // Returns valid Joint::ptr_t to child iff only one child is active, else
  1357. // returns null Joint::ptr_t
  1358. Joint::ptr_t Joint::getSingleActiveChild()
  1359. {
  1360. Joint::ptr_t active_child;
  1361. for (Joint::ptr_t& child : mChildren)
  1362. {
  1363. if (child->isActive())
  1364. {
  1365. if (active_child)
  1366. {
  1367. // Second child --> this Joint is not a "false" sub-base
  1368. active_child.reset();
  1369. break;
  1370. }
  1371. active_child = child;
  1372. }
  1373. }
  1374. return active_child;
  1375. }
  1376. void Joint::setLocalRot(const LLQuaternion& new_local_rot)
  1377. {
  1378. if (!localRotLocked())
  1379. {
  1380. constexpr F32 BLEND_COEF = 0.25f;
  1381. mLocalRot = lerp(BLEND_COEF, mLocalRot, new_local_rot);
  1382. }
  1383. }
  1384. // Only call this if you know what you are doing; this should only be called
  1385. // once before starting IK algorithm iterations.
  1386. void Joint::setLocalScale(const LLVector3& scale)
  1387. {
  1388. // Compute final scale adustment to applly to mLocalPos and mBone
  1389. constexpr F32 MIN_INVERTABLE_SCALE = 1.0e-15f;
  1390. LLVector3 re_scale;
  1391. for (U32 i = 0; i < 3; ++i)
  1392. {
  1393. // Verify mLocalScale component to avoid introducing NaN
  1394. if (mLocalScale[i] > MIN_INVERTABLE_SCALE)
  1395. {
  1396. re_scale[i] = scale[i] / mLocalScale[i];
  1397. }
  1398. else
  1399. {
  1400. re_scale[i] = 0.f;
  1401. }
  1402. }
  1403. // We remember the final scale adjustment for later...
  1404. mLocalScale = scale;
  1405. // ...and apply it immediately onto mLocalPos and mBone.
  1406. mBone.scaleVec(re_scale);
  1407. mLocalPos.scaleVec(re_scale);
  1408. mLocalPosLength = mLocalPos.length();
  1409. }
  1410. LLVector3 Joint::getPreScaledLocalPos() const
  1411. {
  1412. LLVector3 pos = mLocalPos;
  1413. // We inverse-scale mLocalPos because we already applied the info's scale
  1414. // to mLocalPos so we could perform IK without constantly recomputing it,
  1415. // and now we are being asked for mLocalPos in the info's pre-scaled frame.
  1416. LLVector3 inv_scale = mInfoPtr->getScale();
  1417. constexpr F32 MIN_INVERTABLE_SCALE = 1.0e-15f;
  1418. for (U32 i = 0; i < 3; ++i)
  1419. {
  1420. // Verify mLocalScale component to avoid introducing NaN
  1421. if (inv_scale[i] > MIN_INVERTABLE_SCALE)
  1422. {
  1423. inv_scale[i] = 1.f / inv_scale[i];
  1424. }
  1425. else
  1426. {
  1427. inv_scale[i] = 0.f;
  1428. }
  1429. }
  1430. pos.scaleVec(inv_scale);
  1431. return pos;
  1432. }
  1433. void Joint::adjustWorldRot(const LLQuaternion& adjustment)
  1434. {
  1435. mRot = mRot * adjustment;
  1436. updateLocalRot();
  1437. if (enforceConstraint())
  1438. {
  1439. applyLocalRot();
  1440. }
  1441. }
  1442. void Joint::collectTargetPositions(std::vector<LLVector3>& local_targets,
  1443. std::vector<LLVector3>& world_targets) const
  1444. {
  1445. // The "target positions" are points in the Joint local-frame which
  1446. // correspond to points in other frames: either child positions or a target
  1447. // end-effector. We need to know these positions in both local and world
  1448. // frames.
  1449. //
  1450. // Note: it is expected this Joint has either: a target, or at least one
  1451. // active child
  1452. if (hasPosTarget())
  1453. {
  1454. local_targets.emplace_back(mBone);
  1455. world_targets.emplace_back(mConfig->getTargetPos());
  1456. }
  1457. else
  1458. {
  1459. // *TODO: local_centroid and its length are invarient for the lifetime
  1460. // of the Chains so we could pre-compute and cache them and simplify
  1461. // the logic which consumes this info.
  1462. for (const auto& child : mChildren)
  1463. {
  1464. if (child->isActive())
  1465. {
  1466. local_targets.emplace_back(child->mLocalPos);
  1467. world_targets.emplace_back(child->mPos);
  1468. }
  1469. }
  1470. }
  1471. }
  1472. void Joint::transformTargetsToParentLocal(std::vector<LLVector3>& local) const
  1473. {
  1474. if (mParent)
  1475. {
  1476. LLQuaternion world_to_parent = mParent->mRot;
  1477. world_to_parent.transpose();
  1478. for (auto& target : local)
  1479. {
  1480. LLVector3 world_target = (mPos + target * mRot) - mParent->mPos;
  1481. target = world_target * world_to_parent;
  1482. }
  1483. }
  1484. }
  1485. bool Joint::swingTowardTargets(const std::vector<LLVector3>& local_targets,
  1486. const std::vector<LLVector3>& world_targets)
  1487. {
  1488. if (localRotLocked())
  1489. {
  1490. // Nothing to do, but we assume targets are not yet aligned and return
  1491. // 'true'
  1492. return true;
  1493. }
  1494. constexpr F32 MIN_SWING_ANGLE = 0.001f * F_PI;
  1495. bool something_changed = false;
  1496. if (hasRotTarget())
  1497. {
  1498. mRot = mConfig->getTargetRot();
  1499. something_changed = true;
  1500. }
  1501. else
  1502. {
  1503. size_t num_targets = local_targets.size();
  1504. LLQuaternion adjustment;
  1505. if (num_targets == 1)
  1506. {
  1507. LLVector3 old_bone = local_targets[0] * mRot;
  1508. LLVector3 new_bone = world_targets[0] - mPos;
  1509. adjustment.shortestArc(old_bone, new_bone);
  1510. }
  1511. else
  1512. {
  1513. adjustment.mQ[VW] = 0.f;
  1514. for (size_t i = 0; i < num_targets; ++i)
  1515. {
  1516. LLVector3 old_bone = local_targets[i] * mRot;
  1517. LLVector3 new_bone = world_targets[i] - mPos;
  1518. LLQuaternion adj;
  1519. adj.shortestArc(old_bone, new_bone);
  1520. if (adj.mQ[VW] < 0.f)
  1521. {
  1522. // Negate to keep all arithmetic on the same hypersphere
  1523. adjustment = adjustment - adj;
  1524. }
  1525. else
  1526. {
  1527. adjustment = adjustment + adj;
  1528. }
  1529. }
  1530. adjustment.normalize();
  1531. }
  1532. if (!LLQuaternion::almost_equal(adjustment,
  1533. LLQuaternion::DEFAULT, MIN_SWING_ANGLE))
  1534. {
  1535. // lerp the adjustment instead of using the full rotation: this
  1536. // allows swing to distribute along the length of the chain.
  1537. constexpr F32 SWING_FACTOR = 0.25f;
  1538. adjustment = lerp(SWING_FACTOR, LLQuaternion::DEFAULT, adjustment);
  1539. // compute mRot
  1540. mRot = mRot * adjustment;
  1541. mRot.normalize();
  1542. something_changed = true;
  1543. }
  1544. }
  1545. if (something_changed)
  1546. {
  1547. // Compute mLocalRot. Instead of calling updateLocalRot() which has
  1548. // extra checks unnecessary in this context, we do the math explicitly.
  1549. LLQuaternion inv_parent_rot = mParent->mRot;
  1550. inv_parent_rot.transpose();
  1551. mLocalRot = mRot * inv_parent_rot;
  1552. mLocalRot.normalize();
  1553. if (enforceConstraint())
  1554. {
  1555. applyLocalRot();
  1556. #if LLIK_EXPERIMENTAL
  1557. // EXPERIMENTAL: we hit the constraint during the swing; perhaps
  1558. // some twist can get us closer
  1559. twistTowardTargets(local_targets, world_targets);
  1560. #endif
  1561. }
  1562. }
  1563. return something_changed;
  1564. }
  1565. #if LLIK_EXPERIMENTAL
  1566. void Joint::twistTowardTargets(const std::vector<LLVector3>& local_targets,
  1567. const std::vector<LLVector3>& world_targets)
  1568. {
  1569. if (!mConstraint->allowsTwist())
  1570. {
  1571. return;
  1572. }
  1573. // Always twist about mConstraint->mForward axis
  1574. LLVector3 axis = mConstraint->getForwardAxis() * mRot;
  1575. LLQuaternion adjustment;
  1576. size_t num_targets = local_targets.size();
  1577. if (num_targets == 1)
  1578. {
  1579. // Transform to the world-frame with mPos as origin
  1580. LLVector3 local_target = local_targets[0] * mRot;
  1581. LLVector3 world_target = world_targets[0] - mPos;
  1582. F32 target_length = local_target.length();
  1583. constexpr F32 MIN_TARGET_LENGTH = 1.0e-2f;
  1584. if (target_length < MIN_TARGET_LENGTH)
  1585. {
  1586. // Bone is too short
  1587. return;
  1588. }
  1589. // Remove components parallel to axis
  1590. local_target -= (local_target * axis) * axis;
  1591. world_target -= (world_target * axis) * axis;
  1592. if (local_target * world_target < 0.f)
  1593. {
  1594. // This discrepancy is better served with a swing
  1595. return;
  1596. }
  1597. F32 radius = local_target.length();
  1598. constexpr F32 MIN_RADIUS_FRACTION = 1.0e-2f;
  1599. const F32 MIN_RADIUS = MIN_RADIUS_FRACTION * target_length;
  1600. if (radius < MIN_RADIUS || world_target.length() < MIN_RADIUS)
  1601. {
  1602. // Twist movement too small to bother
  1603. return;
  1604. }
  1605. // Compute the adjustment
  1606. adjustment.shortestArc(local_target, world_target);
  1607. }
  1608. else
  1609. {
  1610. adjustment.mQ[VW] = 0.f;
  1611. U32 num_adjustments = 0;
  1612. for (size_t i = 0; i < local_targets.size(); ++i)
  1613. {
  1614. LLQuaternion adj;
  1615. // Transform to the world-frame with mPos as origin
  1616. LLVector3 local_target = local_targets[i] * mRot;
  1617. LLVector3 world_target = world_targets[i] - mPos;
  1618. F32 target_length = local_target.length();
  1619. constexpr F32 MIN_TARGET_LENGTH = 1.0e-2f;
  1620. if (target_length < MIN_TARGET_LENGTH)
  1621. {
  1622. // bone is too short
  1623. adjustment = adjustment + adj;
  1624. return;
  1625. }
  1626. // Remove components parallel to axis
  1627. local_target -= (local_target * axis) * axis;
  1628. world_target -= (world_target * axis) * axis;
  1629. if (local_target * world_target < 0.f)
  1630. {
  1631. // This discrepancy is better served with a swing
  1632. adjustment = adjustment + adj;
  1633. return;
  1634. }
  1635. F32 radius = local_target.length();
  1636. constexpr F32 MIN_RADIUS_FRACTION = 1.0e-2f;
  1637. const F32 MIN_RADIUS = MIN_RADIUS_FRACTION * target_length;
  1638. if (radius < MIN_RADIUS || world_target.length() < MIN_RADIUS)
  1639. {
  1640. // Twist movement will be too small
  1641. adjustment = adjustment + adj;
  1642. return;
  1643. }
  1644. // Compute the adjustment
  1645. adj.shortestArc(local_target, world_target);
  1646. adjustment = adjustment + adj;
  1647. ++num_adjustments;
  1648. }
  1649. if (num_adjustments == 0)
  1650. {
  1651. return;
  1652. }
  1653. adjustment.normalize();
  1654. }
  1655. // lerp the adjustment instead of using the full rotation; this allows
  1656. // twist to distribute along the length of the chain.
  1657. constexpr F32 TWIST_BLEND = 0.4f;
  1658. adjustment = lerp(TWIST_BLEND, LLQuaternion::DEFAULT, adjustment);
  1659. // Compute mRot
  1660. mRot = mRot * adjustment;
  1661. mRot.normalize();
  1662. // Compute mLocalRot. Instead of calling updateLocalRot() which has extra
  1663. // checks unnecessary in this context, we do the math explicitly.
  1664. LLQuaternion inv_parent_rot = mParent->mRot;
  1665. inv_parent_rot.transpose();
  1666. mLocalRot = mRot * inv_parent_rot;
  1667. mLocalRot.normalize();
  1668. if (enforceConstraint())
  1669. {
  1670. applyLocalRot();
  1671. }
  1672. }
  1673. #endif // LLIK_EXPERIMENTAL
  1674. void Joint::untwist()
  1675. {
  1676. if (hasRotTarget())
  1677. {
  1678. mRot = mConfig->getTargetRot();
  1679. updateLocalRot();
  1680. }
  1681. else if (!localRotLocked())
  1682. {
  1683. // Compute new_local_rot
  1684. LLQuaternion new_local_rot = LLQuaternion::DEFAULT;
  1685. if (mConstraint && !hasDisabledConstraint())
  1686. {
  1687. new_local_rot = mConstraint->minimizeTwist(mLocalRot);
  1688. }
  1689. else
  1690. {
  1691. LLVector3 bone = mBone;
  1692. bone.normalize();
  1693. LLVector3 new_bone = bone * mLocalRot;
  1694. LLVector3 swing_axis = bone % new_bone;
  1695. constexpr F32 MIN_SWING_AXIS_LENGTH = 1.0e-3f;
  1696. if (swing_axis.length() > MIN_SWING_AXIS_LENGTH)
  1697. {
  1698. F32 swing_angle = acosf(new_bone * bone);
  1699. new_local_rot.setAngleAxis(swing_angle, swing_axis);
  1700. }
  1701. }
  1702. // Blend toward new_local_rot
  1703. constexpr F32 UNTWIST_BLEND = 0.25f;
  1704. mLocalRot = lerp(UNTWIST_BLEND, mLocalRot, new_local_rot);
  1705. // Note: if UNTWIST_BLEND is increased here the consequence will be
  1706. // more noticeable occasional pops in some joints. It is an interaction
  1707. // with transitions in/out of the
  1708. // if (swing_axis.length() > MIN_SWING_AXIS_LENGTH)
  1709. // condition above.
  1710. // Apply new mLocalRot
  1711. LLQuaternion new_rot = mLocalRot * mParent->mRot;
  1712. if (!mParent->localRotLocked())
  1713. {
  1714. // Check to see if new mLocalRot would change world-frame bone
  1715. // (which only happens for some Constraints)
  1716. LLVector3 old_bone = mBone * mRot;
  1717. LLVector3 new_bone = mBone * new_rot;
  1718. constexpr F32 MIN_DELTA_COEF = 0.01f;
  1719. if ((new_bone - old_bone).length() >
  1720. MIN_DELTA_COEF * mBone.length())
  1721. {
  1722. // The new mLocalRot would change the world-frame bone
  1723. // direction so we counter-rotate mParent to compensate.
  1724. // Compute axis of correction
  1725. LLVector3 axis = mParent->mBone * mParent->mRot;
  1726. axis.normalize();
  1727. // Project child bones to plane
  1728. old_bone = old_bone - (old_bone * axis) * axis;
  1729. new_bone = new_bone - (new_bone * axis) * axis;
  1730. // Compute correction from new_bone back to old_bone
  1731. LLQuaternion twist;
  1732. twist.shortestArc(new_bone, old_bone);
  1733. // Compute new parent rot
  1734. LLQuaternion new_parent_rot = mParent->mRot * twist;
  1735. new_parent_rot.normalize();
  1736. mParent->setWorldRot(new_parent_rot);
  1737. mParent->updateLocalRot();
  1738. // Compute new rot
  1739. new_rot = mLocalRot * mParent->mRot;
  1740. }
  1741. }
  1742. mRot = new_rot;
  1743. mRot.normalize();
  1744. }
  1745. }
  1746. ///////////////////////////////////////////////////////////////////////////////
  1747. // LLIK::Solver class
  1748. ///////////////////////////////////////////////////////////////////////////////
  1749. void Solver::resetSkeleton()
  1750. {
  1751. mSkeleton.begin()->second->resetRecursively();
  1752. }
  1753. // Computes the offset from the "tip" of from_id to the "end" of to_id or the
  1754. // negative when from_id > to_id
  1755. LLVector3 Solver::computeReach(S16 to_id, S16 from_id) const
  1756. {
  1757. S16 ancestor = from_id;
  1758. S16 descendent = to_id;
  1759. bool swapped = false;
  1760. if (ancestor > descendent)
  1761. {
  1762. ancestor = to_id;
  1763. descendent = from_id;
  1764. swapped = true;
  1765. }
  1766. LLVector3 reach;
  1767. // Start at descendent and traverse up the limb until we find the ancestor
  1768. joint_map_t::const_iterator itr = mSkeleton.find(descendent);
  1769. if (itr != mSkeleton.end())
  1770. {
  1771. Joint::ptr_t joint = itr->second;
  1772. LLVector3 chain_reach = joint->getBone();
  1773. while (joint)
  1774. {
  1775. chain_reach += joint->getLocalPos();
  1776. joint = joint->getParent();
  1777. if (joint && joint->getID() == ancestor)
  1778. {
  1779. // Success !
  1780. reach = chain_reach;
  1781. break;
  1782. }
  1783. }
  1784. }
  1785. if (swapped)
  1786. {
  1787. reach = - reach;
  1788. }
  1789. return reach;
  1790. }
  1791. void Solver::addJoint(S16 joint_id, S16 parent_id, LLJoint* joint_info,
  1792. const Constraint::ptr_t& constraint)
  1793. {
  1794. if (!joint_info)
  1795. {
  1796. llwarns_sparse << "Cannot add with NULL joint info." << llendl;
  1797. return;
  1798. }
  1799. // Note: parent Joints must be added BEFORE their children.
  1800. if (joint_id < 0)
  1801. {
  1802. llwarns << "Failed to add invalid joint_id=" << joint_id << llendl;
  1803. return;
  1804. }
  1805. joint_map_t::iterator itr = mSkeleton.find(joint_id);
  1806. if (itr != mSkeleton.end())
  1807. {
  1808. llwarns << "Failed to add joint_id=" << joint_id << ": already exists"
  1809. << llendl;
  1810. return;
  1811. }
  1812. Joint::ptr_t parent;
  1813. itr = mSkeleton.find(parent_id);
  1814. if (itr == mSkeleton.end())
  1815. {
  1816. if (parent_id >= mRootID)
  1817. {
  1818. llwarns << "failed to add joint_id=" << joint_id
  1819. << ": could not find parent_id=" << parent_id << llendl;
  1820. return;
  1821. }
  1822. }
  1823. else
  1824. {
  1825. parent = itr->second;
  1826. }
  1827. Joint::ptr_t joint = std::make_shared<Joint>(joint_info);
  1828. joint->setParent(parent);
  1829. if (parent)
  1830. {
  1831. parent->addChild(joint);
  1832. }
  1833. mSkeleton.emplace(joint_id, joint);
  1834. joint->setConstraint(constraint);
  1835. }
  1836. void Solver::addWristID(S16 wrist_id)
  1837. {
  1838. auto joint_itr = mSkeleton.find(wrist_id);
  1839. if (joint_itr == mSkeleton.end())
  1840. {
  1841. llwarns << "Failed to find wrist_id=" << wrist_id << llendl;
  1842. return;
  1843. }
  1844. mWristJoints.push_back(joint_itr->second);
  1845. }
  1846. #if LLIK_EXPERIMENTAL
  1847. void Solver::adjustTargets(joint_config_map_t& targets)
  1848. {
  1849. // When an end-effector has both target_position and target_orientation
  1850. // the IK problem can be reduced by giving the parent a target_position.
  1851. // We scan targets for such conditions and when found: add/update the
  1852. // parent's Target with target_position.
  1853. for (auto& data_pair : targets)
  1854. {
  1855. Joint::Config& target = data_pair.second;
  1856. U8 mask = target.getFlags();
  1857. if (!target.hasWorldPos() || target.hasLocalRot() ||
  1858. !target.hasWorldRot())
  1859. {
  1860. // Target does not match our needs
  1861. continue;
  1862. }
  1863. S16 id = data_pair.first;
  1864. auto joint_itr = mSkeleton.find(id);
  1865. if (joint_itr == mSkeleton.end())
  1866. {
  1867. // Joint does not exist
  1868. continue;
  1869. }
  1870. Joint::ptr_t& joint = joint_itr->second;
  1871. const Joint::ptr_t& parent = joint->getParent();
  1872. if (!parent)
  1873. {
  1874. // No parent
  1875. continue;
  1876. }
  1877. // Compute parent's target pos. Note: we assume joint->mLocalPos ==
  1878. // parent_joint->mBone (e.g. parent's end is same position as joint's
  1879. // tip) which is not true in general, but is true for elbow->wrist.
  1880. LLVector3 parent_target_pos = target.getPos() -
  1881. joint->getBone() * target.getRot();
  1882. auto parent_target_itr = targets.find(parent->getID());
  1883. if (parent_target_itr != targets.end())
  1884. {
  1885. // parent already has a target --> modify it
  1886. parent_target_itr->second.setPos(parent_target_pos);
  1887. }
  1888. else
  1889. {
  1890. // Parent does not have a target yet, so give it one.
  1891. Joint::Config parent_target;
  1892. parent_target.setPos(parent_target_pos);
  1893. targets.insert({parent->getID(), parent_target});
  1894. }
  1895. // Delegate joint's target but set the joint active. The joint's world
  1896. // transform will be updated during the IK iterations after all chains
  1897. // have been processed.
  1898. target.delegate();
  1899. joint->activate();
  1900. }
  1901. }
  1902. #endif // LLIK_EXPERIMENTAL
  1903. // The Skeleton relaxes toward the T-pose and the IK solution will tend to put
  1904. // the elbows higher than normal for a humanoid character. The dropElbow()
  1905. // method tries to orient the elbows lower to achieve a more natural pose.
  1906. void Solver::dropElbow(const Joint::ptr_t& wrist_joint)
  1907. {
  1908. const Joint::ptr_t& elbow_joint = wrist_joint->getParent();
  1909. const Joint::ptr_t& shoulder_joint = elbow_joint->getParent();
  1910. if (shoulder_joint->hasPosTarget())
  1911. {
  1912. // Remember: end-of-shoulder is tip-of-elbow. Assume whoever is setting
  1913. // the shoulder's target position knows what they are doing.
  1914. return;
  1915. }
  1916. // Compute some geometry
  1917. LLVector3 shoulder_tip = shoulder_joint->getWorldTipPos();
  1918. LLVector3 elbow_tip = elbow_joint->getWorldTipPos();
  1919. LLVector3 elbow_end = elbow_joint->computeWorldEndPos();
  1920. LLVector3 axis = elbow_end - shoulder_tip;
  1921. axis.normalize();
  1922. // Compute rotation of shoulder to bring upper-arm down
  1923. LLVector3 down = (LLVector3::z_axis % axis) % axis;
  1924. LLVector3 shoulder_bone = elbow_tip - shoulder_tip;
  1925. LLVector3 projection = shoulder_bone - (shoulder_bone * axis) * axis;
  1926. LLQuaternion adjustment;
  1927. adjustment.shortestArc(projection, down);
  1928. // Adjust shoulder to bring upper-arm down
  1929. shoulder_joint->adjustWorldRot(adjustment);
  1930. // elbow_joint's mLocalRot remains unchanged, but we need to update its
  1931. // world-frame transforms
  1932. elbow_joint->updatePosAndRotFromParent();
  1933. if (wrist_joint->isActive())
  1934. {
  1935. // In theory: only wrist_joint's mLocalRot has changed, not its
  1936. // world-frame transform.
  1937. wrist_joint->updateLocalRot();
  1938. // *TODO ? Enforce twist of wrist's Constraint and back-rotate the
  1939. // elbow-drop to compensate
  1940. }
  1941. }
  1942. bool Solver::updateJointConfigs(const joint_config_map_t& configs)
  1943. {
  1944. bool something_changed = configs.size() != mJointConfigs.size();
  1945. // Check to see if configs changed since last iteration.
  1946. if (!something_changed)
  1947. {
  1948. for (const auto& data_pair : mJointConfigs)
  1949. {
  1950. joint_config_map_t::const_iterator itr =
  1951. configs.find(data_pair.first);
  1952. if (itr == configs.end())
  1953. {
  1954. something_changed = true;
  1955. break;
  1956. }
  1957. // Found old target in current configs.
  1958. const Joint::Config& old_target = data_pair.second;
  1959. const Joint::Config& new_target = itr->second;
  1960. U8 mask = old_target.getFlags();
  1961. if (mask != new_target.getFlags())
  1962. {
  1963. something_changed = true;
  1964. break;
  1965. }
  1966. if ((mask & CONFIG_FLAG_TARGET_POS) &&
  1967. dist_vec(old_target.getTargetPos(),
  1968. new_target.getTargetPos()) > mAcceptableError)
  1969. {
  1970. something_changed = true;
  1971. break;
  1972. }
  1973. if ((mask & CONFIG_FLAG_TARGET_ROT) &&
  1974. !LLQuaternion::almost_equal(old_target.getTargetRot(),
  1975. new_target.getTargetRot()))
  1976. {
  1977. something_changed = true;
  1978. break;
  1979. }
  1980. if ((mask & CONFIG_FLAG_LOCAL_POS) &&
  1981. dist_vec(old_target.getLocalPos(),
  1982. new_target.getLocalPos()) > mAcceptableError)
  1983. {
  1984. something_changed = true;
  1985. break;
  1986. }
  1987. if ((mask & CONFIG_FLAG_LOCAL_ROT) &&
  1988. !LLQuaternion::almost_equal(old_target.getLocalRot(),
  1989. new_target.getLocalRot()))
  1990. {
  1991. something_changed = true;
  1992. break;
  1993. }
  1994. }
  1995. }
  1996. if (something_changed)
  1997. {
  1998. mJointConfigs = configs;
  1999. }
  2000. return something_changed;
  2001. }
  2002. void Solver::rebuildAllChains()
  2003. {
  2004. // Before recompute chains: clear active status on old chains
  2005. for (const auto& data_pair : mChainMap)
  2006. {
  2007. const joint_list_t& chain = data_pair.second;
  2008. for (const Joint::ptr_t& joint : chain)
  2009. {
  2010. joint->resetFlags();
  2011. }
  2012. }
  2013. mChainMap.clear();
  2014. mActiveRoots.clear();
  2015. // makeChains
  2016. //
  2017. // Consider the following hypothetical skeleton, where each Joint tip
  2018. // has a numerical ID and each end-effector tip is denoted with
  2019. // bracketed [ID]:
  2020. // 8 [11]
  2021. // / /
  2022. // 7---14--[15] 10
  2023. // / /
  2024. // 6---12---13 9
  2025. // / /
  2026. // 0----1---2----3----4---[5]--16---17--[18]
  2027. // `
  2028. // 19
  2029. // `
  2030. // [20]
  2031. //
  2032. // The target ID list is: [5,11,15,18,20].
  2033. // IK would need to solve all joints except for [8,12,13].
  2034. // In other words: all Joints are "active" except [8,12,13].
  2035. //
  2036. // We divide the Skeleton into "chain segments" that start at a targeted
  2037. // Joint and continue up until: root (0), end-effector ([ID]), or
  2038. // sub-base (Joint with multiple children).
  2039. //
  2040. // Inward passes operate on the Chains in order such that when it is time
  2041. // to update a sub-base all of its active children will have already been
  2042. // updated: it will be able to compute the centroid of its mWorldEndPos.
  2043. //
  2044. // Outward passes also only operate on the Chains. This simplifies
  2045. // the logic because there will be no need to check for target or sub-base
  2046. // until the end of a Chain is reached. Any Joint not on a Chain (e.g.
  2047. // non-active) will keep its parent-relative rotation.
  2048. //
  2049. // The initial chain list would be:
  2050. // { 5:[5,4,3,2]
  2051. // 11:[11,10,9,5]
  2052. // 15:[15,14,7]
  2053. // 18:[18,17,16,5]
  2054. // 20:[20,19,2] }
  2055. // Where all chains include their end_point and also sub-base.
  2056. // The remaining active non-targeted sub_base_map would be:
  2057. // { 2:[2,1,0]
  2058. // 7:[7,6]
  2059. // 6:[6,2] }
  2060. // In this scenario Joints (6) and (7) are "false" sub-bases: they
  2061. // don't have targets and have multiple children but only one of them is "active".
  2062. // We can condense the chains to be:
  2063. // { 5:[5,4,3,2]
  2064. // 11:[11,10,9,5]
  2065. // 15:[15,14,7,6,2]
  2066. // 18:[18,17,16,5]
  2067. // 20:[20,19,2] }
  2068. // and:
  2069. // { 2:[2,1,0] }
  2070. //
  2071. std::set<S16> sub_bases;
  2072. // mJointConfigs is sorted by joint_id low-to-high and we rely on this in
  2073. // buildChain().
  2074. for (auto& data_pair : mJointConfigs)
  2075. {
  2076. // Make sure joint_id is valid
  2077. S16 joint_id = data_pair.first;
  2078. joint_map_t::iterator itr = mSkeleton.find(joint_id);
  2079. if (itr == mSkeleton.end())
  2080. {
  2081. continue;
  2082. }
  2083. Joint::ptr_t joint = itr->second;
  2084. // Joint caches a pointer to the Target and the Joint::Config will
  2085. // remain valid for the duration of the IK iterations.
  2086. Joint::Config& config = data_pair.second;
  2087. joint->setConfig(config);
  2088. if (joint->getID() == mRootID)
  2089. {
  2090. // For root world-frame == local-frame
  2091. U8 flags = joint->getConfigFlags();
  2092. if (flags & MASK_ROT)
  2093. {
  2094. LLQuaternion q =
  2095. (flags & CONFIG_FLAG_LOCAL_ROT) ? config.getLocalRot()
  2096. : config.getTargetRot();
  2097. joint->lockLocalRot(q);
  2098. joint->activate();
  2099. mActiveRoots.insert(joint);
  2100. }
  2101. if (flags & MASK_POS)
  2102. {
  2103. LLVector3 p =
  2104. (flags & CONFIG_FLAG_LOCAL_POS) ? config.getLocalPos()
  2105. : config.getTargetPos();
  2106. joint->setLocalPos(p);
  2107. joint->activate();
  2108. }
  2109. if (flags & CONFIG_FLAG_LOCAL_SCALE)
  2110. {
  2111. joint->setLocalScale(config.getLocalScale());
  2112. }
  2113. continue;
  2114. }
  2115. if (config.hasLocalRot())
  2116. {
  2117. joint->lockLocalRot(config.getLocalRot());
  2118. }
  2119. #if LLIK_EXPERIMENTAL
  2120. if (config.hasDelegated())
  2121. {
  2122. // Do not build chain for delegated Target
  2123. continue;
  2124. }
  2125. #endif
  2126. if (config.hasTargetPos())
  2127. {
  2128. // Add and build chain
  2129. mChainMap[joint_id] = joint_list_t();
  2130. buildChain(joint, mChainMap[joint_id], sub_bases);
  2131. // *HACK or FIX ? If we have sequential end effectors, we are not
  2132. // guaranteed the expression module has sent us positions that can
  2133. // be solved. We will instead assume that the child's position is
  2134. // higher prioriy than the parent, get direction from child to
  2135. // parent and move the parent's target to the exact bone length.
  2136. // *TODO: will not work correctly for a parent with multiple direct
  2137. // children with effector targets. Because we create the targets
  2138. // form low to high we will know if the parent is an end-effector.
  2139. Joint::ptr_t parent = joint->getParent();
  2140. if (parent->hasPosTarget())
  2141. {
  2142. // Sequential targets detected
  2143. LLVector3 child_target_pos = config.getTargetPos();
  2144. LLVector3 parent_target_pos = parent->getTargetPos();
  2145. LLVector3 direction = parent_target_pos - child_target_pos;
  2146. direction.normalize();
  2147. direction *= joint->getLocalPosLength();
  2148. parent_target_pos = child_target_pos + direction;
  2149. parent->setTargetPos(parent_target_pos);
  2150. }
  2151. }
  2152. else if (config.hasLocalPos())
  2153. {
  2154. joint->setLocalPos(config.getLocalPos());
  2155. joint->activate();
  2156. }
  2157. if (config.hasLocalScale())
  2158. {
  2159. joint->setLocalScale(config.getLocalScale());
  2160. joint->activate();
  2161. }
  2162. }
  2163. // Each sub_base gets its own Chain
  2164. while (sub_bases.size() > 0)
  2165. {
  2166. std::set<S16> new_sub_bases;
  2167. for (S16 joint_id : sub_bases)
  2168. {
  2169. // Add and build chain
  2170. Joint::ptr_t joint = mSkeleton[joint_id];
  2171. mChainMap[joint_id] = joint_list_t();
  2172. buildChain(joint, mChainMap[joint_id], new_sub_bases);
  2173. }
  2174. sub_bases = std::move(new_sub_bases);
  2175. }
  2176. // Eliminate "false" sub-bases and condense the Chains; search for
  2177. // Chain-joins.
  2178. std::vector<U16> joins;
  2179. for (const auto& data_pair : mChainMap)
  2180. {
  2181. const Joint::ptr_t& outer_end = data_pair.second[0];
  2182. if (!outer_end->hasPosTarget() && !isSubBase(outer_end->getID()))
  2183. {
  2184. Joint::ptr_t active_child = outer_end->getSingleActiveChild();
  2185. if (active_child)
  2186. {
  2187. // outer_end does not have a target, is not flagged as subbase,
  2188. // and has only one active_child --> it is a "false" sub-base
  2189. // and we will try to "join" this Chain to another.
  2190. joins.push_back(outer_end->getID());
  2191. }
  2192. }
  2193. }
  2194. // Make the joins
  2195. for (U16 id : joins)
  2196. {
  2197. // Hunt for recipient chain
  2198. for (auto& data_pair : mChainMap)
  2199. {
  2200. auto& recipient = data_pair.second;
  2201. const Joint::ptr_t& inner_end = recipient[recipient.size() - 1];
  2202. if (inner_end->getID() == id)
  2203. {
  2204. // Copy donor to recipient
  2205. const auto& donor = mChainMap[id];
  2206. recipient.insert(recipient.end(), ++(donor.begin()),
  2207. donor.end());
  2208. // Erase donor
  2209. mChainMap.erase(id);
  2210. break;
  2211. }
  2212. }
  2213. }
  2214. // Cache the set of active branch roots
  2215. for (auto& data_pair : mChainMap)
  2216. {
  2217. auto& chain = data_pair.second;
  2218. size_t last_index = chain.size() - 1;
  2219. Joint::ptr_t chain_base = chain[last_index];
  2220. Joint::ptr_t parent = chain_base->getParent();
  2221. if (!parent || !parent->isActive())
  2222. {
  2223. mActiveRoots.insert(chain_base);
  2224. }
  2225. }
  2226. // Cache the list of all active joints
  2227. mActiveJoints.clear();
  2228. for (auto& data_pair : mSkeleton)
  2229. {
  2230. if (data_pair.second->isActive())
  2231. {
  2232. mActiveJoints.push_back(data_pair.second);
  2233. data_pair.second->flagForHarvest();
  2234. }
  2235. }
  2236. }
  2237. ////////////////////////////////////// Solvers ////////////////////////////////
  2238. F32 Solver::solve()
  2239. {
  2240. rebuildAllChains();
  2241. // Before each solve: we relax a fraction toward the reset pose. This
  2242. // provides return pressure that removes floating-point drift that would
  2243. // otherwise wander around within the valid zones of the constraints.
  2244. constexpr F32 INITIAL_RELAXATION_FACTOR = 0.25f;
  2245. for (auto& root : mActiveRoots)
  2246. {
  2247. root->relaxRotationsRecursively(INITIAL_RELAXATION_FACTOR);
  2248. }
  2249. constexpr U32 MAX_FABRIK_ITERATIONS = 16;
  2250. constexpr U32 MIN_FABRIK_ITERATIONS = 4;
  2251. F32 max_error = F32_MAX;
  2252. for (U32 loop = 0;
  2253. loop < MIN_FABRIK_ITERATIONS ||
  2254. (loop < MAX_FABRIK_ITERATIONS && max_error > mAcceptableError);
  2255. ++loop)
  2256. {
  2257. max_error = solveOnce();
  2258. }
  2259. mLastError = max_error;
  2260. return mLastError;
  2261. }
  2262. F32 Solver::solveOnce()
  2263. {
  2264. constexpr bool constrain = true;
  2265. constexpr bool drop_elbow = true;
  2266. constexpr bool untwist = true;
  2267. #if LLIK_EXPERIMENTAL
  2268. executeCcd(constrain, drop_elbow, untwist);
  2269. #endif
  2270. executeFabrik(constrain, drop_elbow, untwist);
  2271. return measureMaxError();
  2272. }
  2273. void Solver::executeFabrik(bool constrain, bool drop_elbow, bool untwist)
  2274. {
  2275. executeFabrikPass();
  2276. // Pull elbows downward toward a more natual pose
  2277. for (const auto& wrist_joint : mWristJoints)
  2278. {
  2279. dropElbow(wrist_joint);
  2280. }
  2281. if (!constrain)
  2282. {
  2283. return;
  2284. }
  2285. // Since our FABRIK implementation does not enforce constraints during the
  2286. // forward/backward passes, we do it here.
  2287. enforceConstraintsOutward();
  2288. if (!untwist)
  2289. {
  2290. return;
  2291. }
  2292. // It is often possible to remove excess twist between the Joints without
  2293. // swinging their bones in the world-frame. We try this now to help reduce
  2294. // the "spin drift" that can occur where Joint orientations pick up
  2295. // systematic and floating-point errors and drift within the twist-limits
  2296. // of their constraints.
  2297. for (const auto& data_pair : mChainMap)
  2298. {
  2299. const joint_list_t& chain = data_pair.second;
  2300. untwistChain(chain);
  2301. }
  2302. executeFabrikPass();
  2303. // Note: we do not bother enforcing constraints after untwisting.
  2304. }
  2305. LLVector3 Solver::getJointLocalPos(S16 joint_id) const
  2306. {
  2307. LLVector3 pos;
  2308. auto itr = mSkeleton.find(joint_id);
  2309. if (itr != mSkeleton.end())
  2310. {
  2311. pos = itr->second->getLocalPos();
  2312. }
  2313. return pos;
  2314. }
  2315. bool Solver::getJointLocalTransform(S16 joint_id, LLVector3& pos,
  2316. LLQuaternion& rot) const
  2317. {
  2318. auto itr = mSkeleton.find(joint_id);
  2319. if (itr == mSkeleton.end())
  2320. {
  2321. return false;
  2322. }
  2323. pos = itr->second->getLocalPos();
  2324. rot = itr->second->getLocalRot();
  2325. return true;
  2326. }
  2327. LLVector3 Solver::getJointWorldEndPos(S16 joint_id) const
  2328. {
  2329. LLVector3 pos;
  2330. joint_map_t::const_iterator itr = mSkeleton.find(joint_id);
  2331. if (itr != mSkeleton.end())
  2332. {
  2333. pos = itr->second->computeWorldEndPos();
  2334. }
  2335. return pos;
  2336. }
  2337. LLQuaternion Solver::getJointWorldRot(S16 joint_id) const
  2338. {
  2339. LLQuaternion rot;
  2340. joint_map_t::const_iterator itr = mSkeleton.find(joint_id);
  2341. if (itr != mSkeleton.end())
  2342. {
  2343. rot = itr->second->getWorldRot();
  2344. }
  2345. return rot;
  2346. }
  2347. void Solver::resetJointGeometry(S16 joint_id,
  2348. const Constraint::ptr_t& constraint)
  2349. {
  2350. joint_map_t::iterator itr = mSkeleton.find(joint_id);
  2351. if (itr == mSkeleton.end())
  2352. {
  2353. llwarns << "Failed update unknown joint_id=" << joint_id << llendl;
  2354. return;
  2355. }
  2356. const Joint::ptr_t& joint = itr->second;
  2357. joint->resetFromInfo();
  2358. joint->setConstraint(constraint);
  2359. // Note: will need to call computeReach() after all Joints geometries are
  2360. // reset.
  2361. }
  2362. void Solver::buildChain(Joint::ptr_t joint, joint_list_t& chain,
  2363. std::set<S16>& sub_bases)
  2364. {
  2365. // Builds a Chain in descending order (inward) from end-effector or sub-
  2366. // base. Stops at next end-effector (has target), sub-base (more than one
  2367. // active child), or root. Side effect: sets each Joint on chain "active".
  2368. chain.push_back(joint);
  2369. joint->activate();
  2370. // Walk up the chain of ancestors and add to chain but stop at: end-effector,
  2371. // sub-base, or root. When a sub-base is encountered push its id onto
  2372. // sub_bases.
  2373. joint = joint->getParent();
  2374. while (joint)
  2375. {
  2376. chain.push_back(joint);
  2377. joint->activate();
  2378. S16 joint_id = joint->getID();
  2379. // Yes, add the joint to the chain before the break checks below
  2380. // because we want to include the final joint (e.g. root, sub-base, or
  2381. // previously targeted joint) at the end of the chain.
  2382. if (isSubRoot(joint_id))
  2383. {
  2384. // AURA hack to deal with lack of constraints in spine
  2385. break;
  2386. }
  2387. if (joint_id == mRootID)
  2388. {
  2389. break;
  2390. }
  2391. if (joint->hasPosTarget())
  2392. {
  2393. // Truncate this chain at targeted ancestor joint
  2394. break;
  2395. }
  2396. if ((mSubBaseIds.empty() && joint->getNumChildren() > 1) ||
  2397. isSubBase(joint_id))
  2398. {
  2399. sub_bases.insert(joint_id);
  2400. break;
  2401. }
  2402. joint = joint->getParent();
  2403. }
  2404. }
  2405. void Solver::executeFabrikInward(const joint_list_t& chain)
  2406. {
  2407. // Chain starts at end-effector or sub-base. Do not forget: chain is
  2408. // organized in descending order: for inward pass we traverse the chain
  2409. // forward.
  2410. // Outer end of chain is special: it either has a target or is a sub-base
  2411. // with active children
  2412. chain[0]->updateEndInward();
  2413. // Traverse Chain forward. Skip first Joint in chain (the "outer end"): we
  2414. // just handled it. Also skip last Joint in chain (the "inner end"): it is
  2415. // either the outer end of another chain (and will be updated then) or it
  2416. // is one of the "active roots" and will be handled after all chains.
  2417. S32 last_index = (S32)(chain.size()) - 1;
  2418. for (S32 i = 1; i < last_index; ++i)
  2419. {
  2420. chain[i]->updateInward(chain[i - 1]);
  2421. }
  2422. }
  2423. void Solver::executeFabrikOutward(const joint_list_t& chain)
  2424. {
  2425. // Chain starts at a end-effector or sub-base. Do not forget: chain is
  2426. // organized in descending order: for outward pass we traverse the chain
  2427. // in reverse.
  2428. S32 last_index = (S32)(chain.size()) - 1;
  2429. // Skip the Joint at last_index: chain's inner-end does not move at this
  2430. // stage. Traverse the middle of chain in reverse
  2431. for (S32 i = last_index - 1; i > 0; --i)
  2432. {
  2433. chain[i]->updateOutward();
  2434. }
  2435. // Outer end of chain is special: it either has a target or is a sub-base
  2436. // with active children
  2437. chain[0]->updateEndOutward();
  2438. }
  2439. void Solver::shiftChainToBase(const joint_list_t& chain)
  2440. {
  2441. size_t last_index = (S32)(chain.size()) - 1;
  2442. const Joint::ptr_t& inner_end_child = chain[last_index - 1];
  2443. LLVector3 offset = inner_end_child->computeWorldTipOffset();
  2444. if (offset.lengthSquared() > mAcceptableError * mAcceptableError)
  2445. {
  2446. for (size_t i = 0; i < last_index; ++i)
  2447. {
  2448. chain[i]->shiftPos(-offset);
  2449. }
  2450. }
  2451. }
  2452. void Solver::executeFabrikPass()
  2453. {
  2454. // FABRIK = Forward And Backward Reching Inverse Kinematics
  2455. // http://andreasaristidou.com/FABRIK.html
  2456. // mChainMap is sorted by outer_end joint_id, low-to-high so for the inward
  2457. // pass we traverse the chains in reverse order.
  2458. for (chain_map_t::const_reverse_iterator itr = mChainMap.rbegin(),
  2459. rend = mChainMap.rend();
  2460. itr != rend; ++itr)
  2461. {
  2462. executeFabrikInward(itr->second);
  2463. }
  2464. // executeFabrikInward() does not update child mLocalRots for the inner_end
  2465. // so we must do it manually for each active root
  2466. for (auto& root : mActiveRoots)
  2467. {
  2468. root->updateChildLocalRots();
  2469. }
  2470. // The outward pass must solve the combined set of chains from-low-to-high
  2471. // so we process them in forward order.
  2472. for (const auto& data_pair : mChainMap)
  2473. {
  2474. const joint_list_t& chain = data_pair.second;
  2475. executeFabrikOutward(chain);
  2476. }
  2477. }
  2478. void Solver::enforceConstraintsOutward()
  2479. {
  2480. for (const auto& data_pair : mChainMap)
  2481. {
  2482. const joint_list_t& chain = data_pair.second;
  2483. // Chain starts at a end-effector or sub-base. Do not forget: chain is
  2484. // organized in descending order: for outward pass we traverse the
  2485. // chain in reverse.
  2486. S32 last_index = (S32)(chain.size()) - 1;
  2487. // Skip the Joint at last_index: chain's inner-end does not move at
  2488. // this stage. Traverse the middle of chain in reverse.
  2489. for (S32 i = last_index - 1; i > -1; --i)
  2490. {
  2491. const Joint::ptr_t& joint = chain[i];
  2492. joint->updatePosAndRotFromParent();
  2493. if (joint->enforceConstraint())
  2494. {
  2495. joint->applyLocalRot();
  2496. }
  2497. }
  2498. chain[0]->updateChildLocalRots();
  2499. }
  2500. }
  2501. #if LLIK_EXPERIMENTAL
  2502. void Solver::executeCcd(bool constrain, bool drop_elbow, bool untwist)
  2503. {
  2504. // *TODO:
  2505. // - modify executeCcdPass() to handle enforce_constraints;
  2506. // - handle drop_elbow before CCD pass;
  2507. // - handle untwist ?
  2508. executeCcdPass(constrain);
  2509. }
  2510. // Cyclic Coordinate Descend (CCD) is an alternative IK algorithm.
  2511. // http://rodolphe-vaillant.fr/entry/114/cyclic-coordonate-descent-inverse-kynematic-ccd-ik
  2512. //
  2513. // It converges well however is more susceptible than FABRIK to solution
  2514. // instability when Constraints are being enforced. We keep it around just in
  2515. // case we want to try it, or for when we figure out how to enforce Constraints
  2516. // without making CCD unstable.
  2517. void Solver::executeCcdPass(bool constrain)
  2518. {
  2519. // mChainMap is sorted by outer_end joint_id, low-to-high and CCD is an
  2520. // inward pass, so we traverse the map in reverse
  2521. for (chain_map_t::const_reverse_iterator itr = mChainMap.rbegin(),
  2522. rend = mChainMap.rend();
  2523. itr != rend; ++itr)
  2524. {
  2525. executeCcdInward(itr->second, constrain);
  2526. }
  2527. // executeCcdInward(chain) recomputes world-frame transform of all Joints
  2528. // in chain... except the child of the chain's inner_end. Now that all
  2529. // chains are solved we shift each chain to connect with its sub-base.
  2530. for (auto& data_pair: mChainMap)
  2531. {
  2532. shiftChainToBase(data_pair.second);
  2533. }
  2534. }
  2535. void Solver::executeCcdInward(const joint_list_t& chain, bool constrain)
  2536. {
  2537. // 'chain' starts at a end-effector or sub-base. Do not forget: 'chain' is
  2538. // organized in descending order: for inward pass we traverse the Chain
  2539. // forward.
  2540. const Joint::ptr_t& outer_end = chain[0];
  2541. // outer_end has one or more targets known in both local and world frames.
  2542. // For CCD we'll be swinging each joint of the Chain as we traverse inward
  2543. // in attempts to get the local-frame targets to align with their world-
  2544. //frame counterparts.
  2545. std::vector<LLVector3> local_targets, world_targets;
  2546. outer_end->collectTargetPositions(local_targets, world_targets);
  2547. if (!outer_end->swingTowardTargets(local_targets, world_targets))
  2548. {
  2549. // Targets are close enough
  2550. return;
  2551. }
  2552. // Traverse Chain forward and swing each part. Skip first Joint in 'chain'
  2553. // (the "outer end"): we just handled it. Also skip last Joint in 'chain'
  2554. // (the "inner end"): it is either the outer end of another Chain (and will
  2555. // be updated as part of a subsequent Chain) or it is one of the "active
  2556. // roots" and is not moved.
  2557. S32 last_index = (S32)(chain.size()) - 1;
  2558. S32 last_swung_index = 0;
  2559. for (S32 i = 1; i < last_index; ++i)
  2560. {
  2561. chain[i - 1]->transformTargetsToParentLocal(local_targets);
  2562. if (!chain[i]->swingTowardTargets(local_targets, world_targets))
  2563. {
  2564. break;
  2565. }
  2566. last_swung_index = i;
  2567. }
  2568. // Update the world-frame transforms of swung Joints
  2569. for (S32 i = last_swung_index - 1; i > -1; --i)
  2570. {
  2571. chain[i]->updatePosAndRotFromParent();
  2572. }
  2573. // Finally: make sure to update outer_end's childrens' mLocalRots. Note: we
  2574. // do not bother to enforce constraints in this step.
  2575. outer_end->updateChildLocalRots();
  2576. }
  2577. #endif // LLIK_EXPERIMENTAL
  2578. void Solver::untwistChain(const joint_list_t& chain)
  2579. {
  2580. S32 last_index = (S32)(chain.size()) - 1;
  2581. // Note: we start at last_index-1 becuase Joint::untwist() will affect its
  2582. // parent's twist and we don't want to mess with the inner_end of the chain
  2583. // since it will be handled later in another chain.
  2584. for (S32 i = last_index - 1; i > -1; --i)
  2585. {
  2586. chain[i]->untwist();
  2587. }
  2588. chain[0]->updateChildLocalRots();
  2589. }
  2590. F32 Solver::measureMaxError()
  2591. {
  2592. F32 max_error = 0.f;
  2593. for (auto& data_pair : mJointConfigs)
  2594. {
  2595. S16 joint_id = data_pair.first;
  2596. if (joint_id == mRootID)
  2597. {
  2598. // Skip error measure of root joint: should always be zero.
  2599. continue;
  2600. }
  2601. Joint::Config& target = data_pair.second;
  2602. #if LLIK_EXPERIMENTAL
  2603. if (target.hasTargetPos() && !target.hasDelegated())
  2604. #else
  2605. if (target.hasTargetPos())
  2606. #endif
  2607. {
  2608. LLVector3 end_pos = mSkeleton[joint_id]->computeWorldEndPos();
  2609. F32 dist = dist_vec(end_pos, target.getTargetPos());
  2610. if (dist > max_error)
  2611. {
  2612. max_error = dist;
  2613. }
  2614. }
  2615. }
  2616. return max_error;
  2617. }
  2618. } // namespace LLIK
  2619. ///////////////////////////////////////////////////////////////////////////////
  2620. // LLIKConstraintFactory class
  2621. ///////////////////////////////////////////////////////////////////////////////
  2622. void LLIKConstraintFactory::initSingleton()
  2623. {
  2624. std::string filename =
  2625. gDirUtil.getFullPath(LL_PATH_CHARACTER, "avatar_constraint.llsd");
  2626. llifstream file(filename.c_str());
  2627. if (!file.is_open())
  2628. {
  2629. llwarns << "Error opening the IK constraints file: " << filename
  2630. << llendl;
  2631. return;
  2632. }
  2633. LLSD map;
  2634. if (!LLSDSerialize::deserialize(map, file, LLSDSerialize::SIZE_UNLIMITED))
  2635. {
  2636. llwarns << "Unable to load and parse IK constraints from: " << filename
  2637. << llendl;
  2638. return;
  2639. }
  2640. for (LLSD::map_const_iterator it = map.beginMap(), end = map.endMap();
  2641. it != end; ++it)
  2642. {
  2643. const std::string& joint_name = it->first;
  2644. const LLSD& data = it->second;
  2645. LLIK::Constraint::ptr_t ptr = getConstraint(data);
  2646. if (ptr)
  2647. {
  2648. mJointMapping.emplace(joint_name, ptr);
  2649. }
  2650. }
  2651. }
  2652. LLIK::Constraint::ptr_t
  2653. LLIKConstraintFactory::getConstrForJoint(const std::string& joint_name) const
  2654. {
  2655. auto it = mJointMapping.find(joint_name);
  2656. return it != mJointMapping.end() ? it->second : LLIK::Constraint::ptr_t();
  2657. }
  2658. LLIK::Constraint::ptr_t LLIKConstraintFactory::getConstraint(const LLSD& data)
  2659. {
  2660. LLIK::Constraint::ptr_t ptr = create(data);
  2661. if (ptr)
  2662. {
  2663. U64 hash = ptr->getHash();
  2664. auto it = mConstraints.find(hash);
  2665. if (it != mConstraints.end())
  2666. {
  2667. ptr = it->second;
  2668. }
  2669. else
  2670. {
  2671. mConstraints[hash] = ptr;
  2672. }
  2673. }
  2674. return ptr;
  2675. }
  2676. //static
  2677. LLIK::Constraint::ptr_t LLIKConstraintFactory::create(const LLSD& data)
  2678. {
  2679. std::string type = data["type"].asString();
  2680. LLStringUtil::toUpper(type);
  2681. LLIK::Constraint::ptr_t ptr;
  2682. if (type == SIMPLE_CONE_NAME)
  2683. {
  2684. ptr = std::make_shared<LLIK::SimpleCone>(data);
  2685. }
  2686. else if (type == TWIST_LIMITED_CONE_NAME)
  2687. {
  2688. ptr = std::make_shared<LLIK::TwistLimitedCone>(data);
  2689. }
  2690. else if (type == ELBOW_NAME)
  2691. {
  2692. ptr = std::make_shared<LLIK::ElbowConstraint>(data);
  2693. }
  2694. else if (type == KNEE_NAME)
  2695. {
  2696. ptr = std::make_shared<LLIK::KneeConstraint>(data);
  2697. }
  2698. else if (type == ACUTE_ELLIPSOIDAL_NAME)
  2699. {
  2700. ptr = std::make_shared<LLIK::AcuteEllipsoidalCone>(data);
  2701. }
  2702. else if (type == DOUBLE_LIMITED_HINGE_NAME)
  2703. {
  2704. ptr = std::make_shared<LLIK::DoubleLimitedHinge>(data);
  2705. }
  2706. return ptr;
  2707. }