LWSLoader.cpp 28 KB

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