Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

352 linhas
11 KiB

  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2012, assimp team
  5. All rights reserved.
  6. Redistribution and use of this software in source and binary forms,
  7. with or without modification, are permitted provided that the
  8. following conditions are met:
  9. * Redistributions of source code must retain the above
  10. copyright notice, this list of conditions and the
  11. following disclaimer.
  12. * Redistributions in binary form must reproduce the above
  13. copyright notice, this list of conditions and the
  14. following disclaimer in the documentation and/or other
  15. materials provided with the distribution.
  16. * Neither the name of the assimp team, nor the names of its
  17. contributors may be used to endorse or promote products
  18. derived from this software without specific prior
  19. written permission of the assimp team.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. ----------------------------------------------------------------------
  32. */
  33. #include "AssimpPCH.h"
  34. #ifndef ASSIMP_BUILD_NO_EXPORT
  35. #ifndef ASSIMP_BUILD_NO_OBJ_EXPORTER
  36. #include "ObjExporter.h"
  37. #include "../include/assimp/version.h"
  38. using namespace Assimp;
  39. namespace Assimp {
  40. // ------------------------------------------------------------------------------------------------
  41. // Worker function for exporting a scene to Wavefront OBJ. Prototyped and registered in Exporter.cpp
  42. void ExportSceneObj(const char* pFile,IOSystem* pIOSystem, const aiScene* pScene)
  43. {
  44. // invoke the exporter
  45. ObjExporter exporter(pFile, pScene);
  46. // we're still here - export successfully completed. Write both the main OBJ file and the material script
  47. {
  48. boost::scoped_ptr<IOStream> outfile (pIOSystem->Open(pFile,"wt"));
  49. if(outfile == NULL) {
  50. throw DeadlyExportError("could not open output .obj file: " + std::string(pFile));
  51. }
  52. outfile->Write( exporter.mOutput.str().c_str(), static_cast<size_t>(exporter.mOutput.tellp()),1);
  53. }
  54. {
  55. boost::scoped_ptr<IOStream> outfile (pIOSystem->Open(exporter.GetMaterialLibFileName(),"wt"));
  56. if(outfile == NULL) {
  57. throw DeadlyExportError("could not open output .mtl file: " + std::string(exporter.GetMaterialLibFileName()));
  58. }
  59. outfile->Write( exporter.mOutputMat.str().c_str(), static_cast<size_t>(exporter.mOutputMat.tellp()),1);
  60. }
  61. }
  62. } // end of namespace Assimp
  63. // ------------------------------------------------------------------------------------------------
  64. ObjExporter :: ObjExporter(const char* _filename, const aiScene* pScene)
  65. : filename(_filename)
  66. , pScene(pScene)
  67. , endl("\n")
  68. {
  69. // make sure that all formatting happens using the standard, C locale and not the user's current locale
  70. const std::locale& l = std::locale("C");
  71. mOutput.imbue(l);
  72. mOutputMat.imbue(l);
  73. WriteGeometryFile();
  74. WriteMaterialFile();
  75. }
  76. // ------------------------------------------------------------------------------------------------
  77. std::string ObjExporter :: GetMaterialLibName()
  78. {
  79. // within the Obj file, we use just the relative file name with the path stripped
  80. const std::string& s = GetMaterialLibFileName();
  81. std::string::size_type il = s.find_last_of("/\\");
  82. if (il != std::string::npos) {
  83. return s.substr(il + 1);
  84. }
  85. return s;
  86. }
  87. // ------------------------------------------------------------------------------------------------
  88. std::string ObjExporter :: GetMaterialLibFileName()
  89. {
  90. return filename + ".mtl";
  91. }
  92. // ------------------------------------------------------------------------------------------------
  93. void ObjExporter :: WriteHeader(std::ostringstream& out)
  94. {
  95. out << "# File produced by Open Asset Import Library (http://www.assimp.sf.net)" << endl;
  96. out << "# (assimp v" << aiGetVersionMajor() << '.' << aiGetVersionMinor() << '.' << aiGetVersionRevision() << ")" << endl << endl;
  97. }
  98. // ------------------------------------------------------------------------------------------------
  99. std::string ObjExporter :: GetMaterialName(unsigned int index)
  100. {
  101. const aiMaterial* const mat = pScene->mMaterials[index];
  102. aiString s;
  103. if(AI_SUCCESS == mat->Get(AI_MATKEY_NAME,s)) {
  104. return std::string(s.data,s.length);
  105. }
  106. char number[ sizeof(unsigned int) * 3 + 1 ];
  107. ASSIMP_itoa10(number,index);
  108. return "$Material_" + std::string(number);
  109. }
  110. // ------------------------------------------------------------------------------------------------
  111. void ObjExporter :: WriteMaterialFile()
  112. {
  113. WriteHeader(mOutputMat);
  114. for(unsigned int i = 0; i < pScene->mNumMaterials; ++i) {
  115. const aiMaterial* const mat = pScene->mMaterials[i];
  116. int illum = 1;
  117. mOutputMat << "newmtl " << GetMaterialName(i) << endl;
  118. aiColor4D c;
  119. if(AI_SUCCESS == mat->Get(AI_MATKEY_COLOR_DIFFUSE,c)) {
  120. mOutputMat << "kd " << c.r << " " << c.g << " " << c.b << endl;
  121. }
  122. if(AI_SUCCESS == mat->Get(AI_MATKEY_COLOR_AMBIENT,c)) {
  123. mOutputMat << "ka " << c.r << " " << c.g << " " << c.b << endl;
  124. }
  125. if(AI_SUCCESS == mat->Get(AI_MATKEY_COLOR_SPECULAR,c)) {
  126. mOutputMat << "ks " << c.r << " " << c.g << " " << c.b << endl;
  127. }
  128. if(AI_SUCCESS == mat->Get(AI_MATKEY_COLOR_EMISSIVE,c)) {
  129. mOutputMat << "ke " << c.r << " " << c.g << " " << c.b << endl;
  130. }
  131. float o;
  132. if(AI_SUCCESS == mat->Get(AI_MATKEY_OPACITY,o)) {
  133. mOutputMat << "d " << o << endl;
  134. }
  135. if(AI_SUCCESS == mat->Get(AI_MATKEY_SHININESS,o) && o) {
  136. mOutputMat << "Ns " << o << endl;
  137. illum = 2;
  138. }
  139. mOutputMat << "illum " << illum << endl;
  140. aiString s;
  141. if(AI_SUCCESS == mat->Get(AI_MATKEY_TEXTURE_DIFFUSE(0),s)) {
  142. mOutputMat << "map_kd " << s.data << endl;
  143. }
  144. if(AI_SUCCESS == mat->Get(AI_MATKEY_TEXTURE_AMBIENT(0),s)) {
  145. mOutputMat << "map_ka " << s.data << endl;
  146. }
  147. if(AI_SUCCESS == mat->Get(AI_MATKEY_TEXTURE_SPECULAR(0),s)) {
  148. mOutputMat << "map_ks " << s.data << endl;
  149. }
  150. if(AI_SUCCESS == mat->Get(AI_MATKEY_TEXTURE_SHININESS(0),s)) {
  151. mOutputMat << "map_ns " << s.data << endl;
  152. }
  153. if(AI_SUCCESS == mat->Get(AI_MATKEY_TEXTURE_HEIGHT(0),s) || AI_SUCCESS == mat->Get(AI_MATKEY_TEXTURE_NORMALS(0),s)) {
  154. // implementations seem to vary here, so write both variants
  155. mOutputMat << "bump " << s.data << endl;
  156. mOutputMat << "map_bump " << s.data << endl;
  157. }
  158. mOutputMat << endl;
  159. }
  160. }
  161. // ------------------------------------------------------------------------------------------------
  162. void ObjExporter :: WriteGeometryFile()
  163. {
  164. WriteHeader(mOutput);
  165. mOutput << "mtllib " << GetMaterialLibName() << endl << endl;
  166. // collect mesh geometry
  167. aiMatrix4x4 mBase;
  168. AddNode(pScene->mRootNode,mBase);
  169. // write vertex positions
  170. vpMap.getVectors(vp);
  171. mOutput << "# " << vp.size() << " vertex positions" << endl;
  172. BOOST_FOREACH(const aiVector3D& v, vp) {
  173. mOutput << "v " << v.x << " " << v.y << " " << v.z << endl;
  174. }
  175. mOutput << endl;
  176. // write uv coordinates
  177. vtMap.getVectors(vt);
  178. mOutput << "# " << vt.size() << " UV coordinates" << endl;
  179. BOOST_FOREACH(const aiVector3D& v, vt) {
  180. mOutput << "vt " << v.x << " " << v.y << " " << v.z << endl;
  181. }
  182. mOutput << endl;
  183. // write vertex normals
  184. vnMap.getVectors(vn);
  185. mOutput << "# " << vn.size() << " vertex normals" << endl;
  186. BOOST_FOREACH(const aiVector3D& v, vn) {
  187. mOutput << "vn " << v.x << " " << v.y << " " << v.z << endl;
  188. }
  189. mOutput << endl;
  190. // now write all mesh instances
  191. BOOST_FOREACH(const MeshInstance& m, meshes) {
  192. mOutput << "# Mesh \'" << m.name << "\' with " << m.faces.size() << " faces" << endl;
  193. mOutput << "g " << m.name << endl;
  194. mOutput << "usemtl " << m.matname << endl;
  195. BOOST_FOREACH(const Face& f, m.faces) {
  196. mOutput << f.kind << ' ';
  197. BOOST_FOREACH(const FaceVertex& fv, f.indices) {
  198. mOutput << ' ' << fv.vp;
  199. if (f.kind != 'p') {
  200. if (fv.vt || f.kind == 'f') {
  201. mOutput << '/';
  202. }
  203. if (fv.vt) {
  204. mOutput << fv.vt;
  205. }
  206. if (f.kind == 'f') {
  207. mOutput << '/';
  208. if (fv.vn) {
  209. mOutput << fv.vn;
  210. }
  211. }
  212. }
  213. }
  214. mOutput << endl;
  215. }
  216. mOutput << endl;
  217. }
  218. }
  219. int ObjExporter::vecIndexMap::getIndex(const aiVector3D& vec)
  220. {
  221. vecIndexMap::dataType::iterator vertIt = vecMap.find(vec);
  222. if(vertIt != vecMap.end()){// vertex already exists, so reference it
  223. return vertIt->second;
  224. }
  225. vecMap[vec] = mNextIndex;
  226. int ret = mNextIndex;
  227. mNextIndex++;
  228. return ret;
  229. }
  230. void ObjExporter::vecIndexMap::getVectors( std::vector<aiVector3D>& vecs )
  231. {
  232. vecs.resize(vecMap.size());
  233. for(vecIndexMap::dataType::iterator it = vecMap.begin(); it != vecMap.end(); it++){
  234. vecs[it->second-1] = it->first;
  235. }
  236. }
  237. // ------------------------------------------------------------------------------------------------
  238. void ObjExporter :: AddMesh(const aiString& name, const aiMesh* m, const aiMatrix4x4& mat)
  239. {
  240. meshes.push_back(MeshInstance());
  241. MeshInstance& mesh = meshes.back();
  242. mesh.name = std::string(name.data,name.length) + (m->mName.length ? "_"+std::string(m->mName.data,m->mName.length) : "");
  243. mesh.matname = GetMaterialName(m->mMaterialIndex);
  244. mesh.faces.resize(m->mNumFaces);
  245. for(unsigned int i = 0; i < m->mNumFaces; ++i) {
  246. const aiFace& f = m->mFaces[i];
  247. Face& face = mesh.faces[i];
  248. switch (f.mNumIndices) {
  249. case 1:
  250. face.kind = 'p';
  251. break;
  252. case 2:
  253. face.kind = 'l';
  254. break;
  255. default:
  256. face.kind = 'f';
  257. }
  258. face.indices.resize(f.mNumIndices);
  259. for(unsigned int a = 0; a < f.mNumIndices; ++a) {
  260. const unsigned int idx = f.mIndices[a];
  261. aiVector3D vert = mat * m->mVertices[idx];
  262. face.indices[a].vp = vpMap.getIndex(vert);
  263. if (m->mNormals) {
  264. face.indices[a].vn = vnMap.getIndex(m->mNormals[idx]);
  265. }
  266. else{
  267. face.indices[a].vn = 0;
  268. }
  269. if (m->mTextureCoords[0]) {
  270. face.indices[a].vt = vtMap.getIndex(m->mTextureCoords[0][idx]);
  271. }
  272. else{
  273. face.indices[a].vt = 0;
  274. }
  275. }
  276. }
  277. }
  278. // ------------------------------------------------------------------------------------------------
  279. void ObjExporter :: AddNode(const aiNode* nd, const aiMatrix4x4& mParent)
  280. {
  281. const aiMatrix4x4& mAbs = mParent * nd->mTransformation;
  282. for(unsigned int i = 0; i < nd->mNumMeshes; ++i) {
  283. AddMesh(nd->mName, pScene->mMeshes[nd->mMeshes[i]],mAbs);
  284. }
  285. for(unsigned int i = 0; i < nd->mNumChildren; ++i) {
  286. AddNode(nd->mChildren[i],mAbs);
  287. }
  288. }
  289. #endif
  290. #endif