image_compress_basisu.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. /**************************************************************************/
  2. /* image_compress_basisu.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "image_compress_basisu.h"
  31. #include "core/io/image.h"
  32. #include "core/os/os.h"
  33. #include "core/string/print_string.h"
  34. #include "servers/rendering_server.h"
  35. #include <transcoder/basisu_transcoder.h>
  36. #ifdef TOOLS_ENABLED
  37. #include <encoder/basisu_comp.h>
  38. static Mutex init_mutex;
  39. static bool initialized = false;
  40. #endif
  41. void basis_universal_init() {
  42. basist::basisu_transcoder_init();
  43. }
  44. #ifdef TOOLS_ENABLED
  45. template <typename T>
  46. inline void _basisu_pad_mipmap(const uint8_t *p_image_mip_data, Vector<uint8_t> &r_mip_data_padded, int p_next_width, int p_next_height, int p_width, int p_height, int64_t p_size) {
  47. // Source mip's data interpreted as 32-bit RGBA blocks to help with copying pixel data.
  48. const T *mip_src_data = reinterpret_cast<const T *>(p_image_mip_data);
  49. // Reserve space in the padded buffer.
  50. r_mip_data_padded.resize(p_next_width * p_next_height * sizeof(T));
  51. T *data_padded_ptr = reinterpret_cast<T *>(r_mip_data_padded.ptrw());
  52. // Pad mipmap to the nearest block by smearing.
  53. int x = 0, y = 0;
  54. for (y = 0; y < p_height; y++) {
  55. for (x = 0; x < p_width; x++) {
  56. data_padded_ptr[p_next_width * y + x] = mip_src_data[p_width * y + x];
  57. }
  58. // First, smear in x.
  59. for (; x < p_next_width; x++) {
  60. data_padded_ptr[p_next_width * y + x] = data_padded_ptr[p_next_width * y + x - 1];
  61. }
  62. }
  63. // Then, smear in y.
  64. for (; y < p_next_height; y++) {
  65. for (x = 0; x < p_next_width; x++) {
  66. data_padded_ptr[p_next_width * y + x] = data_padded_ptr[p_next_width * y + x - p_next_width];
  67. }
  68. }
  69. }
  70. Vector<uint8_t> basis_universal_packer(const Ref<Image> &p_image, Image::UsedChannels p_channels) {
  71. init_mutex.lock();
  72. if (!initialized) {
  73. basisu::basisu_encoder_init();
  74. initialized = true;
  75. }
  76. init_mutex.unlock();
  77. uint64_t start_time = OS::get_singleton()->get_ticks_msec();
  78. Ref<Image> image = p_image->duplicate();
  79. bool is_hdr = false;
  80. if (image->get_format() <= Image::FORMAT_RGB565) {
  81. image->convert(Image::FORMAT_RGBA8);
  82. } else if (image->get_format() <= Image::FORMAT_RGBE9995) {
  83. image->convert(Image::FORMAT_RGBAF);
  84. is_hdr = true;
  85. }
  86. basisu::basis_compressor_params params;
  87. params.m_uastc = true;
  88. params.m_quality_level = basisu::BASISU_QUALITY_MIN;
  89. params.m_pack_uastc_flags &= ~basisu::cPackUASTCLevelMask;
  90. params.m_pack_uastc_flags |= basisu::cPackUASTCLevelFastest;
  91. params.m_rdo_uastc = 0.0f;
  92. params.m_rdo_uastc_quality_scalar = 0.0f;
  93. params.m_rdo_uastc_dict_size = 1024;
  94. params.m_mip_fast = true;
  95. params.m_multithreading = true;
  96. params.m_check_for_alpha = false;
  97. if (!OS::get_singleton()->is_stdout_verbose()) {
  98. params.m_print_stats = false;
  99. params.m_compute_stats = false;
  100. params.m_status_output = false;
  101. }
  102. basisu::job_pool job_pool(OS::get_singleton()->get_processor_count());
  103. params.m_pJob_pool = &job_pool;
  104. BasisDecompressFormat decompress_format = BASIS_DECOMPRESS_MAX;
  105. if (is_hdr) {
  106. decompress_format = BASIS_DECOMPRESS_HDR_RGB;
  107. params.m_hdr = true;
  108. params.m_uastc_hdr_options.set_quality_level(0);
  109. } else {
  110. switch (p_channels) {
  111. case Image::USED_CHANNELS_L: {
  112. decompress_format = BASIS_DECOMPRESS_RGB;
  113. } break;
  114. case Image::USED_CHANNELS_LA: {
  115. params.m_force_alpha = true;
  116. decompress_format = BASIS_DECOMPRESS_RGBA;
  117. } break;
  118. case Image::USED_CHANNELS_R: {
  119. decompress_format = BASIS_DECOMPRESS_R;
  120. } break;
  121. case Image::USED_CHANNELS_RG: {
  122. params.m_force_alpha = true;
  123. image->convert_rg_to_ra_rgba8();
  124. decompress_format = BASIS_DECOMPRESS_RG;
  125. } break;
  126. case Image::USED_CHANNELS_RGB: {
  127. decompress_format = BASIS_DECOMPRESS_RGB;
  128. } break;
  129. case Image::USED_CHANNELS_RGBA: {
  130. params.m_force_alpha = true;
  131. decompress_format = BASIS_DECOMPRESS_RGBA;
  132. } break;
  133. }
  134. }
  135. ERR_FAIL_COND_V(decompress_format == BASIS_DECOMPRESS_MAX, Vector<uint8_t>());
  136. // Copy the source image data with mipmaps into BasisU.
  137. {
  138. const int orig_width = image->get_width();
  139. const int orig_height = image->get_height();
  140. bool is_res_div_4 = (orig_width % 4 == 0) && (orig_height % 4 == 0);
  141. // Image's resolution rounded up to the nearest values divisible by 4.
  142. int next_width = orig_width <= 2 ? orig_width : (orig_width + 3) & ~3;
  143. int next_height = orig_height <= 2 ? orig_height : (orig_height + 3) & ~3;
  144. Vector<uint8_t> image_data = image->get_data();
  145. basisu::vector<basisu::image> basisu_mipmaps;
  146. basisu::vector<basisu::imagef> basisu_mipmaps_hdr;
  147. // Buffer for storing padded mipmap data.
  148. Vector<uint8_t> mip_data_padded;
  149. for (int32_t i = 0; i <= image->get_mipmap_count(); i++) {
  150. int64_t ofs, size;
  151. int width, height;
  152. image->get_mipmap_offset_size_and_dimensions(i, ofs, size, width, height);
  153. const uint8_t *image_mip_data = image_data.ptr() + ofs;
  154. // Pad the mipmap's data if its resolution isn't divisible by 4.
  155. if (image->has_mipmaps() && !is_res_div_4 && (width > 2 && height > 2) && (width != next_width || height != next_height)) {
  156. if (is_hdr) {
  157. _basisu_pad_mipmap<BasisRGBAF>(image_mip_data, mip_data_padded, next_width, next_height, width, height, size);
  158. } else {
  159. _basisu_pad_mipmap<uint32_t>(image_mip_data, mip_data_padded, next_width, next_height, width, height, size);
  160. }
  161. // Override the image_mip_data pointer with our temporary Vector.
  162. image_mip_data = reinterpret_cast<const uint8_t *>(mip_data_padded.ptr());
  163. // Override the mipmap's properties.
  164. width = next_width;
  165. height = next_height;
  166. size = mip_data_padded.size();
  167. }
  168. // Get the next mipmap's resolution.
  169. next_width /= 2;
  170. next_height /= 2;
  171. // Copy the source mipmap's data to a BasisU image.
  172. if (is_hdr) {
  173. basisu::imagef basisu_image(width, height);
  174. memcpy(reinterpret_cast<uint8_t *>(basisu_image.get_ptr()), image_mip_data, size);
  175. if (i == 0) {
  176. params.m_source_images_hdr.push_back(basisu_image);
  177. } else {
  178. basisu_mipmaps_hdr.push_back(basisu_image);
  179. }
  180. } else {
  181. basisu::image basisu_image(width, height);
  182. memcpy(basisu_image.get_ptr(), image_mip_data, size);
  183. if (i == 0) {
  184. params.m_source_images.push_back(basisu_image);
  185. } else {
  186. basisu_mipmaps.push_back(basisu_image);
  187. }
  188. }
  189. }
  190. if (is_hdr) {
  191. params.m_source_mipmap_images_hdr.push_back(basisu_mipmaps_hdr);
  192. } else {
  193. params.m_source_mipmap_images.push_back(basisu_mipmaps);
  194. }
  195. }
  196. // Encode the image data.
  197. basisu::basis_compressor compressor;
  198. compressor.init(params);
  199. int basisu_err = compressor.process();
  200. ERR_FAIL_COND_V(basisu_err != basisu::basis_compressor::cECSuccess, Vector<uint8_t>());
  201. const basisu::uint8_vec &basisu_encoded = compressor.get_output_basis_file();
  202. Vector<uint8_t> basisu_data;
  203. basisu_data.resize(basisu_encoded.size() + 4);
  204. uint8_t *basisu_data_ptr = basisu_data.ptrw();
  205. // Copy the encoded BasisU data into the output buffer.
  206. *(uint32_t *)basisu_data_ptr = decompress_format;
  207. memcpy(basisu_data_ptr + 4, basisu_encoded.get_ptr(), basisu_encoded.size());
  208. print_verbose(vformat("BasisU: Encoding a %dx%d image with %d mipmaps took %d ms.", p_image->get_width(), p_image->get_height(), p_image->get_mipmap_count(), OS::get_singleton()->get_ticks_msec() - start_time));
  209. return basisu_data;
  210. }
  211. #endif // TOOLS_ENABLED
  212. Ref<Image> basis_universal_unpacker_ptr(const uint8_t *p_data, int p_size) {
  213. uint64_t start_time = OS::get_singleton()->get_ticks_msec();
  214. Ref<Image> image;
  215. ERR_FAIL_NULL_V_MSG(p_data, image, "Cannot unpack invalid BasisUniversal data.");
  216. const uint8_t *src_ptr = p_data;
  217. int src_size = p_size;
  218. basist::transcoder_texture_format basisu_format = basist::transcoder_texture_format::cTFTotalTextureFormats;
  219. Image::Format image_format = Image::FORMAT_MAX;
  220. // Get supported compression formats.
  221. bool bptc_supported = RS::get_singleton()->has_os_feature("bptc");
  222. bool astc_supported = RS::get_singleton()->has_os_feature("astc");
  223. bool rgtc_supported = RS::get_singleton()->has_os_feature("rgtc");
  224. bool s3tc_supported = RS::get_singleton()->has_os_feature("s3tc");
  225. bool etc2_supported = RS::get_singleton()->has_os_feature("etc2");
  226. bool needs_ra_rg_swap = false;
  227. bool needs_rg_trim = false;
  228. BasisDecompressFormat decompress_format = (BasisDecompressFormat)(*(uint32_t *)(src_ptr));
  229. switch (decompress_format) {
  230. case BASIS_DECOMPRESS_R: {
  231. if (rgtc_supported) {
  232. basisu_format = basist::transcoder_texture_format::cTFBC4_R;
  233. image_format = Image::FORMAT_RGTC_R;
  234. } else if (s3tc_supported) {
  235. basisu_format = basist::transcoder_texture_format::cTFBC1;
  236. image_format = Image::FORMAT_DXT1;
  237. } else if (etc2_supported) {
  238. basisu_format = basist::transcoder_texture_format::cTFETC2_EAC_R11;
  239. image_format = Image::FORMAT_ETC2_R11;
  240. } else {
  241. // No supported VRAM compression formats, decompress.
  242. basisu_format = basist::transcoder_texture_format::cTFRGBA32;
  243. image_format = Image::FORMAT_RGBA8;
  244. needs_rg_trim = true;
  245. }
  246. } break;
  247. case BASIS_DECOMPRESS_RG: {
  248. if (rgtc_supported) {
  249. basisu_format = basist::transcoder_texture_format::cTFBC5_RG;
  250. image_format = Image::FORMAT_RGTC_RG;
  251. } else if (s3tc_supported) {
  252. basisu_format = basist::transcoder_texture_format::cTFBC3;
  253. image_format = Image::FORMAT_DXT5_RA_AS_RG;
  254. } else if (etc2_supported) {
  255. basisu_format = basist::transcoder_texture_format::cTFETC2_EAC_RG11;
  256. image_format = Image::FORMAT_ETC2_RG11;
  257. } else {
  258. // No supported VRAM compression formats, decompress.
  259. basisu_format = basist::transcoder_texture_format::cTFRGBA32;
  260. image_format = Image::FORMAT_RGBA8;
  261. needs_ra_rg_swap = true;
  262. needs_rg_trim = true;
  263. }
  264. } break;
  265. case BASIS_DECOMPRESS_RG_AS_RA: {
  266. if (s3tc_supported) {
  267. basisu_format = basist::transcoder_texture_format::cTFBC3;
  268. image_format = Image::FORMAT_DXT5_RA_AS_RG;
  269. } else if (etc2_supported) {
  270. basisu_format = basist::transcoder_texture_format::cTFETC2;
  271. image_format = Image::FORMAT_ETC2_RA_AS_RG;
  272. } else {
  273. // No supported VRAM compression formats, decompress.
  274. basisu_format = basist::transcoder_texture_format::cTFRGBA32;
  275. image_format = Image::FORMAT_RGBA8;
  276. needs_ra_rg_swap = true;
  277. needs_rg_trim = true;
  278. }
  279. } break;
  280. case BASIS_DECOMPRESS_RGB: {
  281. if (bptc_supported) {
  282. basisu_format = basist::transcoder_texture_format::cTFBC7_M6_OPAQUE_ONLY;
  283. image_format = Image::FORMAT_BPTC_RGBA;
  284. } else if (astc_supported) {
  285. basisu_format = basist::transcoder_texture_format::cTFASTC_4x4_RGBA;
  286. image_format = Image::FORMAT_ASTC_4x4;
  287. } else if (s3tc_supported) {
  288. basisu_format = basist::transcoder_texture_format::cTFBC1;
  289. image_format = Image::FORMAT_DXT1;
  290. } else if (etc2_supported) {
  291. basisu_format = basist::transcoder_texture_format::cTFETC1;
  292. image_format = Image::FORMAT_ETC2_RGB8;
  293. } else {
  294. // No supported VRAM compression formats, decompress.
  295. basisu_format = basist::transcoder_texture_format::cTFRGBA32;
  296. image_format = Image::FORMAT_RGBA8;
  297. }
  298. } break;
  299. case BASIS_DECOMPRESS_RGBA: {
  300. if (bptc_supported) {
  301. basisu_format = basist::transcoder_texture_format::cTFBC7_M5;
  302. image_format = Image::FORMAT_BPTC_RGBA;
  303. } else if (astc_supported) {
  304. basisu_format = basist::transcoder_texture_format::cTFASTC_4x4_RGBA;
  305. image_format = Image::FORMAT_ASTC_4x4;
  306. } else if (s3tc_supported) {
  307. basisu_format = basist::transcoder_texture_format::cTFBC3;
  308. image_format = Image::FORMAT_DXT5;
  309. } else if (etc2_supported) {
  310. basisu_format = basist::transcoder_texture_format::cTFETC2;
  311. image_format = Image::FORMAT_ETC2_RGBA8;
  312. } else {
  313. // No supported VRAM compression formats, decompress.
  314. basisu_format = basist::transcoder_texture_format::cTFRGBA32;
  315. image_format = Image::FORMAT_RGBA8;
  316. }
  317. } break;
  318. case BASIS_DECOMPRESS_HDR_RGB: {
  319. if (bptc_supported) {
  320. basisu_format = basist::transcoder_texture_format::cTFBC6H;
  321. image_format = Image::FORMAT_BPTC_RGBFU;
  322. } else if (astc_supported) {
  323. basisu_format = basist::transcoder_texture_format::cTFASTC_HDR_4x4_RGBA;
  324. image_format = Image::FORMAT_ASTC_4x4_HDR;
  325. } else {
  326. // No supported VRAM compression formats, decompress.
  327. basisu_format = basist::transcoder_texture_format::cTFRGB_9E5;
  328. image_format = Image::FORMAT_RGBE9995;
  329. }
  330. } break;
  331. default: {
  332. ERR_FAIL_V(image);
  333. } break;
  334. }
  335. src_ptr += 4;
  336. src_size -= 4;
  337. basist::basisu_transcoder transcoder;
  338. ERR_FAIL_COND_V(!transcoder.validate_header(src_ptr, src_size), image);
  339. transcoder.start_transcoding(src_ptr, src_size);
  340. basist::basisu_image_info basisu_info;
  341. transcoder.get_image_info(src_ptr, src_size, basisu_info, 0);
  342. // Create the buffer for transcoded/decompressed data.
  343. Vector<uint8_t> out_data;
  344. out_data.resize(Image::get_image_data_size(basisu_info.m_width, basisu_info.m_height, image_format, basisu_info.m_total_levels > 1));
  345. uint8_t *dst = out_data.ptrw();
  346. memset(dst, 0, out_data.size());
  347. for (uint32_t i = 0; i < basisu_info.m_total_levels; i++) {
  348. basist::basisu_image_level_info basisu_level;
  349. transcoder.get_image_level_info(src_ptr, src_size, basisu_level, 0, i);
  350. uint32_t mip_block_or_pixel_count = Image::is_format_compressed(image_format) ? basisu_level.m_total_blocks : basisu_level.m_orig_width * basisu_level.m_orig_height;
  351. int64_t ofs = Image::get_image_mipmap_offset(basisu_info.m_width, basisu_info.m_height, image_format, i);
  352. bool result = transcoder.transcode_image_level(src_ptr, src_size, 0, i, dst + ofs, mip_block_or_pixel_count, basisu_format);
  353. if (!result) {
  354. print_line(vformat("BasisUniversal cannot unpack level %d.", i));
  355. break;
  356. }
  357. }
  358. image = Image::create_from_data(basisu_info.m_width, basisu_info.m_height, basisu_info.m_total_levels > 1, image_format, out_data);
  359. if (needs_ra_rg_swap) {
  360. // Swap uncompressed RA-as-RG texture's color channels.
  361. image->convert_ra_rgba8_to_rg();
  362. }
  363. if (needs_rg_trim) {
  364. // Remove unnecessary color channels from uncompressed textures.
  365. if (decompress_format == BASIS_DECOMPRESS_R) {
  366. image->convert(Image::FORMAT_R8);
  367. } else if (decompress_format == BASIS_DECOMPRESS_RG || decompress_format == BASIS_DECOMPRESS_RG_AS_RA) {
  368. image->convert(Image::FORMAT_RG8);
  369. }
  370. }
  371. print_verbose(vformat("BasisU: Transcoding a %dx%d image with %d mipmaps into %s took %d ms.",
  372. image->get_width(), image->get_height(), image->get_mipmap_count(), Image::get_format_name(image_format), OS::get_singleton()->get_ticks_msec() - start_time));
  373. return image;
  374. }
  375. Ref<Image> basis_universal_unpacker(const Vector<uint8_t> &p_buffer) {
  376. return basis_universal_unpacker_ptr(p_buffer.ptr(), p_buffer.size());
  377. }