Path: blob/master/modules/basis_universal/image_compress_basisu.cpp
10277 views
/**************************************************************************/1/* image_compress_basisu.cpp */2/**************************************************************************/3/* This file is part of: */4/* GODOT ENGINE */5/* https://godotengine.org */6/**************************************************************************/7/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */8/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */9/* */10/* Permission is hereby granted, free of charge, to any person obtaining */11/* a copy of this software and associated documentation files (the */12/* "Software"), to deal in the Software without restriction, including */13/* without limitation the rights to use, copy, modify, merge, publish, */14/* distribute, sublicense, and/or sell copies of the Software, and to */15/* permit persons to whom the Software is furnished to do so, subject to */16/* the following conditions: */17/* */18/* The above copyright notice and this permission notice shall be */19/* included in all copies or substantial portions of the Software. */20/* */21/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */22/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */23/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */24/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */25/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */26/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */27/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */28/**************************************************************************/2930#include "image_compress_basisu.h"3132#include "core/config/project_settings.h"33#include "core/io/image.h"34#include "core/os/os.h"35#include "core/string/print_string.h"36#include "servers/rendering_server.h"3738#include <transcoder/basisu_transcoder.h>39#ifdef TOOLS_ENABLED40#include <encoder/basisu_comp.h>4142static Mutex init_mutex;43static bool initialized = false;44#endif4546void basis_universal_init() {47basist::basisu_transcoder_init();48}4950#ifdef TOOLS_ENABLED51template <typename T>52inline 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) {53// Source mip's data interpreted as 32-bit RGBA blocks to help with copying pixel data.54const T *mip_src_data = reinterpret_cast<const T *>(p_image_mip_data);5556// Reserve space in the padded buffer.57r_mip_data_padded.resize(p_next_width * p_next_height * sizeof(T));58T *data_padded_ptr = reinterpret_cast<T *>(r_mip_data_padded.ptrw());5960// Pad mipmap to the nearest block by smearing.61int x = 0, y = 0;62for (y = 0; y < p_height; y++) {63for (x = 0; x < p_width; x++) {64data_padded_ptr[p_next_width * y + x] = mip_src_data[p_width * y + x];65}6667// First, smear in x.68for (; x < p_next_width; x++) {69data_padded_ptr[p_next_width * y + x] = data_padded_ptr[p_next_width * y + x - 1];70}71}7273// Then, smear in y.74for (; y < p_next_height; y++) {75for (x = 0; x < p_next_width; x++) {76data_padded_ptr[p_next_width * y + x] = data_padded_ptr[p_next_width * y + x - p_next_width];77}78}79}8081Vector<uint8_t> basis_universal_packer(const Ref<Image> &p_image, Image::UsedChannels p_channels, const Image::BasisUniversalPackerParams &p_basisu_params) {82init_mutex.lock();83if (!initialized) {84basisu::basisu_encoder_init();85initialized = true;86}87init_mutex.unlock();8889uint64_t start_time = OS::get_singleton()->get_ticks_msec();9091Ref<Image> image = p_image->duplicate();92bool is_hdr = false;9394if (image->get_format() <= Image::FORMAT_RGB565) {95image->convert(Image::FORMAT_RGBA8);96} else if (image->get_format() <= Image::FORMAT_RGBE9995) {97image->convert(Image::FORMAT_RGBAF);98is_hdr = true;99}100101int rdo_dict_size = GLOBAL_GET_CACHED(int, "rendering/textures/basis_universal/rdo_dict_size");102bool zstd_supercompression = GLOBAL_GET_CACHED(bool, "rendering/textures/basis_universal/zstd_supercompression");103int zstd_supercompression_level = GLOBAL_GET_CACHED(int, "rendering/textures/basis_universal/zstd_supercompression_level");104105basisu::basis_compressor_params params;106107params.m_uastc = true;108params.m_pack_uastc_ldr_4x4_flags &= ~basisu::cPackUASTCLevelMask;109params.m_pack_uastc_ldr_4x4_flags |= p_basisu_params.uastc_level;110111params.m_rdo_uastc_ldr_4x4 = p_basisu_params.rdo_quality_loss >= 0.01;112params.m_rdo_uastc_ldr_4x4_quality_scalar = p_basisu_params.rdo_quality_loss;113params.m_rdo_uastc_ldr_4x4_dict_size = rdo_dict_size;114115params.m_create_ktx2_file = true;116params.m_ktx2_uastc_supercompression = zstd_supercompression ? basist::KTX2_SS_ZSTANDARD : basist::KTX2_SS_NONE;117params.m_ktx2_zstd_supercompression_level = zstd_supercompression_level;118119params.m_mip_fast = true;120params.m_multithreading = true;121params.m_check_for_alpha = false;122123if (!OS::get_singleton()->is_stdout_verbose()) {124params.m_print_stats = false;125params.m_compute_stats = false;126params.m_status_output = false;127}128129basisu::job_pool job_pool(OS::get_singleton()->get_processor_count());130params.m_pJob_pool = &job_pool;131132BasisDecompressFormat decompress_format = BASIS_DECOMPRESS_MAX;133134if (is_hdr) {135decompress_format = BASIS_DECOMPRESS_HDR_RGB;136params.m_hdr = true;137params.m_uastc_hdr_4x4_options.set_quality_level(p_basisu_params.uastc_level);138139} else {140switch (p_channels) {141case Image::USED_CHANNELS_L: {142decompress_format = BASIS_DECOMPRESS_RGB;143} break;144case Image::USED_CHANNELS_LA: {145params.m_force_alpha = true;146decompress_format = BASIS_DECOMPRESS_RGBA;147} break;148case Image::USED_CHANNELS_R: {149decompress_format = BASIS_DECOMPRESS_R;150} break;151case Image::USED_CHANNELS_RG: {152params.m_force_alpha = true;153image->convert_rg_to_ra_rgba8();154decompress_format = BASIS_DECOMPRESS_RG;155} break;156case Image::USED_CHANNELS_RGB: {157decompress_format = BASIS_DECOMPRESS_RGB;158} break;159case Image::USED_CHANNELS_RGBA: {160params.m_force_alpha = true;161decompress_format = BASIS_DECOMPRESS_RGBA;162} break;163}164}165166ERR_FAIL_COND_V(decompress_format == BASIS_DECOMPRESS_MAX, Vector<uint8_t>());167168// Copy the source image data with mipmaps into BasisU.169{170const int orig_width = image->get_width();171const int orig_height = image->get_height();172173bool is_res_div_4 = (orig_width % 4 == 0) && (orig_height % 4 == 0);174175// Image's resolution rounded up to the nearest values divisible by 4.176int next_width = orig_width <= 2 ? orig_width : (orig_width + 3) & ~3;177int next_height = orig_height <= 2 ? orig_height : (orig_height + 3) & ~3;178179Vector<uint8_t> image_data = image->get_data();180basisu::vector<basisu::image> basisu_mipmaps;181basisu::vector<basisu::imagef> basisu_mipmaps_hdr;182183// Buffer for storing padded mipmap data.184Vector<uint8_t> mip_data_padded;185186for (int32_t i = 0; i <= image->get_mipmap_count(); i++) {187int64_t ofs, size;188int width, height;189image->get_mipmap_offset_size_and_dimensions(i, ofs, size, width, height);190191const uint8_t *image_mip_data = image_data.ptr() + ofs;192193// Pad the mipmap's data if its resolution isn't divisible by 4.194if (image->has_mipmaps() && !is_res_div_4 && (width > 2 && height > 2) && (width != next_width || height != next_height)) {195if (is_hdr) {196_basisu_pad_mipmap<BasisRGBAF>(image_mip_data, mip_data_padded, next_width, next_height, width, height, size);197} else {198_basisu_pad_mipmap<uint32_t>(image_mip_data, mip_data_padded, next_width, next_height, width, height, size);199}200201// Override the image_mip_data pointer with our temporary Vector.202image_mip_data = reinterpret_cast<const uint8_t *>(mip_data_padded.ptr());203204// Override the mipmap's properties.205width = next_width;206height = next_height;207size = mip_data_padded.size();208}209210// Get the next mipmap's resolution.211next_width /= 2;212next_height /= 2;213214// Copy the source mipmap's data to a BasisU image.215if (is_hdr) {216basisu::imagef basisu_image(width, height);217memcpy(reinterpret_cast<uint8_t *>(basisu_image.get_ptr()), image_mip_data, size);218219if (i == 0) {220params.m_source_images_hdr.push_back(basisu_image);221} else {222basisu_mipmaps_hdr.push_back(basisu_image);223}224225} else {226basisu::image basisu_image(width, height);227memcpy(basisu_image.get_ptr(), image_mip_data, size);228229if (i == 0) {230params.m_source_images.push_back(basisu_image);231} else {232basisu_mipmaps.push_back(basisu_image);233}234}235}236237if (is_hdr) {238params.m_source_mipmap_images_hdr.push_back(basisu_mipmaps_hdr);239} else {240params.m_source_mipmap_images.push_back(basisu_mipmaps);241}242}243244// Encode the image data.245basisu::basis_compressor compressor;246compressor.init(params);247248int basisu_err = compressor.process();249ERR_FAIL_COND_V(basisu_err != basisu::basis_compressor::cECSuccess, Vector<uint8_t>());250251const basisu::uint8_vec &basisu_encoded = compressor.get_output_ktx2_file();252253Vector<uint8_t> basisu_data;254basisu_data.resize(basisu_encoded.size() + 4);255uint8_t *basisu_data_ptr = basisu_data.ptrw();256257// Copy the encoded BasisU data into the output buffer.258*(uint32_t *)basisu_data_ptr = decompress_format | BASIS_DECOMPRESS_FLAG_KTX2;259memcpy(basisu_data_ptr + 4, basisu_encoded.get_ptr(), basisu_encoded.size());260261print_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));262263return basisu_data;264}265#endif // TOOLS_ENABLED266267Ref<Image> basis_universal_unpacker_ptr(const uint8_t *p_data, int p_size) {268uint64_t start_time = OS::get_singleton()->get_ticks_msec();269270Ref<Image> image;271ERR_FAIL_NULL_V_MSG(p_data, image, "Cannot unpack invalid BasisUniversal data.");272273const uint8_t *src_ptr = p_data;274int src_size = p_size;275276basist::transcoder_texture_format basisu_format = basist::transcoder_texture_format::cTFTotalTextureFormats;277Image::Format image_format = Image::FORMAT_MAX;278279// Get supported compression formats.280bool bptc_supported = RS::get_singleton()->has_os_feature("bptc");281bool astc_supported = RS::get_singleton()->has_os_feature("astc");282bool rgtc_supported = RS::get_singleton()->has_os_feature("rgtc");283bool s3tc_supported = RS::get_singleton()->has_os_feature("s3tc");284bool etc2_supported = RS::get_singleton()->has_os_feature("etc2");285bool astc_hdr_supported = RS::get_singleton()->has_os_feature("astc_hdr");286287bool needs_ra_rg_swap = false;288bool needs_rg_trim = false;289290uint32_t decompress_format = *(uint32_t *)(src_ptr);291bool is_ktx2 = decompress_format & BASIS_DECOMPRESS_FLAG_KTX2;292decompress_format &= ~BASIS_DECOMPRESS_FLAG_KTX2;293294switch (decompress_format) {295case BASIS_DECOMPRESS_R: {296if (rgtc_supported) {297basisu_format = basist::transcoder_texture_format::cTFBC4_R;298image_format = Image::FORMAT_RGTC_R;299} else if (s3tc_supported) {300basisu_format = basist::transcoder_texture_format::cTFBC1;301image_format = Image::FORMAT_DXT1;302} else if (etc2_supported) {303basisu_format = basist::transcoder_texture_format::cTFETC2_EAC_R11;304image_format = Image::FORMAT_ETC2_R11;305} else {306// No supported VRAM compression formats, decompress.307basisu_format = basist::transcoder_texture_format::cTFRGBA32;308image_format = Image::FORMAT_RGBA8;309needs_rg_trim = true;310}311312} break;313case BASIS_DECOMPRESS_RG: {314if (rgtc_supported) {315basisu_format = basist::transcoder_texture_format::cTFBC5_RG;316image_format = Image::FORMAT_RGTC_RG;317} else if (s3tc_supported) {318basisu_format = basist::transcoder_texture_format::cTFBC3;319image_format = Image::FORMAT_DXT5_RA_AS_RG;320} else if (etc2_supported) {321basisu_format = basist::transcoder_texture_format::cTFETC2_EAC_RG11;322image_format = Image::FORMAT_ETC2_RG11;323} else {324// No supported VRAM compression formats, decompress.325basisu_format = basist::transcoder_texture_format::cTFRGBA32;326image_format = Image::FORMAT_RGBA8;327needs_ra_rg_swap = true;328needs_rg_trim = true;329}330331} break;332case BASIS_DECOMPRESS_RG_AS_RA: {333if (s3tc_supported) {334basisu_format = basist::transcoder_texture_format::cTFBC3;335image_format = Image::FORMAT_DXT5_RA_AS_RG;336} else if (etc2_supported) {337basisu_format = basist::transcoder_texture_format::cTFETC2;338image_format = Image::FORMAT_ETC2_RA_AS_RG;339} else {340// No supported VRAM compression formats, decompress.341basisu_format = basist::transcoder_texture_format::cTFRGBA32;342image_format = Image::FORMAT_RGBA8;343needs_ra_rg_swap = true;344needs_rg_trim = true;345}346347} break;348case BASIS_DECOMPRESS_RGB: {349if (bptc_supported) {350basisu_format = basist::transcoder_texture_format::cTFBC7_M6_OPAQUE_ONLY;351image_format = Image::FORMAT_BPTC_RGBA;352} else if (astc_supported) {353basisu_format = basist::transcoder_texture_format::cTFASTC_4x4_RGBA;354image_format = Image::FORMAT_ASTC_4x4;355} else if (s3tc_supported) {356basisu_format = basist::transcoder_texture_format::cTFBC1;357image_format = Image::FORMAT_DXT1;358} else if (etc2_supported) {359basisu_format = basist::transcoder_texture_format::cTFETC1;360image_format = Image::FORMAT_ETC2_RGB8;361} else {362// No supported VRAM compression formats, decompress.363basisu_format = basist::transcoder_texture_format::cTFRGBA32;364image_format = Image::FORMAT_RGBA8;365}366367} break;368case BASIS_DECOMPRESS_RGBA: {369if (bptc_supported) {370basisu_format = basist::transcoder_texture_format::cTFBC7_M5;371image_format = Image::FORMAT_BPTC_RGBA;372} else if (astc_supported) {373basisu_format = basist::transcoder_texture_format::cTFASTC_4x4_RGBA;374image_format = Image::FORMAT_ASTC_4x4;375} else if (s3tc_supported) {376basisu_format = basist::transcoder_texture_format::cTFBC3;377image_format = Image::FORMAT_DXT5;378} else if (etc2_supported) {379basisu_format = basist::transcoder_texture_format::cTFETC2;380image_format = Image::FORMAT_ETC2_RGBA8;381} else {382// No supported VRAM compression formats, decompress.383basisu_format = basist::transcoder_texture_format::cTFRGBA32;384image_format = Image::FORMAT_RGBA8;385}386387} break;388case BASIS_DECOMPRESS_HDR_RGB: {389if (bptc_supported) {390basisu_format = basist::transcoder_texture_format::cTFBC6H;391image_format = Image::FORMAT_BPTC_RGBFU;392} else if (astc_hdr_supported) {393basisu_format = basist::transcoder_texture_format::cTFASTC_HDR_4x4_RGBA;394image_format = Image::FORMAT_ASTC_4x4_HDR;395} else {396// No supported VRAM compression formats, decompress.397basisu_format = basist::transcoder_texture_format::cTFRGB_9E5;398image_format = Image::FORMAT_RGBE9995;399}400401} break;402default: {403ERR_FAIL_V(image);404} break;405}406407src_ptr += 4;408src_size -= 4;409410if (is_ktx2) {411basist::ktx2_transcoder transcoder;412ERR_FAIL_COND_V(!transcoder.init(src_ptr, src_size), image);413414transcoder.start_transcoding();415416// Create the buffer for transcoded/decompressed data.417Vector<uint8_t> out_data;418out_data.resize(Image::get_image_data_size(transcoder.get_width(), transcoder.get_height(), image_format, transcoder.get_levels() > 1));419420uint8_t *dst = out_data.ptrw();421memset(dst, 0, out_data.size());422423for (uint32_t i = 0; i < transcoder.get_levels(); i++) {424basist::ktx2_image_level_info basisu_level;425transcoder.get_image_level_info(basisu_level, i, 0, 0);426427uint32_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;428int64_t ofs = Image::get_image_mipmap_offset(transcoder.get_width(), transcoder.get_height(), image_format, i);429430bool result = transcoder.transcode_image_level(i, 0, 0, dst + ofs, mip_block_or_pixel_count, basisu_format);431432if (!result) {433print_line(vformat("BasisUniversal cannot unpack level %d.", i));434break;435}436}437438image = Image::create_from_data(transcoder.get_width(), transcoder.get_height(), transcoder.get_levels() > 1, image_format, out_data);439} else {440basist::basisu_transcoder transcoder;441ERR_FAIL_COND_V(!transcoder.validate_header(src_ptr, src_size), image);442443transcoder.start_transcoding(src_ptr, src_size);444445basist::basisu_image_info basisu_info;446transcoder.get_image_info(src_ptr, src_size, basisu_info, 0);447448// Create the buffer for transcoded/decompressed data.449Vector<uint8_t> out_data;450out_data.resize(Image::get_image_data_size(basisu_info.m_width, basisu_info.m_height, image_format, basisu_info.m_total_levels > 1));451452uint8_t *dst = out_data.ptrw();453memset(dst, 0, out_data.size());454455for (uint32_t i = 0; i < basisu_info.m_total_levels; i++) {456basist::basisu_image_level_info basisu_level;457transcoder.get_image_level_info(src_ptr, src_size, basisu_level, 0, i);458459uint32_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;460int64_t ofs = Image::get_image_mipmap_offset(basisu_info.m_width, basisu_info.m_height, image_format, i);461462bool result = transcoder.transcode_image_level(src_ptr, src_size, 0, i, dst + ofs, mip_block_or_pixel_count, basisu_format);463464if (!result) {465print_line(vformat("BasisUniversal cannot unpack level %d.", i));466break;467}468}469470image = Image::create_from_data(basisu_info.m_width, basisu_info.m_height, basisu_info.m_total_levels > 1, image_format, out_data);471}472473if (needs_ra_rg_swap) {474// Swap uncompressed RA-as-RG texture's color channels.475image->convert_ra_rgba8_to_rg();476}477478if (needs_rg_trim) {479// Remove unnecessary color channels from uncompressed textures.480if (decompress_format == BASIS_DECOMPRESS_R) {481image->convert(Image::FORMAT_R8);482} else if (decompress_format == BASIS_DECOMPRESS_RG || decompress_format == BASIS_DECOMPRESS_RG_AS_RA) {483image->convert(Image::FORMAT_RG8);484}485}486487print_verbose(vformat("BasisU: Transcoding a %dx%d image with %d mipmaps into %s took %d ms.",488image->get_width(), image->get_height(), image->get_mipmap_count(), Image::get_format_name(image_format), OS::get_singleton()->get_ticks_msec() - start_time));489490return image;491}492493Ref<Image> basis_universal_unpacker(const Vector<uint8_t> &p_buffer) {494return basis_universal_unpacker_ptr(p_buffer.ptr(), p_buffer.size());495}496497498