/* 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