14 const unsigned char *pixels,
17 unsigned int channels,
23 if (pixels ==
nullptr || (channels != 3 && channels != 4)) {
24 return KTX_INVALID_VALUE;
28 if (width % 4 != 0 || height % 4 != 0) {
29 return KTX_INVALID_VALUE;
34 const size_t row_size = size_t(width) * channels;
35 std::vector<unsigned char> flipped(row_size * height);
36 for (
unsigned int y = 0;
y < height;
y++) {
37 memcpy(flipped.data() +
size_t(
y) * row_size,
38 pixels +
size_t(height - 1 -
y) * row_size,
42 ktxTextureCreateInfo create_info = {};
49 create_info.baseWidth = width;
50 create_info.baseHeight = height;
51 create_info.baseDepth = 1;
52 create_info.numDimensions = 2;
53 create_info.numLevels = 1;
54 create_info.numLayers = 1;
55 create_info.numFaces = 1;
56 create_info.isArray = KTX_FALSE;
57 create_info.generateMipmaps = KTX_FALSE;
60 ktx_error_code_e result = ktxTexture2_Create(
61 &create_info, KTX_TEXTURE_CREATE_ALLOC_STORAGE, &
texture);
62 if (result != KTX_SUCCESS) {
66 result = ktxTexture_SetImageFromMemory(ktxTexture(
texture),
72 if (result != KTX_SUCCESS) {
73 ktxTexture_Destroy(ktxTexture(
texture));
77 ktxBasisParams params = {};
78 params.structSize =
sizeof(params);
79 params.threadCount = std::max(1u, std::thread::hardware_concurrency());
84 params.uastc = KTX_TRUE;
85 const int level = int(
float(quality) / 100.0f *
float(KTX_PACK_UASTC_MAX_LEVEL) + 0.5f);
86 params.uastcFlags = ktx_pack_uastc_flags(std::clamp(level, 0,
int(KTX_PACK_UASTC_MAX_LEVEL)));
91 params.compressionLevel = KTX_ETC1S_DEFAULT_COMPRESSION_LEVEL;
92 params.qualityLevel = uint32_t(
93 std::clamp(
int(
float(quality) / 100.0f * 254.0f + 1.5f), 1, 255));
96 result = ktxTexture2_CompressBasisEx(
texture, ¶ms);
97 if (result != KTX_SUCCESS) {
98 ktxTexture_Destroy(ktxTexture(
texture));
106 ktxTexture2_SetPrimaries(
texture, KHR_DF_PRIMARIES_UNSPECIFIED);
112 if (use_uastc && compress > 0) {
113 const ktx_uint32_t zstd_level = ktx_uint32_t(std::clamp(compress, 1, 22));
114 result = ktxTexture2_DeflateZstd(
texture, zstd_level);
115 if (result != KTX_SUCCESS) {
116 ktxTexture_Destroy(ktxTexture(
texture));
121 result = ktxTexture_WriteToNamedFile(ktxTexture(
texture), filename);
122 ktxTexture_Destroy(ktxTexture(
texture));
int encodeToFile(const char *filename, const unsigned char *pixels, unsigned int width, unsigned int height, unsigned int channels, int quality, int is_data, int use_uastc, int compress)