ImageExtractor.cpp 13 KB

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