LWSLoader.cpp 34 KB

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