Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/modules/basis_universal/image_compress_basisu.cpp
20936 views
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
31
#include "image_compress_basisu.h"
32
33
#include "core/config/project_settings.h"
34
#include "core/io/image.h"
35
#include "core/os/os.h"
36
#include "core/string/print_string.h"
37
#include "servers/rendering/rendering_server.h"
38
39
GODOT_GCC_WARNING_PUSH
40
GODOT_GCC_WARNING_IGNORE("-Wenum-conversion")
41
GODOT_GCC_WARNING_IGNORE("-Wshadow")
42
GODOT_GCC_WARNING_IGNORE("-Wunused-value")
43
44
#include <transcoder/basisu_transcoder.h>
45
#ifdef TOOLS_ENABLED
46
#include <encoder/basisu_comp.h>
47
48
static Mutex init_mutex;
49
static bool initialized = false;
50
#endif
51
52
GODOT_GCC_WARNING_POP
53
54
void basis_universal_init() {
55
basist::basisu_transcoder_init();
56
}
57
58
#ifdef TOOLS_ENABLED
59
template <typename T>
60
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) {
61
// Source mip's data interpreted as 32-bit RGBA blocks to help with copying pixel data.
62
const T *mip_src_data = reinterpret_cast<const T *>(p_image_mip_data);
63
64
// Reserve space in the padded buffer.
65
r_mip_data_padded.resize(p_next_width * p_next_height * sizeof(T));
66
T *data_padded_ptr = reinterpret_cast<T *>(r_mip_data_padded.ptrw());
67
68
// Pad mipmap to the nearest block by smearing.
69
int x = 0, y = 0;
70
for (y = 0; y < p_height; y++) {
71
for (x = 0; x < p_width; x++) {
72
data_padded_ptr[p_next_width * y + x] = mip_src_data[p_width * y + x];
73
}
74
75
// First, smear in x.
76
for (; x < p_next_width; x++) {
77
data_padded_ptr[p_next_width * y + x] = data_padded_ptr[p_next_width * y + x - 1];
78
}
79
}
80
81
// Then, smear in y.
82
for (; y < p_next_height; y++) {
83
for (x = 0; x < p_next_width; x++) {
84
data_padded_ptr[p_next_width * y + x] = data_padded_ptr[p_next_width * y + x - p_next_width];
85
}
86
}
87
}
88
89
Vector<uint8_t> basis_universal_packer(const Ref<Image> &p_image, Image::UsedChannels p_channels, const Image::BasisUniversalPackerParams &p_basisu_params) {
90
init_mutex.lock();
91
if (!initialized) {
92
basisu::basisu_encoder_init();
93
initialized = true;
94
}
95
init_mutex.unlock();
96
97
uint64_t start_time = OS::get_singleton()->get_ticks_msec();
98
99
Ref<Image> image = p_image->duplicate();
100
bool is_hdr = false;
101
102
if (image->get_format() <= Image::FORMAT_RGB565) {
103
image->convert(Image::FORMAT_RGBA8);
104
} else if (image->get_format() <= Image::FORMAT_RGBE9995) {
105
image->convert(Image::FORMAT_RGBAF);
106
is_hdr = true;
107
}
108
109
int rdo_dict_size = GLOBAL_GET_CACHED(int, "rendering/textures/basis_universal/rdo_dict_size");
110
bool zstd_supercompression = GLOBAL_GET_CACHED(bool, "rendering/textures/basis_universal/zstd_supercompression");
111
int zstd_supercompression_level = GLOBAL_GET_CACHED(int, "rendering/textures/basis_universal/zstd_supercompression_level");
112
113
basisu::basis_compressor_params params;
114
115
params.m_uastc = true;
116
params.m_pack_uastc_ldr_4x4_flags &= ~basisu::cPackUASTCLevelMask;
117
params.m_pack_uastc_ldr_4x4_flags |= p_basisu_params.uastc_level;
118
119
params.m_rdo_uastc_ldr_4x4 = p_basisu_params.rdo_quality_loss >= 0.01;
120
params.m_rdo_uastc_ldr_4x4_quality_scalar = p_basisu_params.rdo_quality_loss;
121
params.m_rdo_uastc_ldr_4x4_dict_size = rdo_dict_size;
122
123
params.m_create_ktx2_file = true;
124
params.m_ktx2_uastc_supercompression = zstd_supercompression ? basist::KTX2_SS_ZSTANDARD : basist::KTX2_SS_NONE;
125
params.m_ktx2_zstd_supercompression_level = zstd_supercompression_level;
126
127
params.m_mip_fast = true;
128
params.m_multithreading = true;
129
params.m_check_for_alpha = false;
130
131
if (!OS::get_singleton()->is_stdout_verbose()) {
132
params.m_print_stats = false;
133
params.m_compute_stats = false;
134
params.m_status_output = false;
135
}
136
137
basisu::job_pool job_pool(OS::get_singleton()->get_processor_count());
138
params.m_pJob_pool = &job_pool;
139
140
BasisDecompressFormat decompress_format = BASIS_DECOMPRESS_MAX;
141
142
if (is_hdr) {
143
decompress_format = BASIS_DECOMPRESS_HDR_RGB;
144
params.m_hdr = true;
145
params.m_uastc_hdr_4x4_options.set_quality_level(p_basisu_params.uastc_level);
146
147
} else {
148
switch (p_channels) {
149
case Image::USED_CHANNELS_L: {
150
decompress_format = BASIS_DECOMPRESS_RGB;
151
} break;
152
case Image::USED_CHANNELS_LA: {
153
params.m_force_alpha = true;
154
decompress_format = BASIS_DECOMPRESS_RGBA;
155
} break;
156
case Image::USED_CHANNELS_R: {
157
decompress_format = BASIS_DECOMPRESS_R;
158
} break;
159
case Image::USED_CHANNELS_RG: {
160
params.m_force_alpha = true;
161
image->convert_rg_to_ra_rgba8();
162
decompress_format = BASIS_DECOMPRESS_RG;
163
} break;
164
case Image::USED_CHANNELS_RGB: {
165
decompress_format = BASIS_DECOMPRESS_RGB;
166
} break;
167
case Image::USED_CHANNELS_RGBA: {
168
params.m_force_alpha = true;
169
decompress_format = BASIS_DECOMPRESS_RGBA;
170
} break;
171
}
172
}
173
174
ERR_FAIL_COND_V(decompress_format == BASIS_DECOMPRESS_MAX, Vector<uint8_t>());
175
176
// Copy the source image data with mipmaps into BasisU.
177
{
178
const int orig_width = image->get_width();
179
const int orig_height = image->get_height();
180
181
bool is_res_div_4 = (orig_width % 4 == 0) && (orig_height % 4 == 0);
182
183
// Image's resolution rounded up to the nearest values divisible by 4.
184
int next_width = orig_width <= 2 ? orig_width : (orig_width + 3) & ~3;
185
int next_height = orig_height <= 2 ? orig_height : (orig_height + 3) & ~3;
186
187
Vector<uint8_t> image_data = image->get_data();
188
basisu::vector<basisu::image> basisu_mipmaps;
189
basisu::vector<basisu::imagef> basisu_mipmaps_hdr;
190
191
// Buffer for storing padded mipmap data.
192
Vector<uint8_t> mip_data_padded;
193
194
for (int32_t i = 0; i <= image->get_mipmap_count(); i++) {
195
int64_t ofs, size;
196
int width, height;
197
image->get_mipmap_offset_size_and_dimensions(i, ofs, size, width, height);
198
199
const uint8_t *image_mip_data = image_data.ptr() + ofs;
200
201
// Pad the mipmap's data if its resolution isn't divisible by 4.
202
if (image->has_mipmaps() && !is_res_div_4 && (width > 2 && height > 2) && (width != next_width || height != next_height)) {
203
if (is_hdr) {
204
_basisu_pad_mipmap<BasisRGBAF>(image_mip_data, mip_data_padded, next_width, next_height, width, height, size);
205
} else {
206
_basisu_pad_mipmap<uint32_t>(image_mip_data, mip_data_padded, next_width, next_height, width, height, size);
207
}
208
209
// Override the image_mip_data pointer with our temporary Vector.
210
image_mip_data = reinterpret_cast<const uint8_t *>(mip_data_padded.ptr());
211
212
// Override the mipmap's properties.
213
width = next_width;
214
height = next_height;
215
size = mip_data_padded.size();
216
}
217
218
// Get the next mipmap's resolution.
219
next_width /= 2;
220
next_height /= 2;
221
222
// Copy the source mipmap's data to a BasisU image.
223
if (is_hdr) {
224
basisu::imagef basisu_image(width, height);
225
memcpy(reinterpret_cast<uint8_t *>(basisu_image.get_ptr()), image_mip_data, size);
226
227
if (i == 0) {
228
params.m_source_images_hdr.push_back(basisu_image);
229
} else {
230
basisu_mipmaps_hdr.push_back(basisu_image);
231
}
232
233
} else {
234
basisu::image basisu_image(width, height);
235
memcpy(basisu_image.get_ptr(), image_mip_data, size);
236
237
if (i == 0) {
238
params.m_source_images.push_back(basisu_image);
239
} else {
240
basisu_mipmaps.push_back(basisu_image);
241
}
242
}
243
}
244
245
if (is_hdr) {
246
params.m_source_mipmap_images_hdr.push_back(basisu_mipmaps_hdr);
247
} else {
248
params.m_source_mipmap_images.push_back(basisu_mipmaps);
249
}
250
}
251
252
// Encode the image data.
253
basisu::basis_compressor compressor;
254
compressor.init(params);
255
256
int basisu_err = compressor.process();
257
ERR_FAIL_COND_V(basisu_err != basisu::basis_compressor::cECSuccess, Vector<uint8_t>());
258
259
const basisu::uint8_vec &basisu_encoded = compressor.get_output_ktx2_file();
260
261
Vector<uint8_t> basisu_data;
262
basisu_data.resize(basisu_encoded.size() + 4);
263
uint8_t *basisu_data_ptr = basisu_data.ptrw();
264
265
// Copy the encoded BasisU data into the output buffer.
266
*(uint32_t *)basisu_data_ptr = decompress_format | BASIS_DECOMPRESS_FLAG_KTX2;
267
memcpy(basisu_data_ptr + 4, basisu_encoded.get_ptr(), basisu_encoded.size());
268
269
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));
270
271
return basisu_data;
272
}
273
#endif // TOOLS_ENABLED
274
275
Ref<Image> basis_universal_unpacker_ptr(const uint8_t *p_data, int p_size) {
276
uint64_t start_time = OS::get_singleton()->get_ticks_msec();
277
278
Ref<Image> image;
279
ERR_FAIL_NULL_V_MSG(p_data, image, "Cannot unpack invalid BasisUniversal data.");
280
281
const uint8_t *src_ptr = p_data;
282
int src_size = p_size;
283
284
basist::transcoder_texture_format basisu_format = basist::transcoder_texture_format::cTFTotalTextureFormats;
285
Image::Format image_format = Image::FORMAT_MAX;
286
287
// Get supported compression formats.
288
bool bptc_supported = RS::get_singleton()->has_os_feature("bptc");
289
bool astc_supported = RS::get_singleton()->has_os_feature("astc");
290
bool rgtc_supported = RS::get_singleton()->has_os_feature("rgtc");
291
bool s3tc_supported = RS::get_singleton()->has_os_feature("s3tc");
292
bool etc2_supported = RS::get_singleton()->has_os_feature("etc2");
293
bool astc_hdr_supported = RS::get_singleton()->has_os_feature("astc_hdr");
294
295
bool needs_ra_rg_swap = false;
296
bool needs_rg_trim = false;
297
298
uint32_t decompress_format = *(uint32_t *)(src_ptr);
299
bool is_ktx2 = decompress_format & BASIS_DECOMPRESS_FLAG_KTX2;
300
decompress_format &= ~BASIS_DECOMPRESS_FLAG_KTX2;
301
302
switch (decompress_format) {
303
case BASIS_DECOMPRESS_R: {
304
if (rgtc_supported) {
305
basisu_format = basist::transcoder_texture_format::cTFBC4_R;
306
image_format = Image::FORMAT_RGTC_R;
307
} else if (s3tc_supported) {
308
basisu_format = basist::transcoder_texture_format::cTFBC1;
309
image_format = Image::FORMAT_DXT1;
310
} else if (etc2_supported) {
311
basisu_format = basist::transcoder_texture_format::cTFETC2_EAC_R11;
312
image_format = Image::FORMAT_ETC2_R11;
313
} else {
314
// No supported VRAM compression formats, decompress.
315
basisu_format = basist::transcoder_texture_format::cTFRGBA32;
316
image_format = Image::FORMAT_RGBA8;
317
needs_rg_trim = true;
318
}
319
320
} break;
321
case BASIS_DECOMPRESS_RG: {
322
if (rgtc_supported) {
323
basisu_format = basist::transcoder_texture_format::cTFBC5_RG;
324
image_format = Image::FORMAT_RGTC_RG;
325
} else if (s3tc_supported) {
326
basisu_format = basist::transcoder_texture_format::cTFBC3;
327
image_format = Image::FORMAT_DXT5_RA_AS_RG;
328
} else if (etc2_supported) {
329
basisu_format = basist::transcoder_texture_format::cTFETC2_EAC_RG11;
330
image_format = Image::FORMAT_ETC2_RG11;
331
} else {
332
// No supported VRAM compression formats, decompress.
333
basisu_format = basist::transcoder_texture_format::cTFRGBA32;
334
image_format = Image::FORMAT_RGBA8;
335
needs_ra_rg_swap = true;
336
needs_rg_trim = true;
337
}
338
339
} break;
340
case BASIS_DECOMPRESS_RG_AS_RA: {
341
if (s3tc_supported) {
342
basisu_format = basist::transcoder_texture_format::cTFBC3;
343
image_format = Image::FORMAT_DXT5_RA_AS_RG;
344
} else if (etc2_supported) {
345
basisu_format = basist::transcoder_texture_format::cTFETC2;
346
image_format = Image::FORMAT_ETC2_RA_AS_RG;
347
} else {
348
// No supported VRAM compression formats, decompress.
349
basisu_format = basist::transcoder_texture_format::cTFRGBA32;
350
image_format = Image::FORMAT_RGBA8;
351
needs_ra_rg_swap = true;
352
needs_rg_trim = true;
353
}
354
355
} break;
356
case BASIS_DECOMPRESS_RGB: {
357
if (bptc_supported) {
358
basisu_format = basist::transcoder_texture_format::cTFBC7_M6_OPAQUE_ONLY;
359
image_format = Image::FORMAT_BPTC_RGBA;
360
} else if (astc_supported) {
361
basisu_format = basist::transcoder_texture_format::cTFASTC_4x4_RGBA;
362
image_format = Image::FORMAT_ASTC_4x4;
363
} else if (s3tc_supported) {
364
basisu_format = basist::transcoder_texture_format::cTFBC1;
365
image_format = Image::FORMAT_DXT1;
366
} else if (etc2_supported) {
367
basisu_format = basist::transcoder_texture_format::cTFETC1;
368
image_format = Image::FORMAT_ETC2_RGB8;
369
} else {
370
// No supported VRAM compression formats, decompress.
371
basisu_format = basist::transcoder_texture_format::cTFRGBA32;
372
image_format = Image::FORMAT_RGBA8;
373
}
374
375
} break;
376
case BASIS_DECOMPRESS_RGBA: {
377
if (bptc_supported) {
378
basisu_format = basist::transcoder_texture_format::cTFBC7_M5;
379
image_format = Image::FORMAT_BPTC_RGBA;
380
} else if (astc_supported) {
381
basisu_format = basist::transcoder_texture_format::cTFASTC_4x4_RGBA;
382
image_format = Image::FORMAT_ASTC_4x4;
383
} else if (s3tc_supported) {
384
basisu_format = basist::transcoder_texture_format::cTFBC3;
385
image_format = Image::FORMAT_DXT5;
386
} else if (etc2_supported) {
387
basisu_format = basist::transcoder_texture_format::cTFETC2;
388
image_format = Image::FORMAT_ETC2_RGBA8;
389
} else {
390
// No supported VRAM compression formats, decompress.
391
basisu_format = basist::transcoder_texture_format::cTFRGBA32;
392
image_format = Image::FORMAT_RGBA8;
393
}
394
395
} break;
396
case BASIS_DECOMPRESS_HDR_RGB: {
397
if (bptc_supported) {
398
basisu_format = basist::transcoder_texture_format::cTFBC6H;
399
image_format = Image::FORMAT_BPTC_RGBFU;
400
} else if (astc_hdr_supported) {
401
basisu_format = basist::transcoder_texture_format::cTFASTC_HDR_4x4_RGBA;
402
image_format = Image::FORMAT_ASTC_4x4_HDR;
403
} else {
404
// No supported VRAM compression formats, decompress.
405
basisu_format = basist::transcoder_texture_format::cTFRGB_9E5;
406
image_format = Image::FORMAT_RGBE9995;
407
}
408
409
} break;
410
default: {
411
ERR_FAIL_V(image);
412
} break;
413
}
414
415
src_ptr += 4;
416
src_size -= 4;
417
418
if (is_ktx2) {
419
basist::ktx2_transcoder transcoder;
420
ERR_FAIL_COND_V(!transcoder.init(src_ptr, src_size), image);
421
422
transcoder.start_transcoding();
423
424
// Create the buffer for transcoded/decompressed data.
425
Vector<uint8_t> out_data;
426
out_data.resize(Image::get_image_data_size(transcoder.get_width(), transcoder.get_height(), image_format, transcoder.get_levels() > 1));
427
428
uint8_t *dst = out_data.ptrw();
429
memset(dst, 0, out_data.size());
430
431
for (uint32_t i = 0; i < transcoder.get_levels(); i++) {
432
basist::ktx2_image_level_info basisu_level;
433
transcoder.get_image_level_info(basisu_level, i, 0, 0);
434
435
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;
436
int64_t ofs = Image::get_image_mipmap_offset(transcoder.get_width(), transcoder.get_height(), image_format, i);
437
438
bool result = transcoder.transcode_image_level(i, 0, 0, dst + ofs, mip_block_or_pixel_count, basisu_format);
439
440
if (!result) {
441
print_line(vformat("BasisUniversal cannot unpack level %d.", i));
442
break;
443
}
444
}
445
446
image = Image::create_from_data(transcoder.get_width(), transcoder.get_height(), transcoder.get_levels() > 1, image_format, out_data);
447
} else {
448
basist::basisu_transcoder transcoder;
449
ERR_FAIL_COND_V(!transcoder.validate_header(src_ptr, src_size), image);
450
451
transcoder.start_transcoding(src_ptr, src_size);
452
453
basist::basisu_image_info basisu_info;
454
transcoder.get_image_info(src_ptr, src_size, basisu_info, 0);
455
456
// Create the buffer for transcoded/decompressed data.
457
Vector<uint8_t> out_data;
458
out_data.resize(Image::get_image_data_size(basisu_info.m_width, basisu_info.m_height, image_format, basisu_info.m_total_levels > 1));
459
460
uint8_t *dst = out_data.ptrw();
461
memset(dst, 0, out_data.size());
462
463
for (uint32_t i = 0; i < basisu_info.m_total_levels; i++) {
464
basist::basisu_image_level_info basisu_level;
465
transcoder.get_image_level_info(src_ptr, src_size, basisu_level, 0, i);
466
467
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;
468
int64_t ofs = Image::get_image_mipmap_offset(basisu_info.m_width, basisu_info.m_height, image_format, i);
469
470
bool result = transcoder.transcode_image_level(src_ptr, src_size, 0, i, dst + ofs, mip_block_or_pixel_count, basisu_format);
471
472
if (!result) {
473
print_line(vformat("BasisUniversal cannot unpack level %d.", i));
474
break;
475
}
476
}
477
478
image = Image::create_from_data(basisu_info.m_width, basisu_info.m_height, basisu_info.m_total_levels > 1, image_format, out_data);
479
}
480
481
if (needs_ra_rg_swap) {
482
// Swap uncompressed RA-as-RG texture's color channels.
483
image->convert_ra_rgba8_to_rg();
484
}
485
486
if (needs_rg_trim) {
487
// Remove unnecessary color channels from uncompressed textures.
488
if (decompress_format == BASIS_DECOMPRESS_R) {
489
image->convert(Image::FORMAT_R8);
490
} else if (decompress_format == BASIS_DECOMPRESS_RG || decompress_format == BASIS_DECOMPRESS_RG_AS_RA) {
491
image->convert(Image::FORMAT_RG8);
492
}
493
}
494
495
print_verbose(vformat("BasisU: Transcoding a %dx%d image with %d mipmaps into %s took %d ms.",
496
image->get_width(), image->get_height(), image->get_mipmap_count(), Image::get_format_name(image_format), OS::get_singleton()->get_ticks_msec() - start_time));
497
498
return image;
499
}
500
501
Ref<Image> basis_universal_unpacker(const Vector<uint8_t> &p_buffer) {
502
return basis_universal_unpacker_ptr(p_buffer.ptr(), p_buffer.size());
503
}
504
505