Path: blob/master/modules/cvtt/image_compress_cvtt.cpp
10277 views
/**************************************************************************/1/* image_compress_cvtt.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_cvtt.h"3132#include "core/object/worker_thread_pool.h"33#include "core/os/os.h"34#include "core/string/print_string.h"35#include "core/templates/safe_refcount.h"3637#include <ConvectionKernels.h>3839struct CVTTCompressionJobParams {40bool is_hdr = false;41bool is_signed = false;42int bytes_per_pixel = 0;43cvtt::BC7EncodingPlan bc7_plan;44cvtt::Options options;45};4647struct CVTTCompressionRowTask {48Vector<uint8_t> in_mm;49uint8_t *out_mm_bytes = nullptr;50int y_start = 0;51int width = 0;52int height = 0;53};5455struct CVTTCompressionJobQueue {56CVTTCompressionJobParams job_params;57const CVTTCompressionRowTask *job_tasks = nullptr;58uint32_t num_tasks = 0;59SafeNumeric<uint32_t> current_task;60};6162static void _digest_row_task(const CVTTCompressionJobParams &p_job_params, const CVTTCompressionRowTask &p_row_task) {63const uint8_t *in_bytes = p_row_task.in_mm.ptr();64uint8_t *out_bytes = p_row_task.out_mm_bytes;65int w = p_row_task.width;66int h = p_row_task.height;6768int y_start = p_row_task.y_start;69int y_end = y_start + 4;7071int bytes_per_pixel = p_job_params.bytes_per_pixel;72bool is_hdr = p_job_params.is_hdr;73bool is_signed = p_job_params.is_signed;7475cvtt::PixelBlockU8 input_blocks_ldr[cvtt::NumParallelBlocks];76cvtt::PixelBlockF16 input_blocks_hdr[cvtt::NumParallelBlocks];7778for (int x_start = 0; x_start < w; x_start += 4 * cvtt::NumParallelBlocks) {79int x_end = x_start + 4 * cvtt::NumParallelBlocks;8081for (int y = y_start; y < y_end; y++) {82int first_input_element = (y - y_start) * 4;83const uint8_t *row_start;84if (y >= h) {85row_start = in_bytes + (h - 1) * (w * bytes_per_pixel);86} else {87row_start = in_bytes + y * (w * bytes_per_pixel);88}8990for (int x = x_start; x < x_end; x++) {91const uint8_t *pixel_start;92if (x >= w) {93pixel_start = row_start + (w - 1) * bytes_per_pixel;94} else {95pixel_start = row_start + x * bytes_per_pixel;96}9798int block_index = (x - x_start) / 4;99int block_element = (x - x_start) % 4 + first_input_element;100if (is_hdr) {101memcpy(input_blocks_hdr[block_index].m_pixels[block_element], pixel_start, bytes_per_pixel);102input_blocks_hdr[block_index].m_pixels[block_element][3] = 0x3c00; // 1.0 (unused)103} else {104memcpy(input_blocks_ldr[block_index].m_pixels[block_element], pixel_start, bytes_per_pixel);105}106}107}108109uint8_t output_blocks[16 * cvtt::NumParallelBlocks];110111if (is_hdr) {112if (is_signed) {113cvtt::Kernels::EncodeBC6HS(output_blocks, input_blocks_hdr, p_job_params.options);114} else {115cvtt::Kernels::EncodeBC6HU(output_blocks, input_blocks_hdr, p_job_params.options);116}117} else {118cvtt::Kernels::EncodeBC7(output_blocks, input_blocks_ldr, p_job_params.options, p_job_params.bc7_plan);119}120121unsigned int num_real_blocks = ((w - x_start) + 3) / 4;122if (num_real_blocks > cvtt::NumParallelBlocks) {123num_real_blocks = cvtt::NumParallelBlocks;124}125126memcpy(out_bytes, output_blocks, 16 * num_real_blocks);127out_bytes += 16 * num_real_blocks;128}129}130131static void _digest_job_queue(void *p_job_queue, uint32_t p_index) {132CVTTCompressionJobQueue *job_queue = static_cast<CVTTCompressionJobQueue *>(p_job_queue);133uint32_t num_tasks = job_queue->num_tasks;134uint32_t total_threads = WorkerThreadPool::get_singleton()->get_thread_count();135uint32_t start = p_index * num_tasks / total_threads;136uint32_t end = (p_index + 1 == total_threads) ? num_tasks : ((p_index + 1) * num_tasks / total_threads);137138for (uint32_t i = start; i < end; i++) {139_digest_row_task(job_queue->job_params, job_queue->job_tasks[i]);140}141}142143void image_compress_cvtt(Image *p_image, Image::UsedChannels p_channels) {144uint64_t start_time = OS::get_singleton()->get_ticks_msec();145146if (p_image->is_compressed()) {147return; //do not compress, already compressed148}149150int w = p_image->get_width();151int h = p_image->get_height();152153if (w % 4 != 0 || h % 4 != 0) {154w = w <= 2 ? w : (w + 3) & ~3;155h = h <= 2 ? h : (h + 3) & ~3;156}157158bool is_ldr = (p_image->get_format() <= Image::FORMAT_RGBA8);159bool is_hdr = (p_image->get_format() >= Image::FORMAT_RF) && (p_image->get_format() <= Image::FORMAT_RGBE9995);160161if (!is_ldr && !is_hdr) {162return; // Not a usable source format163}164165cvtt::Options options;166uint32_t flags = cvtt::Flags::Default;167flags |= cvtt::Flags::BC7_RespectPunchThrough;168if (p_channels == Image::USED_CHANNELS_RG) { //guessing this is a normal map169flags |= cvtt::Flags::Uniform;170}171options.flags = flags;172173Image::Format target_format = Image::FORMAT_BPTC_RGBA;174175bool is_signed = false;176if (is_hdr) {177if (p_image->get_format() != Image::FORMAT_RGBH) {178p_image->convert(Image::FORMAT_RGBH);179}180181is_signed = p_image->detect_signed();182target_format = is_signed ? Image::FORMAT_BPTC_RGBF : Image::FORMAT_BPTC_RGBFU;183} else {184p_image->convert(Image::FORMAT_RGBA8); //still uses RGBA to convert185}186187Vector<uint8_t> data;188int64_t target_size = Image::get_image_data_size(w, h, target_format, p_image->has_mipmaps());189int mm_count = p_image->has_mipmaps() ? Image::get_image_required_mipmaps(w, h, target_format) : 0;190data.resize(target_size);191int shift = Image::get_format_pixel_rshift(target_format);192193uint8_t *wb = data.ptrw();194195int64_t dst_ofs = 0;196197CVTTCompressionJobQueue job_queue;198job_queue.job_params.is_hdr = is_hdr;199job_queue.job_params.is_signed = is_signed;200job_queue.job_params.options = options;201job_queue.job_params.bytes_per_pixel = is_hdr ? 6 : 4;202cvtt::Kernels::ConfigureBC7EncodingPlanFromQuality(job_queue.job_params.bc7_plan, 5);203204// Amdahl's law (Wikipedia)205// If a program needs 20 hours to complete using a single thread, but a one-hour portion of the program cannot be parallelized,206// therefore only the remaining 19 hours (p = 0.95) of execution time can be parallelized, then regardless of how many threads are devoted207// to a parallelized execution of this program, the minimum execution time cannot be less than one hour.208//209// The number of executions with different inputs can be increased while the latency is the same.210211Vector<CVTTCompressionRowTask> tasks;212213for (int i = 0; i <= mm_count; i++) {214Vector<uint8_t> in_data;215int width, height;216Image::get_image_mipmap_offset_and_dimensions(w, h, target_format, i, width, height);217218int bw = width % 4 != 0 ? width + (4 - width % 4) : width;219int bh = height % 4 != 0 ? height + (4 - height % 4) : height;220221int64_t src_mip_ofs, src_mip_size;222int src_mip_w, src_mip_h;223p_image->get_mipmap_offset_size_and_dimensions(i, src_mip_ofs, src_mip_size, src_mip_w, src_mip_h);224225// Pad textures to nearest block by smearing.226if (width != src_mip_w || height != src_mip_h) {227const uint8_t *src_mip_read = p_image->ptr() + src_mip_ofs;228229// Reserve the buffer for padded image data.230int px_size = Image::get_format_pixel_size(p_image->get_format());231in_data.resize(width * height * px_size);232uint8_t *ptrw = in_data.ptrw();233234int x = 0, y = 0;235for (y = 0; y < src_mip_h; y++) {236for (x = 0; x < src_mip_w; x++) {237memcpy(ptrw + (width * y + x) * px_size, src_mip_read + (src_mip_w * y + x) * px_size, px_size);238}239240// First, smear in x.241for (; x < width; x++) {242memcpy(ptrw + (width * y + x) * px_size, ptrw + (width * y + x - 1) * px_size, px_size);243}244}245246// Then, smear in y.247for (; y < height; y++) {248for (x = 0; x < width; x++) {249memcpy(ptrw + (width * y + x) * px_size, ptrw + (width * y + x - width) * px_size, px_size);250}251}252} else {253// Create a buffer filled with the source mip layer data.254in_data.resize(src_mip_size);255memcpy(in_data.ptrw(), p_image->ptr() + src_mip_ofs, src_mip_size);256}257258//const uint8_t *in_bytes = &rb[src_ofs];259uint8_t *out_bytes = &wb[dst_ofs];260261for (int y_start = 0; y_start < height; y_start += 4) {262CVTTCompressionRowTask row_task;263row_task.width = width;264row_task.height = height;265row_task.y_start = y_start;266row_task.in_mm = in_data;267row_task.out_mm_bytes = out_bytes;268269tasks.push_back(row_task);270271out_bytes += 16 * (bw / 4);272}273274dst_ofs += (MAX(4, bw) * MAX(4, bh)) >> shift;275}276277const CVTTCompressionRowTask *tasks_rb = tasks.ptr();278279job_queue.job_tasks = &tasks_rb[0];280job_queue.num_tasks = static_cast<uint32_t>(tasks.size());281WorkerThreadPool::GroupID group_task = WorkerThreadPool::get_singleton()->add_native_group_task(&_digest_job_queue, &job_queue, WorkerThreadPool::get_singleton()->get_thread_count(), -1, true, SNAME("CVTT Compress"));282WorkerThreadPool::get_singleton()->wait_for_group_task_completion(group_task);283284p_image->set_data(w, h, p_image->has_mipmaps(), target_format, data);285286print_verbose(vformat("CVTT: Encoding took %d ms.", OS::get_singleton()->get_ticks_msec() - start_time));287}288289void image_decompress_cvtt(Image *p_image) {290Image::Format target_format;291bool is_signed = false;292bool is_hdr = false;293294Image::Format input_format = p_image->get_format();295296switch (input_format) {297case Image::FORMAT_BPTC_RGBA:298target_format = Image::FORMAT_RGBA8;299break;300case Image::FORMAT_BPTC_RGBF:301case Image::FORMAT_BPTC_RGBFU:302target_format = Image::FORMAT_RGBH;303is_signed = (input_format == Image::FORMAT_BPTC_RGBF);304is_hdr = true;305break;306default:307return; // Invalid input format308};309310int w = p_image->get_width();311int h = p_image->get_height();312313const uint8_t *rb = p_image->get_data().ptr();314315Vector<uint8_t> data;316int64_t target_size = Image::get_image_data_size(w, h, target_format, p_image->has_mipmaps());317int mm_count = p_image->get_mipmap_count();318data.resize(target_size);319320uint8_t *wb = data.ptrw();321322int bytes_per_pixel = is_hdr ? 6 : 4;323324int64_t dst_ofs = 0;325326for (int i = 0; i <= mm_count; i++) {327int64_t src_ofs = p_image->get_mipmap_offset(i);328329const uint8_t *in_bytes = &rb[src_ofs];330uint8_t *out_bytes = &wb[dst_ofs];331332cvtt::PixelBlockU8 output_blocks_ldr[cvtt::NumParallelBlocks];333cvtt::PixelBlockF16 output_blocks_hdr[cvtt::NumParallelBlocks];334335for (int y_start = 0; y_start < h; y_start += 4) {336int y_end = y_start + 4;337338for (int x_start = 0; x_start < w; x_start += 4 * cvtt::NumParallelBlocks) {339uint8_t input_blocks[16 * cvtt::NumParallelBlocks];340memset(input_blocks, 0, sizeof(input_blocks));341342unsigned int num_real_blocks = ((w - x_start) + 3) / 4;343if (num_real_blocks > cvtt::NumParallelBlocks) {344num_real_blocks = cvtt::NumParallelBlocks;345}346347memcpy(input_blocks, in_bytes, 16 * num_real_blocks);348in_bytes += 16 * num_real_blocks;349350int x_end = x_start + 4 * num_real_blocks;351352if (is_hdr) {353if (is_signed) {354cvtt::Kernels::DecodeBC6HS(output_blocks_hdr, input_blocks);355} else {356cvtt::Kernels::DecodeBC6HU(output_blocks_hdr, input_blocks);357}358} else {359cvtt::Kernels::DecodeBC7(output_blocks_ldr, input_blocks);360}361362for (int y = y_start; y < y_end; y++) {363int first_input_element = (y - y_start) * 4;364uint8_t *row_start;365if (y >= h) {366row_start = out_bytes + (h - 1) * (w * bytes_per_pixel);367} else {368row_start = out_bytes + y * (w * bytes_per_pixel);369}370371for (int x = x_start; x < x_end; x++) {372uint8_t *pixel_start;373if (x >= w) {374pixel_start = row_start + (w - 1) * bytes_per_pixel;375} else {376pixel_start = row_start + x * bytes_per_pixel;377}378379int block_index = (x - x_start) / 4;380int block_element = (x - x_start) % 4 + first_input_element;381if (is_hdr) {382memcpy(pixel_start, output_blocks_hdr[block_index].m_pixels[block_element], bytes_per_pixel);383} else {384memcpy(pixel_start, output_blocks_ldr[block_index].m_pixels[block_element], bytes_per_pixel);385}386}387}388}389}390391dst_ofs += w * h * bytes_per_pixel;392w >>= 1;393h >>= 1;394}395p_image->set_data(p_image->get_width(), p_image->get_height(), p_image->has_mipmaps(), target_format, data);396}397398399