LWSLoader.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (ASSIMP)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2010, ASSIMP Development Team
  6. All rights reserved.
  7. Redistribution and use of this software in source and binary forms,
  8. with or without modification, are permitted provided that the following
  9. conditions are met:
  10. * Redistributions of source code must retain the above
  11. copyright notice, this list of conditions and the
  12. following disclaimer.
  13. * Redistributions in binary form must reproduce the above
  14. copyright notice, this list of conditions and the
  15. following disclaimer in the documentation and/or other
  16. materials provided with the distribution.
  17. * Neither the name of the ASSIMP team, nor the names of its
  18. contributors may be used to endorse or promote products
  19. derived from this software without specific prior
  20. written permission of the ASSIMP Development Team.
  21. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. ---------------------------------------------------------------------------
  33. */
  34. /** @file LWSLoader.cpp
  35. * @brief Implementation of the LWS importer class
  36. */
  37. #include "AssimpPCH.h"
  38. #include "LWSLoader.h"
  39. #include "ParsingUtils.h"
  40. #include "fast_atof.h"
  41. #include "SceneCombiner.h"
  42. #include "GenericProperty.h"
  43. #include "SkeletonMeshBuilder.h"
  44. #include "ConvertToLHProcess.h"
  45. #include "Importer.h"
  46. using namespace Assimp;
  47. // ------------------------------------------------------------------------------------------------
  48. // Recursive parsing of LWS files
  49. void LWS::Element::Parse (const char*& buffer)
  50. {
  51. for (;SkipSpacesAndLineEnd(&buffer);SkipLine(&buffer)) {
  52. // begin of a new element with children
  53. bool sub = false;
  54. if (*buffer == '{') {
  55. ++buffer;
  56. SkipSpaces(&buffer);
  57. sub = true;
  58. }
  59. else if (*buffer == '}')
  60. return;
  61. children.push_back(Element());
  62. // copy data line - read token per token
  63. const char* cur = buffer;
  64. while (!IsSpaceOrNewLine(*buffer)) ++buffer;
  65. children.back().tokens[0] = std::string(cur,(size_t) (buffer-cur));
  66. SkipSpaces(&buffer);
  67. if (children.back().tokens[0] == "Plugin")
  68. {
  69. DefaultLogger::get()->debug("LWS: Skipping over plugin-specific data");
  70. // strange stuff inside Plugin/Endplugin blocks. Needn't
  71. // follow LWS syntax, so we skip over it
  72. for (;SkipSpacesAndLineEnd(&buffer);SkipLine(&buffer)) {
  73. if (!::strncmp(buffer,"EndPlugin",9)) {
  74. //SkipLine(&buffer);
  75. break;
  76. }
  77. }
  78. continue;
  79. }
  80. cur = buffer;
  81. while (!IsLineEnd(*buffer)) ++buffer;
  82. children.back().tokens[1] = std::string(cur,(size_t) (buffer-cur));
  83. // parse more elements recursively
  84. if (sub)
  85. children.back().Parse(buffer);
  86. }
  87. }
  88. // ------------------------------------------------------------------------------------------------
  89. // Constructor to be privately used by Importer
  90. LWSImporter::LWSImporter()
  91. {
  92. // nothing to do here
  93. }
  94. // ------------------------------------------------------------------------------------------------
  95. // Destructor, private as well
  96. LWSImporter::~LWSImporter()
  97. {
  98. // nothing to do here
  99. }
  100. // ------------------------------------------------------------------------------------------------
  101. // Returns whether the class can handle the format of the given file.
  102. bool LWSImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler,bool checkSig) const
  103. {
  104. const std::string extension = GetExtension(pFile);
  105. if (extension == "lws" || extension == "mot")
  106. return true;
  107. // if check for extension is not enough, check for the magic tokens LWSC and LWMO
  108. if (!extension.length() || checkSig) {
  109. uint32_t tokens[2];
  110. tokens[0] = AI_MAKE_MAGIC("LWSC");
  111. tokens[1] = AI_MAKE_MAGIC("LWMO");
  112. return CheckMagicToken(pIOHandler,pFile,tokens,2);
  113. }
  114. return false;
  115. }
  116. // ------------------------------------------------------------------------------------------------
  117. // Get list of file extensions
  118. void LWSImporter::GetExtensionList(std::set<std::string>& extensions)
  119. {
  120. extensions.insert("lws");
  121. extensions.insert("mot");
  122. }
  123. // ------------------------------------------------------------------------------------------------
  124. // Setup configuration properties
  125. void LWSImporter::SetupProperties(const Importer* pImp)
  126. {
  127. // AI_CONFIG_FAVOUR_SPEED
  128. configSpeedFlag = (0 != pImp->GetPropertyInteger(AI_CONFIG_FAVOUR_SPEED,0));
  129. // AI_CONFIG_IMPORT_LWS_ANIM_START
  130. first = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_LWS_ANIM_START,
  131. 150392 /* magic hack */);
  132. // AI_CONFIG_IMPORT_LWS_ANIM_END
  133. last = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_LWS_ANIM_END,
  134. 150392 /* magic hack */);
  135. if (last < first) {
  136. std::swap(last,first);
  137. }
  138. }
  139. // ------------------------------------------------------------------------------------------------
  140. // Read an envelope description
  141. void LWSImporter::ReadEnvelope(const LWS::Element& dad, LWO::Envelope& fill )
  142. {
  143. if (dad.children.empty()) {
  144. DefaultLogger::get()->error("LWS: Envelope descriptions must not be empty");
  145. return;
  146. }
  147. // reserve enough storage
  148. std::list< LWS::Element >::const_iterator it = dad.children.begin();;
  149. fill.keys.reserve(strtoul10(it->tokens[1].c_str()));
  150. for (++it; it != dad.children.end(); ++it) {
  151. const char* c = (*it).tokens[1].c_str();
  152. if ((*it).tokens[0] == "Key") {
  153. fill.keys.push_back(LWO::Key());
  154. LWO::Key& key = fill.keys.back();
  155. float f;
  156. SkipSpaces(&c);
  157. c = fast_atof_move(c,key.value);
  158. SkipSpaces(&c);
  159. c = fast_atof_move(c,f);
  160. key.time = f;
  161. unsigned int span = strtoul10(c,&c), num = 0;
  162. switch (span) {
  163. case 0:
  164. key.inter = LWO::IT_TCB;
  165. num = 5;
  166. break;
  167. case 1:
  168. case 2:
  169. key.inter = LWO::IT_HERM;
  170. num = 5;
  171. break;
  172. case 3:
  173. key.inter = LWO::IT_LINE;
  174. num = 0;
  175. break;
  176. case 4:
  177. key.inter = LWO::IT_STEP;
  178. num = 0;
  179. break;
  180. case 5:
  181. key.inter = LWO::IT_BEZ2;
  182. num = 4;
  183. break;
  184. default:
  185. DefaultLogger::get()->error("LWS: Unknown span type");
  186. }
  187. for (unsigned int i = 0; i < num;++i) {
  188. SkipSpaces(&c);
  189. c = fast_atof_move(c,key.params[i]);
  190. }
  191. }
  192. else if ((*it).tokens[0] == "Behaviors") {
  193. SkipSpaces(&c);
  194. fill.pre = (LWO::PrePostBehaviour) strtoul10(c,&c);
  195. SkipSpaces(&c);
  196. fill.post = (LWO::PrePostBehaviour) strtoul10(c,&c);
  197. }
  198. }
  199. }
  200. // ------------------------------------------------------------------------------------------------
  201. // Read animation channels in the old LightWave animation format
  202. void LWSImporter::ReadEnvelope_Old(
  203. std::list< LWS::Element >::const_iterator& it,
  204. const std::list< LWS::Element >::const_iterator& end,
  205. LWS::NodeDesc& nodes,
  206. unsigned int /*version*/)
  207. {
  208. unsigned int num,sub_num;
  209. if (++it == end)goto unexpected_end;
  210. num = strtoul10((*it).tokens[0].c_str());
  211. for (unsigned int i = 0; i < num; ++i) {
  212. nodes.channels.push_back(LWO::Envelope());
  213. LWO::Envelope& envl = nodes.channels.back();
  214. envl.index = i;
  215. envl.type = (LWO::EnvelopeType)(i+1);
  216. if (++it == end)goto unexpected_end;
  217. sub_num = strtoul10((*it).tokens[0].c_str());
  218. for (unsigned int n = 0; n < sub_num;++n) {
  219. if (++it == end)goto unexpected_end;
  220. // parse value and time, skip the rest for the moment.
  221. LWO::Key key;
  222. const char* c = fast_atof_move((*it).tokens[0].c_str(),key.value);
  223. SkipSpaces(&c);
  224. float f;
  225. fast_atof_move((*it).tokens[0].c_str(),f);
  226. key.time = f;
  227. envl.keys.push_back(key);
  228. }
  229. }
  230. return;
  231. unexpected_end:
  232. DefaultLogger::get()->error("LWS: Encountered unexpected end of file while parsing object motion");
  233. }
  234. // ------------------------------------------------------------------------------------------------
  235. // Setup a nice name for a node
  236. void LWSImporter::SetupNodeName(aiNode* nd, LWS::NodeDesc& src)
  237. {
  238. const unsigned int combined = src.number | ((unsigned int)src.type) << 28u;
  239. // the name depends on the type. We break LWS's strange naming convention
  240. // and return human-readable, but still machine-parsable and unique, strings.
  241. if (src.type == LWS::NodeDesc::OBJECT) {
  242. if (src.path.length()) {
  243. std::string::size_type s = src.path.find_last_of("\\/");
  244. if (s == std::string::npos)
  245. s = 0;
  246. else ++s;
  247. std::string::size_type t = src.path.substr(s).find_last_of(".");
  248. nd->mName.length = ::sprintf(nd->mName.data,"%s_(%08X)",src.path.substr(s).substr(0,t).c_str(),combined);
  249. return;
  250. }
  251. }
  252. nd->mName.length = ::sprintf(nd->mName.data,"%s_(%08X)",src.name,combined);
  253. }
  254. // ------------------------------------------------------------------------------------------------
  255. // Recursively build the scenegraph
  256. void LWSImporter::BuildGraph(aiNode* nd, LWS::NodeDesc& src, std::vector<AttachmentInfo>& attach,
  257. BatchLoader& batch,
  258. aiCamera**& camOut,
  259. aiLight**& lightOut,
  260. std::vector<aiNodeAnim*>& animOut)
  261. {
  262. // Setup a very cryptic name for the node, we want the user to be happy
  263. SetupNodeName(nd,src);
  264. aiNode* ndAnim = nd;
  265. // If the node is an object
  266. if (src.type == LWS::NodeDesc::OBJECT) {
  267. // If the object is from an external file, get it
  268. aiScene* obj = NULL;
  269. if (src.path.length() ) {
  270. obj = batch.GetImport(src.id);
  271. if (!obj) {
  272. DefaultLogger::get()->error("LWS: Failed to read external file " + src.path);
  273. }
  274. else {
  275. if (obj->mRootNode->mNumChildren == 1) {
  276. //If the pivot is not set for this layer, get it from the external object
  277. if (!src.isPivotSet) {
  278. src.pivotPos.x = +obj->mRootNode->mTransformation.a4;
  279. src.pivotPos.y = +obj->mRootNode->mTransformation.b4;
  280. src.pivotPos.z = -obj->mRootNode->mTransformation.c4; //The sign is the RH to LH back conversion
  281. }
  282. //Remove first node from obj (the old pivot), reset transform of second node (the mesh node)
  283. aiNode* newRootNode = obj->mRootNode->mChildren[0];
  284. obj->mRootNode->mChildren[0] = NULL;
  285. delete obj->mRootNode;
  286. obj->mRootNode = newRootNode;
  287. obj->mRootNode->mTransformation.a4 = 0.0;
  288. obj->mRootNode->mTransformation.b4 = 0.0;
  289. obj->mRootNode->mTransformation.c4 = 0.0;
  290. }
  291. }
  292. }
  293. //Setup the pivot node (also the animation node), the one we received
  294. nd->mName = std::string("Pivot:") + nd->mName.data;
  295. ndAnim = nd;
  296. //Add the attachment node to it
  297. nd->mNumChildren = 1;
  298. nd->mChildren = new aiNode*[1];
  299. nd->mChildren[0] = new aiNode();
  300. nd->mChildren[0]->mParent = nd;
  301. nd->mChildren[0]->mTransformation.a4 = -src.pivotPos.x;
  302. nd->mChildren[0]->mTransformation.b4 = -src.pivotPos.y;
  303. nd->mChildren[0]->mTransformation.c4 = -src.pivotPos.z;
  304. SetupNodeName(nd->mChildren[0], src);
  305. //Update the attachment node
  306. nd = nd->mChildren[0];
  307. //Push attachment, if the object came from an external file
  308. if (obj) {
  309. attach.push_back(AttachmentInfo(obj,nd));
  310. }
  311. }
  312. // If object is a light source - setup a corresponding ai structure
  313. else if (src.type == LWS::NodeDesc::LIGHT) {
  314. aiLight* lit = *lightOut++ = new aiLight();
  315. // compute final light color
  316. lit->mColorDiffuse = lit->mColorSpecular = src.lightColor*src.lightIntensity;
  317. // name to attach light to node -> unique due to LWs indexing system
  318. lit->mName = nd->mName;
  319. // detemine light type and setup additional members
  320. if (src.lightType == 2) { /* spot light */
  321. lit->mType = aiLightSource_SPOT;
  322. lit->mAngleInnerCone = (float)AI_DEG_TO_RAD( src.lightConeAngle );
  323. lit->mAngleOuterCone = lit->mAngleInnerCone+(float)AI_DEG_TO_RAD( src.lightEdgeAngle );
  324. }
  325. else if (src.lightType == 1) { /* directional light source */
  326. lit->mType = aiLightSource_DIRECTIONAL;
  327. }
  328. else lit->mType = aiLightSource_POINT;
  329. // fixme: no proper handling of light falloffs yet
  330. if (src.lightFalloffType == 1)
  331. lit->mAttenuationConstant = 1.f;
  332. else if (src.lightFalloffType == 1)
  333. lit->mAttenuationLinear = 1.f;
  334. else
  335. lit->mAttenuationQuadratic = 1.f;
  336. }
  337. // If object is a camera - setup a corresponding ai structure
  338. else if (src.type == LWS::NodeDesc::CAMERA) {
  339. aiCamera* cam = *camOut++ = new aiCamera();
  340. // name to attach cam to node -> unique due to LWs indexing system
  341. cam->mName = nd->mName;
  342. }
  343. // Get the node transformation from the LWO key
  344. LWO::AnimResolver resolver(src.channels,fps);
  345. resolver.ExtractBindPose(ndAnim->mTransformation);
  346. // .. and construct animation channels
  347. aiNodeAnim* anim = NULL;
  348. if (first != last) {
  349. resolver.SetAnimationRange(first,last);
  350. resolver.ExtractAnimChannel(&anim,AI_LWO_ANIM_FLAG_SAMPLE_ANIMS|AI_LWO_ANIM_FLAG_START_AT_ZERO);
  351. if (anim) {
  352. anim->mNodeName = ndAnim->mName;
  353. animOut.push_back(anim);
  354. }
  355. }
  356. // Add children
  357. if (src.children.size()) {
  358. nd->mChildren = new aiNode*[src.children.size()];
  359. for (std::list<LWS::NodeDesc*>::iterator it = src.children.begin(); it != src.children.end(); ++it) {
  360. aiNode* ndd = nd->mChildren[nd->mNumChildren++] = new aiNode();
  361. ndd->mParent = nd;
  362. BuildGraph(ndd,**it,attach,batch,camOut,lightOut,animOut);
  363. }
  364. }
  365. }
  366. // ------------------------------------------------------------------------------------------------
  367. // Determine the exact location of a LWO file
  368. std::string LWSImporter::FindLWOFile(const std::string& in)
  369. {
  370. // insert missing directory seperator if necessary
  371. std::string tmp;
  372. if (in.length() > 3 && in[1] == ':'&& in[2] != '\\' && in[2] != '/')
  373. {
  374. tmp = in[0] + ":\\" + in.substr(2);
  375. }
  376. else tmp = in;
  377. if (io->Exists(tmp))
  378. return in;
  379. // file is not accessible for us ... maybe it's packed by
  380. // LightWave's 'Package Scene' command?
  381. // Relevant for us are the following two directories:
  382. // <folder>\Objects\<hh>\<*>.lwo
  383. // <folder>\Scenes\<hh>\<*>.lws
  384. // where <hh> is optional.
  385. std::string test = ".." + io->getOsSeparator() + tmp;
  386. if (io->Exists(test))
  387. return test;
  388. test = ".." + io->getOsSeparator() + test;
  389. if (io->Exists(test))
  390. return test;
  391. // return original path, maybe the IOsystem knows better
  392. return tmp;
  393. }
  394. // ------------------------------------------------------------------------------------------------
  395. // Read file into given scene data structure
  396. void LWSImporter::InternReadFile( const std::string& pFile, aiScene* pScene,
  397. IOSystem* pIOHandler)
  398. {
  399. io = pIOHandler;
  400. boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile, "rb"));
  401. // Check whether we can read from the file
  402. if( file.get() == NULL) {
  403. throw DeadlyImportError( "Failed to open LWS file " + pFile + ".");
  404. }
  405. // Allocate storage and copy the contents of the file to a memory buffer
  406. std::vector< char > mBuffer;
  407. TextFileToBuffer(file.get(),mBuffer);
  408. // Parse the file structure
  409. LWS::Element root; const char* dummy = &mBuffer[0];
  410. root.Parse(dummy);
  411. // Construct a Batchimporter to read more files recursively
  412. BatchLoader batch(pIOHandler);
  413. // batch.SetBasePath(pFile);
  414. // Construct an array to receive the flat output graph
  415. std::list<LWS::NodeDesc> nodes;
  416. unsigned int cur_light = 0, cur_camera = 0, cur_object = 0;
  417. unsigned int num_light = 0, num_camera = 0, num_object = 0;
  418. // check magic identifier, 'LWSC'
  419. bool motion_file = false;
  420. std::list< LWS::Element >::const_iterator it = root.children.begin();
  421. if ((*it).tokens[0] == "LWMO")
  422. motion_file = true;
  423. if ((*it).tokens[0] != "LWSC" && !motion_file)
  424. throw DeadlyImportError("LWS: Not a LightWave scene, magic tag LWSC not found");
  425. // get file format version and print to log
  426. ++it;
  427. unsigned int version = strtoul10((*it).tokens[0].c_str());
  428. DefaultLogger::get()->info("LWS file format version is " + (*it).tokens[0]);
  429. first = 0.;
  430. last = 60.;
  431. fps = 25.; /* seems to be a good default frame rate */
  432. // Now read all elements in a very straghtforward manner
  433. for (; it != root.children.end(); ++it) {
  434. const char* c = (*it).tokens[1].c_str();
  435. // 'FirstFrame': begin of animation slice
  436. if ((*it).tokens[0] == "FirstFrame") {
  437. if (150392. != first /* see SetupProperties() */)
  438. first = strtoul10(c,&c)-1.; /* we're zero-based */
  439. }
  440. // 'LastFrame': end of animation slice
  441. else if ((*it).tokens[0] == "LastFrame") {
  442. if (150392. != last /* see SetupProperties() */)
  443. last = strtoul10(c,&c)-1.; /* we're zero-based */
  444. }
  445. // 'FramesPerSecond': frames per second
  446. else if ((*it).tokens[0] == "FramesPerSecond") {
  447. fps = strtoul10(c,&c);
  448. }
  449. // 'LoadObjectLayer': load a layer of a specific LWO file
  450. else if ((*it).tokens[0] == "LoadObjectLayer") {
  451. // get layer index
  452. const int layer = strtoul10(c,&c);
  453. // setup the layer to be loaded
  454. BatchLoader::PropertyMap props;
  455. SetGenericProperty(props.ints,AI_CONFIG_IMPORT_LWO_ONE_LAYER_ONLY,layer);
  456. // add node to list
  457. LWS::NodeDesc d;
  458. d.type = LWS::NodeDesc::OBJECT;
  459. if (version >= 4) { // handle LWSC 4 explicit ID
  460. SkipSpaces(&c);
  461. d.number = strtoul16(c,&c) & AI_LWS_MASK;
  462. }
  463. else d.number = cur_object++;
  464. // and add the file to the import list
  465. SkipSpaces(&c);
  466. std::string path = FindLWOFile( c );
  467. d.path = path;
  468. d.id = batch.AddLoadRequest(path,0,&props);
  469. nodes.push_back(d);
  470. num_object++;
  471. }
  472. // 'LoadObject': load a LWO file into the scenegraph
  473. else if ((*it).tokens[0] == "LoadObject") {
  474. // add node to list
  475. LWS::NodeDesc d;
  476. d.type = LWS::NodeDesc::OBJECT;
  477. if (version >= 4) { // handle LWSC 4 explicit ID
  478. d.number = strtoul16(c,&c) & AI_LWS_MASK;
  479. SkipSpaces(&c);
  480. }
  481. else d.number = cur_object++;
  482. std::string path = FindLWOFile( c );
  483. d.id = batch.AddLoadRequest(path,0,NULL);
  484. d.path = path;
  485. nodes.push_back(d);
  486. num_object++;
  487. }
  488. // 'AddNullObject': add a dummy node to the hierarchy
  489. else if ((*it).tokens[0] == "AddNullObject") {
  490. // add node to list
  491. LWS::NodeDesc d;
  492. d.type = LWS::NodeDesc::OBJECT;
  493. if (version >= 4) { // handle LWSC 4 explicit ID
  494. d.number = strtoul16(c,&c) & AI_LWS_MASK;
  495. SkipSpaces(&c);
  496. }
  497. else d.number = cur_object++;
  498. d.name = c;
  499. nodes.push_back(d);
  500. num_object++;
  501. }
  502. // 'NumChannels': Number of envelope channels assigned to last layer
  503. else if ((*it).tokens[0] == "NumChannels") {
  504. // ignore for now
  505. }
  506. // 'Channel': preceedes any envelope description
  507. else if ((*it).tokens[0] == "Channel") {
  508. if (nodes.empty()) {
  509. if (motion_file) {
  510. // LightWave motion file. Add dummy node
  511. LWS::NodeDesc d;
  512. d.type = LWS::NodeDesc::OBJECT;
  513. d.name = c;
  514. d.number = cur_object++;
  515. nodes.push_back(d);
  516. }
  517. else DefaultLogger::get()->error("LWS: Unexpected keyword: \'Channel\'");
  518. }
  519. // important: index of channel
  520. nodes.back().channels.push_back(LWO::Envelope());
  521. LWO::Envelope& env = nodes.back().channels.back();
  522. env.index = strtoul10(c);
  523. // currently we can just interpret the standard channels 0...9
  524. // (hack) assume that index-i yields the binary channel type from LWO
  525. env.type = (LWO::EnvelopeType)(env.index+1);
  526. }
  527. // 'Envelope': a single animation channel
  528. else if ((*it).tokens[0] == "Envelope") {
  529. if (nodes.empty() || nodes.back().channels.empty())
  530. DefaultLogger::get()->error("LWS: Unexpected keyword: \'Envelope\'");
  531. else {
  532. ReadEnvelope((*it),nodes.back().channels.back());
  533. }
  534. }
  535. // 'ObjectMotion': animation information for older lightwave formats
  536. else if (version < 3 && ((*it).tokens[0] == "ObjectMotion" ||
  537. (*it).tokens[0] == "CameraMotion" ||
  538. (*it).tokens[0] == "LightMotion")) {
  539. if (nodes.empty())
  540. DefaultLogger::get()->error("LWS: Unexpected keyword: \'<Light|Object|Camera>Motion\'");
  541. else {
  542. ReadEnvelope_Old(it,root.children.end(),nodes.back(),version);
  543. }
  544. }
  545. // 'Pre/PostBehavior': pre/post animation behaviour for LWSC 2
  546. else if (version == 2 && (*it).tokens[0] == "Pre/PostBehavior") {
  547. if (nodes.empty())
  548. DefaultLogger::get()->error("LWS: Unexpected keyword: \'Pre/PostBehavior'");
  549. else {
  550. for (std::list<LWO::Envelope>::iterator it = nodes.back().channels.begin(); it != nodes.back().channels.end(); ++it) {
  551. // two ints per envelope
  552. LWO::Envelope& env = *it;
  553. env.pre = (LWO::PrePostBehaviour) strtoul10(c,&c); SkipSpaces(&c);
  554. env.post = (LWO::PrePostBehaviour) strtoul10(c,&c); SkipSpaces(&c);
  555. }
  556. }
  557. }
  558. // 'ParentItem': specifies the parent of the current element
  559. else if ((*it).tokens[0] == "ParentItem") {
  560. if (nodes.empty())
  561. DefaultLogger::get()->error("LWS: Unexpected keyword: \'ParentItem\'");
  562. else nodes.back().parent = strtoul16(c,&c);
  563. }
  564. // 'ParentObject': deprecated one for older formats
  565. else if (version < 3 && (*it).tokens[0] == "ParentObject") {
  566. if (nodes.empty())
  567. DefaultLogger::get()->error("LWS: Unexpected keyword: \'ParentObject\'");
  568. else {
  569. nodes.back().parent = strtoul10(c,&c) | (1u << 28u);
  570. }
  571. }
  572. // 'AddCamera': add a camera to the scenegraph
  573. else if ((*it).tokens[0] == "AddCamera") {
  574. // add node to list
  575. LWS::NodeDesc d;
  576. d.type = LWS::NodeDesc::CAMERA;
  577. if (version >= 4) { // handle LWSC 4 explicit ID
  578. d.number = strtoul16(c,&c) & AI_LWS_MASK;
  579. }
  580. else d.number = cur_camera++;
  581. nodes.push_back(d);
  582. num_camera++;
  583. }
  584. // 'CameraName': set name of currently active camera
  585. else if ((*it).tokens[0] == "CameraName") {
  586. if (nodes.empty() || nodes.back().type != LWS::NodeDesc::CAMERA)
  587. DefaultLogger::get()->error("LWS: Unexpected keyword: \'CameraName\'");
  588. else nodes.back().name = c;
  589. }
  590. // 'AddLight': add a light to the scenegraph
  591. else if ((*it).tokens[0] == "AddLight") {
  592. // add node to list
  593. LWS::NodeDesc d;
  594. d.type = LWS::NodeDesc::LIGHT;
  595. if (version >= 4) { // handle LWSC 4 explicit ID
  596. d.number = strtoul16(c,&c) & AI_LWS_MASK;
  597. }
  598. else d.number = cur_light++;
  599. nodes.push_back(d);
  600. num_light++;
  601. }
  602. // 'LightName': set name of currently active light
  603. else if ((*it).tokens[0] == "LightName") {
  604. if (nodes.empty() || nodes.back().type != LWS::NodeDesc::LIGHT)
  605. DefaultLogger::get()->error("LWS: Unexpected keyword: \'LightName\'");
  606. else nodes.back().name = c;
  607. }
  608. // 'LightIntensity': set intensity of currently active light
  609. else if ((*it).tokens[0] == "LightIntensity" || (*it).tokens[0] == "LgtIntensity" ) {
  610. if (nodes.empty() || nodes.back().type != LWS::NodeDesc::LIGHT)
  611. DefaultLogger::get()->error("LWS: Unexpected keyword: \'LightIntensity\'");
  612. else fast_atof_move(c, nodes.back().lightIntensity );
  613. }
  614. // 'LightType': set type of currently active light
  615. else if ((*it).tokens[0] == "LightType") {
  616. if (nodes.empty() || nodes.back().type != LWS::NodeDesc::LIGHT)
  617. DefaultLogger::get()->error("LWS: Unexpected keyword: \'LightType\'");
  618. else nodes.back().lightType = strtoul10(c);
  619. }
  620. // 'LightFalloffType': set falloff type of currently active light
  621. else if ((*it).tokens[0] == "LightFalloffType") {
  622. if (nodes.empty() || nodes.back().type != LWS::NodeDesc::LIGHT)
  623. DefaultLogger::get()->error("LWS: Unexpected keyword: \'LightFalloffType\'");
  624. else nodes.back().lightFalloffType = strtoul10(c);
  625. }
  626. // 'LightConeAngle': set cone angle of currently active light
  627. else if ((*it).tokens[0] == "LightConeAngle") {
  628. if (nodes.empty() || nodes.back().type != LWS::NodeDesc::LIGHT)
  629. DefaultLogger::get()->error("LWS: Unexpected keyword: \'LightConeAngle\'");
  630. else nodes.back().lightConeAngle = fast_atof(c);
  631. }
  632. // 'LightEdgeAngle': set area where we're smoothing from min to max intensity
  633. else if ((*it).tokens[0] == "LightEdgeAngle") {
  634. if (nodes.empty() || nodes.back().type != LWS::NodeDesc::LIGHT)
  635. DefaultLogger::get()->error("LWS: Unexpected keyword: \'LightEdgeAngle\'");
  636. else nodes.back().lightEdgeAngle = fast_atof(c);
  637. }
  638. // 'LightColor': set color of currently active light
  639. else if ((*it).tokens[0] == "LightColor") {
  640. if (nodes.empty() || nodes.back().type != LWS::NodeDesc::LIGHT)
  641. DefaultLogger::get()->error("LWS: Unexpected keyword: \'LightColor\'");
  642. else {
  643. c = fast_atof_move(c, (float&) nodes.back().lightColor.r );
  644. SkipSpaces(&c);
  645. c = fast_atof_move(c, (float&) nodes.back().lightColor.g );
  646. SkipSpaces(&c);
  647. c = fast_atof_move(c, (float&) nodes.back().lightColor.b );
  648. }
  649. }
  650. // 'PivotPosition': position of local transformation origin
  651. else if ((*it).tokens[0] == "PivotPosition" || (*it).tokens[0] == "PivotPoint") {
  652. if (nodes.empty())
  653. DefaultLogger::get()->error("LWS: Unexpected keyword: \'PivotPosition\'");
  654. else {
  655. c = fast_atof_move(c, (float&) nodes.back().pivotPos.x );
  656. SkipSpaces(&c);
  657. c = fast_atof_move(c, (float&) nodes.back().pivotPos.y );
  658. SkipSpaces(&c);
  659. c = fast_atof_move(c, (float&) nodes.back().pivotPos.z );
  660. // Mark pivotPos as set
  661. nodes.back().isPivotSet = true;
  662. }
  663. }
  664. }
  665. // resolve parenting
  666. for (std::list<LWS::NodeDesc>::iterator it = nodes.begin(); it != nodes.end(); ++it) {
  667. // check whether there is another node which calls us a parent
  668. for (std::list<LWS::NodeDesc>::iterator dit = nodes.begin(); dit != nodes.end(); ++dit) {
  669. if (dit != it && *it == (*dit).parent) {
  670. if ((*dit).parent_resolved) {
  671. // fixme: it's still possible to produce an overflow due to cross references ..
  672. DefaultLogger::get()->error("LWS: Found cross reference in scenegraph");
  673. continue;
  674. }
  675. (*it).children.push_back(&*dit);
  676. (*dit).parent_resolved = &*it;
  677. }
  678. }
  679. }
  680. // find out how many nodes have no parent yet
  681. unsigned int no_parent = 0;
  682. for (std::list<LWS::NodeDesc>::iterator it = nodes.begin(); it != nodes.end(); ++it) {
  683. if (!(*it).parent_resolved)
  684. ++ no_parent;
  685. }
  686. if (!no_parent)
  687. throw DeadlyImportError("LWS: Unable to find scene root node");
  688. // Load all subsequent files
  689. batch.LoadAll();
  690. // and build the final output graph by attaching the loaded external
  691. // files to ourselves. first build a master graph
  692. aiScene* master = new aiScene();
  693. aiNode* nd = master->mRootNode = new aiNode();
  694. // allocate storage for cameras&lights
  695. if (num_camera) {
  696. master->mCameras = new aiCamera*[master->mNumCameras = num_camera];
  697. }
  698. aiCamera** cams = master->mCameras;
  699. if (num_light) {
  700. master->mLights = new aiLight*[master->mNumLights = num_light];
  701. }
  702. aiLight** lights = master->mLights;
  703. std::vector<AttachmentInfo> attach;
  704. std::vector<aiNodeAnim*> anims;
  705. nd->mName.Set("<LWSRoot>");
  706. nd->mChildren = new aiNode*[no_parent];
  707. for (std::list<LWS::NodeDesc>::iterator it = nodes.begin(); it != nodes.end(); ++it) {
  708. if (!(*it).parent_resolved) {
  709. aiNode* ro = nd->mChildren[ nd->mNumChildren++ ] = new aiNode();
  710. ro->mParent = nd;
  711. // ... and build the scene graph. If we encounter object nodes,
  712. // add then to our attachment table.
  713. BuildGraph(ro,*it, attach, batch, cams, lights, anims);
  714. }
  715. }
  716. // create a master animation channel for us
  717. if (anims.size()) {
  718. master->mAnimations = new aiAnimation*[master->mNumAnimations = 1];
  719. aiAnimation* anim = master->mAnimations[0] = new aiAnimation();
  720. anim->mName.Set("LWSMasterAnim");
  721. // LWS uses seconds as time units, but we convert to frames
  722. anim->mTicksPerSecond = fps;
  723. anim->mDuration = last-(first-1); /* fixme ... zero or one-based?*/
  724. anim->mChannels = new aiNodeAnim*[anim->mNumChannels = anims.size()];
  725. std::copy(anims.begin(),anims.end(),anim->mChannels);
  726. }
  727. // convert the master scene to RH
  728. MakeLeftHandedProcess monster_cheat;
  729. monster_cheat.Execute(master);
  730. // .. ccw
  731. FlipWindingOrderProcess flipper;
  732. flipper.Execute(master);
  733. // OK ... finally build the output graph
  734. SceneCombiner::MergeScenes(&pScene,master,attach,
  735. AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES | (!configSpeedFlag ? (
  736. AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES_IF_NECESSARY | AI_INT_MERGE_SCENE_GEN_UNIQUE_MATNAMES) : 0));
  737. // Check flags
  738. if (!pScene->mNumMeshes || !pScene->mNumMaterials) {
  739. pScene->mFlags |= AI_SCENE_FLAGS_INCOMPLETE;
  740. if (pScene->mNumAnimations) {
  741. // construct skeleton mesh
  742. SkeletonMeshBuilder builder(pScene);
  743. }
  744. }
  745. }