LWSLoader.cpp 34 KB

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