11#include <unordered_map>
14#ifdef SOURCEPP_BUILD_WITH_TBB
18#ifdef SOURCEPP_BUILD_WITH_THREADS
23#include <BufferStream.h>
37[[nodiscard]] std::vector<std::byte> compressData(std::span<const std::byte> data, int16_t level,
CompressionMethod method) {
41 mz_ulong compressedSize = mz_compressBound(data.size());
42 std::vector<std::byte> out(compressedSize);
45 while ((status = mz_compress2(
reinterpret_cast<unsigned char*
>(out.data()), &compressedSize,
reinterpret_cast<const unsigned char*
>(data.data()), data.size(), level)) == MZ_BUF_ERROR) {
47 out.resize(compressedSize);
50 if (status != MZ_OK) {
53 out.resize(compressedSize);
61 const auto expectedSize = ZSTD_compressBound(data.size());
62 std::vector<std::byte> out(expectedSize);
64 const auto compressedSize = ZSTD_compress(out.data(), expectedSize, data.data(), data.size(), level);
65 if (ZSTD_isError(compressedSize)) {
69 out.resize(compressedSize);
82template<std::
unsigned_
integral T,
bool ExistingDataIsSwizzled>
83constexpr void swizzleUncompressedImageData(std::span<std::byte> inputData, std::span<std::byte> outputData,
ImageFormat format, uint16_t width, uint16_t height, uint16_t depth) {
90 ](uint32_t x, uint32_t y, uint32_t z) {
91 auto widthL2m = widthL2;
92 auto heightL2m = heightL2;
93 auto depthL2m = depthL2;
95 uint32_t shiftCount = 0;
98 offset |= (z & 1) << shiftCount++;
101 if (heightL2m --> 0) {
102 offset |= (y & 1) << shiftCount++;
105 if (widthL2m --> 0) {
106 offset |= (x & 1) << shiftCount++;
109 }
while (x || y || z);
113 const auto* inputPtr =
reinterpret_cast<const T*
>(inputData.data());
114 auto* outputPtr =
reinterpret_cast<T*
>(outputData.data());
116 for (uint16_t x = 0; x < width; x++) {
117 for (uint16_t y = 0; y < height; y++) {
118 for (uint16_t z = 0; z < depth; z++) {
119 if constexpr (ExistingDataIsSwizzled) {
120 *outputPtr++ =
reinterpret_cast<const T*
>(inputData.data())[zIndex(x, y, z)];
122 reinterpret_cast<T*
>(outputData.data())[zIndex(x, y, z)] = *inputPtr++;
129template<
bool ExistingDataIsSwizzled>
130void swizzleUncompressedImageDataXBOX(std::span<std::byte> inputData, std::span<std::byte> outputData,
ImageFormat format, uint16_t width, uint16_t height, uint16_t depth) {
131 const auto zIndex = [
135 ](int32_t x, int32_t y, int32_t z) {
136 int widthL2m = widthL2;
137 int heightL2m = heightL2;
138 int depthL2m = depthL2;
140 uint32_t shiftCount = 0;
142 while (widthL2m > 0 || heightL2m > 0 || depthL2m > 0) {
144 offset |= (x & 1) << shiftCount++;
149 offset |= (y & 1) << shiftCount++;
154 offset |= (z & 1) << shiftCount++;
164 uint32_t linearIndex = 0;
165 for (uint16_t z = 0; z < depth; z++) {
166 for (uint16_t y = 0; y < height; y++) {
167 for (uint16_t x = 0; x < width; x++) {
168 const auto codedIndex = zIndex(x, y, z);
169 for (uint32_t b = 0; b < stride; b++) {
170 if constexpr (ExistingDataIsSwizzled) {
171 outputData[linearIndex * stride + b] = inputData[codedIndex * stride + b];
173 outputData[codedIndex * stride + b] = inputData[linearIndex * stride + b];
182template<
bool ConvertingFromSource>
183void swapImageDataEndianForConsole(std::span<std::byte> imageData,
ImageFormat format, uint8_t mipCount, uint16_t frameCount, uint8_t faceCount, uint16_t width, uint16_t height, uint16_t depth,
VTF::Platform platform) {
196 std::ranges::copy(newData, imageData.begin());
204 std::span dxtData{
reinterpret_cast<uint16_t*
>(imageData.data()), imageData.size() /
sizeof(uint16_t)};
206#ifdef SOURCEPP_BUILD_WITH_TBB
207 std::execution::par_unseq,
209 dxtData.begin(), dxtData.end(), [](uint16_t& value) {
210 BufferStream::swap_endian(&value);
222 std::vector<std::byte> out(imageData.size());
223 for(
int mip = mipCount - 1; mip >= 0; mip--) {
225 for (
int frame = 0; frame < frameCount; frame++) {
226 for (
int face = 0; face < faceCount; face++) {
227 if (uint32_t offset, length;
ImageFormatDetails::getDataPosition(offset, length, format, mip, mipCount, frame, frameCount, face, faceCount, width, height)) {
228 std::span imageDataSpan{imageData.data() + offset, length * mipDepth};
229 std::span outSpan{out.data() + offset, length * mipDepth};
231 ::swizzleUncompressedImageDataXBOX<ConvertingFromSource>(imageDataSpan, outSpan, format, mipWidth, mipHeight, mipDepth);
233 ::swizzleUncompressedImageData<uint32_t, ConvertingFromSource>(imageDataSpan, outSpan, format, mipWidth, mipHeight, mipDepth);
235 ::swizzleUncompressedImageData<uint16_t, ConvertingFromSource>(imageDataSpan, outSpan, format, mipWidth, mipHeight, mipDepth);
237 ::swizzleUncompressedImageData<uint8_t, ConvertingFromSource>(imageDataSpan, outSpan, format, mipWidth, mipHeight, mipDepth);
243 std::memcpy(imageData.data(), out.data(), out.size());
247template<
bool ConvertingFromDDS>
248[[nodiscard]] std::vector<std::byte> convertBetweenDDSAndVTFMipOrderForXBOX(
bool padded, std::span<const std::byte> imageData,
ImageFormat format, uint8_t mipCount, uint16_t frameCount, uint8_t faceCount, uint16_t width, uint16_t height, uint16_t depth,
bool& ok) {
249 std::vector<std::byte> reorderedImageData;
251 BufferStream reorderedStream{reorderedImageData};
253 if constexpr (ConvertingFromDDS) {
254 for (
int i = mipCount - 1; i >= 0; i--) {
256 for (
int j = 0; j < frameCount; j++) {
257 for (
int k = 0; k < faceCount; k++) {
258 for (
int l = 0; l < mipDepth; l++) {
259 uint32_t oldOffset, length;
260 if (!
ImageFormatDetails::getDataPositionXBOX(oldOffset, length, padded, format, i, mipCount, j, frameCount, k, faceCount, width, height, l, depth)) {
264 reorderedStream << imageData.subspan(oldOffset, length);
270 for (
int j = 0; j < frameCount; j++) {
271 for (
int k = 0; k < faceCount; k++) {
272 for (
int i = 0; i < mipCount; i++) {
274 for (
int l = 0; l < mipDepth; l++) {
275 uint32_t oldOffset, length;
276 if (!
ImageFormatDetails::getDataPosition(oldOffset, length, format, i, mipCount, j, frameCount, k, faceCount, width, height, l, depth)) {
280 reorderedStream << imageData.subspan(oldOffset, length);
284 if (padded && j + 1 != frameCount && reorderedStream.tell() > 512) {
291 return reorderedImageData;
297 switch (this->
type) {
299 if (this->data.size() <=
sizeof(uint32_t)) {
302 return SHT{{
reinterpret_cast<const std::byte*
>(this->data.data()) +
sizeof(uint32_t), *
reinterpret_cast<const uint32_t*
>(this->data.data())}};
305 if (this->data.size() !=
sizeof(uint32_t)) {
308 return *
reinterpret_cast<const uint32_t*
>(this->data.data());
310 if (this->data.size() !=
sizeof(uint32_t)) {
313 return std::make_tuple(
314 *(
reinterpret_cast<const uint8_t*
>(this->data.data()) + 0),
315 *(
reinterpret_cast<const uint8_t*
>(this->data.data()) + 1),
316 *(
reinterpret_cast<const uint8_t*
>(this->data.data()) + 2),
317 *(
reinterpret_cast<const uint8_t*
>(this->data.data()) + 3));
319 if (this->data.size() <=
sizeof(uint32_t)) {
322 return std::string(
reinterpret_cast<const char*
>(this->data.data()) +
sizeof(uint32_t), *
reinterpret_cast<const uint32_t*
>(this->data.data()));
324 if (this->data.size() <=
sizeof(uint32_t)) {
327 return HOT{{
reinterpret_cast<const std::byte*
>(this->data.data()) +
sizeof(uint32_t), *
reinterpret_cast<const uint32_t*
>(this->data.data())}};
335 static constexpr auto PALETTE_FRAME_SIZE = 256 *
sizeof(ImagePixel::BGRA8888);
336 if (this->data.size() % PALETTE_FRAME_SIZE != 0 || PALETTE_FRAME_SIZE * frame > this->data.size()) {
339 return {this->data.data() + PALETTE_FRAME_SIZE * frame, this->data.data() + PALETTE_FRAME_SIZE * (frame + 1)};
355 return std::get<std::tuple<uint8_t, uint8_t, uint8_t, uint8_t>>(this->
convertData());
367 if (this->data.size() <
sizeof(uint32_t) * 2) {
370 return static_cast<int16_t
>(BufferStream{this->data}.skip<uint32_t>().read<uint32_t>() & 0xffff);
374 if (this->data.size() <
sizeof(uint32_t) * 2) {
377 const auto method =
static_cast<int16_t
>((BufferStream{this->data}.skip<uint32_t>().read<uint32_t>() & 0xffff0000) >> 16);
385 if (this->data.size() < ((mipCount - 1 - mip) * frameCount * faceCount + frame * faceCount + face + 2) *
sizeof(uint32_t)) {
388 return BufferStream{this->data}.skip<uint32_t>((mipCount - 1 - mip) * frameCount * faceCount + frame * faceCount + face + 2).read<uint32_t>();
395VTF::VTF(std::vector<std::byte>&& vtfData,
bool parseHeaderOnly)
396 :
data(std::move(vtfData)) {
397 BufferStreamReadOnly stream{this->data};
399 if (
const auto signature = stream.read<uint32_t>(); signature ==
VTF_SIGNATURE) {
400 stream >> this->platform;
401 if (this->platform != PLATFORM_PC) {
404 stream >> this->version;
409 stream.set_big_endian(
true);
410 stream >> this->platform;
411 if (this->platform != PLATFORM_X360 && this->platform != PLATFORM_PS3_ORANGEBOX && this->platform != PLATFORM_PS3_PORTAL2) {
414 stream >> this->version;
415 if (this->version != 8) {
420 this->platform = PLATFORM_PS3_PORTAL2;
426 stream >> this->platform;
427 if (this->platform != PLATFORM_XBOX) {
430 stream >> this->version;
431 if (this->version != 0) {
440 const auto headerSize = stream.read<uint32_t>();
442 const auto readResources = [
this, &stream](uint32_t resourceCount) {
444 this->resources.reserve(resourceCount);
445 for (
int i = 0; i < resourceCount; i++) {
446 auto& [type, flags_, data_] = this->resources.emplace_back();
448 auto typeAndFlags = stream.read<uint32_t>();
449 if (stream.is_big_endian()) {
451 BufferStream::swap_endian(&typeAndFlags);
455 data_ = stream.read_span<std::byte>(4);
458 BufferStream::swap_endian(
reinterpret_cast<uint32_t*
>(data_.data()));
467 std::ranges::sort(this->resources, [](
const Resource& lhs,
const Resource& rhs) {
477 return *
reinterpret_cast<uint32_t*
>(lhs.
data.data()) < *
reinterpret_cast<uint32_t*
>(rhs.
data.data());
482 for (
auto& resource : this->resources) {
485 const auto lastOffset = *
reinterpret_cast<uint32_t*
>(lastResource->data.data());
486 const auto currentOffset = *
reinterpret_cast<uint32_t*
>(resource.data.data());
487 const auto curPos = stream.tell();
488 stream.seek(lastOffset);
489 lastResource->data = stream.read_span<std::byte>(currentOffset - lastOffset);
490 stream.seek(
static_cast<int64_t
>(curPos));
492 lastResource = &resource;
496 const auto offset = *
reinterpret_cast<uint32_t*
>(lastResource->data.data());
497 const auto curPos = stream.tell();
499 lastResource->data = stream.read_span<std::byte>(stream.size() - offset);
500 stream.seek(
static_cast<int64_t
>(curPos));
505 const auto postReadTransform = [
this] {
509 if (this->format ==
ImageFormat::DXT1 && this->flags & (FLAG_V0_ONE_BIT_ALPHA | FLAG_V0_MULTI_BIT_ALPHA)) {
515 this->format =
static_cast<ImageFormat>(
static_cast<int32_t
>(this->format) - 3);
519 if (this->flags & FLAG_V0_NO_MIP && this->mipCount > 1) {
520 this->removeFlags(FLAG_V0_NO_MIP);
524 switch (this->platform) {
525 case PLATFORM_UNKNOWN:
532 .read(this->frameCount)
533 .read(this->startFrame)
535 .read(this->reflectivity[0])
536 .read(this->reflectivity[1])
537 .read(this->reflectivity[2])
539 .read(this->bumpMapScale)
541 .read(this->mipCount);
547 stream >> this->thumbnailWidth >> this->thumbnailHeight;
548 if (this->thumbnailWidth == 0 || this->thumbnailHeight == 0) {
554 if (this->version < 2) {
557 stream.read(this->depth);
560 if (parseHeaderOnly) {
565 if (this->version >= 3) {
567 auto resourceCount = stream.read<uint32_t>();
569 readResources(resourceCount);
571 this->opened = stream.tell() == headerSize;
573 if (this->opened && this->version >= 6) {
576 if (auxResource && imageResource) {
577 if (auxResource->getDataAsAuxCompressionLevel() != 0) {
578 const auto faceCount = this->getFaceCount();
579 std::vector<std::byte> decompressedImageData(
ImageFormatDetails::getDataLength(this->format, this->mipCount, this->frameCount, faceCount, this->width, this->height, this->depth));
580 uint32_t oldOffset = 0;
581 for (
int i = this->mipCount - 1; i >= 0; i--) {
582 for (
int j = 0; j < this->frameCount; j++) {
583 for (
int k = 0; k < faceCount; k++) {
584 uint32_t oldLength = auxResource->getDataAsAuxCompressionLength(i, this->mipCount, j, this->frameCount, k, faceCount);
585 if (uint32_t newOffset, newLength;
ImageFormatDetails::getDataPosition(newOffset, newLength, this->format, i, this->mipCount, j, this->frameCount, k, faceCount, this->width, this->height, 0, this->getDepth())) {
587 mz_ulong decompressedImageDataSize = newLength * this->depth;
588 switch (auxResource->getDataAsAuxCompressionMethod()) {
591 if (mz_uncompress(
reinterpret_cast<unsigned char*
>(decompressedImageData.data() + newOffset), &decompressedImageDataSize,
reinterpret_cast<const unsigned char*
>(imageResource->data.data() + oldOffset), oldLength) != MZ_OK) {
592 this->opened =
false;
597 if (
const auto decompressedSize = ZSTD_decompress(decompressedImageData.data() + newOffset, decompressedImageDataSize, imageResource->data.data() + oldOffset, oldLength); ZSTD_isError(decompressedSize) || decompressedSize != decompressedImageDataSize) {
598 this->opened =
false;
608 oldOffset += oldLength;
618 this->opened = stream.tell() == headerSize;
620 this->resources.reserve(2);
622 if (this->hasThumbnailData()) {
623 this->resources.push_back({
629 if (this->hasImageData()) {
630 this->resources.push_back({
633 .data = stream.read_span<std::byte>(stream.size() - stream.tell()),
639 this->compressionLevel = resource->getDataAsAuxCompressionLevel();
640 this->compressionMethod = resource->getDataAsAuxCompressionMethod();
645 case PLATFORM_XBOX: {
646 if (this->platform == PLATFORM_XBOX) {
647 uint16_t preloadSize = 0, imageOffset = 0;
653 .read(this->frameCount)
656 .read(this->reflectivity[0])
657 .read(this->reflectivity[1])
658 .read(this->reflectivity[2])
659 .read(this->bumpMapScale)
661 .read(this->thumbnailWidth)
662 .read(this->thumbnailHeight)
663 .read(this->fallbackWidth)
664 .read(this->fallbackHeight)
665 .read(this->consoleMipScale)
668 const bool headerSizeIsAccurate = stream.tell() == headerSize;
676 const auto faceCount = (this->flags & FLAG_V0_ENVMAP) ? 6 : 1;
678 if (this->thumbnailWidth == 0 || this->thumbnailHeight == 0) {
682 this->resources.push_back({
690 this->resources.push_back({
693 .data = stream.read_span<std::byte>(256 *
sizeof(ImagePixel::BGRA8888) * this->frameCount),
699 std::vector<std::byte> reorderedFallbackData;
700 if (this->hasFallbackData()) {
701 if (stream.tell() + fallbackSize != preloadSize) {
704 if (stream.tell() + fallbackSize != preloadSize) {
705 this->opened =
false;
708 this->fallbackMipCount = 1;
710 this->flags |= FLAG_V0_NO_MIP;
712 reorderedFallbackData = ::convertBetweenDDSAndVTFMipOrderForXBOX<true>(
false, stream.read_span<std::byte>(fallbackSize), this->format, this->fallbackMipCount, this->frameCount, faceCount, this->fallbackWidth, this->fallbackHeight, 1, ok);
714 this->opened =
false;
717 ::swapImageDataEndianForConsole<true>(reorderedFallbackData, this->format, this->fallbackMipCount, this->frameCount, faceCount, this->fallbackWidth, this->fallbackHeight, 1, this->platform);
720 this->opened = headerSizeIsAccurate;
721 if (parseHeaderOnly) {
726 std::vector<std::byte> reorderedImageData;
727 if (this->hasImageData()) {
728 reorderedImageData = ::convertBetweenDDSAndVTFMipOrderForXBOX<true>(
true, stream.seek(imageOffset).read_span<std::byte>(imageSize), this->format, this->mipCount, this->frameCount, faceCount, this->width, this->height, this->depth, ok);
730 this->opened =
false;
733 ::swapImageDataEndianForConsole<true>(reorderedImageData, this->format, this->mipCount, this->frameCount, faceCount, this->width, this->height, this->depth, this->platform);
737 if (this->hasFallbackData()) {
740 if (this->hasImageData()) {
747 case PLATFORM_PS3_ORANGEBOX:
748 case PLATFORM_PS3_PORTAL2: {
749 uint8_t resourceCount;
755 .read(this->frameCount)
757 .read(this->consoleMipScale)
759 .read(this->reflectivity[0])
760 .read(this->reflectivity[1])
761 .read(this->reflectivity[2])
762 .read(this->bumpMapScale)
764 .skip<math::Vec4ui8>()
770 if (this->platform == PLATFORM_PS3_PORTAL2) {
771 stream.skip<uint32_t>();
776 if (parseHeaderOnly) {
781 this->resources.reserve(resourceCount);
782 readResources(resourceCount);
784 this->opened = stream.tell() == headerSize;
787 for (
const auto& resource : this->resources) {
791 this->setResourceInternal(resource.type, *decompressedData);
801 ::swapImageDataEndianForConsole<true>(resource.data, this->thumbnailFormat, 1, 1, 1, this->thumbnailWidth, this->thumbnailHeight, 1, this->platform);
803 if (this->platform == PLATFORM_PS3_ORANGEBOX) {
805 const auto reorderedFallbackData = ::convertBetweenDDSAndVTFMipOrderForXBOX<true>(
false, resource.data, this->format, this->mipCount, this->frameCount, this->getFaceCount(), this->width, this->height, this->depth, ok);
806 if (!ok || reorderedFallbackData.size() != resource.data.size()) {
807 this->opened =
false;
810 std::memcpy(resource.data.data(), reorderedFallbackData.data(), resource.data.size());
812 ::swapImageDataEndianForConsole<true>(resource.data, this->format, this->mipCount, this->frameCount, this->getFaceCount(), this->width, this->height, this->depth, this->platform);
814 BufferStream::swap_endian(
reinterpret_cast<uint32_t*
>(resource.data.data()));
822VTF::VTF(std::span<const std::byte> vtfData,
bool parseHeaderOnly)
823 :
VTF(std::vector<std::byte>{vtfData.begin(), vtfData.end()}, parseHeaderOnly) {}
825VTF::VTF(
const std::filesystem::path& vtfPath,
bool parseHeaderOnly)
826 :
VTF(
fs::readFileBuffer(vtfPath), parseHeaderOnly) {}
834 this->data = other.
data;
836 this->width = other.
width;
837 this->height = other.
height;
843 this->format = other.
format;
852 this->depth = other.
depth;
854 this->resources.clear();
855 for (
const auto& [otherType, otherFlags, otherData] : other.
resources) {
856 auto& [
type, flags_, data_] = this->resources.emplace_back();
859 data_ = {this->data.data() + (otherData.data() - other.
data.data()), otherData.size()};
871VTF::operator bool()
const {
878 for (
int i = 0; i < writer.
mipCount; i++) {
881 for (
int l = 0; l < writer.
depth; l++) {
882 if (options.
invertGreenChannel && !writer.
setImage(
ImageConversion::invertGreenChannelForImageData(writer.
getImageDataRaw(i, j, k, l), writer.
getFormat(), writer.
getWidth(i), writer.
getHeight(i)), writer.
getFormat(), writer.
getWidth(i), writer.
getHeight(i),
ImageConversion::ResizeFilter::DEFAULT, i, j, k, l)) {
885 if (options.
gammaCorrection != 1.f && !writer.
setImage(
ImageConversion::gammaCorrectImageData(writer.
getImageDataRaw(i, j, k, l), writer.
getFormat(), writer.
getWidth(i), writer.
getHeight(i), options.
gammaCorrection), writer.
getFormat(), writer.
getWidth(i), writer.
getHeight(i),
ImageConversion::ResizeFilter::DEFAULT, i, j, k, l)) {
936 if (requestedResizeWidth !=
width || requestedResizeHeight !=
height) {
938 if (!writer.
setImage(imageDataResized,
format, requestedResizeWidth, requestedResizeHeight, options.
filter)) {
947 return writer.
bake(vtfPath);
951 std::vector<std::byte> imageData;
954 return create(imageData,
format, requestedResizeWidth, requestedResizeHeight, vtfPath, options);
963 if (requestedResizeWidth !=
width || requestedResizeHeight !=
height) {
965 if (!writer.
setImage(imageDataResized,
format, requestedResizeWidth, requestedResizeHeight, options.
filter)) {
980 std::vector<std::byte> imageData;
983 return create(imageData,
format, requestedResizeWidth, requestedResizeHeight, options);
997 return writer.
bake(vtfPath);
1016 return this->platform;
1020 if (this->platform == newPlatform) {
1025 const auto oldPlatform = this->platform;
1027 switch (newPlatform) {
1031 switch (oldPlatform) {
1058 this->platform = newPlatform;
1062 this->
regenerateImageData(this->format, this->width, this->height, this->mipCount, this->frameCount, 6, this->depth);
1077 this->thumbnailHeight = 0;
1092 if (this->mipCount != maxMipCount) {
1099 return this->version;
1107 const auto faceCount = newVersion < 1 || newVersion > 4 ? 6 : 7;
1108 this->
regenerateImageData(this->format, this->width, this->height, this->mipCount, this->frameCount, faceCount, this->depth);
1112 const bool srgb = this->
isSRGB();
1129 this->version = newVersion;
1171 if (newWidth == 0 || newHeight == 0) {
1181 if (this->width == newWidth && this->height == newHeight) {
1184 auto newMipCount = this->mipCount;
1186 newMipCount = maxMipCount;
1192 this->frameCount = 1;
1194 this->width = newWidth;
1195 this->height = newHeight;
1223 if (this->version >= 5) {
1225 }
else if (this->version == 4) {
1229 if (this->version >= 5) {
1231 }
else if (this->version == 4) {
1265 return this->format;
1276 this->format = newFormat;
1279 const auto oldFormat = this->format;
1281 this->
regenerateImageData(newFormat, this->width +
math::paddingForAlignment(4, this->width), this->height +
math::paddingForAlignment(4, this->height), this->mipCount, this->frameCount, this->
getFaceCount(), this->depth, filter, quality);
1283 this->
regenerateImageData(newFormat, this->width, this->height, this->mipCount, this->frameCount, this->
getFaceCount(), this->depth, filter, quality);
1287 const auto fallbackConverted =
ImageConversion::convertSeveralImageDataToFormat(fallbackResource->data, oldFormat, this->format,
ImageDimensions::getMaximumMipCount(this->fallbackWidth, this->fallbackHeight), this->frameCount, this->getFaceCount(), this->fallbackWidth, this->fallbackHeight, 1, quality);
1293 return this->mipCount;
1302 newMipCount = maxMipCount;
1321 if (this->mipCount <= 1) {
1327 auto* outputDataPtr = imageResource->data.data();
1330#ifdef SOURCEPP_BUILD_WITH_THREADS
1331 std::vector<std::future<void>> futures;
1332 futures.reserve(this->frameCount * faceCount * this->depth);
1334 for (
int j = 0; j < this->frameCount; j++) {
1335 for (
int k = 0; k < faceCount; k++) {
1336#ifdef SOURCEPP_BUILD_WITH_THREADS
1337 futures.push_back(std::async(std::launch::async, [
this, filter, outputDataPtr, faceCount, j, k] {
1339 for (
int i = 1; i < this->mipCount; i++) {
1342 for (
int l = 0; l < mipDepth; l++) {
1343 auto mip =
ImageConversion::resizeImageData(this->
getImageDataRaw(i - 1, j, k, l), this->format, mipWidthM1, mipWidth, mipHeightM1, mipHeight, this->
isSRGB(), filter);
1344 if (uint32_t offset, length;
ImageFormatDetails::getDataPosition(offset, length, this->format, i, this->mipCount, j, this->frameCount, k, faceCount, this->width, this->height, l, this->depth) && mip.size() == length) {
1345 std::memcpy(outputDataPtr + offset, mip.data(), length);
1349#ifdef SOURCEPP_BUILD_WITH_THREADS
1351 if (futures.size() >= std::thread::hardware_concurrency()) {
1352 for (
auto& future : futures) {
1360#ifdef SOURCEPP_BUILD_WITH_THREADS
1361 for (
auto& future : futures) {
1368 return this->frameCount;
1390 if (this->platform !=
PLATFORM_PC || this->version >= 6) {
1396 if (this->version >= 1 && this->version <= 4 && expectedLength < image->
data.size()) {
1399 if (expectedLength == image->data.size()) {
1409 this->
regenerateImageData(this->format, this->width, this->height, this->mipCount, this->frameCount, isCubeMap ? ((this->version >= 1 && this->version <= 4) ? 7 : 6) : 1, this->depth);
1429 this->
regenerateImageData(this->format, this->width, this->height, this->mipCount, newFrameCount, isCubeMap ? ((this->version >= 1 && this->version <= 4) ? 7 : 6) : 1, newDepth);
1450 static constexpr auto getReflectivityForImage = [](
const VTF& vtf, uint16_t frame, uint8_t face, uint16_t slice) {
1451 static constexpr auto getReflectivityForPixel = [](
const ImagePixel::RGBA8888* pixel) -> math::Vec3f {
1453 math::Vec3f ref{
static_cast<float>(pixel->r()),
static_cast<float>(pixel->g()),
static_cast<float>(pixel->b())};
1455 ref = ref / 255.f * 0.922f;
1464 for (uint64_t i = 0; i < rgba8888Data.size(); i += 4) {
1465 out += getReflectivityForPixel(
reinterpret_cast<ImagePixel::RGBA8888*
>(rgba8888Data.data() + i));
1467 return out / (rgba8888Data.size() /
sizeof(ImagePixel::RGBA8888));
1472#ifdef SOURCEPP_BUILD_WITH_THREADS
1473 if (this->frameCount > 1 || faceCount > 1 || this->depth > 1) {
1474 std::vector<std::future<math::Vec3f>> futures;
1475 futures.reserve(this->frameCount * faceCount * this->depth);
1478 for (
int j = 0; j < this->frameCount; j++) {
1479 for (
int k = 0; k < faceCount; k++) {
1480 for (
int l = 0; l < this->depth; l++) {
1481 futures.push_back(std::async(std::launch::async, [
this, j, k, l] {
1482 return getReflectivityForImage(*
this, j, k, l);
1484 if (futures.size() >= std::thread::hardware_concurrency()) {
1485 for (
auto& future : futures) {
1494 for (
auto& future : futures) {
1497 this->
reflectivity /= this->frameCount * faceCount * this->depth;
1499 this->
reflectivity = getReflectivityForImage(*
this, 0, 0, 0);
1503 for (
int j = 0; j < this->frameCount; j++) {
1504 for (
int k = 0; k < faceCount; k++) {
1505 for (
int l = 0; l < this->depth; l++) {
1506 this->
reflectivity += getReflectivityForImage(*
this, j, k, l);
1510 this->
reflectivity /= this->frameCount * faceCount * this->depth;
1531 return this->thumbnailHeight;
1547 return this->resources;
1551 for (
const auto& resource : this->resources) {
1552 if (resource.type ==
type) {
1560 for (
auto& resource : this->resources) {
1561 if (resource.type ==
type) {
1569 if (
const auto* resource = this->
getResource(type); resource && resource->
data.size() == data_.size()) {
1570 std::memcpy(resource->data.data(), data_.data(), data_.size());
1575 std::unordered_map<Resource::Type, std::pair<std::vector<std::byte>, uint64_t>> resourceData;
1576 for (
const auto& [type_, flags_, dataSpan] : this->resources) {
1577 resourceData[type_] = {std::vector<std::byte>{dataSpan.begin(), dataSpan.end()}, 0};
1581 if (data_.empty()) {
1582 resourceData.erase(
type);
1584 resourceData[
type] = {{data_.begin(), data_.end()}, 0};
1589 BufferStream writer{this->data};
1591 for (
auto resourceType : resourceData | std::views::keys) {
1592 if (!resourceData.contains(resourceType)) {
1595 auto& [specificResourceData, offset] = resourceData[resourceType];
1596 if (resourceType ==
type) {
1600 {this->data.data() + offset, specificResourceData.size()},
1603 *resourcePtr = newResource;
1605 this->resources.push_back(newResource);
1607 }
else if (!resourceData.contains(resourceType)) {
1610 offset = writer.tell();
1611 writer.write(specificResourceData);
1613 this->data.resize(writer.size());
1615 for (
auto& [type_, flags_, dataSpan] : this->resources) {
1616 if (resourceData.contains(type_)) {
1617 const auto& [specificResourceData, offset] = resourceData[type_];
1618 dataSpan = {this->data.data() + offset, specificResourceData.size()};
1624 std::erase_if(this->resources, [
type](
const Resource& resource) {
return resource.
type ==
type; });
1628 if (!newWidth) newWidth = 1;
1629 if (!newHeight) newHeight = 1;
1630 if (!newMipCount) newMipCount = 1;
1631 if (!newFrameCount) newFrameCount = 1;
1632 if (!newFaceCount) newFaceCount = 1;
1633 if (!newDepth) newDepth = 1;
1635 if (newMipCount > 1) {
1638 if (
ImageFormatDetails::compressed(newFormat) && ((newWidth > 4 && !std::has_single_bit(newWidth)) || (newHeight > 4 && !std::has_single_bit(newHeight)))) {
1648 if (this->format == newFormat && this->width == newWidth && this->height == newHeight && this->mipCount == newMipCount && this->frameCount == newFrameCount && faceCount == newFaceCount && this->depth == newDepth) {
1652 std::vector<std::byte> newImageData;
1654 if (this->format != newFormat && this->width == newWidth && this->height == newHeight && this->mipCount == newMipCount && this->frameCount == newFrameCount && faceCount == newFaceCount && this->depth == newDepth) {
1658 for (
int i = newMipCount - 1; i >= 0; i--) {
1661 int sourceMipIndex = 0;
1662 for (
int mip = 0, bestScore = std::numeric_limits<int>::max(); mip < this->mipCount; mip++) {
1664 if (mipWidth == newMipWidth && mipHeight == newMipHeight) {
1667 const auto widthDiff =
static_cast<int>(mipWidth) -
static_cast<int>(newMipWidth);
1668 const auto heightDiff =
static_cast<int>(mipHeight) -
static_cast<int>(newMipHeight);
1669 if (widthDiff < 0 || heightDiff < 0) {
1672 if (
const auto score = widthDiff + heightDiff; score < bestScore) {
1674 sourceMipIndex = mip;
1679 for (
int j = 0; j < newFrameCount; j++) {
1680 for (
int k = 0; k < newFaceCount; k++) {
1681 for (
int l = 0; l < newMipDepth; l++) {
1684 std::vector<std::byte> imageBacking;
1685 if (sourceMipWidth != newMipWidth || sourceMipHeight != newMipHeight) {
1687 imageSpan = imageBacking;
1689 if (uint32_t offset, length;
ImageFormatDetails::getDataPosition(offset, length, this->format, i, newMipCount, j, newFrameCount, k, newFaceCount, newWidth, newHeight, l, newDepth) && imageSpan.size() == length) {
1690 std::memcpy(newImageData.data() + offset, imageSpan.data(), length);
1697 if (this->format != newFormat) {
1705 this->format = newFormat;
1706 this->width = newWidth;
1707 this->height = newHeight;
1708 this->mipCount = newMipCount;
1709 this->frameCount = newFrameCount;
1710 if (newFaceCount > 1) {
1715 this->depth = newDepth;
1721 const auto targetSize = 256 *
sizeof(ImagePixel::BGRA8888) * this->frameCount;
1722 if (palette->data.size() != targetSize) {
1723 std::vector<std::byte> paletteData{palette->data.begin(), palette->data.end()};
1724 paletteData.resize(targetSize);
1736 return palette->getDataAsPalette(frame);
1741std::vector<std::byte>
VTF::getParticleSheetFrameDataRaw(uint16_t& spriteWidth, uint16_t& spriteHeight, uint32_t shtSequenceID, uint32_t shtFrame, uint8_t shtBounds, uint8_t mip, uint16_t frame, uint8_t face, uint16_t slice)
const {
1750 auto sht = shtResource->getDataAsParticleSheet();
1751 const auto* sequence = sht.getSequenceFromID(shtSequenceID);
1752 if (!sequence || sequence->frames.size() <= shtFrame || shtBounds >= sht.getFrameBoundsCount()) {
1760 const auto& bounds = sequence->frames[shtFrame].bounds[shtBounds];
1761 uint16_t x1 = std::clamp<uint16_t>(std::floor(bounds.x1 *
static_cast<float>(this->getWidth(mip))), 0, this->getWidth(mip));
1762 uint16_t y1 = std::clamp<uint16_t>(std::ceil( bounds.y1 *
static_cast<float>(this->getHeight(mip))), 0, this->getHeight(mip));
1763 uint16_t x2 = std::clamp<uint16_t>(std::ceil( bounds.x2 *
static_cast<float>(this->getWidth(mip))), 0, this->getHeight(mip));
1764 uint16_t y2 = std::clamp<uint16_t>(std::floor(bounds.y2 *
static_cast<float>(this->getHeight(mip))), 0, this->getWidth(mip));
1766 if (x1 > x2) [[unlikely]] {
1769 if (y1 > y2) [[unlikely]] {
1772 spriteWidth = x2 - x1;
1773 spriteWidth = y2 - y1;
1775 const auto out =
ImageConversion::cropImageData(this->
getImageDataRaw(mip, frame, face, slice), this->
getFormat(), this->
getWidth(mip), spriteWidth, x1, this->
getHeight(mip), spriteHeight, y1);
1783std::vector<std::byte>
VTF::getParticleSheetFrameDataAs(
ImageFormat newFormat, uint16_t& spriteWidth, uint16_t& spriteHeight, uint32_t shtSequenceID, uint32_t shtFrame, uint8_t shtBounds, uint8_t mip, uint16_t frame, uint8_t face, uint16_t slice)
const {
1784 return ImageConversion::convertImageDataToFormat(this->
getParticleSheetFrameDataRaw(spriteWidth, spriteHeight, shtSequenceID, shtFrame, shtBounds, mip, frame, face, slice), this->
getFormat(), newFormat, spriteWidth, spriteHeight);
1787std::vector<std::byte>
VTF::getParticleSheetFrameDataAsRGBA8888(uint16_t& spriteWidth, uint16_t& spriteHeight, uint32_t shtSequenceID, uint32_t shtFrame, uint8_t shtBounds, uint8_t mip, uint16_t frame, uint8_t face, uint16_t slice)
const {
1792 std::vector<std::byte> particleSheetData;
1793 BufferStream writer{particleSheetData};
1795 const auto bakedSheet = value.
bake();
1796 writer.write<uint32_t>(bakedSheet.size()).write(bakedSheet);
1797 particleSheetData.resize(writer.size());
1816 BufferStream writer{&lodData,
sizeof(lodData)};
1818 writer << u << v << u360 << v360;
1836 std::vector<std::byte> keyValuesData;
1837 BufferStream writer{keyValuesData};
1839 writer.write<uint32_t>(value.size()).write(value,
false);
1840 keyValuesData.resize(writer.size());
1850 std::vector<std::byte> hotspotData;
1851 BufferStream writer{hotspotData};
1853 const auto bakedHotspotData = value.
bake();
1854 writer.write<uint32_t>(bakedHotspotData.size()).write(bakedHotspotData);
1855 hotspotData.resize(writer.size());
1892 if (uint32_t offset, length;
ImageFormatDetails::getDataPosition(offset, length, this->format, mip, this->mipCount, frame, this->frameCount, face, this->
getFaceCount(), this->width, this->height, slice, this->depth)) {
1893 return imageResource->data.subspan(offset, length);
1900 const auto rawImageData = this->
getImageDataRaw(mip, frame, face, slice);
1901 if (rawImageData.empty()) {
1919 if (imageData_.empty()) {
1924 uint16_t resizedWidth = width_, resizedHeight = height_;
1931 mip = newMipCount - 1;
1936 this->
regenerateImageData(format_, resizedWidth, resizedHeight, mip + 1, frame + 1, face ? (face < 6 ? 6 : face) : 0, slice + 1);
1945 if (!imageResource) {
1948 if (uint32_t offset, length;
ImageFormatDetails::getDataPosition(offset, length, this->format, mip, this->mipCount, frame, this->frameCount, face, faceCount, this->width, this->height, slice, this->depth)) {
1949 std::vector<std::byte> image{imageData_.begin(), imageData_.end()};
1951 if (width_ != newWidth || height_ != newHeight) {
1954 if (format_ != this->format) {
1957 std::memcpy(imageResource->data.data() + offset, image.data(), image.size());
1964 int inputWidth, inputHeight, inputFrameCount;
1968 if (imageData_.empty() || inputFormat ==
ImageFormat::EMPTY || !inputWidth || !inputHeight || !inputFrameCount) {
1973 auto [requestedResizeWidth, requestedResizeHeight] = resizeBounds.
clamp(inputWidth, inputHeight);
1976 if (inputFrameCount == 1) {
1977 if (requestedResizeWidth != inputWidth || requestedResizeHeight != inputHeight) {
1979 return this->
setImage(imageDataResized, inputFormat, requestedResizeWidth, requestedResizeHeight, filter, mip, frame, face, slice, quality);
1981 return this->
setImage(imageData_, inputFormat, inputWidth, inputHeight, filter, mip, frame, face, slice, quality);
1985 bool allSuccess =
true;
1987 for (
int currentFrame = 0; currentFrame < inputFrameCount; currentFrame++) {
1988 std::span currentFrameData{imageData_.data() + currentFrame * frameSize, imageData_.data() + currentFrame * frameSize + frameSize};
1989 if (requestedResizeWidth != inputWidth || requestedResizeHeight != inputHeight) {
1991 if (!this->
setImage(currentFrameResized, inputFormat, requestedResizeWidth, requestedResizeHeight, filter, mip, frame + currentFrame, face, slice, quality)) {
1994 }
else if (!this->
setImage(currentFrameData, inputFormat, inputWidth, inputHeight, filter, mip, frame + currentFrame, face, slice, quality)) {
1997 if (currentFrame == 0 && this->frameCount < frame + inputFrameCount) {
2010 if (
auto data_ = this->
saveImageToFile(mip, frame, face, slice, fileFormat); !data_.empty()) {
2022 return thumbnailResource->data;
2029 if (rawThumbnailData.empty()) {
2046 this->thumbnailHeight = height_;
2051 int inputWidth, inputHeight, inputFrameCount;
2055 if (imageData_.empty() || inputFormat ==
ImageFormat::EMPTY || !inputWidth || !inputHeight || !inputFrameCount) {
2060 if (inputFrameCount == 1) {
2061 this->
setThumbnail(imageData_, inputFormat, inputWidth, inputHeight, quality);
2067 this->
setThumbnail({imageData_.data(), frameSize}, inputFormat, inputWidth, inputHeight, quality);
2079 this->thumbnailHeight = 1;
2080 std::array newThumbnail{
2081 static_cast<std::byte
>(
static_cast<uint8_t
>(std::clamp(this->
reflectivity[0], 0.f, 1.f) * 255.f)),
2082 static_cast<std::byte
>(
static_cast<uint8_t
>(std::clamp(this->
reflectivity[1], 0.f, 1.f) * 255.f)),
2083 static_cast<std::byte
>(
static_cast<uint8_t
>(std::clamp(this->
reflectivity[2], 0.f, 1.f) * 255.f)),
2089 this->thumbnailHeight = 16;
2090 this->
setResourceInternal(
Resource::TYPE_THUMBNAIL_DATA,
ImageConversion::convertImageDataToFormat(
ImageConversion::resizeImageData(this->
getImageDataRaw(), this->format, this->width, this->
thumbnailWidth, this->height, this->thumbnailHeight, this->
isSRGB(), filter), this->format, this->
thumbnailFormat, this->
thumbnailWidth, this->thumbnailHeight, quality));
2097 this->thumbnailHeight = 0;
2118 if (uint32_t offset, length;
ImageFormatDetails::getDataPosition(offset, length, this->format, mip, this->
fallbackMipCount, frame, this->frameCount, face, this->
getFaceCount(), this->
fallbackWidth, this->
fallbackHeight)) {
2119 return fallbackResource->data.subspan(offset, length);
2127 if (rawFallbackData.empty()) {
2153 std::vector<std::byte> fallbackData;
2157 for (
int j = 0; j < this->frameCount; j++) {
2158 for (
int k = 0; k < faceCount; k++) {
2159 auto mip =
ImageConversion::resizeImageData(this->
getImageDataRaw(0, j, k, 0), this->format, this->width, mipWidth, this->height, mipHeight, this->
isSRGB(), filter);
2160 if (uint32_t offset, length;
ImageFormatDetails::getDataPosition(offset, length, this->format, i, this->
fallbackMipCount, j, this->frameCount, k, faceCount, this->
fallbackWidth, this->
fallbackHeight) && mip.size() == length) {
2161 std::memcpy(fallbackData.data() + offset, mip.data(), length);
2182 if (
auto data_ = this->
saveFallbackToFile(mip, frame, face, fileFormat); !data_.empty()) {
2203 uint64_t vtfSize = 0;
2205 switch (this->platform) {
2209 switch (this->version) {
2212 vtfSize +=
sizeof(uint64_t);
2213 vtfSize +=
sizeof(uint32_t) * (2 + this->mipCount * this->frameCount * this->
getFaceCount());
2218 vtfSize += 11 +
sizeof(uint32_t) +
sizeof(uint64_t) * this->
getResources().size();
2219 for (
const auto& [resourceType, resourceFlags, resourceData] : this->
getResources()) {
2221 vtfSize += resourceData.size();
2225 vtfSize +=
sizeof(uint16_t);
2228 vtfSize +=
sizeof(uint32_t) * 9 +
sizeof(
float) * 4 +
sizeof(uint16_t) * 4 +
sizeof(uint8_t) * 3;
2229 if (this->version < 3) {
2234 vtfSize += thumbnailResource->data.size();
2238 vtfSize += imageResource->data.size();
2241 vtfSize +=
static_cast<uint64_t
>(
static_cast<double>(imageResource->data.size()) / 1.75);
2250 vtfSize +=
sizeof(uint32_t) * 6 +
sizeof(
float) * 4 +
sizeof(uint16_t) * 6 +
sizeof(uint8_t) * 6;
2253 vtfSize += thumbnailResource->data.size();
2257 vtfSize += paletteResource->data.size();
2267 if (vtfSize > 512) {
2272 vtfSize +=
sizeof(uint32_t);
2275 vtfSize +=
sizeof(uint32_t) * 7 +
sizeof(
float) * 4 +
sizeof(uint16_t) * 5 +
sizeof(uint8_t) * 6;
2276 vtfSize +=
sizeof(uint64_t) * this->
getResources().size();
2278 for (
const auto& [resourceType, resourceFlags, resourceData] : this->
getResources()) {
2280 vtfSize += resourceData.size();
2285 vtfSize += imageResource->data.size();
2288 vtfSize +=
static_cast<uint64_t
>(
static_cast<double>(imageResource->data.size()) / 1.75);
2297 std::vector<std::byte> out;
2298 BufferStream writer{out};
2300 const auto writeResources = [&writer](uint64_t headerLengthPos,
const std::vector<Resource>& sortedResources) -> uint64_t {
2301 auto resourceHeaderCurPos = writer.tell();
2302 writer.pad<uint64_t>(sortedResources.size());
2303 auto resourceDataCurPos = writer.tell();
2304 writer.seek_u(headerLengthPos).write<uint32_t>(resourceDataCurPos);
2306 uint64_t resourceHeaderImagePos = 0;
2307 for (
const auto& resource : sortedResources) {
2308 writer.seek_u(resourceHeaderCurPos);
2310 uint32_t resourceType = resource.type;
2314 if (writer.is_big_endian()) {
2316 BufferStream::swap_endian(&resourceType);
2318 writer.write<uint32_t>(resourceType);
2321 resourceHeaderImagePos = writer.tell();
2322 writer.write<uint32_t>(0);
2323 resourceHeaderCurPos = writer.tell();
2328 writer.write(resource.data);
2329 resourceHeaderCurPos = writer.tell();
2331 writer.write<uint32_t>(resourceDataCurPos);
2332 resourceHeaderCurPos = writer.tell();
2333 writer.seek_u(resourceDataCurPos).write(resource.data);
2334 resourceDataCurPos = writer.tell();
2337 if (resourceHeaderImagePos) {
2338 writer.seek_u(resourceHeaderImagePos).write<uint32_t>(resourceDataCurPos);
2339 for (
auto& resource : sortedResources) {
2341 writer.seek_u(resourceDataCurPos).write(resource.data);
2345 return resourceDataCurPos;
2351 auto bakeFormat = this->format;
2352 auto bakeFlags = this->
flags;
2359 bakeFormat =
static_cast<ImageFormat>(
static_cast<int32_t
>(this->format) + 3);
2362 switch (this->platform) {
2369 .write(this->version);
2371 const auto headerLengthPos = writer.tell();
2372 writer.write<uint32_t>(0);
2376 .write(this->height)
2378 .write(this->frameCount)
2387 .write(this->mipCount)
2390 .write(this->thumbnailHeight);
2392 if (this->version >= 2) {
2393 writer << this->depth;
2396 if (this->version < 3) {
2398 const auto headerSize = writer.tell();
2399 writer.seek_u(headerLengthPos).write<uint32_t>(headerSize).seek_u(headerSize);
2402 writer.write(thumbnailResource->data);
2405 writer.write(imageResource->data);
2408 std::vector<std::byte> auxCompressionResourceData;
2409 std::vector<std::byte> compressedImageResourceData;
2410 bool hasAuxCompression =
false;
2413 if (hasAuxCompression) {
2415 auxCompressionResourceData.resize((this->mipCount * this->frameCount * faceCount + 2) *
sizeof(uint32_t));
2416 BufferStream auxWriter{auxCompressionResourceData,
false};
2423 .write<uint32_t>(auxCompressionResourceData.size() -
sizeof(uint32_t))
2427 for (
int i = this->mipCount - 1; i >= 0; i--) {
2428 for (
int j = 0; j < this->frameCount; j++) {
2429 for (
int k = 0; k < faceCount; k++) {
2430 if (uint32_t offset, length;
ImageFormatDetails::getDataPosition(offset, length, this->format, i, this->mipCount, j, this->frameCount, k, faceCount, this->width, this->height, 0, this->depth)) {
2432 compressedImageResourceData.insert(compressedImageResourceData.end(), compressedData.begin(), compressedData.end());
2433 auxWriter.write<uint32_t>(compressedData.size());
2441 writer.pad(3).write<uint32_t>(this->
getResources().size() + hasAuxCompression).pad(8);
2443 std::vector<Resource> sortedResources = this->
getResources();
2444 if (hasAuxCompression) {
2445 for (
auto& resource : sortedResources) {
2447 resource.data = compressedImageResourceData;
2451 sortedResources.push_back({
2454 .data = auxCompressionResourceData,
2457 std::ranges::sort(sortedResources, [](
const Resource& lhs,
const Resource& rhs) {
2460 writeResources(headerLengthPos, sortedResources);
2466 writer.write<uint32_t>(0);
2468 const auto headerSizePos = writer.tell();
2473 .write(this->height)
2475 .write(this->frameCount);
2476 const auto preloadSizePos = writer.tell();
2477 writer.write<uint16_t>(0);
2478 const auto imageOffsetPos = writer.tell();
2485 .write(this->format)
2487 .write(this->thumbnailHeight)
2493 const auto headerSize = writer.tell();
2494 writer.seek_u(headerSizePos).write<uint32_t>(headerSize).seek_u(headerSize);
2497 writer.write(thumbnailResource->data);
2502 writer.write(paletteResource->data);
2506 bool hasFallbackResource =
false;
2508 hasFallbackResource =
true;
2509 std::vector<std::byte> reorderedFallbackData{fallbackResource->data.begin(), fallbackResource->data.end()};
2514 writer.write(reorderedFallbackData);
2520 const auto preloadSize = writer.tell();
2521 writer.seek_u(preloadSizePos).write<uint32_t>(preloadSize).seek_u(preloadSize);
2523 if (hasFallbackResource) {
2526 const auto imageOffset = writer.tell();
2527 writer.seek_u(imageOffsetPos).write<uint16_t>(imageOffset).seek_u(imageOffset);
2530 std::vector<std::byte> reorderedImageData{imageResource->data.begin(), imageResource->data.end()};
2531 ::swapImageDataEndianForConsole<false>(reorderedImageData, this->format, this->mipCount, this->frameCount, this->
getFaceCount(), this->width, this->height, this->depth, this->platform);
2533 reorderedImageData = ::convertBetweenDDSAndVTFMipOrderForXBOX<false>(
true, reorderedImageData, this->format, this->mipCount, this->frameCount, this->
getFaceCount(), this->width, this->height, this->depth, ok);
2535 writer.write(reorderedImageData);
2540 if (writer.tell() > 512) {
2550 writer.set_big_endian(
true);
2554 writer.set_big_endian(
true);
2555 writer << this->platform;
2557 writer.write<uint32_t>(8);
2559 const auto headerLengthPos = writer.tell();
2564 .write(this->height)
2566 .write(this->frameCount);
2567 const auto preloadPos = writer.tell();
2571 .write<uint8_t>(this->resources.size())
2577 .write<uint8_t>(std::clamp(
static_cast<int>(std::roundf(this->
reflectivity[0] * 255)), 0, 255))
2578 .write<uint8_t>(std::clamp(
static_cast<int>(std::roundf(this->
reflectivity[1] * 255)), 0, 255))
2579 .write<uint8_t>(std::clamp(
static_cast<int>(std::roundf(this->
reflectivity[2] * 255)), 0, 255))
2580 .write<uint8_t>(255);
2581 const auto compressionPos = writer.tell();
2582 writer.write<uint32_t>(0);
2586 writer.write<uint32_t>(0);
2589 std::vector<std::byte> thumbnailResourceData;
2590 std::vector<std::byte> imageResourceData;
2591 std::vector<Resource> sortedResources = this->
getResources();
2592 for (
auto& resource : sortedResources) {
2594 thumbnailResourceData = {resource.data.begin(), resource.data.end()};
2595 ::swapImageDataEndianForConsole<false>(thumbnailResourceData, this->
thumbnailFormat, 1, 1, 1, this->
thumbnailWidth, this->thumbnailHeight, 1, this->platform);
2596 resource.data = thumbnailResourceData;
2600 imageResourceData = ::convertBetweenDDSAndVTFMipOrderForXBOX<false>(
false, resource.data, this->format, this->mipCount, this->frameCount, this->getFaceCount(), this->width, this->height, this->depth, ok);
2601 if (!ok || imageResourceData.size() != resource.data.size()) {
2605 imageResourceData = {resource.data.begin(), resource.data.end()};
2607 ::swapImageDataEndianForConsole<false>(imageResourceData, this->format, this->mipCount, this->frameCount, this->
getFaceCount(), this->width, this->height, this->depth, this->platform);
2617 fixedCompressionLevel = 6;
2620 imageResourceData = std::move(*compressedData);
2621 const auto curPos = writer.tell();
2622 writer.seek_u(compressionPos).write<uint32_t>(imageResourceData.size()).seek_u(curPos);
2626 resource.data = imageResourceData;
2630 std::ranges::sort(sortedResources, [](
const Resource& lhs,
const Resource& rhs) {
2633 const auto resourceDataImagePos = writeResources(headerLengthPos, sortedResources);
2634 writer.seek_u(preloadPos).write(std::max<uint16_t>(resourceDataImagePos, 2048));
2638 out.resize(writer.size());
#define SOURCEPP_DEBUG_BREAK
Create a breakpoint in debug.
std::vector< std::byte > bake() const
std::vector< std::byte > bake() const
void setImageHeightResizeMethod(ImageConversion::ResizeMethod imageHeightResizeMethod_)
bool setFrameFaceAndDepth(uint16_t newFrameCount, bool isCubeMap, uint16_t newDepth=1)
void removeKeyValuesDataResource()
void computeFallback(ImageConversion::ResizeFilter filter=ImageConversion::ResizeFilter::DEFAULT)
uint8_t getFallbackHeight() const
CompressionMethod compressionMethod
void computeReflectivity()
uint8_t getThumbnailWidth() const
std::vector< std::byte > saveThumbnailToFile(ImageConversion::FileFormat fileFormat=ImageConversion::FileFormat::DEFAULT) const
ImageFormat getFormat() const
void setPlatform(Platform newPlatform)
uint16_t getHeight(uint8_t mip=0) const
VTF & operator=(const VTF &other)
uint8_t getFallbackWidth() const
sourcepp::math::Vec3f reflectivity
uint16_t getWidth(uint8_t mip=0) const
void setThumbnail(std::span< const std::byte > imageData_, ImageFormat format_, uint16_t width_, uint16_t height_, float quality=ImageConversion::DEFAULT_COMPRESSED_QUALITY)
bool setRecommendedMipCount()
static bool createInternal(VTF &writer, CreationOptions options)
std::vector< std::byte > getParticleSheetFrameDataAsRGBA8888(uint16_t &spriteWidth, uint16_t &spriteHeight, uint32_t shtSequenceID, uint32_t shtFrame, uint8_t shtBounds=0, uint8_t mip=0, uint16_t frame=0, uint8_t face=0, uint16_t slice=0) const
This is a convenience function. You're best off uploading the bounds to the GPU and scaling the UV th...
void regenerateImageData(ImageFormat newFormat, uint16_t newWidth, uint16_t newHeight, uint8_t newMipCount, uint16_t newFrameCount, uint8_t newFaceCount, uint16_t newDepth, ImageConversion::ResizeFilter filter=ImageConversion::ResizeFilter::DEFAULT, float quality=ImageConversion::DEFAULT_COMPRESSED_QUALITY)
bool hasFallbackData() const
void computeMips(ImageConversion::ResizeFilter filter=ImageConversion::ResizeFilter::DEFAULT)
void setImageWidthResizeMethod(ImageConversion::ResizeMethod imageWidthResizeMethod_)
void setCompressionLevel(int16_t newCompressionLevel)
ImageConversion::ResizeMethod imageHeightResizeMethod
void setFormat(ImageFormat newFormat, ImageConversion::ResizeFilter filter=ImageConversion::ResizeFilter::DEFAULT, float quality=ImageConversion::DEFAULT_COMPRESSED_QUALITY)
void setImageResizeMethods(ImageConversion::ResizeMethod imageWidthResizeMethod_, ImageConversion::ResizeMethod imageHeightResizeMethod_)
std::vector< std::byte > getParticleSheetFrameDataAs(ImageFormat newFormat, uint16_t &spriteWidth, uint16_t &spriteHeight, uint32_t shtSequenceID, uint32_t shtFrame, uint8_t shtBounds=0, uint8_t mip=0, uint16_t frame=0, uint8_t face=0, uint16_t slice=0) const
This is a convenience function. You're best off uploading the bounds to the GPU and scaling the UV th...
float getBumpMapScale() const
void setKeyValuesDataResource(std::string_view value)
void computeTransparencyFlags()
std::vector< std::byte > saveFallbackToFile(uint8_t mip=0, uint16_t frame=0, uint8_t face=0, ImageConversion::FileFormat fileFormat=ImageConversion::FileFormat::DEFAULT) const
std::vector< std::byte > data
Platform getPlatform() const
std::vector< std::byte > getPaletteResourceFrame(uint16_t frame=0) const
void addFlags(uint32_t flags_)
uint8_t getFaceCount() const
ImageFormat thumbnailFormat
void setFlags(uint32_t flags_)
void setSize(uint16_t newWidth, uint16_t newHeight, ImageConversion::ResizeFilter filter)
ImageConversion::ResizeMethod getImageHeightResizeMethod() const
void setBumpMapScale(float newBumpMapScale)
ImageFormat getThumbnailFormat() const
uint16_t getStartFrame() const
static constexpr auto FORMAT_DEFAULT
This value is only valid when passed to VTF::create through CreationOptions or VTF::setFormat.
bool hasThumbnailData() const
void setReflectivity(sourcepp::math::Vec3f newReflectivity)
const std::vector< Resource > & getResources() const
void removeHotspotDataResource()
void setVersion(uint32_t newVersion)
std::vector< std::byte > saveImageToFile(uint8_t mip=0, uint16_t frame=0, uint8_t face=0, uint16_t slice=0, ImageConversion::FileFormat fileFormat=ImageConversion::FileFormat::DEFAULT) const
Resource * getResourceInternal(Resource::Type type)
void computeThumbnail(ImageConversion::ResizeFilter filter=ImageConversion::ResizeFilter::DEFAULT, float quality=ImageConversion::DEFAULT_COMPRESSED_QUALITY)
std::vector< std::byte > bake() const
bool hasImageData() const
ImageConversion::ResizeMethod imageWidthResizeMethod
std::span< const std::byte > getFallbackDataRaw(uint8_t mip=0, uint16_t frame=0, uint8_t face=0) const
void removeParticleSheetResource()
std::vector< std::byte > getFallbackDataAs(ImageFormat newFormat, uint8_t mip=0, uint16_t frame=0, uint8_t face=0) const
static bool create(std::span< const std::byte > imageData, ImageFormat format, uint16_t width, uint16_t height, const std::filesystem::path &vtfPath, const CreationOptions &options)
std::vector< std::byte > getImageDataAsRGBA8888(uint8_t mip=0, uint16_t frame=0, uint8_t face=0, uint16_t slice=0) const
uint16_t getFrameCount() const
uint8_t getMipCount() const
void setLODResource(uint8_t u, uint8_t v, uint8_t u360=0, uint8_t v360=0)
void removeResourceInternal(Resource::Type type)
std::vector< std::byte > getFallbackDataAsRGBA8888(uint8_t mip=0, uint16_t frame=0, uint8_t face=0) const
bool setFrameCount(uint16_t newFrameCount)
ImageConversion::ResizeMethod getImageWidthResizeMethod() const
std::vector< std::byte > getImageDataAs(ImageFormat newFormat, uint8_t mip=0, uint16_t frame=0, uint8_t face=0, uint16_t slice=0) const
static ImageFormat getDefaultCompressedFormat(ImageFormat inputFormat, uint32_t version, bool isCubeMap)
void setStartFrame(uint16_t newStartFrame)
std::vector< std::byte > getThumbnailDataAs(ImageFormat newFormat) const
std::span< const std::byte > getImageDataRaw(uint8_t mip=0, uint16_t frame=0, uint8_t face=0, uint16_t slice=0) const
sourcepp::math::Vec3f getReflectivity() const
uint8_t getFallbackMipCount() const
std::vector< std::byte > getThumbnailDataAsRGBA8888() const
uint8_t getConsoleMipScale() const
uint16_t getDepth(uint8_t mip=0) const
uint16_t getPaddedHeight(uint8_t mip=0) const
static constexpr auto FORMAT_UNCHANGED
This value is only valid when passed to VTF::create through CreationOptions.
std::span< const std::byte > getThumbnailDataRaw() const
bool setMipCount(uint8_t newMipCount)
void setExtendedFlagsResource(uint32_t value)
CompressionMethod getCompressionMethod() const
uint16_t getPaddedWidth(uint8_t mip=0) const
void setCRCResource(uint32_t value)
void setCompressionMethod(CompressionMethod newCompressionMethod)
bool setFaceCount(bool isCubeMap)
uint8_t getThumbnailHeight() const
void setConsoleMipScale(uint8_t consoleMipScale_)
const Resource * getResource(Resource::Type type) const
uint32_t getFlags() const
void setParticleSheetResource(const SHT &value)
@ FLAG_V0_MULTI_BIT_ALPHA
uint32_t getVersion() const
int16_t getCompressionLevel() const
void setHotspotDataResource(const HOT &value)
void removeFlags(uint32_t flags_)
void setResourceInternal(Resource::Type type, std::span< const std::byte > data_)
bool setDepth(uint16_t newDepth)
uint64_t estimateBakeSize() const
std::vector< Resource > resources
bool setImage(std::span< const std::byte > imageData_, ImageFormat format_, uint16_t width_, uint16_t height_, ImageConversion::ResizeFilter filter=ImageConversion::ResizeFilter::DEFAULT, uint8_t mip=0, uint16_t frame=0, uint8_t face=0, uint16_t slice=0, float quality=ImageConversion::DEFAULT_COMPRESSED_QUALITY)
std::vector< std::byte > getParticleSheetFrameDataRaw(uint16_t &spriteWidth, uint16_t &spriteHeight, uint32_t shtSequenceID, uint32_t shtFrame, uint8_t shtBounds=0, uint8_t mip=0, uint16_t frame=0, uint8_t face=0, uint16_t slice=0) const
This is a convenience function. You're best off uploading the bounds to the GPU and scaling the UV th...
void removeExtendedFlagsResource()
std::optional< std::vector< std::byte > > compressValveLZMA(std::span< const std::byte > data, uint8_t compressLevel=6)
constexpr auto VALVE_LZMA_SIGNATURE
std::optional< std::vector< std::byte > > decompressValveLZMA(std::span< const std::byte > data)
bool writeFileBuffer(const std::filesystem::path &filepath, std::span< const std::byte > buffer)
std::vector< std::byte > readFileBuffer(const std::filesystem::path &filepath, std::size_t startOffset=0)
constexpr uint16_t paddingForAlignment(uint16_t alignment, uint64_t n)
constexpr uint32_t log2ceil(uint32_t value)
std::vector< std::byte > convertFileToImageData(std::span< const std::byte > fileData, ImageFormat &format, int &width, int &height, int &frameCount)
std::vector< std::byte > convertImageDataToFile(std::span< const std::byte > imageData, ImageFormat format, uint16_t width, uint16_t height, FileFormat fileFormat=FileFormat::DEFAULT)
Converts image data to the given file format (PNG or EXR by default).
void setResizedDims(uint16_t &width, ResizeMethod widthResize, uint16_t &height, ResizeMethod heightResize)
Set the new image dimensions given a resize method.
std::vector< std::byte > convertImageDataToFormat(std::span< const std::byte > imageData, ImageFormat oldFormat, ImageFormat newFormat, uint16_t width, uint16_t height, float quality=DEFAULT_COMPRESSED_QUALITY)
Converts an image from one format to another.
std::vector< std::byte > convertSeveralImageDataToFormat(std::span< const std::byte > imageData, ImageFormat oldFormat, ImageFormat newFormat, uint8_t mipCount, uint16_t frameCount, uint8_t faceCount, uint16_t width, uint16_t height, uint16_t depth, float quality=DEFAULT_COMPRESSED_QUALITY)
Converts several images from one format to another.
std::vector< std::byte > gammaCorrectImageData(std::span< const std::byte > imageData, ImageFormat format, uint16_t width, uint16_t height, float gamma)
Perform gamma correction on the given image data. Will not perform gamma correction if the input imag...
std::vector< std::byte > cropImageData(std::span< const std::byte > imageData, ImageFormat format, uint16_t width, uint16_t newWidth, uint16_t xOffset, uint16_t height, uint16_t newHeight, uint16_t yOffset)
Crops the given image to the new dimensions. If the image format is compressed it will be converted t...
std::vector< std::byte > invertGreenChannelForImageData(std::span< const std::byte > imageData, ImageFormat format, uint16_t width, uint16_t height)
Invert the green channel. Meant for converting normal maps between OpenGL and DirectX formats.
std::vector< std::byte > resizeImageData(std::span< const std::byte > imageData, ImageFormat format, uint16_t width, uint16_t newWidth, uint16_t height, uint16_t newHeight, bool srgb, ResizeFilter filter, ResizeEdge edge=ResizeEdge::CLAMP)
Resize given image data to the new dimensions.
constexpr uint8_t getMaximumMipCount(uint16_t width, uint16_t height, uint16_t depth=1)
Calculate the largest mip count a texture with the given width, height, and depth can contain.
constexpr std::pair< uint16_t, uint16_t > getMipDims(uint8_t mip, uint16_t width, uint16_t height, bool addCompressedFormatPadding=false)
Get the width and height at a given mip level.
constexpr uint16_t getMipDim(uint8_t mip, uint16_t dim, bool addCompressedFormatPadding=false)
Get the dimension at a given mip level.
std::vector< std::byte > convertP8ImageDataToBGRA8888(std::span< const std::byte > paletteData, std::span< const std::byte > imageData)
Converts a paletted image to something usable.
constexpr uint32_t VTF_SIGNATURE
constexpr uint32_t XTF_SIGNATURE
constexpr uint32_t VTFX_SIGNATURE
constexpr uint32_t VTF3_SIGNATURE
std::pair< uint16_t, uint16_t > clamp(uint16_t width, uint16_t height) const
HOT getDataAsHotspotData() const
std::tuple< uint8_t, uint8_t, uint8_t, uint8_t > getDataAsLODControlInfo() const
ConvertedData convertData() const
std::string getDataAsKeyValuesData() const
int16_t getDataAsAuxCompressionLevel() const
CompressionMethod getDataAsAuxCompressionMethod() const
SHT getDataAsParticleSheet() const
std::variant< std::monostate, SHT, uint32_t, std::tuple< uint8_t, uint8_t, uint8_t, uint8_t >, std::string, HOT > ConvertedData
uint32_t getDataAsExtendedFlags() const
uint32_t getDataAsCRC() const
uint32_t getDataAsAuxCompressionLength(uint8_t mip, uint8_t mipCount, uint16_t frame, uint16_t frameCount, uint16_t face, uint16_t faceCount) const
@ TYPE_PARTICLE_SHEET_DATA
std::vector< std::byte > getDataAsPalette(uint16_t frame) const
std::span< std::byte > data
uint16_t initialFrameCount
ImageConversion::ResizeBounds resizeBounds
float compressedFormatQuality
bool computeTransparencyFlags
ImageConversion::ResizeFilter filter
ImageConversion::ResizeMethod heightResizeMethod
CompressionMethod compressionMethod
ImageConversion::ResizeMethod widthResizeMethod