LWSLoader.cpp 34 KB

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