Path: blob/master/modules/betsy/image_compress_betsy.cpp
10277 views
/**************************************************************************/1/* image_compress_betsy.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_betsy.h"3132#include "core/config/project_settings.h"3334#include "betsy_bc1.h"3536#include "alpha_stitch.glsl.gen.h"37#include "bc1.glsl.gen.h"38#include "bc4.glsl.gen.h"39#include "bc6h.glsl.gen.h"40#include "servers/display_server.h"4142static Mutex betsy_mutex;43static BetsyCompressor *betsy = nullptr;4445static const BetsyShaderType FORMAT_TO_TYPE[BETSY_FORMAT_MAX] = {46BETSY_SHADER_BC1_STANDARD,47BETSY_SHADER_BC1_DITHER,48BETSY_SHADER_BC1_STANDARD,49BETSY_SHADER_BC4_SIGNED,50BETSY_SHADER_BC4_UNSIGNED,51BETSY_SHADER_BC4_SIGNED,52BETSY_SHADER_BC4_UNSIGNED,53BETSY_SHADER_BC6_SIGNED,54BETSY_SHADER_BC6_UNSIGNED,55};5657static const RD::DataFormat BETSY_TO_RD_FORMAT[BETSY_FORMAT_MAX] = {58RD::DATA_FORMAT_R32G32_UINT,59RD::DATA_FORMAT_R32G32_UINT,60RD::DATA_FORMAT_R32G32_UINT,61RD::DATA_FORMAT_R32G32_UINT,62RD::DATA_FORMAT_R32G32_UINT,63RD::DATA_FORMAT_R32G32_UINT,64RD::DATA_FORMAT_R32G32_UINT,65RD::DATA_FORMAT_R32G32B32A32_UINT,66RD::DATA_FORMAT_R32G32B32A32_UINT,67};6869static const Image::Format BETSY_TO_IMAGE_FORMAT[BETSY_FORMAT_MAX] = {70Image::FORMAT_DXT1,71Image::FORMAT_DXT1,72Image::FORMAT_DXT5,73Image::FORMAT_RGTC_R,74Image::FORMAT_RGTC_R,75Image::FORMAT_RGTC_RG,76Image::FORMAT_RGTC_RG,77Image::FORMAT_BPTC_RGBF,78Image::FORMAT_BPTC_RGBFU,79};8081void BetsyCompressor::_init() {82if (!DisplayServer::can_create_rendering_device()) {83return;84}8586// Create local RD.87RenderingContextDriver *rcd = nullptr;88RenderingDevice *rd = RenderingServer::get_singleton()->create_local_rendering_device();8990if (rd == nullptr) {91#if defined(RD_ENABLED)92#if defined(METAL_ENABLED)93rcd = memnew(RenderingContextDriverMetal);94rd = memnew(RenderingDevice);95#endif96#if defined(VULKAN_ENABLED)97if (rcd == nullptr) {98rcd = memnew(RenderingContextDriverVulkan);99rd = memnew(RenderingDevice);100}101#endif102#endif103if (rcd != nullptr && rd != nullptr) {104Error err = rcd->initialize();105if (err == OK) {106err = rd->initialize(rcd);107}108109if (err != OK) {110memdelete(rd);111memdelete(rcd);112rd = nullptr;113rcd = nullptr;114}115}116}117118ERR_FAIL_NULL_MSG(rd, "Unable to create a local RenderingDevice.");119120compress_rd = rd;121compress_rcd = rcd;122123// Create the sampler state.124RD::SamplerState src_sampler_state;125{126src_sampler_state.repeat_u = RD::SAMPLER_REPEAT_MODE_CLAMP_TO_EDGE;127src_sampler_state.repeat_v = RD::SAMPLER_REPEAT_MODE_CLAMP_TO_EDGE;128src_sampler_state.mag_filter = RD::SAMPLER_FILTER_NEAREST;129src_sampler_state.min_filter = RD::SAMPLER_FILTER_NEAREST;130src_sampler_state.mip_filter = RD::SAMPLER_FILTER_NEAREST;131}132133src_sampler = compress_rd->sampler_create(src_sampler_state);134135// Initialize RDShaderFiles.136{137Ref<RDShaderFile> bc1_shader;138bc1_shader.instantiate();139Error err = bc1_shader->parse_versions_from_text(bc1_shader_glsl);140141if (err != OK) {142bc1_shader->print_errors("Betsy BC1 compress shader");143}144145// Standard BC1 compression.146cached_shaders[BETSY_SHADER_BC1_STANDARD].compiled = compress_rd->shader_create_from_spirv(bc1_shader->get_spirv_stages("standard"));147ERR_FAIL_COND(cached_shaders[BETSY_SHADER_BC1_STANDARD].compiled.is_null());148149cached_shaders[BETSY_SHADER_BC1_STANDARD].pipeline = compress_rd->compute_pipeline_create(cached_shaders[BETSY_SHADER_BC1_STANDARD].compiled);150ERR_FAIL_COND(cached_shaders[BETSY_SHADER_BC1_STANDARD].pipeline.is_null());151152// Dither BC1 variant. Unused, so comment out for now.153//cached_shaders[BETSY_SHADER_BC1_DITHER].compiled = compress_rd->shader_create_from_spirv(bc1_shader->get_spirv_stages("dithered"));154//ERR_FAIL_COND(cached_shaders[BETSY_SHADER_BC1_DITHER].compiled.is_null());155156//cached_shaders[BETSY_SHADER_BC1_DITHER].pipeline = compress_rd->compute_pipeline_create(cached_shaders[BETSY_SHADER_BC1_DITHER].compiled);157//ERR_FAIL_COND(cached_shaders[BETSY_SHADER_BC1_DITHER].pipeline.is_null());158}159160{161Ref<RDShaderFile> bc4_shader;162bc4_shader.instantiate();163Error err = bc4_shader->parse_versions_from_text(bc4_shader_glsl);164165if (err != OK) {166bc4_shader->print_errors("Betsy BC4 compress shader");167}168169// Signed BC4 compression. Unused, so comment out for now.170//cached_shaders[BETSY_SHADER_BC4_SIGNED].compiled = compress_rd->shader_create_from_spirv(bc4_shader->get_spirv_stages("signed"));171//ERR_FAIL_COND(cached_shaders[BETSY_SHADER_BC4_SIGNED].compiled.is_null());172173//cached_shaders[BETSY_SHADER_BC4_SIGNED].pipeline = compress_rd->compute_pipeline_create(cached_shaders[BETSY_SHADER_BC4_SIGNED].compiled);174//ERR_FAIL_COND(cached_shaders[BETSY_SHADER_BC4_SIGNED].pipeline.is_null());175176// Unsigned BC4 compression.177cached_shaders[BETSY_SHADER_BC4_UNSIGNED].compiled = compress_rd->shader_create_from_spirv(bc4_shader->get_spirv_stages("unsigned"));178ERR_FAIL_COND(cached_shaders[BETSY_SHADER_BC4_UNSIGNED].compiled.is_null());179180cached_shaders[BETSY_SHADER_BC4_UNSIGNED].pipeline = compress_rd->compute_pipeline_create(cached_shaders[BETSY_SHADER_BC4_UNSIGNED].compiled);181ERR_FAIL_COND(cached_shaders[BETSY_SHADER_BC4_UNSIGNED].pipeline.is_null());182}183184{185Ref<RDShaderFile> bc6h_shader;186bc6h_shader.instantiate();187Error err = bc6h_shader->parse_versions_from_text(bc6h_shader_glsl);188189if (err != OK) {190bc6h_shader->print_errors("Betsy BC6 compress shader");191}192193// Signed BC6 compression.194cached_shaders[BETSY_SHADER_BC6_SIGNED].compiled = compress_rd->shader_create_from_spirv(bc6h_shader->get_spirv_stages("signed"));195ERR_FAIL_COND(cached_shaders[BETSY_SHADER_BC6_SIGNED].compiled.is_null());196197cached_shaders[BETSY_SHADER_BC6_SIGNED].pipeline = compress_rd->compute_pipeline_create(cached_shaders[BETSY_SHADER_BC6_SIGNED].compiled);198ERR_FAIL_COND(cached_shaders[BETSY_SHADER_BC6_SIGNED].pipeline.is_null());199200// Unsigned BC6 compression.201cached_shaders[BETSY_SHADER_BC6_UNSIGNED].compiled = compress_rd->shader_create_from_spirv(bc6h_shader->get_spirv_stages("unsigned"));202ERR_FAIL_COND(cached_shaders[BETSY_SHADER_BC6_UNSIGNED].compiled.is_null());203204cached_shaders[BETSY_SHADER_BC6_UNSIGNED].pipeline = compress_rd->compute_pipeline_create(cached_shaders[BETSY_SHADER_BC6_UNSIGNED].compiled);205ERR_FAIL_COND(cached_shaders[BETSY_SHADER_BC6_UNSIGNED].pipeline.is_null());206}207208{209Ref<RDShaderFile> alpha_stitch_shader;210alpha_stitch_shader.instantiate();211Error err = alpha_stitch_shader->parse_versions_from_text(alpha_stitch_shader_glsl);212213if (err != OK) {214alpha_stitch_shader->print_errors("Betsy alpha stitch shader");215}216cached_shaders[BETSY_SHADER_ALPHA_STITCH].compiled = compress_rd->shader_create_from_spirv(alpha_stitch_shader->get_spirv_stages());217ERR_FAIL_COND(cached_shaders[BETSY_SHADER_ALPHA_STITCH].compiled.is_null());218219cached_shaders[BETSY_SHADER_ALPHA_STITCH].pipeline = compress_rd->compute_pipeline_create(cached_shaders[BETSY_SHADER_ALPHA_STITCH].compiled);220ERR_FAIL_COND(cached_shaders[BETSY_SHADER_ALPHA_STITCH].pipeline.is_null());221}222}223224void BetsyCompressor::init() {225WorkerThreadPool::TaskID tid = WorkerThreadPool::get_singleton()->add_task(callable_mp(this, &BetsyCompressor::_thread_loop), true, "Betsy pump task", true);226command_queue.set_pump_task_id(tid);227command_queue.push(this, &BetsyCompressor::_assign_mt_ids, tid);228command_queue.push_and_sync(this, &BetsyCompressor::_init);229DEV_ASSERT(task_id == tid);230}231232void BetsyCompressor::_assign_mt_ids(WorkerThreadPool::TaskID p_pump_task_id) {233task_id = p_pump_task_id;234}235236// Yield thread to WTP so other tasks can be done on it.237// Automatically regains control as soon a task is pushed to the command queue.238void BetsyCompressor::_thread_loop() {239while (!exit) {240WorkerThreadPool::get_singleton()->yield();241command_queue.flush_all();242}243}244245void BetsyCompressor::_thread_exit() {246exit = true;247248if (compress_rd != nullptr) {249if (dxt1_encoding_table_buffer.is_valid()) {250compress_rd->free(dxt1_encoding_table_buffer);251}252253compress_rd->free(src_sampler);254255// Clear the shader cache, pipelines will be unreferenced automatically.256for (int i = 0; i < BETSY_SHADER_MAX; i++) {257if (cached_shaders[i].compiled.is_valid()) {258compress_rd->free(cached_shaders[i].compiled);259}260}261262// Free the RD (and RCD if necessary).263memdelete(compress_rd);264compress_rd = nullptr;265if (compress_rcd != nullptr) {266memdelete(compress_rcd);267compress_rcd = nullptr;268}269}270}271272void BetsyCompressor::finish() {273command_queue.push(this, &BetsyCompressor::_thread_exit);274if (task_id != WorkerThreadPool::INVALID_TASK_ID) {275WorkerThreadPool::get_singleton()->wait_for_task_completion(task_id);276task_id = WorkerThreadPool::INVALID_TASK_ID;277}278}279280// Helper functions.281282static int get_next_multiple(int n, int m) {283return n + (m - (n % m));284}285286static Error get_src_texture_format(Image *r_img, RD::DataFormat &r_format) {287switch (r_img->get_format()) {288case Image::FORMAT_L8:289r_img->convert(Image::FORMAT_RGBA8);290r_format = RD::DATA_FORMAT_R8G8B8A8_UNORM;291break;292293case Image::FORMAT_LA8:294r_img->convert(Image::FORMAT_RGBA8);295r_format = RD::DATA_FORMAT_R8G8B8A8_UNORM;296break;297298case Image::FORMAT_R8:299r_format = RD::DATA_FORMAT_R8_UNORM;300break;301302case Image::FORMAT_RG8:303r_format = RD::DATA_FORMAT_R8G8_UNORM;304break;305306case Image::FORMAT_RGB8:307r_img->convert(Image::FORMAT_RGBA8);308r_format = RD::DATA_FORMAT_R8G8B8A8_UNORM;309break;310311case Image::FORMAT_RGBA8:312r_format = RD::DATA_FORMAT_R8G8B8A8_UNORM;313break;314315case Image::FORMAT_RH:316r_format = RD::DATA_FORMAT_R16_SFLOAT;317break;318319case Image::FORMAT_RGH:320r_format = RD::DATA_FORMAT_R16G16_SFLOAT;321break;322323case Image::FORMAT_RGBH:324r_img->convert(Image::FORMAT_RGBAH);325r_format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;326break;327328case Image::FORMAT_RGBAH:329r_format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;330break;331332case Image::FORMAT_RF:333r_format = RD::DATA_FORMAT_R32_SFLOAT;334break;335336case Image::FORMAT_RGF:337r_format = RD::DATA_FORMAT_R32G32_SFLOAT;338break;339340case Image::FORMAT_RGBF:341r_img->convert(Image::FORMAT_RGBAF);342r_format = RD::DATA_FORMAT_R32G32B32A32_SFLOAT;343break;344345case Image::FORMAT_RGBAF:346r_format = RD::DATA_FORMAT_R32G32B32A32_SFLOAT;347break;348349case Image::FORMAT_RGBE9995:350r_format = RD::DATA_FORMAT_E5B9G9R9_UFLOAT_PACK32;351break;352353default: {354return ERR_UNAVAILABLE;355}356}357358return OK;359}360361Error BetsyCompressor::_compress(BetsyFormat p_format, Image *r_img) {362uint64_t start_time = OS::get_singleton()->get_ticks_msec();363364// Return an error so that the compression can fall back to cpu compression365if (compress_rd == nullptr) {366return ERR_CANT_CREATE;367}368369if (r_img->is_compressed()) {370return ERR_INVALID_DATA;371}372373int img_width = r_img->get_width();374int img_height = r_img->get_height();375if (img_width % 4 != 0 || img_height % 4 != 0) {376img_width = img_width <= 2 ? img_width : (img_width + 3) & ~3;377img_height = img_height <= 2 ? img_height : (img_height + 3) & ~3;378}379380Error err = OK;381382// Destination format.383Image::Format dest_format = BETSY_TO_IMAGE_FORMAT[p_format];384RD::DataFormat dst_rd_format = BETSY_TO_RD_FORMAT[p_format];385386BetsyShaderType shader_type = FORMAT_TO_TYPE[p_format];387BetsyShader shader = cached_shaders[shader_type];388BetsyShader secondary_shader; // The secondary shader is used for alpha blocks. For BC it's BC4U and for ETC it's ETC2_RU (8-bit variant).389BetsyShader stitch_shader;390bool needs_alpha_block = false;391392switch (p_format) {393case BETSY_FORMAT_BC3:394case BETSY_FORMAT_BC5_UNSIGNED:395needs_alpha_block = true;396secondary_shader = cached_shaders[BETSY_SHADER_BC4_UNSIGNED];397stitch_shader = cached_shaders[BETSY_SHADER_ALPHA_STITCH];398break;399default:400break;401}402403// src_texture format information.404RD::TextureFormat src_texture_format;405{406src_texture_format.array_layers = 1;407src_texture_format.depth = 1;408src_texture_format.mipmaps = 1;409src_texture_format.texture_type = RD::TEXTURE_TYPE_2D;410src_texture_format.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_CAN_UPDATE_BIT | RD::TEXTURE_USAGE_CAN_COPY_TO_BIT;411}412413err = get_src_texture_format(r_img, src_texture_format.format);414415if (err != OK) {416return err;417}418419// For the destination format just copy the source format and change the usage bits.420RD::TextureFormat dst_texture_format = src_texture_format;421dst_texture_format.usage_bits = RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | RD::TEXTURE_USAGE_STORAGE_BIT | RD::TEXTURE_USAGE_CAN_COPY_FROM_BIT | RD::TEXTURE_USAGE_CAN_COPY_TO_BIT | RD::TEXTURE_USAGE_CAN_UPDATE_BIT;422dst_texture_format.format = dst_rd_format;423424RD::TextureFormat dst_texture_format_alpha;425RD::TextureFormat dst_texture_format_combined;426427if (needs_alpha_block) {428dst_texture_format_combined = dst_texture_format;429dst_texture_format_combined.format = RD::DATA_FORMAT_R32G32B32A32_UINT;430431dst_texture_format.usage_bits |= RD::TEXTURE_USAGE_SAMPLING_BIT;432433dst_texture_format_alpha = dst_texture_format;434dst_texture_format_alpha.format = RD::DATA_FORMAT_R32G32_UINT;435}436437// Encoding table setup.438if ((dest_format == Image::FORMAT_DXT1 || dest_format == Image::FORMAT_DXT5) && dxt1_encoding_table_buffer.is_null()) {439dxt1_encoding_table_buffer = compress_rd->storage_buffer_create(1024 * 4, Span(dxt1_encoding_table).reinterpret<uint8_t>());440}441442const int mip_count = r_img->get_mipmap_count() + 1;443444// Container for the compressed data.445Vector<uint8_t> dst_data;446dst_data.resize(Image::get_image_data_size(img_width, img_height, dest_format, r_img->has_mipmaps()));447uint8_t *dst_data_ptr = dst_data.ptrw();448449Vector<Vector<uint8_t>> src_images;450src_images.push_back(Vector<uint8_t>());451Vector<uint8_t> *src_image_ptr = src_images.ptrw();452453// Compress each mipmap.454for (int i = 0; i < mip_count; i++) {455int width, height;456Image::get_image_mipmap_offset_and_dimensions(img_width, img_height, dest_format, i, width, height);457458int64_t src_mip_ofs, src_mip_size;459int src_mip_w, src_mip_h;460r_img->get_mipmap_offset_size_and_dimensions(i, src_mip_ofs, src_mip_size, src_mip_w, src_mip_h);461462// Set the source texture width and size.463src_texture_format.height = height;464src_texture_format.width = width;465466// Set the destination texture width and size.467dst_texture_format.height = (height + 3) >> 2;468dst_texture_format.width = (width + 3) >> 2;469470// Pad textures to nearest block by smearing.471if (width != src_mip_w || height != src_mip_h) {472const uint8_t *src_mip_read = r_img->ptr() + src_mip_ofs;473474// Reserve the buffer for padded image data.475int px_size = Image::get_format_pixel_size(r_img->get_format());476src_image_ptr[0].resize(width * height * px_size);477uint8_t *ptrw = src_image_ptr[0].ptrw();478479int x = 0, y = 0;480for (y = 0; y < src_mip_h; y++) {481for (x = 0; x < src_mip_w; x++) {482memcpy(ptrw + (width * y + x) * px_size, src_mip_read + (src_mip_w * y + x) * px_size, px_size);483}484485// First, smear in x.486for (; x < width; x++) {487memcpy(ptrw + (width * y + x) * px_size, ptrw + (width * y + x - 1) * px_size, px_size);488}489}490491// Then, smear in y.492for (; y < height; y++) {493for (x = 0; x < width; x++) {494memcpy(ptrw + (width * y + x) * px_size, ptrw + (width * y + x - width) * px_size, px_size);495}496}497} else {498// Create a buffer filled with the source mip layer data.499src_image_ptr[0].resize(src_mip_size);500memcpy(src_image_ptr[0].ptrw(), r_img->ptr() + src_mip_ofs, src_mip_size);501}502503// Create the textures on the GPU.504RID src_texture = compress_rd->texture_create(src_texture_format, RD::TextureView(), src_images);505RID dst_texture_primary = compress_rd->texture_create(dst_texture_format, RD::TextureView());506507{508Vector<RD::Uniform> uniforms;509{510{511RD::Uniform u;512u.uniform_type = RD::UNIFORM_TYPE_SAMPLER_WITH_TEXTURE;513u.binding = 0;514u.append_id(src_sampler);515u.append_id(src_texture);516uniforms.push_back(u);517}518{519RD::Uniform u;520u.uniform_type = RD::UNIFORM_TYPE_IMAGE;521u.binding = 1;522u.append_id(dst_texture_primary);523uniforms.push_back(u);524}525526if (dest_format == Image::FORMAT_DXT1 || dest_format == Image::FORMAT_DXT5) {527RD::Uniform u;528u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;529u.binding = 2;530u.append_id(dxt1_encoding_table_buffer);531uniforms.push_back(u);532}533}534535RID uniform_set = compress_rd->uniform_set_create(uniforms, shader.compiled, 0);536RD::ComputeListID compute_list = compress_rd->compute_list_begin();537538compress_rd->compute_list_bind_compute_pipeline(compute_list, shader.pipeline);539compress_rd->compute_list_bind_uniform_set(compute_list, uniform_set, 0);540541switch (shader_type) {542case BETSY_SHADER_BC6_SIGNED:543case BETSY_SHADER_BC6_UNSIGNED: {544BC6PushConstant push_constant;545push_constant.sizeX = 1.0f / width;546push_constant.sizeY = 1.0f / height;547548compress_rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(BC6PushConstant));549compress_rd->compute_list_dispatch(compute_list, get_next_multiple(width, 32) / 32, get_next_multiple(height, 32) / 32, 1);550} break;551552case BETSY_SHADER_BC1_STANDARD: {553BC1PushConstant push_constant;554push_constant.num_refines = 2;555556compress_rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(BC1PushConstant));557compress_rd->compute_list_dispatch(compute_list, get_next_multiple(width, 32) / 32, get_next_multiple(height, 32) / 32, 1);558} break;559560case BETSY_SHADER_BC4_UNSIGNED: {561BC4PushConstant push_constant;562push_constant.channel_idx = 0;563564compress_rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(BC4PushConstant));565compress_rd->compute_list_dispatch(compute_list, 1, get_next_multiple(width, 16) / 16, get_next_multiple(height, 16) / 16);566} break;567568default: {569} break;570}571572compress_rd->compute_list_end();573574if (!needs_alpha_block) {575compress_rd->submit();576compress_rd->sync();577}578}579580RID dst_texture_rid = dst_texture_primary;581582if (needs_alpha_block) {583// Set the destination texture width and size.584dst_texture_format_alpha.height = (height + 3) >> 2;585dst_texture_format_alpha.width = (width + 3) >> 2;586587RID dst_texture_alpha = compress_rd->texture_create(dst_texture_format_alpha, RD::TextureView());588589{590Vector<RD::Uniform> uniforms;591{592{593RD::Uniform u;594u.uniform_type = RD::UNIFORM_TYPE_SAMPLER_WITH_TEXTURE;595u.binding = 0;596u.append_id(src_sampler);597u.append_id(src_texture);598uniforms.push_back(u);599}600{601RD::Uniform u;602u.uniform_type = RD::UNIFORM_TYPE_IMAGE;603u.binding = 1;604u.append_id(dst_texture_alpha);605uniforms.push_back(u);606}607}608609RID uniform_set = compress_rd->uniform_set_create(uniforms, secondary_shader.compiled, 0);610RD::ComputeListID compute_list = compress_rd->compute_list_begin();611612compress_rd->compute_list_bind_compute_pipeline(compute_list, secondary_shader.pipeline);613compress_rd->compute_list_bind_uniform_set(compute_list, uniform_set, 0);614615BC4PushConstant push_constant;616push_constant.channel_idx = dest_format == Image::FORMAT_DXT5 ? 3 : 1;617618compress_rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(BC4PushConstant));619compress_rd->compute_list_dispatch(compute_list, 1, get_next_multiple(width, 16) / 16, get_next_multiple(height, 16) / 16);620621compress_rd->compute_list_end();622}623624// Stitching625626// Set the destination texture width and size.627dst_texture_format_combined.height = (height + 3) >> 2;628dst_texture_format_combined.width = (width + 3) >> 2;629630RID dst_texture_combined = compress_rd->texture_create(dst_texture_format_combined, RD::TextureView());631632{633Vector<RD::Uniform> uniforms;634{635{636RD::Uniform u;637u.uniform_type = RD::UNIFORM_TYPE_SAMPLER_WITH_TEXTURE;638u.binding = 0;639u.append_id(src_sampler);640u.append_id(dest_format == Image::FORMAT_DXT5 ? dst_texture_alpha : dst_texture_primary);641uniforms.push_back(u);642}643{644RD::Uniform u;645u.uniform_type = RD::UNIFORM_TYPE_SAMPLER_WITH_TEXTURE;646u.binding = 1;647u.append_id(src_sampler);648u.append_id(dest_format == Image::FORMAT_DXT5 ? dst_texture_primary : dst_texture_alpha);649uniforms.push_back(u);650}651{652RD::Uniform u;653u.uniform_type = RD::UNIFORM_TYPE_IMAGE;654u.binding = 2;655u.append_id(dst_texture_combined);656uniforms.push_back(u);657}658}659660RID uniform_set = compress_rd->uniform_set_create(uniforms, stitch_shader.compiled, 0);661RD::ComputeListID compute_list = compress_rd->compute_list_begin();662663compress_rd->compute_list_bind_compute_pipeline(compute_list, stitch_shader.pipeline);664compress_rd->compute_list_bind_uniform_set(compute_list, uniform_set, 0);665compress_rd->compute_list_dispatch(compute_list, get_next_multiple(width, 32) / 32, get_next_multiple(height, 32) / 32, 1);666667compress_rd->compute_list_end();668669compress_rd->submit();670compress_rd->sync();671}672673dst_texture_rid = dst_texture_combined;674675compress_rd->free(dst_texture_primary);676compress_rd->free(dst_texture_alpha);677}678679// Copy data from the GPU to the buffer.680const Vector<uint8_t> texture_data = compress_rd->texture_get_data(dst_texture_rid, 0);681int64_t dst_ofs = Image::get_image_mipmap_offset(img_width, img_height, dest_format, i);682683memcpy(dst_data_ptr + dst_ofs, texture_data.ptr(), texture_data.size());684685// Free the source and dest texture.686compress_rd->free(src_texture);687compress_rd->free(dst_texture_rid);688}689690src_images.clear();691692// Set the compressed data to the image.693r_img->set_data(img_width, img_height, r_img->has_mipmaps(), dest_format, dst_data);694695print_verbose(696vformat("Betsy: Encoding a %dx%d image with %d mipmaps as %s took %d ms.",697img_width,698img_height,699r_img->get_mipmap_count(),700Image::get_format_name(dest_format),701OS::get_singleton()->get_ticks_msec() - start_time));702703return OK;704}705706void ensure_betsy_exists() {707betsy_mutex.lock();708if (betsy == nullptr) {709betsy = memnew(BetsyCompressor);710betsy->init();711}712betsy_mutex.unlock();713}714715Error _betsy_compress_bptc(Image *r_img, Image::UsedChannels p_channels) {716ensure_betsy_exists();717Image::Format format = r_img->get_format();718Error result = ERR_UNAVAILABLE;719720if (format >= Image::FORMAT_RF && format <= Image::FORMAT_RGBE9995) {721if (r_img->detect_signed()) {722result = betsy->compress(BETSY_FORMAT_BC6_SIGNED, r_img);723} else {724result = betsy->compress(BETSY_FORMAT_BC6_UNSIGNED, r_img);725}726}727728if (!GLOBAL_GET("rendering/textures/vram_compression/cache_gpu_compressor")) {729free_device();730}731732return result;733}734735Error _betsy_compress_s3tc(Image *r_img, Image::UsedChannels p_channels) {736ensure_betsy_exists();737Error result = ERR_UNAVAILABLE;738739switch (p_channels) {740case Image::USED_CHANNELS_RGB:741case Image::USED_CHANNELS_L:742result = betsy->compress(BETSY_FORMAT_BC1, r_img);743break;744745case Image::USED_CHANNELS_RGBA:746case Image::USED_CHANNELS_LA:747result = betsy->compress(BETSY_FORMAT_BC3, r_img);748break;749750case Image::USED_CHANNELS_R:751result = betsy->compress(BETSY_FORMAT_BC4_UNSIGNED, r_img);752break;753754case Image::USED_CHANNELS_RG:755result = betsy->compress(BETSY_FORMAT_BC5_UNSIGNED, r_img);756break;757758default:759break;760}761762if (!GLOBAL_GET("rendering/textures/vram_compression/cache_gpu_compressor")) {763free_device();764}765766return result;767}768769void free_device() {770if (betsy != nullptr) {771betsy->finish();772memdelete(betsy);773}774}775776777