diff --git a/CMakeLists.txt b/CMakeLists.txt index 561bbc127..ba583b93b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -130,6 +130,7 @@ list(APPEND CMAKE_MODULE_PATH "${VCPKG_INSTALLED_PATH}/share") set(SOURCES "model/Texture.cpp" +"model/ktx2.cpp" "utilities/Timer.cpp" "utilities/asciiname.cpp" "utilities/workerpool.cpp" diff --git a/application/editormodetextures.cpp b/application/editormodetextures.cpp index e3423de5e..476de2ab5 100644 --- a/application/editormodetextures.cpp +++ b/application/editormodetextures.cpp @@ -30,7 +30,7 @@ char const *const material_payload{"EU07_MATERIAL"}; // files the browser shows: textures, and the materials, which are kept with them bool texture_file(std::string const &Extension) { - return Extension == ".dds" || Extension == ".tga" || Extension == ".png" || Extension == ".bmp" || Extension == ".jpg" || Extension == ".ktx" || Extension == ".tex"; + return Extension == ".dds" || Extension == ".ktx2" || Extension == ".tga" || Extension == ".png" || Extension == ".bmp" || Extension == ".jpg" || Extension == ".ktx" || Extension == ".tex"; } std::string lowercase(std::string Text) diff --git a/application/editormodetrackprops.cpp b/application/editormodetrackprops.cpp index fd6c16052..d290648d7 100644 --- a/application/editormodetrackprops.cpp +++ b/application/editormodetrackprops.cpp @@ -139,7 +139,7 @@ std::string lowered(std::string Text) bool texture_extension(std::string const &Extension) { - return Extension == ".dds" || Extension == ".tga" || Extension == ".png" || Extension == ".bmp" || Extension == ".jpg" || Extension == ".ktx" || Extension == ".tex"; + return Extension == ".dds" || Extension == ".ktx2" || Extension == ".tga" || Extension == ".png" || Extension == ".bmp" || Extension == ".jpg" || Extension == ".ktx" || Extension == ".tex"; } // a name in two lines under a tile: as much as fits, then the rest; the end, where the names differ, is kept when the rest is too long diff --git a/model/Texture.cpp b/model/Texture.cpp index d058ca9b2..cf497e9ae 100644 --- a/model/Texture.cpp +++ b/model/Texture.cpp @@ -22,6 +22,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Logs.h" #include "utilities/utilities.h" #include "scene/sn_utils.h" +#include "model/ktx2.h" #include "rendering/flip-s3tc.h" #include "rendering/common/texturealpha.h" #include "stb/stb_image.h" @@ -30,6 +31,8 @@ http://mozilla.org/MPL/2.0/. #include "winheaders.h" #include +#include +#include #include #define EU07_DEFERRED_TEXTURE_UPLOAD @@ -51,6 +54,10 @@ struct texture_request { int height { 0 }; int mapcount { 0 }; int blocksize { 0 }; + // of a ktx2 file: its image, of which the worker reads mapcount levels from firstlevel on (and unpacks them), flipped if flip + // is set; width and height are those of the first level read + std::optional ktx2image; + std::size_t firstlevel { 0 }; // handed to the workers (texture_source::prefetch()), and when: the main thread only bool submitted { false }; std::chrono::steady_clock::time_point submittime; @@ -61,11 +68,74 @@ struct texture_request { // every texel passes the alpha test of the shadow maps: checked by the worker threads, not by a thread waiting for the data std::optional alphakept; bool failed { false }; + std::string error; // why the data couldn't be read, when the reader knows bool done { false }; // guarded by the mutex of the loader }; namespace { +// what the texture takes of a format of the ktx2 files: the format of its data, and the components it has +struct ktx2_layout { + GLint format; + GLint components; +}; + +ktx2_layout ktx2_layout_of( ktx2::Format const Format ) { + using enum ktx2::Format; + switch( Format ) { + case bc1Rgb: { return { GL_COMPRESSED_RGB_S3TC_DXT1_EXT, GL_RGB }; } + // the 1 bit alpha is cut out by the alpha test, the texture isn't a translucent one: as with the dxt1 dds files + case bc1Rgba: { return { GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_RGB }; } + case bc2: { return { GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, GL_RGBA }; } + case bc3: { return { GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_RGBA }; } + case bc4: { return { GL_COMPRESSED_RED_RGTC1, GL_RED }; } + case bc4Signed: { return { GL_COMPRESSED_SIGNED_RED_RGTC1, GL_RED }; } + case bc5: { return { GL_COMPRESSED_RG_RGTC2, GL_RG }; } + case bc5Signed: { return { GL_COMPRESSED_SIGNED_RG_RGTC2, GL_RG }; } + case bc6h: { return { GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT, GL_RGB }; } + case bc6hSigned: { return { GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT, GL_RGB }; } + // whether the texels use the alpha is checked on the data (bc7_components()) + case bc7: { return { GL_COMPRESSED_RGBA_BPTC_UNORM, GL_RGBA }; } + case bgra8: { return { GL_BGRA, GL_RGBA }; } + default: { return { GL_RGBA, GL_RGBA }; } + } } + +// the alpha test of the shadow maps checked on the data of a ktx2 file. the formats without alpha are known to pass it by their +// format alone +std::optional ktx2_alpha_kept( ktx2::Format const Format, std::span const Data ) { + using enum ktx2::Format; + switch( Format ) { + case bc1Rgba: { return gfx::texels_pass_alpha_test( gfx::alpha_layout::bc1, Data ); } + case bc2: { return gfx::texels_pass_alpha_test( gfx::alpha_layout::bc2, Data ); } + case bc3: { return gfx::texels_pass_alpha_test( gfx::alpha_layout::bc3, Data ); } + case bc7: { return gfx::texels_pass_alpha_test( gfx::alpha_layout::bc7, Data ); } + case rgba8: + case bgra8: { return gfx::texels_pass_alpha_test( gfx::alpha_layout::rgba8, Data ); } + default: { return std::nullopt; } + } } + +// reads the levels of a ktx2 file a request asks for, unpacks and flips them. Check: the alpha of the texels checked too +void read_ktx2( texture_request &Request, bool const Check ) { + auto const &image { *Request.ktx2image }; + Request.data.clear(); + std::ifstream file( Request.file, std::ios::binary ); + if( false == file.is_open() ) { + Request.failed = true; + return; + } + if( false == ktx2::ReadLevels( file, image, Request.firstlevel, static_cast( Request.mapcount ), Request.data, Request.error ) ) { + Request.data = std::vector(); + Request.failed = true; + return; + } + if( Request.flip ) { + ktx2::FlipLevels( image.format, Request.data, static_cast( Request.width ), static_cast( Request.height ), static_cast( Request.mapcount ) ); + } + Request.alphakept.reset(); + if( Check ) { + Request.alphakept = ktx2_alpha_kept( image.format, Request.data ); + } } + // the alpha test of the shadow maps checked on the data of a dds file, block by block of its format std::optional dds_alpha_kept( texture_request const &Request ) { switch( Request.fourcc ) { @@ -163,6 +233,10 @@ private: // same as the reading part of texture_source::load_DDS(). Check: the alpha of the texels checked too (on a worker thread) static void read( texture_request &Request, bool const Check ) { + if( Request.ktx2image.has_value() ) { + read_ktx2( Request, Check ); + return; + } std::ifstream file( Request.file, std::ios::binary ); if( false == file.is_open() ) { Request.failed = true; @@ -316,6 +390,46 @@ GLint bc7_components( std::istream &File, std::streamoff const Start, std::size_ } return GL_RGB; } +// the components of BC7 data held in memory (a level of a ktx2 file), checked as bc7_components() checks a dds file +GLint bc7_components( std::span const Data ) { + for( std::size_t block = 0; block + 16 <= Data.size(); block += 16 ) { + if( bc7_block_has_alpha( &Data[ block ] ) ) { + return GL_RGBA; + } + } + return GL_RGB; } + +// the components of a bc7 ktx2 image: a level of up to 256x256 texels (or the smallest one) checked for translucent texels, as for +// the dds files. the level is read from the file whether the data is streamed or not, so the result doesn't depend on it +GLint ktx2_bc7_components( std::istream &File, ktx2::Description const &Image, std::size_t Level ) { + while( ( Level + 1 < Image.levels.size() ) + && ( std::max( ktx2::LevelExtent( Image.width, Level ), ktx2::LevelExtent( Image.height, Level ) ) > 256 ) ) { + ++Level; + } + std::vector probe; + std::string error; + if( false == ktx2::ReadLevels( File, Image, Level, 1, probe, error ) ) { + // a broken file, erring on the side of translucency like DXT5 does + return GL_RGBA; + } + return bc7_components( probe ); } + +// the first level of a ktx2 image within maxtexturesize, or the count of the levels when none is +std::size_t ktx2_first_level( ktx2::Description const &Image ) { + auto const limit { static_cast( std::max( Global.CurrentMaxTextureSize, 1 ) ) }; + std::size_t level { 0 }; + while( ( level < Image.levels.size() ) + && ( std::max( ktx2::LevelExtent( Image.width, level ), ktx2::LevelExtent( Image.height, level ) ) > limit ) ) { + ++level; + } + return level; } + +// the formats of the bptc extension, BC6H and BC7 +bool is_bptc( GLint const Format ) { + return ( Format == GL_COMPRESSED_RGBA_BPTC_UNORM ) + || ( Format == GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT ) + || ( Format == GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT ); } + // BC7 is core since GL 4.2, older contexts need the extension. requires current gl context bool bptc_supported() { static bool const supported = []() { @@ -346,6 +460,7 @@ GLint readback_format( GLint const Internalformat ) { switch( Internalformat ) { case GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC: { return GL_COMPRESSED_RGBA8_ETC2_EAC; } case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: { return GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; } + case GL_COMPRESSED_SRGB_S3TC_DXT1_EXT: { return GL_COMPRESSED_RGB_S3TC_DXT1_EXT; } case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: { return GL_COMPRESSED_RGBA_S3TC_DXT3_EXT; } case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: { return GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; } case GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM: { return GL_COMPRESSED_RGBA_BPTC_UNORM; } @@ -371,6 +486,15 @@ std::unordered_map texture_source::precompressed_formats = { GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, 16 }, { GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM, 16 }, { GL_COMPRESSED_RGBA_BPTC_UNORM, 16 }, + // of the ktx2 files only + { GL_COMPRESSED_RGB_S3TC_DXT1_EXT, 8 }, + { GL_COMPRESSED_SRGB_S3TC_DXT1_EXT, 8 }, + { GL_COMPRESSED_RED_RGTC1, 8 }, + { GL_COMPRESSED_SIGNED_RED_RGTC1, 8 }, + { GL_COMPRESSED_RG_RGTC2, 16 }, + { GL_COMPRESSED_SIGNED_RG_RGTC2, 16 }, + { GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT, 16 }, + { GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT, 16 }, }; std::unordered_map opengl_texture::drivercompressed_formats = @@ -416,7 +540,50 @@ std::unordered_map> opengl_texture::mapp { GL_RGB, GL_COMPRESSED_RGBA_BPTC_UNORM }, { GL_RG, GL_COMPRESSED_RGBA_BPTC_UNORM }, { GL_RED, GL_COMPRESSED_RGBA_BPTC_UNORM } } }, - { GL_RGBA, { { GL_SRGB_ALPHA, GL_SRGB8_ALPHA8 }, + // of the ktx2 files only. bc4, bc5 and bc6h have no srgb variants: their values are taken as they are, whatever the material wants + { GL_COMPRESSED_RGB_S3TC_DXT1_EXT, { { GL_SRGB_ALPHA, GL_COMPRESSED_SRGB_S3TC_DXT1_EXT }, + { GL_SRGB, GL_COMPRESSED_SRGB_S3TC_DXT1_EXT }, + { GL_RGBA, GL_COMPRESSED_RGB_S3TC_DXT1_EXT }, + { GL_RGB, GL_COMPRESSED_RGB_S3TC_DXT1_EXT }, + { GL_RG, GL_COMPRESSED_RGB_S3TC_DXT1_EXT }, + { GL_RED, GL_COMPRESSED_RGB_S3TC_DXT1_EXT } } }, + { GL_COMPRESSED_RED_RGTC1, { { GL_SRGB_ALPHA, GL_COMPRESSED_RED_RGTC1 }, + { GL_SRGB, GL_COMPRESSED_RED_RGTC1 }, + { GL_RGBA, GL_COMPRESSED_RED_RGTC1 }, + { GL_RGB, GL_COMPRESSED_RED_RGTC1 }, + { GL_RG, GL_COMPRESSED_RED_RGTC1 }, + { GL_RED, GL_COMPRESSED_RED_RGTC1 } } }, + { GL_COMPRESSED_SIGNED_RED_RGTC1, { { GL_SRGB_ALPHA, GL_COMPRESSED_SIGNED_RED_RGTC1 }, + { GL_SRGB, GL_COMPRESSED_SIGNED_RED_RGTC1 }, + { GL_RGBA, GL_COMPRESSED_SIGNED_RED_RGTC1 }, + { GL_RGB, GL_COMPRESSED_SIGNED_RED_RGTC1 }, + { GL_RG, GL_COMPRESSED_SIGNED_RED_RGTC1 }, + { GL_RED, GL_COMPRESSED_SIGNED_RED_RGTC1 } } }, + { GL_COMPRESSED_RG_RGTC2, { { GL_SRGB_ALPHA, GL_COMPRESSED_RG_RGTC2 }, + { GL_SRGB, GL_COMPRESSED_RG_RGTC2 }, + { GL_RGBA, GL_COMPRESSED_RG_RGTC2 }, + { GL_RGB, GL_COMPRESSED_RG_RGTC2 }, + { GL_RG, GL_COMPRESSED_RG_RGTC2 }, + { GL_RED, GL_COMPRESSED_RG_RGTC2 } } }, + { GL_COMPRESSED_SIGNED_RG_RGTC2, { { GL_SRGB_ALPHA, GL_COMPRESSED_SIGNED_RG_RGTC2 }, + { GL_SRGB, GL_COMPRESSED_SIGNED_RG_RGTC2 }, + { GL_RGBA, GL_COMPRESSED_SIGNED_RG_RGTC2 }, + { GL_RGB, GL_COMPRESSED_SIGNED_RG_RGTC2 }, + { GL_RG, GL_COMPRESSED_SIGNED_RG_RGTC2 }, + { GL_RED, GL_COMPRESSED_SIGNED_RG_RGTC2 } } }, + { GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT, { { GL_SRGB_ALPHA, GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT }, + { GL_SRGB, GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT }, + { GL_RGBA, GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT }, + { GL_RGB, GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT }, + { GL_RG, GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT }, + { GL_RED, GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT } } }, + { GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT, { { GL_SRGB_ALPHA, GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT }, + { GL_SRGB, GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT }, + { GL_RGBA, GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT }, + { GL_RGB, GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT }, + { GL_RG, GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT }, + { GL_RED, GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT } } }, + { GL_RGBA, { { GL_SRGB_ALPHA, GL_SRGB8_ALPHA8 }, { GL_SRGB, GL_SRGB8 }, { GL_RGBA, GL_RGBA8 }, { GL_RGB, GL_RGB8 }, @@ -483,6 +650,7 @@ texture_source::load() { else if( type == ".tga" ) { load_TGA(); } else if( type == ".png" ) { load_STBI(); } else if( type == ".ktx" ) { load_KTX(); } + else if( type == ".ktx2" ) { load_KTX2(); } else if( type == ".bmp" ) { load_STBI(); } else if( type == ".jpg" ) { load_STBI(); } else if( type == ".tex" ) { load_TEX(); } @@ -1080,6 +1248,78 @@ texture_source::load_KTX() { data_state = resource_state::good; } +// a khronos texture 2.0 file: the levels within maxtexturesize, unpacked (zstd) and with the bottom row first. the material +// decides between srgb and linear colour, as it does for the dds files +void +texture_source::load_KTX2() { + + auto const path { FileOnDisk( name + type ) }; + std::ifstream file( path, std::ios::binary ); + std::string error; + auto image { ktx2::Parse( file, error ) }; + if( false == image.has_value() ) { + ErrorLog( std::format( "Bad texture: \"{}{}\" can't be read: {}", name, type, error ), logtype::texture ); + data_state = resource_state::failed; + return; + } + + auto const first { ktx2_first_level( *image ) }; + if( first == image->levels.size() ) { + WriteLog( std::format( "Texture \"{}\" has no mipmaps which can fit currently set texture pixelcount limits.", name ) ); + data_state = resource_state::failed; + return; + } + if( first > 0 ) { + WriteLog( std::format( "Texture pixelcount exceeds specified limits, skipping {} mipmap level(s) of \"{}\"", first, name ), logtype::texture ); + } + + auto const layout { ktx2_layout_of( image->format ) }; + data_format = layout.format; + data_width = ktx2::LevelExtent( image->width, first ); + data_height = ktx2::LevelExtent( image->height, first ); + // of plain texels only the largest level is taken, the gpu makes the rest as it does for the other image files + auto const count { ktx2::IsCompressed( image->format ) ? image->levels.size() - first : std::size_t { 1 } }; + data_mapcount = static_cast( count ); + data_components = ( + image->format == ktx2::Format::bc7 ? + ktx2_bc7_components( file, *image, first ) : + layout.components ); + + // the data is kept with the bottom row first. the file states where its first row is, and one which doesn't is taken the way + // the dds files are (ddsupperorigin) + auto const topfirst { ( image->origin == ktx2::Origin::top ) || ( ( image->origin == ktx2::Origin::unstated ) && Global.dds_upper_origin ) }; + auto const flip { topfirst && ktx2::CanFlip( image->format ) }; + if( topfirst && ( false == flip ) ) { + WriteLog( std::format( "Warning: BC6H/BC7 texture \"{}\" has its first row at the top and can't be flipped, it's loaded as stored", name ), logtype::texture ); + } + + if( true == Global.gfx_texture_streaming ) { + // the levels are read and unpacked by a worker thread, everything else about the texture is known already + request = std::make_shared(); + request->file = path; + request->flip = flip; + request->width = static_cast( data_width ); + request->height = static_cast( data_height ); + request->mapcount = static_cast( count ); + request->firstlevel = first; + request->ktx2image = std::move( image ); + data_state = resource_state::loading; + return; + } + + data.clear(); + if( false == ktx2::ReadLevels( file, *image, first, count, data, error ) ) { + data = std::vector(); + ErrorLog( std::format( "Bad texture: \"{}{}\": {}", name, type, error ), logtype::texture ); + data_state = resource_state::failed; + return; + } + if( flip ) { + ktx2::FlipLevels( image->format, data, data_width, data_height, count ); + } + data_state = resource_state::good; +} + void texture_source::load_TEX() { @@ -1322,9 +1562,9 @@ opengl_texture::create( bool const Static ) { return false; } - if( ( data_format == GL_COMPRESSED_RGBA_BPTC_UNORM ) + if( is_bptc( data_format ) && ( false == bptc_supported() ) ) { - ErrorLog( "Bad texture: \"" + name + "\" uses BC7 compression, which the graphics driver doesn't support", logtype::texture ); + ErrorLog( std::format( "Bad texture: \"{}\" uses {} compression, which the graphics driver doesn't support", name, ( data_format == GL_COMPRESSED_RGBA_BPTC_UNORM ? "BC7" : "BC6H" ) ), logtype::texture ); data = std::vector(); data_state = resource_state::failed; // NOTE: temporary workaround for texture assignment errors, same as in load() @@ -1476,6 +1716,9 @@ texture_source::complete_data() { if( true == completed->failed ) { data_state = resource_state::failed; + if( false == completed->error.empty() ) { + ErrorLog( std::format( "Bad texture: \"{}{}\": {}", name, type, completed->error ), logtype::texture ); + } ErrorLog( "Bad texture: failed to load texture \"" + name + "\"" ); // NOTE: temporary workaround for texture assignment errors, same as in load() on_failed(); @@ -1517,7 +1760,7 @@ bool texture_source::streamed() const { return ( ( true == Global.gfx_texture_streaming ) - && ( type == ".dds" ) + && ( ( type == ".dds" ) || ( type == ".ktx2" ) ) && ( false == is_rendertarget ) ); } @@ -2184,7 +2427,7 @@ texture_bank::find_on_disk( std::string const &Texturename ) { // if the first attempt fails, try entire extension list // NOTE: slightly wasteful as it means preferred extension is tested twice, but, eh - return FileExists(filenames, {".dds", ".tga", ".ktx", ".png", ".bmp", ".jpg", ".tex"}); + return FileExists(filenames, {".dds", ".ktx2", ".tga", ".ktx", ".png", ".bmp", ".jpg", ".tex"}); } //--------------------------------------------------------------------------- diff --git a/model/Texture.h b/model/Texture.h index 0e47d4676..302d0fb25 100644 --- a/model/Texture.h +++ b/model/Texture.h @@ -31,11 +31,19 @@ http://mozilla.org/MPL/2.0/. #ifndef GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM #define GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM 0x8E8D #endif +// BC6H, of the same extension: data_format of BC6H ktx2 files +#ifndef GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT +#define GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT 0x8E8E +#endif +#ifndef GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT +#define GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT 0x8E8F +#endif struct texture_request; // texture data read by a worker thread, with gfx.textures.streaming -// a texture as its file gives it, whichever api draws it: read and decoded (dds, tga, png, bmp, jpg, ktx, tex), with the mipmaps -// the file has, kept within maxtexturesize; with gfx.textures.streaming the data of a dds file is read by worker threads. the +// a texture as its file gives it, whichever api draws it: read and decoded (dds, ktx2, tga, png, bmp, jpg, ktx, tex), with the +// mipmaps the file has, kept within maxtexturesize; with gfx.textures.streaming the data of a dds or ktx2 file is read (and the +// levels of a ktx2 file packed with zstd unpacked) by worker threads. the // data is laid out as opengl takes it (the bottom row first) and its formats are the values of opengl (GL_RGBA, // GL_COMPRESSED_RGBA_S3TC_DXT1_EXT ...), which the renderers take as they are. a renderer makes its own object of the texture // from the data (create()) @@ -120,6 +128,7 @@ public: void load_PNG(); void load_DDS(); void load_KTX(); + void load_KTX2(); void load_TEX(); void load_STBI(); void load_TGA(); diff --git a/model/ktx2.cpp b/model/ktx2.cpp new file mode 100644 index 000000000..430067ea0 --- /dev/null +++ b/model/ktx2.cpp @@ -0,0 +1,511 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "model/ktx2.h" + +#include +#include +#include +#include + +#include "zstd.h" + +namespace ktx2 +{ + +namespace +{ + +// «KTX 20»\r\n\x1A\n +constexpr std::array identifier{0xAB, 0x4B, 0x54, 0x58, 0x20, 0x32, 0x30, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A}; +// the identifier, the 9 words of the image and the index of the data format descriptor, the key/value data and the global data +constexpr std::size_t headerBytes{80}; +constexpr std::size_t levelEntryBytes{24}; +constexpr std::uint32_t schemeNone{0}; +constexpr std::uint32_t schemeBasisLz{1}; +constexpr std::uint32_t schemeZstd{2}; +// more levels than an image of 2^31 texels has: a broken file +constexpr std::uint32_t maxLevels{32}; +// the key/value data holds a few short entries; more than this is a broken file +constexpr std::uint32_t maxKeyValueBytes{1u << 20}; + +std::uint32_t readU32(std::span const Bytes, std::size_t const Offset) +{ + return static_cast(Bytes[Offset]) | (static_cast(Bytes[Offset + 1]) << 8) | + (static_cast(Bytes[Offset + 2]) << 16) | (static_cast(Bytes[Offset + 3]) << 24); +} + +std::uint64_t readU64(std::span const Bytes, std::size_t const Offset) +{ + return static_cast(readU32(Bytes, Offset)) | (static_cast(readU32(Bytes, Offset + 4)) << 32); +} + +// reads Out.size() bytes at Offset of the stream; false when the stream ends before +bool readBytes(std::istream &Stream, std::uint64_t const Offset, std::span const Out) +{ + Stream.clear(); + Stream.seekg(static_cast(Offset)); + Stream.read(reinterpret_cast(Out.data()), static_cast(Out.size())); + return Stream.gcount() == static_cast(Out.size()); +} + +std::uint64_t streamBytes(std::istream &Stream) +{ + Stream.clear(); + Stream.seekg(0, std::ios::end); + auto const end{static_cast(Stream.tellg())}; + return end < 0 ? 0 : static_cast(end); +} + +// whether Length bytes at Offset are within a file of FileBytes +bool fits(std::uint64_t const Offset, std::uint64_t const Length, std::uint64_t const FileBytes) +{ + return (Length <= FileBytes) && (Offset <= FileBytes - Length); +} + +struct FormatEntry +{ + std::uint32_t vkFormat; + Format format; + bool srgb; +}; + +// the values of VkFormat the game takes +constexpr std::array formats{ + FormatEntry{37, Format::rgba8, false}, // VK_FORMAT_R8G8B8A8_UNORM + FormatEntry{43, Format::rgba8, true}, // VK_FORMAT_R8G8B8A8_SRGB + FormatEntry{44, Format::bgra8, false}, // VK_FORMAT_B8G8R8A8_UNORM + FormatEntry{50, Format::bgra8, true}, // VK_FORMAT_B8G8R8A8_SRGB + FormatEntry{131, Format::bc1Rgb, false}, // VK_FORMAT_BC1_RGB_UNORM_BLOCK + FormatEntry{132, Format::bc1Rgb, true}, + FormatEntry{133, Format::bc1Rgba, false}, // VK_FORMAT_BC1_RGBA_UNORM_BLOCK + FormatEntry{134, Format::bc1Rgba, true}, + FormatEntry{135, Format::bc2, false}, // VK_FORMAT_BC2_UNORM_BLOCK + FormatEntry{136, Format::bc2, true}, + FormatEntry{137, Format::bc3, false}, // VK_FORMAT_BC3_UNORM_BLOCK + FormatEntry{138, Format::bc3, true}, + FormatEntry{139, Format::bc4, false}, // VK_FORMAT_BC4_UNORM_BLOCK + FormatEntry{140, Format::bc4Signed, false}, + FormatEntry{141, Format::bc5, false}, // VK_FORMAT_BC5_UNORM_BLOCK + FormatEntry{142, Format::bc5Signed, false}, + FormatEntry{143, Format::bc6h, false}, // VK_FORMAT_BC6H_UFLOAT_BLOCK + FormatEntry{144, Format::bc6hSigned, false}, + FormatEntry{145, Format::bc7, false}, // VK_FORMAT_BC7_UNORM_BLOCK + FormatEntry{146, Format::bc7, true}, +}; + +// the words of the header the description is made of +struct Header +{ + std::uint32_t vkFormat{0}; + std::uint32_t width{0}; + std::uint32_t height{0}; + std::uint32_t depth{0}; + std::uint32_t layers{0}; + std::uint32_t faces{0}; + std::uint32_t levels{0}; + std::uint32_t scheme{0}; + std::uint32_t keyValueOffset{0}; + std::uint32_t keyValueLength{0}; + + explicit Header(std::span const Bytes) + : vkFormat{readU32(Bytes, 12)}, width{readU32(Bytes, 20)}, height{readU32(Bytes, 24)}, depth{readU32(Bytes, 28)}, + layers{readU32(Bytes, 32)}, faces{readU32(Bytes, 36)}, levels{readU32(Bytes, 40)}, scheme{readU32(Bytes, 44)}, + keyValueOffset{readU32(Bytes, 56)}, keyValueLength{readU32(Bytes, 60)} + { + } + + // why the game can't take the image the header describes, empty when it can + std::string shapeError() const + { + if ((width == 0) || (height == 0)) + { + return "the image isn't a 2d one"; + } + if (depth != 0) + { + return "3d images aren't supported"; + } + if (layers > 1) + { + return "arrays of images aren't supported"; + } + if (faces != 1) + { + return "cube maps aren't supported"; + } + if (levels > maxLevels) + { + return std::format("it gives {} levels", levels); + } + return {}; + } +}; + +std::optional supercompressionOf(std::uint32_t const Scheme, std::string &Error) +{ + if (Scheme == schemeNone) + { + return Supercompression::none; + } + if (Scheme == schemeZstd) + { + return Supercompression::zstd; + } + Error = (Scheme == schemeBasisLz ? std::string{"basis universal (basislz) isn't supported"} : std::format("its supercompression scheme {} isn't supported", Scheme)); + return std::nullopt; +} + +// what the key/value data says of the first row of the levels +Origin originOf(std::span const KeyValues) +{ + std::string_view const orientationKey{"KTXorientation"}; + std::size_t offset{0}; + while (offset + 4 <= KeyValues.size()) + { + auto const length{static_cast(readU32(KeyValues, offset))}; + offset += 4; + if (length > KeyValues.size() - offset) + { + // a broken entry, nothing after it can be trusted + return Origin::unstated; + } + std::string_view const entry{reinterpret_cast(KeyValues.data() + offset), length}; + // each entry is padded to 4 bytes + offset += (length + 3) & ~std::size_t{3}; + auto const keyEnd{entry.find('\0')}; + if ((keyEnd == std::string_view::npos) || (entry.substr(0, keyEnd) != orientationKey)) + { + continue; + } + // "rd" for the first row at the top, "ru" for the first row at the bottom + auto const value{entry.substr(keyEnd + 1)}; + if (value.size() < 2) + { + return Origin::unstated; + } + if (value[1] == 'u') + { + return Origin::bottom; + } + return (value[1] == 'd' ? Origin::top : Origin::unstated); + } + return Origin::unstated; +} + +// the levels of the index, checked against the size of the file and of the image +bool readLevelIndex(std::istream &Stream, Header const &Head, std::uint64_t const FileBytes, Description &Image, std::string &Error) +{ + auto const count{std::max(Head.levels, 1)}; + std::vector index(static_cast(count) * levelEntryBytes); + if (false == readBytes(Stream, headerBytes, index)) + { + Error = "the file is shorter than its index of levels"; + return false; + } + for (std::size_t level = 0; level < count; ++level) + { + auto const entry{level * levelEntryBytes}; + Level const read{readU64(index, entry), readU64(index, entry + 8), readU64(index, entry + 16)}; + if (false == fits(read.offset, read.length, FileBytes)) + { + Error = std::format("level {} is past the end of the file", level); + return false; + } + auto const expected{LevelBytes(Image.format, LevelExtent(Image.width, level), LevelExtent(Image.height, level))}; + // the level packed with zstd is unpacked into a buffer of the size the file gives, which has to be the size of the level + auto const whole{Image.supercompression == Supercompression::none ? read.length >= expected : read.uncompressedLength == expected}; + if (false == whole) + { + Error = std::format("level {} doesn't hold the {} bytes of its texels", level, expected); + return false; + } + Image.levels.push_back(read); + } + return true; +} + +// the rows of the indices of a bc1 colour block (a byte each) swapped, the first Rows of them +void flipColourRows(std::span const Block, std::uint32_t const Rows) +{ + std::ranges::reverse(Block.subspan(4, Rows)); +} + +// the rows of the explicit alpha of a bc2 block (16 bits each) swapped +void flipExplicitAlphaRows(std::span const Block, std::uint32_t const Rows) +{ + for (std::uint32_t row = 0; row < Rows / 2; ++row) + { + std::ranges::swap_ranges(Block.subspan(row * 2, 2), Block.subspan((Rows - 1 - row) * 2, 2)); + } +} + +// the rows of the indices of a bc4 block (12 bits each, after the two end points) swapped. a bc3 alpha and each half of bc5 are such a block +void flipBc4Rows(std::span const Block, std::uint32_t const Rows) +{ + std::uint64_t bits{0}; + for (std::size_t idx = 0; idx < 6; ++idx) + { + bits |= static_cast(Block[2 + idx]) << (8 * idx); + } + std::array rows{}; + for (std::size_t row = 0; row < rows.size(); ++row) + { + rows[row] = (bits >> (12 * row)) & 0xfff; + } + std::ranges::reverse(std::span{rows}.first(Rows)); + std::uint64_t flipped{0}; + for (std::size_t row = 0; row < rows.size(); ++row) + { + flipped |= rows[row] << (12 * row); + } + for (std::size_t idx = 0; idx < 6; ++idx) + { + Block[2 + idx] = static_cast((flipped >> (8 * idx)) & 0xff); + } +} + +void flipBlock(Format const Value, std::span const Block, std::uint32_t const Rows) +{ + using enum Format; + switch (Value) + { + case bc1Rgb: + case bc1Rgba: + flipColourRows(Block, Rows); + break; + case bc2: + flipExplicitAlphaRows(Block.first(8), Rows); + flipColourRows(Block.subspan(8), Rows); + break; + case bc3: + flipBc4Rows(Block.first(8), Rows); + flipColourRows(Block.subspan(8), Rows); + break; + case bc4: + case bc4Signed: + flipBc4Rows(Block, Rows); + break; + case bc5: + case bc5Signed: + flipBc4Rows(Block.first(8), Rows); + flipBc4Rows(Block.subspan(8), Rows); + break; + default: + break; + } +} + +// the rows of Data, RowBytes each, in the reverse order +void swapRows(std::span const Data, std::size_t const RowBytes, std::uint32_t const Rows) +{ + for (std::uint32_t row = 0; row < Rows / 2; ++row) + { + std::ranges::swap_ranges(Data.subspan(row * RowBytes, RowBytes), Data.subspan((Rows - 1 - row) * RowBytes, RowBytes)); + } +} + +void flipLevel(Format const Value, std::span const Level, std::uint32_t const Width, std::uint32_t const Height) +{ + if (false == IsCompressed(Value)) + { + swapRows(Level, static_cast(Width) * BlockBytes(Value), Height); + return; + } + auto const blockBytes{BlockBytes(Value)}; + auto const blockRows{(Height + 3) / 4}; + // a level lower than a block holds only its first rows of texels. (a height above 4 which isn't a multiple of 4 would need the + // texels moved across the blocks: such a level is flipped block by block, as the dds files are) + auto const texelRows{std::min(Height, 4u)}; + for (std::size_t offset = 0; offset + blockBytes <= Level.size(); offset += blockBytes) + { + flipBlock(Value, Level.subspan(offset, blockBytes), texelRows); + } + swapRows(Level, static_cast((Width + 3) / 4) * blockBytes, blockRows); +} + +// reads the level Index of the image and appends it to Data. Packed: a buffer for the data of a level packed with zstd +bool readLevel(std::istream &Stream, Description const &Image, std::size_t const Index, std::vector &Packed, std::vector &Data, std::string &Error) +{ + auto const &level{Image.levels[Index]}; + auto const expected{static_cast(LevelBytes(Image.format, LevelExtent(Image.width, Index), LevelExtent(Image.height, Index)))}; + auto const start{Data.size()}; + Data.resize(start + expected); + auto const target{std::span{Data}.subspan(start)}; + if (Image.supercompression == Supercompression::none) + { + if (false == readBytes(Stream, level.offset, target)) + { + Data.resize(start); + Error = std::format("level {} couldn't be read", Index); + return false; + } + return true; + } + Packed.resize(static_cast(level.length)); + if (false == readBytes(Stream, level.offset, Packed)) + { + Data.resize(start); + Error = std::format("level {} couldn't be read", Index); + return false; + } + auto const unpacked{ZSTD_decompress(target.data(), target.size(), Packed.data(), Packed.size())}; + if ((ZSTD_isError(unpacked) != 0) || (unpacked != expected)) + { + Data.resize(start); + Error = std::format("level {} couldn't be unpacked", Index); + return false; + } + return true; +} + +} // namespace + +std::optional Parse(std::istream &Stream, std::string &Error) +{ + auto const fileBytes{streamBytes(Stream)}; + std::array bytes{}; + if (false == readBytes(Stream, 0, bytes)) + { + Error = "the file is shorter than the header"; + return std::nullopt; + } + if (false == std::ranges::equal(std::span{bytes}.first(identifier.size()), identifier)) + { + Error = "it isn't a ktx2 file"; + return std::nullopt; + } + Header const head{bytes}; + Error = head.shapeError(); + if (false == Error.empty()) + { + return std::nullopt; + } + auto const format{std::ranges::find(formats, head.vkFormat, &FormatEntry::vkFormat)}; + if (format == formats.end()) + { + Error = (head.vkFormat == 0 ? std::string{"basis universal (or no stated format) isn't supported"} : std::format("its format (vkFormat {}) isn't supported", head.vkFormat)); + return std::nullopt; + } + auto const supercompression{supercompressionOf(head.scheme, Error)}; + if (false == supercompression.has_value()) + { + return std::nullopt; + } + + Description image; + image.format = format->format; + image.srgb = format->srgb; + image.width = head.width; + image.height = head.height; + image.supercompression = *supercompression; + if (false == readLevelIndex(Stream, head, fileBytes, image, Error)) + { + return std::nullopt; + } + // the orientation is optional: data which can't be read is taken for none + if ((head.keyValueLength > 0) && (head.keyValueLength <= maxKeyValueBytes) && fits(head.keyValueOffset, head.keyValueLength, fileBytes)) + { + std::vector keyValues(head.keyValueLength); + if (readBytes(Stream, head.keyValueOffset, keyValues)) + { + image.origin = originOf(keyValues); + } + } + Error.clear(); + return image; +} + +bool IsCompressed(Format const Value) +{ + return (Value != Format::rgba8) && (Value != Format::bgra8); +} + +std::uint32_t BlockBytes(Format const Value) +{ + using enum Format; + switch (Value) + { + case bc1Rgb: + case bc1Rgba: + case bc4: + case bc4Signed: + return 8; + case rgba8: + case bgra8: + return 4; + default: + return 16; + } +} + +std::uint64_t LevelBytes(Format const Value, std::uint32_t const Width, std::uint32_t const Height) +{ + if (false == IsCompressed(Value)) + { + return static_cast(Width) * Height * BlockBytes(Value); + } + return static_cast((Width + 3) / 4) * ((Height + 3) / 4) * BlockBytes(Value); +} + +std::uint32_t LevelExtent(std::uint32_t const Extent, std::size_t const Level) +{ + if (Level >= 32) + { + return 1; + } + return std::max(Extent >> Level, 1u); +} + +bool ReadLevels(std::istream &Stream, Description const &Image, std::size_t const First, std::size_t const Count, std::vector &Data, std::string &Error) +{ + if ((First > Image.levels.size()) || (Count > Image.levels.size() - First)) + { + Error = std::format("the file has no level {}", First + Count - 1); + return false; + } + std::vector packed; + for (auto index = First; index < First + Count; ++index) + { + if (false == readLevel(Stream, Image, index, packed, Data, Error)) + { + return false; + } + } + return true; +} + +bool CanFlip(Format const Value) +{ + return (Value != Format::bc6h) && (Value != Format::bc6hSigned) && (Value != Format::bc7); +} + +void FlipLevels(Format const Value, std::span const Data, std::uint32_t const Width, std::uint32_t const Height, std::size_t const Count) +{ + if (false == CanFlip(Value)) + { + return; + } + std::size_t offset{0}; + for (std::size_t level = 0; level < Count; ++level) + { + auto const width{LevelExtent(Width, level)}; + auto const height{LevelExtent(Height, level)}; + auto const bytes{static_cast(LevelBytes(Value, width, height))}; + if (bytes > Data.size() - offset) + { + return; + } + flipLevel(Value, Data.subspan(offset, bytes), width, height); + offset += bytes; + } +} + +} // namespace ktx2 diff --git a/model/ktx2.h b/model/ktx2.h new file mode 100644 index 000000000..5a2ae2f57 --- /dev/null +++ b/model/ktx2.h @@ -0,0 +1,105 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +// the khronos texture 2.0 files (.ktx2) the game takes: a 2d image with its mipmaps, of the bc formats (bc1 to bc7) or of plain +// rgba / bgra bytes, its levels stored as they are or packed with zstd. the files hold the levels the way vulkan takes them; what +// the renderers make of them is the matter of texture_source::load_KTX2() (model/Texture.cpp). the code here knows nothing of +// opengl or vulkan, so that it can be tested on its own +namespace ktx2 +{ + +// the formats of the texels the game takes from the files (vkFormat of the header) +enum class Format +{ + bc1Rgb, // no alpha + bc1Rgba, // 1 bit alpha + bc2, + bc3, + bc4, // one channel (red) + bc4Signed, + bc5, // two channels (red, green): normal maps + bc5Signed, + bc6h, // hdr colour, no alpha + bc6hSigned, + bc7, + rgba8, + bgra8 +}; + +// how the levels are stored in the file +enum class Supercompression +{ + none, + zstd +}; + +// where the file says the first row of a level is (the KTXorientation key) +enum class Origin +{ + unstated, + top, // "rd", what the format holds by default + bottom // "ru" +}; + +// a level of the image in the file: where its data is, how many bytes it takes there and how many unpacked +struct Level +{ + std::uint64_t offset{0}; + std::uint64_t length{0}; + std::uint64_t uncompressedLength{0}; +}; + +// what the header of a file tells of its image +struct Description +{ + Format format{Format::rgba8}; + bool srgb{false}; // the file states srgb colour (the material decides it in the game, as it does for the dds files) + std::uint32_t width{0}; + std::uint32_t height{0}; + Supercompression supercompression{Supercompression::none}; + Origin origin{Origin::unstated}; + std::vector levels; // the largest first +}; + +// the description of the image of a file, or nothing and the reason in Error when the game can't take it. reads the header, the +// index of the levels and the key/value data; the levels themselves aren't read +std::optional Parse(std::istream &Stream, std::string &Error); + +// whether the format is made of the 4x4 blocks +bool IsCompressed(Format Value); +// the bytes of a 4x4 block of a compressed format, of a texel of the others +std::uint32_t BlockBytes(Format Value); +// the bytes the data of a level of the given size takes +std::uint64_t LevelBytes(Format Value, std::uint32_t Width, std::uint32_t Height); +// the size of a level +std::uint32_t LevelExtent(std::uint32_t Extent, std::size_t Level); + +// appends the data of Count levels of the image, from the level First on, to Data: read from the file and unpacked. false and the +// reason in Error when the file doesn't hold them whole +bool ReadLevels(std::istream &Stream, Description const &Image, std::size_t First, std::size_t Count, std::vector &Data, std::string &Error); + +// whether the rows of the format can be turned upside down without decoding it: not those of bc6h and bc7, whose blocks are +// split into parts in many ways +bool CanFlip(Format Value); +// turns the rows of Count levels, one after another in Data and the first of the given size, upside down. of a compressed level the +// rows of its blocks swap places and the rows of texels inside each block too; a level lower than a block has only its rows of +// texels swapped, the rest of the block isn't drawn +void FlipLevels(Format Value, std::span Data, std::uint32_t Width, std::uint32_t Height, std::size_t Count); + +} // namespace ktx2 diff --git a/model/materialdata.cpp b/model/materialdata.cpp index 8d026d71a..7c4c13bb7 100644 --- a/model/materialdata.cpp +++ b/model/materialdata.cpp @@ -23,7 +23,7 @@ TextureTest( std::string const &Name ) { auto const lookup { FileExists( { Global.asCurrentTexturePath + Name, Name, paths::textures + Name }, - { ".mat", ".dds", ".tga", ".ktx", ".png", ".bmp", ".jpg", ".tex" } ) }; + { ".mat", ".dds", ".ktx2", ".tga", ".ktx", ".png", ".bmp", ".jpg", ".tex" } ) }; return lookup.first + lookup.second; } diff --git a/rendering/vulkan14/vulkan14texture.cpp b/rendering/vulkan14/vulkan14texture.cpp index c0d469fe6..ff6951298 100644 --- a/rendering/vulkan14/vulkan14texture.cpp +++ b/rendering/vulkan14/vulkan14texture.cpp @@ -498,10 +498,50 @@ void image_table::clear() // formats +namespace +{ + +// the compressed formats only the ktx2 files give, which hold no alpha: it reads 1 as it does in opengl, so the alpha test of the +// shadow maps keeps every texel. bc4, bc5 and bc6h have no srgb variants, their values are taken as they are (as in the opengl +// renderer). nothing for the other formats +std::optional alphaless_format_of(GLint const Format, bool const Srgb) +{ + texture_format result; + result.compressed = true; + result.components.a = VK_COMPONENT_SWIZZLE_ONE; + switch (Format) + { + case GL_COMPRESSED_SRGB_S3TC_DXT1_EXT: + case GL_COMPRESSED_RGB_S3TC_DXT1_EXT: + result.format = ((Srgb || (Format == GL_COMPRESSED_SRGB_S3TC_DXT1_EXT)) ? VK_FORMAT_BC1_RGB_SRGB_BLOCK : VK_FORMAT_BC1_RGB_UNORM_BLOCK); + result.block_bytes = 8; + return result; + case GL_COMPRESSED_RED_RGTC1: + case GL_COMPRESSED_SIGNED_RED_RGTC1: + result.format = (Format == GL_COMPRESSED_RED_RGTC1 ? VK_FORMAT_BC4_UNORM_BLOCK : VK_FORMAT_BC4_SNORM_BLOCK); + result.block_bytes = 8; + return result; + case GL_COMPRESSED_RG_RGTC2: + case GL_COMPRESSED_SIGNED_RG_RGTC2: + result.format = (Format == GL_COMPRESSED_RG_RGTC2 ? VK_FORMAT_BC5_UNORM_BLOCK : VK_FORMAT_BC5_SNORM_BLOCK); + result.block_bytes = 16; + return result; + case GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT: + case GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT: + result.format = (Format == GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT ? VK_FORMAT_BC6H_UFLOAT_BLOCK : VK_FORMAT_BC6H_SFLOAT_BLOCK); + result.block_bytes = 16; + return result; + default: + return std::nullopt; + } +} + +} // namespace + texture_format texture_format_of(GLint Format, GLint Hint) { // (etc2 of the ktx files isn't mapped: the desktop gpus don't sample it, and the feature isn't enabled on the device; the - // opengl driver decodes it) + // opengl driver decodes it. the bc formats of the ktx2 files are: all of them are part of textureCompressionBC) // the material wants srgb colours (the default), or values: the compressed formats keep their alpha either way, as in the // opengl renderer (opengl_texture::mapping) auto const srgb{(Hint == 0) || (Hint == GL_SRGB_ALPHA) || (Hint == GL_SRGB)}; @@ -533,6 +573,15 @@ texture_format texture_format_of(GLint Format, GLint Hint) result.compressed = true; result.block_bytes = 16; return result; + default: + break; + } + if (auto const alphaless{alphaless_format_of(Format, srgb)}; alphaless.has_value()) + { + return *alphaless; + } + switch (Format) + { case GL_RGBA: case GL_BGRA: case GL_RGB: diff --git a/tests/unit/CMakeLists.txt b/tests/unit/CMakeLists.txt index 44684b79b..65ce5d5c6 100644 --- a/tests/unit/CMakeLists.txt +++ b/tests/unit/CMakeLists.txt @@ -34,6 +34,9 @@ add_executable(${UNIT_TESTS_NAME} "${CMAKE_SOURCE_DIR}/editor/editorFouling.cpp" # which textures the shadow maps draw without the alpha test "${CMAKE_SOURCE_DIR}/rendering/common/texturealpha.cpp" + # and the ktx2 texture files, with the zstd their levels are packed with + "${CMAKE_SOURCE_DIR}/model/ktx2.cpp" + "${DEPS_DIR}/zstd/zstd.c" # and the movement of the free camera the motion blur takes "${CMAKE_SOURCE_DIR}/rendering/common/freecameramotion.cpp" # and the http client the editor fetches its aids with diff --git a/tests/unit/test_ktx2.cpp b/tests/unit/test_ktx2.cpp new file mode 100644 index 000000000..1bf5bbc81 --- /dev/null +++ b/tests/unit/test_ktx2.cpp @@ -0,0 +1,419 @@ +#include "stdafx.h" +#include "doctest.h" +#include "model/ktx2.h" + +#include "zstd.h" + +#include +#include +#include +#include +#include +#include + +// the khronos texture 2.0 files the game reads: what the header tells, the levels read and unpacked from zstd, and the rows of the +// bc formats turned upside down without decoding them +namespace +{ + +using Bytes = std::vector; + +// a file made for a test: the levels are stored the smallest first, after the header, the index and the key/value data, as the +// tools write them +struct TestFile +{ + std::uint32_t vkFormat{145}; // VK_FORMAT_BC7_UNORM_BLOCK + std::uint32_t width{16}; + std::uint32_t height{16}; + std::uint32_t depth{0}; + std::uint32_t faces{1}; + std::uint32_t scheme{0}; + std::string orientation; // the value of KTXorientation, no key when empty + std::vector levels; // the data stored of each level, the largest first + std::vector unpacked; // the sizes of the levels packed with zstd, unpacked + std::uint64_t levelOffsetShift{0}; // moves the data of the levels in the index, for a broken file +}; + +void put32(std::string &Out, std::uint32_t const Value) +{ + for (int shift = 0; shift < 32; shift += 8) + { + Out.push_back(static_cast((Value >> shift) & 0xff)); + } +} + +void put64(std::string &Out, std::uint64_t const Value) +{ + put32(Out, static_cast(Value & 0xffffffffu)); + put32(Out, static_cast(Value >> 32)); +} + +std::string keyValues(std::string const &Orientation) +{ + std::string out; + if (Orientation.empty()) + { + return out; + } + std::string entry{"KTXorientation"}; + entry.push_back('\0'); + entry += Orientation; + entry.push_back('\0'); + put32(out, static_cast(entry.size())); + out += entry; + out.resize((out.size() + 3) & ~std::size_t{3}, '\0'); + return out; +} + +std::string write(TestFile const &File) +{ + auto const kvd{keyValues(File.orientation)}; + auto const count{File.levels.size()}; + auto const kvdOffset{80 + 24 * count}; + // the data of the levels, the smallest first + std::vector offsets(count); + auto position{kvdOffset + kvd.size()}; + for (auto level = count; level-- > 0;) + { + offsets[level] = position; + position += File.levels[level].size(); + } + + std::string out{"\xAB\x4B\x54\x58\x20\x32\x30\xBB\x0D\x0A\x1A\x0A", 12}; + put32(out, File.vkFormat); + put32(out, 1); // typeSize + put32(out, File.width); + put32(out, File.height); + put32(out, File.depth); + put32(out, 0); // layerCount + put32(out, File.faces); + put32(out, static_cast(count)); + put32(out, File.scheme); + put32(out, 0); // dfdByteOffset: the descriptor isn't read + put32(out, 0); + put32(out, kvd.empty() ? 0 : static_cast(kvdOffset)); + put32(out, static_cast(kvd.size())); + put64(out, 0); // sgdByteOffset + put64(out, 0); + for (std::size_t level = 0; level < count; ++level) + { + put64(out, offsets[level] + File.levelOffsetShift); + put64(out, File.levels[level].size()); + put64(out, File.unpacked.empty() ? File.levels[level].size() : File.unpacked[level]); + } + out += kvd; + for (auto level = count; level-- > 0;) + { + out.append(reinterpret_cast(File.levels[level].data()), File.levels[level].size()); + } + return out; +} + +// data of the given size made of a running count, different in each level +Bytes counting(std::size_t const Size, std::uint8_t const Start) +{ + Bytes out(Size); + std::iota(out.begin(), out.end(), Start); + return out; +} + +Bytes pack(Bytes const &Data) +{ + Bytes out(ZSTD_compressBound(Data.size())); + auto const size{ZSTD_compress(out.data(), out.size(), Data.data(), Data.size(), 3)}; + REQUIRE(ZSTD_isError(size) == 0); + out.resize(size); + return out; +} + +std::optional parse(std::string const &Content, std::string &Error) +{ + std::istringstream stream{Content}; + return ktx2::Parse(stream, Error); +} + +// the bc7 file of a 16x16 image with its three levels down to a block +TestFile bc7File() +{ + TestFile file; + file.levels = {counting(16 * 16, 0), counting(4 * 16, 1), counting(16, 2)}; + return file; +} + +} // namespace + +TEST_CASE("ktx2: the header of a bc7 file describes its image and levels") +{ + auto file{bc7File()}; + file.vkFormat = 146; // VK_FORMAT_BC7_SRGB_BLOCK + std::string error; + auto const image{parse(write(file), error)}; + REQUIRE_MESSAGE(image.has_value(), error); + CHECK(image->format == ktx2::Format::bc7); + CHECK(image->srgb); + CHECK(image->width == 16); + CHECK(image->height == 16); + CHECK(image->supercompression == ktx2::Supercompression::none); + CHECK(image->origin == ktx2::Origin::unstated); + REQUIRE(image->levels.size() == 3); + CHECK(image->levels[0].length == 256); + CHECK(image->levels[2].length == 16); +} + +TEST_CASE("ktx2: the levels are read the largest first, from where the index puts them") +{ + auto const file{bc7File()}; + auto const content{write(file)}; + std::string error; + auto const image{parse(content, error)}; + REQUIRE(image.has_value()); + + std::istringstream stream{content}; + Bytes data; + REQUIRE_MESSAGE(ktx2::ReadLevels(stream, *image, 0, 3, data, error), error); + Bytes expected; + for (auto const &level : file.levels) + { + expected.insert(expected.end(), level.begin(), level.end()); + } + CHECK(data == expected); + + // the levels past those too large for the game, appended to what's there + Bytes tail{9}; + REQUIRE(ktx2::ReadLevels(stream, *image, 1, 2, tail, error)); + CHECK(tail.size() == 1 + 64 + 16); + CHECK(tail[0] == 9); + CHECK(tail[1] == file.levels[1][0]); + CHECK_FALSE(ktx2::ReadLevels(stream, *image, 2, 2, tail, error)); +} + +TEST_CASE("ktx2: levels packed with zstd are unpacked") +{ + TestFile file; + file.vkFormat = 133; // VK_FORMAT_BC1_RGBA_UNORM_BLOCK + file.width = 8; + file.height = 8; + file.scheme = 2; + std::vector const plain{counting(4 * 8, 10), counting(8, 20), counting(8, 30), counting(8, 40)}; + for (auto const &level : plain) + { + file.levels.push_back(pack(level)); + file.unpacked.push_back(level.size()); + } + auto const content{write(file)}; + std::string error; + auto const image{parse(content, error)}; + REQUIRE_MESSAGE(image.has_value(), error); + CHECK(image->format == ktx2::Format::bc1Rgba); + CHECK_FALSE(image->srgb); + CHECK(image->supercompression == ktx2::Supercompression::zstd); + + std::istringstream stream{content}; + Bytes data; + REQUIRE_MESSAGE(ktx2::ReadLevels(stream, *image, 0, 4, data, error), error); + Bytes expected; + for (auto const &level : plain) + { + expected.insert(expected.end(), level.begin(), level.end()); + } + CHECK(data == expected); +} + +TEST_CASE("ktx2: a level which doesn't unpack fails to be read and leaves the data as it was") +{ + TestFile file; + file.vkFormat = 141; // VK_FORMAT_BC5_UNORM_BLOCK + file.width = 4; + file.height = 4; + file.scheme = 2; + file.levels = {Bytes(16, 0x55)}; // not zstd + file.unpacked = {16}; + auto const content{write(file)}; + std::string error; + auto const image{parse(content, error)}; + REQUIRE(image.has_value()); + std::istringstream stream{content}; + Bytes data{1, 2}; + CHECK_FALSE(ktx2::ReadLevels(stream, *image, 0, 1, data, error)); + CHECK(data == Bytes{1, 2}); + CHECK_FALSE(error.empty()); +} + +TEST_CASE("ktx2: the orientation key tells where the first row is") +{ + auto file{bc7File()}; + std::string error; + file.orientation = "rd"; + CHECK(parse(write(file), error)->origin == ktx2::Origin::top); + file.orientation = "ru"; + CHECK(parse(write(file), error)->origin == ktx2::Origin::bottom); + file.orientation = "r"; + CHECK(parse(write(file), error)->origin == ktx2::Origin::unstated); +} + +TEST_CASE("ktx2: the formats of the bc family and plain bytes are known") +{ + struct Case + { + std::uint32_t vkFormat; + ktx2::Format format; + bool srgb; + }; + std::array const cases{Case{37, ktx2::Format::rgba8, false}, Case{50, ktx2::Format::bgra8, true}, Case{132, ktx2::Format::bc1Rgb, true}, + Case{135, ktx2::Format::bc2, false}, Case{138, ktx2::Format::bc3, true}, Case{139, ktx2::Format::bc4, false}, + Case{140, ktx2::Format::bc4Signed, false}, Case{142, ktx2::Format::bc5Signed, false}, Case{143, ktx2::Format::bc6h, false}, + Case{144, ktx2::Format::bc6hSigned, false}}; + for (auto const &item : cases) + { + CAPTURE(item.vkFormat); + TestFile file; + file.vkFormat = item.vkFormat; + file.width = 4; + file.height = 4; + file.levels = {Bytes(ktx2::LevelBytes(item.format, 4, 4))}; + std::string error; + auto const image{parse(write(file), error)}; + REQUIRE_MESSAGE(image.has_value(), error); + CHECK(image->format == item.format); + CHECK(image->srgb == item.srgb); + } +} + +TEST_CASE("ktx2: files the game can't take are refused with the reason") +{ + std::string error; + SUBCASE("not a ktx2 file") + { + auto content{write(bc7File())}; + content[5] = '1'; // "KTX 10" + CHECK_FALSE(parse(content, error).has_value()); + } + SUBCASE("cut short in the header") + { + CHECK_FALSE(parse(write(bc7File()).substr(0, 40), error).has_value()); + } + SUBCASE("basis universal") + { + auto file{bc7File()}; + file.vkFormat = 0; + file.scheme = 1; + CHECK_FALSE(parse(write(file), error).has_value()); + } + SUBCASE("basislz supercompression") + { + auto file{bc7File()}; + file.scheme = 1; + CHECK_FALSE(parse(write(file), error).has_value()); + } + SUBCASE("an unknown format") + { + auto file{bc7File()}; + file.vkFormat = 147; // VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK + CHECK_FALSE(parse(write(file), error).has_value()); + } + SUBCASE("a cube map") + { + auto file{bc7File()}; + file.faces = 6; + CHECK_FALSE(parse(write(file), error).has_value()); + } + SUBCASE("a 3d image") + { + auto file{bc7File()}; + file.depth = 4; + CHECK_FALSE(parse(write(file), error).has_value()); + } + SUBCASE("a level past the end of the file") + { + auto file{bc7File()}; + file.levelOffsetShift = 1000; + CHECK_FALSE(parse(write(file), error).has_value()); + } + SUBCASE("a level shorter than its texels") + { + auto file{bc7File()}; + file.levels[1].resize(32); + CHECK_FALSE(parse(write(file), error).has_value()); + } + SUBCASE("a packed level which unpacks to another size") + { + auto file{bc7File()}; + file.scheme = 2; + file.unpacked = {256, 64, 32}; + CHECK_FALSE(parse(write(file), error).has_value()); + } + CHECK_FALSE(error.empty()); +} + +TEST_CASE("ktx2: the sizes of the levels") +{ + CHECK(ktx2::LevelExtent(16, 0) == 16); + CHECK(ktx2::LevelExtent(16, 3) == 2); + CHECK(ktx2::LevelExtent(16, 7) == 1); + CHECK(ktx2::LevelExtent(16, 40) == 1); + CHECK(ktx2::LevelBytes(ktx2::Format::bc1Rgb, 8, 8) == 32); + CHECK(ktx2::LevelBytes(ktx2::Format::bc1Rgb, 2, 1) == 8); + CHECK(ktx2::LevelBytes(ktx2::Format::bc5, 8, 4) == 32); + CHECK(ktx2::LevelBytes(ktx2::Format::bc7, 1, 1) == 16); + CHECK(ktx2::LevelBytes(ktx2::Format::rgba8, 3, 2) == 24); +} + +TEST_CASE("ktx2: the rows of a bc1 image are turned upside down block by block") +{ + // a 4x8 image: two blocks one above the other, each with its colours and a row of indices per texel row + Bytes data{0x11, 0x11, 0x22, 0x22, 0x00, 0x01, 0x02, 0x03, 0x33, 0x33, 0x44, 0x44, 0x10, 0x11, 0x12, 0x13}; + ktx2::FlipLevels(ktx2::Format::bc1Rgb, data, 4, 8, 1); + CHECK(data == Bytes{0x33, 0x33, 0x44, 0x44, 0x13, 0x12, 0x11, 0x10, 0x11, 0x11, 0x22, 0x22, 0x03, 0x02, 0x01, 0x00}); + + // a level of 2 rows has only those swapped, the rest of the block isn't drawn + Bytes lowLevel{0x11, 0x11, 0x22, 0x22, 0x00, 0x01, 0x02, 0x03}; + ktx2::FlipLevels(ktx2::Format::bc1Rgba, lowLevel, 2, 2, 1); + CHECK(lowLevel == Bytes{0x11, 0x11, 0x22, 0x22, 0x01, 0x00, 0x02, 0x03}); +} + +TEST_CASE("ktx2: the rows of the alpha and of the channels of bc2 to bc5 are swapped") +{ + // a bc4 block of 4 rows of 12 bit indices: 0x001, 0x002, 0x003, 0x004 + Bytes const bc4{0xff, 0x00, 0x01, 0x20, 0x00, 0x03, 0x40, 0x00}; + auto flipped{bc4}; + ktx2::FlipLevels(ktx2::Format::bc4, flipped, 4, 4, 1); + CHECK(flipped == Bytes{0xff, 0x00, 0x04, 0x30, 0x00, 0x02, 0x10, 0x00}); + + // the alpha of bc3 is a bc4 block, its colour a bc1 one + Bytes bc3{bc4}; + bc3.insert(bc3.end(), {0x11, 0x11, 0x22, 0x22, 0x00, 0x01, 0x02, 0x03}); + ktx2::FlipLevels(ktx2::Format::bc3, bc3, 4, 4, 1); + CHECK(Bytes(bc3.begin(), bc3.begin() + 8) == flipped); + CHECK(Bytes(bc3.begin() + 12, bc3.end()) == Bytes{0x03, 0x02, 0x01, 0x00}); + + // the explicit alpha of bc2: 16 bits a row + Bytes bc2{0x01, 0x10, 0x02, 0x20, 0x03, 0x30, 0x04, 0x40, 0x11, 0x11, 0x22, 0x22, 0x00, 0x01, 0x02, 0x03}; + ktx2::FlipLevels(ktx2::Format::bc2, bc2, 4, 4, 1); + CHECK(Bytes(bc2.begin(), bc2.begin() + 8) == Bytes{0x04, 0x40, 0x03, 0x30, 0x02, 0x20, 0x01, 0x10}); + + // flipped twice, the levels of an image come back as they were + for (auto const format : {ktx2::Format::bc2, ktx2::Format::bc3, ktx2::Format::bc4Signed, ktx2::Format::bc5}) + { + auto const original{counting(static_cast(ktx2::LevelBytes(format, 16, 8) + ktx2::LevelBytes(format, 8, 4) + ktx2::LevelBytes(format, 4, 2)), 7)}; + auto data{original}; + ktx2::FlipLevels(format, data, 16, 8, 3); + CHECK(data != original); + ktx2::FlipLevels(format, data, 16, 8, 3); + CHECK(data == original); + } +} + +TEST_CASE("ktx2: plain texels have their rows swapped, bc6h and bc7 are left as they are") +{ + Bytes rgba{1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6}; + ktx2::FlipLevels(ktx2::Format::rgba8, rgba, 2, 3, 1); + CHECK(rgba == Bytes{5, 5, 5, 5, 6, 6, 6, 6, 3, 3, 3, 3, 4, 4, 4, 4, 1, 1, 1, 1, 2, 2, 2, 2}); + + CHECK_FALSE(ktx2::CanFlip(ktx2::Format::bc7)); + CHECK_FALSE(ktx2::CanFlip(ktx2::Format::bc6h)); + CHECK(ktx2::CanFlip(ktx2::Format::bc5Signed)); + auto const original{counting(32, 0)}; + auto data{original}; + ktx2::FlipLevels(ktx2::Format::bc7, data, 4, 8, 1); + CHECK(data == original); +}