UnrealLoader.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  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 UnrealLoader.cpp
  35. * @brief Implementation of the UNREAL (*.3D) importer class
  36. *
  37. * Sources:
  38. * http://local.wasp.uwa.edu.au/~pbourke/dataformats/unreal/
  39. */
  40. #ifndef ASSIMP_BUILD_NO_3D_IMPORTER
  41. #include "AssetLib/Unreal/UnrealLoader.h"
  42. #include "PostProcessing/ConvertToLHProcess.h"
  43. #include <assimp/ParsingUtils.h>
  44. #include <assimp/StreamReader.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 <assimp/Importer.hpp>
  51. #include <cstdint>
  52. #include <memory>
  53. namespace Assimp {
  54. namespace Unreal {
  55. /*
  56. 0 = Normal one-sided
  57. 1 = Normal two-sided
  58. 2 = Translucent two-sided
  59. 3 = Masked two-sided
  60. 4 = Modulation blended two-sided
  61. 8 = Placeholder triangle for weapon positioning (invisible)
  62. */
  63. enum MeshFlags {
  64. MF_NORMAL_OS = 0,
  65. MF_NORMAL_TS = 1,
  66. MF_NORMAL_TRANS_TS = 2,
  67. MF_NORMAL_MASKED_TS = 3,
  68. MF_NORMAL_MOD_TS = 4,
  69. MF_WEAPON_PLACEHOLDER = 8
  70. };
  71. // a single triangle
  72. struct Triangle {
  73. uint16_t mVertex[3]; // Vertex indices
  74. char mType; // James' Mesh Type
  75. char mColor; // Color for flat and Gourand Shaded
  76. unsigned char mTex[3][2]; // Texture UV coordinates
  77. unsigned char mTextureNum; // Source texture offset
  78. char mFlags; // Unreal Mesh Flags (unused)
  79. unsigned int matIndex;
  80. };
  81. // temporary representation for a material
  82. struct TempMat {
  83. TempMat() :
  84. type(MF_NORMAL_OS), tex(), numFaces(0) {}
  85. explicit TempMat(const Triangle &in) :
  86. type((Unreal::MeshFlags)in.mType), tex(in.mTextureNum), numFaces(0) {}
  87. // type of mesh
  88. Unreal::MeshFlags type;
  89. // index of texture
  90. unsigned int tex;
  91. // number of faces using us
  92. unsigned int numFaces;
  93. // for std::find
  94. bool operator==(const TempMat &o) {
  95. return (tex == o.tex && type == o.type);
  96. }
  97. };
  98. struct Vertex {
  99. int32_t X : 11;
  100. int32_t Y : 11;
  101. int32_t Z : 10;
  102. };
  103. // UNREAL vertex compression
  104. inline void CompressVertex(const aiVector3D &v, uint32_t &out) {
  105. union {
  106. Vertex n;
  107. int32_t t;
  108. };
  109. t = 0;
  110. n.X = (int32_t)v.x;
  111. n.Y = (int32_t)v.y;
  112. n.Z = (int32_t)v.z;
  113. ::memcpy(&out, &t, sizeof(int32_t));
  114. }
  115. // UNREAL vertex decompression
  116. inline void DecompressVertex(aiVector3D &v, int32_t in) {
  117. union {
  118. Vertex n;
  119. int32_t i;
  120. };
  121. i = in;
  122. v.x = (float)n.X;
  123. v.y = (float)n.Y;
  124. v.z = (float)n.Z;
  125. }
  126. } // end namespace Unreal
  127. static constexpr aiImporterDesc desc = {
  128. "Unreal Mesh Importer",
  129. "",
  130. "",
  131. "",
  132. aiImporterFlags_SupportTextFlavour,
  133. 0,
  134. 0,
  135. 0,
  136. 0,
  137. "3d uc"
  138. };
  139. // ------------------------------------------------------------------------------------------------
  140. // Constructor to be privately used by Importer
  141. UnrealImporter::UnrealImporter() :
  142. mConfigFrameID(0), mConfigHandleFlags(true) {
  143. // empty
  144. }
  145. // ------------------------------------------------------------------------------------------------
  146. // Destructor, private as well
  147. UnrealImporter::~UnrealImporter() = default;
  148. // ------------------------------------------------------------------------------------------------
  149. // Returns whether the class can handle the format of the given file.
  150. bool UnrealImporter::CanRead(const std::string &filename, IOSystem * /*pIOHandler*/, bool /*checkSig*/) const {
  151. return SimpleExtensionCheck(filename, "3d", "uc");
  152. }
  153. // ------------------------------------------------------------------------------------------------
  154. // Build a string of all file extensions supported
  155. const aiImporterDesc *UnrealImporter::GetInfo() const {
  156. return &desc;
  157. }
  158. // ------------------------------------------------------------------------------------------------
  159. // Setup configuration properties for the loader
  160. void UnrealImporter::SetupProperties(const Importer *pImp) {
  161. // The
  162. // AI_CONFIG_IMPORT_UNREAL_KEYFRAME option overrides the
  163. // AI_CONFIG_IMPORT_GLOBAL_KEYFRAME option.
  164. mConfigFrameID = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_UNREAL_KEYFRAME, -1);
  165. if (static_cast<unsigned int>(-1) == mConfigFrameID) {
  166. mConfigFrameID = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_GLOBAL_KEYFRAME, 0);
  167. }
  168. // AI_CONFIG_IMPORT_UNREAL_HANDLE_FLAGS, default is true
  169. mConfigHandleFlags = (0 != pImp->GetPropertyInteger(AI_CONFIG_IMPORT_UNREAL_HANDLE_FLAGS, 1));
  170. }
  171. // ------------------------------------------------------------------------------------------------
  172. // Imports the given file into the given scene structure.
  173. void UnrealImporter::InternReadFile(const std::string &pFile,
  174. aiScene *pScene, IOSystem *pIOHandler) {
  175. // For any of the 3 files being passed get the three correct paths
  176. // First of all, determine file extension
  177. std::string::size_type pos = pFile.find_last_of('.');
  178. std::string extension = GetExtension(pFile);
  179. std::string d_path, a_path, uc_path;
  180. if (extension == "3d") {
  181. // jjjj_d.3d
  182. // jjjj_a.3d
  183. pos = pFile.find_last_of('_');
  184. if (std::string::npos == pos) {
  185. throw DeadlyImportError("UNREAL: Unexpected naming scheme");
  186. }
  187. extension = pFile.substr(0, pos);
  188. } else {
  189. extension = pFile.substr(0, pos);
  190. }
  191. // build proper paths
  192. d_path = extension + "_d.3d";
  193. a_path = extension + "_a.3d";
  194. uc_path = extension + ".uc";
  195. ASSIMP_LOG_DEBUG("UNREAL: data file is ", d_path);
  196. ASSIMP_LOG_DEBUG("UNREAL: aniv file is ", a_path);
  197. ASSIMP_LOG_DEBUG("UNREAL: uc file is ", uc_path);
  198. // and open the files ... we can't live without them
  199. std::unique_ptr<IOStream> p(pIOHandler->Open(d_path));
  200. if (!p)
  201. throw DeadlyImportError("UNREAL: Unable to open _d file");
  202. StreamReaderLE d_reader(pIOHandler->Open(d_path));
  203. const uint16_t numTris = d_reader.GetI2();
  204. const uint16_t numVert = d_reader.GetI2();
  205. d_reader.IncPtr(44);
  206. if (!numTris || numVert < 3)
  207. throw DeadlyImportError("UNREAL: Invalid number of vertices/triangles");
  208. // maximum texture index
  209. unsigned int maxTexIdx = 0;
  210. // collect triangles
  211. std::vector<Unreal::Triangle> triangles(numTris);
  212. for (auto &tri : triangles) {
  213. for (unsigned int i = 0; i < 3; ++i) {
  214. tri.mVertex[i] = d_reader.GetI2();
  215. if (tri.mVertex[i] >= numTris) {
  216. ASSIMP_LOG_WARN("UNREAL: vertex index out of range");
  217. tri.mVertex[i] = 0;
  218. }
  219. }
  220. tri.mType = d_reader.GetI1();
  221. // handle mesh flagss?
  222. if (mConfigHandleFlags)
  223. tri.mType = Unreal::MF_NORMAL_OS;
  224. else {
  225. // ignore MOD and MASKED for the moment, treat them as two-sided
  226. if (tri.mType == Unreal::MF_NORMAL_MOD_TS || tri.mType == Unreal::MF_NORMAL_MASKED_TS)
  227. tri.mType = Unreal::MF_NORMAL_TS;
  228. }
  229. d_reader.IncPtr(1);
  230. for (unsigned int i = 0; i < 3; ++i)
  231. for (unsigned int i2 = 0; i2 < 2; ++i2)
  232. tri.mTex[i][i2] = d_reader.GetI1();
  233. tri.mTextureNum = d_reader.GetI1();
  234. maxTexIdx = std::max(maxTexIdx, (unsigned int)tri.mTextureNum);
  235. d_reader.IncPtr(1);
  236. }
  237. p.reset(pIOHandler->Open(a_path));
  238. if (!p)
  239. throw DeadlyImportError("UNREAL: Unable to open _a file");
  240. StreamReaderLE a_reader(pIOHandler->Open(a_path));
  241. // read number of frames
  242. const uint32_t numFrames = a_reader.GetI2();
  243. if (mConfigFrameID >= numFrames) {
  244. throw DeadlyImportError("UNREAL: The requested frame does not exist");
  245. }
  246. uint32_t st = a_reader.GetI2();
  247. if (st != numVert * 4u)
  248. throw DeadlyImportError("UNREAL: Unexpected aniv file length");
  249. // skip to our frame
  250. a_reader.IncPtr(mConfigFrameID * numVert * 4);
  251. // collect vertices
  252. std::vector<aiVector3D> vertices(numVert);
  253. for (auto &vertex : vertices) {
  254. int32_t val = a_reader.GetI4();
  255. Unreal::DecompressVertex(vertex, val);
  256. }
  257. // list of textures.
  258. std::vector<std::pair<unsigned int, std::string>> textures;
  259. // allocate the output scene
  260. aiNode *nd = pScene->mRootNode = new aiNode();
  261. nd->mName.Set("<UnrealRoot>");
  262. // we can live without the uc file if necessary
  263. std::unique_ptr<IOStream> pb(pIOHandler->Open(uc_path));
  264. if (pb) {
  265. std::vector<char> _data;
  266. TextFileToBuffer(pb.get(), _data);
  267. const char *data = &_data[0];
  268. std::vector<std::pair<std::string, std::string>> tempTextures;
  269. // do a quick search in the UC file for some known, usually texture-related, tags
  270. for (; *data; ++data) {
  271. if (TokenMatchI(data, "#exec", 5)) {
  272. SkipSpacesAndLineEnd(&data);
  273. // #exec TEXTURE IMPORT [...] NAME=jjjjj [...] FILE=jjjj.pcx [...]
  274. if (TokenMatchI(data, "TEXTURE", 7)) {
  275. SkipSpacesAndLineEnd(&data);
  276. if (TokenMatchI(data, "IMPORT", 6)) {
  277. tempTextures.emplace_back();
  278. std::pair<std::string, std::string> &me = tempTextures.back();
  279. for (; !IsLineEnd(*data); ++data) {
  280. if (!ASSIMP_strincmp(data, "NAME=", 5)) {
  281. const char *d = data += 5;
  282. for (; !IsSpaceOrNewLine(*data); ++data)
  283. ;
  284. me.first = std::string(d, (size_t)(data - d));
  285. } else if (!ASSIMP_strincmp(data, "FILE=", 5)) {
  286. const char *d = data += 5;
  287. for (; !IsSpaceOrNewLine(*data); ++data)
  288. ;
  289. me.second = std::string(d, (size_t)(data - d));
  290. }
  291. }
  292. if (!me.first.length() || !me.second.length())
  293. tempTextures.pop_back();
  294. }
  295. }
  296. // #exec MESHMAP SETTEXTURE MESHMAP=box NUM=1 TEXTURE=Jtex1
  297. // #exec MESHMAP SCALE MESHMAP=box X=0.1 Y=0.1 Z=0.2
  298. else if (TokenMatchI(data, "MESHMAP", 7)) {
  299. SkipSpacesAndLineEnd(&data);
  300. if (TokenMatchI(data, "SETTEXTURE", 10)) {
  301. textures.emplace_back();
  302. std::pair<unsigned int, std::string> &me = textures.back();
  303. for (; !IsLineEnd(*data); ++data) {
  304. if (!ASSIMP_strincmp(data, "NUM=", 4)) {
  305. data += 4;
  306. me.first = strtoul10(data, &data);
  307. } else if (!ASSIMP_strincmp(data, "TEXTURE=", 8)) {
  308. data += 8;
  309. const char *d = data;
  310. for (; !IsSpaceOrNewLine(*data); ++data)
  311. ;
  312. me.second = std::string(d, (size_t)(data - d));
  313. // try to find matching path names, doesn't care if we don't find them
  314. for (std::vector<std::pair<std::string, std::string>>::const_iterator it = tempTextures.begin();
  315. it != tempTextures.end(); ++it) {
  316. if ((*it).first == me.second) {
  317. me.second = (*it).second;
  318. break;
  319. }
  320. }
  321. }
  322. }
  323. } else if (TokenMatchI(data, "SCALE", 5)) {
  324. for (; !IsLineEnd(*data); ++data) {
  325. if (data[0] == 'X' && data[1] == '=') {
  326. data = fast_atoreal_move<float>(data + 2, (float &)nd->mTransformation.a1);
  327. } else if (data[0] == 'Y' && data[1] == '=') {
  328. data = fast_atoreal_move<float>(data + 2, (float &)nd->mTransformation.b2);
  329. } else if (data[0] == 'Z' && data[1] == '=') {
  330. data = fast_atoreal_move<float>(data + 2, (float &)nd->mTransformation.c3);
  331. }
  332. }
  333. }
  334. }
  335. }
  336. }
  337. } else {
  338. ASSIMP_LOG_ERROR("Unable to open .uc file");
  339. }
  340. std::vector<Unreal::TempMat> materials;
  341. materials.reserve(textures.size() * 2 + 5);
  342. // find out how many output meshes and materials we'll have and build material indices
  343. for (Unreal::Triangle &tri : triangles) {
  344. Unreal::TempMat mat(tri);
  345. std::vector<Unreal::TempMat>::iterator nt = std::find(materials.begin(), materials.end(), mat);
  346. if (nt == materials.end()) {
  347. // add material
  348. tri.matIndex = static_cast<unsigned int>(materials.size());
  349. mat.numFaces = 1;
  350. materials.push_back(mat);
  351. ++pScene->mNumMeshes;
  352. } else {
  353. tri.matIndex = static_cast<unsigned int>(nt - materials.begin());
  354. ++nt->numFaces;
  355. }
  356. }
  357. if (!pScene->mNumMeshes) {
  358. throw DeadlyImportError("UNREAL: Unable to find valid mesh data");
  359. }
  360. // allocate meshes and bind them to the node graph
  361. pScene->mMeshes = new aiMesh *[pScene->mNumMeshes];
  362. pScene->mMaterials = new aiMaterial *[pScene->mNumMaterials = pScene->mNumMeshes];
  363. nd->mNumMeshes = pScene->mNumMeshes;
  364. nd->mMeshes = new unsigned int[nd->mNumMeshes];
  365. for (unsigned int i = 0; i < pScene->mNumMeshes; ++i) {
  366. aiMesh *m = pScene->mMeshes[i] = new aiMesh();
  367. m->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
  368. const unsigned int num = materials[i].numFaces;
  369. m->mFaces = new aiFace[num];
  370. m->mVertices = new aiVector3D[num * 3];
  371. m->mTextureCoords[0] = new aiVector3D[num * 3];
  372. nd->mMeshes[i] = i;
  373. // create materials, too
  374. aiMaterial *mat = new aiMaterial();
  375. pScene->mMaterials[i] = mat;
  376. // all white by default - texture rulez
  377. aiColor3D color(1.f, 1.f, 1.f);
  378. aiString s;
  379. ::ai_snprintf(s.data, MAXLEN, "mat%u_tx%u_", i, materials[i].tex);
  380. // set the two-sided flag
  381. if (materials[i].type == Unreal::MF_NORMAL_TS) {
  382. const int twosided = 1;
  383. mat->AddProperty(&twosided, 1, AI_MATKEY_TWOSIDED);
  384. ::strcat(s.data, "ts_");
  385. } else
  386. ::strcat(s.data, "os_");
  387. // make TRANS faces 90% opaque that RemRedundantMaterials won't catch us
  388. if (materials[i].type == Unreal::MF_NORMAL_TRANS_TS) {
  389. const float opac = 0.9f;
  390. mat->AddProperty(&opac, 1, AI_MATKEY_OPACITY);
  391. ::strcat(s.data, "tran_");
  392. } else
  393. ::strcat(s.data, "opaq_");
  394. // a special name for the weapon attachment point
  395. if (materials[i].type == Unreal::MF_WEAPON_PLACEHOLDER) {
  396. s.length = ::ai_snprintf(s.data, MAXLEN, "$WeaponTag$");
  397. color = aiColor3D(0.f, 0.f, 0.f);
  398. }
  399. // set color and name
  400. mat->AddProperty(&color, 1, AI_MATKEY_COLOR_DIFFUSE);
  401. s.length = static_cast<ai_uint32>(::strlen(s.data));
  402. mat->AddProperty(&s, AI_MATKEY_NAME);
  403. // set texture, if any
  404. const unsigned int tex = materials[i].tex;
  405. for (std::vector<std::pair<unsigned int, std::string>>::const_iterator it = textures.begin(); it != textures.end(); ++it) {
  406. if ((*it).first == tex) {
  407. s.Set((*it).second);
  408. mat->AddProperty(&s, AI_MATKEY_TEXTURE_DIFFUSE(0));
  409. break;
  410. }
  411. }
  412. }
  413. // fill them.
  414. for (const Unreal::Triangle &tri : triangles) {
  415. Unreal::TempMat mat(tri);
  416. std::vector<Unreal::TempMat>::iterator nt = std::find(materials.begin(), materials.end(), mat);
  417. aiMesh *mesh = pScene->mMeshes[nt - materials.begin()];
  418. aiFace &f = mesh->mFaces[mesh->mNumFaces++];
  419. f.mIndices = new unsigned int[f.mNumIndices = 3];
  420. for (unsigned int i = 0; i < 3; ++i, mesh->mNumVertices++) {
  421. f.mIndices[i] = mesh->mNumVertices;
  422. mesh->mVertices[mesh->mNumVertices] = vertices[tri.mVertex[i]];
  423. mesh->mTextureCoords[0][mesh->mNumVertices] = aiVector3D(tri.mTex[i][0] / 255.f, 1.f - tri.mTex[i][1] / 255.f, 0.f);
  424. }
  425. }
  426. // convert to RH
  427. MakeLeftHandedProcess hero;
  428. hero.Execute(pScene);
  429. FlipWindingOrderProcess flipper;
  430. flipper.Execute(pScene);
  431. }
  432. } // namespace Assimp
  433. #endif // !! ASSIMP_BUILD_NO_3D_IMPORTER