llbvhloader.cpp 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551
  1. /**
  2. * @file llbvhloader.cpp
  3. * @brief Translates a BVH files to LindenLabAnimation format.
  4. *
  5. * $LicenseInfo:firstyear=2004&license=viewergpl$
  6. *
  7. * Copyright (c) 2004-2009, 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 "linden_common.h"
  33. #include <deque>
  34. #include "boost/lexical_cast.hpp"
  35. #include "boost/tokenizer.hpp"
  36. #include "llbvhloader.h"
  37. #include "lldatapacker.h"
  38. #include "lldir.h"
  39. #include "llkeyframemotion.h"
  40. #include "llquantize.h"
  41. #include "llsdserialize.h"
  42. #include "llstl.h"
  43. using namespace std;
  44. // The .bvh does not have a formal spec, and different readers interpret things
  45. // in their own way. In OUR usage, frame 0 is used in optimization and is not
  46. // considered to be part of the animation.
  47. constexpr S32 NUMBER_OF_IGNORED_FRAMES_AT_START = 1;
  48. // In our usage, the last frame is used only to indicate what the penultimate
  49. // frame should be interpolated towards. I.e. the animation only plays up to
  50. // the start of the last frame. There is no hold or exptrapolation past that
  51. // point. Thus there are two frame of the total that do not contribute to the
  52. // total running time of the animation.
  53. constexpr S32 NUMBER_OF_UNPLAYED_FRAMES = 2;
  54. constexpr F32 POSITION_KEYFRAME_THRESHOLD_SQUARED = 0.03f * 0.03f;
  55. constexpr F32 ROTATION_KEYFRAME_THRESHOLD = 0.01f;
  56. constexpr F32 POSITION_MOTION_THRESHOLD_SQUARED = 0.001f * 0.001f;
  57. constexpr F32 ROTATION_MOTION_THRESHOLD = 0.001f;
  58. char gInFile[1024];
  59. char gOutFile[1024];
  60. const char* find_next_whitespace(const char* p)
  61. {
  62. while (*p && isspace(*p)) ++p;
  63. while (*p && !isspace(*p)) ++p;
  64. return p;
  65. }
  66. // XYZ order in BVH files must be passed to mayaQ() as ZYX. This function
  67. // reverses the input string before passing it on to StringToOrder().
  68. LLQuaternion::Order bvh_str_to_order(char* str)
  69. {
  70. char order[4];
  71. order[0] = str[2];
  72. order[1] = str[1];
  73. order[2] = str[0];
  74. order[3] = '\0';
  75. LLQuaternion::Order ret = StringToOrder(order);
  76. return ret;
  77. }
  78. LLBVHLoader::LLBVHLoader(const char* buffer, ELoadStatus& load_status,
  79. S32& error_line,
  80. std::map<std::string, std::string>& joint_alias_map)
  81. {
  82. reset();
  83. error_line = 0;
  84. mStatus = loadTranslationTable("anim.ini");
  85. load_status = mStatus;
  86. llinfos << "Load Status 00 : "<< load_status << llendl;
  87. if (mStatus == E_ST_NO_XLT_FILE)
  88. {
  89. LL_DEBUGS("BVHLoader") << "No translation table found." << LL_ENDL;
  90. load_status = mStatus;
  91. return;
  92. }
  93. else if (mStatus != E_ST_OK)
  94. {
  95. LL_DEBUGS("BVHLoader") << "ERROR: [line: " << getLineNumber() << "] "
  96. << mStatus << LL_ENDL;
  97. error_line = getLineNumber();
  98. load_status = mStatus;
  99. return;
  100. }
  101. // Recognize all names we have been told are legal.
  102. for (std::map<std::string, std::string>::iterator
  103. iter = joint_alias_map.begin(), end = joint_alias_map.end();
  104. iter != end; ++iter)
  105. {
  106. makeTranslation(iter->first , iter->second);
  107. }
  108. char error_text[128];
  109. // Read all joints in BVH file.
  110. mStatus = loadBVHFile(buffer, error_text, error_line);
  111. LL_DEBUGS("BVHLoader") << "Raw data from file:";
  112. dumpBVHInfo();
  113. LL_CONT << LL_ENDL;
  114. if (mStatus != E_ST_OK)
  115. {
  116. LL_DEBUGS("BVHLoader") << "ERROR: [line: " << getLineNumber() << "] "
  117. << mStatus << LL_ENDL;
  118. load_status = mStatus;
  119. error_line = getLineNumber();
  120. return;
  121. }
  122. // Maps between joints found in file and the aliased names.
  123. applyTranslations();
  124. optimize();
  125. LL_DEBUGS("BVHLoader") << "After translations and optimize:";
  126. dumpBVHInfo();
  127. LL_CONT << LL_ENDL;
  128. mInitialized = true;
  129. error_line = 0;
  130. }
  131. LLBVHLoader::~LLBVHLoader()
  132. {
  133. std::for_each(mJoints.begin(), mJoints.end(), DeletePointer());
  134. mJoints.clear();
  135. }
  136. ELoadStatus LLBVHLoader::loadTranslationTable(const char* filename)
  137. {
  138. //--------------------------------------------------------------------
  139. // Open file
  140. //--------------------------------------------------------------------
  141. std::string path = gDirUtil.getFullPath(LL_PATH_APP_SETTINGS, filename);
  142. LLFile infile(path, "r");
  143. if (!infile)
  144. {
  145. return E_ST_NO_XLT_FILE;
  146. }
  147. llinfos << "Loading translation table: " << filename << llendl;
  148. //--------------------------------------------------------------------
  149. // Register file to be closed on function exit
  150. //--------------------------------------------------------------------
  151. //--------------------------------------------------------------------
  152. // Load header
  153. //--------------------------------------------------------------------
  154. if (!getLine(infile))
  155. {
  156. return E_ST_EOF;
  157. }
  158. if (strncmp(mLine, "Translations 1.0", 16))
  159. {
  160. return E_ST_NO_XLT_HEADER;
  161. }
  162. //--------------------------------------------------------------------
  163. // load data one line at a time
  164. //--------------------------------------------------------------------
  165. bool loadingGlobals = false;
  166. while (getLine(infile))
  167. {
  168. //----------------------------------------------------------------
  169. // Check the 1st token on the line to determine if it's empty or a
  170. // comment
  171. //----------------------------------------------------------------
  172. char token[128];
  173. if (sscanf(mLine, " %127s", token) != 1)
  174. {
  175. continue;
  176. }
  177. if (token[0] == '#')
  178. {
  179. continue;
  180. }
  181. //----------------------------------------------------------------
  182. // Check if a [jointName] or [GLOBALS] was specified.
  183. //----------------------------------------------------------------
  184. if (token[0] == '[')
  185. {
  186. char name[128];
  187. if (sscanf(mLine, " [%127[^]]", name) != 1)
  188. {
  189. return E_ST_NO_XLT_NAME;
  190. }
  191. if (strcmp(name, "GLOBALS") == 0)
  192. {
  193. loadingGlobals = true;
  194. continue;
  195. }
  196. }
  197. //----------------------------------------------------------------
  198. // Check for optional emote
  199. //----------------------------------------------------------------
  200. if (loadingGlobals &&
  201. LLStringUtil::compareInsensitive(token, "emote") == 0)
  202. {
  203. char emote_str[1024];
  204. if (sscanf(mLine, " %*s = %1023s", emote_str) != 1)
  205. {
  206. return E_ST_NO_XLT_EMOTE;
  207. }
  208. mEmoteName.assign(emote_str);
  209. LL_DEBUGS("BVHLoader") << "Emote: " << mEmoteName.c_str()
  210. << LL_ENDL;
  211. continue;
  212. }
  213. //----------------------------------------------------------------
  214. // Check for global priority setting
  215. //----------------------------------------------------------------
  216. if (loadingGlobals &&
  217. LLStringUtil::compareInsensitive(token, "priority") == 0)
  218. {
  219. S32 priority;
  220. if (sscanf(mLine, " %*s = %d", &priority) != 1)
  221. {
  222. return E_ST_NO_XLT_PRIORITY;
  223. }
  224. mPriority = priority;
  225. LL_DEBUGS("BVHLoader") << "Priority: " << mPriority << LL_ENDL;
  226. continue;
  227. }
  228. //----------------------------------------------------------------
  229. // Check for global loop setting
  230. //----------------------------------------------------------------
  231. if (loadingGlobals &&
  232. LLStringUtil::compareInsensitive(token, "loop") == 0)
  233. {
  234. char trueFalse[128];
  235. trueFalse[0] = '\0';
  236. F32 loop_in = 0.f;
  237. F32 loop_out = 1.f;
  238. if (sscanf(mLine, " %*s = %f %f", &loop_in, &loop_out) == 2)
  239. {
  240. mLoop = true;
  241. }
  242. else if (sscanf(mLine, " %*s = %127s", trueFalse) == 1)
  243. {
  244. mLoop = LLStringUtil::compareInsensitive(trueFalse, "true") == 0;
  245. }
  246. else
  247. {
  248. return E_ST_NO_XLT_LOOP;
  249. }
  250. mLoopInPoint = loop_in * mDuration;
  251. mLoopOutPoint = loop_out * mDuration;
  252. continue;
  253. }
  254. //----------------------------------------------------------------
  255. // Check for global easeIn setting
  256. //----------------------------------------------------------------
  257. if (loadingGlobals &&
  258. LLStringUtil::compareInsensitive(token, "easein") == 0)
  259. {
  260. F32 duration;
  261. char type[128];
  262. if (sscanf(mLine, " %*s = %f %127s", &duration, type) != 2)
  263. {
  264. return E_ST_NO_XLT_EASEIN;
  265. }
  266. mEaseIn = duration;
  267. continue;
  268. }
  269. //----------------------------------------------------------------
  270. // Check for global easeOut setting
  271. //----------------------------------------------------------------
  272. if (loadingGlobals &&
  273. LLStringUtil::compareInsensitive(token, "easeout") == 0)
  274. {
  275. F32 duration;
  276. char type[128];
  277. if (sscanf(mLine, " %*s = %f %127s", &duration, type) != 2)
  278. {
  279. return E_ST_NO_XLT_EASEOUT;
  280. }
  281. mEaseOut = duration;
  282. continue;
  283. }
  284. //----------------------------------------------------------------
  285. // Check for global handMorph setting
  286. //----------------------------------------------------------------
  287. if (loadingGlobals &&
  288. LLStringUtil::compareInsensitive(token, "hand") == 0)
  289. {
  290. S32 handMorph;
  291. if (sscanf(mLine, " %*s = %d", &handMorph) != 1)
  292. {
  293. return E_ST_NO_XLT_HAND;
  294. }
  295. mHand = handMorph;
  296. continue;
  297. }
  298. if (loadingGlobals &&
  299. LLStringUtil::compareInsensitive(token, "constraint") == 0)
  300. {
  301. Constraint constraint;
  302. // Try reading optional target direction
  303. if (sscanf(mLine,
  304. " %*s = %d %f %f %f %f %15s %f %f %f %15s %f %f %f %f %f %f",
  305. &constraint.mChainLength,
  306. &constraint.mEaseInStart,
  307. &constraint.mEaseInStop,
  308. &constraint.mEaseOutStart,
  309. &constraint.mEaseOutStop,
  310. constraint.mSourceJointName,
  311. &constraint.mSourceOffset.mV[VX],
  312. &constraint.mSourceOffset.mV[VY],
  313. &constraint.mSourceOffset.mV[VZ],
  314. constraint.mTargetJointName,
  315. &constraint.mTargetOffset.mV[VX],
  316. &constraint.mTargetOffset.mV[VY],
  317. &constraint.mTargetOffset.mV[VZ],
  318. &constraint.mTargetDir.mV[VX],
  319. &constraint.mTargetDir.mV[VY],
  320. &constraint.mTargetDir.mV[VZ]) != 16)
  321. {
  322. if (sscanf(mLine,
  323. " %*s = %d %f %f %f %f %15s %f %f %f %15s %f %f %f",
  324. &constraint.mChainLength,
  325. &constraint.mEaseInStart,
  326. &constraint.mEaseInStop,
  327. &constraint.mEaseOutStart,
  328. &constraint.mEaseOutStop,
  329. constraint.mSourceJointName,
  330. &constraint.mSourceOffset.mV[VX],
  331. &constraint.mSourceOffset.mV[VY],
  332. &constraint.mSourceOffset.mV[VZ],
  333. constraint.mTargetJointName,
  334. &constraint.mTargetOffset.mV[VX],
  335. &constraint.mTargetOffset.mV[VY],
  336. &constraint.mTargetOffset.mV[VZ]) != 13)
  337. {
  338. return E_ST_NO_CONSTRAINT;
  339. }
  340. }
  341. else if (!constraint.mTargetDir.isExactlyZero())
  342. {
  343. // Normalize direction
  344. constraint.mTargetDir.normalize();
  345. }
  346. constraint.mConstraintType = CONSTRAINT_TYPE_POINT;
  347. mConstraints.push_back(constraint);
  348. continue;
  349. }
  350. if (loadingGlobals &&
  351. LLStringUtil::compareInsensitive(token, "planar_constraint") == 0)
  352. {
  353. Constraint constraint;
  354. // Try reading optional target direction
  355. if (sscanf(mLine,
  356. " %*s = %d %f %f %f %f %15s %f %f %f %15s %f %f %f %f %f %f",
  357. &constraint.mChainLength,
  358. &constraint.mEaseInStart,
  359. &constraint.mEaseInStop,
  360. &constraint.mEaseOutStart,
  361. &constraint.mEaseOutStop,
  362. constraint.mSourceJointName,
  363. &constraint.mSourceOffset.mV[VX],
  364. &constraint.mSourceOffset.mV[VY],
  365. &constraint.mSourceOffset.mV[VZ],
  366. constraint.mTargetJointName,
  367. &constraint.mTargetOffset.mV[VX],
  368. &constraint.mTargetOffset.mV[VY],
  369. &constraint.mTargetOffset.mV[VZ],
  370. &constraint.mTargetDir.mV[VX],
  371. &constraint.mTargetDir.mV[VY],
  372. &constraint.mTargetDir.mV[VZ]) != 16)
  373. {
  374. if (sscanf(mLine,
  375. " %*s = %d %f %f %f %f %15s %f %f %f %15s %f %f %f",
  376. &constraint.mChainLength,
  377. &constraint.mEaseInStart,
  378. &constraint.mEaseInStop,
  379. &constraint.mEaseOutStart,
  380. &constraint.mEaseOutStop,
  381. constraint.mSourceJointName,
  382. &constraint.mSourceOffset.mV[VX],
  383. &constraint.mSourceOffset.mV[VY],
  384. &constraint.mSourceOffset.mV[VZ],
  385. constraint.mTargetJointName,
  386. &constraint.mTargetOffset.mV[VX],
  387. &constraint.mTargetOffset.mV[VY],
  388. &constraint.mTargetOffset.mV[VZ]) != 13)
  389. {
  390. return E_ST_NO_CONSTRAINT;
  391. }
  392. }
  393. else if (!constraint.mTargetDir.isExactlyZero())
  394. {
  395. // Normalize direction
  396. constraint.mTargetDir.normalize();
  397. }
  398. constraint.mConstraintType = CONSTRAINT_TYPE_PLANE;
  399. mConstraints.push_back(constraint);
  400. }
  401. }
  402. return E_ST_OK;
  403. }
  404. void LLBVHLoader::makeTranslation(const std::string& alias_name,
  405. const std::string& joint_name)
  406. {
  407. // This uses []'s implicit call to ctor.
  408. Translation& new_trans = mTranslations[alias_name];
  409. new_trans.mOutName = joint_name;
  410. if (joint_name == "mPelvis")
  411. {
  412. new_trans.mRelativePositionKey = true;
  413. new_trans.mRelativeRotationKey = true;
  414. }
  415. LLMatrix3 fm;
  416. LLVector3 vect1(0.f, 1.f, 0.f);
  417. LLVector3 vect2(0.f, 0.f, 1.f);
  418. LLVector3 vect3(1.f, 0.f, 0.f);
  419. fm.setRows(vect1, vect2, vect3);
  420. new_trans.mFrameMatrix = fm;
  421. }
  422. #if 0 // Not used
  423. ELoadStatus LLBVHLoader::loadAliases(const char* filename)
  424. {
  425. std::string path = gDirUtil.getFullPath(LL_PATH_APP_SETTINGS, filename);
  426. llifstream input_stream;
  427. input_stream.open(path.c_str(), std::ios::in | std::ios::binary);
  428. if (!input_stream.is_open())
  429. {
  430. llwarns << "Cannot open joint alias file " << path << llendl;
  431. return E_ST_NO_XLT_FILE;
  432. }
  433. LLSD aliases_sd;
  434. if (LLSDSerialize::fromXML(aliases_sd, input_stream))
  435. {
  436. for (LLSD::map_iterator it = aliases_sd.beginMap(),
  437. end = aliases_sd.endMap();
  438. it != end; ++it)
  439. {
  440. LLSD::String alias_name = it->first;
  441. LLSD::String joint_name = it->second;
  442. makeTranslation(alias_name, joint_name);
  443. }
  444. }
  445. else
  446. {
  447. input_stream.close();
  448. return E_ST_NO_XLT_HEADER;
  449. }
  450. input_stream.close();
  451. return E_ST_OK;
  452. }
  453. #endif
  454. void LLBVHLoader::dumpBVHInfo()
  455. {
  456. for (U32 j = 0, count = mJoints.size(); j < count; ++j)
  457. {
  458. Joint* joint = mJoints[j];
  459. LL_DEBUGS("BVHLoader") << "Joint: " << joint->mName << LL_ENDL;
  460. for (S32 i = 0, count = llmin(mNumFrames, (S32)joint->mKeys.size());
  461. i < count; ++i)
  462. {
  463. Key& prevkey = joint->mKeys[llmax(i - 1, 0)];
  464. Key& key = joint->mKeys[i];
  465. if (i == 0 ||
  466. key.mPos[0] != prevkey.mPos[0] ||
  467. key.mPos[1] != prevkey.mPos[1] ||
  468. key.mPos[2] != prevkey.mPos[2] ||
  469. key.mRot[0] != prevkey.mRot[0] ||
  470. key.mRot[1] != prevkey.mRot[1] ||
  471. key.mRot[2] != prevkey.mRot[2])
  472. {
  473. LL_DEBUGS("BVHLoader") << " Frame: " << i << " - Pos: "
  474. << key.mPos[0] << "," << key.mPos[1]
  475. << "," << key.mPos[2] << " - Rot: "
  476. << key.mRot[0] << "," << key.mRot[1]
  477. << "," << key.mRot[2] << LL_ENDL;
  478. }
  479. }
  480. }
  481. }
  482. ELoadStatus LLBVHLoader::loadBVHFile(const char* buffer, char* error_text,
  483. S32& err_line)
  484. {
  485. std::string line;
  486. err_line = 0;
  487. error_text[127] = '\0';
  488. std::string str(buffer);
  489. typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
  490. boost::char_separator<char> sep("\r\n");
  491. tokenizer tokens(str, sep);
  492. tokenizer::iterator iter = tokens.begin();
  493. mLineNumber = 0;
  494. mJoints.clear();
  495. std::vector<S32> parent_joints;
  496. //--------------------------------------------------------------------
  497. // Consume hierarchy
  498. //--------------------------------------------------------------------
  499. if (iter == tokens.end())
  500. {
  501. return E_ST_EOF;
  502. }
  503. line = *(iter++);
  504. ++err_line;
  505. if (!strstr(line.c_str(), "HIERARCHY"))
  506. {
  507. return E_ST_NO_HIER;
  508. }
  509. //--------------------------------------------------------------------
  510. // Consume joints
  511. //--------------------------------------------------------------------
  512. while (true)
  513. {
  514. //----------------------------------------------------------------
  515. // Get next line
  516. //----------------------------------------------------------------
  517. if (iter == tokens.end())
  518. {
  519. return E_ST_EOF;
  520. }
  521. line = *(iter++);
  522. ++err_line;
  523. //----------------------------------------------------------------
  524. // Consume }
  525. //----------------------------------------------------------------
  526. if (strstr(line.c_str(), "}"))
  527. {
  528. if (parent_joints.size() > 0)
  529. {
  530. parent_joints.pop_back();
  531. }
  532. continue;
  533. }
  534. //----------------------------------------------------------------
  535. // If MOTION, break out
  536. //----------------------------------------------------------------
  537. if (strstr(line.c_str(), "MOTION"))
  538. break;
  539. //----------------------------------------------------------------
  540. // It must be either ROOT or JOINT or EndSite
  541. //----------------------------------------------------------------
  542. if (strstr(line.c_str(), "ROOT") || strstr(line.c_str(), "JOINT"))
  543. {
  544. }
  545. else if (strstr(line.c_str(), "End Site"))
  546. {
  547. ++iter; // {
  548. ++iter; // OFFSET
  549. ++iter; // }
  550. S32 depth = 0;
  551. for (S32 j = (S32)parent_joints.size() - 1; j >= 0; --j)
  552. {
  553. Joint* joint = mJoints[parent_joints[j]];
  554. if (depth > joint->mChildTreeMaxDepth)
  555. {
  556. joint->mChildTreeMaxDepth = depth;
  557. }
  558. ++depth;
  559. }
  560. continue;
  561. }
  562. else
  563. {
  564. strncpy(error_text, line.c_str(), 127);
  565. return E_ST_NO_JOINT;
  566. }
  567. //----------------------------------------------------------------
  568. // Get the joint name
  569. //----------------------------------------------------------------
  570. char jointName[80];
  571. if (sscanf(line.c_str(), "%*s %79s", jointName) != 1)
  572. {
  573. strncpy(error_text, line.c_str(), 127);
  574. return E_ST_NO_NAME;
  575. }
  576. //---------------------------------------------------------------
  577. // We require the root joint be "hip" - DEV-26188
  578. //---------------------------------------------------------------
  579. if (mJoints.size() == 0)
  580. {
  581. // The root joint of the BVH file must be hip (mPelvis) or an alias
  582. // of mPelvis.
  583. const char* FORCED_ROOT_NAME = "hip";
  584. TranslationMap::iterator hip_joint = mTranslations.find(FORCED_ROOT_NAME);
  585. TranslationMap::iterator root_joint = mTranslations.find(jointName);
  586. if (hip_joint == mTranslations.end() ||
  587. root_joint == mTranslations.end() ||
  588. root_joint->second.mOutName != hip_joint->second.mOutName)
  589. {
  590. strncpy(error_text, line.c_str(), 127);
  591. return E_ST_BAD_ROOT;
  592. }
  593. }
  594. //----------------------------------------------------------------
  595. // Add a set of keyframes for this joint
  596. //----------------------------------------------------------------
  597. mJoints.push_back(new Joint(jointName));
  598. Joint* joint = mJoints.back();
  599. LL_DEBUGS("BVHLoader") << "Created joint: " << jointName
  600. << " - Index: " << mJoints.size() - 1
  601. << LL_ENDL;
  602. S32 depth = 1;
  603. for (S32 j = (S32)parent_joints.size() - 1; j >= 0; --j)
  604. {
  605. Joint* pjoint = mJoints[parent_joints[j]];
  606. LL_DEBUGS("BVHLoader") << "Ancestor: " << pjoint->mName << LL_ENDL;
  607. if (depth > pjoint->mChildTreeMaxDepth)
  608. {
  609. pjoint->mChildTreeMaxDepth = depth;
  610. }
  611. ++depth;
  612. }
  613. //----------------------------------------------------------------
  614. // Get next line
  615. //----------------------------------------------------------------
  616. if (iter == tokens.end())
  617. {
  618. return E_ST_EOF;
  619. }
  620. line = *(iter++);
  621. ++err_line;
  622. //----------------------------------------------------------------
  623. // It must be {
  624. //----------------------------------------------------------------
  625. if (!strstr(line.c_str(), "{"))
  626. {
  627. strncpy(error_text, line.c_str(), 127);
  628. return E_ST_NO_OFFSET;
  629. }
  630. else
  631. {
  632. parent_joints.push_back((S32)mJoints.size() - 1);
  633. }
  634. //----------------------------------------------------------------
  635. // Get next line
  636. //----------------------------------------------------------------
  637. if (iter == tokens.end())
  638. {
  639. return E_ST_EOF;
  640. }
  641. line = *(iter++);
  642. ++err_line;
  643. //----------------------------------------------------------------
  644. // It must be OFFSET
  645. //----------------------------------------------------------------
  646. if (!strstr(line.c_str(), "OFFSET"))
  647. {
  648. strncpy(error_text, line.c_str(), 127);
  649. return E_ST_NO_OFFSET;
  650. }
  651. //----------------------------------------------------------------
  652. // Get next line
  653. //----------------------------------------------------------------
  654. if (iter == tokens.end())
  655. {
  656. return E_ST_EOF;
  657. }
  658. line = *(iter++);
  659. ++err_line;
  660. //----------------------------------------------------------------
  661. // It must be CHANNELS
  662. //----------------------------------------------------------------
  663. if (!strstr(line.c_str(), "CHANNELS"))
  664. {
  665. strncpy(error_text, line.c_str(), 127);
  666. return E_ST_NO_CHANNELS;
  667. }
  668. // Animating position (via mNumChannels = 6) is only supported for
  669. // mPelvis.
  670. if (sscanf(line.c_str(), " CHANNELS %d", &joint->mNumChannels) != 1)
  671. {
  672. // Assume default if not otherwise specified.
  673. if (mJoints.size() == 1)
  674. {
  675. joint->mNumChannels = 6;
  676. }
  677. else
  678. {
  679. joint->mNumChannels = 3;
  680. }
  681. }
  682. //----------------------------------------------------------------
  683. // Get rotation order
  684. //----------------------------------------------------------------
  685. const char* p = line.c_str();
  686. for (S32 i = 0; i < 3; ++i)
  687. {
  688. p = strstr(p, "rotation");
  689. if (!p)
  690. {
  691. strncpy(error_text, line.c_str(), 127);
  692. return E_ST_NO_ROTATION;
  693. }
  694. const char axis = *(p - 1);
  695. if (axis != 'X' && axis != 'Y' && axis != 'Z')
  696. {
  697. strncpy(error_text, line.c_str(), 127);
  698. return E_ST_NO_AXIS;
  699. }
  700. joint->mOrder[i] = axis;
  701. ++p;
  702. }
  703. }
  704. //--------------------------------------------------------------------
  705. // Consume motion
  706. //--------------------------------------------------------------------
  707. if (!strstr(line.c_str(), "MOTION"))
  708. {
  709. strncpy(error_text, line.c_str(), 127);
  710. return E_ST_NO_MOTION;
  711. }
  712. //--------------------------------------------------------------------
  713. // Get number of frames
  714. //--------------------------------------------------------------------
  715. if (iter == tokens.end())
  716. {
  717. return E_ST_EOF;
  718. }
  719. line = *(iter++);
  720. ++err_line;
  721. if (!strstr(line.c_str(), "Frames:"))
  722. {
  723. strncpy(error_text, line.c_str(), 127);
  724. return E_ST_NO_FRAMES;
  725. }
  726. if (sscanf(line.c_str(), "Frames: %d", &mNumFrames) != 1)
  727. {
  728. strncpy(error_text, line.c_str(), 127);
  729. return E_ST_NO_FRAMES;
  730. }
  731. //--------------------------------------------------------------------
  732. // Get frame time
  733. //--------------------------------------------------------------------
  734. if (iter == tokens.end())
  735. {
  736. return E_ST_EOF;
  737. }
  738. line = *(iter++);
  739. ++err_line;
  740. if (!strstr(line.c_str(), "Frame Time:"))
  741. {
  742. strncpy(error_text, line.c_str(), 127);
  743. return E_ST_NO_FRAME_TIME;
  744. }
  745. if (sscanf(line.c_str(), "Frame Time: %f", &mFrameTime) != 1)
  746. {
  747. strncpy(error_text, line.c_str(), 127);
  748. return E_ST_NO_FRAME_TIME;
  749. }
  750. if (mNumFrames > NUMBER_OF_UNPLAYED_FRAMES)
  751. {
  752. mDuration = (F32)(mNumFrames - NUMBER_OF_UNPLAYED_FRAMES) * mFrameTime;
  753. }
  754. else
  755. {
  756. // If the user only supplies one animation frame (after the ignored
  757. // reference frame 0), hold for mFrameTime.
  758. mDuration = (F32)mNumFrames * mFrameTime;
  759. }
  760. if (!mLoop)
  761. {
  762. mLoopOutPoint = mDuration;
  763. }
  764. //--------------------------------------------------------------------
  765. // Load frames
  766. //--------------------------------------------------------------------
  767. for (S32 i = 0; i < mNumFrames; ++i)
  768. {
  769. // get next line
  770. if (iter == tokens.end())
  771. {
  772. return E_ST_EOF;
  773. }
  774. line = *(iter++);
  775. ++err_line;
  776. // Split line into a collection of floats.
  777. std::deque<F32> floats;
  778. boost::char_separator<char> whitespace_sep("\t ");
  779. tokenizer float_tokens(line, whitespace_sep);
  780. tokenizer::iterator float_token_iter = float_tokens.begin();
  781. while (float_token_iter != float_tokens.end())
  782. {
  783. try
  784. {
  785. F32 val = boost::lexical_cast<float>(*float_token_iter);
  786. floats.push_back(val);
  787. }
  788. catch (const boost::bad_lexical_cast&)
  789. {
  790. strncpy(error_text, line.c_str(), 127);
  791. return E_ST_NO_POS;
  792. }
  793. ++float_token_iter;
  794. }
  795. LL_DEBUGS("BVHLoader") << "Got " << floats.size() << " floats."
  796. << LL_ENDL;
  797. for (U32 j = 0; j < mJoints.size(); ++j)
  798. {
  799. Joint* joint = mJoints[j];
  800. joint->mKeys.push_back(Key());
  801. Key& key = joint->mKeys.back();
  802. if (floats.size() < (size_t)joint->mNumChannels)
  803. {
  804. strncpy(error_text, line.c_str(), 127);
  805. return E_ST_NO_ROT;
  806. }
  807. // assume either numChannels == 6, in which case we have pos + rot,
  808. // or numChannels == 3, in which case we have only rot.
  809. if (joint->mNumChannels == 6)
  810. {
  811. key.mPos[0] = floats.front();
  812. floats.pop_front();
  813. key.mPos[1] = floats.front();
  814. floats.pop_front();
  815. key.mPos[2] = floats.front();
  816. floats.pop_front();
  817. }
  818. key.mRot[joint->mOrder[0] - 'X'] = floats.front();
  819. floats.pop_front();
  820. key.mRot[joint->mOrder[1] - 'X'] = floats.front();
  821. floats.pop_front();
  822. key.mRot[joint->mOrder[2] - 'X'] = floats.front();
  823. floats.pop_front();
  824. }
  825. }
  826. return E_ST_OK;
  827. }
  828. void LLBVHLoader::applyTranslations()
  829. {
  830. for (JointVector::iterator ji = mJoints.begin(), end = mJoints.end();
  831. ji != end; ++ji)
  832. {
  833. Joint* joint = *ji;
  834. //----------------------------------------------------------------
  835. // Look for a translation for this joint.
  836. // If none, skip to next joint
  837. //----------------------------------------------------------------
  838. TranslationMap::iterator ti = mTranslations.find(joint->mName);
  839. if (ti == mTranslations.end())
  840. {
  841. continue;
  842. }
  843. Translation &trans = ti->second;
  844. //----------------------------------------------------------------
  845. // Set the ignore flag if necessary
  846. //----------------------------------------------------------------
  847. if (trans.mIgnore)
  848. {
  849. LL_DEBUGS("BVHLoader") << "Ignoring " << joint->mName.c_str()
  850. << LL_ENDL;
  851. joint->mIgnore = true;
  852. continue;
  853. }
  854. //----------------------------------------------------------------
  855. // Set the output name
  856. //----------------------------------------------------------------
  857. if (!trans.mOutName.empty())
  858. {
  859. LL_DEBUGS("BVHLoader") << "Changing " << joint->mName.c_str()
  860. << " to " << trans.mOutName.c_str()
  861. << LL_ENDL;
  862. joint->mOutName = trans.mOutName;
  863. }
  864. // Allow joint position changes as of SL-318, excepted for 3 channels
  865. // animations.
  866. joint->mIgnorePositions = joint->mNumChannels == 3;
  867. //----------------------------------------------------------------
  868. // Set the relativepos flags if necessary
  869. //----------------------------------------------------------------
  870. if (trans.mRelativePositionKey)
  871. {
  872. LL_DEBUGS("BVHLoader") << "Removing 1st position offset from all keys for "
  873. << joint->mOutName.c_str() << LL_ENDL;
  874. joint->mRelativePositionKey = true;
  875. }
  876. if (trans.mRelativeRotationKey)
  877. {
  878. LL_DEBUGS("BVHLoader") << "Removing 1st rotation from all keys for "
  879. << joint->mOutName.c_str() << LL_ENDL;
  880. joint->mRelativeRotationKey = true;
  881. }
  882. if (trans.mRelativePosition.length() > 0.0f)
  883. {
  884. joint->mRelativePosition = trans.mRelativePosition;
  885. LL_DEBUGS("BVHLoader") << "Removing "
  886. << joint->mRelativePosition.mV[0] << " "
  887. << joint->mRelativePosition.mV[1] << " "
  888. << joint->mRelativePosition.mV[2]
  889. << " from all position keys in "
  890. << joint->mOutName.c_str() << LL_ENDL;
  891. }
  892. //----------------------------------------------------------------
  893. // Set change of coordinate frame
  894. //----------------------------------------------------------------
  895. joint->mFrameMatrix = trans.mFrameMatrix;
  896. joint->mOffsetMatrix = trans.mOffsetMatrix;
  897. //----------------------------------------------------------------
  898. // Set mergeparent name
  899. //----------------------------------------------------------------
  900. if (!trans.mMergeParentName.empty())
  901. {
  902. LL_DEBUGS("BVHLoader") << "Merging " << joint->mOutName.c_str()
  903. << " with parent "
  904. << trans.mMergeParentName.c_str()
  905. << LL_ENDL;
  906. joint->mMergeParentName = trans.mMergeParentName;
  907. }
  908. //----------------------------------------------------------------
  909. // Set mergechild name
  910. //----------------------------------------------------------------
  911. if (!trans.mMergeChildName.empty())
  912. {
  913. LL_DEBUGS("BVHLoader") << "Merging " << joint->mName.c_str()
  914. << " with child "
  915. << trans.mMergeChildName.c_str() << LL_ENDL;
  916. joint->mMergeChildName = trans.mMergeChildName;
  917. }
  918. //----------------------------------------------------------------
  919. // Set joint priority
  920. //----------------------------------------------------------------
  921. joint->mPriority = mPriority + trans.mPriorityModifier;
  922. }
  923. }
  924. void LLBVHLoader::optimize()
  925. {
  926. // RN: assume motion blend, which is the default now
  927. if (!mLoop && mEaseIn + mEaseOut > mDuration && mDuration != 0.f)
  928. {
  929. F32 factor = mDuration / (mEaseIn + mEaseOut);
  930. mEaseIn *= factor;
  931. mEaseOut *= factor;
  932. }
  933. for (JointVector::iterator ji = mJoints.begin(), end = mJoints.end();
  934. ji != end; ++ji)
  935. {
  936. Joint* joint = *ji;
  937. bool pos_changed = false;
  938. bool rot_changed = false;
  939. if (!joint->mIgnore)
  940. {
  941. joint->mNumPosKeys = 0;
  942. joint->mNumRotKeys = 0;
  943. LLQuaternion::Order order = bvh_str_to_order(joint->mOrder);
  944. KeyVector::iterator first_key = joint->mKeys.begin();
  945. // No key ?
  946. if (first_key == joint->mKeys.end())
  947. {
  948. joint->mIgnore = true;
  949. continue;
  950. }
  951. LLVector3 first_frame_pos(first_key->mPos);
  952. LLQuaternion first_frame_rot = mayaQ(first_key->mRot[0],
  953. first_key->mRot[1],
  954. first_key->mRot[2], order);
  955. // Skip first key
  956. KeyVector::iterator ki = joint->mKeys.begin();
  957. if (joint->mKeys.size() == 1)
  958. {
  959. // *FIX: use single frame to move pelvis
  960. // if only one keyframe force output for this joint
  961. rot_changed = true;
  962. }
  963. else
  964. {
  965. // If more than one keyframe, use first frame as reference and
  966. // skip to second
  967. first_key->mIgnorePos = true;
  968. first_key->mIgnoreRot = true;
  969. ++ki;
  970. }
  971. KeyVector::iterator ki_prev = ki;
  972. KeyVector::iterator ki_last_good_pos = ki;
  973. KeyVector::iterator ki_last_good_rot = ki;
  974. S32 numPosFramesConsidered = 2;
  975. S32 numRotFramesConsidered = 2;
  976. F32 rot_threshold = ROTATION_KEYFRAME_THRESHOLD /
  977. llmax((F32)joint->mChildTreeMaxDepth * 0.33f,
  978. 1.f);
  979. double diff_max = 0;
  980. KeyVector::iterator ki_max = ki;
  981. for ( ; ki != joint->mKeys.end(); ++ki)
  982. {
  983. if (ki_prev == ki_last_good_pos)
  984. {
  985. ++joint->mNumPosKeys;
  986. if (dist_vec_squared(LLVector3(ki_prev->mPos),
  987. first_frame_pos) > POSITION_MOTION_THRESHOLD_SQUARED)
  988. {
  989. pos_changed = true;
  990. }
  991. }
  992. else
  993. {
  994. // Check position for noticeable effect
  995. LLVector3 test_pos(ki_prev->mPos);
  996. LLVector3 last_good_pos(ki_last_good_pos->mPos);
  997. LLVector3 current_pos(ki->mPos);
  998. LLVector3 interp_pos = lerp(current_pos,
  999. last_good_pos,
  1000. 1.f / (F32)numPosFramesConsidered);
  1001. if (dist_vec_squared(current_pos,
  1002. first_frame_pos) > POSITION_MOTION_THRESHOLD_SQUARED)
  1003. {
  1004. pos_changed = true;
  1005. }
  1006. if (dist_vec_squared(interp_pos,
  1007. test_pos) < POSITION_KEYFRAME_THRESHOLD_SQUARED)
  1008. {
  1009. ki_prev->mIgnorePos = true;
  1010. ++numPosFramesConsidered;
  1011. }
  1012. else
  1013. {
  1014. numPosFramesConsidered = 2;
  1015. ki_last_good_pos = ki_prev;
  1016. ++joint->mNumPosKeys;
  1017. }
  1018. }
  1019. if (ki_prev == ki_last_good_rot)
  1020. {
  1021. ++joint->mNumRotKeys;
  1022. LLQuaternion test_rot = mayaQ(ki_prev->mRot[0],
  1023. ki_prev->mRot[1],
  1024. ki_prev->mRot[2], order);
  1025. F32 x_delta = dist_vec(LLVector3::x_axis * first_frame_rot,
  1026. LLVector3::x_axis * test_rot);
  1027. F32 y_delta = dist_vec(LLVector3::y_axis * first_frame_rot,
  1028. LLVector3::y_axis * test_rot);
  1029. F32 rot_test = x_delta + y_delta;
  1030. if (rot_test > ROTATION_MOTION_THRESHOLD)
  1031. {
  1032. rot_changed = true;
  1033. }
  1034. }
  1035. else
  1036. {
  1037. // Check rotation for noticeable effect
  1038. LLQuaternion test_rot = mayaQ(ki_prev->mRot[0],
  1039. ki_prev->mRot[1],
  1040. ki_prev->mRot[2], order);
  1041. LLQuaternion last_good_rot = mayaQ(ki_last_good_rot->mRot[0],
  1042. ki_last_good_rot->mRot[1],
  1043. ki_last_good_rot->mRot[2],
  1044. order);
  1045. LLQuaternion current_rot = mayaQ(ki->mRot[0],
  1046. ki->mRot[1],
  1047. ki->mRot[2], order);
  1048. LLQuaternion interp_rot = lerp(1.f / (F32)numRotFramesConsidered,
  1049. current_rot, last_good_rot);
  1050. F32 x_delta;
  1051. F32 y_delta;
  1052. F32 rot_test;
  1053. // Test if the rotation has changed significantly since the
  1054. // very first frame. If false for all frames, then we'll
  1055. // just throw out this joint's rotation entirely.
  1056. x_delta = dist_vec(LLVector3::x_axis * first_frame_rot,
  1057. LLVector3::x_axis * test_rot);
  1058. y_delta = dist_vec(LLVector3::y_axis * first_frame_rot,
  1059. LLVector3::y_axis * test_rot);
  1060. rot_test = x_delta + y_delta;
  1061. if (rot_test > ROTATION_MOTION_THRESHOLD)
  1062. {
  1063. rot_changed = true;
  1064. }
  1065. x_delta = dist_vec(LLVector3::x_axis * interp_rot,
  1066. LLVector3::x_axis * test_rot);
  1067. y_delta = dist_vec(LLVector3::y_axis * interp_rot,
  1068. LLVector3::y_axis * test_rot);
  1069. rot_test = x_delta + y_delta;
  1070. // Draw a line between the last good keyframe and current.
  1071. // Test the distance between the last frame (current-1,
  1072. // i.e. ki_prev) and the line. If it's greater than some
  1073. // threshold, then it represents a significant frame and we
  1074. // want to include it.
  1075. if (rot_test >= rot_threshold ||
  1076. (ki + 1 == joint->mKeys.end() &&
  1077. numRotFramesConsidered > 2))
  1078. {
  1079. // Add the current test keyframe (which is technically
  1080. // the previous key, i.e. ki_prev).
  1081. numRotFramesConsidered = 2;
  1082. ki_last_good_rot = ki_prev;
  1083. ++joint->mNumRotKeys;
  1084. // Add another keyframe between the last good keyframe
  1085. // and current, at whatever point was the most
  1086. // "significant" (i.e. had the largest deviation from
  1087. // the earlier tests). Note that a more robust approach
  1088. // would be test all intermediate keyframes against the
  1089. // line between the last good keyframe and current, but
  1090. // we're settling for this other method because it's
  1091. // significantly faster.
  1092. if (diff_max > 0)
  1093. {
  1094. if (ki_max->mIgnoreRot)
  1095. {
  1096. ki_max->mIgnoreRot = false;
  1097. ++joint->mNumRotKeys;
  1098. }
  1099. diff_max = 0;
  1100. }
  1101. }
  1102. else
  1103. {
  1104. // This keyframe isn't significant enough, throw it
  1105. // away.
  1106. ki_prev->mIgnoreRot = true;
  1107. ++numRotFramesConsidered;
  1108. // Store away the keyframe that has the largest
  1109. // deviation from the interpolated line, for insertion
  1110. // later.
  1111. if (rot_test > diff_max)
  1112. {
  1113. diff_max = rot_test;
  1114. ki_max = ki;
  1115. }
  1116. }
  1117. }
  1118. ki_prev = ki;
  1119. }
  1120. }
  1121. // Do not output joints with no motion
  1122. if (!(pos_changed || rot_changed))
  1123. {
  1124. LL_DEBUGS("BVHLoader") << "Ignoring joint " << joint->mName
  1125. << LL_ENDL;
  1126. joint->mIgnore = true;
  1127. }
  1128. }
  1129. }
  1130. void LLBVHLoader::reset()
  1131. {
  1132. mLineNumber = 0;
  1133. mNumFrames = 0;
  1134. mFrameTime = 0.0f;
  1135. mDuration = 0.0f;
  1136. mPriority = 2;
  1137. mLoop = false;
  1138. mLoopInPoint = 0.f;
  1139. mLoopOutPoint = 0.f;
  1140. mEaseIn = 0.3f;
  1141. mEaseOut = 0.3f;
  1142. mHand = 1;
  1143. mInitialized = false;
  1144. mEmoteName.clear();
  1145. mLineNumber = 0;
  1146. mTranslations.clear();
  1147. mConstraints.clear();
  1148. }
  1149. bool LLBVHLoader::getLine(LLFILE* fp)
  1150. {
  1151. if (!feof(fp) && fgets(mLine, BVH_PARSER_LINE_SIZE, fp))
  1152. {
  1153. ++mLineNumber;
  1154. return true;
  1155. }
  1156. return false;
  1157. }
  1158. // Returns required size of output buffer
  1159. U32 LLBVHLoader::getOutputSize()
  1160. {
  1161. LLDataPackerBinaryBuffer dp;
  1162. serialize(dp);
  1163. return dp.getCurrentSize();
  1164. }
  1165. // Writes contents to datapacker
  1166. bool LLBVHLoader::serialize(LLDataPacker& dp)
  1167. {
  1168. // Count number of non-ignored joints
  1169. S32 num_joints = 0;
  1170. for (JointVector::iterator ji = mJoints.begin(), end = mJoints.end();
  1171. ji != end; ++ji)
  1172. {
  1173. Joint* joint = *ji;
  1174. if (joint && !joint->mIgnore)
  1175. {
  1176. ++num_joints;
  1177. }
  1178. }
  1179. // Print header
  1180. dp.packU16(KEYFRAME_MOTION_VERSION, "version");
  1181. dp.packU16(KEYFRAME_MOTION_SUBVERSION, "sub_version");
  1182. dp.packS32(mPriority, "base_priority");
  1183. dp.packF32(mDuration, "duration");
  1184. dp.packString(mEmoteName, "emote_name");
  1185. dp.packF32(mLoopInPoint, "loop_in_point");
  1186. dp.packF32(mLoopOutPoint, "loop_out_point");
  1187. dp.packS32(mLoop, "loop");
  1188. dp.packF32(mEaseIn, "ease_in_duration");
  1189. dp.packF32(mEaseOut, "ease_out_duration");
  1190. dp.packU32(mHand, "hand_pose");
  1191. dp.packU32(num_joints, "num_joints");
  1192. for (JointVector::iterator ji = mJoints.begin(), end = mJoints.end();
  1193. ji != end; ++ji)
  1194. {
  1195. Joint* joint = *ji;
  1196. // If ignored, skip it
  1197. if (!joint || joint->mIgnore)
  1198. {
  1199. continue;
  1200. }
  1201. LLQuaternion first_frame_rot;
  1202. LLQuaternion fixup_rot;
  1203. dp.packString(joint->mOutName, "joint_name");
  1204. dp.packS32(joint->mPriority, "joint_priority");
  1205. // Compute coordinate frame rotation
  1206. LLQuaternion frame_rot(joint->mFrameMatrix);
  1207. LLQuaternion frame_rot_inv = ~frame_rot;
  1208. LLQuaternion offset_rot(joint->mOffsetMatrix);
  1209. // Find mergechild and mergeparent joints, if specified
  1210. LLQuaternion merge_parent_rot;
  1211. LLQuaternion merge_child_rot;
  1212. Joint* merge_parent = NULL;
  1213. Joint* merge_child = NULL;
  1214. for (JointVector::iterator mji = mJoints.begin(), mend = mJoints.end();
  1215. mji != mend; ++mji)
  1216. {
  1217. Joint* mjoint = *mji;
  1218. if (!mjoint) continue; // Paranoia
  1219. if (!joint->mMergeParentName.empty() &&
  1220. mjoint->mName == joint->mMergeParentName)
  1221. {
  1222. merge_parent = *mji;
  1223. }
  1224. if (!joint->mMergeChildName.empty() &&
  1225. mjoint->mName == joint->mMergeChildName)
  1226. {
  1227. merge_child = *mji;
  1228. }
  1229. }
  1230. dp.packS32(joint->mNumRotKeys, "num_rot_keys");
  1231. LLQuaternion::Order order = bvh_str_to_order(joint->mOrder);
  1232. S32 frame = 0;
  1233. for (KeyVector::iterator ki = joint->mKeys.begin(),
  1234. kend = joint->mKeys.end();
  1235. ki != kend; ++ki)
  1236. {
  1237. if (frame == 0 && joint->mRelativeRotationKey)
  1238. {
  1239. first_frame_rot = mayaQ(ki->mRot[0], ki->mRot[1], ki->mRot[2],
  1240. order);
  1241. fixup_rot.shortestArc(LLVector3::z_axis * first_frame_rot *
  1242. frame_rot, LLVector3::z_axis);
  1243. }
  1244. if (ki->mIgnoreRot)
  1245. {
  1246. ++frame;
  1247. continue;
  1248. }
  1249. // Time elapsed before this frame starts.
  1250. F32 time = (F32)(frame - NUMBER_OF_IGNORED_FRAMES_AT_START) *
  1251. mFrameTime;
  1252. if (time < 0.f)
  1253. {
  1254. time = 0.f;
  1255. }
  1256. if (merge_parent)
  1257. {
  1258. merge_parent_rot = mayaQ(merge_parent->mKeys[frame-1].mRot[0],
  1259. merge_parent->mKeys[frame-1].mRot[1],
  1260. merge_parent->mKeys[frame-1].mRot[2],
  1261. bvh_str_to_order(merge_parent->mOrder));
  1262. LLQuaternion parent_frame_rot(merge_parent->mFrameMatrix);
  1263. LLQuaternion parent_offset_rot(merge_parent->mOffsetMatrix);
  1264. merge_parent_rot = ~parent_frame_rot * merge_parent_rot *
  1265. parent_frame_rot * parent_offset_rot;
  1266. }
  1267. else
  1268. {
  1269. merge_parent_rot.loadIdentity();
  1270. }
  1271. if (merge_child)
  1272. {
  1273. merge_child_rot = mayaQ(merge_child->mKeys[frame-1].mRot[0],
  1274. merge_child->mKeys[frame-1].mRot[1],
  1275. merge_child->mKeys[frame-1].mRot[2],
  1276. bvh_str_to_order(merge_child->mOrder));
  1277. LLQuaternion child_frame_rot(merge_child->mFrameMatrix);
  1278. LLQuaternion child_offset_rot(merge_child->mOffsetMatrix);
  1279. merge_child_rot = ~child_frame_rot * merge_child_rot *
  1280. child_frame_rot * child_offset_rot;
  1281. }
  1282. else
  1283. {
  1284. merge_child_rot.loadIdentity();
  1285. }
  1286. LLQuaternion inRot = mayaQ(ki->mRot[0], ki->mRot[1], ki->mRot[2],
  1287. order);
  1288. LLQuaternion outRot = frame_rot_inv * merge_child_rot * inRot *
  1289. merge_parent_rot * ~first_frame_rot *
  1290. frame_rot * offset_rot;
  1291. U16 time_short = F32_to_U16(time, 0.f, mDuration);
  1292. dp.packU16(time_short, "time");
  1293. U16 x, y, z;
  1294. LLVector3 rot_vec = outRot.packToVector3();
  1295. rot_vec.quantize16(-1.f, 1.f, -1.f, 1.f);
  1296. x = F32_to_U16(rot_vec.mV[VX], -1.f, 1.f);
  1297. y = F32_to_U16(rot_vec.mV[VY], -1.f, 1.f);
  1298. z = F32_to_U16(rot_vec.mV[VZ], -1.f, 1.f);
  1299. dp.packU16(x, "rot_angle_x");
  1300. dp.packU16(y, "rot_angle_y");
  1301. dp.packU16(z, "rot_angle_z");
  1302. ++frame;
  1303. }
  1304. // Output position keys if joint has motion
  1305. if (!joint->mIgnorePositions)
  1306. {
  1307. dp.packS32(joint->mNumPosKeys, "num_pos_keys");
  1308. LLVector3 rel_pos = joint->mRelativePosition;
  1309. LLVector3 rel_key;
  1310. frame = 0;
  1311. for (KeyVector::iterator ki = joint->mKeys.begin(),
  1312. kend = joint->mKeys.end();
  1313. ki != kend; ++ki)
  1314. {
  1315. if (frame == 0 && joint->mRelativePositionKey)
  1316. {
  1317. rel_key.set(ki->mPos);
  1318. }
  1319. if (ki->mIgnorePos)
  1320. {
  1321. ++frame;
  1322. continue;
  1323. }
  1324. // Time elapsed before this frame starts.
  1325. F32 time = (F32)(frame - NUMBER_OF_IGNORED_FRAMES_AT_START) *
  1326. mFrameTime;
  1327. if (time < 0.f)
  1328. {
  1329. time = 0.f;
  1330. }
  1331. LLVector3 in_pos = (LLVector3(ki->mPos) - rel_key) *
  1332. ~first_frame_rot; // * fixup_rot;
  1333. LLVector3 out_pos = in_pos * frame_rot * offset_rot;
  1334. constexpr F32 INCHES_TO_METERS = 0.02540005f;
  1335. out_pos *= INCHES_TO_METERS;
  1336. out_pos -= rel_pos;
  1337. // SL-318: pelvis position can only move 5m. Limit all joint
  1338. // position offsets to this distance.
  1339. out_pos.clamp(-LL_MAX_PELVIS_OFFSET, LL_MAX_PELVIS_OFFSET);
  1340. U16 time_short = F32_to_U16(time, 0.f, mDuration);
  1341. dp.packU16(time_short, "time");
  1342. U16 x, y, z;
  1343. out_pos.quantize16(-LL_MAX_PELVIS_OFFSET, LL_MAX_PELVIS_OFFSET,
  1344. -LL_MAX_PELVIS_OFFSET,
  1345. LL_MAX_PELVIS_OFFSET);
  1346. x = F32_to_U16(out_pos.mV[VX], -LL_MAX_PELVIS_OFFSET,
  1347. LL_MAX_PELVIS_OFFSET);
  1348. y = F32_to_U16(out_pos.mV[VY], -LL_MAX_PELVIS_OFFSET,
  1349. LL_MAX_PELVIS_OFFSET);
  1350. z = F32_to_U16(out_pos.mV[VZ], -LL_MAX_PELVIS_OFFSET,
  1351. LL_MAX_PELVIS_OFFSET);
  1352. dp.packU16(x, "pos_x");
  1353. dp.packU16(y, "pos_y");
  1354. dp.packU16(z, "pos_z");
  1355. ++frame;
  1356. }
  1357. }
  1358. else
  1359. {
  1360. dp.packS32(0, "num_pos_keys");
  1361. }
  1362. }
  1363. S32 num_constraints = (S32)mConstraints.size();
  1364. dp.packS32(num_constraints, "num_constraints");
  1365. for (ConstraintVector::iterator it = mConstraints.begin(),
  1366. end = mConstraints.end();
  1367. it != end; ++it)
  1368. {
  1369. U8 byte = it->mChainLength;
  1370. dp.packU8(byte, "chain_length");
  1371. byte = it->mConstraintType;
  1372. dp.packU8(byte, "constraint_type");
  1373. dp.packBinaryDataFixed((U8*)it->mSourceJointName, 16, "source_volume");
  1374. dp.packVector3(it->mSourceOffset, "source_offset");
  1375. dp.packBinaryDataFixed((U8*)it->mTargetJointName, 16, "target_volume");
  1376. dp.packVector3(it->mTargetOffset, "target_offset");
  1377. dp.packVector3(it->mTargetDir, "target_dir");
  1378. dp.packF32(it->mEaseInStart, "ease_in_start");
  1379. dp.packF32(it->mEaseInStop, "ease_in_stop");
  1380. dp.packF32(it->mEaseOutStart, "ease_out_start");
  1381. dp.packF32(it->mEaseOutStop, "ease_out_stop");
  1382. }
  1383. return true;
  1384. }