ImageExtractor.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2012, 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 ImageExtractor.cpp
  35. * @brief Implementation of the 'assimp extract' utility
  36. */
  37. #include "Main.h"
  38. #include <../code/fast_atof.h>
  39. #include <../code/StringComparison.h>
  40. const char* AICMD_MSG_DUMP_HELP_E =
  41. "assimp extract <model> [<out>] [-t<n>] [-f<fmt>] [-ba] [-s] [common parameters]\n"
  42. "\t -ba Writes BMP's with alpha channel\n"
  43. "\t -t<n> Zero-based index of the texture to be extracted \n"
  44. "\t -f<f> Specify the file format if <out> is omitted \n"
  45. "\t[See the assimp_cmd docs for a full list of all common parameters] \n"
  46. "\t -cfast Fast post processing preset, runs just a few important steps \n"
  47. "\t -cdefault Default post processing: runs all recommended steps\n"
  48. "\t -cfull Fires almost all post processing steps \n"
  49. ;
  50. #define AI_EXTRACT_WRITE_BMP_ALPHA 0x1
  51. #include <assimp/Compiler/pushpack1.h>
  52. // -----------------------------------------------------------------------------------
  53. // Data structure for the first header of a BMP
  54. struct BITMAPFILEHEADER
  55. {
  56. uint16_t bfType ;
  57. uint32_t bfSize;
  58. uint16_t bfReserved1 ;
  59. uint16_t bfReserved2;
  60. uint32_t bfOffBits;
  61. } PACK_STRUCT;
  62. // -----------------------------------------------------------------------------------
  63. // Data structure for the second header of a BMP
  64. struct BITMAPINFOHEADER
  65. {
  66. int32_t biSize;
  67. int32_t biWidth;
  68. int32_t biHeight;
  69. int16_t biPlanes;
  70. int16_t biBitCount;
  71. uint32_t biCompression;
  72. int32_t biSizeImage;
  73. int32_t biXPelsPerMeter;
  74. int32_t biYPelsPerMeter;
  75. int32_t biClrUsed;
  76. int32_t biClrImportant;
  77. // pixel data follows header
  78. } PACK_STRUCT;
  79. // -----------------------------------------------------------------------------------
  80. // Data structure for the header of a TGA
  81. struct TGA_HEADER
  82. {
  83. uint8_t identsize; // size of ID field that follows 18 byte header (0 usually)
  84. uint8_t colourmaptype; // type of colour map 0=none, 1=has palette
  85. uint8_t imagetype; // type of image 0=none,1=indexed,2=rgb,3=grey,+8=rle packed
  86. uint16_t colourmapstart; // first colour map entry in palette
  87. uint16_t colourmaplength; // number of colours in palette
  88. uint8_t colourmapbits; // number of bits per palette entry 15,16,24,32
  89. uint16_t xstart; // image x origin
  90. uint16_t ystart; // image y origin
  91. uint16_t width; // image width in pixels
  92. uint16_t height; // image height in pixels
  93. uint8_t bits; // image bits per pixel 8,16,24,32
  94. uint8_t descriptor; // image descriptor bits (vh flip bits)
  95. // pixel data follows header
  96. } PACK_STRUCT;
  97. #include <assimp/Compiler/poppack1.h>
  98. // -----------------------------------------------------------------------------------
  99. // Save a texture as bitmap
  100. int SaveAsBMP (FILE* file, const aiTexel* data, unsigned int width, unsigned int height, bool SaveAlpha = false)
  101. {
  102. if (!file || !data) {
  103. return 1;
  104. }
  105. const unsigned int numc = (SaveAlpha ? 4 : 3);
  106. unsigned char* buffer = new unsigned char[width*height*numc];
  107. for (unsigned int y = 0; y < height; ++y) {
  108. for (unsigned int x = 0; x < width; ++x) {
  109. unsigned char* s = &buffer[(y*width+x) * numc];
  110. const aiTexel* t = &data [ y*width+x];
  111. s[0] = t->b;
  112. s[1] = t->g;
  113. s[2] = t->r;
  114. if (4 == numc)
  115. s[3] = t->a;
  116. }
  117. }
  118. BITMAPFILEHEADER header;
  119. header.bfType = 'B' | (int('M') << 8u);
  120. header.bfOffBits = sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER);
  121. header.bfSize = header.bfOffBits+width*height*numc;
  122. header.bfReserved1 = header.bfReserved2 = 0;
  123. fwrite(&header,sizeof(BITMAPFILEHEADER),1,file);
  124. BITMAPINFOHEADER info;
  125. info.biSize = 40;
  126. info.biWidth = width;
  127. info.biHeight = height;
  128. info.biPlanes = 1;
  129. info.biBitCount = numc<<3;
  130. info.biCompression = 0;
  131. info.biSizeImage = width*height*numc;
  132. info.biXPelsPerMeter = 1; // dummy
  133. info.biYPelsPerMeter = 1; // dummy
  134. info.biClrUsed = 0;
  135. info.biClrImportant = 0;
  136. fwrite(&info,sizeof(BITMAPINFOHEADER),1,file);
  137. unsigned char* temp = buffer+info.biSizeImage;
  138. const unsigned int row = width*numc;
  139. for (int y = 0; temp -= row,y < info.biHeight;++y) {
  140. fwrite(temp,row,1,file);
  141. }
  142. // delete the buffer
  143. delete[] buffer;
  144. return 0;
  145. }
  146. // -----------------------------------------------------------------------------------
  147. // Save a texture as tga
  148. int SaveAsTGA (FILE* file, const aiTexel* data, unsigned int width, unsigned int height)
  149. {
  150. if (!file || !data) {
  151. return 1;
  152. }
  153. TGA_HEADER head = {0};
  154. head.bits = 32;
  155. head.height = (uint16_t)height;
  156. head.width = (uint16_t)width;
  157. head.descriptor |= (1u<<5);
  158. head.imagetype = 2; // actually it's RGBA
  159. fwrite(&head,sizeof(TGA_HEADER),1,file);
  160. for (unsigned int y = 0; y < height; ++y) {
  161. for (unsigned int x = 0; x < width; ++x) {
  162. fwrite(data + y*width+x,4,1,file);
  163. }
  164. }
  165. return 0;
  166. }
  167. // -----------------------------------------------------------------------------------
  168. // Do the texture import for a given aiTexture
  169. int DoExport(const aiTexture* tx, FILE* p, const std::string& extension,
  170. unsigned int flags)
  171. {
  172. // export the image to the appropriate decoder
  173. if (extension == "bmp") {
  174. SaveAsBMP(p,tx->pcData,tx->mWidth,tx->mHeight,
  175. (0 != (flags & AI_EXTRACT_WRITE_BMP_ALPHA)));
  176. }
  177. else if (extension == "tga") {
  178. SaveAsTGA(p,tx->pcData,tx->mWidth,tx->mHeight);
  179. }
  180. else {
  181. printf("assimp extract: No available texture encoder found for %s\n", extension.c_str());
  182. return 1;
  183. }
  184. return 0;
  185. }
  186. // -----------------------------------------------------------------------------------
  187. // Implementation of the assimp extract utility
  188. int Assimp_Extract (const char* const* params, unsigned int num)
  189. {
  190. const char* const invalid = "assimp extract: Invalid number of arguments. See \'assimp extract --help\'\n";
  191. if (num < 1) {
  192. printf(invalid);
  193. return 1;
  194. }
  195. // --help
  196. if (!strcmp( params[0], "-h") || !strcmp( params[0], "--help") || !strcmp( params[0], "-?") ) {
  197. printf("%s",AICMD_MSG_DUMP_HELP_E);
  198. return 0;
  199. }
  200. // asssimp extract in out [options]
  201. if (num < 1) {
  202. printf(invalid);
  203. return 1;
  204. }
  205. std::string in = std::string(params[0]);
  206. std::string out = (num > 1 ? std::string(params[1]) : "-");
  207. // get import flags
  208. ImportData import;
  209. ProcessStandardArguments(import,params+1,num-1);
  210. bool nosuffix = false;
  211. unsigned int texIdx = 0xffffffff, flags = 0;
  212. // process other flags
  213. std::string extension = "bmp";
  214. for (unsigned int i = (out[0] == '-' ? 1 : 2); i < num;++i) {
  215. if (!params[i]) {
  216. continue;
  217. }
  218. if (!strncmp( params[i], "-f",2)) {
  219. extension = std::string(params[i]+2);
  220. }
  221. else if ( !strncmp( params[i], "--format=",9)) {
  222. extension = std::string(params[i]+9);
  223. }
  224. else if ( !strcmp( params[i], "--nosuffix") || !strcmp(params[i],"-s")) {
  225. nosuffix = true;
  226. }
  227. else if ( !strncmp( params[i], "--texture=",10)) {
  228. texIdx = Assimp::strtoul10(params[i]+10);
  229. }
  230. else if ( !strncmp( params[i], "-t",2)) {
  231. texIdx = Assimp::strtoul10(params[i]+2);
  232. }
  233. else if ( !strcmp( params[i], "-ba") || !strcmp( params[i], "--bmp-with-alpha")) {
  234. flags |= AI_EXTRACT_WRITE_BMP_ALPHA;
  235. }
  236. #if 0
  237. else {
  238. printf("Unknown parameter: %s\n",params[i]);
  239. return 10;
  240. }
  241. #endif
  242. }
  243. std::transform(extension.begin(),extension.end(),extension.begin(),::tolower);
  244. if (out[0] == '-') {
  245. // take file name from input file
  246. std::string::size_type s = in.find_last_of('.');
  247. if (s == std::string::npos)
  248. s = in.length();
  249. out = in.substr(0,s);
  250. }
  251. // take file extension from file name, if given
  252. std::string::size_type s = out.find_last_of('.');
  253. if (s != std::string::npos) {
  254. extension = out.substr(s+1,in.length()-(s+1));
  255. out = out.substr(0,s);
  256. }
  257. // import the main model
  258. const aiScene* scene = ImportModel(import,in);
  259. if (!scene) {
  260. printf("assimp extract: Unable to load input file %s\n",in.c_str());
  261. return 5;
  262. }
  263. // get the texture(s) to be exported
  264. if (texIdx != 0xffffffff) {
  265. // check whether the requested texture is existing
  266. if (texIdx >= scene->mNumTextures) {
  267. ::printf("assimp extract: Texture %i requested, but there are just %i textures\n",
  268. texIdx, scene->mNumTextures);
  269. return 6;
  270. }
  271. }
  272. else {
  273. ::printf("assimp extract: Exporting %i textures\n",scene->mNumTextures);
  274. }
  275. // now write all output textures
  276. for (unsigned int i = 0; i < scene->mNumTextures;++i) {
  277. if (texIdx != 0xffffffff && texIdx != i) {
  278. continue;
  279. }
  280. const aiTexture* tex = scene->mTextures[i];
  281. std::string out_cpy = out, out_ext = extension;
  282. // append suffix if necessary - always if all textures are exported
  283. if (!nosuffix || (texIdx == 0xffffffff)) {
  284. out_cpy.append ("_img");
  285. char tmp[10];
  286. Assimp::ASSIMP_itoa10(tmp,i);
  287. out_cpy.append(std::string(tmp));
  288. }
  289. // if the texture is a compressed one, we'll export
  290. // it to its native file format
  291. if (!tex->mHeight) {
  292. printf("assimp extract: Texture %i is compressed (%s). Writing native file format.\n",
  293. i,tex->achFormatHint);
  294. // modify file extension
  295. out_ext = std::string(tex->achFormatHint);
  296. }
  297. out_cpy.append("."+out_ext);
  298. // open output file
  299. FILE* p = ::fopen(out_cpy.c_str(),"wb");
  300. if (!p) {
  301. printf("assimp extract: Unable to open output file %s\n",out_cpy.c_str());
  302. return 7;
  303. }
  304. int m;
  305. if (!tex->mHeight) {
  306. m = (1 != fwrite(tex->pcData,tex->mWidth,1,p));
  307. }
  308. else m = DoExport(tex,p,extension,flags);
  309. ::fclose(p);
  310. printf("assimp extract: Wrote texture %i to %s\n",i, out_cpy.c_str());
  311. if (texIdx != 0xffffffff)
  312. return m;
  313. }
  314. return 0;
  315. }