LWSLoader.cpp 28 KB

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