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