LWSLoader.cpp 33 KB

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