diff --git a/include/gamepp/gamepp.h b/include/gamepp/gamepp.h index b9775da5a..f8b57e232 100644 --- a/include/gamepp/gamepp.h +++ b/include/gamepp/gamepp.h @@ -42,28 +42,28 @@ class GameInstance { * @param command The command to run. * @return This GameInstance. */ - const GameInstance& command(std::string_view command) const; + const GameInstance& command(std::string_view command) const; // NOLINT(*-use-nodiscard) /** * Begin "pressing" an input such as forward or left. - * @param command The input to run (without the plus sign prefix). + * @param input The input to run (without the plus sign prefix). * @return This GameInstance. */ - const GameInstance& inputBegin(std::string_view input) const; + const GameInstance& inputBegin(std::string_view input) const; // NOLINT(*-use-nodiscard) /** * End "pressing" an input such as forward or left. - * @param command The input to run (without the minus sign prefix). + * @param input The input to run (without the minus sign prefix). * @return This GameInstance. */ - const GameInstance& inputEnd(std::string_view input) const; + const GameInstance& inputEnd(std::string_view input) const; // NOLINT(*-use-nodiscard) /** * Begin and end "pressing" an input in one tick, like tapping the use key. - * @param command The input to run (without any prefix). + * @param input The input to run (without any prefix). * @return This GameInstance. */ - const GameInstance& inputOnce(std::string_view input) const; + const GameInstance& inputOnce(std::string_view input) const; // NOLINT(*-use-nodiscard) /** * Begin and end "pressing" an input in the given timespan, like holding the use key. @@ -71,14 +71,14 @@ class GameInstance { * @param sec The time to hold the input for. * @return This GameInstance. */ - const GameInstance& inputHold(std::string_view input, double sec) const; + const GameInstance& inputHold(std::string_view input, double sec) const; // NOLINT(*-use-nodiscard) /** * Sleep on the current thread for the given number of seconds. * @param sec The number of seconds. * @return This GameInstance. */ - const GameInstance& wait(double sec) const; + const GameInstance& wait(double sec) const; // NOLINT(*-use-nodiscard) protected: GameInstance() = default; diff --git a/include/kvpp/KV1.h b/include/kvpp/KV1.h index 3d8e26d40..eb2ff3567 100644 --- a/include/kvpp/KV1.h +++ b/include/kvpp/KV1.h @@ -278,10 +278,10 @@ class KV1ElementWritable : public KV1ElementBase> { stream_.write('\t'); } }; - constexpr auto writeQuotedString = [](BufferStream& stream_, std::string_view str, const parser::text::EscapeSequenceMap& escapeSequences, char quoteStart = '\"', char quoteEnd = '\"') { + constexpr auto writeQuotedString = [](BufferStream& stream_, std::string_view str, const parser::text::EscapeSequenceMap& escapeSequences_, char quoteStart = '\"', char quoteEnd = '\"') { stream_.write(quoteStart); if (!str.empty()) { - stream_.write(parser::text::convertSpecialCharsToEscapes(str, escapeSequences), false); + stream_.write(parser::text::convertSpecialCharsToEscapes(str, escapeSequences_), false); } stream_.write(quoteEnd); }; diff --git a/include/toolpp/FGD.h b/include/toolpp/FGD.h index 0ee139ad2..bb36c53d1 100644 --- a/include/toolpp/FGD.h +++ b/include/toolpp/FGD.h @@ -125,7 +125,7 @@ class FGDWriter { AutoVisGroupWriter& visGroup(const std::string& name, const std::vector& entities); - FGDWriter& endAutoVisGroup(); + FGDWriter& endAutoVisGroup() const; // NOLINT(*-use-nodiscard) private: FGDWriter& parent; @@ -139,7 +139,7 @@ class FGDWriter { KeyValueChoicesWriter& choice(const std::string& value, const std::string& displayName); - EntityWriter& endKeyValueChoices(); + EntityWriter& endKeyValueChoices() const; // NOLINT(*-use-nodiscard) private: EntityWriter& parent; @@ -151,7 +151,7 @@ class FGDWriter { KeyValueFlagsWriter& flag(uint64_t value, const std::string& displayName, bool enabledByDefault, const std::string& description = ""); - EntityWriter& endKeyValueFlags(); + EntityWriter& endKeyValueFlags() const; // NOLINT(*-use-nodiscard) private: EntityWriter& parent; @@ -169,7 +169,7 @@ class FGDWriter { EntityWriter& output(const std::string& name, const std::string& valueType, const std::string& description = ""); - FGDWriter& endEntity(); + FGDWriter& endEntity() const; // NOLINT(*-use-nodiscard) private: FGDWriter& parent; diff --git a/include/vpkpp/PackFile.h b/include/vpkpp/PackFile.h index c2e7c449a..ccd9a59e9 100644 --- a/include/vpkpp/PackFile.h +++ b/include/vpkpp/PackFile.h @@ -1,16 +1,13 @@ #pragma once -#include #include #include #include #include #include -#include #include #include -#include #include #include diff --git a/include/vpkpp/format/VPK.h b/include/vpkpp/format/VPK.h index 551ecb1d6..ea7a0d047 100644 --- a/include/vpkpp/format/VPK.h +++ b/include/vpkpp/format/VPK.h @@ -1,7 +1,6 @@ #pragma once #include -#include #include "../PackFile.h" diff --git a/include/vpkpp/format/VPK_VTMB.h b/include/vpkpp/format/VPK_VTMB.h index 83353d725..e83fe345e 100644 --- a/include/vpkpp/format/VPK_VTMB.h +++ b/include/vpkpp/format/VPK_VTMB.h @@ -1,8 +1,5 @@ #pragma once -#include -#include - #include "../PackFile.h" namespace vpkpp { diff --git a/include/vpkpp/format/ZIP.h b/include/vpkpp/format/ZIP.h index eb6f1bd7c..2ac101c18 100644 --- a/include/vpkpp/format/ZIP.h +++ b/include/vpkpp/format/ZIP.h @@ -52,7 +52,7 @@ class ZIP : public PackFile { void addEntryInternal(Entry& entry, const std::string& path, std::vector& buffer, EntryOptions options) override; - bool bakeTempZip(const std::string& writeZipPath, BakeOptions options, const EntryCallback& callback); + bool bakeTempZip(const std::string& writeZipPath, BakeOptions options, const EntryCallback& callback) const; // NOLINT(*-use-nodiscard) bool openZIP(std::string_view path); diff --git a/include/vtfpp/ImageConversion.h b/include/vtfpp/ImageConversion.h index 226005361..2e946956d 100644 --- a/include/vtfpp/ImageConversion.h +++ b/include/vtfpp/ImageConversion.h @@ -41,7 +41,7 @@ struct RGB888 { }; VTFPP_CHECK_SIZE(RGB888); -struct RGB888_BLUESCREEN : public RGB888 { +struct RGB888_BLUESCREEN : RGB888 { static constexpr auto FORMAT = ImageFormat::RGB888_BLUESCREEN; }; VTFPP_CHECK_SIZE(RGB888_BLUESCREEN); @@ -54,7 +54,7 @@ struct BGR888 { }; VTFPP_CHECK_SIZE(BGR888); -struct BGR888_BLUESCREEN : public BGR888 { +struct BGR888_BLUESCREEN : BGR888 { static constexpr auto FORMAT = ImageFormat::BGR888_BLUESCREEN; }; VTFPP_CHECK_SIZE(BGR888_BLUESCREEN); diff --git a/include/vtfpp/ImageFormats.h b/include/vtfpp/ImageFormats.h index 1bb428fb8..cb2c01225 100644 --- a/include/vtfpp/ImageFormats.h +++ b/include/vtfpp/ImageFormats.h @@ -1,7 +1,5 @@ #pragma once -#include - #include namespace vtfpp { @@ -584,8 +582,7 @@ namespace ImageFormatDetails { default: break; } - uint32_t out = width * height * sliceCount * bpp(format) / 8; - return out; + return width * height * sliceCount * (bpp(format) / 8); } [[nodiscard]] constexpr uint32_t getDataLength(ImageFormat format, uint8_t mipCount, uint16_t frameCount, uint8_t faceCount, uint16_t width, uint16_t height, uint16_t sliceCount = 1) { @@ -603,7 +600,7 @@ namespace ImageFormatDetails { for (int j = 0; j < frameCount; j++) { for (int k = 0; k < faceCount; k++) { for (int l = 0; l < sliceCount; l++) { - auto imageSize = ImageFormatDetails::getDataLength(format, ImageDimensions::getMipDim(i, width), ImageDimensions::getMipDim(i, height)); + const auto imageSize = ImageFormatDetails::getDataLength(format, ImageDimensions::getMipDim(i, width), ImageDimensions::getMipDim(i, height)); if (i == mip && j == frame && k == face && l == slice) { length = imageSize; return true; diff --git a/include/vtfpp/VTF.h b/include/vtfpp/VTF.h index 783ea7643..3cf0cc5f1 100644 --- a/include/vtfpp/VTF.h +++ b/include/vtfpp/VTF.h @@ -4,7 +4,6 @@ #include #include #include -#include #include #include #include @@ -166,10 +165,10 @@ class VTF { }; /// This value is only valid when passed to VTF::create through CreationOptions - static constexpr ImageFormat FORMAT_UNCHANGED = static_cast(-2); + static constexpr auto FORMAT_UNCHANGED = static_cast(-2); /// This value is only valid when passed to VTF::create through CreationOptions or VTF::setFormat - static constexpr ImageFormat FORMAT_DEFAULT = static_cast(-1); + static constexpr auto FORMAT_DEFAULT = static_cast(-1); static constexpr int32_t MAX_RESOURCES = 32; diff --git a/src/bsppp/bsppp.cpp b/src/bsppp/bsppp.cpp index cd44076a7..a6b36c79b 100644 --- a/src/bsppp/bsppp.cpp +++ b/src/bsppp/bsppp.cpp @@ -121,7 +121,7 @@ bool BSP::hasLump(BSPLump lumpIndex) const { if (this->path.empty()) { return false; } - auto lump = static_cast>(lumpIndex); + const auto lump = static_cast>(lumpIndex); return this->header.lumps[lump].length != 0 && this->header.lumps[lump].offset != 0; } @@ -137,14 +137,14 @@ void BSP::setLumpVersion(BSPLump lumpIndex, int32_t version) { this->writeHeader(); } -std::optional> BSP::readLump(BSPLump lump) const { - if (this->path.empty() || !this->hasLump(lump)) { +std::optional> BSP::readLump(BSPLump lumpIndex) const { + if (this->path.empty() || !this->hasLump(lumpIndex)) { return std::nullopt; } FileStream reader{this->path}; return reader - .seek_in(this->header.lumps[static_cast>(lump)].offset) - .read_bytes(this->header.lumps[static_cast>(lump)].length); + .seek_in(this->header.lumps[static_cast>(lumpIndex)].offset) + .read_bytes(this->header.lumps[static_cast>(lumpIndex)].length); } void BSP::writeLump(BSPLump lumpIndex, std::span data, bool condenseFile) { @@ -157,10 +157,10 @@ void BSP::writeLump(BSPLump lumpIndex, std::span data, bool con if (!this->hasLump(lumpIndex) || !condenseFile) { // Put the lump at the end of the file int32_t lastLumpOffset = 0, lastLumpLength = 0; - for (const Lump& lump : this->header.lumps) { + for (const auto& [lumpOffset, lumpLength, lumpVersion, lumpFourCC] : this->header.lumps) { if (lastLumpOffset < this->header.lumps[lumpToMove].offset) { - lastLumpOffset = lump.offset; - lastLumpLength = lump.length; + lastLumpOffset = lumpOffset; + lastLumpLength = lumpLength; } } if (lastLumpOffset == 0) { @@ -221,10 +221,10 @@ void BSP::writeLump(BSPLump lumpIndex, std::span data, bool con // Resize file if it shrank int32_t lastLumpOffset = 0, lastLumpLength = 0; - for (const Lump& lump : this->header.lumps) { + for (const auto& [lumpOffset, lumpLength, lumpVersion, lumpFourCC] : this->header.lumps) { if (lastLumpOffset < this->header.lumps[lumpToMove].offset) { - lastLumpOffset = lump.offset; - lastLumpLength = lump.length; + lastLumpOffset = lumpOffset; + lastLumpLength = lumpLength; } } if (std::filesystem::file_size(this->path) > lastLumpOffset + lastLumpLength) { @@ -242,10 +242,10 @@ bool BSP::applyLumpPatchFile(const std::string& lumpFilePath) { return false; } - auto offset = reader.read(); - auto index = reader.read(); - auto version = reader.read(); - auto length = reader.read(); + const auto offset = reader.read(); + const auto index = reader.read(); + const auto version = reader.read(); + const auto length = reader.read(); if (index < 0 || index > BSP_LUMP_COUNT || offset <= 0 || length <= 0) { return false; } @@ -261,7 +261,7 @@ void BSP::createLumpPatchFile(BSPLump lumpIndex) const { return; } - auto& lump = this->header.lumps.at(static_cast>(lumpIndex)); + const auto& [lumpOffset, lumpLength, lumpVersion, lumpFourCC] = this->header.lumps.at(static_cast>(lumpIndex)); const auto fsPath = std::filesystem::path{this->path}; const auto fsStem = (fsPath.parent_path() / fsPath.stem()).string() + "_l_"; @@ -277,8 +277,8 @@ void BSP::createLumpPatchFile(BSPLump lumpIndex) const { .seek_out(0) .write(sizeof(int32_t) * 5) .write(lumpIndex) - .write(lump.version) - .write(lump.length) + .write(lumpVersion) + .write(lumpLength) .write(this->header.mapRevision) .write(*lumpData); } diff --git a/src/dmxpp/dmxpp.cpp b/src/dmxpp/dmxpp.cpp index 57f24c90a..108b295eb 100644 --- a/src/dmxpp/dmxpp.cpp +++ b/src/dmxpp/dmxpp.cpp @@ -100,40 +100,41 @@ bool DMX::openBinary(BufferStream& stream) { } else { stringCount = stream.read(); } + stringList.reserve(stringCount); for (int i = 0; i < stringCount; i++) { stringList.push_back(stream.read_string()); } // Read a string index and get the string from the list - const auto readStringFromIndex = [stringListIndicesAreShort, &stringList](BufferStream& stream) { + const auto readStringFromIndex = [stringListIndicesAreShort, &stringList](BufferStream& stream_) { if (stringListIndicesAreShort) { - return stringList.at(stream.read()); + return stringList.at(stream_.read()); } - return stringList.at(stream.read()); + return stringList.at(stream_.read()); }; // Read elements - int elementCount = stream.read(); + const int elementCount = stream.read(); for (int i = 0; i < elementCount; i++) { - auto& element = this->elements.emplace_back(); - element.type = readStringFromIndex(stream); + auto& [type, name, guid, attributes] = this->elements.emplace_back(); + type = readStringFromIndex(stream); if (elementNamesAreStoredInStringList) { - element.name = readStringFromIndex(stream); + name = readStringFromIndex(stream); } else { - element.name = stream.read_string(); + name = stream.read_string(); } - element.guid = stream.read_bytes<16>(); + guid = stream.read_bytes<16>(); } // Helper to read a value for an attribute std::function readValue; - readValue = [&readValue, &readStringFromIndex](BufferStream& stream, Value::ID type, bool useStringList) -> Value::Generic { - const auto readArrayValue = [&readValue](BufferStream& stream, Value::ID type) { + readValue = [&readValue, &readStringFromIndex](BufferStream& stream_, Value::ID type, bool useStringList) -> Value::Generic { + const auto readArrayValue = [&readValue](BufferStream& reader, Value::ID type_) { std::vector out; - auto size = stream.read(); + auto size = reader.read(); out.reserve(size); for (int i = 0; i < size; i++) { - out.push_back(std::get(readValue(stream, Value::arrayIDToInnerID(type), true))); + out.push_back(std::get(readValue(reader, Value::arrayIDToInnerID(type_), true))); } return out; }; @@ -143,75 +144,75 @@ bool DMX::openBinary(BufferStream& stream) { return Value::Invalid{}; case ELEMENT: { Value::Element value; - value.index = stream.read(); + value.index = stream_.read(); if (value.index == -2) { // Parse the ASCII GUID if it's a stub - value.stubGUID = stream.read_string(); + value.stubGUID = stream_.read_string(); } return value; } case INT: - return stream.read(); + return stream_.read(); case FLOAT: - return stream.read(); + return stream_.read(); case BOOL: - return stream.read(); + return stream_.read(); case STRING: - return useStringList ? readStringFromIndex(stream) : stream.read_string(); + return useStringList ? readStringFromIndex(stream_) : stream_.read_string(); case BYTEARRAY: - return stream.read_bytes(stream.read()); + return stream_.read_bytes(stream_.read()); case TIME: - return Value::Time{static_cast(static_cast(stream.read()) / 10000.0)}; + return Value::Time{static_cast(static_cast(stream_.read()) / 10000.0)}; case COLOR: - return stream.read(); + return stream_.read(); case VECTOR2: - return stream.read(); + return stream_.read(); case VECTOR3: case EULER_ANGLE: - return stream.read(); + return stream_.read(); case VECTOR4: case QUATERNION: - return stream.read(); + return stream_.read(); case MATRIX_4X4: - return stream.read(); + return stream_.read(); case ARRAY_ELEMENT: - return readArrayValue.operator()(stream, type); + return readArrayValue.operator()(stream_, type); case ARRAY_INT: - return readArrayValue.operator()(stream, type); + return readArrayValue.operator()(stream_, type); case ARRAY_FLOAT: - return readArrayValue.operator()(stream, type); + return readArrayValue.operator()(stream_, type); case ARRAY_BOOL: - return readArrayValue.operator()(stream, type); + return readArrayValue.operator()(stream_, type); case ARRAY_STRING: - return readArrayValue.operator()(stream, type); + return readArrayValue.operator()(stream_, type); case ARRAY_BYTEARRAY: - return readArrayValue.operator()>(stream, type); + return readArrayValue.operator()>(stream_, type); case ARRAY_TIME: - return readArrayValue.operator()(stream, type); + return readArrayValue.operator()(stream_, type); case ARRAY_COLOR: - return readArrayValue.operator()(stream, type); + return readArrayValue.operator()(stream_, type); case ARRAY_VECTOR2: - return readArrayValue.operator()(stream, type); + return readArrayValue.operator()(stream_, type); case ARRAY_VECTOR3: case ARRAY_EULER_ANGLE: - return readArrayValue.operator()(stream, type); + return readArrayValue.operator()(stream_, type); case ARRAY_VECTOR4: case ARRAY_QUATERNION: - return readArrayValue.operator()(stream, type); + return readArrayValue.operator()(stream_, type); case ARRAY_MATRIX_4X4: - return readArrayValue.operator()(stream, type); + return readArrayValue.operator()(stream_, type); } return 0; // Dummy to get it to compile }; // Read element attributes - for (auto& element : this->elements) { - int attributeCount = stream.read(); + for (auto& [type, name, guid, attributes] : this->elements) { + const int attributeCount = stream.read(); for (int i = 0; i < attributeCount; i++) { - auto& attribute = element.attributes.emplace_back(); - attribute.name = readStringFromIndex(stream); - attribute.type = Value::byteToID(stream.read()); - attribute.value = readValue(stream, attribute.type, stringValuesAreStoredInStringList); + auto& [attrName, attrType, attrValue] = attributes.emplace_back(); + attrName = readStringFromIndex(stream); + attrType = Value::byteToID(stream.read()); + attrValue = readValue(stream, attrType, stringValuesAreStoredInStringList); } } diff --git a/src/dmxpp/structs/Value.cpp b/src/dmxpp/structs/Value.cpp index 0fde519eb..f3930585e 100644 --- a/src/dmxpp/structs/Value.cpp +++ b/src/dmxpp/structs/Value.cpp @@ -65,11 +65,11 @@ std::string DMXAttribute::getValue() const { case INVALID: return Value::IDToString(this->type); case ELEMENT: { - auto element = this->getValueAs(); - if (element.index == -2) { - return "GUID: " + element.stubGUID; + const auto [index, stubGUID] = this->getValueAs(); + if (index == -2) { + return "GUID: " + stubGUID; } - return '#' + std::to_string(element.index); + return '#' + std::to_string(index); } case INT: return std::to_string(this->getValueAs()); @@ -92,25 +92,25 @@ std::string DMXAttribute::getValue() const { case TIME: return std::to_string(this->getValueAs()); case COLOR: { - auto color = this->getValueAs(); - return "rgba(" + std::to_string(color.r) + ", " + std::to_string(color.g) + ", " + std::to_string(color.b) + ", " + std::to_string(color.a) + ')'; + const auto [r, g, b, a] = this->getValueAs(); + return "rgba(" + std::to_string(r) + ", " + std::to_string(g) + ", " + std::to_string(b) + ", " + std::to_string(a) + ')'; } case VECTOR2: { - auto vec2 = this->getValueAs(); + const auto vec2 = this->getValueAs(); return '[' + std::to_string(vec2[0]) + ", " + std::to_string(vec2[1]) + ']'; } case VECTOR3: case EULER_ANGLE: { - auto vec3 = this->getValueAs(); + const auto vec3 = this->getValueAs(); return '[' + std::to_string(vec3[0]) + ", " + std::to_string(vec3[1]) + ", " + std::to_string(vec3[2]) + ']'; } case VECTOR4: case QUATERNION: { - auto vec4 = this->getValueAs(); + const auto vec4 = this->getValueAs(); return '[' + std::to_string(vec4[0]) + ", " + std::to_string(vec4[1]) + ", " + std::to_string(vec4[2]) + ", " + std::to_string(vec4[3]) + ']'; } case MATRIX_4X4: { - auto mat4 = this->getValueAs(); + const auto mat4 = this->getValueAs(); std::string out; for (int i = 0; i < 4; i++) { out += (i == 0 ? '[' : ' '); @@ -128,7 +128,7 @@ std::string DMXAttribute::getValue() const { return out; } case ARRAY_ELEMENT: { - auto elements = this->getValueAs>(); + const auto elements = this->getValueAs>(); std::string out = "["; for (int i = 0; i < elements.size(); i++) { if (elements[i].index == -2) { @@ -140,7 +140,7 @@ std::string DMXAttribute::getValue() const { return out + ']'; } case ARRAY_INT: { - auto ints = this->getValueAs>(); + const auto ints = this->getValueAs>(); std::string out = "["; for (int i = 0; i < ints.size(); i++) { out += (i == 0 ? "" : " ") + std::to_string(ints[i]) + (i == ints.size() - 1 ? "" : ","); @@ -148,7 +148,7 @@ std::string DMXAttribute::getValue() const { return out + ']'; } case ARRAY_FLOAT: { - auto floats = this->getValueAs>(); + const auto floats = this->getValueAs>(); std::string out = "["; for (int i = 0; i < floats.size(); i++) { out += (i == 0 ? "" : " ") + std::to_string(floats[i]) + (i == floats.size() - 1 ? "" : ","); @@ -156,7 +156,7 @@ std::string DMXAttribute::getValue() const { return out + ']'; } case ARRAY_BOOL: { - auto bools = this->getValueAs>(); + const auto bools = this->getValueAs>(); std::string out = "["; for (int i = 0; i < bools.size(); i++) { out += (i == 0 ? "" : " ") + std::string{bools[i] ? "true" : "false"} + (i == bools.size() - 1 ? "" : ","); @@ -164,7 +164,7 @@ std::string DMXAttribute::getValue() const { return out + ']'; } case ARRAY_STRING: { - auto strings = this->getValueAs>(); + const auto strings = this->getValueAs>(); std::string out = "["; for (int i = 0; i < strings.size(); i++) { out += (i == 0 ? "" : " ") + strings[i] + (i == strings.size() - 1 ? "" : ",\n"); @@ -172,7 +172,7 @@ std::string DMXAttribute::getValue() const { return out + ']'; } case ARRAY_BYTEARRAY: { - auto bytearrays = this->getValueAs>(); + const auto bytearrays = this->getValueAs>(); std::string out = "["; for (int i = 0; i < bytearrays.size(); i++) { std::string hex; @@ -187,7 +187,7 @@ std::string DMXAttribute::getValue() const { return out + ']'; } case ARRAY_TIME: { - auto times = this->getValueAs>(); + const auto times = this->getValueAs>(); std::string out = "["; for (int i = 0; i < times.size(); i++) { out += (i == 0 ? "" : " ") + std::to_string(times[i]) + (i == times.size() - 1 ? "" : ","); @@ -195,7 +195,7 @@ std::string DMXAttribute::getValue() const { return out + ']'; } case ARRAY_COLOR: { - auto colors = this->getValueAs>(); + const auto colors = this->getValueAs>(); std::string out = "["; for (int i = 0; i < colors.size(); i++) { out += (i == 0 ? "" : " ") + std::string{"rgba("} + std::to_string(colors[i].r) + ", " + std::to_string(colors[i].g) + ", " + std::to_string(colors[i].b) + ", " + std::to_string(colors[i].a) + ')' + (i == colors.size() - 1 ? "" : ",\n"); @@ -203,7 +203,7 @@ std::string DMXAttribute::getValue() const { return out + ']'; } case ARRAY_VECTOR2: { - auto vectors = this->getValueAs>(); + const auto vectors = this->getValueAs>(); std::string out = "["; for (int i = 0; i < vectors.size(); i++) { out += (i == 0 ? "" : " ") + std::string{"["} + std::to_string(vectors[i][0]) + ", " + std::to_string(vectors[i][1]) + ']' + (i == vectors.size() - 1 ? "" : ",\n"); @@ -212,7 +212,7 @@ std::string DMXAttribute::getValue() const { } case ARRAY_VECTOR3: case ARRAY_EULER_ANGLE: { - auto vectors = this->getValueAs>(); + const auto vectors = this->getValueAs>(); std::string out = "["; for (int i = 0; i < vectors.size(); i++) { out += (i == 0 ? "" : " ") + std::string{"["} + std::to_string(vectors[i][0]) + ", " + std::to_string(vectors[i][1]) + ", " + std::to_string(vectors[i][2]) + ']' + (i == vectors.size() - 1 ? "" : ",\n"); @@ -221,7 +221,7 @@ std::string DMXAttribute::getValue() const { } case ARRAY_VECTOR4: case ARRAY_QUATERNION: { - auto vectors = this->getValueAs>(); + const auto vectors = this->getValueAs>(); std::string out = "["; for (int i = 0; i < vectors.size(); i++) { out += (i == 0 ? "" : " ") + std::string{"["} + std::to_string(vectors[i][0]) + ", " + std::to_string(vectors[i][1]) + ", " + std::to_string(vectors[i][2]) + ']' + ", " + std::to_string(vectors[i][3]) + ']' + (i == vectors.size() - 1 ? "" : ",\n"); @@ -229,7 +229,7 @@ std::string DMXAttribute::getValue() const { return out + ']'; } case ARRAY_MATRIX_4X4: { - auto matrices = this->getValueAs>(); + const auto matrices = this->getValueAs>(); std::string out = "["; for (int m = 0; m < matrices.size(); m++) { out += (m == 0 ? "[" : " ["); diff --git a/src/mdlpp/mdlpp.cpp b/src/mdlpp/mdlpp.cpp index c2c1d3ceb..9145581c9 100644 --- a/src/mdlpp/mdlpp.cpp +++ b/src/mdlpp/mdlpp.cpp @@ -60,11 +60,11 @@ BakedModel StudioModel::processModelData(int currentLOD) const { if (this->vvd.fixups.empty()) { std::transform(this->vvd.vertices.begin(), this->vvd.vertices.end(), std::back_inserter(model.vertices), convertVertex); } else { - for (const auto& fixup : this->vvd.fixups) { - if (fixup.LOD < currentLOD) { + for (const auto& [LOD, sourceVertexID, vertexCount] : this->vvd.fixups) { + if (LOD < currentLOD) { continue; } - std::span fixupVertices{this->vvd.vertices.begin() + fixup.sourceVertexID, static_cast::size_type>(fixup.vertexCount)}; + std::span fixupVertices{this->vvd.vertices.begin() + sourceVertexID, static_cast::size_type>(vertexCount)}; std::transform(fixupVertices.begin(), fixupVertices.end(), std::back_inserter(model.vertices), convertVertex); } } diff --git a/src/mdlpp/structs/MDL.cpp b/src/mdlpp/structs/MDL.cpp index 82e077d36..53132f466 100644 --- a/src/mdlpp/structs/MDL.cpp +++ b/src/mdlpp/structs/MDL.cpp @@ -32,14 +32,14 @@ bool MDL::open(const std::byte* data, std::size_t size) { this->flags = static_cast(stream.read()); - auto boneCount = stream.read(); - auto boneOffset = stream.read(); + const auto boneCount = stream.read(); + const auto boneOffset = stream.read(); - auto boneControllerCount = stream.read(); - auto boneControllerOffset = stream.read(); + const auto boneControllerCount = stream.read(); + const auto boneControllerOffset = stream.read(); - auto hitboxSetCount = stream.read(); - auto hitboxSetOffset = stream.read(); + const auto hitboxSetCount = stream.read(); + const auto hitboxSetOffset = stream.read(); //auto animDescCount = stream.read(); //auto animDescOffset = stream.read(); @@ -53,18 +53,18 @@ bool MDL::open(const std::byte* data, std::size_t size) { .read(this->activityListVersion) .read(this->eventsIndexed); - auto materialCount = stream.read(); - auto materialOffset = stream.read(); + const auto materialCount = stream.read(); + const auto materialOffset = stream.read(); - auto materialDirCount = stream.read(); - auto materialDirOffset = stream.read(); + const auto materialDirCount = stream.read(); + const auto materialDirOffset = stream.read(); - auto skinReferenceCount = stream.read(); - auto skinReferenceFamilyCount = stream.read(); - auto skinReferenceOffset = stream.read(); + const auto skinReferenceCount = stream.read(); + const auto skinReferenceFamilyCount = stream.read(); + const auto skinReferenceOffset = stream.read(); - auto bodyPartCount = stream.read(); - auto bodyPartOffset = stream.read(); + const auto bodyPartCount = stream.read(); + const auto bodyPartOffset = stream.read(); // Done reading sequentially, start seeking to offsets @@ -103,17 +103,17 @@ bool MDL::open(const std::byte* data, std::size_t size) { } for (int i = 0; i < hitboxSetCount; i++) { - auto hitboxSetPos = hitboxSetOffset + i * (sizeof(int32_t) * 3); + const auto hitboxSetPos = hitboxSetOffset + i * (sizeof(int32_t) * 3); stream.seek_u(hitboxSetPos); auto& hitboxSet = this->hitboxSets.emplace_back(); parser::binary::readStringAtOffset(stream, hitboxSet.name); - auto hitboxCount = stream.read(); - auto hitboxOffset = stream.read(); + const auto hitboxCount = stream.read(); + const auto hitboxOffset = stream.read(); for (int j = 0; j < hitboxCount; j++) { - auto hitboxPos = hitboxOffset + j * (sizeof(int32_t) * 11 + sizeof(math::Vec3f) * 2); + const auto hitboxPos = hitboxOffset + j * (sizeof(int32_t) * 11 + sizeof(math::Vec3f) * 2); stream.seek_u(hitboxSetPos + hitboxPos); auto& hitbox = hitboxSet.hitboxes.emplace_back(); @@ -170,24 +170,24 @@ bool MDL::open(const std::byte* data, std::size_t size) { stream.seek(skinReferenceOffset); for (int i = 0; i < skinReferenceFamilyCount; i++) { std::vector skinFamily; - for (int j = 0; j < skinReferenceCount; j++) { + skinFamily.reserve(skinReferenceCount); + for (int j = 0; j < skinReferenceCount; j++) { skinFamily.push_back(stream.read()); } this->skins.push_back(std::move(skinFamily)); } for (int i = 0; i < bodyPartCount; i++) { - auto bodyPartPos = bodyPartOffset + i * (sizeof(int32_t) * 4); + const auto bodyPartPos = bodyPartOffset + i * (sizeof(int32_t) * 4); stream.seek_u(bodyPartPos); auto& bodyPart = this->bodyParts.emplace_back(); parser::binary::readStringAtOffset(stream, bodyPart.name); - auto modelsCount = stream.read(); - // base - stream.skip(); - auto modelsOffset = stream.read(); + const auto modelsCount = stream.read(); + stream.skip(); // base + const auto modelsOffset = stream.read(); for (int j = 0; j < modelsCount; j++) { auto modelPos = modelsOffset + j * (64 + sizeof(float) + sizeof(int32_t) * 20); @@ -200,15 +200,15 @@ bool MDL::open(const std::byte* data, std::size_t size) { .read(model.type) .read(model.boundingRadius); - auto meshesCount = stream.read(); - auto meshesOffset = stream.read(); + const auto meshesCount = stream.read(); + const auto meshesOffset = stream.read(); stream .read(model.verticesCount) .read(model.verticesOffset); for (int k = 0; k < meshesCount; k++) { - auto meshPos = meshesOffset + k * (sizeof(int32_t) * (18 + MAX_LOD_COUNT) + sizeof(math::Vec3f)); + const auto meshPos = meshesOffset + k * (sizeof(int32_t) * (18 + MAX_LOD_COUNT) + sizeof(math::Vec3f)); stream.seek_u(bodyPartPos + modelPos + meshPos); auto& mesh = model.meshes.emplace_back(); diff --git a/src/mdlpp/structs/VTX.cpp b/src/mdlpp/structs/VTX.cpp index bd57c19fc..13041d95f 100644 --- a/src/mdlpp/structs/VTX.cpp +++ b/src/mdlpp/structs/VTX.cpp @@ -26,46 +26,46 @@ bool VTX::open(const std::byte* data, std::size_t size, const MDL::MDL& mdl) { // todo: read material replacement list stream.skip(); - auto bodyPartCount = stream.read(); - auto bodyPartOffset = stream.read(); + const auto bodyPartCount = stream.read(); + const auto bodyPartOffset = stream.read(); for (int i = 0; i < bodyPartCount; i++) { - auto bodyPartPos = bodyPartOffset + i * ((sizeof(int32_t) * 2)); + const auto bodyPartPos = bodyPartOffset + i * ((sizeof(int32_t) * 2)); stream.seek_u(bodyPartPos); auto& bodyPart = this->bodyParts.emplace_back(); - auto modelCount = stream.read(); - auto modelOffset = stream.read(); + const auto modelCount = stream.read(); + const auto modelOffset = stream.read(); for (int j = 0; j < modelCount; j++) { - auto modelPos = modelOffset + j * (sizeof(int32_t) * 2); + const auto modelPos = modelOffset + j * (sizeof(int32_t) * 2); stream.seek_u(bodyPartPos + modelPos); auto& model = bodyPart.models.emplace_back(); - auto modelLODCount = stream.read(); - auto modelLODOffset = stream.read(); + const auto modelLODCount = stream.read(); + const auto modelLODOffset = stream.read(); for (int k = 0; k < modelLODCount; k++) { - auto modelLODPos = modelLODOffset + k * (sizeof(int32_t) * 2 + sizeof(float)); + const auto modelLODPos = modelLODOffset + k * (sizeof(int32_t) * 2 + sizeof(float)); stream.seek_u(bodyPartPos + modelPos + modelLODPos); auto& modelLOD = model.modelLODs.emplace_back(); - auto meshCount = stream.read(); - auto meshOffset = stream.read(); + const auto meshCount = stream.read(); + const auto meshOffset = stream.read(); stream.read(modelLOD.switchDistance); for (int l = 0; l < meshCount; l++) { - auto meshPos = meshOffset + l * (sizeof(int32_t) * 2 + sizeof(Mesh::Flags)); + const auto meshPos = meshOffset + l * (sizeof(int32_t) * 2 + sizeof(Mesh::Flags)); stream.seek_u(bodyPartPos + modelPos + modelLODPos + meshPos); auto& mesh = modelLOD.meshes.emplace_back(); - auto stripGroupCount = stream.read(); - auto stripGroupOffset = stream.read(); + const auto stripGroupCount = stream.read(); + const auto stripGroupOffset = stream.read(); stream.read(mesh.flags); @@ -74,31 +74,31 @@ bool VTX::open(const std::byte* data, std::size_t size, const MDL::MDL& mdl) { if (mdl.version >= 49) { stripGroupNumInts += 2; } - auto stripGroupPos = stripGroupOffset + m * (sizeof(int32_t) * stripGroupNumInts + sizeof(StripGroup::Flags)); + const auto stripGroupPos = stripGroupOffset + m * (sizeof(int32_t) * stripGroupNumInts + sizeof(StripGroup::Flags)); stream.seek_u(bodyPartPos + modelPos + modelLODPos + meshPos + stripGroupPos); auto& stripGroup = mesh.stripGroups.emplace_back(); - auto vertexCount = stream.read(); - auto vertexOffset = stream.read(); + const auto vertexCount = stream.read(); + const auto vertexOffset = stream.read(); auto stripGroupCurrentPos = stream.tell(); stream.seek_u(bodyPartPos + modelPos + modelLODPos + meshPos + stripGroupPos + vertexOffset); for (int n = 0; n < vertexCount; n++) { - auto& vertex = stripGroup.vertices.emplace_back(); + auto& [meshVertexID] = stripGroup.vertices.emplace_back(); // todo: process bone data stream.skip(4); - stream.read(vertex.meshVertexID); + stream.read(meshVertexID); // ditto stream.skip(3); } stream.seek_u(stripGroupCurrentPos); - auto indexCount = stream.read(); - auto indexOffset = stream.read(); + const auto indexCount = stream.read(); + const auto indexOffset = stream.read(); stripGroupCurrentPos = stream.tell(); stream.seek_u(bodyPartPos + modelPos + modelLODPos + meshPos + stripGroupPos + indexOffset); @@ -108,8 +108,8 @@ bool VTX::open(const std::byte* data, std::size_t size, const MDL::MDL& mdl) { } stream.seek_u(stripGroupCurrentPos); - auto stripCount = stream.read(); - auto stripOffset = stream.read(); + const auto stripCount = stream.read(); + const auto stripOffset = stream.read(); stream.read(stripGroup.flags); @@ -122,15 +122,15 @@ bool VTX::open(const std::byte* data, std::size_t size, const MDL::MDL& mdl) { for (int n = 0; n < stripCount; n++) { auto& strip = stripGroup.strips.emplace_back(); - auto indicesCount = stream.read(); + const auto indicesCount = stream.read(); stream.read(strip.indicesOffset); // todo: check if offset is in bytes - strip.indices = std::span(stripGroup.indices.begin() + strip.indicesOffset, indicesCount); + strip.indices = std::span(stripGroup.indices.begin() + strip.indicesOffset, indicesCount); - auto verticesCount = stream.read(); + const auto verticesCount = stream.read(); stream.read(strip.verticesOffset); // todo: check if offset is in bytes - strip.vertices = std::span(stripGroup.vertices.begin() + strip.verticesOffset, verticesCount); + strip.vertices = std::span(stripGroup.vertices.begin() + strip.verticesOffset, verticesCount); stream .read(strip.boneCount) diff --git a/src/mdlpp/structs/VVD.cpp b/src/mdlpp/structs/VVD.cpp index b99763aa2..0b599017e 100644 --- a/src/mdlpp/structs/VVD.cpp +++ b/src/mdlpp/structs/VVD.cpp @@ -26,28 +26,28 @@ bool VVD::open(const std::byte* data, std::size_t size, const MDL::MDL& mdl) { .read(this->numLODs) .read(this->numVerticesInLOD); - auto fixupsCount = stream.read(); - auto fixupsOffset = stream.read(); - auto verticesOffset = stream.read(); - auto tangentsOffset = stream.read(); + const auto fixupsCount = stream.read(); + const auto fixupsOffset = stream.read(); + const auto verticesOffset = stream.read(); + const auto tangentsOffset = stream.read(); stream.seek(verticesOffset); for (int i = 0; i < this->numVerticesInLOD[0]; i++) { - auto& vertex = this->vertices.emplace_back(); + auto& [boneWeight, position, normal, uv, tangent] = this->vertices.emplace_back(); - stream.read(vertex.boneWeight.weight); + stream.read(boneWeight.weight); std::array bones{}; stream.read(bones); - auto boneCount = stream.read(); + const auto boneCount = stream.read(); for (int8_t j = 0; j < boneCount && j < MAX_BONES_PER_VERTEX; j++) { - vertex.boneWeight.bones.push_back(bones[j]); + boneWeight.bones.push_back(bones[j]); } stream - .read(vertex.position) - .read(vertex.normal) - .read(vertex.uv); + .read(position) + .read(normal) + .read(uv); // tangents are assigned below } @@ -58,12 +58,8 @@ bool VVD::open(const std::byte* data, std::size_t size, const MDL::MDL& mdl) { stream.seek(fixupsOffset); for (int i = 0; i < fixupsCount; i++) { - auto& fixup = this->fixups.emplace_back(); - - stream - .read(fixup.LOD) - .read(fixup.sourceVertexID) - .read(fixup.vertexCount); + auto& [LOD, sourceVertexID, vertexCount] = this->fixups.emplace_back(); + stream >> LOD >> sourceVertexID >> vertexCount; } return true; diff --git a/src/sourcepp/FS.cpp b/src/sourcepp/FS.cpp index 83364a73a..529759b0c 100644 --- a/src/sourcepp/FS.cpp +++ b/src/sourcepp/FS.cpp @@ -4,8 +4,6 @@ #include -#include - using namespace sourcepp; std::vector fs::readFileBuffer(const std::string& filepath, std::size_t startOffset) { diff --git a/src/sourcepp/String.cpp b/src/sourcepp/String.cpp index db29cece8..0a2f5c241 100644 --- a/src/sourcepp/String.cpp +++ b/src/sourcepp/String.cpp @@ -127,7 +127,7 @@ std::string string::toUpper(std::string_view input) { std::string string::createRandom(uint16_t length, std::string_view chars) { auto& generator = ::getRandomGenerator(); - std::uniform_int_distribution<> distribution{0, static_cast(chars.length() - 1)}; + std::uniform_int_distribution distribution{0, static_cast(chars.length() - 1)}; std::string out; for (uint16_t i = 0; i < length; i++) { @@ -141,7 +141,7 @@ std::string string::generateUUIDv4() { static constexpr std::string_view chars = "0123456789abcdef"; auto& generator = ::getRandomGenerator(); - std::uniform_int_distribution<> distribution{0, static_cast(chars.length() - 1)}; + std::uniform_int_distribution distribution{0, static_cast(chars.length() - 1)}; std::string out; for (uint16_t i = 0; i < 8; i++) { @@ -162,7 +162,7 @@ std::string string::generateUUIDv4() { } std::string string::padNumber(int64_t number, int width, char pad) { - auto numStr = std::to_string(number); + const auto numStr = std::to_string(number); return std::string(width - std::min(width, numStr.length()), pad) + numStr; } @@ -188,7 +188,7 @@ void string::denormalizeSlashes(std::string& path, bool stripSlashPrefix, bool s std::from_chars_result string::toBool(std::string_view number, bool& out, int base) { uint8_t tmp; - auto result = std::from_chars(number.data(), number.data() + number.size(), tmp, base); + const auto result = std::from_chars(number.data(), number.data() + number.size(), tmp, base); out = tmp; return result; } diff --git a/src/sourcepp/crypto/RSA.cpp b/src/sourcepp/crypto/RSA.cpp index c7517a4ca..8f4a8227b 100644 --- a/src/sourcepp/crypto/RSA.cpp +++ b/src/sourcepp/crypto/RSA.cpp @@ -28,7 +28,7 @@ std::pair crypto::computeSHA256KeyPair(uint16_t size) } bool crypto::verifySHA256PublicKey(const std::vector& buffer, const std::vector& publicKey, const std::vector& signature) { - CryptoPP::RSASS::Verifier verifier{ + const CryptoPP::RSASS::Verifier verifier{ CryptoPP::VectorSource(reinterpret_cast&>(publicKey), true).Ref() }; return verifier.VerifyMessage(reinterpret_cast(buffer.data()), buffer.size(), @@ -38,7 +38,7 @@ bool crypto::verifySHA256PublicKey(const std::vector& buffer, const s std::vector crypto::signDataWithSHA256PrivateKey(const std::vector& buffer, const std::vector& privateKey) { CryptoPP::AutoSeededRandomPool rng; - CryptoPP::RSASS::Signer signer{ + const CryptoPP::RSASS::Signer signer{ CryptoPP::VectorSource(reinterpret_cast&>(privateKey), true).Ref() }; diff --git a/src/sourcepp/parser/Binary.cpp b/src/sourcepp/parser/Binary.cpp index ce0852693..dccda20dc 100644 --- a/src/sourcepp/parser/Binary.cpp +++ b/src/sourcepp/parser/Binary.cpp @@ -5,13 +5,13 @@ using namespace sourcepp; void parser::binary::readStringAtOffset(BufferStream& stream, std::string& str, std::ios::seekdir offsetFrom, std::size_t subtractFromOffset) { - int offset = stream.read(); + const auto offset = stream.read(); if (offset == 0) { str = ""; return; } - auto pos = stream.tell(); + const auto pos = stream.tell(); stream.seek(offset - static_cast(subtractFromOffset), offsetFrom); stream.read(str); stream.seek_u(pos); diff --git a/src/sourcepp/parser/Text.cpp b/src/sourcepp/parser/Text.cpp index 2578ed55a..354892b45 100644 --- a/src/sourcepp/parser/Text.cpp +++ b/src/sourcepp/parser/Text.cpp @@ -120,9 +120,8 @@ void parser::text::eatWhitespaceAndComments(BufferStream& stream, std::string_vi eatSingleLineComment(stream); eatWhitespaceAndComments(stream, singleLineCommentStart, multiLineCommentStart); return; - } else { - stream.seek(-static_cast(singleLineCommentStart.length()), std::ios::cur); } + stream.seek(-static_cast(singleLineCommentStart.length()), std::ios::cur); } if (!multiLineCommentStart.empty()) { @@ -130,9 +129,8 @@ void parser::text::eatWhitespaceAndComments(BufferStream& stream, std::string_vi eatMultiLineComment(stream); eatWhitespaceAndComments(stream, singleLineCommentStart, multiLineCommentStart); return; - } else { - stream.seek(-static_cast(multiLineCommentStart.length()), std::ios::cur); } + stream.seek(-static_cast(multiLineCommentStart.length()), std::ios::cur); } } @@ -145,7 +143,7 @@ bool parser::text::tryToEatChar(BufferStream& stream, char c) { } std::string_view parser::text::readStringToBuffer(BufferStream& stream, BufferStream& backing, std::string_view start, std::string_view end, const EscapeSequenceMap& escapeSequences) { - auto startSpan = backing.tell(); + const auto startSpan = backing.tell(); bool stopAtWhitespace = true; char c = stream.read(); @@ -182,7 +180,7 @@ std::string_view parser::text::readUnquotedStringToBuffer(BufferStream& stream, } std::string_view parser::text::readUnquotedStringToBuffer(BufferStream& stream, BufferStream& backing, std::string_view end, const EscapeSequenceMap& escapeSequences) { - auto startSpan = backing.tell(); + const auto startSpan = backing.tell(); for (char c = stream.read(); !isWhitespace(c) && end.find(c) == std::string_view::npos; c = stream.read()) { if (!escapeSequences.empty() && c == '\\') { diff --git a/src/steampp/steampp.cpp b/src/steampp/steampp.cpp index 1042c1df6..36c10636a 100644 --- a/src/steampp/steampp.cpp +++ b/src/steampp/steampp.cpp @@ -5,7 +5,6 @@ #include #include -#include #include #include #include @@ -43,8 +42,8 @@ bool isAppUsingSource2EnginePredicate(std::string_view installDir) { return true; } std::filesystem::directory_iterator subDirIterator{entry.path(), std::filesystem::directory_options::skip_permission_denied}; - return std::any_of(std::filesystem::begin(subDirIterator), std::filesystem::end(subDirIterator), [](const auto& entry) { - return entry.is_directory() && std::filesystem::exists(entry.path() / "gameinfo.gi"); + return std::any_of(std::filesystem::begin(subDirIterator), std::filesystem::end(subDirIterator), [](const auto& entry_) { + return entry_.is_directory() && std::filesystem::exists(entry_.path() / "gameinfo.gi"); }); }); } @@ -55,7 +54,8 @@ std::unordered_set getAppsKnownToUseEngine(bool(*p)(std::string_view)) { return { #include "cache/EngineSource.inl" }; - } else if (p == &::isAppUsingSource2EnginePredicate) { + } + if (p == &::isAppUsingSource2EnginePredicate) { return { #include "cache/EngineSource2.inl" }; @@ -79,7 +79,7 @@ bool isAppUsingEngine(const Steam* steam, AppID appID) { return false; } - auto installDir = steam->getAppInstallDir(appID); + const auto installDir = steam->getAppInstallDir(appID); if (std::error_code ec; !std::filesystem::exists(installDir, ec)) [[unlikely]] { return false; } @@ -149,9 +149,8 @@ Steam::Steam() { } if (location.empty()) { return; - } else { - steamLocation = location; } + steamLocation = location; } #endif diff --git a/src/toolpp/CmdSeq.cpp b/src/toolpp/CmdSeq.cpp index ba11869bc..a2e06a3ea 100644 --- a/src/toolpp/CmdSeq.cpp +++ b/src/toolpp/CmdSeq.cpp @@ -21,24 +21,24 @@ std::vector bakeBinary(const CmdSeq& cmdSeq) { .write(cmdSeq.getVersion()) .write(cmdSeq.getSequences().size()); - for (const auto& sequence : cmdSeq.getSequences()) { + for (const auto& [seqName, seqCommands] : cmdSeq.getSequences()) { writer - .write(sequence.name, true, 128) - .write(sequence.commands.size()); + .write(seqName, true, 128) + .write(seqCommands.size()); - for (const auto& command : sequence.commands) { + for (const auto& [enabled, special, executable, arguments, ensureFileExists, pathToTheoreticallyExistingFile, useProcessWindow, waitForKeypress] : seqCommands) { writer - .write(command.enabled) - .write(command.special) - .write(command.executable, true, 260) - .write(command.arguments, true, 260) + .write(enabled) + .write(special) + .write(executable, true, 260) + .write(arguments, true, 260) .write(true) - .write(command.ensureFileExists) - .write(command.pathToTheoreticallyExistingFile, true, 260) - .write(command.useProcessWindow); + .write(ensureFileExists) + .write(pathToTheoreticallyExistingFile, true, 260) + .write(useProcessWindow); if (cmdSeq.getVersion() > 0.15f) { - writer.write(command.waitForKeypress); + writer.write(waitForKeypress); } } } @@ -50,19 +50,19 @@ std::vector bakeBinary(const CmdSeq& cmdSeq) { std::vector bakeKeyValues(const CmdSeq& cmdSeq) { KV1Writer kv; auto& kvFile = kv.addChild("Command Sequences"); - for (const auto& sequence : cmdSeq.getSequences()) { - auto& kvSequence = kvFile.addChild(sequence.name); - for (int i = 1; i <= sequence.commands.size(); i++) { - const auto& command = sequence.commands[i - 1]; + for (const auto& [seqName, seqCommands] : cmdSeq.getSequences()) { + auto& kvSequence = kvFile.addChild(seqName); + for (int i = 1; i <= seqCommands.size(); i++) { + const auto& [enabled, special, executable, arguments, ensureFileExists, pathToTheoreticallyExistingFile, useProcessWindow, waitForKeypress] = seqCommands[i - 1]; auto& kvCommand = kvSequence.addChild(std::to_string(i)); - kvCommand["enabled"] = command.enabled; - kvCommand["special_cmd"] = static_cast(command.special); - kvCommand["run"] = command.executable; - kvCommand["params"] = command.arguments; - kvCommand["ensure_check"] = command.ensureFileExists; - kvCommand["ensure_fn"] = command.pathToTheoreticallyExistingFile; - kvCommand["use_process_wnd"] = command.useProcessWindow; - kvCommand["no_wait"] = command.waitForKeypress; + kvCommand["enabled"] = enabled; + kvCommand["special_cmd"] = static_cast(special); + kvCommand["run"] = executable; + kvCommand["params"] = arguments; + kvCommand["ensure_check"] = ensureFileExists; + kvCommand["ensure_fn"] = pathToTheoreticallyExistingFile; + kvCommand["use_process_wnd"] = useProcessWindow; + kvCommand["no_wait"] = waitForKeypress; } } @@ -114,55 +114,55 @@ void CmdSeq::setVersion(bool isV02) { } } -void CmdSeq::parseBinary(const std::string& path_) { - FileStream reader{path_}; +void CmdSeq::parseBinary(const std::string& path) { + FileStream reader{path}; if (!reader) { return; } reader.seek_in(31).read(this->version); - auto sequenceCount = reader.read(); + const auto sequenceCount = reader.read(); for (uint32_t s = 0; s < sequenceCount; s++) { - auto& sequence = this->sequences.emplace_back(); - sequence.name = reader.read_string(128); + auto& [seqName, seqCommands] = this->sequences.emplace_back(); + seqName = reader.read_string(128); - auto commandCount = reader.read(); + const auto commandCount = reader.read(); for (uint32_t c = 0; c < commandCount; c++) { - auto& command = sequence.commands.emplace_back(); - command.enabled = reader.read() & 0xFF; - command.special = reader.read(); - command.executable = reader.read_string(260); - command.arguments = reader.read_string(260); + auto& [enabled, special, executable, arguments, ensureFileExists, pathToTheoreticallyExistingFile, useProcessWindow, waitForKeypress] = seqCommands.emplace_back(); + enabled = reader.read() & 0xFF; + special = reader.read(); + executable = reader.read_string(260); + arguments = reader.read_string(260); reader.skip_in(); - command.ensureFileExists = reader.read(); - command.pathToTheoreticallyExistingFile = reader.read_string(260); - command.useProcessWindow = reader.read(); + ensureFileExists = reader.read(); + pathToTheoreticallyExistingFile = reader.read_string(260); + useProcessWindow = reader.read(); if (version > 0.15f) { - command.waitForKeypress = reader.read(); + waitForKeypress = reader.read(); } } } } -void CmdSeq::parseKeyValues(const std::string& path_) { +void CmdSeq::parseKeyValues(const std::string& path) { this->version = 0.2f; - KV1 cmdSeq{fs::readFileText(path_)}; + const KV1 cmdSeq{fs::readFileText(path)}; for (const auto& kvSequence : cmdSeq["Command Sequences"].getChildren()) { - auto& sequence = this->sequences.emplace_back(); - sequence.name = kvSequence.getKey(); + auto& [seqName, seqCommands] = this->sequences.emplace_back(); + seqName = kvSequence.getKey(); for (const auto& kvCommand : kvSequence.getChildren()) { - auto& command = sequence.commands.emplace_back(); - string::toBool(kvCommand["enabled"].getValue(), command.enabled); - string::toInt(kvCommand["special_cmd"].getValue(), reinterpret_cast&>(command.special)); - command.executable = kvCommand["run"].getValue(); - command.arguments = kvCommand["params"].getValue(); - string::toBool(kvCommand["ensure_check"].getValue(), command.ensureFileExists); - command.pathToTheoreticallyExistingFile = kvCommand["ensure_fn"].getValue(); - string::toBool(kvCommand["use_process_wnd"].getValue(), command.useProcessWindow); - string::toBool(kvCommand["no_wait"].getValue(), command.waitForKeypress); + auto& [enabled, special, executable, arguments, ensureFileExists, pathToTheoreticallyExistingFile, useProcessWindow, waitForKeypress] = seqCommands.emplace_back(); + string::toBool(kvCommand["enabled"].getValue(), enabled); + string::toInt(kvCommand["special_cmd"].getValue(), reinterpret_cast&>(special)); + executable = kvCommand["run"].getValue(); + arguments = kvCommand["params"].getValue(); + string::toBool(kvCommand["ensure_check"].getValue(), ensureFileExists); + pathToTheoreticallyExistingFile = kvCommand["ensure_fn"].getValue(); + string::toBool(kvCommand["use_process_wnd"].getValue(), useProcessWindow); + string::toBool(kvCommand["no_wait"].getValue(), waitForKeypress); } } } diff --git a/src/toolpp/FGD.cpp b/src/toolpp/FGD.cpp index 594c5029a..f9f955ca8 100644 --- a/src/toolpp/FGD.cpp +++ b/src/toolpp/FGD.cpp @@ -15,8 +15,8 @@ using namespace toolpp; namespace { -constexpr const char* INVALID_SYNTAX_MSG = "Invalid syntax found in FGD!"; -constexpr const char* INVALID_CLASS_MSG = "Invalid class found in FGD!"; +constexpr auto INVALID_SYNTAX_MSG = "Invalid syntax found in FGD!"; +constexpr auto INVALID_CLASS_MSG = "Invalid class found in FGD!"; [[nodiscard]] bool tryToEatSeparator(BufferStream& stream, char sep) { parser::text::eatWhitespaceAndSingleLineComments(stream); @@ -30,12 +30,12 @@ constexpr const char* INVALID_CLASS_MSG = "Invalid class found in FGD!"; static constexpr std::string_view END = "\"\n"; - auto startSpan = backing.tell(); + const auto startSpan = backing.tell(); while (true) { char c = stream.read(); if (c != '\"') { stream.seek(-1, std::ios::cur); - auto out = parser::text::readUnquotedStringToBuffer(stream, backing, ":", parser::text::NO_ESCAPE_SEQUENCES); + const auto out = parser::text::readUnquotedStringToBuffer(stream, backing, ":", parser::text::NO_ESCAPE_SEQUENCES); if (stream.seek(-1, std::ios::cur).peek() != ':') { stream.skip(); parser::text::eatWhitespaceAndSingleLineComments(stream); @@ -96,7 +96,7 @@ void readMapSize(BufferStreamReadOnly& stream, BufferStream& backing, math::Vec2 throw parser::text::syntax_error{INVALID_SYNTAX_MSG}; } } - auto mapSizeString = parser::text::readStringToBuffer(stream, backing, "(", ")", parser::text::NO_ESCAPE_SEQUENCES); + const auto mapSizeString = parser::text::readStringToBuffer(stream, backing, "(", ")", parser::text::NO_ESCAPE_SEQUENCES); auto mapSizes = string::split(mapSizeString, ','); if (mapSizes.size() != 2) { throw parser::text::syntax_error{INVALID_SYNTAX_MSG}; @@ -122,7 +122,7 @@ void readAutoVisGroups(BufferStreamReadOnly& stream, BufferStream& backing, std: if (!::tryToEatSeparator(stream, '=')) { throw parser::text::syntax_error{INVALID_SYNTAX_MSG}; } - auto parentName = ::readFGDString(stream, backing); + const auto parentName = ::readFGDString(stream, backing); if (!::tryToEatSeparator(stream, '[')) { throw parser::text::syntax_error{INVALID_SYNTAX_MSG}; } @@ -192,7 +192,7 @@ void readEntityFieldModifiers(BufferStreamReadOnly& stream, BufferStream& backin parser::text::eatWhitespace(stream); if (stream.peek() == 'r') { - if (auto modifier = parser::text::readUnquotedStringToBuffer(stream, backing); modifier == "readonly") { + if (const auto modifier = parser::text::readUnquotedStringToBuffer(stream, backing); modifier == "readonly") { readonly = true; } else if (modifier == "report") { reportable = true; @@ -204,27 +204,28 @@ void readEntityFieldModifiers(BufferStreamReadOnly& stream, BufferStream& backin } parser::text::eatWhitespace(stream); if (stream.peek() == 'r') { - if (auto modifier = parser::text::readUnquotedStringToBuffer(stream, backing); modifier == "report") { + if (const auto modifier = parser::text::readUnquotedStringToBuffer(stream, backing); modifier == "report") { reportable = true; } else { stream.seek(-static_cast(modifier.length()), std::ios::cur); - return; + //return; } } } void readEntityKeyValue(BufferStreamReadOnly& stream, BufferStream& backing, FGD::Entity& entity) { // Key and value type (looks like "key(valueType)", or "input key(valueType)" for i/o) - auto name = parser::text::readUnquotedStringToBuffer(stream, backing, "(", parser::text::NO_ESCAPE_SEQUENCES); + const auto name = parser::text::readUnquotedStringToBuffer(stream, backing, "(", parser::text::NO_ESCAPE_SEQUENCES); parser::text::eatWhitespace(stream); if (string::iequals(name, "input")) { ::readEntityIO(stream, backing, entity, true); return; - } else if (string::iequals(name, "output")) { + } + if (string::iequals(name, "output")) { ::readEntityIO(stream, backing, entity, false); return; } - auto valueType = parser::text::readUnquotedStringToBuffer(stream, backing, ")", parser::text::NO_ESCAPE_SEQUENCES); + const auto valueType = parser::text::readUnquotedStringToBuffer(stream, backing, ")", parser::text::NO_ESCAPE_SEQUENCES); // If there is a space after the value type, we need to get rid of the parenthesis here parser::text::eatWhitespace(stream); if (stream.peek() == ')') { @@ -287,7 +288,7 @@ void readEntityKeyValue(BufferStreamReadOnly& stream, BufferStream& backing, FGD while (stream.peek() != ']') { auto& flag = field.flags.emplace_back(); - auto valueString = ::readFGDString(stream, backing); + const auto valueString = ::readFGDString(stream, backing); if (string::toInt(valueString, flag.value).ec != std::errc{}) { flag.value = 0; } @@ -300,7 +301,7 @@ void readEntityKeyValue(BufferStreamReadOnly& stream, BufferStream& backing, FGD if (!::tryToEatSeparator(stream, ':')) { continue; } - auto enabledByDefaultString = ::readFGDString(stream, backing); + const auto enabledByDefaultString = ::readFGDString(stream, backing); int enabledByDefault = 0; if (string::toInt(enabledByDefaultString, enabledByDefault).ec != std::errc{}) { flag.enabledByDefault = false; @@ -349,7 +350,7 @@ void overwriteEntity(FGD::Entity& oldEntity, FGD::Entity& newEntity) { } for (const auto& field : newEntity.fields) { if (auto it = std::find_if(oldEntity.fields.begin(), oldEntity.fields.end(), [&field](const auto& oldField) { - return oldField.name == field.name; + return oldField.name == field.name; }); it != oldEntity.fields.end()) { it->valueType = field.valueType; it->readonly = field.readonly; @@ -369,7 +370,7 @@ void overwriteEntity(FGD::Entity& oldEntity, FGD::Entity& newEntity) { } for (const auto& field : newEntity.fieldsWithChoices) { if (auto it = std::find_if(oldEntity.fieldsWithChoices.begin(), oldEntity.fieldsWithChoices.end(), [&field](const auto& oldField) { - return oldField.name == field.name; + return oldField.name == field.name; }); it != oldEntity.fieldsWithChoices.end()) { it->readonly = field.readonly; it->reportable = field.reportable; @@ -389,7 +390,7 @@ void overwriteEntity(FGD::Entity& oldEntity, FGD::Entity& newEntity) { } for (const auto& field : newEntity.fieldsWithFlags) { if (auto it = std::find_if(oldEntity.fieldsWithFlags.begin(), oldEntity.fieldsWithFlags.end(), [&field](const auto& oldField) { - return oldField.name == field.name; + return oldField.name == field.name; }); it != oldEntity.fieldsWithFlags.end()) { it->readonly = field.readonly; it->reportable = field.reportable; @@ -400,7 +401,7 @@ void overwriteEntity(FGD::Entity& oldEntity, FGD::Entity& newEntity) { } for (const auto& input : newEntity.inputs) { if (auto it = std::find_if(oldEntity.inputs.begin(), oldEntity.inputs.end(), [&input](const auto& oldInput) { - return oldInput.name == input.name; + return oldInput.name == input.name; }); it != oldEntity.inputs.end()) { it->valueType = input.valueType; if (!input.description.empty()) { @@ -412,7 +413,7 @@ void overwriteEntity(FGD::Entity& oldEntity, FGD::Entity& newEntity) { } for (const auto& output : newEntity.outputs) { if (auto it = std::find_if(oldEntity.outputs.begin(), oldEntity.outputs.end(), [&output](const auto& oldOutput) { - return oldOutput.name == output.name; + return oldOutput.name == output.name; }); it != oldEntity.outputs.end()) { it->valueType = output.valueType; if (!output.description.empty()) { @@ -435,7 +436,7 @@ void readEntity(BufferStreamReadOnly& stream, BufferStream& backing, std::string // Entity name parser::text::eatWhitespaceAndSingleLineComments(stream); - auto name = ::readFGDString(stream, backing); + const auto name = ::readFGDString(stream, backing); // If a colon is here, the entity has a description if (::tryToEatSeparator(stream, ':')) { @@ -498,7 +499,7 @@ void FGD::load(const std::string& fgdPath) { BufferStreamReadOnly stream{fgdData}; try { - std::vector seenPaths{fgdPath}; + std::vector seenPaths{fgdPath}; string::normalizeSlashes(seenPaths.front()); this->readEntities(stream, fgdPath, seenPaths); } catch (const std::overflow_error&) {} @@ -539,7 +540,7 @@ void FGD::readEntities(BufferStreamReadOnly& stream, const std::string& path, st throw parser::text::syntax_error{INVALID_SYNTAX_MSG}; } - auto classType = parser::text::readUnquotedStringToBuffer(stream, backing, "(", parser::text::NO_ESCAPE_SEQUENCES); + const auto classType = parser::text::readUnquotedStringToBuffer(stream, backing, "(", parser::text::NO_ESCAPE_SEQUENCES); if (string::iequals(classType, "include")) { parser::text::eatWhitespace(stream); // Assume the include path is relative to the current file being processed @@ -662,7 +663,7 @@ FGDWriter::AutoVisGroupWriter& FGDWriter::AutoVisGroupWriter::visGroup(const std return *this; } -FGDWriter& FGDWriter::AutoVisGroupWriter::endAutoVisGroup() { +FGDWriter& FGDWriter::AutoVisGroupWriter::endAutoVisGroup() const { this->parent.writer.write("]\n\n", 3); return this->parent; } @@ -744,7 +745,7 @@ FGDWriter::EntityWriter::KeyValueChoicesWriter& FGDWriter::EntityWriter::KeyValu return *this; } -FGDWriter::EntityWriter& FGDWriter::EntityWriter::KeyValueChoicesWriter::endKeyValueChoices() { +FGDWriter::EntityWriter& FGDWriter::EntityWriter::KeyValueChoicesWriter::endKeyValueChoices() const { this->parent.parent.writer.write("\t]\n", 3); return this->parent; } @@ -783,7 +784,7 @@ FGDWriter::EntityWriter::KeyValueFlagsWriter& FGDWriter::EntityWriter::KeyValueF return *this; } -FGDWriter::EntityWriter& FGDWriter::EntityWriter::KeyValueFlagsWriter::endKeyValueFlags() { +FGDWriter::EntityWriter& FGDWriter::EntityWriter::KeyValueFlagsWriter::endKeyValueFlags() const { this->parent.parent.writer.write("\t]\n", 3); return this->parent; } @@ -824,7 +825,7 @@ FGDWriter::EntityWriter& FGDWriter::EntityWriter::output(const std::string& name return *this; } -FGDWriter& FGDWriter::EntityWriter::endEntity() { +FGDWriter& FGDWriter::EntityWriter::endEntity() const { this->parent.writer.write("]\n\n", 3); return this->parent; } diff --git a/src/vpkpp/format/BSP.cpp b/src/vpkpp/format/BSP.cpp index fa5f0b760..a9f02dc6a 100644 --- a/src/vpkpp/format/BSP.cpp +++ b/src/vpkpp/format/BSP.cpp @@ -2,11 +2,10 @@ #include +#include #include #include #include - -#include #include #include @@ -90,8 +89,8 @@ std::unique_ptr BSP::open(const std::string& path, const EntryCallback bool BSP::bake(const std::string& outputDir_, BakeOptions options, const EntryCallback& callback) { // Get the proper file output folder - std::string outputDir = this->getBakeOutputDir(outputDir_); - std::string outputPath = outputDir + '/' + this->getFilename(); + const std::string outputDir = this->getBakeOutputDir(outputDir_); + const std::string outputPath = outputDir + '/' + this->getFilename(); // If the output path is different, copy the entire BSP there if (outputPath != this->fullFilePath) { diff --git a/src/vpkpp/format/FPX.cpp b/src/vpkpp/format/FPX.cpp index 96a5b3b23..e0eb08d57 100644 --- a/src/vpkpp/format/FPX.cpp +++ b/src/vpkpp/format/FPX.cpp @@ -1,7 +1,6 @@ #include #include - #include using namespace vpkpp; @@ -30,7 +29,7 @@ std::unique_ptr FPX::open(const std::string& path, const EntryCallback auto fpx = FPX::openInternal(path, callback); if (!fpx && path.length() > 8) { // If it just tried to load a numbered archive, let's try to load the directory FPX - if (auto dirPath = path.substr(0, path.length() - 8) + FPX_DIR_SUFFIX.data() + std::filesystem::path{path}.extension().string(); std::filesystem::exists(dirPath)) { + if (const auto dirPath = path.substr(0, path.length() - 8) + FPX_DIR_SUFFIX.data() + std::filesystem::path{path}.extension().string(); std::filesystem::exists(dirPath)) { fpx = FPX::openInternal(dirPath, callback); } } diff --git a/src/vpkpp/format/GCF.cpp b/src/vpkpp/format/GCF.cpp index f5e3aa2f2..b1bacb5bd 100644 --- a/src/vpkpp/format/GCF.cpp +++ b/src/vpkpp/format/GCF.cpp @@ -4,10 +4,8 @@ #include #include - #include #include -#include using namespace sourcepp; using namespace vpkpp; diff --git a/src/vpkpp/format/GMA.cpp b/src/vpkpp/format/GMA.cpp index 62cdf93c0..67bf35896 100644 --- a/src/vpkpp/format/GMA.cpp +++ b/src/vpkpp/format/GMA.cpp @@ -3,7 +3,6 @@ #include #include - #include #include @@ -83,7 +82,7 @@ bool GMA::verifyPackFileChecksum() const { return true; } - auto checksum = *(reinterpret_cast(data.data() + data.size()) - 1); + const auto checksum = *(reinterpret_cast(data.data() + data.size()) - 1); data.pop_back(); data.pop_back(); data.pop_back(); diff --git a/src/vpkpp/format/PAK.cpp b/src/vpkpp/format/PAK.cpp index 1645edcea..a696879de 100644 --- a/src/vpkpp/format/PAK.cpp +++ b/src/vpkpp/format/PAK.cpp @@ -4,9 +4,6 @@ #include -#include -#include - using namespace sourcepp; using namespace vpkpp; @@ -124,15 +121,15 @@ bool PAK::bake(const std::string& outputDir_, BakeOptions options, const EntryCa stream.write(PAK_SIGNATURE); // Index and size of directory - const uint32_t directoryIndex = sizeof(PAK_SIGNATURE) + sizeof(uint32_t) * 2; - stream.write(directoryIndex); + static constexpr uint32_t DIRECTORY_INDEX = sizeof(PAK_SIGNATURE) + sizeof(uint32_t) * 2; + stream.write(DIRECTORY_INDEX); const uint32_t directorySize = entriesToBake.size() * 64; stream.write(directorySize); // Directory for (const auto& [path, entry] : entriesToBake) { stream.write(path, false, PAK_FILENAME_MAX_SIZE); - stream.write(static_cast(entry->offset + directoryIndex + directorySize)); + stream.write(static_cast(entry->offset + DIRECTORY_INDEX + directorySize)); stream.write(static_cast(entry->length)); if (callback) { diff --git a/src/vpkpp/format/PCK.cpp b/src/vpkpp/format/PCK.cpp index dd3ff6946..e3b7e21d5 100644 --- a/src/vpkpp/format/PCK.cpp +++ b/src/vpkpp/format/PCK.cpp @@ -1,11 +1,10 @@ #include #include +#include #include - #include -#include using namespace sourcepp; using namespace vpkpp; @@ -235,7 +234,7 @@ bool PCK::bake(const std::string& outputDir_, BakeOptions options, const EntryCa // Dry-run to get the length of the directory section this->dataOffset = stream.tell_out(); - for (const auto& [path, entry] : entriesToBake) { + for (const auto& path : std::views::keys(entriesToBake)) { const auto entryPath = std::string{PCK_PATH_PREFIX} + path; const auto padding = math::getPaddingForAlignment(PCK_DIRECTORY_STRING_PADDING, static_cast(entryPath.length())); this->dataOffset += diff --git a/src/vpkpp/format/VPK.cpp b/src/vpkpp/format/VPK.cpp index 98e4ee504..2034a7cc9 100644 --- a/src/vpkpp/format/VPK.cpp +++ b/src/vpkpp/format/VPK.cpp @@ -86,7 +86,7 @@ std::unique_ptr VPK::open(const std::string& path, const EntryCallback auto vpk = VPK::openInternal(path, callback); if (!vpk && path.length() > 8) { // If it just tried to load a numbered archive, let's try to load the directory VPK - if (auto dirPath = path.substr(0, path.length() - 8) + VPK_DIR_SUFFIX.data() + std::filesystem::path{path}.extension().string(); std::filesystem::exists(dirPath)) { + if (const auto dirPath = path.substr(0, path.length() - 8) + VPK_DIR_SUFFIX.data() + std::filesystem::path{path}.extension().string(); std::filesystem::exists(dirPath)) { vpk = VPK::openInternal(dirPath, callback); } } @@ -315,7 +315,7 @@ std::optional> VPK::readEntry(const std::string& path_) c if (!entryLength) { return {}; } - std::vector out(entryLength, static_cast(0)); + std::vector out(entryLength, static_cast(0)); if (!entry->extraData.empty()) { std::copy(entry->extraData.begin(), entry->extraData.end(), out.begin()); @@ -356,7 +356,7 @@ std::optional> VPK::readEntry(const std::string& path_) c std::unique_ptr dDict{ ZSTD_createDDict(decompressionDict->data(), decompressionDict->size()), - [](void* dDict) { ZSTD_freeDDict(reinterpret_cast(dDict)); }, + [](void* dDict_) { ZSTD_freeDDict(static_cast(dDict_)); }, }; if (!dDict) { return std::nullopt; @@ -364,7 +364,7 @@ std::optional> VPK::readEntry(const std::string& path_) c std::unique_ptr dCtx{ ZSTD_createDCtx(), - [](void* dCtx) { ZSTD_freeDCtx(reinterpret_cast(dCtx)); }, + [](void* dCtx_) { ZSTD_freeDCtx(static_cast(dCtx_)); }, }; if (!dCtx) { return std::nullopt; @@ -419,7 +419,7 @@ void VPK::addEntryInternal(Entry& entry, const std::string& path, std::vector 0) { - auto clampedPreloadBytes = std::clamp(options.vpk_preloadBytes, 0u, buffer.size() > VPK_MAX_PRELOAD_BYTES ? VPK_MAX_PRELOAD_BYTES : static_cast(buffer.size())); + const auto clampedPreloadBytes = std::clamp(options.vpk_preloadBytes, 0u, buffer.size() > VPK_MAX_PRELOAD_BYTES ? VPK_MAX_PRELOAD_BYTES : static_cast(buffer.size())); entry.extraData.resize(clampedPreloadBytes); std::memcpy(entry.extraData.data(), buffer.data(), clampedPreloadBytes); buffer.erase(buffer.begin(), buffer.begin() + clampedPreloadBytes); @@ -437,8 +437,8 @@ void VPK::addEntryInternal(Entry& entry, const std::string& path, std::vectorcleanEntryPath(filename_); - if (auto entry = this->findEntry(filename); entry && (!entry->unbaked || entry->flags & VPK_FLAG_REUSING_CHUNK)) { + const auto filename = this->cleanEntryPath(filename_); + if (const auto entry = this->findEntry(filename); entry && (!entry->unbaked || entry->flags & VPK_FLAG_REUSING_CHUNK)) { this->freedChunks.push_back({entry->offset, entry->length, entry->archiveIndex}); } return PackFile::removeEntry(filename); @@ -475,7 +475,7 @@ bool VPK::bake(const std::string& outputDir_, BakeOptions options, const EntryCa cDict = { ZSTD_createCDict(compressionDict->data(), compressionDict->size(), options.zip_compressionStrength), - [](void* cDict) { ZSTD_freeCDict(reinterpret_cast(cDict)); }, + [](void* cDict_) { ZSTD_freeCDict(static_cast(cDict_)); }, }; if (!cDict) { return false; @@ -483,7 +483,7 @@ bool VPK::bake(const std::string& outputDir_, BakeOptions options, const EntryCa cCtx = { ZSTD_createCCtx(), - [](void* cCtx) { ZSTD_freeCCtx(reinterpret_cast(cCtx)); }, + [](void* cCtx_) { ZSTD_freeCCtx(static_cast(cCtx_)); }, }; if (!cCtx) { return false; @@ -499,7 +499,7 @@ bool VPK::bake(const std::string& outputDir_, BakeOptions options, const EntryCa if (extension.starts_with('.')) { extension = extension.substr(1); } - auto parentDir = fsPath.parent_path().string(); + const auto parentDir = fsPath.parent_path().string(); if (extension.empty()) { extension = " "; @@ -606,7 +606,7 @@ bool VPK::bake(const std::string& outputDir_, BakeOptions options, const EntryCa if (ZSTD_isError(compressedSize) || compressedData.size() < compressedSize) { return false; } - stream.write(std::span{compressedData.data(), compressedSize}); + stream.write(std::span{compressedData.data(), compressedSize}); entry->compressedLength = compressedSize; } #endif @@ -679,11 +679,11 @@ bool VPK::bake(const std::string& outputDir_, BakeOptions options, const EntryCa this->md5Entries.clear(); if (options.vpk_generateMD5Entries) { this->runForAllEntries([this](const std::string& path, const Entry& entry) { - auto binData = this->readEntry(path); + const auto binData = this->readEntry(path); if (!binData) { return; } - MD5Entry md5Entry{ + const MD5Entry md5Entry{ .archiveIndex = entry.archiveIndex, .offset = static_cast(entry.offset), .length = static_cast(entry.length - entry.extraData.size()), @@ -774,20 +774,19 @@ VPK::operator std::string() const { } bool VPK::generateKeyPairFiles(const std::string& name) { - auto keys = crypto::computeSHA256KeyPair(1024); + const auto [privateKey, publicKey] = crypto::computeSHA256KeyPair(1024); { auto privateKeyPath = name + ".privatekey.vdf"; FileStream stream{privateKeyPath, FileStream::OPT_TRUNCATE | FileStream::OPT_CREATE_IF_NONEXISTENT}; std::string output; // Template size, remove %s and %s, add key sizes, add null terminator size - output.resize(VPK_KEYPAIR_PRIVATE_KEY_TEMPLATE.size() - 4 + keys.first.size() + keys.second.size() + 1); - if (std::sprintf(output.data(), VPK_KEYPAIR_PRIVATE_KEY_TEMPLATE.data(), keys.first.data(), keys.second.data()) < 0) { + output.resize(VPK_KEYPAIR_PRIVATE_KEY_TEMPLATE.size() - 4 + privateKey.size() + publicKey.size() + 1); + if (std::sprintf(output.data(), VPK_KEYPAIR_PRIVATE_KEY_TEMPLATE.data(), privateKey.data(), publicKey.data()) < 0) { return false; - } else { - output.pop_back(); - stream.write(output, false); } + output.pop_back(); + stream.write(output, false); } { auto publicKeyPath = name + ".publickey.vdf"; @@ -795,13 +794,12 @@ bool VPK::generateKeyPairFiles(const std::string& name) { std::string output; // Template size, remove %s, add key size, add null terminator size - output.resize(VPK_KEYPAIR_PUBLIC_KEY_TEMPLATE.size() - 2 + keys.second.size() + 1); - if (std::sprintf(output.data(), VPK_KEYPAIR_PUBLIC_KEY_TEMPLATE.data(), keys.second.data()) < 0) { + output.resize(VPK_KEYPAIR_PUBLIC_KEY_TEMPLATE.size() - 2 + publicKey.size() + 1); + if (std::sprintf(output.data(), VPK_KEYPAIR_PUBLIC_KEY_TEMPLATE.data(), publicKey.data()) < 0) { return false; - } else { - output.pop_back(); - stream.write(output, false); } + output.pop_back(); + stream.write(output, false); } return true; } @@ -811,13 +809,13 @@ bool VPK::sign(const std::string& filename_) { return false; } - KV1 fileKV{fs::readFileText(filename_)}; + const KV1 fileKV{fs::readFileText(filename_)}; - auto privateKeyHex = fileKV["private_key"]["rsa_private_key"].getValue(); + const auto privateKeyHex = fileKV["private_key"]["rsa_private_key"].getValue(); if (privateKeyHex.empty()) { return false; } - auto publicKeyHex = fileKV["private_key"]["public_key"]["rsa_public_key"].getValue(); + const auto publicKeyHex = fileKV["private_key"]["public_key"]["rsa_public_key"].getValue(); if (publicKeyHex.empty()) { return false; } diff --git a/src/vpkpp/format/VPK_VTMB.cpp b/src/vpkpp/format/VPK_VTMB.cpp index 5ac92980b..28e570123 100644 --- a/src/vpkpp/format/VPK_VTMB.cpp +++ b/src/vpkpp/format/VPK_VTMB.cpp @@ -3,9 +3,7 @@ #include #include - #include -#include #include using namespace sourcepp; @@ -34,7 +32,7 @@ std::unique_ptr VPK_VTMB::open(const std::string& path, const EntryCal } // Extra check to make sure this is a VTMB VPK path - auto stem = std::filesystem::path{path}.stem().string(); + const auto stem = std::filesystem::path{path}.stem().string(); if (stem.length() != 7 || !stem.starts_with("pack") || !parser::text::isNumber(stem.substr(4))) { return nullptr; } diff --git a/src/vpkpp/format/WAD3.cpp b/src/vpkpp/format/WAD3.cpp index dff63ea44..91525ff81 100644 --- a/src/vpkpp/format/WAD3.cpp +++ b/src/vpkpp/format/WAD3.cpp @@ -19,8 +19,6 @@ #include #include - -#include #include using namespace sourcepp; @@ -193,9 +191,9 @@ bool WAD3::bake(const std::string& outputDir_, BakeOptions options, const EntryC // Convert the extension back into the type int type = 0; - std::size_t pos = path.find_last_of('.'); + const std::size_t pos = path.find_last_of('.'); if (pos > 0) { - std::string_view ext = path.c_str() + pos + 1; + const std::string_view ext = path.c_str() + pos + 1; for (int i = WFT_FIRST; i < WFT_COUNT; i++) { if (string::iequals(ext, k_FileTypeNames[i - WFT_FIRST])) { type = i; diff --git a/src/vpkpp/format/ZIP.cpp b/src/vpkpp/format/ZIP.cpp index dd90184fb..620d26bb9 100644 --- a/src/vpkpp/format/ZIP.cpp +++ b/src/vpkpp/format/ZIP.cpp @@ -13,7 +13,6 @@ #include #include -#include #include using namespace sourcepp; @@ -92,8 +91,8 @@ std::vector ZIP::verifyEntryChecksums() const { } std::optional> ZIP::readEntry(const std::string& path_) const { - auto path = this->cleanEntryPath(path_); - auto entry = this->findEntry(path); + const auto path = this->cleanEntryPath(path_); + const auto entry = this->findEntry(path); if (!entry) { return std::nullopt; } @@ -127,8 +126,8 @@ void ZIP::addEntryInternal(Entry& entry, const std::string& path, std::vectorgetBakeOutputDir(outputDir_); - std::string outputPath = outputDir + '/' + this->getFilename(); + const std::string outputDir = this->getBakeOutputDir(outputDir_); + const std::string outputPath = outputDir + '/' + this->getFilename(); // Use temp folder so we can read from the current ZIP if (!this->bakeTempZip(this->tempZIPPath, options, callback)) { @@ -152,7 +151,7 @@ Attribute ZIP::getSupportedEntryAttributes() const { } EntryCompressionType ZIP::getEntryCompressionType(const std::string& path_) const { - auto path = this->cleanEntryPath(path_); + const auto path = this->cleanEntryPath(path_); if (this->entries.count(path)) { return static_cast(this->entries.at(path).flags >> 16); } @@ -160,14 +159,14 @@ EntryCompressionType ZIP::getEntryCompressionType(const std::string& path_) cons } void ZIP::setEntryCompressionType(const std::string& path_, EntryCompressionType type) { - auto path = this->cleanEntryPath(path_); + const auto path = this->cleanEntryPath(path_); if (this->entries.count(path)) { this->entries.at(path).flags = (static_cast(type) << 16) | (this->entries.at(path).flags & 0xffff); } } uint16_t ZIP::getEntryCompressionStrength(const std::string& path_) const { - auto path = this->cleanEntryPath(path_); + const auto path = this->cleanEntryPath(path_); if (this->entries.count(path)) { return static_cast(this->entries.at(path).flags & 0xffff); } @@ -175,13 +174,13 @@ uint16_t ZIP::getEntryCompressionStrength(const std::string& path_) const { } void ZIP::setEntryCompressionStrength(const std::string& path_, uint16_t strength) { - auto path = this->cleanEntryPath(path_); + const auto path = this->cleanEntryPath(path_); if (this->entries.count(path)) { this->entries.at(path).flags = (this->entries.at(path).flags & 0xffff0000) | strength; } } -bool ZIP::bakeTempZip(const std::string& writeZipPath, BakeOptions options, const EntryCallback& callback) { +bool ZIP::bakeTempZip(const std::string& writeZipPath, BakeOptions options, const EntryCallback& callback) const { void* writeStreamHandle = mz_stream_os_create(); if (mz_stream_open(writeStreamHandle, writeZipPath.c_str(), MZ_OPEN_MODE_CREATE | MZ_OPEN_MODE_WRITE)) { return false; @@ -213,8 +212,7 @@ bool ZIP::bakeTempZip(const std::string& writeZipPath, BakeOptions options, cons mz_zip_writer_set_compress_level(writeZipHandle, (entry.flags & 0xffff) > 0 ? static_cast(entry.flags & 0xffff) : options.zip_compressionStrength); } - mz_zip_entry fileInfo; - std::memset(&fileInfo, 0, sizeof(mz_zip_entry)); + mz_zip_entry fileInfo{}; fileInfo.filename = path.c_str(); fileInfo.filename_size = path.length(); fileInfo.version_madeby = MZ_VERSION_MADEBY; diff --git a/src/vtfpp/ImageConversion.cpp b/src/vtfpp/ImageConversion.cpp index ee826f12e..e515555e5 100644 --- a/src/vtfpp/ImageConversion.cpp +++ b/src/vtfpp/ImageConversion.cpp @@ -274,7 +274,7 @@ namespace { std::vector newData; newData.resize(imageData.size() / (ImageFormatDetails::bpp(format) / 8) * (ImageFormatDetails::bpp(ImageFormat::RGBA8888) / 8)); - std::span newDataSpan{reinterpret_cast(newData.data()), newData.size() / sizeof(ImagePixel::RGBA8888)}; + std::span newDataSpan{reinterpret_cast(newData.data()), newData.size() / sizeof(ImagePixel::RGBA8888)}; #define VTFPP_REMAP_TO_8(value, shift) math::remap((value), (1 << (shift)) - 1, (1 << 8) - 1) @@ -336,7 +336,7 @@ namespace { return {imageData.begin(), imageData.end()}; } - std::span imageDataSpan{reinterpret_cast(imageData.data()), imageData.size() / sizeof(ImagePixel::RGBA8888)}; + std::span imageDataSpan{reinterpret_cast(imageData.data()), imageData.size() / sizeof(ImagePixel::RGBA8888)}; std::vector newData; newData.resize(imageData.size() / (ImageFormatDetails::bpp(ImageFormat::RGBA8888) / 8) * (ImageFormatDetails::bpp(format) / 8)); @@ -404,7 +404,7 @@ namespace { std::vector newData; newData.resize(imageData.size() / (ImageFormatDetails::bpp(format) / 8) * (ImageFormatDetails::bpp(ImageFormat::RGBA16161616) / 8)); - std::span newDataSpan{reinterpret_cast(newData.data()), newData.size() / sizeof(ImagePixel::RGBA16161616)}; + std::span newDataSpan{reinterpret_cast(newData.data()), newData.size() / sizeof(ImagePixel::RGBA16161616)}; #define VTFPP_REMAP_TO_16(value, shift) math::remap((value), (1 << (shift)) - 1, (1 << 16) - 1) @@ -475,7 +475,7 @@ namespace { return {imageData.begin(), imageData.end()}; } - std::span imageDataSpan{reinterpret_cast(imageData.data()), imageData.size() / sizeof(ImagePixel::RGBA16161616)}; + std::span imageDataSpan{reinterpret_cast(imageData.data()), imageData.size() / sizeof(ImagePixel::RGBA16161616)}; std::vector newData; newData.resize(imageData.size() / (ImageFormatDetails::bpp(ImageFormat::RGBA16161616) / 8) * (ImageFormatDetails::bpp(format) / 8)); @@ -522,7 +522,7 @@ namespace { std::vector newData; newData.resize(imageData.size() / (ImageFormatDetails::bpp(format) / 8) * (ImageFormatDetails::bpp(ImageFormat::RGBA32323232F) / 8)); - std::span newDataSpan{reinterpret_cast(newData.data()), newData.size() / sizeof(ImagePixel::RGBA32323232F)}; + std::span newDataSpan{reinterpret_cast(newData.data()), newData.size() / sizeof(ImagePixel::RGBA32323232F)}; #define VTFPP_CONVERT_DETAIL(InputType, r, g, b, a, ...) \ std::span imageDataSpan{reinterpret_cast(imageData.data()), imageData.size() / sizeof(ImagePixel::InputType)}; \ @@ -564,7 +564,7 @@ namespace { return {imageData.begin(), imageData.end()}; } - std::span imageDataSpan{reinterpret_cast(imageData.data()), imageData.size() / sizeof(ImagePixel::RGBA32323232F)}; + std::span imageDataSpan{reinterpret_cast(imageData.data()), imageData.size() / sizeof(ImagePixel::RGBA32323232F)}; std::vector newData; newData.resize(imageData.size() / (ImageFormatDetails::bpp(ImageFormat::RGBA32323232F) / 8) * (ImageFormatDetails::bpp(format) / 8)); @@ -608,9 +608,9 @@ namespace { std::vector newData; newData.resize(imageData.size() / (ImageFormatDetails::bpp(ImageFormat::RGBA8888) / 8) * (ImageFormatDetails::bpp(ImageFormat::RGBA32323232F) / 8)); - std::span newDataSpan{reinterpret_cast(newData.data()), newData.size() / sizeof(ImagePixel::RGBA32323232F)}; + std::span newDataSpan{reinterpret_cast(newData.data()), newData.size() / sizeof(ImagePixel::RGBA32323232F)}; - std::span imageDataSpan{reinterpret_cast(imageData.data()), imageData.size() / sizeof(ImagePixel::RGBA8888)}; \ + std::span imageDataSpan{reinterpret_cast(imageData.data()), imageData.size() / sizeof(ImagePixel::RGBA8888)}; \ std::transform( #ifdef SOURCEPP_BUILD_WITH_TBB std::execution::unseq, @@ -634,9 +634,9 @@ namespace { std::vector newData; newData.resize(imageData.size() / (ImageFormatDetails::bpp(ImageFormat::RGBA32323232F) / 8) * (ImageFormatDetails::bpp(ImageFormat::RGBA8888) / 8)); - std::span newDataSpan{reinterpret_cast(newData.data()), newData.size() / sizeof(ImagePixel::RGBA8888)}; + std::span newDataSpan{reinterpret_cast(newData.data()), newData.size() / sizeof(ImagePixel::RGBA8888)}; - std::span imageDataSpan{reinterpret_cast(imageData.data()), imageData.size() / sizeof(ImagePixel::RGBA32323232F)}; \ + std::span imageDataSpan{reinterpret_cast(imageData.data()), imageData.size() / sizeof(ImagePixel::RGBA32323232F)}; \ std::transform( #ifdef SOURCEPP_BUILD_WITH_TBB std::execution::unseq, @@ -660,9 +660,9 @@ namespace { std::vector newData; newData.resize(imageData.size() / (ImageFormatDetails::bpp(ImageFormat::RGBA8888) / 8) * (ImageFormatDetails::bpp(ImageFormat::RGBA16161616) / 8)); - std::span newDataSpan{reinterpret_cast(newData.data()), newData.size() / sizeof(ImagePixel::RGBA16161616)}; + std::span newDataSpan{reinterpret_cast(newData.data()), newData.size() / sizeof(ImagePixel::RGBA16161616)}; - std::span imageDataSpan{reinterpret_cast(imageData.data()), imageData.size() / sizeof(ImagePixel::RGBA8888)}; \ + std::span imageDataSpan{reinterpret_cast(imageData.data()), imageData.size() / sizeof(ImagePixel::RGBA8888)}; \ std::transform( #ifdef SOURCEPP_BUILD_WITH_TBB std::execution::unseq, @@ -686,9 +686,9 @@ namespace { std::vector newData; newData.resize(imageData.size() / (ImageFormatDetails::bpp(ImageFormat::RGBA16161616) / 8) * (ImageFormatDetails::bpp(ImageFormat::RGBA8888) / 8)); - std::span newDataSpan{reinterpret_cast(newData.data()), newData.size() / sizeof(ImagePixel::RGBA8888)}; + std::span newDataSpan{reinterpret_cast(newData.data()), newData.size() / sizeof(ImagePixel::RGBA8888)}; - std::span imageDataSpan{reinterpret_cast(imageData.data()), imageData.size() / sizeof(ImagePixel::RGBA16161616)}; \ + std::span imageDataSpan{reinterpret_cast(imageData.data()), imageData.size() / sizeof(ImagePixel::RGBA16161616)}; \ std::transform( #ifdef SOURCEPP_BUILD_WITH_TBB std::execution::unseq, @@ -712,9 +712,9 @@ namespace { std::vector newData; newData.resize(imageData.size() / (ImageFormatDetails::bpp(ImageFormat::RGBA32323232F) / 8) * (ImageFormatDetails::bpp(ImageFormat::RGBA16161616) / 8)); - std::span newDataSpan{reinterpret_cast(newData.data()), newData.size() / sizeof(ImagePixel::RGBA16161616)}; + std::span newDataSpan{reinterpret_cast(newData.data()), newData.size() / sizeof(ImagePixel::RGBA16161616)}; - std::span imageDataSpan{reinterpret_cast(imageData.data()), imageData.size() / sizeof(ImagePixel::RGBA32323232F)}; \ + std::span imageDataSpan{reinterpret_cast(imageData.data()), imageData.size() / sizeof(ImagePixel::RGBA32323232F)}; \ std::transform( #ifdef SOURCEPP_BUILD_WITH_TBB std::execution::unseq, @@ -738,9 +738,9 @@ namespace { std::vector newData; newData.resize(imageData.size() / (ImageFormatDetails::bpp(ImageFormat::RGBA16161616) / 8) * (ImageFormatDetails::bpp(ImageFormat::RGBA32323232F) / 8)); - std::span newDataSpan{reinterpret_cast(newData.data()), newData.size() / sizeof(ImagePixel::RGBA32323232F)}; + std::span newDataSpan{reinterpret_cast(newData.data()), newData.size() / sizeof(ImagePixel::RGBA32323232F)}; - std::span imageDataSpan{reinterpret_cast(imageData.data()), imageData.size() / sizeof(ImagePixel::RGBA16161616)}; \ + std::span imageDataSpan{reinterpret_cast(imageData.data()), imageData.size() / sizeof(ImagePixel::RGBA16161616)}; \ std::transform( #ifdef SOURCEPP_BUILD_WITH_TBB std::execution::unseq, @@ -770,7 +770,7 @@ std::vector ImageConversion::convertImageDataToFormat(std::span newData; - ImageFormat intermediaryOldFormat = ImageFormatDetails::containerFormat(oldFormat); + const ImageFormat intermediaryOldFormat = ImageFormatDetails::containerFormat(oldFormat); if (ImageFormatDetails::compressed(oldFormat)) { newData = ::convertImageDataUsingCompressonator(imageData, oldFormat, intermediaryOldFormat, width, height); } else if (intermediaryOldFormat == ImageFormat::RGBA8888) { @@ -787,7 +787,7 @@ std::vector ImageConversion::convertImageDataToFormat(std::span ImageConversion::convertImageDataToFile(std::span out; - auto stbWriteFunc = [](void* out, void* data, int size) { - std::copy(reinterpret_cast(data), reinterpret_cast(data) + size, std::back_inserter(*reinterpret_cast*>(out))); + auto stbWriteFunc = [](void* out_, void* data, int size) { + std::copy_n(static_cast(data), size, std::back_inserter(*static_cast*>(out_))); }; if (fileFormat == FileFormat::DEFAULT) { @@ -887,10 +887,10 @@ std::vector ImageConversion::convertImageDataToFile(std::span ImageConversion::convertImageDataToFile(std::span ImageConversion::convertImageDataToFile(std::span ImageConversion::convertImageDataToFile(std::span ImageConversion::convertFileToImageData(std::span(fileData.data()), static_cast(fileData.size()))) { - std::unique_ptr stbImage{ + const std::unique_ptr stbImage{ stbi_loadf_from_memory(reinterpret_cast(fileData.data()), static_cast(fileData.size()), &width, &height, &channels, 0), &stbi_image_free, }; @@ -970,8 +971,11 @@ std::vector ImageConversion::convertFileToImageData(std::span(stbImage.get()), reinterpret_cast(stbImage.get()) + ImageFormatDetails::getDataLength(format, width, height)}; - } else if (stbi_is_16_bit_from_memory(reinterpret_cast(fileData.data()), static_cast(fileData.size()))) { - std::unique_ptr stbImage{ + } + + // 16-bit single-frame image + if (stbi_is_16_bit_from_memory(reinterpret_cast(fileData.data()), static_cast(fileData.size()))) { + const std::unique_ptr stbImage{ stbi_load_16_from_memory(reinterpret_cast(fileData.data()), static_cast(fileData.size()), &width, &height, &channels, 0), &stbi_image_free, }; @@ -986,8 +990,11 @@ std::vector ImageConversion::convertFileToImageData(std::span(stbImage.get()), reinterpret_cast(stbImage.get()) + ImageFormatDetails::getDataLength(format, width, height)}; - } else if (fileData.size() >= 3 && static_cast(fileData[0]) == 'G' && static_cast(fileData[1]) == 'I' && static_cast(fileData[2]) == 'F') { - std::unique_ptr stbImage{ + } + + // 8-bit or less multi-frame image + if (fileData.size() >= 3 && static_cast(fileData[0]) == 'G' && static_cast(fileData[1]) == 'I' && static_cast(fileData[2]) == 'F') { + const std::unique_ptr stbImage{ stbi_load_gif_from_memory(reinterpret_cast(fileData.data()), static_cast(fileData.size()), nullptr, &width, &height, &frameCount, &channels, 0), &stbi_image_free, }; @@ -1004,25 +1011,26 @@ std::vector ImageConversion::convertFileToImageData(std::span(stbImage.get()), reinterpret_cast(stbImage.get() + (ImageFormatDetails::getDataLength(format, width, height) * frameCount))}; - } else { - std::unique_ptr stbImage{ - stbi_load_from_memory(reinterpret_cast(fileData.data()), static_cast(fileData.size()), &width, &height, &channels, 0), - &stbi_image_free, - }; - if (!stbImage) { - return {}; - } + } - switch (channels) { - case 1: format = ImageFormat::I8; break; - case 2: format = ImageFormat::UV88; break; - case 3: format = ImageFormat::RGB888; break; - case 4: format = ImageFormat::RGBA8888; break; - default: return {}; - } + // 8-bit or less single frame image + const std::unique_ptr stbImage{ + stbi_load_from_memory(reinterpret_cast(fileData.data()), static_cast(fileData.size()), &width, &height, &channels, 0), + &stbi_image_free, + }; + if (!stbImage) { + return {}; + } - return {reinterpret_cast(stbImage.get()), reinterpret_cast(stbImage.get()) + ImageFormatDetails::getDataLength(format, width, height)}; + switch (channels) { + case 1: format = ImageFormat::I8; break; + case 2: format = ImageFormat::UV88; break; + case 3: format = ImageFormat::RGB888; break; + case 4: format = ImageFormat::RGBA8888; break; + default: return {}; } + + return {reinterpret_cast(stbImage.get()), reinterpret_cast(stbImage.get()) + ImageFormatDetails::getDataLength(format, width, height)}; } uint16_t ImageConversion::getResizedDim(uint16_t n, ResizeMethod method) { diff --git a/src/vtfpp/PPL.cpp b/src/vtfpp/PPL.cpp index 5e6660bc6..c300de2c6 100644 --- a/src/vtfpp/PPL.cpp +++ b/src/vtfpp/PPL.cpp @@ -16,14 +16,14 @@ PPL::PPL(std::span pplData) { BufferStreamReadOnly reader{pplData.data(), pplData.size()}; reader >> this->version >> this->checksum >> this->format; - auto imageCount = reader.read(); + const auto imageCount = reader.read(); reader.skip(4); for (uint32_t i = 0; i < imageCount; i++) { - auto lod = reader.read(); - auto offset = reader.read(); - auto length = reader.read(); - auto width = reader.read(); - auto height = reader.read(); + const auto lod = reader.read(); + const auto offset = reader.read(); + const auto length = reader.read(); + const auto width = reader.read(); + const auto height = reader.read(); reader.skip(3); this->images[lod] = { @@ -88,11 +88,11 @@ std::optional PPL::getImageAs(ImageFormat newFormat, uint32_t lod) c if (!this->hasImageForLOD(lod)) { return std::nullopt; } - const auto& image = this->images.at(lod); + const auto& [width, height, data] = this->images.at(lod); return Image{ - .width = image.width, - .height = image.height, - .data = ImageConversion::convertImageDataToFormat(image.data, this->format, newFormat, image.width, image.height), + .width = width, + .height = height, + .data = ImageConversion::convertImageDataToFormat(data, this->format, newFormat, width, height), }; } @@ -164,7 +164,7 @@ bool PPL::setImage(const std::string& imagePath, uint32_t resizedWidth, uint32_t } std::vector PPL::saveImageToFile(uint32_t lod, ImageConversion::FileFormat fileFormat) const { - if (auto image = this->getImageRaw(lod)) { + if (const auto image = this->getImageRaw(lod)) { return ImageConversion::convertImageDataToFile(image->data, this->format, image->width, image->height, fileFormat); } return {}; @@ -198,7 +198,7 @@ std::vector PPL::bake() { for (int i = 0; i < 3; i++) { writer.write(0); } - auto seekPoint = writer.tell(); + const auto seekPoint = writer.tell(); writer.seek_u(currentOffset).write(image.data); const auto alignment = math::getPaddingForAlignment(ALIGNMENT, writer.tell()); for (int i = 0; i < alignment; i++) { diff --git a/src/vtfpp/VTF.cpp b/src/vtfpp/VTF.cpp index f62edcd8d..f7402f339 100644 --- a/src/vtfpp/VTF.cpp +++ b/src/vtfpp/VTF.cpp @@ -62,7 +62,7 @@ Resource::ConvertedData Resource::convertData() const { if (this->data.size() <= sizeof(uint32_t) || this->data.size() % sizeof(uint32_t) != 0) { return {}; } - return std::span{reinterpret_cast(this->data.data()), this->data.size() / 4}; + return std::span{reinterpret_cast(this->data.data()), this->data.size() / 4}; default: break; } @@ -146,17 +146,17 @@ VTF::VTF(std::vector&& vtfData, bool parseHeaderOnly) Resource* lastResource = nullptr; for (int i = 0; i < resourceCount; i++) { - auto& resource = this->resources.emplace_back(); + auto& [type, flags, data] = this->resources.emplace_back(); auto typeAndFlags = stream.read(); - resource.type = static_cast(typeAndFlags & 0xffffff); // last 3 bytes - resource.flags = static_cast(typeAndFlags >> 24); // first byte - resource.data = stream.read_span(4); + type = static_cast(typeAndFlags & 0xffffff); // last 3 bytes + flags = static_cast(typeAndFlags >> 24); // first byte + data = stream.read_span(4); - if (!(resource.flags & Resource::FLAG_LOCAL_DATA)) { + if (!(flags & Resource::FLAG_LOCAL_DATA)) { if (lastResource) { auto lastOffset = *reinterpret_cast(lastResource->data.data()); - auto currentOffset = *reinterpret_cast(resource.data.data()); + auto currentOffset = *reinterpret_cast(data.data()); auto curPos = stream.tell(); stream.seek(lastOffset); @@ -262,11 +262,11 @@ VTF& VTF::operator=(const VTF& other) { this->sliceCount = other.sliceCount; this->resources.clear(); - for (const auto& otherResource : other.resources) { - auto& resource = this->resources.emplace_back(); - resource.type = otherResource.type; - resource.flags = otherResource.flags; - resource.data = {this->data.data() + (otherResource.data.data() - other.data.data()), otherResource.data.size()}; + for (const auto& [otherType, otherFlags, otherData] : other.resources) { + auto& [type, flags, data] = this->resources.emplace_back(); + type = otherType; + flags = otherFlags; + data = {this->data.data() + (otherData.data() - other.data.data()), otherData.size()}; } this->compressionLevel = other.compressionLevel; @@ -433,7 +433,7 @@ void VTF::setSize(uint16_t newWidth, uint16_t newHeight, ImageConversion::Resize return; } auto newMipCount = this->mipCount; - if (auto recommendedCount = ImageDimensions::getRecommendedMipCountForDims(this->format, newWidth, newHeight); newMipCount > recommendedCount) { + if (const auto recommendedCount = ImageDimensions::getRecommendedMipCountForDims(this->format, newWidth, newHeight); newMipCount > recommendedCount) { newMipCount = recommendedCount; } this->regenerateImageData(this->format, newWidth, newHeight, newMipCount, this->frameCount, this->getFaceCount(), this->sliceCount, filter); @@ -472,7 +472,8 @@ ImageFormat VTF::getFormat() const { void VTF::setFormat(ImageFormat newFormat, ImageConversion::ResizeFilter filter) { if (newFormat == VTF::FORMAT_UNCHANGED || newFormat == this->format) { return; - } else if (newFormat == VTF::FORMAT_DEFAULT) { + } + if (newFormat == VTF::FORMAT_DEFAULT) { newFormat = this->getDefaultFormat(); } if (!this->hasImageData()) { @@ -480,7 +481,7 @@ void VTF::setFormat(ImageFormat newFormat, ImageConversion::ResizeFilter filter) return; } auto newMipCount = this->mipCount; - if (auto recommendedCount = ImageDimensions::getRecommendedMipCountForDims(newFormat, this->width, this->height); newMipCount > recommendedCount) { + if (const auto recommendedCount = ImageDimensions::getRecommendedMipCountForDims(newFormat, this->width, this->height); newMipCount > recommendedCount) { newMipCount = recommendedCount; } if (ImageFormatDetails::compressed(newFormat)) { @@ -498,7 +499,7 @@ bool VTF::setMipCount(uint8_t newMipCount) { if (!this->hasImageData()) { return false; } - if (auto recommended = ImageDimensions::getRecommendedMipCountForDims(this->format, this->width, this->height); newMipCount > recommended) { + if (const auto recommended = ImageDimensions::getRecommendedMipCountForDims(this->format, this->width, this->height); newMipCount > recommended) { newMipCount = recommended; if (newMipCount == 1) { return false; @@ -593,7 +594,8 @@ uint8_t VTF::getFaceCount() const { const auto expectedLength = ImageFormatDetails::getDataLength(this->format, this->mipCount, this->frameCount, 6, this->width, this->height, this->sliceCount); if (this->majorVersion == 7 && this->minorVersion >= 1 && this->minorVersion <= 4 && expectedLength < image->data.size()) { return 7; - } else if (expectedLength == image->data.size()) { + } + if (expectedLength == image->data.size()) { return 6; } return 1; @@ -654,8 +656,8 @@ void VTF::setReflectivity(sourcepp::math::Vec3f newReflectivity) { } void VTF::computeReflectivity() { - static constexpr auto getReflectivityForImage = [](VTF& vtf, uint16_t frame, uint8_t face, uint8_t faceCount, uint16_t slice) { - static constexpr auto getReflectivityForPixel = [](ImagePixel::RGBA8888* pixel) -> math::Vec3f { + static constexpr auto getReflectivityForImage = [](const VTF& vtf, uint16_t frame, uint8_t face, uint16_t slice) { + static constexpr auto getReflectivityForPixel = [](const ImagePixel::RGBA8888* pixel) -> math::Vec3f { // http://markjstock.org/doc/gsd_talk_11_notes.pdf page 11 math::Vec3f ref{static_cast(pixel->r), static_cast(pixel->g), static_cast(pixel->b)}; ref /= 255.f * 0.9f; @@ -684,8 +686,8 @@ void VTF::computeReflectivity() { for (int j = 0; j < this->frameCount; j++) { for (int k = 0; k < faceCount; k++) { for (int l = 0; l < this->sliceCount; l++) { - futures.push_back(std::async(std::launch::async, [this, j, k, faceCount, l] { - return getReflectivityForImage(*this, j, k, faceCount, l); + futures.push_back(std::async(std::launch::async, [this, j, k, l] { + return getReflectivityForImage(*this, j, k, l); })); if (std::thread::hardware_concurrency() > 0 && futures.size() >= std::thread::hardware_concurrency() * 2) { for (auto& future : futures) { @@ -702,14 +704,14 @@ void VTF::computeReflectivity() { } this->reflectivity /= this->frameCount * faceCount * this->sliceCount; } else { - this->reflectivity = getReflectivityForImage(*this, 0, 0, 1, 0); + this->reflectivity = getReflectivityForImage(*this, 0, 0, 0); } #else this->reflectivity = {}; for (int j = 0; j < this->frameCount; j++) { for (int k = 0; k < faceCount; k++) { for (int l = 0; l < this->sliceCount; l++) { - this->reflectivity += getReflectivityForImage(*this, j, k, faceCount, l); + this->reflectivity += getReflectivityForImage(*this, j, k, l); } } } @@ -767,8 +769,8 @@ void VTF::setResourceInternal(Resource::Type type, std::span da // Store resource data std::unordered_map, uint64_t>> resourceData; - for (const auto& resource : this->resources) { - resourceData[resource.type] = {std::vector{resource.data.begin(), resource.data.end()}, 0}; + for (const auto& [type, flags, data] : this->resources) { + resourceData[type] = {std::vector{data.begin(), data.end()}, 0}; } // Set new resource @@ -806,16 +808,16 @@ void VTF::setResourceInternal(Resource::Type type, std::span da } this->data.resize(writer.size()); - for (auto& resource : this->resources) { - if (resourceData.contains(resource.type)) { - const auto& [specificResourceData, offset] = resourceData[resource.type]; - resource.data = {this->data.data() + offset, specificResourceData.size()}; + for (auto& [type, flags, data] : this->resources) { + if (resourceData.contains(type)) { + const auto& [specificResourceData, offset] = resourceData[type]; + data = {this->data.data() + offset, specificResourceData.size()}; } } } void VTF::removeResourceInternal(Resource::Type type) { - this->resources.erase(std::remove_if(this->resources.begin(), this->resources.end(), [type](const Resource& resource) { return resource.type == type; }), this->resources.end()); + std::erase_if(this->resources, [type](const Resource& resource) { return resource.type == type; }); } void VTF::regenerateImageData(ImageFormat newFormat, uint16_t newWidth, uint16_t newHeight, uint8_t newMipCount, uint16_t newFrameCount, uint8_t newFaceCount, uint16_t newSliceCount, ImageConversion::ResizeFilter filter) { @@ -963,7 +965,7 @@ bool VTF::imageDataIsSRGB() const { } std::span VTF::getImageDataRaw(uint8_t mip, uint16_t frame, uint8_t face, uint16_t slice) const { - if (auto imageResource = this->getResource(Resource::TYPE_IMAGE_DATA)) { + if (const auto imageResource = this->getResource(Resource::TYPE_IMAGE_DATA)) { 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->sliceCount)) { return imageResource->data.subspan(offset, length); } @@ -972,7 +974,7 @@ std::span VTF::getImageDataRaw(uint8_t mip, uint16_t frame, uin } std::vector VTF::getImageDataAs(ImageFormat newFormat, uint8_t mip, uint16_t frame, uint8_t face, uint16_t slice) const { - auto rawImageData = this->getImageDataRaw(mip, frame, face, slice); + const auto rawImageData = this->getImageDataRaw(mip, frame, face, slice); if (rawImageData.empty()) { return {}; } @@ -991,7 +993,7 @@ bool VTF::setImage(std::span imageData_, ImageFormat format_, u resizedWidth += math::getPaddingForAlignment(4, resizedWidth); resizedHeight += math::getPaddingForAlignment(4, resizedHeight); } - if (auto newMipCount = ImageDimensions::getRecommendedMipCountForDims(format_, resizedWidth, resizedHeight); newMipCount <= mip) { + if (const auto newMipCount = ImageDimensions::getRecommendedMipCountForDims(format_, resizedWidth, resizedHeight); newMipCount <= mip) { mip = newMipCount - 1; } if (face > 6 || (face == 6 && (this->minorVersion < 1 || this->minorVersion > 4))) { @@ -1068,14 +1070,14 @@ bool VTF::hasThumbnailData() const { } std::span VTF::getThumbnailDataRaw() const { - if (auto thumbnailResource = this->getResource(Resource::TYPE_THUMBNAIL_DATA)) { + if (const auto thumbnailResource = this->getResource(Resource::TYPE_THUMBNAIL_DATA)) { return thumbnailResource->data; } return {}; } std::vector VTF::getThumbnailDataAs(ImageFormat newFormat) const { - auto rawThumbnailData = this->getThumbnailDataRaw(); + const auto rawThumbnailData = this->getThumbnailDataRaw(); if (rawThumbnailData.empty()) { return {}; } @@ -1119,7 +1121,7 @@ std::vector VTF::bake() const { BufferStream writer{out}; writer << VTF_SIGNATURE << this->majorVersion << this->minorVersion; - auto headerLengthPos = writer.tell(); + const auto headerLengthPos = writer.tell(); writer.write(0); writer @@ -1202,15 +1204,15 @@ std::vector VTF::bake() const { } writer.seek_u(resourceStart); - static constexpr auto writeNonLocalResource = [](BufferStream& writer, Resource::Type type, std::span data) { - writer.write(type); - auto resourceOffsetPos = writer.tell(); - writer.seek(0, std::ios::end); - auto resourceOffsetValue = writer.tell(); - writer.write(data); - writer.seek_u(resourceOffsetPos).write(resourceOffsetValue); + static constexpr auto writeNonLocalResource = [](BufferStream& writer_, Resource::Type type, std::span data) { + writer_.write(type); + const auto resourceOffsetPos = writer_.tell(); + writer_.seek(0, std::ios::end); + const auto resourceOffsetValue = writer_.tell(); + writer_.write(data); + writer_.seek_u(resourceOffsetPos).write(resourceOffsetValue); }; - for (auto resourceType : Resource::TYPE_ARRAY_ORDER) { + for (const auto resourceType : Resource::TYPE_ARRAY_ORDER) { if (hasAuxCompression && resourceType == Resource::TYPE_AUX_COMPRESSION) { writeNonLocalResource(writer, resourceType, auxCompressionResourceData); } else if (hasAuxCompression && resourceType == Resource::TYPE_IMAGE_DATA) {