UnrealLoader.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (ASSIMP)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2010, ASSIMP Development 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 Development 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. #include "AssimpPCH.h"
  41. #ifndef ASSIMP_BUILD_NO_3D_IMPORTER
  42. #include "UnrealLoader.h"
  43. #include "StreamReader.h"
  44. #include "ParsingUtils.h"
  45. #include "fast_atof.h"
  46. #include "ConvertToLHProcess.h"
  47. using namespace Assimp;
  48. // ------------------------------------------------------------------------------------------------
  49. // Constructor to be privately used by Importer
  50. UnrealImporter::UnrealImporter()
  51. : configFrameID (0)
  52. , configHandleFlags (true)
  53. {}
  54. // ------------------------------------------------------------------------------------------------
  55. // Destructor, private as well
  56. UnrealImporter::~UnrealImporter()
  57. {}
  58. // ------------------------------------------------------------------------------------------------
  59. // Returns whether the class can handle the format of the given file.
  60. bool UnrealImporter::CanRead( const std::string& pFile, IOSystem* /*pIOHandler*/, bool /*checkSig*/) const
  61. {
  62. return SimpleExtensionCheck(pFile,"3d","uc");
  63. }
  64. // ------------------------------------------------------------------------------------------------
  65. // Build a string of all file extensions supported
  66. void UnrealImporter::GetExtensionList(std::set<std::string>& extensions)
  67. {
  68. extensions.insert("3d");
  69. extensions.insert("uc");
  70. }
  71. // ------------------------------------------------------------------------------------------------
  72. // Setup configuration properties for the loader
  73. void UnrealImporter::SetupProperties(const Importer* pImp)
  74. {
  75. // The
  76. // AI_CONFIG_IMPORT_UNREAL_KEYFRAME option overrides the
  77. // AI_CONFIG_IMPORT_GLOBAL_KEYFRAME option.
  78. configFrameID = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_UNREAL_KEYFRAME,-1);
  79. if(static_cast<unsigned int>(-1) == configFrameID) {
  80. configFrameID = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_GLOBAL_KEYFRAME,0);
  81. }
  82. // AI_CONFIG_IMPORT_UNREAL_HANDLE_FLAGS, default is true
  83. configHandleFlags = (0 != pImp->GetPropertyInteger(AI_CONFIG_IMPORT_UNREAL_HANDLE_FLAGS,1));
  84. }
  85. // ------------------------------------------------------------------------------------------------
  86. // Imports the given file into the given scene structure.
  87. void UnrealImporter::InternReadFile( const std::string& pFile,
  88. aiScene* pScene, IOSystem* pIOHandler)
  89. {
  90. // For any of the 3 files being passed get the three correct paths
  91. // First of all, determine file extension
  92. std::string::size_type pos = pFile.find_last_of('.');
  93. std::string extension = GetExtension(pFile);
  94. std::string d_path,a_path,uc_path;
  95. if (extension == "3d") {
  96. // jjjj_d.3d
  97. // jjjj_a.3d
  98. pos = pFile.find_last_of('_');
  99. if (std::string::npos == pos) {
  100. throw DeadlyImportError("UNREAL: Unexpected naming scheme");
  101. }
  102. extension = pFile.substr(0,pos);
  103. }
  104. else {
  105. extension = pFile.substr(0,pos);
  106. }
  107. // build proper paths
  108. d_path = extension+"_d.3d";
  109. a_path = extension+"_a.3d";
  110. uc_path = extension+".uc";
  111. DefaultLogger::get()->debug("UNREAL: data file is " + d_path);
  112. DefaultLogger::get()->debug("UNREAL: aniv file is " + a_path);
  113. DefaultLogger::get()->debug("UNREAL: uc file is " + uc_path);
  114. // and open the files ... we can't live without them
  115. IOStream* p = pIOHandler->Open(d_path);
  116. if (!p)
  117. throw DeadlyImportError("UNREAL: Unable to open _d file");
  118. StreamReaderLE d_reader(pIOHandler->Open(d_path));
  119. const uint16_t numTris = d_reader.GetI2();
  120. const uint16_t numVert = d_reader.GetI2();
  121. d_reader.IncPtr(44);
  122. if (!numTris || numVert < 3)
  123. throw DeadlyImportError("UNREAL: Invalid number of vertices/triangles");
  124. // maximum texture index
  125. unsigned int maxTexIdx = 0;
  126. // collect triangles
  127. std::vector<Unreal::Triangle> triangles(numTris);
  128. for (std::vector<Unreal::Triangle>::iterator it = triangles.begin(), end = triangles.end();it != end; ++it) {
  129. Unreal::Triangle& tri = *it;
  130. for (unsigned int i = 0; i < 3;++i) {
  131. tri.mVertex[i] = d_reader.GetI2();
  132. if (tri.mVertex[i] >= numTris) {
  133. DefaultLogger::get()->warn("UNREAL: vertex index out of range");
  134. tri.mVertex[i] = 0;
  135. }
  136. }
  137. tri.mType = d_reader.GetI1();
  138. // handle mesh flagss?
  139. if (configHandleFlags)
  140. tri.mType = Unreal::MF_NORMAL_OS;
  141. else {
  142. // ignore MOD and MASKED for the moment, treat them as two-sided
  143. if (tri.mType == Unreal::MF_NORMAL_MOD_TS || tri.mType == Unreal::MF_NORMAL_MASKED_TS)
  144. tri.mType = Unreal::MF_NORMAL_TS;
  145. }
  146. d_reader.IncPtr(1);
  147. for (unsigned int i = 0; i < 3;++i)
  148. for (unsigned int i2 = 0; i2 < 2;++i2)
  149. tri.mTex[i][i2] = d_reader.GetI1();
  150. tri.mTextureNum = d_reader.GetI1();
  151. maxTexIdx = std::max(maxTexIdx,(unsigned int)tri.mTextureNum);
  152. d_reader.IncPtr(1);
  153. }
  154. p = pIOHandler->Open(a_path);
  155. if (!p)
  156. throw DeadlyImportError("UNREAL: Unable to open _a file");
  157. StreamReaderLE a_reader(pIOHandler->Open(a_path));
  158. // read number of frames
  159. const uint32_t numFrames = a_reader.GetI2();
  160. if (configFrameID >= numFrames)
  161. throw DeadlyImportError("UNREAL: The requested frame does not exist");
  162. uint32_t st = a_reader.GetI2();
  163. if (st != numVert*4)
  164. throw DeadlyImportError("UNREAL: Unexpected aniv file length");
  165. // skip to our frame
  166. a_reader.IncPtr(configFrameID *numVert*4);
  167. // collect vertices
  168. std::vector<aiVector3D> vertices(numVert);
  169. for (std::vector<aiVector3D>::iterator it = vertices.begin(), end = vertices.end(); it != end; ++it) {
  170. int32_t val = a_reader.GetI4();
  171. Unreal::DecompressVertex(*it,val);
  172. }
  173. // list of textures.
  174. std::vector< std::pair<unsigned int, std::string> > textures;
  175. // allocate the output scene
  176. aiNode* nd = pScene->mRootNode = new aiNode();
  177. nd->mName.Set("<UnrealRoot>");
  178. // we can live without the uc file if necessary
  179. boost::scoped_ptr<IOStream> pb (pIOHandler->Open(uc_path));
  180. if (pb.get()) {
  181. std::vector<char> _data;
  182. TextFileToBuffer(pb.get(),_data);
  183. const char* data = &_data[0];
  184. std::vector< std::pair< std::string,std::string > > tempTextures;
  185. // do a quick search in the UC file for some known, usually texture-related, tags
  186. for (;*data;++data) {
  187. if (TokenMatchI(data,"#exec",5)) {
  188. SkipSpacesAndLineEnd(&data);
  189. // #exec TEXTURE IMPORT [...] NAME=jjjjj [...] FILE=jjjj.pcx [...]
  190. if (TokenMatchI(data,"TEXTURE",7)) {
  191. SkipSpacesAndLineEnd(&data);
  192. if (TokenMatchI(data,"IMPORT",6)) {
  193. tempTextures.push_back(std::pair< std::string,std::string >());
  194. std::pair< std::string,std::string >& me = tempTextures.back();
  195. for (;!IsLineEnd(*data);++data) {
  196. if (!::ASSIMP_strincmp(data,"NAME=",5)) {
  197. const char *d = data+=5;
  198. for (;!IsSpaceOrNewLine(*data);++data);
  199. me.first = std::string(d,(size_t)(data-d));
  200. }
  201. else if (!::ASSIMP_strincmp(data,"FILE=",5)) {
  202. const char *d = data+=5;
  203. for (;!IsSpaceOrNewLine(*data);++data);
  204. me.second = std::string(d,(size_t)(data-d));
  205. }
  206. }
  207. if (!me.first.length() || !me.second.length())
  208. tempTextures.pop_back();
  209. }
  210. }
  211. // #exec MESHMAP SETTEXTURE MESHMAP=box NUM=1 TEXTURE=Jtex1
  212. // #exec MESHMAP SCALE MESHMAP=box X=0.1 Y=0.1 Z=0.2
  213. else if (TokenMatchI(data,"MESHMAP",7)) {
  214. SkipSpacesAndLineEnd(&data);
  215. if (TokenMatchI(data,"SETTEXTURE",10)) {
  216. textures.push_back(std::pair<unsigned int, std::string>());
  217. std::pair<unsigned int, std::string>& me = textures.back();
  218. for (;!IsLineEnd(*data);++data) {
  219. if (!::ASSIMP_strincmp(data,"NUM=",4)) {
  220. data += 4;
  221. me.first = strtoul10(data,&data);
  222. }
  223. else if (!::ASSIMP_strincmp(data,"TEXTURE=",8)) {
  224. data += 8;
  225. const char *d = data;
  226. for (;!IsSpaceOrNewLine(*data);++data);
  227. me.second = std::string(d,(size_t)(data-d));
  228. // try to find matching path names, doesn't care if we don't find them
  229. for (std::vector< std::pair< std::string,std::string > >::const_iterator it = tempTextures.begin();
  230. it != tempTextures.end(); ++it) {
  231. if ((*it).first == me.second) {
  232. me.second = (*it).second;
  233. break;
  234. }
  235. }
  236. }
  237. }
  238. }
  239. else if (TokenMatchI(data,"SCALE",5)) {
  240. for (;!IsLineEnd(*data);++data) {
  241. if (data[0] == 'X' && data[1] == '=') {
  242. data = fast_atof_move(data+2,(float&)nd->mTransformation.a1);
  243. }
  244. else if (data[0] == 'Y' && data[1] == '=') {
  245. data = fast_atof_move(data+2,(float&)nd->mTransformation.b2);
  246. }
  247. else if (data[0] == 'Z' && data[1] == '=') {
  248. data = fast_atof_move(data+2,(float&)nd->mTransformation.c3);
  249. }
  250. }
  251. }
  252. }
  253. }
  254. }
  255. }
  256. else {
  257. DefaultLogger::get()->error("Unable to open .uc file");
  258. }
  259. std::vector<Unreal::TempMat> materials;
  260. materials.reserve(textures.size()*2+5);
  261. // find out how many output meshes and materials we'll have and build material indices
  262. for (std::vector<Unreal::Triangle>::iterator it = triangles.begin(), end = triangles.end();it != end; ++it) {
  263. Unreal::Triangle& tri = *it;
  264. Unreal::TempMat mat(tri);
  265. std::vector<Unreal::TempMat>::iterator nt = std::find(materials.begin(),materials.end(),mat);
  266. if (nt == materials.end()) {
  267. // add material
  268. tri.matIndex = materials.size();
  269. mat.numFaces = 1;
  270. materials.push_back(mat);
  271. ++pScene->mNumMeshes;
  272. }
  273. else {
  274. tri.matIndex = static_cast<unsigned int>(nt-materials.begin());
  275. ++nt->numFaces;
  276. }
  277. }
  278. if (!pScene->mNumMeshes) {
  279. throw DeadlyImportError("UNREAL: Unable to find valid mesh data");
  280. }
  281. // allocate meshes and bind them to the node graph
  282. pScene->mMeshes = new aiMesh*[pScene->mNumMeshes];
  283. pScene->mMaterials = new aiMaterial*[pScene->mNumMaterials = pScene->mNumMeshes];
  284. nd->mNumMeshes = pScene->mNumMeshes;
  285. nd->mMeshes = new unsigned int[nd->mNumMeshes];
  286. for (unsigned int i = 0; i < pScene->mNumMeshes;++i) {
  287. aiMesh* m = pScene->mMeshes[i] = new aiMesh();
  288. m->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
  289. const unsigned int num = materials[i].numFaces;
  290. m->mFaces = new aiFace [num];
  291. m->mVertices = new aiVector3D [num*3];
  292. m->mTextureCoords[0] = new aiVector3D [num*3];
  293. nd->mMeshes[i] = i;
  294. // create materials, too
  295. MaterialHelper* mat = new MaterialHelper();
  296. pScene->mMaterials[i] = mat;
  297. // all white by default - texture rulez
  298. aiColor3D color(1.f,1.f,1.f);
  299. aiString s;
  300. ::sprintf(s.data,"mat%i_tx%i_",i,materials[i].tex);
  301. // set the two-sided flag
  302. if (materials[i].type == Unreal::MF_NORMAL_TS) {
  303. const int twosided = 1;
  304. mat->AddProperty(&twosided,1,AI_MATKEY_TWOSIDED);
  305. ::strcat(s.data,"ts_");
  306. }
  307. else ::strcat(s.data,"os_");
  308. // make TRANS faces 90% opaque that RemRedundantMaterials won't catch us
  309. if (materials[i].type == Unreal::MF_NORMAL_TRANS_TS) {
  310. const float opac = 0.9f;
  311. mat->AddProperty(&opac,1,AI_MATKEY_OPACITY);
  312. ::strcat(s.data,"tran_");
  313. }
  314. else ::strcat(s.data,"opaq_");
  315. // a special name for the weapon attachment point
  316. if (materials[i].type == Unreal::MF_WEAPON_PLACEHOLDER) {
  317. s.length = ::sprintf(s.data,"$WeaponTag$");
  318. color = aiColor3D(0.f,0.f,0.f);
  319. }
  320. // set color and name
  321. mat->AddProperty(&color,1,AI_MATKEY_COLOR_DIFFUSE);
  322. s.length = ::strlen(s.data);
  323. mat->AddProperty(&s,AI_MATKEY_NAME);
  324. // set texture, if any
  325. const unsigned int tex = materials[i].tex;
  326. for (std::vector< std::pair< unsigned int, std::string > >::const_iterator it = textures.begin();it != textures.end();++it) {
  327. if ((*it).first == tex) {
  328. s.Set((*it).second);
  329. mat->AddProperty(&s,AI_MATKEY_TEXTURE_DIFFUSE(0));
  330. break;
  331. }
  332. }
  333. }
  334. // fill them.
  335. for (std::vector<Unreal::Triangle>::iterator it = triangles.begin(), end = triangles.end();it != end; ++it) {
  336. Unreal::Triangle& tri = *it;
  337. Unreal::TempMat mat(tri);
  338. std::vector<Unreal::TempMat>::iterator nt = std::find(materials.begin(),materials.end(),mat);
  339. aiMesh* mesh = pScene->mMeshes[nt-materials.begin()];
  340. aiFace& f = mesh->mFaces[mesh->mNumFaces++];
  341. f.mIndices = new unsigned int[f.mNumIndices = 3];
  342. for (unsigned int i = 0; i < 3;++i,mesh->mNumVertices++) {
  343. f.mIndices[i] = mesh->mNumVertices;
  344. mesh->mVertices[mesh->mNumVertices] = vertices[ tri.mVertex[i] ];
  345. mesh->mTextureCoords[0][mesh->mNumVertices] = aiVector3D( tri.mTex[i][0] / 255.f, 1.f - tri.mTex[i][1] / 255.f, 0.f);
  346. }
  347. }
  348. // convert to RH
  349. MakeLeftHandedProcess hero;
  350. hero.Execute(pScene);
  351. FlipWindingOrderProcess flipper;
  352. flipper.Execute(pScene);
  353. }
  354. #endif // !! ASSIMP_BUILD_NO_3D_IMPORTER