From 60f5c1a18f03fe2bd5d9354c72f5358b00dae93b Mon Sep 17 00:00:00 2001 From: Jan Date: Fri, 25 Apr 2025 19:21:22 +0100 Subject: [PATCH 01/11] refactor: adjust zcg code for working in x64 --- src/Parser/Parsing/ILexer.h | 17 +- src/Parser/Parsing/Impl/AbstractLexer.h | 148 +++++++++--------- .../Parsing/Impl/DefinesStreamProxy.cpp | 49 +++--- src/Parser/Parsing/Impl/DefinesStreamProxy.h | 19 ++- src/Parser/Parsing/Matcher/MatcherResult.cpp | 47 ++++++ src/Parser/Parsing/Matcher/MatcherResult.h | 116 +++++--------- src/Parser/Parsing/Sequence/SequenceResult.h | 8 +- .../Expression/SimpleExpressionMatchers.cpp | 9 +- .../Expression/SimpleExpressionMatchers.h | 2 +- src/Parser/Parsing/Simple/SimpleLexer.cpp | 7 +- src/Parser/Parsing/Simple/SimpleLexer.h | 15 +- src/Parser/Parsing/TokenPos.cpp | 11 +- src/Parser/Parsing/TokenPos.h | 12 +- src/Utils/Utils/Arguments/ArgumentParser.cpp | 10 +- .../MemberDeclarationModifierComputations.cpp | 8 +- .../Commands/Impl/CommandsParserState.cpp | 119 +++++++------- .../Commands/Impl/CommandsParserState.h | 9 +- .../Matcher/CommandsCommonMatchers.cpp | 7 +- test/ParserTestUtils/Parsing/Mock/MockLexer.h | 21 ++- 19 files changed, 322 insertions(+), 312 deletions(-) create mode 100644 src/Parser/Parsing/Matcher/MatcherResult.cpp diff --git a/src/Parser/Parsing/ILexer.h b/src/Parser/Parsing/ILexer.h index e0a53c3c..9542574e 100644 --- a/src/Parser/Parsing/ILexer.h +++ b/src/Parser/Parsing/ILexer.h @@ -3,11 +3,10 @@ #include "IParserLineStream.h" #include "Parsing/IParserValue.h" -template class ILexer -{ - // TokenType must inherit IParserValue - static_assert(std::is_base_of::value); +#include +template TokenType> class ILexer +{ public: ILexer() = default; virtual ~ILexer() = default; @@ -16,10 +15,10 @@ public: ILexer& operator=(const ILexer& other) = default; ILexer& operator=(ILexer&& other) noexcept = default; - virtual const TokenType& GetToken(unsigned index) = 0; - virtual void PopTokens(int amount) = 0; + virtual const TokenType& GetToken(size_t index) = 0; + virtual void PopTokens(size_t amount) = 0; - _NODISCARD virtual bool IsEof() = 0; - _NODISCARD virtual const TokenPos& GetPos() = 0; - _NODISCARD virtual ParserLine GetLineForPos(const TokenPos& pos) const = 0; + [[nodiscard]] virtual bool IsEof() = 0; + [[nodiscard]] virtual const TokenPos& GetPos() = 0; + [[nodiscard]] virtual ParserLine GetLineForPos(const TokenPos& pos) const = 0; }; diff --git a/src/Parser/Parsing/Impl/AbstractLexer.h b/src/Parser/Parsing/Impl/AbstractLexer.h index 637be807..34b6f2dd 100644 --- a/src/Parser/Parsing/Impl/AbstractLexer.h +++ b/src/Parser/Parsing/Impl/AbstractLexer.h @@ -7,21 +7,82 @@ #include "Utils/StringUtils.h" #include +#include #include #include -template class AbstractLexer : public ILexer +template TokenType> class AbstractLexer : public ILexer { - // TokenType must inherit IParserValue - static_assert(std::is_base_of::value); +public: + const TokenType& GetToken(const size_t index) override + { + while (index >= m_token_cache.size()) + m_token_cache.emplace_back(GetNextToken()); + + return m_token_cache[index]; + } + + void PopTokens(size_t amount) override + { + if (amount == 0 || m_token_cache.empty()) + return; + + if (m_token_cache.size() <= amount) + { + const auto& lastToken = m_token_cache.back(); + while ( + !m_line_cache.empty() + && (m_line_cache.front().m_line_number != lastToken.GetPos().m_line || *m_line_cache.front().m_filename != lastToken.GetPos().m_filename.get())) + { + m_line_cache.pop_front(); + m_line_index--; + } + m_token_cache.clear(); + } + else + { + m_token_cache.erase(m_token_cache.begin(), m_token_cache.begin() + amount); + const auto& firstToken = m_token_cache.front(); + while (!m_line_cache.empty() + && (m_line_cache.front().m_line_number != firstToken.GetPos().m_line + || *m_line_cache.front().m_filename != firstToken.GetPos().m_filename.get())) + { + m_line_cache.pop_front(); + m_line_index--; + } + } + } + + [[nodiscard]] bool IsEof() override + { + return GetToken(0).IsEof(); + } + + [[nodiscard]] const TokenPos& GetPos() override + { + return GetToken(0).GetPos(); + } + + [[nodiscard]] ParserLine GetLineForPos(const TokenPos& pos) const override + { + for (const auto& line : m_line_cache) + { + if (line.m_filename && *line.m_filename == pos.m_filename.get() && line.m_line_number == pos.m_line) + { + return line; + } + } + + return ParserLine(); + } protected: std::deque m_token_cache; std::deque m_line_cache; - IParserLineStream* const m_stream; + IParserLineStream* m_stream; - unsigned m_line_index; - unsigned m_current_line_offset; + size_t m_line_index; + size_t m_current_line_offset; explicit AbstractLexer(IParserLineStream* stream) : m_stream(stream), @@ -83,28 +144,28 @@ protected: return m_line_cache[peekLine].m_line[peekLineOffset]; } - _NODISCARD const ParserLine& CurrentLine() const + [[nodiscard]] const ParserLine& CurrentLine() const { return m_line_cache[m_line_index]; } - _NODISCARD bool IsLineEnd() const + [[nodiscard]] bool IsLineEnd() const { return m_current_line_offset >= CurrentLine().m_line.size(); } - _NODISCARD bool NextCharInLineIs(const char c) + [[nodiscard]] bool NextCharInLineIs(const char c) { return !IsLineEnd() && PeekChar() == c; } - _NODISCARD TokenPos GetPreviousCharacterPos() const + [[nodiscard]] TokenPos GetPreviousCharacterPos() const { const auto& currentLine = CurrentLine(); return TokenPos(*currentLine.m_filename, currentLine.m_line_number, m_current_line_offset); } - _NODISCARD TokenPos GetNextCharacterPos() + [[nodiscard]] TokenPos GetNextCharacterPos() { const auto& currentLine = CurrentLine(); if (m_current_line_offset + 1 >= currentLine.m_line.size()) @@ -227,7 +288,7 @@ protected: m_current_line_offset += numberLength - 1; } - _NODISCARD bool IsIntegerNumber() const + [[nodiscard]] bool IsIntegerNumber() const { const auto& currentLine = CurrentLine(); const auto* currentCharacter = ¤tLine.m_line.c_str()[m_current_line_offset - 1]; @@ -350,67 +411,4 @@ protected: integerValue = ReadInteger(); } } - -public: - const TokenType& GetToken(unsigned index) override - { - while (index >= m_token_cache.size()) - m_token_cache.emplace_back(GetNextToken()); - - return m_token_cache[index]; - } - - void PopTokens(int amount) override - { - if (amount <= 0 || m_token_cache.empty()) - return; - - if (static_cast(m_token_cache.size()) <= amount) - { - const auto& lastToken = m_token_cache.back(); - while ( - !m_line_cache.empty() - && (m_line_cache.front().m_line_number != lastToken.GetPos().m_line || *m_line_cache.front().m_filename != lastToken.GetPos().m_filename.get())) - { - m_line_cache.pop_front(); - m_line_index--; - } - m_token_cache.clear(); - } - else - { - m_token_cache.erase(m_token_cache.begin(), m_token_cache.begin() + amount); - const auto& firstToken = m_token_cache.front(); - while (!m_line_cache.empty() - && (m_line_cache.front().m_line_number != firstToken.GetPos().m_line - || *m_line_cache.front().m_filename != firstToken.GetPos().m_filename.get())) - { - m_line_cache.pop_front(); - m_line_index--; - } - } - } - - _NODISCARD bool IsEof() override - { - return GetToken(0).IsEof(); - } - - _NODISCARD const TokenPos& GetPos() override - { - return GetToken(0).GetPos(); - } - - _NODISCARD ParserLine GetLineForPos(const TokenPos& pos) const override - { - for (const auto& line : m_line_cache) - { - if (line.m_filename && *line.m_filename == pos.m_filename.get() && line.m_line_number == pos.m_line) - { - return line; - } - } - - return ParserLine(); - } }; diff --git a/src/Parser/Parsing/Impl/DefinesStreamProxy.cpp b/src/Parser/Parsing/Impl/DefinesStreamProxy.cpp index 38e80040..9c241627 100644 --- a/src/Parser/Parsing/Impl/DefinesStreamProxy.cpp +++ b/src/Parser/Parsing/Impl/DefinesStreamProxy.cpp @@ -5,7 +5,6 @@ #include "Parsing/Simple/Expression/ISimpleExpression.h" #include "Parsing/Simple/Expression/SimpleExpressionMatchers.h" #include "Parsing/Simple/SimpleExpressionInterpreter.h" -#include "Utils/ClassUtils.h" #include "Utils/StringUtils.h" #include @@ -114,7 +113,7 @@ void DefinesStreamProxy::Define::IdentifyParameters(const std::vector= inputSize) - throw new ParsingException(TokenPos(*line.m_filename, line.m_line_number, static_cast(linePos + 1)), - "Token-pasting operator cannot be used on unclosed string"); + throw ParsingException(TokenPos(*line.m_filename, line.m_line_number, static_cast(linePos + 1)), + "Token-pasting operator cannot be used on unclosed string"); offset++; } @@ -743,12 +736,16 @@ namespace unsigned m_end; }; - void EmitPastedTokens( - ParserLine& line, unsigned& linePos, std::ostream& out, const std::string& input, const TokenPasteToken& token0, const TokenPasteToken& token1) + void EmitPastedTokens(const ParserLine& line, + const unsigned& linePos, + std::ostream& out, + const std::string& input, + const TokenPasteToken& token0, + const TokenPasteToken& token1) { if ((token0.m_type == TokenPasteTokenType::STRING) != (token1.m_type == TokenPasteTokenType::STRING)) - throw new ParsingException(TokenPos(*line.m_filename, line.m_line_number, static_cast(linePos + 1)), - "String token can only use token-pasting operator on other string token"); + throw ParsingException(TokenPos(*line.m_filename, line.m_line_number, static_cast(linePos + 1)), + "String token can only use token-pasting operator on other string token"); if (token0.m_type == TokenPasteTokenType::STRING) { out << '"'; @@ -767,7 +764,7 @@ namespace } // namespace void DefinesStreamProxy::ProcessTokenPastingOperators( - ParserLine& line, unsigned& linePos, std::vector& callstack, std::string& input, unsigned& inputPos) + const ParserLine& line, const unsigned& linePos, std::vector& callstack, std::string& input, unsigned& inputPos) { std::ostringstream ss; @@ -789,7 +786,7 @@ void DefinesStreamProxy::ProcessTokenPastingOperators( if (c == '#' && IsTokenPastingOperatorForwardLookup(input, i)) { if (currentToken.m_type == TokenPasteTokenType::NONE) - throw new ParsingException(CreatePos(line, linePos), "Cannot use token-pasting operator without previous token"); + throw ParsingException(CreatePos(line, linePos), "Cannot use token-pasting operator without previous token"); if (previousToken.m_end < currentToken.m_start) ss << std::string(input, previousToken.m_end, currentToken.m_start - previousToken.m_end); @@ -816,12 +813,12 @@ void DefinesStreamProxy::ProcessTokenPastingOperators( ss << std::string(input, previousToken.m_end, inputSize - previousToken.m_end); if (pasteNext) - throw new ParsingException(CreatePos(line, linePos), "Cannot use token-pasting operator without following token"); + throw ParsingException(CreatePos(line, linePos), "Cannot use token-pasting operator without following token"); input = ss.str(); } -void DefinesStreamProxy::InsertMacroParameters(std::ostringstream& out, const DefinesStreamProxy::Define* macro, std::vector& parameterValues) +void DefinesStreamProxy::InsertMacroParameters(std::ostringstream& out, const Define* macro, const std::vector& parameterValues) { if (parameterValues.empty() || macro->m_parameter_positions.empty()) { @@ -829,7 +826,7 @@ void DefinesStreamProxy::InsertMacroParameters(std::ostringstream& out, const De return; } - auto lastPos = 0u; + auto lastPos = 0uz; for (const auto& parameterPosition : macro->m_parameter_positions) { if (lastPos < parameterPosition.m_parameter_position) @@ -857,7 +854,7 @@ void DefinesStreamProxy::ExpandMacro(ParserLine& line, std::ostringstream& out, std::vector& callstack, const DefinesStreamProxy::Define* macro, - std::vector& parameterValues) + const std::vector& parameterValues) { std::ostringstream rawOutput; InsertMacroParameters(rawOutput, macro, parameterValues); @@ -873,7 +870,7 @@ void DefinesStreamProxy::ExpandMacro(ParserLine& line, } void DefinesStreamProxy::ContinueMacroParameters( - const ParserLine& line, unsigned& linePos, MacroParameterState& state, const std::string& input, unsigned& inputPos) + const ParserLine& line, const unsigned& linePos, MacroParameterState& state, const std::string& input, unsigned& inputPos) { const auto inputLength = input.size(); while (state.m_parameter_state != ParameterState::NOT_IN_PARAMETERS && inputPos < inputLength) diff --git a/src/Parser/Parsing/Impl/DefinesStreamProxy.h b/src/Parser/Parsing/Impl/DefinesStreamProxy.h index 28d8564a..d9beffb6 100644 --- a/src/Parser/Parsing/Impl/DefinesStreamProxy.h +++ b/src/Parser/Parsing/Impl/DefinesStreamProxy.h @@ -107,26 +107,29 @@ private: _NODISCARD bool MatchIfdefDirective(const ParserLine& line, size_t directiveStartPosition, size_t directiveEndPosition); _NODISCARD bool MatchElseDirective(const ParserLine& line, size_t directiveStartPosition, size_t directiveEndPosition); _NODISCARD bool MatchEndifDirective(const ParserLine& line, size_t directiveStartPosition, size_t directiveEndPosition); - _NODISCARD bool MatchDirectives(ParserLine& line); + _NODISCARD bool MatchDirectives(const ParserLine& line); - void ExtractParametersFromMacroUsage(const ParserLine& line, unsigned& linePos, MacroParameterState& state, const std::string& input, unsigned& inputPos); - bool FindMacroForIdentifier(const std::string& input, unsigned wordStart, unsigned wordEnd, const Define*& value) const; + static void ExtractParametersFromMacroUsage( + const ParserLine& line, const unsigned& linePos, MacroParameterState& state, const std::string& input, unsigned& inputPos); + bool FindMacroForIdentifier(const std::string& input, unsigned identifierStart, unsigned identifierEnd, const Define*& value) const; static bool MatchDefinedExpression(const ParserLine& line, size_t& pos, std::string& definitionName); void ExpandDefinedExpressions(ParserLine& line) const; - bool FindNextMacro(const std::string& input, unsigned& inputPos, unsigned& defineStart, const DefinesStreamProxy::Define*& define); + bool FindNextMacro(const std::string& input, unsigned& inputPos, unsigned& defineStart, const DefinesStreamProxy::Define*& define) const; - void ProcessTokenPastingOperators(ParserLine& line, unsigned& linePos, std::vector& callstack, std::string& input, unsigned& inputPos); - void InsertMacroParameters(std::ostringstream& out, const DefinesStreamProxy::Define* macro, std::vector& parameterValues); + static void ProcessTokenPastingOperators( + const ParserLine& line, const unsigned& linePos, std::vector& callstack, std::string& input, unsigned& inputPos); + static void InsertMacroParameters(std::ostringstream& out, const DefinesStreamProxy::Define* macro, const std::vector& parameterValues); void ExpandMacro(ParserLine& line, unsigned& linePos, std::ostringstream& out, std::vector& callstack, const DefinesStreamProxy::Define* macro, - std::vector& parameterValues); + const std::vector& parameterValues); - void ContinueMacroParameters(const ParserLine& line, unsigned& linePos, MacroParameterState& state, const std::string& input, unsigned& inputPos); + static void + ContinueMacroParameters(const ParserLine& line, const unsigned& linePos, MacroParameterState& state, const std::string& input, unsigned& inputPos); void ContinueMultiLineMacro(ParserLine& line); void ProcessNestedMacros(ParserLine& line, unsigned& linePos, std::vector& callstack, std::string& input, unsigned& inputPos); diff --git a/src/Parser/Parsing/Matcher/MatcherResult.cpp b/src/Parser/Parsing/Matcher/MatcherResult.cpp new file mode 100644 index 00000000..b79de9ce --- /dev/null +++ b/src/Parser/Parsing/Matcher/MatcherResult.cpp @@ -0,0 +1,47 @@ +#include "MatcherResult.h" + +namespace +{ + // The highest bit is the fabricated flag + constexpr size_t FABRICATED_FLAG_MASK = 1uz << (sizeof(size_t) * 8uz - 1uz); + constexpr size_t TOKEN_INDEX_MASK = ~FABRICATED_FLAG_MASK; +} // namespace + +MatcherResultTokenIndex::MatcherResultTokenIndex(const size_t index, const bool isFabricated) +{ + m_token_index = index & TOKEN_INDEX_MASK; + if (isFabricated) + m_token_index |= FABRICATED_FLAG_MASK; +} + +bool MatcherResultTokenIndex::IsFabricated() const +{ + return m_token_index & FABRICATED_FLAG_MASK; +} + +size_t MatcherResultTokenIndex::GetTokenIndex() const +{ + return m_token_index & TOKEN_INDEX_MASK; +} + +MatcherResultCapture::MatcherResultCapture(const int captureId, const unsigned tokenIndex) + : MatcherResultCapture(captureId, tokenIndex, false) +{ +} + +MatcherResultCapture::MatcherResultCapture(const int captureId, const unsigned tokenIndex, const bool isFabricated) + : m_capture_id(captureId), + m_token_index(tokenIndex, isFabricated) +{ +} + +MatcherResultCapture::MatcherResultCapture(const int captureId, const MatcherResultTokenIndex index) + : m_capture_id(captureId), + m_token_index(index) +{ +} + +int MatcherResultCapture::GetCaptureId() const +{ + return m_capture_id; +} diff --git a/src/Parser/Parsing/Matcher/MatcherResult.h b/src/Parser/Parsing/Matcher/MatcherResult.h index f3e99e9d..719f30d5 100644 --- a/src/Parser/Parsing/Matcher/MatcherResult.h +++ b/src/Parser/Parsing/Matcher/MatcherResult.h @@ -1,89 +1,40 @@ #pragma once #include "Parsing/IParserValue.h" -#include "Utils/ClassUtils.h" +#include +#include #include -#include #include -template class MatcherResult +class MatcherResultTokenIndex { - // TokenType must inherit IParserValue - static_assert(std::is_base_of::value); - public: - class TokenIndex - { - static constexpr unsigned FABRICATED_FLAG_MASK = std::numeric_limits::max() ^ std::numeric_limits::max(); - static constexpr unsigned TOKEN_INDEX_MASK = ~FABRICATED_FLAG_MASK; - - unsigned m_token_index; - - public: - TokenIndex(const unsigned index, const bool isFabricated) - { - m_token_index = index & TOKEN_INDEX_MASK; - if (isFabricated) - m_token_index |= FABRICATED_FLAG_MASK; - } - - _NODISCARD bool IsFabricated() const - { - return m_token_index & FABRICATED_FLAG_MASK; - } - - _NODISCARD unsigned GetTokenIndex() const - { - return m_token_index & TOKEN_INDEX_MASK; - } - }; - - class Capture - { - public: - int m_capture_id; - TokenIndex m_token_index; - - Capture(const int captureId, const unsigned tokenIndex) - : Capture(captureId, tokenIndex, false) - { - } - - Capture(const int captureId, const unsigned tokenIndex, const bool isFabricated) - : m_capture_id(captureId), - m_token_index(tokenIndex, isFabricated) - { - } - - Capture(const int captureId, const TokenIndex index) - : m_capture_id(captureId), - m_token_index(index) - { - } - - _NODISCARD int GetCaptureId() const - { - return m_capture_id; - } - }; - - bool m_matches; - unsigned m_consumed_token_count; - std::vector m_tags; - std::vector m_captures; - std::vector m_matched_tokens; - std::vector m_fabricated_tokens; + MatcherResultTokenIndex(size_t index, bool isFabricated); + [[nodiscard]] bool IsFabricated() const; + [[nodiscard]] size_t GetTokenIndex() const; private: - MatcherResult(const bool matches, const unsigned consumedTokenCount) - : m_matches(matches), - m_consumed_token_count(consumedTokenCount) - { - } + size_t m_token_index; +}; +class MatcherResultCapture +{ public: - static MatcherResult Match(unsigned consumedTokenCount) + MatcherResultCapture(int captureId, unsigned tokenIndex); + MatcherResultCapture(int captureId, unsigned tokenIndex, bool isFabricated); + MatcherResultCapture(int captureId, MatcherResultTokenIndex index); + + [[nodiscard]] int GetCaptureId() const; + + int m_capture_id; + MatcherResultTokenIndex m_token_index; +}; + +template TokenType> class MatcherResult +{ +public: + static MatcherResult Match(const unsigned consumedTokenCount) { return MatcherResult(true, consumedTokenCount); } @@ -98,12 +49,13 @@ public: m_consumed_token_count += other.m_consumed_token_count; if (!other.m_tags.empty()) - std::copy(other.m_tags.begin(), other.m_tags.end(), std::back_inserter(m_tags)); + std::ranges::copy(other.m_tags, std::back_inserter(m_tags)); for (const auto& capture : other.m_captures) { if (capture.m_token_index.IsFabricated()) - m_captures.emplace_back(capture.GetCaptureId(), TokenIndex(m_fabricated_tokens.size() + capture.m_token_index.GetTokenIndex(), true)); + m_captures.emplace_back(capture.GetCaptureId(), + MatcherResultTokenIndex(m_fabricated_tokens.size() + capture.m_token_index.GetTokenIndex(), true)); else m_captures.emplace_back(capture.GetCaptureId(), capture.m_token_index); } @@ -121,4 +73,18 @@ public: m_fabricated_tokens.emplace_back(std::move(fabricated)); } } + + bool m_matches; + unsigned m_consumed_token_count; + std::vector m_tags; + std::vector m_captures; + std::vector m_matched_tokens; + std::vector m_fabricated_tokens; + +private: + MatcherResult(const bool matches, const unsigned consumedTokenCount) + : m_matches(matches), + m_consumed_token_count(consumedTokenCount) + { + } }; diff --git a/src/Parser/Parsing/Sequence/SequenceResult.h b/src/Parser/Parsing/Sequence/SequenceResult.h index 764e43ea..fb268bd7 100644 --- a/src/Parser/Parsing/Sequence/SequenceResult.h +++ b/src/Parser/Parsing/Sequence/SequenceResult.h @@ -5,9 +5,10 @@ #include "Parsing/ParsingException.h" #include "Utils/ClassUtils.h" +#include #include -template class SequenceResult +template TokenType> class SequenceResult { class Capture { @@ -21,9 +22,6 @@ template class SequenceResult } }; - // TokenType must inherit IParserValue - static_assert(std::is_base_of::value); - std::vector m_tags; std::unordered_map m_captures; @@ -34,7 +32,7 @@ public: : m_tags(result.m_tags), m_tag_offset(0) { - for (const typename MatcherResult::Capture& capture : result.m_captures) + for (const MatcherResultCapture& capture : result.m_captures) { if (capture.m_token_index.IsFabricated()) m_captures[capture.GetCaptureId()].m_tokens.push_back(result.m_fabricated_tokens[capture.m_token_index.GetTokenIndex()]); diff --git a/src/Parser/Parsing/Simple/Expression/SimpleExpressionMatchers.cpp b/src/Parser/Parsing/Simple/Expression/SimpleExpressionMatchers.cpp index a5f21c30..8a347444 100644 --- a/src/Parser/Parsing/Simple/Expression/SimpleExpressionMatchers.cpp +++ b/src/Parser/Parsing/Simple/Expression/SimpleExpressionMatchers.cpp @@ -7,6 +7,7 @@ #include #include +#include static constexpr int TAG_EXPRESSION = SimpleExpressionMatchers::TAG_OFFSET_EXPRESSION + 1; static constexpr int TAG_OPERAND = SimpleExpressionMatchers::TAG_OFFSET_EXPRESSION + 2; @@ -103,7 +104,7 @@ std::unique_ptr SimpleExpressionMatchers::ProcessConditionalO return std::make_unique(std::move(condition), std::move(trueExpression), std::move(falseExpression)); } -std::unique_ptr SimpleExpressionMatchers::ProcessOperand(SequenceResult& result) const +std::unique_ptr SimpleExpressionMatchers::ProcessOperand(SequenceResult& result) { const auto& operandToken = result.NextCapture(CAPTURE_OPERAND); @@ -133,7 +134,7 @@ std::unique_ptr SimpleExpressionMatchers::ProcessExpression(S return nullptr; std::vector> operands; - std::list> operators; + std::list> operators; while (true) { @@ -200,7 +201,7 @@ std::unique_ptr SimpleExpressionMatchers::ProcessExpression(S } operators.sort( - [](const std::pair& p1, const std::pair& p2) + [](const std::pair& p1, const std::pair& p2) { if (p1.second->m_precedence != p2.second->m_precedence) return p1.second->m_precedence > p2.second->m_precedence; @@ -219,7 +220,7 @@ std::unique_ptr SimpleExpressionMatchers::ProcessExpression(S operators.pop_back(); - for (auto& [opIndex, _] : operators) + for (auto& opIndex : operators | std::views::keys) { if (opIndex > operatorIndex) opIndex--; diff --git a/src/Parser/Parsing/Simple/Expression/SimpleExpressionMatchers.h b/src/Parser/Parsing/Simple/Expression/SimpleExpressionMatchers.h index 021688e2..aaf02bc9 100644 --- a/src/Parser/Parsing/Simple/Expression/SimpleExpressionMatchers.h +++ b/src/Parser/Parsing/Simple/Expression/SimpleExpressionMatchers.h @@ -59,7 +59,7 @@ private: std::unique_ptr ProcessExpressionInParenthesis(SequenceResult& result) const; std::unique_ptr ProcessConditionalOperation(std::unique_ptr condition, SequenceResult& result) const; - std::unique_ptr ProcessOperand(SequenceResult& result) const; + static std::unique_ptr ProcessOperand(SequenceResult& result); public: std::unique_ptr Expression(const supplier_t* labelSupplier) const; diff --git a/src/Parser/Parsing/Simple/SimpleLexer.cpp b/src/Parser/Parsing/Simple/SimpleLexer.cpp index 63d5a556..d20fee7f 100644 --- a/src/Parser/Parsing/Simple/SimpleLexer.cpp +++ b/src/Parser/Parsing/Simple/SimpleLexer.cpp @@ -14,7 +14,12 @@ SimpleLexer::MultiCharacterTokenLookupEntry::MultiCharacterTokenLookupEntry(cons SimpleLexer::SimpleLexer(IParserLineStream* stream) : AbstractLexer(stream), - m_config{false, true, false, true, true, {}}, + m_config{.m_emit_new_line_tokens = false, + .m_read_strings = true, + .m_string_escape_sequences = false, + .m_read_integer_numbers = true, + .m_read_floating_point_numbers = true, + .m_multi_character_tokens = {}}, m_check_for_multi_character_tokens(false), m_last_line(1) { diff --git a/src/Parser/Parsing/Simple/SimpleLexer.h b/src/Parser/Parsing/Simple/SimpleLexer.h index c1220d52..bd6e45dc 100644 --- a/src/Parser/Parsing/Simple/SimpleLexer.h +++ b/src/Parser/Parsing/Simple/SimpleLexer.h @@ -7,7 +7,7 @@ #include #include -class SimpleLexer : public AbstractLexer +class SimpleLexer final : public AbstractLexer { public: class Config @@ -30,6 +30,9 @@ public: std::vector m_multi_character_tokens; }; + explicit SimpleLexer(IParserLineStream* stream); + SimpleLexer(IParserLineStream* stream, Config config); + protected: class MultiCharacterTokenLookupEntry { @@ -41,10 +44,6 @@ protected: MultiCharacterTokenLookupEntry(int id, std::string value); }; - Config m_config; - bool m_check_for_multi_character_tokens; - int m_last_line; - std::unique_ptr m_multi_character_token_lookup[std::numeric_limits::max() + 1]; void AddMultiCharacterTokenConfigToLookup(Config::MultiCharacterToken tokenConfig); @@ -52,7 +51,7 @@ protected: SimpleParserValue GetNextToken() override; -public: - explicit SimpleLexer(IParserLineStream* stream); - SimpleLexer(IParserLineStream* stream, Config config); + Config m_config; + bool m_check_for_multi_character_tokens; + size_t m_last_line; }; diff --git a/src/Parser/Parsing/TokenPos.cpp b/src/Parser/Parsing/TokenPos.cpp index fe9d9c5d..d8dcf469 100644 --- a/src/Parser/Parsing/TokenPos.cpp +++ b/src/Parser/Parsing/TokenPos.cpp @@ -1,15 +1,18 @@ #include "TokenPos.h" -const std::string TokenPos::EMPTY_FILENAME; +namespace +{ + const std::string EMPTY_FILENAME; +} TokenPos::TokenPos() : m_filename(EMPTY_FILENAME), - m_line(1), - m_column(1) + m_line(1uz), + m_column(1uz) { } -TokenPos::TokenPos(const std::string& filename, const int line, const int column) +TokenPos::TokenPos(const std::string& filename, const size_t line, const size_t column) : m_filename(filename), m_line(line), m_column(column) diff --git a/src/Parser/Parsing/TokenPos.h b/src/Parser/Parsing/TokenPos.h index 103b2dd5..7ceadd6d 100644 --- a/src/Parser/Parsing/TokenPos.h +++ b/src/Parser/Parsing/TokenPos.h @@ -5,13 +5,11 @@ class TokenPos { - static const std::string EMPTY_FILENAME; - public: - std::reference_wrapper m_filename; - int m_line; - int m_column; - TokenPos(); - TokenPos(const std::string& filename, int line, int column); + TokenPos(const std::string& filename, size_t line, size_t column); + + std::reference_wrapper m_filename; + size_t m_line; + size_t m_column; }; diff --git a/src/Utils/Utils/Arguments/ArgumentParser.cpp b/src/Utils/Utils/Arguments/ArgumentParser.cpp index 1f89a5ed..caff4ce1 100644 --- a/src/Utils/Utils/Arguments/ArgumentParser.cpp +++ b/src/Utils/Utils/Arguments/ArgumentParser.cpp @@ -42,7 +42,7 @@ bool ArgumentParser::ParseArguments(std::vector& args) m_path = args[0]; const auto argCount = args.size(); - for (unsigned argIndex = 1u; argIndex < argCount; argIndex++) + for (auto argIndex = 1uz; argIndex < argCount; argIndex++) { auto& arg = args[argIndex]; @@ -85,7 +85,7 @@ bool ArgumentParser::ParseArguments(std::vector& args) return false; } - if (m_matched_options.find(matchedOption) != m_matched_options.end()) + if (m_matched_options.contains(matchedOption)) { if (!matchedOption->m_multi_use) { @@ -106,7 +106,7 @@ bool ArgumentParser::ParseArguments(std::vector& args) } auto& parameters = m_matched_options[matchedOption]; - for (unsigned parameterIndex = 0; parameterIndex < parameterCount; parameterIndex++) + for (auto parameterIndex = 0uz; parameterIndex < parameterCount; parameterIndex++) { std::string& param = args[argIndex + parameterIndex + 1]; @@ -116,14 +116,14 @@ bool ArgumentParser::ParseArguments(std::vector& args) return false; } - parameters.push_back(param); + parameters.emplace_back(param); } argIndex += parameterCount; } else { - m_matched_arguments.push_back(arg); + m_matched_arguments.emplace_back(arg); } } diff --git a/src/ZoneCodeGeneratorLib/Domain/Computations/MemberDeclarationModifierComputations.cpp b/src/ZoneCodeGeneratorLib/Domain/Computations/MemberDeclarationModifierComputations.cpp index 2b9e99ba..aec0c366 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Computations/MemberDeclarationModifierComputations.cpp +++ b/src/ZoneCodeGeneratorLib/Domain/Computations/MemberDeclarationModifierComputations.cpp @@ -12,18 +12,18 @@ DeclarationModifierComputations::DeclarationModifierComputations(const MemberInf m_modifier_indices(std::move(modifierIndices)) { auto combinedIndex = 0; - auto arraySizes = MemberComputations(m_information).GetArraySizes(); + const auto arraySizes = MemberComputations(m_information).GetArraySizes(); std::vector sizePerDepth(arraySizes.size()); auto currentDepthSize = 1; - for (int i = arraySizes.size(); i > 0; i--) + for (int i = static_cast(arraySizes.size()); i > 0; i--) { sizePerDepth[i - 1] = currentDepthSize; currentDepthSize *= arraySizes[i - 1]; } auto currentDepth = 0; - for (auto modifierIndex : m_modifier_indices) + for (const auto modifierIndex : m_modifier_indices) { combinedIndex += sizePerDepth[currentDepth++] * modifierIndex; } @@ -62,7 +62,7 @@ std::vector DeclarationModifierComputations::GetFollowingD if (m_modifier_indices.size() + 1 < declarationModifiers.size()) { - for (auto i = declarationModifiers.begin() + m_modifier_indices.size() + 1; i != declarationModifiers.end(); ++i) + for (auto i = declarationModifiers.begin() + m_modifier_indices.size() + 1uz; i != declarationModifiers.end(); ++i) { following.push_back(i->get()); } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Impl/CommandsParserState.cpp b/src/ZoneCodeGeneratorLib/Parsing/Commands/Impl/CommandsParserState.cpp index 75f6c66b..00ed3005 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Impl/CommandsParserState.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Impl/CommandsParserState.cpp @@ -1,5 +1,63 @@ #include "CommandsParserState.h" +namespace +{ + MemberInformation* GetMemberWithName(const std::string& memberName, const StructureInformation* type) + { + for (const auto& member : type->m_ordered_members) + { + if (member->m_member->m_name == memberName) + { + return member.get(); + } + } + + return nullptr; + } + + bool GetNextTypenameSeparatorPos(const std::string& typeNameValue, const size_t startPos, size_t& separatorPos) + { + const auto typeNameValueSize = typeNameValue.size(); + for (auto currentHead = startPos + 1; currentHead < typeNameValueSize; currentHead++) + { + if (typeNameValue[currentHead] == ':' && typeNameValue[currentHead - 1] == ':') + { + separatorPos = currentHead - 1; + return true; + } + } + + return false; + } + + bool ExtractMembersFromTypenameInternal(const std::string& typeNameValue, + size_t typeNameOffset, + const StructureInformation* type, + std::vector& members) + { + auto startOffset = typeNameOffset; + while (GetNextTypenameSeparatorPos(typeNameValue, typeNameOffset, typeNameOffset)) + { + auto* foundMember = GetMemberWithName(std::string(typeNameValue, startOffset, typeNameOffset - startOffset), type); + + if (foundMember == nullptr) + return false; + + members.push_back(foundMember); + type = foundMember->m_type; + typeNameOffset += 2; + startOffset = typeNameOffset; + } + + auto* foundMember = GetMemberWithName(std::string(typeNameValue, startOffset, typeNameValue.size() - startOffset), type); + if (foundMember == nullptr) + return false; + + members.push_back(foundMember); + return true; + } +} // namespace + CommandsParserState::CommandsParserState(IDataRepository* repository) : m_repository(repository), m_in_use(nullptr) @@ -36,63 +94,8 @@ void CommandsParserState::SetInUse(StructureInformation* structure) m_in_use = structure; } -MemberInformation* CommandsParserState::GetMemberWithName(const std::string& memberName, StructureInformation* type) -{ - for (const auto& member : type->m_ordered_members) - { - if (member->m_member->m_name == memberName) - { - return member.get(); - } - } - - return nullptr; -} - -bool CommandsParserState::GetNextTypenameSeparatorPos(const std::string& typeNameValue, const unsigned startPos, unsigned& separatorPos) -{ - const auto typeNameValueSize = typeNameValue.size(); - for (auto currentHead = startPos + 1; currentHead < typeNameValueSize; currentHead++) - { - if (typeNameValue[currentHead] == ':' && typeNameValue[currentHead - 1] == ':') - { - separatorPos = currentHead - 1; - return true; - } - } - - return false; -} - -bool CommandsParserState::ExtractMembersFromTypenameInternal(const std::string& typeNameValue, - unsigned typeNameOffset, - StructureInformation* type, - std::vector& members) -{ - auto startOffset = typeNameOffset; - while (GetNextTypenameSeparatorPos(typeNameValue, typeNameOffset, typeNameOffset)) - { - auto* foundMember = GetMemberWithName(std::string(typeNameValue, startOffset, typeNameOffset - startOffset), type); - - if (foundMember == nullptr) - return false; - - members.push_back(foundMember); - type = foundMember->m_type; - typeNameOffset += 2; - startOffset = typeNameOffset; - } - - auto* foundMember = GetMemberWithName(std::string(typeNameValue, startOffset, typeNameValue.size() - startOffset), type); - if (foundMember == nullptr) - return false; - - members.push_back(foundMember); - return true; -} - bool CommandsParserState::GetMembersFromTypename(const std::string& typeNameValue, - StructureInformation* baseType, + const StructureInformation* baseType, std::vector& members) const { return m_in_use != nullptr && ExtractMembersFromTypenameInternal(typeNameValue, 0, m_in_use, members) @@ -114,7 +117,7 @@ bool CommandsParserState::GetTypenameAndMembersFromTypename(const std::string& t } DataDefinition* foundDefinition = nullptr; - unsigned currentSeparatorPos = 0; + auto currentSeparatorPos = 0uz; while (GetNextTypenameSeparatorPos(typeNameValue, currentSeparatorPos, currentSeparatorPos)) { std::string currentTypename(typeNameValue, 0, currentSeparatorPos); @@ -134,7 +137,7 @@ bool CommandsParserState::GetTypenameAndMembersFromTypename(const std::string& t if (foundDefinition == nullptr) return false; - auto* definitionWithMembers = dynamic_cast(foundDefinition); + const auto* definitionWithMembers = dynamic_cast(foundDefinition); if (definitionWithMembers == nullptr) return false; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Impl/CommandsParserState.h b/src/ZoneCodeGeneratorLib/Parsing/Commands/Impl/CommandsParserState.h index be50ef18..a38b322f 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Impl/CommandsParserState.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Impl/CommandsParserState.h @@ -19,17 +19,10 @@ public: [[nodiscard]] StructureInformation* GetInUse() const; void SetInUse(StructureInformation* structure); - bool GetMembersFromTypename(const std::string& typeNameValue, StructureInformation* baseType, std::vector& members) const; + bool GetMembersFromTypename(const std::string& typeNameValue, const StructureInformation* baseType, std::vector& members) const; bool GetTypenameAndMembersFromTypename(const std::string& typeNameValue, StructureInformation*& structure, std::vector& members) const; private: - static MemberInformation* GetMemberWithName(const std::string& memberName, StructureInformation* type); - static bool GetNextTypenameSeparatorPos(const std::string& typeNameValue, unsigned startPos, unsigned& separatorPos); - static bool ExtractMembersFromTypenameInternal(const std::string& typeNameValue, - unsigned typeNameOffset, - StructureInformation* type, - std::vector& members); - IDataRepository* m_repository; StructureInformation* m_in_use; }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Matcher/CommandsCommonMatchers.cpp b/src/ZoneCodeGeneratorLib/Parsing/Commands/Matcher/CommandsCommonMatchers.cpp index 3bc815df..8bed3923 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Matcher/CommandsCommonMatchers.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Matcher/CommandsCommonMatchers.cpp @@ -6,6 +6,7 @@ #include "Domain/Evaluation/Operation.h" #include +#include #include #include #include @@ -353,7 +354,7 @@ std::unique_ptr currentType = nullptr; std::vector> operands; - std::list> operators; + std::list> operators; while (true) { @@ -384,7 +385,7 @@ std::unique_ptr } operators.sort( - [](const std::pair& p1, const std::pair& p2) + [](const std::pair& p1, const std::pair& p2) { if (p1.second->m_precedence != p2.second->m_precedence) return p1.second->m_precedence > p2.second->m_precedence; @@ -402,7 +403,7 @@ std::unique_ptr operators.pop_back(); - for (auto& [opIndex, _] : operators) + for (auto& opIndex : operators | std::views::keys) { if (opIndex > operatorIndex) opIndex--; diff --git a/test/ParserTestUtils/Parsing/Mock/MockLexer.h b/test/ParserTestUtils/Parsing/Mock/MockLexer.h index ae484456..f48c303a 100644 --- a/test/ParserTestUtils/Parsing/Mock/MockLexer.h +++ b/test/ParserTestUtils/Parsing/Mock/MockLexer.h @@ -3,18 +3,12 @@ #include "Parsing/ILexer.h" #include "Utils/ClassUtils.h" +#include #include #include -template class MockLexer final : public ILexer +template TokenType> class MockLexer final : public ILexer { - // TokenType must inherit IParserValue - static_assert(std::is_base_of::value); - - std::vector m_tokens; - TokenType m_eof; - size_t m_pop_count; - public: MockLexer(std::initializer_list> tokens, TokenType eof) : m_tokens(std::make_move_iterator(tokens.begin()), std::make_move_iterator(tokens.end())), @@ -36,7 +30,7 @@ public: MockLexer& operator=(const MockLexer& other) = delete; MockLexer& operator=(MockLexer&& other) noexcept = default; - const TokenType& GetToken(const unsigned index) override + const TokenType& GetToken(const size_t index) override { const auto absoluteIndex = m_pop_count + index; if (absoluteIndex < m_tokens.size()) @@ -45,10 +39,10 @@ public: return m_eof; } - void PopTokens(const int amount) override + void PopTokens(const size_t amount) override { assert(amount >= 0); - m_pop_count += static_cast(amount); + m_pop_count += amount; } bool IsEof() override @@ -70,4 +64,9 @@ public: { return ParserLine(); } + +private: + std::vector m_tokens; + TokenType m_eof; + size_t m_pop_count; }; From 5635470b6edb08b1fb3ce828e3b0d39a4c85d675 Mon Sep 17 00:00:00 2001 From: Jan Date: Fri, 25 Apr 2025 21:26:44 +0100 Subject: [PATCH 02/11] refactor: cryptography component --- premake5.lua | 4 +- src/Crypto/Crypto.cpp | 32 ----- src/Crypto/Crypto.h | 27 ---- src/Crypto/IHashFunction.h | 14 --- src/Crypto/IPublicKeyAlgorithm.h | 22 ---- src/Crypto/IStreamCipher.h | 14 --- src/Crypto/Impl/AlgorithmMD5.cpp | 64 ---------- src/Crypto/Impl/AlgorithmMD5.h | 20 --- src/Crypto/Impl/AlgorithmRSA.cpp | 119 ------------------ src/Crypto/Impl/AlgorithmRSA.h | 25 ---- src/Crypto/Impl/AlgorithmSHA1.cpp | 64 ---------- src/Crypto/Impl/AlgorithmSHA1.h | 20 --- src/Crypto/Impl/AlgorithmSHA256.cpp | 64 ---------- src/Crypto/Impl/AlgorithmSHA256.h | 20 --- src/Crypto/Impl/AlgorithmSalsa20.cpp | 89 ------------- src/Crypto/Impl/AlgorithmSalsa20.h | 21 ---- src/Crypto/Impl/CryptoLibrary.cpp | 15 --- src/Crypto/Impl/CryptoLibrary.h | 10 -- src/{Crypto.lua => Cryptography.lua} | 20 +-- src/Cryptography/Algorithms/AlgorithmMd5.cpp | 54 ++++++++ src/Cryptography/Algorithms/AlgorithmMd5.h | 10 ++ src/Cryptography/Algorithms/AlgorithmRsa.cpp | 84 +++++++++++++ src/Cryptography/Algorithms/AlgorithmRsa.h | 17 +++ .../Algorithms/AlgorithmSalsa20.cpp | 46 +++++++ .../Algorithms/AlgorithmSalsa20.h | 10 ++ src/Cryptography/Algorithms/AlgorithmSha1.cpp | 54 ++++++++ src/Cryptography/Algorithms/AlgorithmSha1.h | 10 ++ .../Algorithms/AlgorithmSha256.cpp | 54 ++++++++ src/Cryptography/Algorithms/AlgorithmSha256.h | 10 ++ src/{Crypto/Impl => Cryptography}/Base64.cpp | 10 +- src/{Crypto/Impl => Cryptography}/Base64.h | 2 +- src/Cryptography/Cryptography.h | 7 ++ src/Cryptography/IHashFunction.h | 22 ++++ src/Cryptography/IPublicKeyAlgorithm.h | 30 +++++ src/Cryptography/IStreamCipher.h | 21 ++++ src/Cryptography/Internal/CryptoLibrary.cpp | 18 +++ src/Cryptography/Internal/CryptoLibrary.h | 13 ++ src/ObjLoading.lua | 2 +- .../Game/IW5/Material/JsonMaterialLoader.cpp | 2 +- .../SoundBank/SoundBankWriter.cpp | 4 +- .../XModel/Gltf/Internal/GltfBuffer.cpp | 2 +- .../Game/IW5/Material/JsonMaterialWriter.cpp | 2 +- src/ObjWriting/XModel/Gltf/GltfTextOutput.cpp | 2 +- src/ZoneCommon.lua | 4 +- .../Zone/XChunk/AbstractSalsa20Processor.cpp | 4 +- .../Zone/XChunk/AbstractSalsa20Processor.h | 7 +- .../XChunkProcessorSalsa20Decryption.cpp | 6 +- .../XChunkProcessorSalsa20Encryption.cpp | 2 +- src/ZoneLoading.lua | 4 +- .../Game/IW4/ZoneLoaderFactoryIW4.cpp | 11 +- .../Game/IW5/ZoneLoaderFactoryIW5.cpp | 11 +- .../Game/T6/ZoneLoaderFactoryT6.cpp | 6 +- src/ZoneLoading/Loading/ILoadingStream.h | 5 + .../Processor/ProcessorAuthedBlocks.cpp | 6 +- .../Loading/Processor/ProcessorAuthedBlocks.h | 5 +- .../Processor/ProcessorStreamCipher.cpp | 10 +- .../Loading/Processor/ProcessorStreamCipher.h | 13 +- .../Loading/Steps/StepVerifyHash.cpp | 2 +- .../Loading/Steps/StepVerifyHash.h | 9 +- .../Loading/Steps/StepVerifySignature.cpp | 2 +- .../Loading/Steps/StepVerifySignature.h | 6 +- src/ZoneLoading/Loading/StreamProcessor.h | 6 +- src/ZoneWriting.lua | 4 +- 63 files changed, 550 insertions(+), 723 deletions(-) delete mode 100644 src/Crypto/Crypto.cpp delete mode 100644 src/Crypto/Crypto.h delete mode 100644 src/Crypto/IHashFunction.h delete mode 100644 src/Crypto/IPublicKeyAlgorithm.h delete mode 100644 src/Crypto/IStreamCipher.h delete mode 100644 src/Crypto/Impl/AlgorithmMD5.cpp delete mode 100644 src/Crypto/Impl/AlgorithmMD5.h delete mode 100644 src/Crypto/Impl/AlgorithmRSA.cpp delete mode 100644 src/Crypto/Impl/AlgorithmRSA.h delete mode 100644 src/Crypto/Impl/AlgorithmSHA1.cpp delete mode 100644 src/Crypto/Impl/AlgorithmSHA1.h delete mode 100644 src/Crypto/Impl/AlgorithmSHA256.cpp delete mode 100644 src/Crypto/Impl/AlgorithmSHA256.h delete mode 100644 src/Crypto/Impl/AlgorithmSalsa20.cpp delete mode 100644 src/Crypto/Impl/AlgorithmSalsa20.h delete mode 100644 src/Crypto/Impl/CryptoLibrary.cpp delete mode 100644 src/Crypto/Impl/CryptoLibrary.h rename src/{Crypto.lua => Cryptography.lua} (61%) create mode 100644 src/Cryptography/Algorithms/AlgorithmMd5.cpp create mode 100644 src/Cryptography/Algorithms/AlgorithmMd5.h create mode 100644 src/Cryptography/Algorithms/AlgorithmRsa.cpp create mode 100644 src/Cryptography/Algorithms/AlgorithmRsa.h create mode 100644 src/Cryptography/Algorithms/AlgorithmSalsa20.cpp create mode 100644 src/Cryptography/Algorithms/AlgorithmSalsa20.h create mode 100644 src/Cryptography/Algorithms/AlgorithmSha1.cpp create mode 100644 src/Cryptography/Algorithms/AlgorithmSha1.h create mode 100644 src/Cryptography/Algorithms/AlgorithmSha256.cpp create mode 100644 src/Cryptography/Algorithms/AlgorithmSha256.h rename src/{Crypto/Impl => Cryptography}/Base64.cpp (76%) rename src/{Crypto/Impl => Cryptography}/Base64.h (84%) create mode 100644 src/Cryptography/Cryptography.h create mode 100644 src/Cryptography/IHashFunction.h create mode 100644 src/Cryptography/IPublicKeyAlgorithm.h create mode 100644 src/Cryptography/IStreamCipher.h create mode 100644 src/Cryptography/Internal/CryptoLibrary.cpp create mode 100644 src/Cryptography/Internal/CryptoLibrary.h diff --git a/premake5.lua b/premake5.lua index e0be302a..53f7714d 100644 --- a/premake5.lua +++ b/premake5.lua @@ -117,7 +117,7 @@ group "" -- Projects -- ======================== include "src/Common.lua" -include "src/Crypto.lua" +include "src/Cryptography.lua" include "src/ImageConverter.lua" include "src/Linker.lua" include "src/Parser.lua" @@ -141,7 +141,7 @@ include "tools/scripts/raw.lua" -- Components group: All projects assist or are part of a tool group "Components" Common:project() - Crypto:project() + Cryptography:project() Parser:project() Utils:project() ZoneCode:project() diff --git a/src/Crypto/Crypto.cpp b/src/Crypto/Crypto.cpp deleted file mode 100644 index 3dc07fd7..00000000 --- a/src/Crypto/Crypto.cpp +++ /dev/null @@ -1,32 +0,0 @@ -#include "Crypto.h" - -#include "Impl/AlgorithmMD5.h" -#include "Impl/AlgorithmRSA.h" -#include "Impl/AlgorithmSHA1.h" -#include "Impl/AlgorithmSHA256.h" -#include "Impl/AlgorithmSalsa20.h" - -std::unique_ptr Crypto::CreateMD5() -{ - return std::make_unique(); -} - -std::unique_ptr Crypto::CreateSHA1() -{ - return std::make_unique(); -} - -std::unique_ptr Crypto::CreateSHA256() -{ - return std::make_unique(); -} - -std::unique_ptr Crypto::CreateSalsa20(const uint8_t* keyBytes, const size_t keySize) -{ - return std::make_unique(keyBytes, keySize); -} - -std::unique_ptr Crypto::CreateRSA(const IPublicKeyAlgorithm::HashingAlgorithm hashingAlgorithm, const RSAPaddingMode paddingMode) -{ - return std::make_unique(hashingAlgorithm, paddingMode); -} diff --git a/src/Crypto/Crypto.h b/src/Crypto/Crypto.h deleted file mode 100644 index e7e5edb8..00000000 --- a/src/Crypto/Crypto.h +++ /dev/null @@ -1,27 +0,0 @@ -#pragma once - -#include "IHashFunction.h" -#include "IPublicKeyAlgorithm.h" -#include "IStreamCipher.h" - -#include -#include - -class Crypto -{ -public: - enum class RSAPaddingMode - { - RSA_PADDING_PKS1, - RSA_PADDING_PSS, - }; - - static std::unique_ptr CreateMD5(); - - static std::unique_ptr CreateSHA1(); - static std::unique_ptr CreateSHA256(); - - static std::unique_ptr CreateSalsa20(const uint8_t* keyBytes, size_t keySize); - - static std::unique_ptr CreateRSA(IPublicKeyAlgorithm::HashingAlgorithm hashingAlgorithm, RSAPaddingMode paddingMode); -}; diff --git a/src/Crypto/IHashFunction.h b/src/Crypto/IHashFunction.h deleted file mode 100644 index 81dbec51..00000000 --- a/src/Crypto/IHashFunction.h +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once - -#include - -class IHashFunction -{ -public: - virtual ~IHashFunction() = default; - - virtual size_t GetHashSize() = 0; - virtual void Init() = 0; - virtual void Process(const void* input, size_t inputSize) = 0; - virtual void Finish(void* hashBuffer) = 0; -}; diff --git a/src/Crypto/IPublicKeyAlgorithm.h b/src/Crypto/IPublicKeyAlgorithm.h deleted file mode 100644 index 9764e0a0..00000000 --- a/src/Crypto/IPublicKeyAlgorithm.h +++ /dev/null @@ -1,22 +0,0 @@ -#pragma once - -#include -#include - -class IPublicKeyAlgorithm -{ -public: - enum class HashingAlgorithm - { - RSA_HASH_SHA256, - RSA_HASH_SHA512 - }; - - virtual ~IPublicKeyAlgorithm() = default; - - virtual bool SetKey(const uint8_t* keyData, size_t keySize) = 0; - - // If needed add a signing method - - virtual bool Verify(const uint8_t* signedData, size_t signedDataSize, const uint8_t* signature, size_t signatureSize) = 0; -}; diff --git a/src/Crypto/IStreamCipher.h b/src/Crypto/IStreamCipher.h deleted file mode 100644 index 076f549c..00000000 --- a/src/Crypto/IStreamCipher.h +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once - -#include -#include - -class IStreamCipher -{ -public: - virtual ~IStreamCipher() = default; - - virtual void SetIV(const uint8_t* iv, size_t ivSize) = 0; - - virtual void Process(const void* plainText, void* cipherText, size_t amount) = 0; -}; diff --git a/src/Crypto/Impl/AlgorithmMD5.cpp b/src/Crypto/Impl/AlgorithmMD5.cpp deleted file mode 100644 index 3e14e74b..00000000 --- a/src/Crypto/Impl/AlgorithmMD5.cpp +++ /dev/null @@ -1,64 +0,0 @@ -#include "AlgorithmMD5.h" - -#include "CryptoLibrary.h" - -#include - -class AlgorithmMD5::AlgorithmMD5Impl -{ - hash_state m_state{}; - -public: - AlgorithmMD5Impl() - { - CryptoLibrary::Init(); - - Init(); - } - - void Init() - { - md5_init(&m_state); - } - - void Process(const void* input, const size_t inputSize) - { - md5_process(&m_state, static_cast(input), inputSize); - } - - void Finish(void* hashBuffer) - { - md5_done(&m_state, static_cast(hashBuffer)); - } -}; - -AlgorithmMD5::AlgorithmMD5() -{ - m_impl = new AlgorithmMD5Impl(); -} - -AlgorithmMD5::~AlgorithmMD5() -{ - delete m_impl; - m_impl = nullptr; -} - -size_t AlgorithmMD5::GetHashSize() -{ - return HASH_SIZE; -} - -void AlgorithmMD5::Init() -{ - m_impl->Init(); -} - -void AlgorithmMD5::Process(const void* input, const size_t inputSize) -{ - m_impl->Process(input, inputSize); -} - -void AlgorithmMD5::Finish(void* hashBuffer) -{ - m_impl->Finish(hashBuffer); -} diff --git a/src/Crypto/Impl/AlgorithmMD5.h b/src/Crypto/Impl/AlgorithmMD5.h deleted file mode 100644 index 4687572a..00000000 --- a/src/Crypto/Impl/AlgorithmMD5.h +++ /dev/null @@ -1,20 +0,0 @@ -#pragma once -#include "IHashFunction.h" - -class AlgorithmMD5 : public IHashFunction -{ - class AlgorithmMD5Impl; - AlgorithmMD5Impl* m_impl; - -public: - static const int HASH_SIZE = 16; - - AlgorithmMD5(); - ~AlgorithmMD5() override; - - size_t GetHashSize() override; - - void Init() override; - void Process(const void* input, size_t inputSize) override; - void Finish(void* hashBuffer) override; -}; diff --git a/src/Crypto/Impl/AlgorithmRSA.cpp b/src/Crypto/Impl/AlgorithmRSA.cpp deleted file mode 100644 index ac65adb9..00000000 --- a/src/Crypto/Impl/AlgorithmRSA.cpp +++ /dev/null @@ -1,119 +0,0 @@ -#include "AlgorithmRSA.h" - -#include "CryptoLibrary.h" - -#include - -class AlgorithmRSA::AlgorithmRSAImpl -{ - rsa_key m_key{}; - HashingAlgorithm m_hash; - Crypto::RSAPaddingMode m_padding; - - const ltc_hash_descriptor* GetHashDescriptor() const - { - switch (m_hash) - { - case HashingAlgorithm::RSA_HASH_SHA256: - return &sha256_desc; - - default: - case HashingAlgorithm::RSA_HASH_SHA512: - return &sha512_desc; - } - } - - int GetPaddingMode() const - { - switch (m_padding) - { - case Crypto::RSAPaddingMode::RSA_PADDING_PKS1: - return LTC_PKCS_1_V1_5; - - default: - case Crypto::RSAPaddingMode::RSA_PADDING_PSS: - return LTC_PKCS_1_PSS; - } - } - -public: - AlgorithmRSAImpl(const HashingAlgorithm hash, const Crypto::RSAPaddingMode padding) - { - m_hash = hash; - m_padding = padding; - - CryptoLibrary::Init(); - } - - ~AlgorithmRSAImpl() = default; - - AlgorithmRSAImpl(AlgorithmRSAImpl& other) = default; - AlgorithmRSAImpl(AlgorithmRSAImpl&& other) = delete; - - AlgorithmRSAImpl& operator=(AlgorithmRSAImpl const& other) = default; - AlgorithmRSAImpl& operator=(AlgorithmRSAImpl&& other) = delete; - - bool SetKey(const uint8_t* keyData, const size_t keySize) - { - return rsa_import(keyData, keySize, &m_key) == CRYPT_OK; - } - - bool Verify(const uint8_t* signedData, const size_t signedDataSize, const uint8_t* signature, const size_t signatureSize) - { - const ltc_hash_descriptor* hashDesc = GetHashDescriptor(); - const int hashId = register_hash(hashDesc); - const int padding = GetPaddingMode(); - - int result; - rsa_verify_hash_ex(signature, signatureSize, signedData, signedDataSize, padding, hashId, 8, &result, &m_key); - - return result == 1; - } -}; - -AlgorithmRSA::AlgorithmRSA(const HashingAlgorithm hash, const Crypto::RSAPaddingMode padding) -{ - m_impl = new AlgorithmRSAImpl(hash, padding); -} - -AlgorithmRSA::~AlgorithmRSA() -{ - delete m_impl; - m_impl = nullptr; -} - -AlgorithmRSA::AlgorithmRSA(AlgorithmRSA& other) -{ - m_impl = new AlgorithmRSAImpl(*other.m_impl); -} - -AlgorithmRSA::AlgorithmRSA(AlgorithmRSA&& other) noexcept -{ - m_impl = other.m_impl; - other.m_impl = nullptr; -} - -AlgorithmRSA& AlgorithmRSA::operator=(AlgorithmRSA const& other) -{ - m_impl = new AlgorithmRSAImpl(*other.m_impl); - - return *this; -} - -AlgorithmRSA& AlgorithmRSA::operator=(AlgorithmRSA&& other) noexcept -{ - m_impl = other.m_impl; - other.m_impl = nullptr; - - return *this; -} - -bool AlgorithmRSA::SetKey(const uint8_t* keyData, size_t keySize) -{ - return m_impl->SetKey(keyData, keySize); -} - -bool AlgorithmRSA::Verify(const uint8_t* signedData, const size_t signedDataSize, const uint8_t* signature, const size_t signatureSize) -{ - return m_impl->Verify(signedData, signedDataSize, signature, signatureSize); -} diff --git a/src/Crypto/Impl/AlgorithmRSA.h b/src/Crypto/Impl/AlgorithmRSA.h deleted file mode 100644 index f84cee0e..00000000 --- a/src/Crypto/Impl/AlgorithmRSA.h +++ /dev/null @@ -1,25 +0,0 @@ -#pragma once -#include "Crypto.h" -#include "IPublicKeyAlgorithm.h" - -#include - -class AlgorithmRSA final : public IPublicKeyAlgorithm -{ - class AlgorithmRSAImpl; - AlgorithmRSAImpl* m_impl; - -public: - AlgorithmRSA(HashingAlgorithm hash, Crypto::RSAPaddingMode padding); - ~AlgorithmRSA() override; - - AlgorithmRSA(AlgorithmRSA& other); - AlgorithmRSA(AlgorithmRSA&& other) noexcept; - - AlgorithmRSA& operator=(AlgorithmRSA const& other); - AlgorithmRSA& operator=(AlgorithmRSA&& other) noexcept; - - bool SetKey(const uint8_t* keyData, size_t keySize) override; - - bool Verify(const uint8_t* signedData, size_t signedDataSize, const uint8_t* signature, size_t signatureSize) override; -}; diff --git a/src/Crypto/Impl/AlgorithmSHA1.cpp b/src/Crypto/Impl/AlgorithmSHA1.cpp deleted file mode 100644 index 21558383..00000000 --- a/src/Crypto/Impl/AlgorithmSHA1.cpp +++ /dev/null @@ -1,64 +0,0 @@ -#include "AlgorithmSHA1.h" - -#include "CryptoLibrary.h" - -#include - -class AlgorithmSHA1::AlgorithmSHA1Impl -{ - hash_state m_state{}; - -public: - AlgorithmSHA1Impl() - { - CryptoLibrary::Init(); - - Init(); - } - - void Init() - { - sha1_init(&m_state); - } - - void Process(const void* input, const size_t inputSize) - { - sha1_process(&m_state, static_cast(input), inputSize); - } - - void Finish(void* hashBuffer) - { - sha1_done(&m_state, static_cast(hashBuffer)); - } -}; - -AlgorithmSHA1::AlgorithmSHA1() -{ - m_impl = new AlgorithmSHA1Impl(); -} - -AlgorithmSHA1::~AlgorithmSHA1() -{ - delete m_impl; - m_impl = nullptr; -} - -size_t AlgorithmSHA1::GetHashSize() -{ - return HASH_SIZE; -} - -void AlgorithmSHA1::Init() -{ - m_impl->Init(); -} - -void AlgorithmSHA1::Process(const void* input, const size_t inputSize) -{ - m_impl->Process(input, inputSize); -} - -void AlgorithmSHA1::Finish(void* hashBuffer) -{ - m_impl->Finish(hashBuffer); -} diff --git a/src/Crypto/Impl/AlgorithmSHA1.h b/src/Crypto/Impl/AlgorithmSHA1.h deleted file mode 100644 index f9ae0514..00000000 --- a/src/Crypto/Impl/AlgorithmSHA1.h +++ /dev/null @@ -1,20 +0,0 @@ -#pragma once -#include "IHashFunction.h" - -class AlgorithmSHA1 : public IHashFunction -{ - class AlgorithmSHA1Impl; - AlgorithmSHA1Impl* m_impl; - -public: - static const int HASH_SIZE = 20; - - AlgorithmSHA1(); - ~AlgorithmSHA1() override; - - size_t GetHashSize() override; - - void Init() override; - void Process(const void* input, size_t inputSize) override; - void Finish(void* hashBuffer) override; -}; diff --git a/src/Crypto/Impl/AlgorithmSHA256.cpp b/src/Crypto/Impl/AlgorithmSHA256.cpp deleted file mode 100644 index a1bf1964..00000000 --- a/src/Crypto/Impl/AlgorithmSHA256.cpp +++ /dev/null @@ -1,64 +0,0 @@ -#include "AlgorithmSHA256.h" - -#include "CryptoLibrary.h" - -#include - -class AlgorithmSHA256::Impl -{ - hash_state m_state{}; - -public: - Impl() - { - CryptoLibrary::Init(); - - Init(); - } - - void Init() - { - sha256_init(&m_state); - } - - void Process(const void* input, const size_t inputSize) - { - sha256_process(&m_state, static_cast(input), inputSize); - } - - void Finish(void* hashBuffer) - { - sha256_done(&m_state, static_cast(hashBuffer)); - } -}; - -AlgorithmSHA256::AlgorithmSHA256() -{ - m_impl = new Impl(); -} - -AlgorithmSHA256::~AlgorithmSHA256() -{ - delete m_impl; - m_impl = nullptr; -} - -size_t AlgorithmSHA256::GetHashSize() -{ - return HASH_SIZE; -} - -void AlgorithmSHA256::Init() -{ - m_impl->Init(); -} - -void AlgorithmSHA256::Process(const void* input, const size_t inputSize) -{ - m_impl->Process(input, inputSize); -} - -void AlgorithmSHA256::Finish(void* hashBuffer) -{ - m_impl->Finish(hashBuffer); -} diff --git a/src/Crypto/Impl/AlgorithmSHA256.h b/src/Crypto/Impl/AlgorithmSHA256.h deleted file mode 100644 index 54875a2a..00000000 --- a/src/Crypto/Impl/AlgorithmSHA256.h +++ /dev/null @@ -1,20 +0,0 @@ -#pragma once -#include "IHashFunction.h" - -class AlgorithmSHA256 : public IHashFunction -{ - class Impl; - Impl* m_impl; - -public: - static const int HASH_SIZE = 32; - - AlgorithmSHA256(); - ~AlgorithmSHA256() override; - - size_t GetHashSize() override; - - void Init() override; - void Process(const void* input, size_t inputSize) override; - void Finish(void* hashBuffer) override; -}; diff --git a/src/Crypto/Impl/AlgorithmSalsa20.cpp b/src/Crypto/Impl/AlgorithmSalsa20.cpp deleted file mode 100644 index 2c5459d6..00000000 --- a/src/Crypto/Impl/AlgorithmSalsa20.cpp +++ /dev/null @@ -1,89 +0,0 @@ -#include "AlgorithmSalsa20.h" - -#include "salsa20.h" - -#include -#include - -class AlgorithmSalsa20::AlgorithmSalsa20Impl -{ - salsa20_ctx m_context{}; - -public: - AlgorithmSalsa20Impl(const uint8_t* keyBytes, const size_t keySize) - { - Salsa20_KeySetup(&m_context, keyBytes, keySize * 8); - } - - ~AlgorithmSalsa20Impl() = default; - - AlgorithmSalsa20Impl(AlgorithmSalsa20Impl& other) = default; - AlgorithmSalsa20Impl(AlgorithmSalsa20Impl&& other) = delete; - - AlgorithmSalsa20Impl& operator=(AlgorithmSalsa20Impl const& other) = default; - AlgorithmSalsa20Impl& operator=(AlgorithmSalsa20Impl&& other) = delete; - - void SetIV(const uint8_t* iv, const size_t ivSize) - { - assert(ivSize == 8); - - if (ivSize != 8) - { - throw std::invalid_argument("Salsa20 IV size must be 8"); - } - - Salsa20_IVSetup(&m_context, iv); - } - - void Process(const void* plainText, void* cipherText, const size_t amount) - { - Salsa20_Encrypt_Bytes(&m_context, static_cast(plainText), static_cast(cipherText), amount); - } -}; - -AlgorithmSalsa20::AlgorithmSalsa20(const uint8_t* keyBytes, const size_t keySize) -{ - m_impl = new AlgorithmSalsa20Impl(keyBytes, keySize); -} - -AlgorithmSalsa20::~AlgorithmSalsa20() -{ - delete m_impl; - m_impl = nullptr; -} - -AlgorithmSalsa20::AlgorithmSalsa20(AlgorithmSalsa20& other) -{ - m_impl = new AlgorithmSalsa20Impl(*other.m_impl); -} - -AlgorithmSalsa20::AlgorithmSalsa20(AlgorithmSalsa20&& other) noexcept -{ - m_impl = other.m_impl; - other.m_impl = nullptr; -} - -AlgorithmSalsa20& AlgorithmSalsa20::operator=(AlgorithmSalsa20 const& other) -{ - m_impl = new AlgorithmSalsa20Impl(*other.m_impl); - - return *this; -} - -AlgorithmSalsa20& AlgorithmSalsa20::operator=(AlgorithmSalsa20&& other) noexcept -{ - m_impl = other.m_impl; - other.m_impl = nullptr; - - return *this; -} - -void AlgorithmSalsa20::SetIV(const uint8_t* iv, const size_t ivSize) -{ - m_impl->SetIV(iv, ivSize); -} - -void AlgorithmSalsa20::Process(const void* plainText, void* cipherText, const size_t amount) -{ - m_impl->Process(plainText, cipherText, amount); -} diff --git a/src/Crypto/Impl/AlgorithmSalsa20.h b/src/Crypto/Impl/AlgorithmSalsa20.h deleted file mode 100644 index 88c0d6ca..00000000 --- a/src/Crypto/Impl/AlgorithmSalsa20.h +++ /dev/null @@ -1,21 +0,0 @@ -#pragma once -#include "IStreamCipher.h" - -class AlgorithmSalsa20 final : public IStreamCipher -{ - class AlgorithmSalsa20Impl; - AlgorithmSalsa20Impl* m_impl; - -public: - AlgorithmSalsa20(const uint8_t* keyBytes, size_t keySize); - ~AlgorithmSalsa20() override; - - AlgorithmSalsa20(AlgorithmSalsa20& other); - AlgorithmSalsa20(AlgorithmSalsa20&& other) noexcept; - - AlgorithmSalsa20& operator=(AlgorithmSalsa20 const& other); - AlgorithmSalsa20& operator=(AlgorithmSalsa20&& other) noexcept; - - void SetIV(const uint8_t* iv, size_t ivSize) override; - void Process(const void* plainText, void* cipherText, size_t amount) override; -}; diff --git a/src/Crypto/Impl/CryptoLibrary.cpp b/src/Crypto/Impl/CryptoLibrary.cpp deleted file mode 100644 index 3db79799..00000000 --- a/src/Crypto/Impl/CryptoLibrary.cpp +++ /dev/null @@ -1,15 +0,0 @@ -#include "CryptoLibrary.h" - -#include "tommath.h" - -void CryptoLibrary::Init() -{ - static bool initialized = false; - - if (!initialized) - { - initialized = true; - - ltc_mp = ltm_desc; - } -} diff --git a/src/Crypto/Impl/CryptoLibrary.h b/src/Crypto/Impl/CryptoLibrary.h deleted file mode 100644 index 68829c41..00000000 --- a/src/Crypto/Impl/CryptoLibrary.h +++ /dev/null @@ -1,10 +0,0 @@ -#pragma once - -#define LTC_NO_PROTOTYPES -#include "tomcrypt.h" - -class CryptoLibrary -{ -public: - static void Init(); -}; diff --git a/src/Crypto.lua b/src/Cryptography.lua similarity index 61% rename from src/Crypto.lua rename to src/Cryptography.lua index 96cd1670..a3740ddc 100644 --- a/src/Crypto.lua +++ b/src/Cryptography.lua @@ -1,29 +1,29 @@ -Crypto = {} +Cryptography = {} -function Crypto:include(includes) +function Cryptography:include(includes) if includes:handle(self:name()) then includedirs { - path.join(ProjectFolder(), "Crypto") + path.join(ProjectFolder(), "Cryptography") } end end -function Crypto:link(links) +function Cryptography:link(links) links:add(self:name()) links:linkto(libtomcrypt) links:linkto(libtommath) links:linkto(salsa20) end -function Crypto:use() +function Cryptography:use() end -function Crypto:name() - return "Crypto" +function Cryptography:name() + return "Cryptography" end -function Crypto:project() +function Cryptography:project() local folder = ProjectFolder() local includes = Includes:create() @@ -34,8 +34,8 @@ function Crypto:project() language "C++" files { - path.join(folder, "Crypto/**.h"), - path.join(folder, "Crypto/**.cpp") + path.join(folder, "Cryptography/**.h"), + path.join(folder, "Cryptography/**.cpp") } self:include(includes) diff --git a/src/Cryptography/Algorithms/AlgorithmMd5.cpp b/src/Cryptography/Algorithms/AlgorithmMd5.cpp new file mode 100644 index 00000000..501bc20e --- /dev/null +++ b/src/Cryptography/Algorithms/AlgorithmMd5.cpp @@ -0,0 +1,54 @@ +#include "AlgorithmMd5.h" + +#include "Internal/CryptoLibrary.h" + +#include + +using namespace cryptography; + +namespace +{ + constexpr int HASH_SIZE = 16; + + class AlgorithmMd5 final : public IHashFunction + { + public: + AlgorithmMd5() + { + internal::CryptoLibrary::Init(); + + Init(); + } + + size_t GetHashSize() override + { + return HASH_SIZE; + } + + void Init() override + { + md5_init(&m_state); + } + + void Process(const void* input, const size_t inputSize) override + { + md5_process(&m_state, static_cast(input), static_cast(inputSize)); + } + + void Finish(void* hashBuffer) override + { + md5_done(&m_state, static_cast(hashBuffer)); + } + + private: + hash_state m_state{}; + }; +} // namespace + +namespace cryptography +{ + std::unique_ptr CreateMd5() + { + return std::make_unique(); + } +} // namespace cryptography diff --git a/src/Cryptography/Algorithms/AlgorithmMd5.h b/src/Cryptography/Algorithms/AlgorithmMd5.h new file mode 100644 index 00000000..d321408e --- /dev/null +++ b/src/Cryptography/Algorithms/AlgorithmMd5.h @@ -0,0 +1,10 @@ +#pragma once + +#include "IHashFunction.h" + +#include + +namespace cryptography +{ + std::unique_ptr CreateMd5(); +} diff --git a/src/Cryptography/Algorithms/AlgorithmRsa.cpp b/src/Cryptography/Algorithms/AlgorithmRsa.cpp new file mode 100644 index 00000000..450fdf71 --- /dev/null +++ b/src/Cryptography/Algorithms/AlgorithmRsa.cpp @@ -0,0 +1,84 @@ +#include "AlgorithmRsa.h" + +#include "Internal/CryptoLibrary.h" + +using namespace cryptography; + +namespace +{ + class AlgorithmRsa final : public IPublicKeyAlgorithm + { + public: + AlgorithmRsa(const HashingAlgorithm hash, const RsaPaddingMode padding) + { + m_hash = hash; + m_padding = padding; + + internal::CryptoLibrary::Init(); + } + + bool SetKey(const uint8_t* keyData, const size_t keySize) override + { + return rsa_import(keyData, static_cast(keySize), &m_key) == CRYPT_OK; + } + + bool Verify(const uint8_t* signedData, const size_t signedDataSize, const uint8_t* signature, const size_t signatureSize) override + { + const ltc_hash_descriptor* hashDesc = GetHashDescriptor(); + const int hashId = register_hash(hashDesc); + const int padding = GetPaddingMode(); + + int result; + rsa_verify_hash_ex(signature, + static_cast(signatureSize), + signedData, + static_cast(signedDataSize), + padding, + hashId, + 8, + &result, + &m_key); + + return result == 1; + } + + private: + [[nodiscard]] const ltc_hash_descriptor* GetHashDescriptor() const + { + switch (m_hash) + { + case HashingAlgorithm::RSA_HASH_SHA256: + return &sha256_desc; + + default: + case HashingAlgorithm::RSA_HASH_SHA512: + return &sha512_desc; + } + } + + [[nodiscard]] int GetPaddingMode() const + { + switch (m_padding) + { + case RsaPaddingMode::RSA_PADDING_PKS1: + return LTC_PKCS_1_V1_5; + + default: + case RsaPaddingMode::RSA_PADDING_PSS: + return LTC_PKCS_1_PSS; + } + } + + rsa_key m_key{}; + HashingAlgorithm m_hash; + RsaPaddingMode m_padding; + }; +} // namespace + +namespace cryptography +{ + std::unique_ptr CreateRsa(const HashingAlgorithm hashingAlgorithm, const RsaPaddingMode paddingMode) + { + return std::make_unique(hashingAlgorithm, paddingMode); + } +} // namespace cryptography diff --git a/src/Cryptography/Algorithms/AlgorithmRsa.h b/src/Cryptography/Algorithms/AlgorithmRsa.h new file mode 100644 index 00000000..5a682bc3 --- /dev/null +++ b/src/Cryptography/Algorithms/AlgorithmRsa.h @@ -0,0 +1,17 @@ +#pragma once + +#include "IPublicKeyAlgorithm.h" + +#include +#include + +namespace cryptography +{ + enum class RsaPaddingMode : std::uint8_t + { + RSA_PADDING_PKS1, + RSA_PADDING_PSS, + }; + + std::unique_ptr CreateRsa(HashingAlgorithm hashingAlgorithm, RsaPaddingMode paddingMode); +} // namespace cryptography diff --git a/src/Cryptography/Algorithms/AlgorithmSalsa20.cpp b/src/Cryptography/Algorithms/AlgorithmSalsa20.cpp new file mode 100644 index 00000000..9a58e8d6 --- /dev/null +++ b/src/Cryptography/Algorithms/AlgorithmSalsa20.cpp @@ -0,0 +1,46 @@ +#include "AlgorithmSalsa20.h" + +#include "salsa20.h" + +#include +#include + +using namespace cryptography; + +namespace +{ + class AlgorithmSalsa20 final : public IStreamCipher + { + public: + AlgorithmSalsa20(const uint8_t* keyBytes, const size_t keySize) + { + Salsa20_KeySetup(&m_context, keyBytes, static_cast(keySize * 8uz)); + } + + void SetIv(const uint8_t* iv, const size_t ivSize) override + { + assert(ivSize == 8); + + if (ivSize != 8) + throw std::invalid_argument("Salsa20 IV size must be 8"); + + Salsa20_IVSetup(&m_context, iv); + } + + void Process(const void* plainText, void* cipherText, const size_t amount) override + { + Salsa20_Encrypt_Bytes(&m_context, static_cast(plainText), static_cast(cipherText), static_cast(amount)); + } + + private: + salsa20_ctx m_context{}; + }; +} // namespace + +namespace cryptography +{ + std::unique_ptr CreateSalsa20(const uint8_t* keyBytes, const size_t keySize) + { + return std::make_unique(keyBytes, keySize); + } +} // namespace cryptography diff --git a/src/Cryptography/Algorithms/AlgorithmSalsa20.h b/src/Cryptography/Algorithms/AlgorithmSalsa20.h new file mode 100644 index 00000000..1e5c95be --- /dev/null +++ b/src/Cryptography/Algorithms/AlgorithmSalsa20.h @@ -0,0 +1,10 @@ +#pragma once + +#include "IStreamCipher.h" + +#include + +namespace cryptography +{ + std::unique_ptr CreateSalsa20(const uint8_t* keyBytes, size_t keySize); +} diff --git a/src/Cryptography/Algorithms/AlgorithmSha1.cpp b/src/Cryptography/Algorithms/AlgorithmSha1.cpp new file mode 100644 index 00000000..4e394a50 --- /dev/null +++ b/src/Cryptography/Algorithms/AlgorithmSha1.cpp @@ -0,0 +1,54 @@ +#include "AlgorithmSha1.h" + +#include "Internal/CryptoLibrary.h" + +#include + +using namespace cryptography; + +namespace +{ + constexpr int HASH_SIZE = 20; + + class AlgorithmSha1 final : public IHashFunction + { + public: + AlgorithmSha1() + { + internal::CryptoLibrary::Init(); + + Init(); + } + + size_t GetHashSize() override + { + return HASH_SIZE; + } + + void Init() override + { + sha1_init(&m_state); + } + + void Process(const void* input, const size_t inputSize) override + { + sha1_process(&m_state, static_cast(input), static_cast(inputSize)); + } + + void Finish(void* hashBuffer) override + { + sha1_done(&m_state, static_cast(hashBuffer)); + } + + private: + hash_state m_state{}; + }; +} // namespace + +namespace cryptography +{ + std::unique_ptr CreateSha1() + { + return std::make_unique(); + } +} // namespace cryptography diff --git a/src/Cryptography/Algorithms/AlgorithmSha1.h b/src/Cryptography/Algorithms/AlgorithmSha1.h new file mode 100644 index 00000000..41e11ac8 --- /dev/null +++ b/src/Cryptography/Algorithms/AlgorithmSha1.h @@ -0,0 +1,10 @@ +#pragma once + +#include "IHashFunction.h" + +#include + +namespace cryptography +{ + std::unique_ptr CreateSha1(); +} diff --git a/src/Cryptography/Algorithms/AlgorithmSha256.cpp b/src/Cryptography/Algorithms/AlgorithmSha256.cpp new file mode 100644 index 00000000..662c8e4a --- /dev/null +++ b/src/Cryptography/Algorithms/AlgorithmSha256.cpp @@ -0,0 +1,54 @@ +#include "AlgorithmSha256.h" + +#include "Internal/CryptoLibrary.h" + +#include + +using namespace cryptography; + +namespace +{ + constexpr int HASH_SIZE = 32; + + class AlgorithmSha256 final : public IHashFunction + { + public: + AlgorithmSha256() + { + internal::CryptoLibrary::Init(); + + Init(); + } + + size_t GetHashSize() override + { + return HASH_SIZE; + } + + void Init() override + { + sha256_init(&m_state); + } + + void Process(const void* input, const size_t inputSize) override + { + sha256_process(&m_state, static_cast(input), static_cast(inputSize)); + } + + void Finish(void* hashBuffer) override + { + sha256_done(&m_state, static_cast(hashBuffer)); + } + + private: + hash_state m_state{}; + }; +} // namespace + +namespace cryptography +{ + std::unique_ptr CreateSha256() + { + return std::make_unique(); + } +} // namespace cryptography diff --git a/src/Cryptography/Algorithms/AlgorithmSha256.h b/src/Cryptography/Algorithms/AlgorithmSha256.h new file mode 100644 index 00000000..22bb1372 --- /dev/null +++ b/src/Cryptography/Algorithms/AlgorithmSha256.h @@ -0,0 +1,10 @@ +#pragma once + +#include "IHashFunction.h" + +#include + +namespace cryptography +{ + std::unique_ptr CreateSha256(); +} diff --git a/src/Crypto/Impl/Base64.cpp b/src/Cryptography/Base64.cpp similarity index 76% rename from src/Crypto/Impl/Base64.cpp rename to src/Cryptography/Base64.cpp index 77d1717f..135faa70 100644 --- a/src/Crypto/Impl/Base64.cpp +++ b/src/Cryptography/Base64.cpp @@ -20,8 +20,9 @@ namespace base64 bool EncodeBase64(const void* inputData, const size_t inputLength, void* outputBuffer, const size_t outputBufferSize) { - unsigned long outLength = outputBufferSize; - const auto result = base64_encode(static_cast(inputData), inputLength, static_cast(outputBuffer), &outLength); + unsigned long outLength = static_cast(outputBufferSize); + const auto result = + base64_encode(static_cast(inputData), static_cast(inputLength), static_cast(outputBuffer), &outLength); return result == CRYPT_OK; } @@ -32,12 +33,13 @@ namespace base64 size_t DecodeBase64(const void* base64Data, const size_t inputLength, void* outputBuffer, const size_t outputBufferSize) { - unsigned long outLength = GetBase64DecodeOutputLength(base64Data, inputLength); + auto outLength = static_cast(GetBase64DecodeOutputLength(base64Data, inputLength)); assert(outLength <= outputBufferSize); if (outLength > outputBufferSize) return 0u; - const auto result = base64_decode(static_cast(base64Data), inputLength, static_cast(outputBuffer), &outLength); + const auto result = + base64_decode(static_cast(base64Data), static_cast(inputLength), static_cast(outputBuffer), &outLength); assert(result == CRYPT_OK); return static_cast(outLength); diff --git a/src/Crypto/Impl/Base64.h b/src/Cryptography/Base64.h similarity index 84% rename from src/Crypto/Impl/Base64.h rename to src/Cryptography/Base64.h index 8264a8c3..5c28685b 100644 --- a/src/Crypto/Impl/Base64.h +++ b/src/Cryptography/Base64.h @@ -8,6 +8,6 @@ namespace base64 size_t GetBase64EncodeOutputLength(size_t inputLength); size_t DecodeBase64(const void* base64Data, size_t inputLength, void* outputBuffer, size_t outputBufferSize); - size_t GetBase64DecodeOutputLength(const void* base64Data, const size_t inputLength); + size_t GetBase64DecodeOutputLength(const void* base64Data, size_t inputLength); size_t GetBase64DecodeOutputLength(size_t inputLength); } // namespace base64 diff --git a/src/Cryptography/Cryptography.h b/src/Cryptography/Cryptography.h new file mode 100644 index 00000000..8aff466f --- /dev/null +++ b/src/Cryptography/Cryptography.h @@ -0,0 +1,7 @@ +#pragma once + +#include "Algorithms/AlgorithmMd5.h" +#include "Algorithms/AlgorithmRsa.h" +#include "Algorithms/AlgorithmSalsa20.h" +#include "Algorithms/AlgorithmSha1.h" +#include "Algorithms/AlgorithmSha256.h" diff --git a/src/Cryptography/IHashFunction.h b/src/Cryptography/IHashFunction.h new file mode 100644 index 00000000..a7519b3c --- /dev/null +++ b/src/Cryptography/IHashFunction.h @@ -0,0 +1,22 @@ +#pragma once + +#include + +namespace cryptography +{ + class IHashFunction + { + public: + IHashFunction() = default; + virtual ~IHashFunction() = default; + IHashFunction(const IHashFunction& other) = default; + IHashFunction(IHashFunction&& other) noexcept = default; + IHashFunction& operator=(const IHashFunction& other) = default; + IHashFunction& operator=(IHashFunction&& other) noexcept = default; + + virtual size_t GetHashSize() = 0; + virtual void Init() = 0; + virtual void Process(const void* input, size_t inputSize) = 0; + virtual void Finish(void* hashBuffer) = 0; + }; +} // namespace cryptography diff --git a/src/Cryptography/IPublicKeyAlgorithm.h b/src/Cryptography/IPublicKeyAlgorithm.h new file mode 100644 index 00000000..475409df --- /dev/null +++ b/src/Cryptography/IPublicKeyAlgorithm.h @@ -0,0 +1,30 @@ +#pragma once + +#include +#include + +namespace cryptography +{ + enum class HashingAlgorithm : std::uint8_t + { + RSA_HASH_SHA256, + RSA_HASH_SHA512 + }; + + class IPublicKeyAlgorithm + { + public: + IPublicKeyAlgorithm() = default; + virtual ~IPublicKeyAlgorithm() = default; + IPublicKeyAlgorithm(const IPublicKeyAlgorithm& other) = default; + IPublicKeyAlgorithm(IPublicKeyAlgorithm&& other) noexcept = default; + IPublicKeyAlgorithm& operator=(const IPublicKeyAlgorithm& other) = default; + IPublicKeyAlgorithm& operator=(IPublicKeyAlgorithm&& other) noexcept = default; + + virtual bool SetKey(const uint8_t* keyData, size_t keySize) = 0; + + // If needed, add a signing method + + virtual bool Verify(const uint8_t* signedData, size_t signedDataSize, const uint8_t* signature, size_t signatureSize) = 0; + }; +} // namespace cryptography diff --git a/src/Cryptography/IStreamCipher.h b/src/Cryptography/IStreamCipher.h new file mode 100644 index 00000000..7c2da861 --- /dev/null +++ b/src/Cryptography/IStreamCipher.h @@ -0,0 +1,21 @@ +#pragma once + +#include +#include + +namespace cryptography +{ + class IStreamCipher + { + public: + IStreamCipher() = default; + virtual ~IStreamCipher() = default; + IStreamCipher(const IStreamCipher& other) = default; + IStreamCipher(IStreamCipher&& other) noexcept = default; + IStreamCipher& operator=(const IStreamCipher& other) = default; + IStreamCipher& operator=(IStreamCipher&& other) noexcept = default; + + virtual void SetIv(const uint8_t* iv, size_t ivSize) = 0; + virtual void Process(const void* plainText, void* cipherText, size_t amount) = 0; + }; +} // namespace cryptography diff --git a/src/Cryptography/Internal/CryptoLibrary.cpp b/src/Cryptography/Internal/CryptoLibrary.cpp new file mode 100644 index 00000000..150ecd5e --- /dev/null +++ b/src/Cryptography/Internal/CryptoLibrary.cpp @@ -0,0 +1,18 @@ +#include "CryptoLibrary.h" + +#include "tommath.h" + +namespace cryptography::internal +{ + void CryptoLibrary::Init() + { + static bool initialized = false; + + if (!initialized) + { + initialized = true; + + ltc_mp = ltm_desc; + } + } +} // namespace cryptography::internal diff --git a/src/Cryptography/Internal/CryptoLibrary.h b/src/Cryptography/Internal/CryptoLibrary.h new file mode 100644 index 00000000..566a1917 --- /dev/null +++ b/src/Cryptography/Internal/CryptoLibrary.h @@ -0,0 +1,13 @@ +#pragma once + +#define LTC_NO_PROTOTYPES +#include "tomcrypt.h" + +namespace cryptography::internal +{ + class CryptoLibrary + { + public: + static void Init(); + }; +} // namespace cryptography::internal diff --git a/src/ObjLoading.lua b/src/ObjLoading.lua index 712ad146..70e945df 100644 --- a/src/ObjLoading.lua +++ b/src/ObjLoading.lua @@ -55,7 +55,7 @@ function ObjLoading:project() useSourceTemplating("ObjLoading") self:include(includes) - Crypto:include(includes) + Cryptography:include(includes) Utils:include(includes) minilzo:include(includes) minizip:include(includes) diff --git a/src/ObjLoading/Game/IW5/Material/JsonMaterialLoader.cpp b/src/ObjLoading/Game/IW5/Material/JsonMaterialLoader.cpp index 3742f848..55380c30 100644 --- a/src/ObjLoading/Game/IW5/Material/JsonMaterialLoader.cpp +++ b/src/ObjLoading/Game/IW5/Material/JsonMaterialLoader.cpp @@ -1,8 +1,8 @@ #include "JsonMaterialLoader.h" +#include "Base64.h" #include "Game/IW5/CommonIW5.h" #include "Game/IW5/Material/JsonMaterial.h" -#include "Impl/Base64.h" #include #include diff --git a/src/ObjLoading/ObjContainer/SoundBank/SoundBankWriter.cpp b/src/ObjLoading/ObjContainer/SoundBank/SoundBankWriter.cpp index 4910f628..fa31a407 100644 --- a/src/ObjLoading/ObjContainer/SoundBank/SoundBankWriter.cpp +++ b/src/ObjLoading/ObjContainer/SoundBank/SoundBankWriter.cpp @@ -1,6 +1,6 @@ #include "SoundBankWriter.h" -#include "Crypto.h" +#include "Cryptography.h" #include "ObjContainer/SoundBank/SoundBankTypes.h" #include "Sound/FlacDecoder.h" #include "Sound/WavTypes.h" @@ -251,7 +251,7 @@ public: SoundAssetBankChecksum checksum{}; - const auto md5Crypt = Crypto::CreateMD5(); + const auto md5Crypt = cryptography::CreateMd5(); md5Crypt->Process(soundData.get(), soundSize); md5Crypt->Finish(checksum.checksumBytes); diff --git a/src/ObjLoading/XModel/Gltf/Internal/GltfBuffer.cpp b/src/ObjLoading/XModel/Gltf/Internal/GltfBuffer.cpp index fcca640b..d7bd6d3a 100644 --- a/src/ObjLoading/XModel/Gltf/Internal/GltfBuffer.cpp +++ b/src/ObjLoading/XModel/Gltf/Internal/GltfBuffer.cpp @@ -1,6 +1,6 @@ #include "GltfBuffer.h" -#include "Impl/Base64.h" +#include "Base64.h" #include "XModel/Gltf/GltfConstants.h" #include diff --git a/src/ObjWriting/Game/IW5/Material/JsonMaterialWriter.cpp b/src/ObjWriting/Game/IW5/Material/JsonMaterialWriter.cpp index 66ec64b4..ff36505a 100644 --- a/src/ObjWriting/Game/IW5/Material/JsonMaterialWriter.cpp +++ b/src/ObjWriting/Game/IW5/Material/JsonMaterialWriter.cpp @@ -1,8 +1,8 @@ #include "JsonMaterialWriter.h" +#include "Base64.h" #include "Game/IW5/CommonIW5.h" #include "Game/IW5/Material/JsonMaterial.h" -#include "Impl/Base64.h" #include "MaterialConstantZoneState.h" #include diff --git a/src/ObjWriting/XModel/Gltf/GltfTextOutput.cpp b/src/ObjWriting/XModel/Gltf/GltfTextOutput.cpp index 49afebd6..c80a72f9 100644 --- a/src/ObjWriting/XModel/Gltf/GltfTextOutput.cpp +++ b/src/ObjWriting/XModel/Gltf/GltfTextOutput.cpp @@ -6,7 +6,7 @@ #include #define LTC_NO_PROTOTYPES -#include "Impl/Base64.h" +#include "Base64.h" #include diff --git a/src/ZoneCommon.lua b/src/ZoneCommon.lua index fa9fd969..3f005f49 100644 --- a/src/ZoneCommon.lua +++ b/src/ZoneCommon.lua @@ -9,14 +9,14 @@ function ZoneCommon:include(includes) Common:include(includes) ObjCommon:include(includes) Parser:include(includes) - Crypto:include(includes) + Cryptography:include(includes) end end function ZoneCommon:link(links) links:add(self:name()) links:linkto(Common) - links:linkto(Crypto) + links:linkto(Cryptography) links:linkto(ObjCommon) links:linkto(Parser) links:linkto(Utils) diff --git a/src/ZoneCommon/Zone/XChunk/AbstractSalsa20Processor.cpp b/src/ZoneCommon/Zone/XChunk/AbstractSalsa20Processor.cpp index a89f6bc7..377a74be 100644 --- a/src/ZoneCommon/Zone/XChunk/AbstractSalsa20Processor.cpp +++ b/src/ZoneCommon/Zone/XChunk/AbstractSalsa20Processor.cpp @@ -40,8 +40,8 @@ void AbstractSalsa20Processor::InitStreams(const std::string& zoneName, const ui { m_stream_block_indices[stream] = 0; - m_stream_contexts[stream].m_salsa20 = Crypto::CreateSalsa20(salsa20Key, keySize); - m_stream_contexts[stream].m_sha1 = Crypto::CreateSHA1(); + m_stream_contexts[stream].m_salsa20 = cryptography::CreateSalsa20(salsa20Key, keySize); + m_stream_contexts[stream].m_sha1 = cryptography::CreateSha1(); } } diff --git a/src/ZoneCommon/Zone/XChunk/AbstractSalsa20Processor.h b/src/ZoneCommon/Zone/XChunk/AbstractSalsa20Processor.h index 38ed4aad..01d56a63 100644 --- a/src/ZoneCommon/Zone/XChunk/AbstractSalsa20Processor.h +++ b/src/ZoneCommon/Zone/XChunk/AbstractSalsa20Processor.h @@ -1,5 +1,6 @@ #pragma once -#include "Crypto.h" + +#include "Cryptography.h" #include "Utils/ClassUtils.h" #include "Utils/ICapturedDataProvider.h" @@ -17,8 +18,8 @@ protected: class StreamContext { public: - std::unique_ptr m_salsa20; - std::unique_ptr m_sha1; + std::unique_ptr m_salsa20; + std::unique_ptr m_sha1; }; int m_stream_count; diff --git a/src/ZoneCommon/Zone/XChunk/XChunkProcessorSalsa20Decryption.cpp b/src/ZoneCommon/Zone/XChunk/XChunkProcessorSalsa20Decryption.cpp index 57018c62..cf1bfb05 100644 --- a/src/ZoneCommon/Zone/XChunk/XChunkProcessorSalsa20Decryption.cpp +++ b/src/ZoneCommon/Zone/XChunk/XChunkProcessorSalsa20Decryption.cpp @@ -1,7 +1,7 @@ #include "XChunkProcessorSalsa20Decryption.h" #include "AbstractSalsa20Processor.h" -#include "Crypto.h" +#include "Cryptography.h" #include @@ -21,10 +21,10 @@ size_t XChunkProcessorSalsa20Decryption::Process( assert(output != nullptr); assert(inputLength <= outputBufferSize); - auto& streamContext = m_stream_contexts[streamNumber]; + const auto& streamContext = m_stream_contexts[streamNumber]; // Initialize Salsa20 with an IV of the first 8 bytes of the current hash block - streamContext.m_salsa20->SetIV(GetHashBlock(streamNumber), SALSA20_IV_SIZE); + streamContext.m_salsa20->SetIv(GetHashBlock(streamNumber), SALSA20_IV_SIZE); streamContext.m_salsa20->Process(input, output, inputLength); // Hash decrypted XChunk diff --git a/src/ZoneCommon/Zone/XChunk/XChunkProcessorSalsa20Encryption.cpp b/src/ZoneCommon/Zone/XChunk/XChunkProcessorSalsa20Encryption.cpp index 3f36b12d..80ca8928 100644 --- a/src/ZoneCommon/Zone/XChunk/XChunkProcessorSalsa20Encryption.cpp +++ b/src/ZoneCommon/Zone/XChunk/XChunkProcessorSalsa20Encryption.cpp @@ -27,7 +27,7 @@ size_t XChunkProcessorSalsa20Encryption::Process( streamContext.m_sha1->Finish(&blockSha1Hash); // Initialize Salsa20 with an IV of the first 8 bytes of the current hash block - streamContext.m_salsa20->SetIV(GetHashBlock(streamNumber), SALSA20_IV_SIZE); + streamContext.m_salsa20->SetIv(GetHashBlock(streamNumber), SALSA20_IV_SIZE); streamContext.m_salsa20->Process(input, output, inputLength); // Advance index to next hash block diff --git a/src/ZoneLoading.lua b/src/ZoneLoading.lua index 4cc3c0fa..0d555bca 100644 --- a/src/ZoneLoading.lua +++ b/src/ZoneLoading.lua @@ -11,7 +11,7 @@ end function ZoneLoading:link(links) links:add(self:name()) - links:linkto(Crypto) + links:linkto(Cryptography) links:linkto(Utils) links:linkto(ZoneCommon) links:linkto(zlib) @@ -53,7 +53,7 @@ function ZoneLoading:project() } self:include(includes) - Crypto:include(includes) + Cryptography:include(includes) Utils:include(includes) zlib:include(includes) ZoneCode:include(includes) diff --git a/src/ZoneLoading/Game/IW4/ZoneLoaderFactoryIW4.cpp b/src/ZoneLoading/Game/IW4/ZoneLoaderFactoryIW4.cpp index a90f8993..e2b4bbc0 100644 --- a/src/ZoneLoading/Game/IW4/ZoneLoaderFactoryIW4.cpp +++ b/src/ZoneLoading/Game/IW4/ZoneLoaderFactoryIW4.cpp @@ -91,11 +91,11 @@ namespace #undef XBLOCK_DEF } - std::unique_ptr SetupRSA(const bool isOfficial) + std::unique_ptr SetupRsa(const bool isOfficial) { if (isOfficial) { - auto rsa = Crypto::CreateRSA(IPublicKeyAlgorithm::HashingAlgorithm::RSA_HASH_SHA256, Crypto::RSAPaddingMode::RSA_PADDING_PSS); + auto rsa = cryptography::CreateRsa(cryptography::HashingAlgorithm::RSA_HASH_SHA256, cryptography::RsaPaddingMode::RSA_PADDING_PSS); if (!rsa->SetKey(ZoneConstants::RSA_PUBLIC_KEY_INFINITY_WARD, sizeof(ZoneConstants::RSA_PUBLIC_KEY_INFINITY_WARD))) { @@ -121,7 +121,7 @@ namespace return; // If file is signed setup a RSA instance. - auto rsa = SetupRSA(isOfficial); + auto rsa = SetupRsa(isOfficial); zoneLoader.AddLoadingStep(std::make_unique(ZoneConstants::MAGIC_AUTH_HEADER)); zoneLoader.AddLoadingStep(std::make_unique(4)); // Skip reserved @@ -147,8 +147,7 @@ namespace auto* masterBlockHashesPtr = masterBlockHashes.get(); zoneLoader.AddLoadingStep(std::move(masterBlockHashes)); - zoneLoader.AddLoadingStep( - std::make_unique(std::unique_ptr(Crypto::CreateSHA256()), 0, subHeaderHashPtr, subHeaderCapturePtr)); + zoneLoader.AddLoadingStep(std::make_unique(cryptography::CreateSha256(), 0, subHeaderHashPtr, subHeaderCapturePtr)); zoneLoader.AddLoadingStep(std::make_unique(subHeaderCapturePtr)); // Skip the rest of the first chunk @@ -158,7 +157,7 @@ namespace std::make_unique(std::make_unique(ZoneConstants::AUTHED_CHUNK_COUNT_PER_GROUP, ZoneConstants::AUTHED_CHUNK_SIZE, std::extent_v, - Crypto::CreateSHA256(), + cryptography::CreateSha256(), masterBlockHashesPtr))); } } // namespace diff --git a/src/ZoneLoading/Game/IW5/ZoneLoaderFactoryIW5.cpp b/src/ZoneLoading/Game/IW5/ZoneLoaderFactoryIW5.cpp index a5dc37bc..f2a18c53 100644 --- a/src/ZoneLoading/Game/IW5/ZoneLoaderFactoryIW5.cpp +++ b/src/ZoneLoading/Game/IW5/ZoneLoaderFactoryIW5.cpp @@ -75,11 +75,11 @@ namespace #undef XBLOCK_DEF } - std::unique_ptr SetupRSA(const bool isOfficial) + std::unique_ptr SetupRsa(const bool isOfficial) { if (isOfficial) { - auto rsa = Crypto::CreateRSA(IPublicKeyAlgorithm::HashingAlgorithm::RSA_HASH_SHA256, Crypto::RSAPaddingMode::RSA_PADDING_PSS); + auto rsa = cryptography::CreateRsa(cryptography::HashingAlgorithm::RSA_HASH_SHA256, cryptography::RsaPaddingMode::RSA_PADDING_PSS); if (!rsa->SetKey(ZoneConstants::RSA_PUBLIC_KEY_INFINITY_WARD, sizeof(ZoneConstants::RSA_PUBLIC_KEY_INFINITY_WARD))) { @@ -105,7 +105,7 @@ namespace return; // If file is signed setup a RSA instance. - auto rsa = SetupRSA(isOfficial); + auto rsa = SetupRsa(isOfficial); zoneLoader.AddLoadingStep(std::make_unique(ZoneConstants::MAGIC_AUTH_HEADER)); zoneLoader.AddLoadingStep(std::make_unique(4)); // Skip reserved @@ -131,8 +131,7 @@ namespace auto* masterBlockHashesPtr = masterBlockHashes.get(); zoneLoader.AddLoadingStep(std::move(masterBlockHashes)); - zoneLoader.AddLoadingStep( - std::make_unique(std::unique_ptr(Crypto::CreateSHA256()), 0, subHeaderHashPtr, subHeaderCapturePtr)); + zoneLoader.AddLoadingStep(std::make_unique(cryptography::CreateSha256(), 0, subHeaderHashPtr, subHeaderCapturePtr)); zoneLoader.AddLoadingStep(std::make_unique(subHeaderCapturePtr)); // Skip the rest of the first chunk @@ -142,7 +141,7 @@ namespace std::make_unique(std::make_unique(ZoneConstants::AUTHED_CHUNK_COUNT_PER_GROUP, ZoneConstants::AUTHED_CHUNK_SIZE, std::extent_v, - Crypto::CreateSHA256(), + cryptography::CreateSha256(), masterBlockHashesPtr))); } } // namespace diff --git a/src/ZoneLoading/Game/T6/ZoneLoaderFactoryT6.cpp b/src/ZoneLoading/Game/T6/ZoneLoaderFactoryT6.cpp index 6ebb70f6..09642fd6 100644 --- a/src/ZoneLoading/Game/T6/ZoneLoaderFactoryT6.cpp +++ b/src/ZoneLoading/Game/T6/ZoneLoaderFactoryT6.cpp @@ -105,11 +105,11 @@ namespace #undef XBLOCK_DEF } - std::unique_ptr SetupRSA(const bool isOfficial) + std::unique_ptr SetupRsa(const bool isOfficial) { if (isOfficial) { - auto rsa = Crypto::CreateRSA(IPublicKeyAlgorithm::HashingAlgorithm::RSA_HASH_SHA256, Crypto::RSAPaddingMode::RSA_PADDING_PSS); + auto rsa = cryptography::CreateRsa(cryptography::HashingAlgorithm::RSA_HASH_SHA256, cryptography::RsaPaddingMode::RSA_PADDING_PSS); if (!rsa->SetKey(ZoneConstants::RSA_PUBLIC_KEY_TREYARCH, sizeof(ZoneConstants::RSA_PUBLIC_KEY_TREYARCH))) { @@ -190,7 +190,7 @@ std::unique_ptr ZoneLoaderFactory::CreateLoaderForHeader(ZoneHeader& SetupBlock(*zoneLoader); // If file is signed setup a RSA instance. - auto rsa = isSecure ? SetupRSA(isOfficial) : nullptr; + auto rsa = isSecure ? SetupRsa(isOfficial) : nullptr; // Add steps for loading the auth header which also contain the signature of the zone if it is signed. ISignatureProvider* signatureProvider = AddAuthHeaderSteps(isSecure, *zoneLoader, fileName); diff --git a/src/ZoneLoading/Loading/ILoadingStream.h b/src/ZoneLoading/Loading/ILoadingStream.h index aade82e1..d9512718 100644 --- a/src/ZoneLoading/Loading/ILoadingStream.h +++ b/src/ZoneLoading/Loading/ILoadingStream.h @@ -6,7 +6,12 @@ class ILoadingStream { public: + ILoadingStream() = default; virtual ~ILoadingStream() = default; + ILoadingStream(const ILoadingStream& other) = default; + ILoadingStream(ILoadingStream&& other) noexcept = default; + ILoadingStream& operator=(const ILoadingStream& other) = default; + ILoadingStream& operator=(ILoadingStream&& other) noexcept = default; virtual size_t Load(void* buffer, size_t length) = 0; virtual int64_t Pos() = 0; diff --git a/src/ZoneLoading/Loading/Processor/ProcessorAuthedBlocks.cpp b/src/ZoneLoading/Loading/Processor/ProcessorAuthedBlocks.cpp index aeb86e5a..cc5c8f39 100644 --- a/src/ZoneLoading/Loading/Processor/ProcessorAuthedBlocks.cpp +++ b/src/ZoneLoading/Loading/Processor/ProcessorAuthedBlocks.cpp @@ -17,7 +17,7 @@ class ProcessorAuthedBlocks::Impl const size_t m_chunk_size; const unsigned m_max_master_block_count; - const std::unique_ptr m_hash_function; + const std::unique_ptr m_hash_function; IHashProvider* const m_master_block_hash_provider; const std::unique_ptr m_chunk_hashes_buffer; const std::unique_ptr m_current_chunk_hash_buffer; @@ -34,7 +34,7 @@ public: const unsigned authedChunkCount, const size_t chunkSize, const unsigned maxMasterBlockCount, - std::unique_ptr hashFunction, + std::unique_ptr hashFunction, IHashProvider* masterBlockHashProvider) : m_base(base), m_authed_chunk_count(authedChunkCount), @@ -141,7 +141,7 @@ public: ProcessorAuthedBlocks::ProcessorAuthedBlocks(const unsigned authedChunkCount, const size_t chunkSize, const unsigned maxMasterBlockCount, - std::unique_ptr hashFunction, + std::unique_ptr hashFunction, IHashProvider* masterBlockHashProvider) : m_impl(new Impl(this, authedChunkCount, chunkSize, maxMasterBlockCount, std::move(hashFunction), masterBlockHashProvider)) { diff --git a/src/ZoneLoading/Loading/Processor/ProcessorAuthedBlocks.h b/src/ZoneLoading/Loading/Processor/ProcessorAuthedBlocks.h index 22a82e6e..5bcf4a19 100644 --- a/src/ZoneLoading/Loading/Processor/ProcessorAuthedBlocks.h +++ b/src/ZoneLoading/Loading/Processor/ProcessorAuthedBlocks.h @@ -1,5 +1,6 @@ #pragma once -#include "Crypto.h" + +#include "Cryptography.h" #include "Loading/IHashProvider.h" #include "Loading/StreamProcessor.h" @@ -14,7 +15,7 @@ public: ProcessorAuthedBlocks(unsigned authedChunkCount, size_t chunkSize, unsigned maxMasterBlockCount, - std::unique_ptr hashFunction, + std::unique_ptr hashFunction, IHashProvider* masterBlockHashProvider); ~ProcessorAuthedBlocks() override; ProcessorAuthedBlocks(const ProcessorAuthedBlocks& other) = delete; diff --git a/src/ZoneLoading/Loading/Processor/ProcessorStreamCipher.cpp b/src/ZoneLoading/Loading/Processor/ProcessorStreamCipher.cpp index 5a03ace9..73279921 100644 --- a/src/ZoneLoading/Loading/Processor/ProcessorStreamCipher.cpp +++ b/src/ZoneLoading/Loading/Processor/ProcessorStreamCipher.cpp @@ -1,14 +1,8 @@ #include "ProcessorStreamCipher.h" -ProcessorStreamCipher::ProcessorStreamCipher(IStreamCipher* cipher) +ProcessorStreamCipher::ProcessorStreamCipher(std::unique_ptr cipher) + : m_cipher(std::move(cipher)) { - m_cipher = cipher; -} - -ProcessorStreamCipher::~ProcessorStreamCipher() -{ - delete m_cipher; - m_cipher = nullptr; } size_t ProcessorStreamCipher::Load(void* buffer, const size_t length) diff --git a/src/ZoneLoading/Loading/Processor/ProcessorStreamCipher.h b/src/ZoneLoading/Loading/Processor/ProcessorStreamCipher.h index ebcc3b24..3b40f4a5 100644 --- a/src/ZoneLoading/Loading/Processor/ProcessorStreamCipher.h +++ b/src/ZoneLoading/Loading/Processor/ProcessorStreamCipher.h @@ -1,14 +1,17 @@ #pragma once -#include "Crypto.h" + +#include "Cryptography.h" #include "Loading/StreamProcessor.h" +#include + class ProcessorStreamCipher final : public StreamProcessor { - IStreamCipher* m_cipher; - public: - explicit ProcessorStreamCipher(IStreamCipher* cipher); - ~ProcessorStreamCipher() override; + explicit ProcessorStreamCipher(std::unique_ptr cipher); size_t Load(void* buffer, size_t length) override; + +private: + std::unique_ptr m_cipher; }; diff --git a/src/ZoneLoading/Loading/Steps/StepVerifyHash.cpp b/src/ZoneLoading/Loading/Steps/StepVerifyHash.cpp index 7264000d..dcbacf8f 100644 --- a/src/ZoneLoading/Loading/Steps/StepVerifyHash.cpp +++ b/src/ZoneLoading/Loading/Steps/StepVerifyHash.cpp @@ -5,7 +5,7 @@ #include #include -StepVerifyHash::StepVerifyHash(std::unique_ptr hashFunction, +StepVerifyHash::StepVerifyHash(std::unique_ptr hashFunction, const unsigned hashIndex, IHashProvider* hashProvider, ICapturedDataProvider* dataProvider) diff --git a/src/ZoneLoading/Loading/Steps/StepVerifyHash.h b/src/ZoneLoading/Loading/Steps/StepVerifyHash.h index b02b4078..b85fb3d7 100644 --- a/src/ZoneLoading/Loading/Steps/StepVerifyHash.h +++ b/src/ZoneLoading/Loading/Steps/StepVerifyHash.h @@ -1,6 +1,6 @@ #pragma once -#include "Crypto.h" +#include "Cryptography.h" #include "Loading/IHashProvider.h" #include "Loading/ILoadingStep.h" #include "Utils/ICapturedDataProvider.h" @@ -9,13 +9,16 @@ class StepVerifyHash final : public ILoadingStep { - std::unique_ptr m_hash_function; + std::unique_ptr m_hash_function; unsigned m_hash_index; IHashProvider* m_hash_provider; ICapturedDataProvider* m_data_provider; public: - StepVerifyHash(std::unique_ptr hashFunction, unsigned hashIndex, IHashProvider* hashProvider, ICapturedDataProvider* dataProvider); + StepVerifyHash(std::unique_ptr hashFunction, + unsigned hashIndex, + IHashProvider* hashProvider, + ICapturedDataProvider* dataProvider); ~StepVerifyHash(); StepVerifyHash(const StepVerifyHash& other) = delete; StepVerifyHash(StepVerifyHash&& other) noexcept = default; diff --git a/src/ZoneLoading/Loading/Steps/StepVerifySignature.cpp b/src/ZoneLoading/Loading/Steps/StepVerifySignature.cpp index c5f2e74e..00152fd6 100644 --- a/src/ZoneLoading/Loading/Steps/StepVerifySignature.cpp +++ b/src/ZoneLoading/Loading/Steps/StepVerifySignature.cpp @@ -4,7 +4,7 @@ #include -StepVerifySignature::StepVerifySignature(std::unique_ptr signatureAlgorithm, +StepVerifySignature::StepVerifySignature(std::unique_ptr signatureAlgorithm, ISignatureProvider* signatureProvider, ICapturedDataProvider* signatureDataProvider) : m_algorithm(std::move(signatureAlgorithm)), diff --git a/src/ZoneLoading/Loading/Steps/StepVerifySignature.h b/src/ZoneLoading/Loading/Steps/StepVerifySignature.h index f415ebea..3ce85bfe 100644 --- a/src/ZoneLoading/Loading/Steps/StepVerifySignature.h +++ b/src/ZoneLoading/Loading/Steps/StepVerifySignature.h @@ -1,18 +1,18 @@ #pragma once -#include "Crypto.h" +#include "Cryptography.h" #include "Loading/ILoadingStep.h" #include "Loading/ISignatureProvider.h" #include "Utils/ICapturedDataProvider.h" class StepVerifySignature final : public ILoadingStep { - std::unique_ptr m_algorithm; + std::unique_ptr m_algorithm; ISignatureProvider* m_signature_provider; ICapturedDataProvider* m_signature_data_provider; public: - StepVerifySignature(std::unique_ptr signatureAlgorithm, + StepVerifySignature(std::unique_ptr signatureAlgorithm, ISignatureProvider* signatureProvider, ICapturedDataProvider* signatureDataProvider); ~StepVerifySignature() override = default; diff --git a/src/ZoneLoading/Loading/StreamProcessor.h b/src/ZoneLoading/Loading/StreamProcessor.h index d3702777..4a718276 100644 --- a/src/ZoneLoading/Loading/StreamProcessor.h +++ b/src/ZoneLoading/Loading/StreamProcessor.h @@ -4,11 +4,11 @@ class StreamProcessor : public ILoadingStream { -protected: - ILoadingStream* m_base_stream; - public: StreamProcessor(); void SetBaseStream(ILoadingStream* baseStream); + +protected: + ILoadingStream* m_base_stream; }; diff --git a/src/ZoneWriting.lua b/src/ZoneWriting.lua index 693662e4..a55b33dd 100644 --- a/src/ZoneWriting.lua +++ b/src/ZoneWriting.lua @@ -11,7 +11,7 @@ end function ZoneWriting:link(links) links:add(self:name()) - links:linkto(Crypto) + links:linkto(Cryptography) links:linkto(Utils) links:linkto(ZoneCommon) links:linkto(zlib) @@ -49,7 +49,7 @@ function ZoneWriting:project() } self:include(includes) - Crypto:include(includes) + Cryptography:include(includes) Utils:include(includes) zlib:include(includes) ZoneCode:include(includes) From ee4301952aef1934d2d344cb3149b2aaf7db6e1b Mon Sep 17 00:00:00 2001 From: Jan Date: Fri, 25 Apr 2025 22:55:04 +0100 Subject: [PATCH 03/11] refactor: fix x64 compilation issues in Common,ObjCommon,ObjCompiling,ObjImage components --- src/Common/Utils/TypeAlignment.h | 6 +- src/ObjCommon/Csv/CsvHeaderRow.cpp | 2 +- src/ObjCommon/Csv/CsvHeaderRow.h | 2 +- .../CommonStructuredDataEnum.cpp | 4 +- .../CommonStructuredDataStruct.cpp | 10 +-- .../KeyValuePairs/KeyValuePairsCompilerT6.cpp | 3 +- src/ObjCompiling/Image/IPak/IPakCreator.cpp | 52 ++++++++------- src/ObjImage/Image/DdsLoader.cpp | 65 ++++++++++--------- src/ObjImage/Image/DdsWriter.cpp | 4 +- src/ObjImage/Image/Dx12TextureLoader.cpp | 8 +-- src/ObjImage/Image/Dx12TextureLoader.h | 16 ++--- src/ObjImage/Image/Dx9TextureLoader.cpp | 6 +- src/ObjImage/Image/Dx9TextureLoader.h | 17 ++--- src/ObjImage/Image/ImageFormat.h | 32 ++++----- src/ObjImage/Image/IwiWriter13.cpp | 2 +- src/ObjImage/Image/IwiWriter27.cpp | 2 +- src/ObjImage/Image/IwiWriter6.cpp | 2 +- src/ObjImage/Image/IwiWriter8.cpp | 2 +- 18 files changed, 116 insertions(+), 119 deletions(-) diff --git a/src/Common/Utils/TypeAlignment.h b/src/Common/Utils/TypeAlignment.h index 58733124..e3eabcd4 100644 --- a/src/Common/Utils/TypeAlignment.h +++ b/src/Common/Utils/TypeAlignment.h @@ -27,9 +27,9 @@ #define gcc_align(x) #else #ifdef _MSVC_LANG -#define type_align(x) __declspec(align(x)) -#define tdef_align(x) __declspec(align(x)) -#define memb_align(x) __declspec(align(x)) +#define type_align(x) /* __declspec(align(x)) */ +#define tdef_align(x) /* __declspec(align(x)) */ +#define memb_align(x) /* __declspec(align(x)) */ #define gcc_align(x) #else #define type_align(x) __attribute__((__aligned__(x))) diff --git a/src/ObjCommon/Csv/CsvHeaderRow.cpp b/src/ObjCommon/Csv/CsvHeaderRow.cpp index bb17aa46..d1d99479 100644 --- a/src/ObjCommon/Csv/CsvHeaderRow.cpp +++ b/src/ObjCommon/Csv/CsvHeaderRow.cpp @@ -21,7 +21,7 @@ bool CsvHeaderRow::RequireIndexForHeader(const std::string& headerName, unsigned if (existingHeader == m_header_row.end()) return false; - out = std::distance(m_header_row.begin(), existingHeader); + out = static_cast(std::distance(m_header_row.begin(), existingHeader)); return true; } diff --git a/src/ObjCommon/Csv/CsvHeaderRow.h b/src/ObjCommon/Csv/CsvHeaderRow.h index e3ab3f65..dad12ecb 100644 --- a/src/ObjCommon/Csv/CsvHeaderRow.h +++ b/src/ObjCommon/Csv/CsvHeaderRow.h @@ -13,7 +13,7 @@ public: bool Read(const CsvInputStream& inputStream); - const std::string& HeaderNameForColumn(unsigned columnIndex) const; + [[nodiscard]] const std::string& HeaderNameForColumn(unsigned columnIndex) const; bool RequireIndexForHeader(const std::string& headerName, unsigned& out) const; [[nodiscard]] std::optional GetIndexForHeader(const std::string& headerName) const; diff --git a/src/ObjCommon/StructuredDataDef/CommonStructuredDataEnum.cpp b/src/ObjCommon/StructuredDataDef/CommonStructuredDataEnum.cpp index 6a62a01f..82e745f8 100644 --- a/src/ObjCommon/StructuredDataDef/CommonStructuredDataEnum.cpp +++ b/src/ObjCommon/StructuredDataDef/CommonStructuredDataEnum.cpp @@ -42,14 +42,14 @@ uint32_t CommonStructuredDataEnum::CalculateChecksum(const uint32_t initialValue { auto checksum = initialValue; - checksum = crc32(checksum, reinterpret_cast(m_name.c_str()), m_name.size() + 1); + checksum = crc32(checksum, reinterpret_cast(m_name.c_str()), static_cast(m_name.size() + 1u)); const auto littleEndianElementCount = endianness::ToLittleEndian(ElementCount()); checksum = crc32(checksum, reinterpret_cast(&littleEndianElementCount), sizeof(littleEndianElementCount)); for (const auto& entry : m_entries) { - checksum = crc32(checksum, reinterpret_cast(entry.m_name.c_str()), entry.m_name.size() + 1); + checksum = crc32(checksum, reinterpret_cast(entry.m_name.c_str()), static_cast(entry.m_name.size() + 1)); const auto littleEndianValue = endianness::ToLittleEndian(entry.m_value); checksum = crc32(checksum, reinterpret_cast(&littleEndianValue), sizeof(littleEndianValue)); diff --git a/src/ObjCommon/StructuredDataDef/CommonStructuredDataStruct.cpp b/src/ObjCommon/StructuredDataDef/CommonStructuredDataStruct.cpp index 31b61ac1..7c81d451 100644 --- a/src/ObjCommon/StructuredDataDef/CommonStructuredDataStruct.cpp +++ b/src/ObjCommon/StructuredDataDef/CommonStructuredDataStruct.cpp @@ -41,10 +41,10 @@ uint32_t CommonStructuredDataStruct::CalculateChecksum(const CommonStructuredDat { auto checksum = initialValue; - checksum = crc32(checksum, reinterpret_cast(m_name.c_str()), m_name.size() + 1); + checksum = crc32(checksum, reinterpret_cast(m_name.c_str()), static_cast(m_name.size() + 1u)); for (const auto& property : m_properties) { - checksum = crc32(checksum, reinterpret_cast(property.m_name.c_str()), property.m_name.size() + 1); + checksum = crc32(checksum, reinterpret_cast(property.m_name.c_str()), static_cast(property.m_name.size() + 1u)); const auto littleEndianOffset = endianness::ToLittleEndian(property.m_offset_in_bits); checksum = crc32(checksum, reinterpret_cast(&littleEndianOffset), sizeof(littleEndianOffset)); @@ -68,7 +68,7 @@ uint32_t CommonStructuredDataStruct::CalculateChecksum(const CommonStructuredDat if (currentType.m_info.type_index < def.m_enums.size()) { const auto& _enum = *def.m_enums[currentType.m_info.type_index]; - checksum = crc32(checksum, reinterpret_cast(_enum.m_name.c_str()), _enum.m_name.size() + 1); + checksum = crc32(checksum, reinterpret_cast(_enum.m_name.c_str()), static_cast(_enum.m_name.size() + 1u)); currentType = CommonStructuredDataType(CommonStructuredDataTypeCategory::UNKNOWN); } break; @@ -76,7 +76,7 @@ uint32_t CommonStructuredDataStruct::CalculateChecksum(const CommonStructuredDat if (currentType.m_info.type_index < def.m_structs.size()) { const auto& _struct = *def.m_structs[currentType.m_info.type_index]; - checksum = crc32(checksum, reinterpret_cast(_struct.m_name.c_str()), _struct.m_name.size() + 1); + checksum = crc32(checksum, reinterpret_cast(_struct.m_name.c_str()), static_cast(_struct.m_name.size() + 1u)); currentType = CommonStructuredDataType(CommonStructuredDataTypeCategory::UNKNOWN); } break; @@ -99,7 +99,7 @@ uint32_t CommonStructuredDataStruct::CalculateChecksum(const CommonStructuredDat if (enumedArray.m_enum_index < def.m_enums.size()) { const auto& _enum = *def.m_enums[enumedArray.m_enum_index]; - checksum = crc32(checksum, reinterpret_cast(_enum.m_name.c_str()), _enum.m_name.size() + 1); + checksum = crc32(checksum, reinterpret_cast(_enum.m_name.c_str()), static_cast(_enum.m_name.size() + 1u)); } currentType = enumedArray.m_array_type; } diff --git a/src/ObjCompiling/Game/T6/KeyValuePairs/KeyValuePairsCompilerT6.cpp b/src/ObjCompiling/Game/T6/KeyValuePairs/KeyValuePairsCompilerT6.cpp index 8cba6771..22da77ce 100644 --- a/src/ObjCompiling/Game/T6/KeyValuePairs/KeyValuePairsCompilerT6.cpp +++ b/src/ObjCompiling/Game/T6/KeyValuePairs/KeyValuePairsCompilerT6.cpp @@ -6,7 +6,6 @@ #include #include -#include using namespace T6; @@ -42,7 +41,7 @@ namespace auto* gameKvps = m_memory.Alloc(); gameKvps->name = m_memory.Dup(m_zone.m_name.c_str()); - gameKvps->numVariables = commonKvps.size(); + gameKvps->numVariables = static_cast(commonKvps.size()); gameKvps->keyValuePairs = m_memory.Alloc(commonKvps.size()); const auto namespaceHash = Common::Com_HashKey(m_zone.m_name.c_str(), 64); diff --git a/src/ObjCompiling/Image/IPak/IPakCreator.cpp b/src/ObjCompiling/Image/IPak/IPakCreator.cpp index 365edd51..64134b2b 100644 --- a/src/ObjCompiling/Image/IPak/IPakCreator.cpp +++ b/src/ObjCompiling/Image/IPak/IPakCreator.cpp @@ -1,7 +1,6 @@ #include "IPakCreator.h" #include "Game/T6/CommonT6.h" -#include "Game/T6/GameT6.h" #include "GitVersion.h" #include "ObjContainer/IPak/IPakTypes.h" #include "Utils/Alignment.h" @@ -23,7 +22,7 @@ namespace static constexpr char BRANDING[] = "Created with OpenAssetTools " GIT_VERSION; static constexpr auto SECTION_COUNT = 3; // Index + Data + Branding - inline static const std::string PAD_DATA = std::string(256, '\xA7'); + inline static const auto PAD_DATA = std::string(256, '\xA7'); public: IPakWriter(std::ostream& stream, ISearchPath& searchPath, const std::vector& images) @@ -70,8 +69,8 @@ namespace void Write(const void* data, const size_t dataSize) { - m_stream.write(static_cast(data), dataSize); - m_current_offset += dataSize; + m_stream.write(static_cast(data), static_cast(dataSize)); + m_current_offset += static_cast(dataSize); } void Pad(const size_t paddingSize) @@ -100,27 +99,30 @@ namespace { GoTo(0); - const IPakHeader header{ipak_consts::IPAK_MAGIC, ipak_consts::IPAK_VERSION, static_cast(m_total_size), SECTION_COUNT}; + const IPakHeader header{.magic = ipak_consts::IPAK_MAGIC, + .version = ipak_consts::IPAK_VERSION, + .size = static_cast(m_total_size), + .sectionCount = SECTION_COUNT}; const IPakSection dataSection{ - ipak_consts::IPAK_DATA_SECTION, - static_cast(m_data_section_offset), - static_cast(m_data_section_size), - static_cast(m_index_entries.size()), + .type = ipak_consts::IPAK_DATA_SECTION, + .offset = static_cast(m_data_section_offset), + .size = static_cast(m_data_section_size), + .itemCount = static_cast(m_index_entries.size()), }; const IPakSection indexSection{ - ipak_consts::IPAK_INDEX_SECTION, - static_cast(m_index_section_offset), - static_cast(sizeof(IPakIndexEntry) * m_index_entries.size()), - static_cast(m_index_entries.size()), + .type = ipak_consts::IPAK_INDEX_SECTION, + .offset = static_cast(m_index_section_offset), + .size = static_cast(sizeof(IPakIndexEntry) * m_index_entries.size()), + .itemCount = static_cast(m_index_entries.size()), }; const IPakSection brandingSection{ - ipak_consts::IPAK_BRANDING_SECTION, - static_cast(m_branding_section_offset), - std::extent_v, - 1, + .type = ipak_consts::IPAK_BRANDING_SECTION, + .offset = static_cast(m_branding_section_offset), + .size = std::extent_v, + .itemCount = 1, }; Write(&header, sizeof(header)); @@ -147,7 +149,7 @@ namespace imageSize = static_cast(openFile.m_length); auto imageData = std::make_unique(imageSize); - openFile.m_stream->read(imageData.get(), imageSize); + openFile.m_stream->read(imageData.get(), static_cast(imageSize)); return imageData; } @@ -177,7 +179,7 @@ namespace IPakDataBlockHeader skipBlockHeader{}; skipBlockHeader.countAndOffset.count = 1; skipBlockHeader.commands[0].compressed = ipak_consts::IPAK_COMMAND_SKIP; - skipBlockHeader.commands[0].size = sizeToSkip - sizeof(IPakDataBlockHeader); + skipBlockHeader.commands[0].size = static_cast(sizeToSkip - sizeof(IPakDataBlockHeader)); Write(&skipBlockHeader, sizeof(skipBlockHeader)); } @@ -199,12 +201,12 @@ namespace m_current_block.countAndOffset.offset = static_cast(m_file_offset); // Reserve space to later write actual block header data - GoTo(m_current_offset + sizeof(IPakDataBlockHeader)); + GoTo(static_cast(m_current_offset + sizeof(IPakDataBlockHeader))); } void WriteChunkData(const void* data, const size_t dataSize) { - auto dataOffset = 0u; + auto dataOffset = 0uz; while (dataOffset < dataSize) { if (m_current_block.countAndOffset.count >= std::extent_v) @@ -225,7 +227,7 @@ namespace continue; } - const auto commandSize = std::min(std::min(remainingSize, ipak_consts::IPAK_COMMAND_DEFAULT_SIZE), remainingChunkBufferWindowSize); + const auto commandSize = std::min({remainingSize, ipak_consts::IPAK_COMMAND_DEFAULT_SIZE, remainingChunkBufferWindowSize}); auto writeUncompressed = true; if (USE_IPAK_COMPRESSION) @@ -254,7 +256,7 @@ namespace Write(&static_cast(data)[dataOffset], commandSize); const auto currentCommand = m_current_block.countAndOffset.count; - m_current_block.commands[currentCommand].size = commandSize; + m_current_block.commands[currentCommand].size = static_cast(commandSize); m_current_block.commands[currentCommand].compressed = ipak_consts::IPAK_COMMAND_UNCOMPRESSED; m_current_block.countAndOffset.count = currentCommand + 1u; } @@ -281,7 +283,7 @@ namespace return; const auto nameHash = T6::Common::R_HashString(imageName.c_str(), 0); - const auto dataHash = static_cast(crc32(0u, reinterpret_cast(imageData.get()), imageSize)); + const auto dataHash = static_cast(crc32(0u, reinterpret_cast(imageData.get()), static_cast(imageSize))); StartNewFile(); const auto startOffset = m_current_block_header_offset; @@ -294,7 +296,7 @@ namespace WriteChunkData(imageData.get(), imageSize); const auto writtenImageSize = static_cast(m_current_offset - startOffset); - indexEntry.size = writtenImageSize; + indexEntry.size = static_cast(writtenImageSize); m_index_entries.emplace_back(indexEntry); } diff --git a/src/ObjImage/Image/DdsLoader.cpp b/src/ObjImage/Image/DdsLoader.cpp index f61a439b..6fbd617b 100644 --- a/src/ObjImage/Image/DdsLoader.cpp +++ b/src/ObjImage/Image/DdsLoader.cpp @@ -14,16 +14,28 @@ namespace dds { static constexpr auto DDS_MAGIC = FileUtils::MakeMagic32('D', 'D', 'S', ' '); - std::istream& m_stream; + public: + explicit DdsLoaderInternal(std::istream& stream) + : m_stream(stream), + m_texture_type(TextureType::T_2D), + m_has_mip_maps(false), + m_width(0u), + m_height(0u), + m_depth(0u), + m_format(nullptr) + { + } - TextureType m_texture_type; - bool m_has_mip_maps; - size_t m_width; - size_t m_height; - size_t m_depth; - const ImageFormat* m_format; + std::unique_ptr LoadDds() + { + if (!ReadMagic() || !ReadHeader()) + return nullptr; - _NODISCARD bool ReadMagic() const + return ReadTextureData(); + } + + private: + [[nodiscard]] bool ReadMagic() const { uint32_t magic; m_stream.read(reinterpret_cast(&magic), sizeof(magic)); @@ -42,7 +54,7 @@ namespace dds return true; } - _NODISCARD bool ReadDxt10Header() + [[nodiscard]] bool ReadDxt10Header() { DDS_HEADER_DXT10 headerDx10{}; m_stream.read(reinterpret_cast(&headerDx10), sizeof(headerDx10)); @@ -86,7 +98,7 @@ namespace dds return false; } - _NODISCARD bool ReadPixelFormatFourCc(DDS_PIXELFORMAT& pf) + [[nodiscard]] bool ReadPixelFormatFourCc(DDS_PIXELFORMAT& pf) { switch (pf.dwFourCC) { @@ -132,7 +144,7 @@ namespace dds } } - _NODISCARD bool ReadPixelFormatUnsigned(DDS_PIXELFORMAT& pf) + [[nodiscard]] bool ReadPixelFormatUnsigned(DDS_PIXELFORMAT& pf) { unsigned rOffset, rSize, gOffset, gSize, bOffset, bSize, aOffset, aSize; @@ -163,7 +175,7 @@ namespace dds return false; } - _NODISCARD bool ReadPixelFormat(DDS_PIXELFORMAT& pf) + [[nodiscard]] bool ReadPixelFormat(DDS_PIXELFORMAT& pf) { if (pf.dwFlags & DDPF_FOURCC) return ReadPixelFormatFourCc(pf); @@ -200,7 +212,7 @@ namespace dds return ReadPixelFormat(header.ddspf); } - _NODISCARD std::unique_ptr ReadTextureData() const + [[nodiscard]] std::unique_ptr ReadTextureData() const { std::unique_ptr result; @@ -229,7 +241,7 @@ namespace dds for (auto mipLevel = 0; mipLevel < mipMapCount; mipLevel++) { - const auto mipSize = result->GetSizeOfMipLevel(mipLevel); + const auto mipSize = static_cast(result->GetSizeOfMipLevel(mipLevel)); for (auto face = 0; face < faceCount; face++) { @@ -246,25 +258,14 @@ namespace dds return result; } - public: - explicit DdsLoaderInternal(std::istream& stream) - : m_stream(stream), - m_texture_type(TextureType::T_2D), - m_has_mip_maps(false), - m_width(0u), - m_height(0u), - m_depth(0u), - m_format(nullptr) - { - } + std::istream& m_stream; - std::unique_ptr LoadDds() - { - if (!ReadMagic() || !ReadHeader()) - return nullptr; - - return ReadTextureData(); - } + TextureType m_texture_type; + bool m_has_mip_maps; + unsigned m_width; + unsigned m_height; + unsigned m_depth; + const ImageFormat* m_format; }; std::unique_ptr LoadDds(std::istream& stream) diff --git a/src/ObjImage/Image/DdsWriter.cpp b/src/ObjImage/Image/DdsWriter.cpp index 324dad40..93e88da0 100644 --- a/src/ObjImage/Image/DdsWriter.cpp +++ b/src/ObjImage/Image/DdsWriter.cpp @@ -55,7 +55,7 @@ public: { const auto* buffer = m_texture->GetBufferForMipLevel(mipLevel); const auto mipLevelSize = m_texture->GetSizeOfMipLevel(mipLevel) * m_texture->GetFaceCount(); - m_stream.write(reinterpret_cast(buffer), mipLevelSize); + m_stream.write(reinterpret_cast(buffer), static_cast(mipLevelSize)); } } @@ -153,7 +153,7 @@ public: header.dwHeight = m_texture->GetHeight(); header.dwWidth = m_texture->GetWidth(); header.dwDepth = m_texture->GetDepth(); - header.dwPitchOrLinearSize = m_texture->GetFormat()->GetPitch(0, m_texture->GetWidth()); + header.dwPitchOrLinearSize = static_cast(m_texture->GetFormat()->GetPitch(0, m_texture->GetWidth())); header.dwMipMapCount = m_texture->HasMipMaps() ? m_texture->GetMipMapCount() : 1; PopulatePixelFormat(header.ddspf); diff --git a/src/ObjImage/Image/Dx12TextureLoader.cpp b/src/ObjImage/Image/Dx12TextureLoader.cpp index 5402a4a8..4e1fe3c0 100644 --- a/src/ObjImage/Image/Dx12TextureLoader.cpp +++ b/src/ObjImage/Image/Dx12TextureLoader.cpp @@ -14,7 +14,7 @@ Dx12TextureLoader::Dx12TextureLoader() const ImageFormat* Dx12TextureLoader::GetFormatForDx12Format() const { - for (auto i : ImageFormat::ALL_FORMATS) + for (const auto* i : ImageFormat::ALL_FORMATS) { if (i->GetDxgiFormat() == m_format) return i; @@ -41,19 +41,19 @@ Dx12TextureLoader& Dx12TextureLoader::HasMipMaps(const bool hasMipMaps) return *this; } -Dx12TextureLoader& Dx12TextureLoader::Width(const size_t width) +Dx12TextureLoader& Dx12TextureLoader::Width(const unsigned width) { m_width = width; return *this; } -Dx12TextureLoader& Dx12TextureLoader::Height(const size_t height) +Dx12TextureLoader& Dx12TextureLoader::Height(const unsigned height) { m_height = height; return *this; } -Dx12TextureLoader& Dx12TextureLoader::Depth(const size_t depth) +Dx12TextureLoader& Dx12TextureLoader::Depth(const unsigned depth) { m_depth = depth; return *this; diff --git a/src/ObjImage/Image/Dx12TextureLoader.h b/src/ObjImage/Image/Dx12TextureLoader.h index 9309f9e4..128d2b69 100644 --- a/src/ObjImage/Image/Dx12TextureLoader.h +++ b/src/ObjImage/Image/Dx12TextureLoader.h @@ -2,8 +2,6 @@ #include "Image/DxgiFormat.h" #include "Image/Texture.h" -#include "Utils/ClassUtils.h" -#include "Utils/MemoryManager.h" #include #include @@ -16,21 +14,21 @@ public: Dx12TextureLoader& Format(oat::DXGI_FORMAT format); Dx12TextureLoader& Type(TextureType textureType); Dx12TextureLoader& HasMipMaps(bool hasMipMaps); - Dx12TextureLoader& Width(size_t width); - Dx12TextureLoader& Height(size_t height); - Dx12TextureLoader& Depth(size_t depth); + Dx12TextureLoader& Width(unsigned width); + Dx12TextureLoader& Height(unsigned height); + Dx12TextureLoader& Depth(unsigned depth); std::unique_ptr LoadTexture(const void* data); private: - _NODISCARD const ImageFormat* GetFormatForDx12Format() const; + [[nodiscard]] const ImageFormat* GetFormatForDx12Format() const; static std::unordered_map m_conversion_table; oat::DXGI_FORMAT m_format; TextureType m_type; bool m_has_mip_maps; - size_t m_width; - size_t m_height; - size_t m_depth; + unsigned m_width; + unsigned m_height; + unsigned m_depth; }; diff --git a/src/ObjImage/Image/Dx9TextureLoader.cpp b/src/ObjImage/Image/Dx9TextureLoader.cpp index 7c3ba93b..9d319bd0 100644 --- a/src/ObjImage/Image/Dx9TextureLoader.cpp +++ b/src/ObjImage/Image/Dx9TextureLoader.cpp @@ -41,19 +41,19 @@ Dx9TextureLoader& Dx9TextureLoader::HasMipMaps(const bool hasMipMaps) return *this; } -Dx9TextureLoader& Dx9TextureLoader::Width(const size_t width) +Dx9TextureLoader& Dx9TextureLoader::Width(const unsigned width) { m_width = width; return *this; } -Dx9TextureLoader& Dx9TextureLoader::Height(const size_t height) +Dx9TextureLoader& Dx9TextureLoader::Height(const unsigned height) { m_height = height; return *this; } -Dx9TextureLoader& Dx9TextureLoader::Depth(const size_t depth) +Dx9TextureLoader& Dx9TextureLoader::Depth(const unsigned depth) { m_depth = depth; return *this; diff --git a/src/ObjImage/Image/Dx9TextureLoader.h b/src/ObjImage/Image/Dx9TextureLoader.h index 5baa5266..212714d4 100644 --- a/src/ObjImage/Image/Dx9TextureLoader.h +++ b/src/ObjImage/Image/Dx9TextureLoader.h @@ -2,11 +2,8 @@ #include "Image/D3DFormat.h" #include "Image/Texture.h" -#include "Utils/ClassUtils.h" -#include "Utils/MemoryManager.h" #include -#include class Dx9TextureLoader { @@ -16,19 +13,19 @@ public: Dx9TextureLoader& Format(oat::D3DFORMAT format); Dx9TextureLoader& Type(TextureType textureType); Dx9TextureLoader& HasMipMaps(bool hasMipMaps); - Dx9TextureLoader& Width(size_t width); - Dx9TextureLoader& Height(size_t height); - Dx9TextureLoader& Depth(size_t depth); + Dx9TextureLoader& Width(unsigned width); + Dx9TextureLoader& Height(unsigned height); + Dx9TextureLoader& Depth(unsigned depth); std::unique_ptr LoadTexture(const void* data); private: - _NODISCARD const ImageFormat* GetFormatForDx9Format() const; + [[nodiscard]] const ImageFormat* GetFormatForDx9Format() const; oat::D3DFORMAT m_format; TextureType m_type; bool m_has_mip_maps; - size_t m_width; - size_t m_height; - size_t m_depth; + unsigned m_width; + unsigned m_height; + unsigned m_depth; }; diff --git a/src/ObjImage/Image/ImageFormat.h b/src/ObjImage/Image/ImageFormat.h index bcd825c7..b87f6ac5 100644 --- a/src/ObjImage/Image/ImageFormat.h +++ b/src/ObjImage/Image/ImageFormat.h @@ -48,13 +48,13 @@ protected: public: virtual ~ImageFormat() = default; - ImageFormatId GetId() const; - oat::D3DFORMAT GetD3DFormat() const; - oat::DXGI_FORMAT GetDxgiFormat() const; + [[nodiscard]] ImageFormatId GetId() const; + [[nodiscard]] oat::D3DFORMAT GetD3DFormat() const; + [[nodiscard]] oat::DXGI_FORMAT GetDxgiFormat() const; - virtual ImageFormatType GetType() const = 0; - virtual size_t GetPitch(unsigned mipLevel, unsigned width) const = 0; - virtual size_t GetSizeOfMipLevel(unsigned mipLevel, unsigned width, unsigned height, unsigned depth) const = 0; + [[nodiscard]] virtual ImageFormatType GetType() const = 0; + [[nodiscard]] virtual size_t GetPitch(unsigned mipLevel, unsigned width) const = 0; + [[nodiscard]] virtual size_t GetSizeOfMipLevel(unsigned mipLevel, unsigned width, unsigned height, unsigned depth) const = 0; static const ImageFormatUnsigned FORMAT_R8_G8_B8; static const ImageFormatUnsigned FORMAT_B8_G8_R8_X8; @@ -98,14 +98,14 @@ public: unsigned aOffset, unsigned aSize); - ImageFormatType GetType() const override; - size_t GetPitch(unsigned mipLevel, unsigned width) const override; - size_t GetSizeOfMipLevel(unsigned mipLevel, unsigned width, unsigned height, unsigned depth) const override; + [[nodiscard]] ImageFormatType GetType() const override; + [[nodiscard]] size_t GetPitch(unsigned mipLevel, unsigned width) const override; + [[nodiscard]] size_t GetSizeOfMipLevel(unsigned mipLevel, unsigned width, unsigned height, unsigned depth) const override; - bool HasR() const; - bool HasG() const; - bool HasB() const; - bool HasA() const; + [[nodiscard]] bool HasR() const; + [[nodiscard]] bool HasG() const; + [[nodiscard]] bool HasB() const; + [[nodiscard]] bool HasA() const; }; class ImageFormatBlockCompressed final : public ImageFormat @@ -116,7 +116,7 @@ public: ImageFormatBlockCompressed(ImageFormatId id, oat::D3DFORMAT d3dFormat, oat::DXGI_FORMAT dxgiFormat, unsigned blockSize, unsigned bitsPerBlock); - ImageFormatType GetType() const override; - size_t GetPitch(unsigned mipLevel, unsigned width) const override; - size_t GetSizeOfMipLevel(unsigned mipLevel, unsigned width, unsigned height, unsigned depth) const override; + [[nodiscard]] ImageFormatType GetType() const override; + [[nodiscard]] size_t GetPitch(unsigned mipLevel, unsigned width) const override; + [[nodiscard]] size_t GetSizeOfMipLevel(unsigned mipLevel, unsigned width, unsigned height, unsigned depth) const override; }; diff --git a/src/ObjImage/Image/IwiWriter13.cpp b/src/ObjImage/Image/IwiWriter13.cpp index b354b6bf..4401fdd6 100644 --- a/src/ObjImage/Image/IwiWriter13.cpp +++ b/src/ObjImage/Image/IwiWriter13.cpp @@ -110,7 +110,7 @@ void IwiWriter::DumpImage(std::ostream& stream, const Texture* texture) currentFileSize += mipLevelSize; if (currentMipLevel < static_cast(std::extent_v)) - header.fileSizeForPicmip[currentMipLevel] = currentFileSize; + header.fileSizeForPicmip[currentMipLevel] = static_cast(currentFileSize); } if (const auto* texture2D = dynamic_cast(texture)) diff --git a/src/ObjImage/Image/IwiWriter27.cpp b/src/ObjImage/Image/IwiWriter27.cpp index 06dbfd9f..8509fabf 100644 --- a/src/ObjImage/Image/IwiWriter27.cpp +++ b/src/ObjImage/Image/IwiWriter27.cpp @@ -113,7 +113,7 @@ void IwiWriter::DumpImage(std::ostream& stream, const Texture* texture) currentFileSize += mipLevelSize; if (currentMipLevel < static_cast(std::extent_v)) - header.fileSizeForPicmip[currentMipLevel] = currentFileSize; + header.fileSizeForPicmip[currentMipLevel] = static_cast(currentFileSize); } if (const auto* texture2D = dynamic_cast(texture)) diff --git a/src/ObjImage/Image/IwiWriter6.cpp b/src/ObjImage/Image/IwiWriter6.cpp index af6102de..9c91c6be 100644 --- a/src/ObjImage/Image/IwiWriter6.cpp +++ b/src/ObjImage/Image/IwiWriter6.cpp @@ -105,7 +105,7 @@ void IwiWriter::DumpImage(std::ostream& stream, const Texture* texture) currentFileSize += mipLevelSize; if (currentMipLevel < static_cast(std::extent_v)) - header.fileSizeForPicmip[currentMipLevel] = currentFileSize; + header.fileSizeForPicmip[currentMipLevel] = static_cast(currentFileSize); } if (const auto* texture2D = dynamic_cast(texture)) diff --git a/src/ObjImage/Image/IwiWriter8.cpp b/src/ObjImage/Image/IwiWriter8.cpp index c062bd04..7cad5095 100644 --- a/src/ObjImage/Image/IwiWriter8.cpp +++ b/src/ObjImage/Image/IwiWriter8.cpp @@ -105,7 +105,7 @@ void IwiWriter::DumpImage(std::ostream& stream, const Texture* texture) currentFileSize += mipLevelSize; if (currentMipLevel < static_cast(std::extent_v)) - header.fileSizeForPicmip[currentMipLevel] = currentFileSize; + header.fileSizeForPicmip[currentMipLevel] = static_cast(currentFileSize); } if (const auto* texture2D = dynamic_cast(texture)) From 5d0c94e4300b75ad63db6c4c06fb27add867360e Mon Sep 17 00:00:00 2001 From: Jan Date: Sat, 26 Apr 2025 10:11:28 +0100 Subject: [PATCH 04/11] refactor: fix x64 compilation for ObjLoading --- src/Common/Game/IW3/IW3_Assets.h | 4 +- src/Common/Game/T6/T6_Assets.h | 4 +- .../CommonStructuredDataStruct.h | 26 ++--- .../Game/IW3/Image/AssetLoaderImageIW3.cpp | 4 +- .../Game/IW4/Menu/LoaderMenuListIW4.cpp | 11 ++- .../Game/IW4/RawFile/LoaderRawFileIW4.cpp | 2 +- .../LoaderStructuredDataDefIW4.cpp | 46 ++++----- .../Game/IW4/Techset/LoaderTechsetIW4.cpp | 95 +++++++++---------- .../Game/IW5/Menu/LoaderMenuListIW5.cpp | 13 +-- .../Game/IW5/RawFile/LoaderRawFileIW5.cpp | 2 +- .../Game/IW5/Script/LoaderScriptFileIW5.cpp | 2 +- .../IW5/Weapon/InfoStringLoaderWeaponIW5.cpp | 20 ++-- .../IW5/Weapon/InfoStringLoaderWeaponIW5.h | 2 +- .../Game/T5/RawFile/LoaderRawFileT5.cpp | 8 +- .../Game/T6/FontIcon/LoaderFontIconT6.cpp | 17 ++-- .../Game/T6/Image/LoaderImageT6.cpp | 4 +- .../Game/T6/RawFile/LoaderRawFileT6.cpp | 4 +- .../Game/T6/Sound/LoaderSoundBankT6.cpp | 20 ++-- .../T6/Weapon/InfoStringLoaderWeaponT6.cpp | 4 +- .../Game/T6/Weapon/JsonWeaponCamoLoaderT6.cpp | 6 +- src/ObjLoading/ObjContainer/IPak/IPak.cpp | 8 +- .../ObjContainer/IPak/IPakEntryReadStream.cpp | 23 +++-- .../ObjContainer/SoundBank/SoundBank.cpp | 43 +++++---- src/ObjLoading/SearchPath/IWD.cpp | 2 +- .../StringTable/StringTableLoader.h | 3 +- .../TechniqueShaderScopeSequences.cpp | 2 +- .../Techset/TechniqueDefinitionAcceptor.cpp | 6 +- .../Techset/TechniqueDefinitionAcceptor.h | 18 ++-- src/ObjLoading/XModel/Gltf/GltfLoader.cpp | 7 +- .../XModel/PartClassificationState.cpp | 2 +- src/ObjLoading/XModel/TangentData.cpp | 4 +- .../Parsing/ZoneDefinitionParserState.cpp | 4 +- .../Zone/XChunk/XChunkProcessorDeflate.cpp | 4 +- .../Zone/XChunk/XChunkProcessorInflate.cpp | 4 +- 34 files changed, 212 insertions(+), 212 deletions(-) diff --git a/src/Common/Game/IW3/IW3_Assets.h b/src/Common/Game/IW3/IW3_Assets.h index 1cb6859c..9e3ae951 100644 --- a/src/Common/Game/IW3/IW3_Assets.h +++ b/src/Common/Game/IW3/IW3_Assets.h @@ -1314,9 +1314,9 @@ namespace IW3 { char levelCount; char flags; - int16_t dimensions[3]; + uint16_t dimensions[3]; int format; - int resourceSize; + unsigned int resourceSize; char data[1]; }; diff --git a/src/Common/Game/T6/T6_Assets.h b/src/Common/Game/T6/T6_Assets.h index ba366b11..628ce514 100644 --- a/src/Common/Game/T6/T6_Assets.h +++ b/src/Common/Game/T6/T6_Assets.h @@ -1478,8 +1478,8 @@ namespace T6 struct FontIcon { const char* name; - int numEntries; - int numAliasEntries; + unsigned int numEntries; + unsigned int numAliasEntries; FontIconEntry* fontIconEntry; FontIconAlias* fontIconAlias; }; diff --git a/src/ObjCommon/StructuredDataDef/CommonStructuredDataStruct.h b/src/ObjCommon/StructuredDataDef/CommonStructuredDataStruct.h index 698be8cc..0294b780 100644 --- a/src/ObjCommon/StructuredDataDef/CommonStructuredDataStruct.h +++ b/src/ObjCommon/StructuredDataDef/CommonStructuredDataStruct.h @@ -1,6 +1,6 @@ #pragma once + #include "CommonStructuredDataTypes.h" -#include "Utils/ClassUtils.h" #include #include @@ -8,29 +8,29 @@ struct CommonStructuredDataStructProperty { - std::string m_name; - CommonStructuredDataType m_type; - size_t m_offset_in_bits; - CommonStructuredDataStructProperty(); explicit CommonStructuredDataStructProperty(std::string name); CommonStructuredDataStructProperty(std::string name, CommonStructuredDataType type, size_t offsetInBits); + + std::string m_name; + CommonStructuredDataType m_type; + size_t m_offset_in_bits; }; class CommonStructuredDataDef; struct CommonStructuredDataStruct { + CommonStructuredDataStruct(); + explicit CommonStructuredDataStruct(std::string name); + + [[nodiscard]] uint32_t CalculateChecksum(const CommonStructuredDataDef& def, uint32_t initialValue) const; + + void SortPropertiesByOffset(); + void SortPropertiesByName(); + std::string m_name; std::vector m_properties; size_t m_bit_offset; size_t m_size_in_byte; - - CommonStructuredDataStruct(); - explicit CommonStructuredDataStruct(std::string name); - - _NODISCARD uint32_t CalculateChecksum(const CommonStructuredDataDef& def, uint32_t initialValue) const; - - void SortPropertiesByOffset(); - void SortPropertiesByName(); }; diff --git a/src/ObjLoading/Game/IW3/Image/AssetLoaderImageIW3.cpp b/src/ObjLoading/Game/IW3/Image/AssetLoaderImageIW3.cpp index 6f65b5af..a4d921c8 100644 --- a/src/ObjLoading/Game/IW3/Image/AssetLoaderImageIW3.cpp +++ b/src/ObjLoading/Game/IW3/Image/AssetLoaderImageIW3.cpp @@ -81,7 +81,7 @@ namespace const auto mipCount = texture->HasMipMaps() ? texture->GetMipMapCount() : 1; const auto faceCount = texture->GetFaceCount(); - size_t dataSize = 0; + auto dataSize = 0uz; for (auto mipLevel = 0; mipLevel < mipCount; mipLevel++) dataSize += texture->GetSizeOfMipLevel(mipLevel) * faceCount; @@ -99,7 +99,7 @@ namespace loadDef->dimensions[1] = image->height; loadDef->dimensions[2] = image->depth; loadDef->format = static_cast(texture->GetFormat()->GetD3DFormat()); - loadDef->resourceSize = dataSize; + loadDef->resourceSize = static_cast(dataSize); char* currentDataBuffer = loadDef->data; for (auto mipLevel = 0; mipLevel < mipCount; mipLevel++) diff --git a/src/ObjLoading/Game/IW4/Menu/LoaderMenuListIW4.cpp b/src/ObjLoading/Game/IW4/Menu/LoaderMenuListIW4.cpp index 8f1417d6..52e00c74 100644 --- a/src/ObjLoading/Game/IW4/Menu/LoaderMenuListIW4.cpp +++ b/src/ObjLoading/Game/IW4/Menu/LoaderMenuListIW4.cpp @@ -83,7 +83,7 @@ namespace menu::MenuAssetZoneState& zoneState, MenuConversionZoneState& conversionState, std::vector& menus, - AssetRegistration& registration) + AssetRegistration& registration) const { const auto alreadyLoadedMenuFile = conversionState.m_menus_by_filename.find(menuFilePath); if (alreadyLoadedMenuFile != conversionState.m_menus_by_filename.end()) @@ -125,12 +125,12 @@ namespace menu::MenuAssetZoneState& zoneState, MenuConversionZoneState& conversionState, std::vector& menus, - AssetRegistration& registration) + AssetRegistration& registration) const { const auto menuCount = parsingResult.m_menus.size(); const auto functionCount = parsingResult.m_functions.size(); const auto menuLoadCount = parsingResult.m_menus_to_load.size(); - auto totalItemCount = 0u; + auto totalItemCount = 0uz; for (const auto& menu : parsingResult.m_menus) totalItemCount += menu->m_items.size(); @@ -182,7 +182,7 @@ namespace return true; } - void CreateMenuListAsset(MenuList& menuList, const std::vector& menus) + void CreateMenuListAsset(MenuList& menuList, const std::vector& menus) const { menuList.menuCount = static_cast(menus.size()); @@ -196,7 +196,8 @@ namespace menuList.menus = nullptr; } - std::unique_ptr ParseMenuFile(std::istream& stream, const std::string& menuFileName, const menu::MenuAssetZoneState& zoneState) + std::unique_ptr + ParseMenuFile(std::istream& stream, const std::string& menuFileName, const menu::MenuAssetZoneState& zoneState) const { menu::MenuFileReader reader(stream, menuFileName, menu::FeatureLevel::IW4, m_search_path); diff --git a/src/ObjLoading/Game/IW4/RawFile/LoaderRawFileIW4.cpp b/src/ObjLoading/Game/IW4/RawFile/LoaderRawFileIW4.cpp index f4b788ad..5d708aa9 100644 --- a/src/ObjLoading/Game/IW4/RawFile/LoaderRawFileIW4.cpp +++ b/src/ObjLoading/Game/IW4/RawFile/LoaderRawFileIW4.cpp @@ -43,7 +43,7 @@ namespace zs.zfree = Z_NULL; zs.opaque = Z_NULL; zs.avail_in = static_cast(file.m_length); - zs.avail_out = compressionBufferSize; + zs.avail_out = static_cast(compressionBufferSize); zs.next_in = reinterpret_cast(uncompressedBuffer.get()); zs.next_out = reinterpret_cast(compressedBuffer); diff --git a/src/ObjLoading/Game/IW4/StructuredDataDef/LoaderStructuredDataDefIW4.cpp b/src/ObjLoading/Game/IW4/StructuredDataDef/LoaderStructuredDataDefIW4.cpp index b0ec0c79..6f662ab2 100644 --- a/src/ObjLoading/Game/IW4/StructuredDataDef/LoaderStructuredDataDefIW4.cpp +++ b/src/ObjLoading/Game/IW4/StructuredDataDef/LoaderStructuredDataDefIW4.cpp @@ -38,38 +38,38 @@ namespace } private: - StructuredDataType ConvertType(CommonStructuredDataType inputType) + static StructuredDataType ConvertType(const CommonStructuredDataType inputType) { switch (inputType.m_category) { case CommonStructuredDataTypeCategory::INT: - return {DATA_INT, {0}}; + return {.type = DATA_INT, .u = {}}; case CommonStructuredDataTypeCategory::BYTE: - return {DATA_BYTE, {0}}; + return {.type = DATA_BYTE, .u = {}}; case CommonStructuredDataTypeCategory::BOOL: - return {DATA_BOOL, {0}}; + return {.type = DATA_BOOL, .u = {}}; case CommonStructuredDataTypeCategory::FLOAT: - return {DATA_FLOAT, {0}}; + return {.type = DATA_FLOAT, .u = {}}; case CommonStructuredDataTypeCategory::SHORT: - return {DATA_SHORT, {0}}; + return {.type = DATA_SHORT, .u = {}}; case CommonStructuredDataTypeCategory::STRING: - return {DATA_STRING, {static_cast(inputType.m_info.string_length)}}; + return {.type = DATA_STRING, .u = {static_cast(inputType.m_info.string_length)}}; case CommonStructuredDataTypeCategory::ENUM: - return {DATA_ENUM, {static_cast(inputType.m_info.type_index)}}; + return {.type = DATA_ENUM, .u = {static_cast(inputType.m_info.type_index)}}; case CommonStructuredDataTypeCategory::STRUCT: - return {DATA_STRUCT, {static_cast(inputType.m_info.type_index)}}; + return {.type = DATA_STRUCT, .u = {static_cast(inputType.m_info.type_index)}}; case CommonStructuredDataTypeCategory::INDEXED_ARRAY: - return {DATA_INDEXED_ARRAY, {static_cast(inputType.m_info.type_index)}}; + return {.type = DATA_INDEXED_ARRAY, .u = {static_cast(inputType.m_info.type_index)}}; case CommonStructuredDataTypeCategory::ENUM_ARRAY: - return {DATA_ENUM_ARRAY, {static_cast(inputType.m_info.type_index)}}; + return {.type = DATA_ENUM_ARRAY, .u = {static_cast(inputType.m_info.type_index)}}; case CommonStructuredDataTypeCategory::UNKNOWN: default: assert(false); - return {DATA_INT, {0}}; + return {.type = DATA_INT, .u = {0}}; } } - void ConvertEnum(CommonStructuredDataEnum& inputEnum, StructuredDataEnum& outputEnum) + void ConvertEnum(CommonStructuredDataEnum& inputEnum, StructuredDataEnum& outputEnum) const { outputEnum.entryCount = static_cast(inputEnum.m_entries.size()); if (inputEnum.m_reserved_entry_count <= 0) @@ -94,10 +94,10 @@ namespace outputEnum.entries = nullptr; } - void ConvertStruct(CommonStructuredDataStruct& inputStruct, StructuredDataStruct& outputStruct) + void ConvertStruct(CommonStructuredDataStruct& inputStruct, StructuredDataStruct& outputStruct) const { outputStruct.size = static_cast(inputStruct.m_size_in_byte); - outputStruct.bitOffset = inputStruct.m_bit_offset; + outputStruct.bitOffset = static_cast(inputStruct.m_bit_offset); outputStruct.propertyCount = static_cast(inputStruct.m_properties.size()); inputStruct.SortPropertiesByName(); @@ -115,34 +115,34 @@ namespace if (outputProperty.type.type != DATA_BOOL) { assert(inputProperty.m_offset_in_bits % 8 == 0); - outputProperty.offset = inputProperty.m_offset_in_bits / 8; + outputProperty.offset = static_cast(inputProperty.m_offset_in_bits / 8uz); } else - outputProperty.offset = inputProperty.m_offset_in_bits; + outputProperty.offset = static_cast(inputProperty.m_offset_in_bits); } } else outputStruct.properties = nullptr; } - void ConvertIndexedArray(const CommonStructuredDataIndexedArray& inputIndexedArray, StructuredDataIndexedArray& outputIndexedArray) + static void ConvertIndexedArray(const CommonStructuredDataIndexedArray& inputIndexedArray, StructuredDataIndexedArray& outputIndexedArray) { outputIndexedArray.arraySize = static_cast(inputIndexedArray.m_element_count); outputIndexedArray.elementType = ConvertType(inputIndexedArray.m_array_type); - outputIndexedArray.elementSize = utils::Align(inputIndexedArray.m_element_size_in_bits, 8uz) / 8uz; + outputIndexedArray.elementSize = static_cast(utils::Align(inputIndexedArray.m_element_size_in_bits, 8uz) / 8uz); } void ConvertEnumedArray(const CommonStructuredDataEnumedArray& inputEnumedArray, StructuredDataEnumedArray& outputEnumedArray) { outputEnumedArray.enumIndex = static_cast(inputEnumedArray.m_enum_index); outputEnumedArray.elementType = ConvertType(inputEnumedArray.m_array_type); - outputEnumedArray.elementSize = utils::Align(inputEnumedArray.m_element_size_in_bits, 8uz) / 8uz; + outputEnumedArray.elementSize = static_cast(utils::Align(inputEnumedArray.m_element_size_in_bits, 8uz) / 8uz); } void ConvertDef(const CommonStructuredDataDef& inputDef, StructuredDataDef& outputDef) { outputDef.version = inputDef.m_version; - outputDef.formatChecksum = inputDef.m_checksum; + outputDef.formatChecksum = static_cast(inputDef.m_checksum); outputDef.enumCount = static_cast(inputDef.m_enums.size()); if (!inputDef.m_enums.empty()) @@ -185,7 +185,7 @@ namespace outputDef.enumedArrays = nullptr; outputDef.rootType = ConvertType(inputDef.m_root_type); - outputDef.size = inputDef.m_size_in_byte; + outputDef.size = static_cast(inputDef.m_size_in_byte); } StructuredDataDefSet* ConvertSet(const std::string& assetName, const std::vector>& commonDefs) @@ -193,7 +193,7 @@ namespace auto* set = m_memory.Alloc(); set->name = m_memory.Dup(assetName.c_str()); - set->defCount = commonDefs.size(); + set->defCount = static_cast(commonDefs.size()); set->defs = m_memory.Alloc(commonDefs.size()); for (auto defIndex = 0u; defIndex < commonDefs.size(); defIndex++) diff --git a/src/ObjLoading/Game/IW4/Techset/LoaderTechsetIW4.cpp b/src/ObjLoading/Game/IW4/Techset/LoaderTechsetIW4.cpp index 8362dc3e..97c1f76a 100644 --- a/src/ObjLoading/Game/IW4/Techset/LoaderTechsetIW4.cpp +++ b/src/ObjLoading/Game/IW4/Techset/LoaderTechsetIW4.cpp @@ -31,14 +31,14 @@ namespace class LoadedTechnique { public: - MaterialTechnique* m_technique; - std::vector m_dependencies; - LoadedTechnique(MaterialTechnique* technique, std::vector dependencies) : m_technique(technique), m_dependencies(std::move(dependencies)) { } + + MaterialTechnique* m_technique; + std::vector m_dependencies; }; class TechniqueZoneLoadingState final : public IZoneAssetCreationState @@ -46,8 +46,7 @@ namespace public: typedef const float (*literal_t)[4]; - public: - _NODISCARD const LoadedTechnique* FindLoadedTechnique(const std::string& techniqueName) const + [[nodiscard]] const LoadedTechnique* FindLoadedTechnique(const std::string& techniqueName) const { const auto loadedTechnique = m_loaded_techniques.find(techniqueName); if (loadedTechnique != m_loaded_techniques.end()) @@ -86,8 +85,6 @@ namespace class ShaderInfoFromFileSystemCacheState final : public IZoneAssetCreationState { - std::unordered_map> m_cached_shader_info; - public: [[nodiscard]] const d3d9::ShaderInfo* LoadShaderInfoFromDisk(ISearchPath& searchPath, const std::string& fileName) { @@ -108,9 +105,9 @@ namespace } const auto shaderData = std::make_unique(shaderSize); - file.m_stream->read(shaderData.get(), shaderSize); + file.m_stream->read(shaderData.get(), static_cast(shaderSize)); - auto shaderInfo = d3d9::ShaderAnalyser::GetShaderInfo(reinterpret_cast(shaderData.get()), shaderSize); + auto shaderInfo = d3d9::ShaderAnalyser::GetShaderInfo(shaderData.get(), shaderSize); if (!shaderInfo) return nullptr; @@ -118,6 +115,9 @@ namespace m_cached_shader_info.emplace(std::make_pair(fileName, std::move(shaderInfo))); return result; } + + private: + std::unordered_map> m_cached_shader_info; }; class TechniqueCreator final : public techset::ITechniqueDefinitionAcceptor @@ -126,10 +126,13 @@ namespace class PassShaderArgument { public: - MaterialShaderArgument m_arg; - MaterialUpdateFrequency m_update_frequency; + explicit PassShaderArgument(const MaterialShaderArgument arg) + : m_arg(arg), + m_update_frequency(GetUpdateFrequencyForArg(arg)) + { + } - static MaterialUpdateFrequency GetUpdateFrequencyForArg(MaterialShaderArgument arg) + static MaterialUpdateFrequency GetUpdateFrequencyForArg(const MaterialShaderArgument arg) { switch (arg.type) { @@ -160,15 +163,22 @@ namespace } } - explicit PassShaderArgument(const MaterialShaderArgument arg) - : m_arg(arg), - m_update_frequency(GetUpdateFrequencyForArg(arg)) - { - } + MaterialShaderArgument m_arg; + MaterialUpdateFrequency m_update_frequency; }; struct Pass { + Pass() + : m_vertex_shader(nullptr), + m_vertex_shader_info(nullptr), + m_pixel_shader(nullptr), + m_pixel_shader_info(nullptr), + m_vertex_decl{}, + m_vertex_decl_asset(nullptr) + { + } + XAssetInfo* m_vertex_shader; const d3d9::ShaderInfo* m_vertex_shader_info; std::unique_ptr m_vertex_shader_info_unq; @@ -184,21 +194,8 @@ namespace MaterialVertexDeclaration m_vertex_decl; XAssetInfo* m_vertex_decl_asset; std::vector m_arguments; - - Pass() - : m_vertex_shader(nullptr), - m_vertex_shader_info(nullptr), - m_pixel_shader(nullptr), - m_pixel_shader_info(nullptr), - m_vertex_decl{}, - m_vertex_decl_asset(nullptr) - { - } }; - std::vector m_passes; - std::vector m_dependencies; - TechniqueCreator( const std::string& techniqueName, ISearchPath& searchPath, MemoryManager& memory, AssetCreationContext& context, ITechsetCreator* techsetCreator) : m_technique_name(techniqueName), @@ -217,10 +214,11 @@ namespace m_passes.emplace_back(); } - static size_t RegisterCountPerElement(const d3d9::ShaderConstant& constant) + static unsigned RegisterCountPerElement(const d3d9::ShaderConstant& constant) { const auto valuesPerRegister = constant.m_register_set == d3d9::RegisterSet::BOOL || constant.m_register_set == d3d9::RegisterSet::SAMPLER ? 1u : 4u; + return utils::Align(constant.m_type_columns * constant.m_type_rows, valuesPerRegister) / valuesPerRegister; } @@ -243,7 +241,7 @@ namespace if (shaderType == techset::ShaderSelector::VERTEX_SHADER && isSamplerArgument) return false; - MaterialShaderArgument argument{}; + MaterialShaderArgument argument; argument.dest = static_cast(shaderArgument.m_register_index + registerOffset); unsigned arrayCount; @@ -258,7 +256,7 @@ namespace return false; argument.type = MTL_ARG_CODE_PIXEL_SAMPLER; - argument.u.codeSampler = samplerSource->source + elementOffset; + argument.u.codeSampler = samplerSource->source + static_cast(elementOffset); arrayCount = static_cast(samplerSource->arrayCount); } @@ -304,13 +302,12 @@ namespace { if (!AutoCreateShaderArgument(techset::ShaderSelector::VERTEX_SHADER, argument, elementIndex, registerIndex)) { - std::ostringstream ss; - ss << "Unassigned vertex shader \"" << pass.m_vertex_shader->m_name << "\" arg: " << argument.m_name; - + std::string elementIndexStr; if (argument.m_type_elements > 1) - ss << '[' << elementIndex << ']'; + elementIndexStr = std::format("[{}]", elementIndex); - errorMessage = ss.str(); + errorMessage = + std::format("Unassigned vertex shader \"{}\" arg: {}{}", pass.m_vertex_shader->m_name, argument.m_name, elementIndexStr); return false; } } @@ -572,11 +569,11 @@ namespace return foundSource; } - bool FindShaderArgument(const d3d9::ShaderInfo& shaderInfo, - const techset::ShaderArgument& argument, - size_t& constantIndex, - size_t& registerOffset, - std::string& errorMessage) const + static bool FindShaderArgument(const d3d9::ShaderInfo& shaderInfo, + const techset::ShaderArgument& argument, + size_t& constantIndex, + size_t& registerOffset, + std::string& errorMessage) { const auto matchingShaderConstant = std::ranges::find_if(shaderInfo.m_constants, [argument](const d3d9::ShaderConstant& constant) @@ -854,14 +851,14 @@ namespace } bool AcceptShaderLiteralArgument(const techset::ShaderSelector shader, - techset::ShaderArgument shaderArgument, - techset::ShaderArgumentLiteralSource source, + const techset::ShaderArgument shaderArgument, + const techset::ShaderArgumentLiteralSource source, std::string& errorMessage) override { assert(!m_passes.empty()); auto& pass = m_passes.at(m_passes.size() - 1); - MaterialShaderArgument argument{}; + MaterialShaderArgument argument; const d3d9::ShaderInfo* shaderInfo; if (shader == techset::ShaderSelector::VERTEX_SHADER) @@ -913,14 +910,14 @@ namespace } bool AcceptShaderMaterialArgument(const techset::ShaderSelector shader, - techset::ShaderArgument shaderArgument, + const techset::ShaderArgument shaderArgument, const techset::ShaderArgumentMaterialSource source, std::string& errorMessage) override { assert(!m_passes.empty()); auto& pass = m_passes.at(m_passes.size() - 1); - MaterialShaderArgument argument{}; + MaterialShaderArgument argument; const d3d9::ShaderInfo* shaderInfo; if (shader == techset::ShaderSelector::VERTEX_SHADER) @@ -1016,6 +1013,8 @@ namespace return true; } + std::vector m_passes; + private: const std::string& m_technique_name; ISearchPath& m_search_path; diff --git a/src/ObjLoading/Game/IW5/Menu/LoaderMenuListIW5.cpp b/src/ObjLoading/Game/IW5/Menu/LoaderMenuListIW5.cpp index 62b27cd5..46e6938c 100644 --- a/src/ObjLoading/Game/IW5/Menu/LoaderMenuListIW5.cpp +++ b/src/ObjLoading/Game/IW5/Menu/LoaderMenuListIW5.cpp @@ -83,7 +83,7 @@ namespace menu::MenuAssetZoneState& zoneState, MenuConversionZoneState& conversionState, std::vector& menus, - AssetRegistration& registration) + AssetRegistration& registration) const { const auto alreadyLoadedMenuFile = conversionState.m_menus_by_filename.find(menuFilePath); if (alreadyLoadedMenuFile != conversionState.m_menus_by_filename.end()) @@ -125,14 +125,14 @@ namespace menu::MenuAssetZoneState& zoneState, MenuConversionZoneState& conversionState, std::vector& menus, - AssetRegistration& registration) + AssetRegistration& registration) const { const auto menuCount = parsingResult.m_menus.size(); const auto functionCount = parsingResult.m_functions.size(); const auto menuLoadCount = parsingResult.m_menus_to_load.size(); auto totalItemCount = 0u; for (const auto& menu : parsingResult.m_menus) - totalItemCount += menu->m_items.size(); + totalItemCount += static_cast(menu->m_items.size()); std::cout << std::format("Successfully read menu file \"{}\" ({} loads, {} menus, {} functions, {} items)\n", fileName, @@ -152,7 +152,7 @@ namespace // Convert all menus and add them as assets for (auto& commonMenu : parsingResult.m_menus) { - auto converter = IMenuConverter::Create(ObjLoading::Configuration.MenuNoOptimization, m_search_path, m_memory, context); + const auto converter = IMenuConverter::Create(ObjLoading::Configuration.MenuNoOptimization, m_search_path, m_memory, context); auto* menuAsset = m_memory.Alloc(); AssetRegistration menuRegistration(commonMenu->m_name, menuAsset); @@ -182,7 +182,7 @@ namespace return true; } - void CreateMenuListAsset(MenuList& menuList, const std::vector& menus) + void CreateMenuListAsset(MenuList& menuList, const std::vector& menus) const { menuList.menuCount = static_cast(menus.size()); @@ -196,7 +196,8 @@ namespace menuList.menus = nullptr; } - std::unique_ptr ParseMenuFile(std::istream& stream, const std::string& menuFileName, const menu::MenuAssetZoneState& zoneState) + std::unique_ptr + ParseMenuFile(std::istream& stream, const std::string& menuFileName, const menu::MenuAssetZoneState& zoneState) const { menu::MenuFileReader reader(stream, menuFileName, menu::FeatureLevel::IW5, m_search_path); diff --git a/src/ObjLoading/Game/IW5/RawFile/LoaderRawFileIW5.cpp b/src/ObjLoading/Game/IW5/RawFile/LoaderRawFileIW5.cpp index 05e2ca8f..139e9ad3 100644 --- a/src/ObjLoading/Game/IW5/RawFile/LoaderRawFileIW5.cpp +++ b/src/ObjLoading/Game/IW5/RawFile/LoaderRawFileIW5.cpp @@ -44,7 +44,7 @@ namespace zs.zfree = Z_NULL; zs.opaque = Z_NULL; zs.avail_in = static_cast(file.m_length); - zs.avail_out = compressionBufferSize; + zs.avail_out = static_cast(compressionBufferSize); zs.next_in = reinterpret_cast(uncompressedBuffer.get()); zs.next_out = reinterpret_cast(compressedBuffer); diff --git a/src/ObjLoading/Game/IW5/Script/LoaderScriptFileIW5.cpp b/src/ObjLoading/Game/IW5/Script/LoaderScriptFileIW5.cpp index df9bdc2d..5ae68da9 100644 --- a/src/ObjLoading/Game/IW5/Script/LoaderScriptFileIW5.cpp +++ b/src/ObjLoading/Game/IW5/Script/LoaderScriptFileIW5.cpp @@ -57,7 +57,7 @@ namespace return AssetCreationResult::Failure(); } - if (offset + (scriptFile->compressedLen + scriptFile->bytecodeLen) > file.m_length) + if (offset + static_cast(scriptFile->compressedLen + scriptFile->bytecodeLen) > static_cast(file.m_length)) { std::cerr << std::format("Error: Specified length in {} GSC BIN structure exceeds the actual file size\n", assetName); return AssetCreationResult::Failure(); diff --git a/src/ObjLoading/Game/IW5/Weapon/InfoStringLoaderWeaponIW5.cpp b/src/ObjLoading/Game/IW5/Weapon/InfoStringLoaderWeaponIW5.cpp index 39310e5a..93f82995 100644 --- a/src/ObjLoading/Game/IW5/Weapon/InfoStringLoaderWeaponIW5.cpp +++ b/src/ObjLoading/Game/IW5/Weapon/InfoStringLoaderWeaponIW5.cpp @@ -232,7 +232,7 @@ namespace } m_weapon.weapCompleteDef.animOverrides = animOverrides; - m_weapon.weapCompleteDef.numAnimOverrides = valueArray.size(); + m_weapon.weapCompleteDef.numAnimOverrides = static_cast(valueArray.size()); return true; } @@ -267,7 +267,7 @@ namespace } m_weapon.weapCompleteDef.soundOverrides = soundOverrides; - m_weapon.weapCompleteDef.numSoundOverrides = valueArray.size(); + m_weapon.weapCompleteDef.numSoundOverrides = static_cast(valueArray.size()); return true; } @@ -305,7 +305,7 @@ namespace } m_weapon.weapCompleteDef.fxOverrides = fxOverrides; - m_weapon.weapCompleteDef.numFxOverrides = valueArray.size(); + m_weapon.weapCompleteDef.numFxOverrides = static_cast(valueArray.size()); return true; } @@ -339,7 +339,7 @@ namespace } m_weapon.weapCompleteDef.reloadOverrides = reloadOverrides; - m_weapon.weapCompleteDef.numReloadStateTimerOverrides = valueArray.size(); + m_weapon.weapCompleteDef.numReloadStateTimerOverrides = static_cast(valueArray.size()); return true; } @@ -392,7 +392,7 @@ namespace m_weapon.weapCompleteDef.notetrackOverrides = m_memory.Alloc(overrideVector.size()); memcpy(m_weapon.weapCompleteDef.notetrackOverrides, overrideVector.data(), sizeof(NoteTrackToSoundEntry) * overrideVector.size()); - m_weapon.weapCompleteDef.numNotetrackOverrides = overrideVector.size(); + m_weapon.weapCompleteDef.numNotetrackOverrides = static_cast(overrideVector.size()); return true; } @@ -437,7 +437,7 @@ namespace return false; } - void ParseAnim(const std::string& value, const char*& animName) + void ParseAnim(const std::string& value, const char*& animName) const { if (value == "none") { @@ -449,7 +449,7 @@ namespace m_registration.AddIndirectAssetReference(m_context.LoadIndirectAssetReference(value)); } - void ParseSoundAlias(const std::string& value, SndAliasCustom& soundAlias) + void ParseSoundAlias(const std::string& value, SndAliasCustom& soundAlias) const { if (value == "none") { @@ -462,7 +462,7 @@ namespace m_registration.AddIndirectAssetReference(m_context.LoadIndirectAssetReference(value)); } - bool ParseFxEffectDef(const std::string& value, FxEffectDef*& fx) + bool ParseFxEffectDef(const std::string& value, FxEffectDef*& fx) const { if (value == "none") { @@ -542,7 +542,7 @@ namespace return true; } - void ParseScriptString(const std::string& value, ScriptString& out) + void ParseScriptString(const std::string& value, ScriptString& out) const { out = m_zone_script_strings.AddOrGetScriptString(value); m_registration.AddScriptString(out); @@ -863,7 +863,7 @@ InfoStringLoaderWeapon::InfoStringLoaderWeapon(MemoryManager& memory, ISearchPat { } -AssetCreationResult InfoStringLoaderWeapon::CreateAsset(const std::string& assetName, const InfoString& infoString, AssetCreationContext& context) +AssetCreationResult InfoStringLoaderWeapon::CreateAsset(const std::string& assetName, const InfoString& infoString, AssetCreationContext& context) const { auto* weaponFullDef = m_memory.Alloc(); diff --git a/src/ObjLoading/Game/IW5/Weapon/InfoStringLoaderWeaponIW5.h b/src/ObjLoading/Game/IW5/Weapon/InfoStringLoaderWeaponIW5.h index 06d6e076..40f14367 100644 --- a/src/ObjLoading/Game/IW5/Weapon/InfoStringLoaderWeaponIW5.h +++ b/src/ObjLoading/Game/IW5/Weapon/InfoStringLoaderWeaponIW5.h @@ -11,7 +11,7 @@ namespace IW5 public: InfoStringLoaderWeapon(MemoryManager& memory, ISearchPath& searchPath, Zone& zone); - AssetCreationResult CreateAsset(const std::string& assetName, const InfoString& infoString, AssetCreationContext& context); + AssetCreationResult CreateAsset(const std::string& assetName, const InfoString& infoString, AssetCreationContext& context) const; private: MemoryManager& m_memory; diff --git a/src/ObjLoading/Game/T5/RawFile/LoaderRawFileT5.cpp b/src/ObjLoading/Game/T5/RawFile/LoaderRawFileT5.cpp index 4ffa79db..ec7ec152 100644 --- a/src/ObjLoading/Game/T5/RawFile/LoaderRawFileT5.cpp +++ b/src/ObjLoading/Game/T5/RawFile/LoaderRawFileT5.cpp @@ -40,7 +40,7 @@ namespace } private: - AssetCreationResult LoadGsc(const SearchPathOpenFile& file, const std::string& assetName, AssetCreationContext& context) + AssetCreationResult LoadGsc(const SearchPathOpenFile& file, const std::string& assetName, AssetCreationContext& context) const { const auto uncompressedBuffer = std::make_unique(static_cast(file.m_length + 1)); @@ -58,7 +58,7 @@ namespace zs.zfree = Z_NULL; zs.opaque = Z_NULL; zs.avail_in = static_cast(file.m_length + 1); - zs.avail_out = compressionBufferSize; + zs.avail_out = static_cast(compressionBufferSize); zs.next_in = reinterpret_cast(uncompressedBuffer.get()); zs.next_out = reinterpret_cast(&compressedBuffer[sizeof(uint32_t) + sizeof(uint32_t)]); @@ -79,7 +79,7 @@ namespace const auto compressedSize = compressionBufferSize - zs.avail_out; reinterpret_cast(compressedBuffer)[0] = static_cast(file.m_length + 1); // outLen - reinterpret_cast(compressedBuffer)[1] = compressedSize; // inLen + reinterpret_cast(compressedBuffer)[1] = static_cast(compressedSize); // inLen auto* rawFile = m_memory.Alloc(); rawFile->name = m_memory.Dup(assetName.c_str()); @@ -91,7 +91,7 @@ namespace return AssetCreationResult::Success(context.AddAsset(assetName, rawFile)); } - AssetCreationResult LoadDefault(const SearchPathOpenFile& file, const std::string& assetName, AssetCreationContext& context) + AssetCreationResult LoadDefault(const SearchPathOpenFile& file, const std::string& assetName, AssetCreationContext& context) const { auto* rawFile = m_memory.Alloc(); rawFile->name = m_memory.Dup(assetName.c_str()); diff --git a/src/ObjLoading/Game/T6/FontIcon/LoaderFontIconT6.cpp b/src/ObjLoading/Game/T6/FontIcon/LoaderFontIconT6.cpp index bcdfb938..43cde72c 100644 --- a/src/ObjLoading/Game/T6/FontIcon/LoaderFontIconT6.cpp +++ b/src/ObjLoading/Game/T6/FontIcon/LoaderFontIconT6.cpp @@ -5,9 +5,7 @@ #include "Game/T6/T6.h" #include -#include #include -#include using namespace T6; @@ -25,8 +23,8 @@ namespace constexpr unsigned ROW_ALIAS_NAME = 2; constexpr unsigned ROW_ALIAS_BUTTON = 3; - constexpr const char* VALUE_TYPE_ICON = "icon"; - constexpr const char* VALUE_TYPE_ALIAS = "alias"; + constexpr auto VALUE_TYPE_ICON = "icon"; + constexpr auto VALUE_TYPE_ALIAS = "alias"; constexpr unsigned COL_COUNT_ICON = 7; constexpr unsigned COL_COUNT_ALIAS = 4; @@ -125,8 +123,8 @@ namespace } } - fontIcon->numEntries = entries.size(); - fontIcon->numAliasEntries = aliases.size(); + fontIcon->numEntries = static_cast(entries.size()); + fontIcon->numAliasEntries = static_cast(aliases.size()); if (fontIcon->numEntries > 0) { @@ -159,7 +157,7 @@ namespace { for (auto& cell : row) { - for (auto c : cell) + for (const auto c : cell) { if (isspace(c)) continue; @@ -220,7 +218,7 @@ namespace const std::string& assetName, const unsigned rowIndex, AssetCreationContext& context, - AssetRegistration& registration) + AssetRegistration& registration) const { if (row.size() < COL_COUNT_ICON) { @@ -246,6 +244,7 @@ namespace std::cerr << std::format("{} Failed to load material \"{}\"\n", ErrorPrefix(assetName, rowIndex), row[ROW_ICON_MATERIAL]); return false; } + registration.AddDependency(materialDependency); icon.fontIconMaterialHandle = materialDependency->Asset(); icon.fontIconName.string = m_memory.Dup(row[ROW_ICON_NAME].c_str()); @@ -254,7 +253,7 @@ namespace return true; } - bool ReadAliasRow( + static bool ReadAliasRow( const std::vector& row, FontIconAlias& alias, const std::string& assetName, const unsigned rowIndex, AssetCreationContext& context) { if (row.size() < COL_COUNT_ALIAS) diff --git a/src/ObjLoading/Game/T6/Image/LoaderImageT6.cpp b/src/ObjLoading/Game/T6/Image/LoaderImageT6.cpp index 76e74131..5c26a32d 100644 --- a/src/ObjLoading/Game/T6/Image/LoaderImageT6.cpp +++ b/src/ObjLoading/Game/T6/Image/LoaderImageT6.cpp @@ -32,8 +32,8 @@ namespace const auto fileSize = static_cast(file.m_length); const auto fileData = std::make_unique(fileSize); - file.m_stream->read(fileData.get(), fileSize); - const auto dataHash = static_cast(crc32(0u, reinterpret_cast(fileData.get()), fileSize)); + file.m_stream->read(fileData.get(), static_cast(fileSize)); + const auto dataHash = static_cast(crc32(0u, reinterpret_cast(fileData.get()), static_cast(fileSize))); std::istringstream ss(std::string(fileData.get(), fileSize)); const auto texture = iwi::LoadIwi(ss); diff --git a/src/ObjLoading/Game/T6/RawFile/LoaderRawFileT6.cpp b/src/ObjLoading/Game/T6/RawFile/LoaderRawFileT6.cpp index 5e92aebc..f3352243 100644 --- a/src/ObjLoading/Game/T6/RawFile/LoaderRawFileT6.cpp +++ b/src/ObjLoading/Game/T6/RawFile/LoaderRawFileT6.cpp @@ -58,7 +58,7 @@ namespace zs.zfree = Z_NULL; zs.opaque = Z_NULL; zs.avail_in = static_cast(file.m_length); - zs.avail_out = compressionBufferSize; + zs.avail_out = static_cast(compressionBufferSize); zs.next_in = reinterpret_cast(uncompressedBuffer.get()); zs.next_out = reinterpret_cast(&compressedBuffer[sizeof(uint32_t)]); @@ -92,7 +92,7 @@ namespace return AssetCreationResult::Success(context.AddAsset(assetName, rawFile)); } - AssetCreationResult LoadDefault(const SearchPathOpenFile& file, const std::string& assetName, AssetCreationContext& context) + AssetCreationResult LoadDefault(const SearchPathOpenFile& file, const std::string& assetName, AssetCreationContext& context) const { auto* rawFile = m_memory.Alloc(); rawFile->name = m_memory.Dup(assetName.c_str()); diff --git a/src/ObjLoading/Game/T6/Sound/LoaderSoundBankT6.cpp b/src/ObjLoading/Game/T6/Sound/LoaderSoundBankT6.cpp index aab25cb4..f72d2a77 100644 --- a/src/ObjLoading/Game/T6/Sound/LoaderSoundBankT6.cpp +++ b/src/ObjLoading/Game/T6/Sound/LoaderSoundBankT6.cpp @@ -679,7 +679,7 @@ namespace if (!aliasList.empty()) aliasLists.emplace_back(CreateAliasList(aliasList, memory)); - sndBank->aliasCount = aliasLists.size(); + sndBank->aliasCount = static_cast(aliasLists.size()); if (sndBank->aliasCount) { sndBank->alias = memory.Alloc(sndBank->aliasCount); @@ -702,7 +702,7 @@ namespace const auto idx = sndBank->alias[i].id % sndBank->aliasCount; if (sndBank->aliasIndex[idx].value == std::numeric_limits::max()) { - sndBank->aliasIndex[idx].value = i; + sndBank->aliasIndex[idx].value = static_cast(i); sndBank->aliasIndex[idx].next = std::numeric_limits::max(); setAliasIndexList[i] = true; } @@ -720,14 +720,14 @@ namespace } auto offset = 1u; - auto freeIdx = std::numeric_limits::max(); + unsigned short freeIdx; while (true) { - freeIdx = (idx + offset) % sndBank->aliasCount; + freeIdx = static_cast((idx + offset) % sndBank->aliasCount); if (sndBank->aliasIndex[freeIdx].value == std::numeric_limits::max()) break; - freeIdx = (idx + sndBank->aliasCount - offset) % sndBank->aliasCount; + freeIdx = static_cast((idx + sndBank->aliasCount - offset) % sndBank->aliasCount); if (sndBank->aliasIndex[freeIdx].value == std::numeric_limits::max()) break; @@ -745,7 +745,7 @@ namespace } sndBank->aliasIndex[idx].next = freeIdx; - sndBank->aliasIndex[freeIdx].value = i; + sndBank->aliasIndex[freeIdx].value = static_cast(i); sndBank->aliasIndex[freeIdx].next = std::numeric_limits::max(); setAliasIndexList[i] = true; } @@ -849,7 +849,7 @@ namespace radverbs.emplace_back(radverb); } - sndBank->radverbCount = radverbs.size(); + sndBank->radverbCount = static_cast(radverbs.size()); if (sndBank->radverbCount) { sndBank->radverbs = memory.Alloc(sndBank->radverbCount); @@ -912,7 +912,7 @@ namespace for (auto& valueJson : duckJson["values"]) { - auto index = GetValueIndex(valueJson["duckGroup"].get(), SOUND_DUCK_GROUPS, std::extent_v); + const auto index = GetValueIndex(valueJson["duckGroup"].get(), SOUND_DUCK_GROUPS, std::extent_v); duck.attenuation[index] = valueJson["attenuation"].get(); duck.filter[index] = valueJson["filter"].get(); @@ -921,7 +921,7 @@ namespace ducks.emplace_back(duck); } - sndBank->duckCount = ducks.size(); + sndBank->duckCount = static_cast(ducks.size()); if (sndBank->duckCount) { sndBank->ducks = memory.Alloc(sndBank->duckCount); @@ -1046,7 +1046,7 @@ namespace if (result) { - sndBank->loadedAssets.dataSize = dataSize; + sndBank->loadedAssets.dataSize = static_cast(dataSize); sndBank->loadedAssets.data = m_memory.Alloc(dataSize); } else diff --git a/src/ObjLoading/Game/T6/Weapon/InfoStringLoaderWeaponT6.cpp b/src/ObjLoading/Game/T6/Weapon/InfoStringLoaderWeaponT6.cpp index a755a51f..6d97ceab 100644 --- a/src/ObjLoading/Game/T6/Weapon/InfoStringLoaderWeaponT6.cpp +++ b/src/ObjLoading/Game/T6/Weapon/InfoStringLoaderWeaponT6.cpp @@ -574,12 +574,12 @@ namespace { if (lastSibling == nullptr) { - attachmentUnique.childLink = attachmentUniqueIndex; + attachmentUnique.childLink = static_cast(attachmentUniqueIndex); lastSibling = weapon.attachmentUniques[attachmentUniqueIndex]; } else { - lastSibling->siblingLink = attachmentUniqueIndex; + lastSibling->siblingLink = static_cast(attachmentUniqueIndex); lastSibling = weapon.attachmentUniques[attachmentUniqueIndex]; } } diff --git a/src/ObjLoading/Game/T6/Weapon/JsonWeaponCamoLoaderT6.cpp b/src/ObjLoading/Game/T6/Weapon/JsonWeaponCamoLoaderT6.cpp index b98df329..fbe08536 100644 --- a/src/ObjLoading/Game/T6/Weapon/JsonWeaponCamoLoaderT6.cpp +++ b/src/ObjLoading/Game/T6/Weapon/JsonWeaponCamoLoaderT6.cpp @@ -151,7 +151,7 @@ namespace { if (!jWeaponCamoMaterialSet.materials.empty()) { - weaponCamoMaterialSet.numMaterials = jWeaponCamoMaterialSet.materials.size(); + weaponCamoMaterialSet.numMaterials = static_cast(jWeaponCamoMaterialSet.materials.size()); weaponCamoMaterialSet.materials = m_memory.Alloc(weaponCamoMaterialSet.numMaterials); for (auto i = 0u; i < weaponCamoMaterialSet.numMaterials; i++) @@ -197,7 +197,7 @@ namespace if (!jWeaponCamo.camoSets.empty()) { - weaponCamo.numCamoSets = jWeaponCamo.camoSets.size(); + weaponCamo.numCamoSets = static_cast(jWeaponCamo.camoSets.size()); weaponCamo.camoSets = m_memory.Alloc(weaponCamo.numCamoSets); for (auto i = 0u; i < weaponCamo.numCamoSets; i++) @@ -214,7 +214,7 @@ namespace if (!jWeaponCamo.camoMaterials.empty()) { - weaponCamo.numCamoMaterials = jWeaponCamo.camoMaterials.size(); + weaponCamo.numCamoMaterials = static_cast(jWeaponCamo.camoMaterials.size()); weaponCamo.camoMaterials = m_memory.Alloc(weaponCamo.numCamoMaterials); for (auto i = 0u; i < weaponCamo.numCamoMaterials; i++) diff --git a/src/ObjLoading/ObjContainer/IPak/IPak.cpp b/src/ObjLoading/ObjContainer/IPak/IPak.cpp index a963f28d..9308499d 100644 --- a/src/ObjLoading/ObjContainer/IPak/IPak.cpp +++ b/src/ObjLoading/ObjContainer/IPak/IPak.cpp @@ -56,9 +56,9 @@ namespace [[nodiscard]] std::unique_ptr GetEntryStream(const Hash nameHash, const Hash dataHash) const override { - IPakIndexEntryKey wantedKey{}; - wantedKey.nameHash = nameHash; - wantedKey.dataHash = dataHash; + const IPakIndexEntryKey wantedKey{ + {.dataHash = dataHash, .nameHash = nameHash} + }; for (auto& entry : m_index_entries) { @@ -209,5 +209,5 @@ IIPak::Hash IIPak::HashString(const std::string& str) IIPak::Hash IIPak::HashData(const void* data, const size_t dataSize) { - return crc32(0, static_cast(data), dataSize); + return crc32(0, static_cast(data), static_cast(dataSize)); } diff --git a/src/ObjLoading/ObjContainer/IPak/IPakEntryReadStream.cpp b/src/ObjLoading/ObjContainer/IPak/IPakEntryReadStream.cpp index 711b8773..710b41fb 100644 --- a/src/ObjLoading/ObjContainer/IPak/IPakEntryReadStream.cpp +++ b/src/ObjLoading/ObjContainer/IPak/IPakEntryReadStream.cpp @@ -2,6 +2,7 @@ #include "ObjContainer/IPak/IPakTypes.h" +#include #include #include #include @@ -24,7 +25,7 @@ IPakEntryReadStream::IPakEntryReadStream( m_current_command_offset(0), m_pos(startOffset), m_base_pos(startOffset), - m_end_pos(startOffset + entrySize), + m_end_pos(startOffset + static_cast(entrySize)), m_buffer_start_pos(0), m_buffer_end_pos(0) { @@ -53,8 +54,7 @@ bool IPakEntryReadStream::SetChunkBufferWindow(const int64_t startPos, size_t ch { // Cannot load more than IPAK_CHUNK_COUNT_PER_READ chunks without overflowing the buffer assert(chunkCount <= IPAK_CHUNK_COUNT_PER_READ); - if (chunkCount > IPAK_CHUNK_COUNT_PER_READ) - chunkCount = IPAK_CHUNK_COUNT_PER_READ; + chunkCount = std::min(chunkCount, IPAK_CHUNK_COUNT_PER_READ); // The start position must be aligned to IPAK_CHUNK_SIZE assert(startPos % IPAK_CHUNK_SIZE == 0); @@ -66,7 +66,7 @@ bool IPakEntryReadStream::SetChunkBufferWindow(const int64_t startPos, size_t ch return true; } - const auto endPos = startPos + static_cast(chunkCount) * IPAK_CHUNK_SIZE; + const auto endPos = startPos + static_cast(chunkCount) * static_cast(IPAK_CHUNK_SIZE); // Check whether the start position is already part of the loaded data // We might be able to reuse previously loaded data @@ -133,7 +133,7 @@ bool IPakEntryReadStream::ValidateBlockHeader(const IPakDataBlockHeader* blockHe } // We expect the current file to be continued where we left off - if (blockHeader->countAndOffset.offset != m_file_head) + if (static_cast(blockHeader->countAndOffset.offset) != m_file_head) { // A matching offset is only relevant if a command contains data for (unsigned currentCommand = 0; currentCommand < blockHeader->countAndOffset.count; currentCommand++) @@ -228,7 +228,7 @@ bool IPakEntryReadStream::ProcessCommand(const size_t commandSize, const int com m_current_command_buffer = m_decompress_buffer; m_current_command_length = outputSize; m_current_command_offset = 0; - m_file_head += outputSize; + m_file_head += static_cast(outputSize); } else { @@ -240,9 +240,9 @@ bool IPakEntryReadStream::ProcessCommand(const size_t commandSize, const int com m_current_command_buffer = &m_chunk_buffer[m_pos - m_buffer_start_pos]; m_current_command_length = commandSize; m_current_command_offset = 0; - m_file_head += commandSize; + m_file_head += static_cast(commandSize); } - m_pos += commandSize; + m_pos += static_cast(commandSize); return true; } @@ -326,7 +326,7 @@ std::streambuf::int_type IPakEntryReadStream::uflow() std::streamsize IPakEntryReadStream::xsgetn(char* ptr, const std::streamsize count) { auto* destBuffer = reinterpret_cast(ptr); - int64_t countRead = 0; + std::streamsize countRead = 0; while (countRead < count) { @@ -337,12 +337,11 @@ std::streamsize IPakEntryReadStream::xsgetn(char* ptr, const std::streamsize cou } auto sizeToRead = count - countRead; - if (sizeToRead > m_current_command_length - m_current_command_offset) - sizeToRead = m_current_command_length - m_current_command_offset; + sizeToRead = std::min(sizeToRead, static_cast(m_current_command_length - m_current_command_offset)); if (sizeToRead > 0) { - assert(static_cast(count - countRead) >= static_cast(sizeToRead)); + assert(count - countRead >= sizeToRead); memcpy(&destBuffer[countRead], &m_current_command_buffer[m_current_command_offset], static_cast(sizeToRead)); countRead += sizeToRead; m_current_command_offset += static_cast(sizeToRead); diff --git a/src/ObjLoading/ObjContainer/SoundBank/SoundBank.cpp b/src/ObjLoading/ObjContainer/SoundBank/SoundBank.cpp index 80181650..06ab0d72 100644 --- a/src/ObjLoading/ObjContainer/SoundBank/SoundBank.cpp +++ b/src/ObjLoading/ObjContainer/SoundBank/SoundBank.cpp @@ -1,9 +1,9 @@ #include "SoundBank.h" -#include "Utils/FileUtils.h" #include "zlib.h" #include +#include #include #include #include @@ -67,18 +67,18 @@ protected: if (dir == std::ios_base::end) { - if (off > m_size) + if (off > static_cast(m_size)) return pos_type(-1); - return seekpos(m_size - off, mode); + return seekpos(static_cast(m_size) - off, mode); } - return seekpos(m_offset + off, mode); + return seekpos(static_cast(m_offset) + off, mode); } pos_type seekpos(const pos_type pos, std::ios_base::openmode mode) override { - if (pos < 0 || pos >= m_size) + if (pos < 0 || pos >= static_cast(m_size)) return pos_type(-1); m_stream.seekg(m_base_offset + pos); @@ -96,7 +96,7 @@ public: { } - _NODISCARD bool is_open() const override + [[nodiscard]] bool is_open() const override { return m_open; } @@ -116,13 +116,13 @@ SoundBankEntryInputStream::SoundBankEntryInputStream() SoundBankEntryInputStream::SoundBankEntryInputStream(std::unique_ptr stream, SoundAssetBankEntry entry) : m_stream(std::move(stream)), - m_entry(entry) + m_entry(std::move(entry)) { } bool SoundBankEntryInputStream::IsOpen() const { - return m_stream.get() != nullptr; + return m_stream != nullptr; } bool SoundBank::ReadHeader() @@ -130,49 +130,50 @@ bool SoundBank::ReadHeader() m_stream->read(reinterpret_cast(&m_header), sizeof(m_header)); if (m_stream->gcount() != sizeof(m_header)) { - printf("Unexpected eof when trying to load sndbank header.\n"); + std::cerr << "Unexpected eof when trying to load sndbank header.\n"; return false; } if (m_header.magic != MAGIC) { - std::cout << "Invalid sndbank magic 0x" << std::hex << m_header.magic << "\n"; + std::cerr << std::format("Invalid sndbank magic 0x{:x}\n", m_header.magic); return false; } if (m_header.version != VERSION) { - std::cout << "Unsupported sndbank version " << m_header.version << " (should be " << VERSION << ")\n"; + std::cerr << std::format("Unsupported sndbank version {} (should be {})\n", m_header.version, VERSION); return false; } if (m_header.entrySize != sizeof(SoundAssetBankEntry)) { - std::cout << "Invalid sndbank entry size 0x" << std::hex << m_header.entrySize << " (should be 0x" << std::hex << sizeof(SoundAssetBankEntry) << ")\n"; + std::cerr << std::format("Invalid sndbank entry size 0x{:x} (should be 0x{:x})\n", m_header.entrySize, sizeof(SoundAssetBankEntry)); return false; } if (m_header.fileSize != m_file_size) { - std::cout << "Invalid sndbank " << m_file_size << " (header expects " << m_header.fileSize << ")\n"; + std::cerr << std::format("Invalid sndbank {} (header expects {})\n", m_file_size, m_header.fileSize); return false; } - if (m_header.entryCount && (m_header.entryOffset <= 0 || m_header.entryOffset + sizeof(SoundAssetBankEntry) * m_header.entryCount > m_file_size)) + if (m_header.entryCount + && (m_header.entryOffset <= 0 || m_header.entryOffset + sizeof(SoundAssetBankEntry) * m_header.entryCount > static_cast(m_file_size))) { - std::cout << "Invalid sndbank entry offset " << m_header.entryOffset << " (filesize is " << m_file_size << ")\n"; + std::cerr << std::format("Invalid sndbank entry offset {} (filesize is {})\n", m_header.entryOffset, m_file_size); return false; } - if (m_header.checksumOffset <= 0 || m_header.checksumOffset + sizeof(SoundAssetBankChecksum) * m_header.entryCount > m_file_size) + if (m_header.checksumOffset <= 0 || m_header.checksumOffset + sizeof(SoundAssetBankChecksum) * m_header.entryCount > static_cast(m_file_size)) { - std::cout << "Invalid sndbank checksum offset " << m_header.checksumOffset << " (filesize is " << m_file_size << ")\n"; + std::cerr << std::format("Invalid sndbank checksum offset {} (filesize is {})\n", m_header.checksumOffset, m_file_size); return false; } if (m_header.dependencyCount * m_header.dependencySize > sizeof(SoundAssetBankHeader::dependencies)) { - std::cout << "Invalid sndbank dependency sizes (count is " << m_header.dependencyCount << "; size is " << m_header.dependencySize << ")\n"; + std::cerr << std::format("Invalid sndbank dependency sizes (count is {}; size is {})\n", m_header.dependencyCount, m_header.dependencySize); return false; } @@ -201,13 +202,13 @@ bool SoundBank::ReadEntries() if (m_stream->gcount() != sizeof(entry)) { - std::cout << "Failed to read sound bank entry at index " << i << "\n"; + std::cerr << std::format("Failed to read sound bank entry at index {}\n", i); return false; } if (entry.offset == 0 || entry.offset + entry.size >= m_file_size) { - std::cout << "Invalid sound bank entry data offset " << entry.offset << " (filesize is " << m_header.fileSize << ")\n"; + std::cerr << std::format("Invalid sound bank entry data offset {} (filesize is {})\n", entry.offset, m_header.fileSize); return false; } @@ -229,7 +230,7 @@ bool SoundBank::ReadChecksums() if (m_stream->gcount() != sizeof(checksum)) { - std::cout << "Failed to read sound bank checksum at index " << i << "\n"; + std::cerr << std::format("Failed to read sound bank checksum at index {}\n", i); return false; } diff --git a/src/ObjLoading/SearchPath/IWD.cpp b/src/ObjLoading/SearchPath/IWD.cpp index ceea87a1..d84a8246 100644 --- a/src/ObjLoading/SearchPath/IWD.cpp +++ b/src/ObjLoading/SearchPath/IWD.cpp @@ -145,7 +145,7 @@ namespace { char temp[1024]; const auto toRead = skipAmount > sizeof(temp) ? sizeof(temp) : static_cast(skipAmount); - unzReadCurrentFile(m_container, temp, toRead); + unzReadCurrentFile(m_container, temp, static_cast(toRead)); skipAmount -= toRead; } diff --git a/src/ObjLoading/StringTable/StringTableLoader.h b/src/ObjLoading/StringTable/StringTableLoader.h index f5fd0b3e..d26abcb5 100644 --- a/src/ObjLoading/StringTable/StringTableLoader.h +++ b/src/ObjLoading/StringTable/StringTableLoader.h @@ -36,8 +36,7 @@ namespace string_table while (csv.NextRow(currentLine)) { - if (currentLine.size() > maxCols) - maxCols = currentLine.size(); + maxCols = std::max(static_cast(currentLine.size()), maxCols); csvLines.emplace_back(std::move(currentLine)); currentLine = std::vector(); } diff --git a/src/ObjLoading/Techset/Parsing/Sequence/TechniqueShaderScopeSequences.cpp b/src/ObjLoading/Techset/Parsing/Sequence/TechniqueShaderScopeSequences.cpp index c94d9f6e..5811a145 100644 --- a/src/ObjLoading/Techset/Parsing/Sequence/TechniqueShaderScopeSequences.cpp +++ b/src/ObjLoading/Techset/Parsing/Sequence/TechniqueShaderScopeSequences.cpp @@ -213,7 +213,7 @@ namespace techset const auto& shaderArgumentIndexToken = result.NextCapture(CAPTURE_SHADER_INDEX); if (shaderArgumentIndexToken.IntegerValue() < 0) throw ParsingException(shaderArgumentIndexToken.GetPos(), "Index cannot be negative"); - const auto index = static_cast(shaderArgumentIndexToken.IntegerValue()); + const auto index = static_cast(shaderArgumentIndexToken.IntegerValue()); arg = ShaderArgument(shaderArgumentNameToken.IdentifierValue(), index); } else diff --git a/src/ObjLoading/Techset/TechniqueDefinitionAcceptor.cpp b/src/ObjLoading/Techset/TechniqueDefinitionAcceptor.cpp index f9aabd71..c576a9d3 100644 --- a/src/ObjLoading/Techset/TechniqueDefinitionAcceptor.cpp +++ b/src/ObjLoading/Techset/TechniqueDefinitionAcceptor.cpp @@ -15,7 +15,7 @@ ShaderArgument::ShaderArgument(std::string argumentName) { } -ShaderArgument::ShaderArgument(std::string argumentName, const size_t argumentIndex) +ShaderArgument::ShaderArgument(std::string argumentName, const unsigned argumentIndex) : m_argument_name(std::move(argumentName)), m_argument_index_specified(true), m_argument_index(argumentIndex) @@ -35,7 +35,7 @@ ShaderArgumentCodeSource::ShaderArgumentCodeSource(std::vector acce { } -ShaderArgumentCodeSource::ShaderArgumentCodeSource(std::vector accessors, const size_t indexAccessor) +ShaderArgumentCodeSource::ShaderArgumentCodeSource(std::vector accessors, const unsigned indexAccessor) : m_accessors(std::move(accessors)), m_index_accessor_specified(true), m_index_accessor(indexAccessor) @@ -102,7 +102,7 @@ ShaderArgumentMaterialSource::ShaderArgumentMaterialSource() { } -ShaderArgumentMaterialSource::ShaderArgumentMaterialSource(const size_t hash) +ShaderArgumentMaterialSource::ShaderArgumentMaterialSource(const unsigned hash) : m_is_hash(true), m_hash(hash) { diff --git a/src/ObjLoading/Techset/TechniqueDefinitionAcceptor.h b/src/ObjLoading/Techset/TechniqueDefinitionAcceptor.h index d01f4a19..353c52cb 100644 --- a/src/ObjLoading/Techset/TechniqueDefinitionAcceptor.h +++ b/src/ObjLoading/Techset/TechniqueDefinitionAcceptor.h @@ -16,11 +16,11 @@ namespace techset public: std::string m_argument_name; bool m_argument_index_specified; - size_t m_argument_index; + unsigned m_argument_index; ShaderArgument(); explicit ShaderArgument(std::string argumentName); - ShaderArgument(std::string argumentName, size_t argumentIndex); + ShaderArgument(std::string argumentName, unsigned argumentIndex); }; class ShaderArgumentCodeSource @@ -28,11 +28,11 @@ namespace techset public: std::vector m_accessors; bool m_index_accessor_specified; - size_t m_index_accessor; + unsigned m_index_accessor; ShaderArgumentCodeSource(); explicit ShaderArgumentCodeSource(std::vector accessors); - ShaderArgumentCodeSource(std::vector accessors, size_t indexAccessor); + ShaderArgumentCodeSource(std::vector accessors, unsigned indexAccessor); }; class ShaderArgumentLiteralSource @@ -53,13 +53,13 @@ namespace techset class ShaderArgumentMaterialSource { public: - bool m_is_hash; - size_t m_hash; - std::string m_name; - ShaderArgumentMaterialSource(); - explicit ShaderArgumentMaterialSource(size_t hash); + explicit ShaderArgumentMaterialSource(unsigned hash); explicit ShaderArgumentMaterialSource(std::string name); + + bool m_is_hash; + unsigned m_hash; + std::string m_name; }; class ITechniqueDefinitionAcceptor diff --git a/src/ObjLoading/XModel/Gltf/GltfLoader.cpp b/src/ObjLoading/XModel/Gltf/GltfLoader.cpp index 1c355eff..df5255e2 100644 --- a/src/ObjLoading/XModel/Gltf/GltfLoader.cpp +++ b/src/ObjLoading/XModel/Gltf/GltfLoader.cpp @@ -258,7 +258,7 @@ namespace VerifyAccessorVertexCount("WEIGHTS_0", weightsAccessor, vertexCount); // clang-format on - const auto vertexOffset = common.m_vertices.size(); + const auto vertexOffset = static_cast(common.m_vertices.size()); common.m_vertices.reserve(vertexOffset + vertexCount); common.m_vertex_bone_weights.reserve(vertexOffset + vertexCount); for (auto vertexIndex = 0u; vertexIndex < vertexCount; vertexIndex++) @@ -300,6 +300,7 @@ namespace } m_vertex_offset_for_accessors.emplace(accessorsForVertex, vertexOffset); + return vertexOffset; } @@ -499,7 +500,7 @@ namespace const auto boneInSkin = std::ranges::find(skin.joints, nodeIndex); if (boneInSkin == skin.joints.end()) throw GltfLoadException("Bone node is not part of skin"); - const auto boneIndexInSkin = std::distance(skin.joints.begin(), boneInSkin); + const auto boneIndexInSkin = static_cast(std::distance(skin.joints.begin(), boneInSkin)); const auto commonBoneOffset = skinBoneOffset + boneIndexInSkin; auto& bone = common.m_bones[commonBoneOffset]; @@ -548,7 +549,7 @@ namespace return false; const auto rootNode = GetRootNodeForSkin(jRoot, skin).value_or(skin.joints[0]); - const auto skinBoneOffset = common.m_bones.size(); + const auto skinBoneOffset = static_cast(common.m_bones.size()); common.m_bones.resize(skinBoneOffset + skin.joints.size()); constexpr float defaultTranslation[3]{0.0f, 0.0f, 0.0f}; diff --git a/src/ObjLoading/XModel/PartClassificationState.cpp b/src/ObjLoading/XModel/PartClassificationState.cpp index e314b03e..be898f50 100644 --- a/src/ObjLoading/XModel/PartClassificationState.cpp +++ b/src/ObjLoading/XModel/PartClassificationState.cpp @@ -72,7 +72,7 @@ bool PartClassificationState::LoadRow(const char** hitLocStart, const char** hit return false; } - const auto hitLocNum = std::distance(hitLocStart, foundHitLoc); + const auto hitLocNum = static_cast(std::distance(hitLocStart, foundHitLoc)); m_part_classifications.emplace(row[0], hitLocNum); return true; diff --git a/src/ObjLoading/XModel/TangentData.cpp b/src/ObjLoading/XModel/TangentData.cpp index a09c25f3..dc509af0 100644 --- a/src/ObjLoading/XModel/TangentData.cpp +++ b/src/ObjLoading/XModel/TangentData.cpp @@ -11,11 +11,11 @@ void TangentData::CreateTangentData(const XModelCommon& common) m_tangents.resize(vertexCount); m_binormals.resize(vertexCount); - auto triCount = 0u; + auto triCount = 0uz; for (const auto& object : common.m_objects) triCount += object.m_faces.size(); - std::vector indices(triCount * 3u); + std::vector indices(triCount * 3uz); auto triOffset = 0u; for (const auto& object : common.m_objects) { diff --git a/src/ZoneCommon/Zone/Definition/Parsing/ZoneDefinitionParserState.cpp b/src/ZoneCommon/Zone/Definition/Parsing/ZoneDefinitionParserState.cpp index 30c8d564..af7a1a62 100644 --- a/src/ZoneCommon/Zone/Definition/Parsing/ZoneDefinitionParserState.cpp +++ b/src/ZoneCommon/Zone/Definition/Parsing/ZoneDefinitionParserState.cpp @@ -26,14 +26,14 @@ namespace if (!maybeObjContainer) return; - maybeObjContainer->m_asset_end = zoneDefinition.m_assets.size(); + maybeObjContainer->m_asset_end = static_cast(zoneDefinition.m_assets.size()); zoneDefinition.m_obj_containers.emplace_back(std::move(*maybeObjContainer)); maybeObjContainer = std::nullopt; } ZoneDefinitionObjContainer DefineNewObjContainer(const ZoneDefinition& zoneDefinition, std::string name, const ZoneDefinitionObjContainerType type) { - return ZoneDefinitionObjContainer(std::move(name), type, zoneDefinition.m_assets.size()); + return ZoneDefinitionObjContainer(std::move(name), type, static_cast(zoneDefinition.m_assets.size())); } void SortObjContainer(ZoneDefinition& zoneDefinition) diff --git a/src/ZoneCommon/Zone/XChunk/XChunkProcessorDeflate.cpp b/src/ZoneCommon/Zone/XChunk/XChunkProcessorDeflate.cpp index 59425014..5cff8933 100644 --- a/src/ZoneCommon/Zone/XChunk/XChunkProcessorDeflate.cpp +++ b/src/ZoneCommon/Zone/XChunk/XChunkProcessorDeflate.cpp @@ -17,9 +17,9 @@ size_t XChunkProcessorDeflate::Process(int streamNumber, const uint8_t* input, c if (ret != Z_OK) throw XChunkException("Initializing deflate failed."); - stream.avail_in = inputLength; + stream.avail_in = static_cast(inputLength); stream.next_in = input; - stream.avail_out = outputBufferSize; + stream.avail_out = static_cast(outputBufferSize); stream.next_out = output; ret = deflate(&stream, Z_FINISH); diff --git a/src/ZoneCommon/Zone/XChunk/XChunkProcessorInflate.cpp b/src/ZoneCommon/Zone/XChunk/XChunkProcessorInflate.cpp index c18e6fe9..bc8420ff 100644 --- a/src/ZoneCommon/Zone/XChunk/XChunkProcessorInflate.cpp +++ b/src/ZoneCommon/Zone/XChunk/XChunkProcessorInflate.cpp @@ -16,9 +16,9 @@ size_t XChunkProcessorInflate::Process(int streamNumber, const uint8_t* input, c if (ret != Z_OK) throw XChunkException("Initializing inflate failed."); - stream.avail_in = inputLength; + stream.avail_in = static_cast(inputLength); stream.next_in = input; - stream.avail_out = outputBufferSize; + stream.avail_out = static_cast(outputBufferSize); stream.next_out = output; ret = inflate(&stream, Z_FULL_FLUSH); From de43e33dcd9fb76b7af3212d5423341752314d83 Mon Sep 17 00:00:00 2001 From: Jan Date: Sat, 26 Apr 2025 10:19:00 +0100 Subject: [PATCH 05/11] refactor: fix x64 compilation for ObjWriting --- .../T6/AssetDumpers/AssetDumperFontIcon.cpp | 37 ++++++++----------- 1 file changed, 16 insertions(+), 21 deletions(-) diff --git a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperFontIcon.cpp b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperFontIcon.cpp index 4849d609..20e375f7 100644 --- a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperFontIcon.cpp +++ b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperFontIcon.cpp @@ -3,7 +3,7 @@ #include "Csv/CsvStream.h" #include "Game/T6/CommonT6.h" -#include +#include using namespace T6; @@ -140,14 +140,14 @@ class AssetDumperFontIconInternal CsvOutputStream m_csv; - static FontIconEntry* FindEntryByHash(FontIcon* fontIcon, const int hash) + static FontIconEntry* FindEntryByHash(const FontIcon* fontIcon, const int hash) { - int lowerBound = 0; - int upperBound = fontIcon->numEntries; + auto lowerBound = 0u; + auto upperBound = fontIcon->numEntries; while (true) { - const int entryIndex = (lowerBound + upperBound) / 2; + const auto entryIndex = (lowerBound + upperBound) / 2u; auto* entry = &fontIcon->fontIconEntry[entryIndex]; if (entry->fontIconName.hash == hash) @@ -157,9 +157,9 @@ class AssetDumperFontIconInternal return nullptr; if (entry->fontIconName.hash < hash) - lowerBound = entryIndex + 1; + lowerBound = entryIndex + 1u; else - upperBound = entryIndex - 1; + upperBound = entryIndex - 1u; } } @@ -174,15 +174,15 @@ class AssetDumperFontIconInternal return nullptr; } - void WriteFontIconEntries(FontIcon* fontIcon) + void WriteFontIconEntries(const FontIcon* fontIcon) { for (const auto& header : ICON_HEADERS) m_csv.WriteColumn(header); m_csv.NextRow(); - for (int iconIndex = 0; iconIndex < fontIcon->numEntries; iconIndex++) + for (auto iconIndex = 0u; iconIndex < fontIcon->numEntries; iconIndex++) { - auto* entry = &fontIcon->fontIconEntry[iconIndex]; + const auto* entry = &fontIcon->fontIconEntry[iconIndex]; m_csv.WriteColumn(std::to_string(iconIndex)); m_csv.WriteColumn(TYPE_ICON); @@ -204,15 +204,15 @@ class AssetDumperFontIconInternal } } - void WriteFontIconAliases(FontIcon* fontIcon) + void WriteFontIconAliases(const FontIcon* fontIcon) { for (const auto& header : ALIAS_HEADERS) m_csv.WriteColumn(header); m_csv.NextRow(); - for (int aliasIndex = 0; aliasIndex < fontIcon->numAliasEntries; aliasIndex++) + for (auto aliasIndex = 0u; aliasIndex < fontIcon->numAliasEntries; aliasIndex++) { - auto* alias = &fontIcon->fontIconAlias[aliasIndex]; + const auto* alias = &fontIcon->fontIconAlias[aliasIndex]; m_csv.WriteColumn(std::to_string(aliasIndex)); m_csv.WriteColumn(TYPE_ALIAS); @@ -220,14 +220,9 @@ class AssetDumperFontIconInternal if (knownAlias) m_csv.WriteColumn(knownAlias->m_name); else - { - std::ostringstream str; - str << '@' << std::hex << alias->aliasHash; + m_csv.WriteColumn(std::format("@{:x}", alias->aliasHash)); - m_csv.WriteColumn(str.str()); - } - - auto* referencedEntry = FindEntryByHash(fontIcon, alias->buttonHash); + const auto* referencedEntry = FindEntryByHash(fontIcon, alias->buttonHash); if (referencedEntry && referencedEntry->fontIconName.string) m_csv.WriteColumn(referencedEntry->fontIconName.string); else @@ -243,7 +238,7 @@ public: { } - void DumpFontIcon(FontIcon* fontIcon) + void DumpFontIcon(const FontIcon* fontIcon) { WriteFontIconEntries(fontIcon); m_csv.NextRow(); From 3b00c1d45b017d3f757b2e012ee100847d53ccea Mon Sep 17 00:00:00 2001 From: Jan Date: Sat, 26 Apr 2025 11:45:33 +0100 Subject: [PATCH 06/11] refactor: fix x64 compilation for ZoneLoading --- src/Common/Zone/ZoneTypes.h | 4 +-- src/ZoneCommon/Zone/XBlock.h | 2 +- .../Game/IW4/ZoneLoaderFactoryIW4.cpp | 15 +++++---- .../Game/IW5/ZoneLoaderFactoryIW5.cpp | 15 +++++---- .../Loading/Processor/ProcessorInflate.cpp | 6 ++-- .../Loading/Processor/ProcessorXChunks.cpp | 12 +++---- .../Loading/Steps/StepAllocXBlocks.cpp | 8 ++--- .../Loading/Steps/StepDumpData.cpp | 10 +++--- src/ZoneLoading/Loading/Steps/StepDumpData.h | 7 ++-- .../Loading/Steps/StepSkipBytes.cpp | 8 ++--- src/ZoneLoading/Loading/Steps/StepSkipBytes.h | 7 ++-- .../Zone/Stream/Impl/XBlockInputStream.cpp | 33 ++++++++----------- .../Zone/Stream/Impl/XBlockInputStream.h | 27 +++++++-------- 13 files changed, 75 insertions(+), 79 deletions(-) diff --git a/src/Common/Zone/ZoneTypes.h b/src/Common/Zone/ZoneTypes.h index 64ca10e9..46bf92ca 100644 --- a/src/Common/Zone/ZoneTypes.h +++ b/src/Common/Zone/ZoneTypes.h @@ -14,6 +14,6 @@ typedef uint32_t xblock_size_t; constexpr uint16_t SCR_STRING_MAX = std::numeric_limits::max(); -typedef int block_t; -typedef int asset_type_t; +typedef unsigned block_t; +typedef unsigned asset_type_t; typedef unsigned int zone_priority_t; diff --git a/src/ZoneCommon/Zone/XBlock.h b/src/ZoneCommon/Zone/XBlock.h index b65c28df..8128864a 100644 --- a/src/ZoneCommon/Zone/XBlock.h +++ b/src/ZoneCommon/Zone/XBlock.h @@ -14,7 +14,7 @@ public: }; std::string m_name; - int m_index; + unsigned m_index; Type m_type; uint8_t* m_buffer; diff --git a/src/ZoneLoading/Game/IW4/ZoneLoaderFactoryIW4.cpp b/src/ZoneLoading/Game/IW4/ZoneLoaderFactoryIW4.cpp index e2b4bbc0..f7347570 100644 --- a/src/ZoneLoading/Game/IW4/ZoneLoaderFactoryIW4.cpp +++ b/src/ZoneLoading/Game/IW4/ZoneLoaderFactoryIW4.cpp @@ -143,7 +143,8 @@ namespace zoneLoader.AddLoadingStep(std::make_unique(fileName, sizeof(DB_AuthSubHeader::fastfileName))); zoneLoader.AddLoadingStep(std::make_unique(4)); // Skip reserved - auto masterBlockHashes = std::make_unique(sizeof(DB_AuthHash::bytes), std::extent_v); + auto masterBlockHashes = + std::make_unique(sizeof(DB_AuthHash::bytes), static_cast(std::extent_v)); auto* masterBlockHashesPtr = masterBlockHashes.get(); zoneLoader.AddLoadingStep(std::move(masterBlockHashes)); @@ -153,12 +154,12 @@ namespace // Skip the rest of the first chunk zoneLoader.AddLoadingStep(std::make_unique(ZoneConstants::AUTHED_CHUNK_SIZE - sizeof(DB_AuthHeader))); - zoneLoader.AddLoadingStep( - std::make_unique(std::make_unique(ZoneConstants::AUTHED_CHUNK_COUNT_PER_GROUP, - ZoneConstants::AUTHED_CHUNK_SIZE, - std::extent_v, - cryptography::CreateSha256(), - masterBlockHashesPtr))); + zoneLoader.AddLoadingStep(std::make_unique( + std::make_unique(ZoneConstants::AUTHED_CHUNK_COUNT_PER_GROUP, + ZoneConstants::AUTHED_CHUNK_SIZE, + static_cast(std::extent_v), + cryptography::CreateSha256(), + masterBlockHashesPtr))); } } // namespace diff --git a/src/ZoneLoading/Game/IW5/ZoneLoaderFactoryIW5.cpp b/src/ZoneLoading/Game/IW5/ZoneLoaderFactoryIW5.cpp index f2a18c53..b35b4274 100644 --- a/src/ZoneLoading/Game/IW5/ZoneLoaderFactoryIW5.cpp +++ b/src/ZoneLoading/Game/IW5/ZoneLoaderFactoryIW5.cpp @@ -127,7 +127,8 @@ namespace zoneLoader.AddLoadingStep(std::make_unique(fileName, sizeof(DB_AuthSubHeader::fastfileName))); zoneLoader.AddLoadingStep(std::make_unique(4)); // Skip reserved - auto masterBlockHashes = std::make_unique(sizeof(DB_AuthHash::bytes), std::extent_v); + auto masterBlockHashes = + std::make_unique(sizeof(DB_AuthHash::bytes), static_cast(std::extent_v)); auto* masterBlockHashesPtr = masterBlockHashes.get(); zoneLoader.AddLoadingStep(std::move(masterBlockHashes)); @@ -137,12 +138,12 @@ namespace // Skip the rest of the first chunk zoneLoader.AddLoadingStep(std::make_unique(ZoneConstants::AUTHED_CHUNK_SIZE - sizeof(DB_AuthHeader))); - zoneLoader.AddLoadingStep( - std::make_unique(std::make_unique(ZoneConstants::AUTHED_CHUNK_COUNT_PER_GROUP, - ZoneConstants::AUTHED_CHUNK_SIZE, - std::extent_v, - cryptography::CreateSha256(), - masterBlockHashesPtr))); + zoneLoader.AddLoadingStep(std::make_unique( + std::make_unique(ZoneConstants::AUTHED_CHUNK_COUNT_PER_GROUP, + ZoneConstants::AUTHED_CHUNK_SIZE, + static_cast(std::extent_v), + cryptography::CreateSha256(), + masterBlockHashesPtr))); } } // namespace diff --git a/src/ZoneLoading/Loading/Processor/ProcessorInflate.cpp b/src/ZoneLoading/Loading/Processor/ProcessorInflate.cpp index afda6ba6..e04de7db 100644 --- a/src/ZoneLoading/Loading/Processor/ProcessorInflate.cpp +++ b/src/ZoneLoading/Loading/Processor/ProcessorInflate.cpp @@ -50,20 +50,20 @@ public: size_t Load(void* buffer, const size_t length) { m_stream.next_out = static_cast(buffer); - m_stream.avail_out = length; + m_stream.avail_out = static_cast(length); while (m_stream.avail_out > 0) { if (m_stream.avail_in == 0) { - m_stream.avail_in = m_base->m_base_stream->Load(m_buffer.get(), m_buffer_size); + m_stream.avail_in = static_cast(m_base->m_base_stream->Load(m_buffer.get(), m_buffer_size)); m_stream.next_in = m_buffer.get(); if (m_stream.avail_in == 0) // EOF return length - m_stream.avail_out; } - auto ret = inflate(&m_stream, Z_SYNC_FLUSH); + const auto ret = inflate(&m_stream, Z_SYNC_FLUSH); if (ret < 0) throw InvalidCompressionException(); diff --git a/src/ZoneLoading/Loading/Processor/ProcessorXChunks.cpp b/src/ZoneLoading/Loading/Processor/ProcessorXChunks.cpp index 1a48ff01..c0f727c8 100644 --- a/src/ZoneLoading/Loading/Processor/ProcessorXChunks.cpp +++ b/src/ZoneLoading/Loading/Processor/ProcessorXChunks.cpp @@ -78,7 +78,7 @@ public: m_is_loading = false; } - uint8_t* GetInputBuffer() const + [[nodiscard]] uint8_t* GetInputBuffer() const { return m_input_buffer; } @@ -140,9 +140,9 @@ class ProcessorXChunks::ProcessorXChunksImpl bool m_eof_reached; unsigned int m_eof_stream; - void AdvanceStream(const unsigned int streamNum) + void AdvanceStream(const unsigned streamNum) { - assert(streamNum >= 0 && streamNum < m_streams.size()); + assert(streamNum < m_streams.size()); if (m_eof_reached) return; @@ -203,8 +203,8 @@ class ProcessorXChunks::ProcessorXChunksImpl m_initialized_streams = true; m_vanilla_buffer_offset = static_cast(m_base->m_base_stream->Pos()); - const unsigned int streamCount = m_streams.size(); - for (unsigned int streamNum = 0; streamNum < streamCount; streamNum++) + const auto streamCount = static_cast(m_streams.size()); + for (auto streamNum = 0u; streamNum < streamCount; streamNum++) { AdvanceStream(streamNum); } @@ -214,7 +214,7 @@ class ProcessorXChunks::ProcessorXChunksImpl m_streams[0]->GetOutput(&m_current_chunk, &m_current_chunk_size); } - bool EndOfStream() const + [[nodiscard]] bool EndOfStream() const { return m_eof_reached && m_eof_stream == m_current_stream; } diff --git a/src/ZoneLoading/Loading/Steps/StepAllocXBlocks.cpp b/src/ZoneLoading/Loading/Steps/StepAllocXBlocks.cpp index aa9e2786..352d814b 100644 --- a/src/ZoneLoading/Loading/Steps/StepAllocXBlocks.cpp +++ b/src/ZoneLoading/Loading/Steps/StepAllocXBlocks.cpp @@ -6,10 +6,10 @@ const uint64_t StepAllocXBlocks::MAX_XBLOCK_SIZE = 0x3C000000; void StepAllocXBlocks::PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) { - const unsigned int blockCount = zoneLoader->m_blocks.size(); + const auto blockCount = static_cast(zoneLoader->m_blocks.size()); - auto* blockSizes = new xblock_size_t[blockCount]; - stream->Load(blockSizes, sizeof(xblock_size_t) * blockCount); + const auto blockSizes = std::make_unique(blockCount); + stream->Load(blockSizes.get(), sizeof(xblock_size_t) * blockCount); uint64_t totalMemory = 0; for (unsigned int block = 0; block < blockCount; block++) @@ -26,6 +26,4 @@ void StepAllocXBlocks::PerformStep(ZoneLoader* zoneLoader, ILoadingStream* strea { zoneLoader->m_blocks[block]->Alloc(blockSizes[block]); } - - delete[] blockSizes; } diff --git a/src/ZoneLoading/Loading/Steps/StepDumpData.cpp b/src/ZoneLoading/Loading/Steps/StepDumpData.cpp index 9257b811..3356ba2b 100644 --- a/src/ZoneLoading/Loading/Steps/StepDumpData.cpp +++ b/src/ZoneLoading/Loading/Steps/StepDumpData.cpp @@ -2,21 +2,21 @@ #include -StepDumpData::StepDumpData(const unsigned int dumpCount) +StepDumpData::StepDumpData(const size_t dumpCount) + : m_dump_count(dumpCount) { - m_dump_count = dumpCount; } void StepDumpData::PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) { uint8_t tempBuffer[128]; - unsigned int dumpedBytes = 0; + auto dumpedBytes = 0uz; std::ofstream tempFile("dump.dat", std::fstream::out | std::fstream::binary); while (dumpedBytes < m_dump_count) { - unsigned int toDump; + size_t toDump; if (m_dump_count - dumpedBytes < sizeof(tempBuffer)) { @@ -33,7 +33,7 @@ void StepDumpData::PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) if (loadedSize == 0) break; - tempFile.write(reinterpret_cast(tempBuffer), loadedSize); + tempFile.write(reinterpret_cast(tempBuffer), static_cast(loadedSize)); } tempFile.close(); diff --git a/src/ZoneLoading/Loading/Steps/StepDumpData.h b/src/ZoneLoading/Loading/Steps/StepDumpData.h index 648bdea3..dc01b570 100644 --- a/src/ZoneLoading/Loading/Steps/StepDumpData.h +++ b/src/ZoneLoading/Loading/Steps/StepDumpData.h @@ -4,10 +4,11 @@ class StepDumpData final : public ILoadingStep { - unsigned int m_dump_count; - public: - explicit StepDumpData(unsigned int dumpCount); + explicit StepDumpData(size_t dumpCount); void PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) override; + +private: + size_t m_dump_count; }; diff --git a/src/ZoneLoading/Loading/Steps/StepSkipBytes.cpp b/src/ZoneLoading/Loading/Steps/StepSkipBytes.cpp index 52dcd09d..028e49c0 100644 --- a/src/ZoneLoading/Loading/Steps/StepSkipBytes.cpp +++ b/src/ZoneLoading/Loading/Steps/StepSkipBytes.cpp @@ -1,18 +1,18 @@ #include "StepSkipBytes.h" -StepSkipBytes::StepSkipBytes(const unsigned int skipCount) +StepSkipBytes::StepSkipBytes(const size_t skipCount) + : m_skip_count(skipCount) { - m_skip_count = skipCount; } void StepSkipBytes::PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) { uint8_t tempBuffer[128]; - unsigned int skippedBytes = 0; + auto skippedBytes = 0uz; while (skippedBytes < m_skip_count) { - unsigned int toSkip; + size_t toSkip; if (m_skip_count - skippedBytes < sizeof(tempBuffer)) { diff --git a/src/ZoneLoading/Loading/Steps/StepSkipBytes.h b/src/ZoneLoading/Loading/Steps/StepSkipBytes.h index eaedf563..417eb805 100644 --- a/src/ZoneLoading/Loading/Steps/StepSkipBytes.h +++ b/src/ZoneLoading/Loading/Steps/StepSkipBytes.h @@ -4,10 +4,11 @@ class StepSkipBytes final : public ILoadingStep { - unsigned int m_skip_count; - public: - explicit StepSkipBytes(unsigned int skipCount); + explicit StepSkipBytes(size_t skipCount); void PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) override; + +private: + size_t m_skip_count; }; diff --git a/src/ZoneLoading/Zone/Stream/Impl/XBlockInputStream.cpp b/src/ZoneLoading/Zone/Stream/Impl/XBlockInputStream.cpp index f1e59b34..55d98480 100644 --- a/src/ZoneLoading/Zone/Stream/Impl/XBlockInputStream.cpp +++ b/src/ZoneLoading/Zone/Stream/Impl/XBlockInputStream.cpp @@ -13,23 +13,16 @@ XBlockInputStream::XBlockInputStream(std::vector& blocks, ILoadingStrea { m_stream = stream; - const unsigned int blockCount = blocks.size(); - m_block_offsets = new size_t[blockCount]{0}; + const auto blockCount = static_cast(blocks.size()); + m_block_offsets = std::make_unique(blockCount); + std::memset(m_block_offsets.get(), 0, sizeof(size_t) * blockCount); m_block_bit_count = blockBitCount; - assert(insertBlock >= 0 && insertBlock < static_cast(blocks.size())); + assert(insertBlock < static_cast(blocks.size())); m_insert_block = blocks[insertBlock]; } -XBlockInputStream::~XBlockInputStream() -{ - delete[] m_block_offsets; - m_block_offsets = nullptr; - - assert(m_block_stack.empty()); -} - void XBlockInputStream::Align(const unsigned align) { assert(!m_block_stack.empty()); @@ -37,13 +30,13 @@ void XBlockInputStream::Align(const unsigned align) if (align > 0) { const block_t blockIndex = m_block_stack.top()->m_index; - m_block_offsets[blockIndex] = (m_block_offsets[blockIndex] + align - 1) / align * align; + m_block_offsets[blockIndex] = (m_block_offsets[blockIndex] + align - 1u) / align * align; } } void XBlockInputStream::PushBlock(const block_t block) { - assert(block >= 0 && block < static_cast(m_blocks.size())); + assert(block < static_cast(m_blocks.size())); XBlock* newBlock = m_blocks[block]; @@ -150,7 +143,7 @@ void XBlockInputStream::IncBlockPos(const size_t size) if (m_block_stack.empty()) return; - XBlock* block = m_block_stack.top(); + const XBlock* block = m_block_stack.top(); m_block_offsets[block->m_index] += size; } @@ -172,7 +165,7 @@ void XBlockInputStream::LoadNullTerminated(void* dst) assert(dst == &block->m_buffer[m_block_offsets[block->m_index]]); uint8_t byte; - size_t offset = reinterpret_cast(dst) - block->m_buffer; + size_t offset = static_cast(dst) - block->m_buffer; do { if (offset >= block->m_buffer_size) @@ -198,7 +191,7 @@ void** XBlockInputStream::InsertPointer() throw BlockOverflowException(m_insert_block); } - void** ptr = reinterpret_cast(&m_insert_block->m_buffer[m_block_offsets[m_insert_block->m_index]]); + auto* ptr = reinterpret_cast(&m_insert_block->m_buffer[m_block_offsets[m_insert_block->m_index]]); IncBlockPos(sizeof(void*)); @@ -211,9 +204,9 @@ void* XBlockInputStream::ConvertOffsetToPointer(const void* offset) { // -1 because otherwise Block 0 Offset 0 would be just 0 which is already used to signalize a nullptr. // So all offsets are moved by 1. - auto offsetInt = reinterpret_cast(offset) - 1; + const auto offsetInt = reinterpret_cast(offset) - 1u; - const block_t blockNum = offsetInt >> (sizeof(offsetInt) * 8 - m_block_bit_count); + const block_t blockNum = static_cast(offsetInt >> (sizeof(offsetInt) * 8u - m_block_bit_count)); const size_t blockOffset = offsetInt & (UINTPTR_MAX >> m_block_bit_count); if (blockNum < 0 || blockNum >= static_cast(m_blocks.size())) @@ -234,9 +227,9 @@ void* XBlockInputStream::ConvertOffsetToPointer(const void* offset) void* XBlockInputStream::ConvertOffsetToAlias(const void* offset) { // For details see ConvertOffsetToPointer - auto offsetInt = reinterpret_cast(offset) - 1; + const auto offsetInt = reinterpret_cast(offset) - 1; - const block_t blockNum = offsetInt >> (sizeof(offsetInt) * 8 - m_block_bit_count); + const block_t blockNum = static_cast(offsetInt >> (sizeof(offsetInt) * 8 - m_block_bit_count)); const size_t blockOffset = offsetInt & (UINTPTR_MAX >> m_block_bit_count); if (blockNum < 0 || blockNum >= static_cast(m_blocks.size())) diff --git a/src/ZoneLoading/Zone/Stream/Impl/XBlockInputStream.h b/src/ZoneLoading/Zone/Stream/Impl/XBlockInputStream.h index bbaba39d..617880aa 100644 --- a/src/ZoneLoading/Zone/Stream/Impl/XBlockInputStream.h +++ b/src/ZoneLoading/Zone/Stream/Impl/XBlockInputStream.h @@ -4,26 +4,14 @@ #include "Zone/Stream/IZoneInputStream.h" #include "Zone/XBlock.h" +#include #include #include class XBlockInputStream final : public IZoneInputStream { - std::vector& m_blocks; - size_t* m_block_offsets; - - std::stack m_block_stack; - std::stack m_temp_offsets; - ILoadingStream* m_stream; - - int m_block_bit_count; - XBlock* m_insert_block; - - void Align(unsigned align); - public: XBlockInputStream(std::vector& blocks, ILoadingStream* stream, int blockBitCount, block_t insertBlock); - ~XBlockInputStream() override; void PushBlock(block_t block) override; block_t PopBlock() override; @@ -39,4 +27,17 @@ public: void* ConvertOffsetToPointer(const void* offset) override; void* ConvertOffsetToAlias(const void* offset) override; + +private: + void Align(unsigned align); + + std::vector& m_blocks; + std::unique_ptr m_block_offsets; + + std::stack m_block_stack; + std::stack m_temp_offsets; + ILoadingStream* m_stream; + + unsigned m_block_bit_count; + XBlock* m_insert_block; }; From a6107e24a215c5c033487677455faafcd05d84c5 Mon Sep 17 00:00:00 2001 From: Jan Laupetin Date: Sat, 26 Apr 2025 18:59:18 +0200 Subject: [PATCH 07/11] chore: disable type alignment on x64 for x86 games --- src/Common/Game/IW3/IW3_Assets.h | 34 ++++---- src/Common/Game/IW4/IW4_Assets.h | 54 ++++++------- src/Common/Game/IW5/IW5_Assets.h | 54 ++++++------- src/Common/Game/T5/T5_Assets.h | 82 +++++++++---------- src/Common/Game/T6/T6_Assets.h | 134 +++++++++++++++---------------- src/Common/Utils/TypeAlignment.h | 34 +++++--- 6 files changed, 204 insertions(+), 188 deletions(-) diff --git a/src/Common/Game/IW3/IW3_Assets.h b/src/Common/Game/IW3/IW3_Assets.h index 9e3ae951..772b757c 100644 --- a/src/Common/Game/IW3/IW3_Assets.h +++ b/src/Common/Game/IW3/IW3_Assets.h @@ -135,7 +135,7 @@ namespace IW3 typedef float vec2_t[2]; typedef float vec3_t[3]; typedef float vec4_t[4]; - typedef tdef_align(128) unsigned int raw_uint128; + typedef tdef_align32(128) unsigned int raw_uint128; struct XModelPiece { @@ -179,7 +179,7 @@ namespace IW3 }; typedef unsigned char ByteVec[3]; - typedef tdef_align(4) unsigned short UShortVec[3]; + typedef tdef_align32(4) unsigned short UShortVec[3]; union XAnimDynamicIndicesTrans { @@ -214,7 +214,7 @@ namespace IW3 XAnimPartTransData u; }; - typedef tdef_align(4) short XQuat[2]; + typedef tdef_align32(4) short XQuat[2]; union XAnimDynamicIndicesQuat { @@ -296,7 +296,7 @@ namespace IW3 uint16_t maxs[3]; }; - struct type_align(16) XSurfaceCollisionNode + struct type_align32(16) XSurfaceCollisionNode { XSurfaceCollisionAabb aabb; uint16_t childBeginIndex; @@ -344,7 +344,7 @@ namespace IW3 char array[4]; }; - struct type_align(16) GfxPackedVertex + struct type_align32(16) GfxPackedVertex { float xyz[3]; float binormalSign; @@ -360,7 +360,7 @@ namespace IW3 uint16_t* vertsBlend; }; - typedef tdef_align(16) uint16_t r_index16_t; + typedef tdef_align32(16) uint16_t r_index16_t; struct XSurface { @@ -633,7 +633,7 @@ namespace IW3 unsigned int loadBits[2]; }; - struct type_align(16) MaterialConstantDef + struct type_align32(16) MaterialConstantDef { unsigned int nameHash; char name[12]; @@ -709,7 +709,7 @@ namespace IW3 MaterialTextureDefInfo u; }; - struct gcc_align(8) GfxDrawSurfFields + struct gcc_align32(8) GfxDrawSurfFields { uint64_t objectId : 16; uint64_t reflectionProbeIndex : 8; @@ -724,8 +724,8 @@ namespace IW3 union GfxDrawSurf { - gcc_align(8) GfxDrawSurfFields fields; - gcc_align(8) uint64_t packed; + gcc_align32(8) GfxDrawSurfFields fields; + gcc_align32(8) uint64_t packed; }; enum materialSurfType_t @@ -1605,7 +1605,7 @@ namespace IW3 cLeaf_t leaf; }; - struct type_align(16) cbrush_t + struct type_align32(16) cbrush_t { float mins[3]; int contents; @@ -1671,7 +1671,7 @@ namespace IW3 typedef unsigned short LeafBrush; - typedef tdef_align(16) cbrush_t cbrush_array_t; + typedef tdef_align32(16) cbrush_t cbrush_array_t; struct clipMap_t { @@ -1775,7 +1775,7 @@ namespace IW3 pathnode_tree_info_t u; }; - struct type_align(16) pathbasenode_t + struct type_align32(16) pathbasenode_t { float vOrigin[3]; unsigned int type; @@ -2044,14 +2044,14 @@ namespace IW3 GfxImage* secondary; }; - struct type_align(4) GfxLightGridEntry + struct type_align32(4) GfxLightGridEntry { uint16_t colorsIndex; char primaryLightIndex; char needsTrace; }; - struct type_align(4) GfxLightGridColors + struct type_align32(4) GfxLightGridColors { char rgb[56][3]; }; @@ -2137,7 +2137,7 @@ namespace IW3 uint16_t surfId; }; - struct type_align(4) GfxSceneDynBrush + struct type_align32(4) GfxSceneDynBrush { BModelDrawInfo info; uint16_t dynEntId; @@ -2265,7 +2265,7 @@ namespace IW3 char pad; }; - typedef tdef_align(4) GfxSceneDynModel GfxSceneDynModel4; + typedef tdef_align32(4) GfxSceneDynModel GfxSceneDynModel4; struct GfxWorld { diff --git a/src/Common/Game/IW4/IW4_Assets.h b/src/Common/Game/IW4/IW4_Assets.h index 2eda44b9..0b8c44c0 100644 --- a/src/Common/Game/IW4/IW4_Assets.h +++ b/src/Common/Game/IW4/IW4_Assets.h @@ -155,10 +155,10 @@ namespace IW4 void* data; }; - typedef tdef_align(16) char raw_byte16; - typedef tdef_align(16) float raw_float16; + typedef tdef_align32(16) char raw_byte16; + typedef tdef_align32(16) float raw_float16; typedef unsigned int raw_uint; - typedef tdef_align(128) unsigned int raw_uint128; + typedef tdef_align32(128) unsigned int raw_uint128; typedef unsigned char cbrushedge_t; typedef unsigned short r_index_t; typedef float vec2_t[2]; @@ -289,7 +289,7 @@ namespace IW4 }; typedef unsigned char ByteVec[3]; - typedef tdef_align(4) unsigned short UShortVec[3]; + typedef tdef_align32(4) unsigned short UShortVec[3]; union XAnimDynamicFrames { @@ -303,7 +303,7 @@ namespace IW4 uint16_t _2[1]; }; - struct type_align(4) XAnimPartTransFrames + struct type_align32(4) XAnimPartTransFrames { float mins[3]; float size[3]; @@ -330,9 +330,9 @@ namespace IW4 uint16_t _2[1]; }; - typedef tdef_align(4) short XQuat2[2]; + typedef tdef_align32(4) short XQuat2[2]; - struct type_align(4) XAnimDeltaPartQuatDataFrames2 + struct type_align32(4) XAnimDeltaPartQuatDataFrames2 { XQuat2* frames; XAnimDynamicIndicesQuat2 indices; @@ -356,7 +356,7 @@ namespace IW4 uint16_t _2[1]; }; - typedef tdef_align(4) short XQuat[4]; + typedef tdef_align32(4) short XQuat[4]; struct XAnimDeltaPartQuatDataFrames { @@ -442,7 +442,7 @@ namespace IW4 char array[4]; }; - struct type_align(16) GfxPackedVertex + struct type_align32(16) GfxPackedVertex { float xyz[3]; float binormalSign; @@ -458,7 +458,7 @@ namespace IW4 uint16_t maxs[3]; }; - struct type_align(16) XSurfaceCollisionNode + struct type_align32(16) XSurfaceCollisionNode { XSurfaceCollisionAabb aabb; uint16_t childBeginIndex; @@ -489,7 +489,7 @@ namespace IW4 XSurfaceCollisionTree* collisionTree; }; - typedef tdef_align(16) uint16_t r_index16_t; + typedef tdef_align32(16) uint16_t r_index16_t; struct XSurface { @@ -673,7 +673,7 @@ namespace IW4 MaterialTextureDefInfo u; }; - struct type_align(16) MaterialConstantDef + struct type_align32(16) MaterialConstantDef { unsigned int nameHash; char name[12]; @@ -843,7 +843,7 @@ namespace IW4 unsigned int toolFlags; }; - struct gcc_align(8) GfxDrawSurfFields + struct gcc_align32(8) GfxDrawSurfFields { uint64_t objectId : 16; uint64_t reflectionProbeIndex : 8; @@ -860,8 +860,8 @@ namespace IW4 union GfxDrawSurf { - gcc_align(8) GfxDrawSurfFields fields; - gcc_align(8) uint64_t packed; + gcc_align32(8) GfxDrawSurfFields fields; + gcc_align32(8) uint64_t packed; }; // The sort key is translated to a numeric value inside the material templates @@ -993,7 +993,7 @@ namespace IW4 GfxStateBits* stateBitsTable; }; - struct type_align(4) GfxImageLoadDef + struct type_align32(4) GfxImageLoadDef { char levelCount; char pad[3]; @@ -2824,7 +2824,7 @@ namespace IW4 int partitionIndex; }; - struct type_align(16) CollisionAabbTree + struct type_align32(16) CollisionAabbTree { float midPoint[3]; uint16_t materialIndex; @@ -2918,8 +2918,8 @@ namespace IW4 float linkMaxs[2]; }; - typedef tdef_align(128) cbrush_t cbrush_array_t; - typedef tdef_align(128) Bounds BoundsArray; + typedef tdef_align32(128) cbrush_t cbrush_array_t; + typedef tdef_align32(128) Bounds BoundsArray; struct clipMap_t { @@ -3116,7 +3116,7 @@ namespace IW4 pathnode_transient_t transient; }; - struct type_align(16) pathbasenode_t + struct type_align32(16) pathbasenode_t { float vOrigin[3]; unsigned int type; @@ -3313,7 +3313,7 @@ namespace IW4 char endVertIndex; }; - union type_align(4) FxGlassGeometryData + union type_align32(4) FxGlassGeometryData { FxGlassVertex vert; FxGlassHoleHeader hole; @@ -3505,14 +3505,14 @@ namespace IW4 r_index_t* indices; }; - struct type_align(4) GfxLightGridEntry + struct type_align32(4) GfxLightGridEntry { uint16_t colorsIndex; char primaryLightIndex; char needsTrace; }; - struct type_align(4) GfxLightGridColors + struct type_align32(4) GfxLightGridColors { char rgb[56][3]; }; @@ -3539,7 +3539,7 @@ namespace IW4 Bounds bounds; }; - struct type_align(4) GfxBrushModel + struct type_align32(4) GfxBrushModel { GfxBrushModelWritable writable; Bounds bounds; @@ -3599,7 +3599,7 @@ namespace IW4 uint16_t surfId; }; - struct type_align(4) GfxSceneDynBrush + struct type_align32(4) GfxSceneDynBrush { BModelDrawInfo info; uint16_t dynEntId; @@ -3744,8 +3744,8 @@ namespace IW4 int exponent; }; - typedef tdef_align(128) GfxCellTree GfxCellTree128; - typedef tdef_align(4) GfxSceneDynModel GfxSceneDynModel4; + typedef tdef_align32(128) GfxCellTree GfxCellTree128; + typedef tdef_align32(4) GfxSceneDynModel GfxSceneDynModel4; struct GfxWorld { diff --git a/src/Common/Game/IW5/IW5_Assets.h b/src/Common/Game/IW5/IW5_Assets.h index c506f3f2..1e52e7af 100644 --- a/src/Common/Game/IW5/IW5_Assets.h +++ b/src/Common/Game/IW5/IW5_Assets.h @@ -221,9 +221,9 @@ namespace IW5 }; }; - typedef tdef_align(16) char raw_byte16; - typedef tdef_align(16) float raw_float16; - typedef tdef_align(128) unsigned int raw_uint128; + typedef tdef_align32(16) char raw_byte16; + typedef tdef_align32(16) float raw_float16; + typedef tdef_align32(128) unsigned int raw_uint128; typedef unsigned char raw_byte; typedef unsigned int raw_uint; typedef unsigned short r_index_t; @@ -338,7 +338,7 @@ namespace IW5 }; typedef unsigned char ByteVec[3]; - typedef tdef_align(4) unsigned short UShortVec[3]; + typedef tdef_align32(4) unsigned short UShortVec[3]; union XAnimDynamicFrames { @@ -352,7 +352,7 @@ namespace IW5 uint16_t _2[1]; }; - struct type_align(4) XAnimPartTransFrames + struct type_align32(4) XAnimPartTransFrames { float mins[3]; float size[3]; @@ -379,9 +379,9 @@ namespace IW5 uint16_t _2[1]; }; - typedef tdef_align(4) short XQuat2[2]; + typedef tdef_align32(4) short XQuat2[2]; - struct type_align(4) XAnimDeltaPartQuatDataFrames2 + struct type_align32(4) XAnimDeltaPartQuatDataFrames2 { XQuat2* frames; XAnimDynamicIndicesQuat2 indices; @@ -405,7 +405,7 @@ namespace IW5 uint16_t _2[1]; }; - typedef tdef_align(4) short XQuat[4]; + typedef tdef_align32(4) short XQuat[4]; struct XAnimDeltaPartQuatDataFrames { @@ -491,7 +491,7 @@ namespace IW5 unsigned char array[4]; }; - struct type_align(16) GfxPackedVertex + struct type_align32(16) GfxPackedVertex { vec3_t xyz; float binormalSign; @@ -507,7 +507,7 @@ namespace IW5 unsigned short maxs[3]; }; - struct type_align(16) XSurfaceCollisionNode + struct type_align32(16) XSurfaceCollisionNode { XSurfaceCollisionAabb aabb; unsigned short childBeginIndex; @@ -543,7 +543,7 @@ namespace IW5 uint16_t i[3]; }; - typedef tdef_align(16) XSurfaceTri XSurfaceTri16; + typedef tdef_align32(16) XSurfaceTri XSurfaceTri16; struct XSurface { @@ -653,7 +653,7 @@ namespace IW5 float quantization; }; - struct gcc_align(8) GfxDrawSurfFields + struct gcc_align32(8) GfxDrawSurfFields { uint64_t unused : 1; uint64_t primarySortKey : 6; @@ -671,8 +671,8 @@ namespace IW5 union GfxDrawSurf { - gcc_align(8) GfxDrawSurfFields fields; - gcc_align(8) uint64_t packed; + gcc_align32(8) GfxDrawSurfFields fields; + gcc_align32(8) uint64_t packed; }; enum MaterialGameFlags @@ -822,7 +822,7 @@ namespace IW5 MaterialTextureDefInfo u; }; - struct type_align(16) MaterialConstantDef + struct type_align32(16) MaterialConstantDef { unsigned int nameHash; char name[12]; @@ -1127,7 +1127,7 @@ namespace IW5 MaterialTechnique* techniques[54]; }; - struct type_align(4) GfxImageLoadDef + struct type_align32(4) GfxImageLoadDef { char levelCount; char pad[3]; @@ -1339,8 +1339,8 @@ namespace IW5 unsigned char edgeCount[2][3]; }; - typedef tdef_align(128) cbrush_t cbrush_array_t; - typedef tdef_align(128) Bounds BoundsArray; + typedef tdef_align32(128) cbrush_t cbrush_array_t; + typedef tdef_align32(128) Bounds BoundsArray; struct ClipInfo { @@ -1410,7 +1410,7 @@ namespace IW5 int partitionIndex; }; - struct type_align(16) CollisionAabbTree + struct type_align32(16) CollisionAabbTree { float midPoint[3]; unsigned short materialIndex; @@ -1761,7 +1761,7 @@ namespace IW5 pathnode_transient_t transient; }; - struct type_align(16) pathbasenode_t + struct type_align32(16) pathbasenode_t { float vOrigin[3]; unsigned int type; @@ -1948,7 +1948,7 @@ namespace IW5 unsigned char endVertIndex; }; - union type_align(4) FxGlassGeometryData + union type_align32(4) FxGlassGeometryData { FxGlassVertex vert; FxGlassHoleHeader hole; @@ -2155,14 +2155,14 @@ namespace IW5 r_index_t* indices; }; - struct type_align(4) GfxLightGridEntry + struct type_align32(4) GfxLightGridEntry { unsigned short colorsIndex; unsigned char primaryLightIndex; unsigned char needsTrace; }; - struct type_align(4) GfxLightGridColors + struct type_align32(4) GfxLightGridColors { unsigned char rgb[56][3]; }; @@ -2190,7 +2190,7 @@ namespace IW5 Bounds bounds; }; - struct type_align(4) GfxBrushModel + struct type_align32(4) GfxBrushModel { GfxBrushModelWritable writable; Bounds bounds; @@ -2250,7 +2250,7 @@ namespace IW5 unsigned short surfId; }; - struct type_align(4) GfxSceneDynBrush + struct type_align32(4) GfxSceneDynBrush { BModelDrawInfo info; unsigned short dynEntId; @@ -2396,7 +2396,7 @@ namespace IW5 int exponent; }; - typedef tdef_align(128) GfxCellTree GfxCellTree128; + typedef tdef_align32(128) GfxCellTree GfxCellTree128; struct GfxWorld { @@ -3446,7 +3446,7 @@ namespace IW5 SndAliasCustom projIgnitionSound; }; - typedef tdef_align(4) AttSight AttSight4; + typedef tdef_align32(4) AttSight AttSight4; struct WeaponAttachment { diff --git a/src/Common/Game/T5/T5_Assets.h b/src/Common/Game/T5/T5_Assets.h index 03235510..95da5a75 100644 --- a/src/Common/Game/T5/T5_Assets.h +++ b/src/Common/Game/T5/T5_Assets.h @@ -193,20 +193,20 @@ namespace T5 void* data; }; - typedef tdef_align(16) char char16; - typedef tdef_align(32) char byte32; - typedef tdef_align(128) char byte128; + typedef tdef_align32(16) char char16; + typedef tdef_align32(32) char byte32; + typedef tdef_align32(128) char byte128; - typedef tdef_align(4) char char_align4; - typedef tdef_align(128) char char_align128; + typedef tdef_align32(4) char char_align4; + typedef tdef_align32(128) char char_align128; - typedef tdef_align(16) char raw_byte16; - typedef tdef_align(128) char raw_byte128; + typedef tdef_align32(16) char raw_byte16; + typedef tdef_align32(128) char raw_byte128; - typedef tdef_align(128) float float_align128; + typedef tdef_align32(128) float float_align128; typedef char cbrushedge_t; - typedef tdef_align(128) unsigned int raw_uint128; + typedef tdef_align32(128) unsigned int raw_uint128; typedef uint16_t ScriptString; @@ -350,7 +350,7 @@ namespace T5 }; typedef unsigned char ByteVec[3]; - typedef tdef_align(4) unsigned short UShortVec[3]; + typedef tdef_align32(4) unsigned short UShortVec[3]; union XAnimDynamicFrames { @@ -385,7 +385,7 @@ namespace T5 XAnimPartTransData u; }; - typedef tdef_align(4) short XQuat[2]; + typedef tdef_align32(4) short XQuat[2]; union XAnimDynamicIndicesQuat { @@ -490,7 +490,7 @@ namespace T5 char array[4]; }; - struct type_align(16) GfxPackedVertex + struct type_align32(16) GfxPackedVertex { vec3_t xyz; float binormalSign; @@ -511,7 +511,7 @@ namespace T5 uint16_t maxs[3]; }; - struct type_align(16) XSurfaceCollisionNode + struct type_align32(16) XSurfaceCollisionNode { XSurfaceCollisionAabb aabb; uint16_t childBeginIndex; @@ -542,7 +542,7 @@ namespace T5 uint16_t i[3]; }; - typedef tdef_align(16) XSurfaceTri XSurfaceTri16; + typedef tdef_align32(16) XSurfaceTri XSurfaceTri16; struct XSurface { @@ -627,7 +627,7 @@ namespace T5 int sflags; }; - struct type_align(16) BrushWrapper + struct type_align32(16) BrushWrapper { vec3_t mins; int contents; @@ -650,7 +650,7 @@ namespace T5 vec3_t halfLengths; }; - typedef tdef_align(16) PhysGeomInfo PhysGeomInfo16; + typedef tdef_align32(16) PhysGeomInfo PhysGeomInfo16; struct PhysGeomList { @@ -713,7 +713,7 @@ namespace T5 PhysConstraints* physConstraints; }; - struct gcc_align(8) GfxDrawSurfFields + struct gcc_align32(8) GfxDrawSurfFields { uint64_t objectId : 16; uint64_t fade : 4; @@ -732,8 +732,8 @@ namespace T5 union GfxDrawSurf { - gcc_align(8) GfxDrawSurfFields fields; - gcc_align(8) uint64_t packed; + gcc_align32(8) GfxDrawSurfFields fields; + gcc_align32(8) uint64_t packed; }; struct MaterialInfo @@ -796,7 +796,7 @@ namespace T5 MaterialTextureDefInfo u; }; - struct type_align(16) MaterialConstantDef + struct type_align32(16) MaterialConstantDef { unsigned int nameHash; char name[12]; @@ -1138,7 +1138,7 @@ namespace T5 SND_ASSET_FLAG_PAD_LOOP_BUFFER = 0x2, }; - typedef tdef_align(2048) char snd_align_char; + typedef tdef_align32(2048) char snd_align_char; struct snd_asset { @@ -1164,7 +1164,7 @@ namespace T5 snd_asset sound; }; - typedef tdef_align(2048) char char_align_2048; + typedef tdef_align32(2048) char char_align_2048; struct PrimedSound { @@ -1254,7 +1254,7 @@ namespace T5 int sequence; }; - struct type_align(4) SndIndexEntry + struct type_align32(4) SndIndexEntry { uint16_t value; uint16_t next; @@ -1409,7 +1409,7 @@ namespace T5 int partitionIndex; }; - struct type_align(16) CollisionAabbTree + struct type_align32(16) CollisionAabbTree { float origin[3]; uint16_t materialIndex; @@ -1426,7 +1426,7 @@ namespace T5 cLeaf_s leaf; }; - struct type_align(16) cbrush_t + struct type_align32(16) cbrush_t { float mins[3]; int contents; @@ -1687,7 +1687,7 @@ namespace T5 int maxy; }; - struct type_align(4) ComWaterCell + struct type_align32(4) ComWaterCell { int16_t waterheight; char flooroffset; @@ -1826,7 +1826,7 @@ namespace T5 pathnode_transient_t transient; }; - struct type_align(16) pathbasenode_t + struct type_align32(16) pathbasenode_t { float vOrigin[3]; unsigned int type; @@ -1926,7 +1926,7 @@ namespace T5 GfxWorldSunColor sunSettings[1]; }; - struct type_align(16) float44 + struct type_align32(16) float44 { union { @@ -1935,7 +1935,7 @@ namespace T5 }; }; - struct type_align(16) GfxLight + struct type_align32(16) GfxLight { char type; char canUseShadowMap; @@ -2130,19 +2130,19 @@ namespace T5 uint16_t* indices; }; - struct type_align(4) GfxLightGridEntry + struct type_align32(4) GfxLightGridEntry { uint16_t colorsIndex; char primaryLightIndex; char needsTrace; }; - struct type_align(4) GfxCompressedLightGridColors + struct type_align32(4) GfxCompressedLightGridColors { char rgb[56][3]; }; - typedef tdef_align(4) char aligned_byte_pointer; + typedef tdef_align32(4) char aligned_byte_pointer; struct GfxLightGrid { @@ -2220,14 +2220,14 @@ namespace T5 uint16_t dynEntId; }; - typedef tdef_align(4) GfxSceneDynModel GfxSceneDynModel4; + typedef tdef_align32(4) GfxSceneDynModel GfxSceneDynModel4; struct BModelDrawInfo { uint16_t surfId; }; - struct type_align(4) GfxSceneDynBrush + struct type_align32(4) GfxSceneDynBrush { BModelDrawInfo info; uint16_t dynEntId; @@ -2283,7 +2283,7 @@ namespace T5 int stream2ByteOffset; }; - struct type_align(16) GfxSurface + struct type_align32(16) GfxSurface { srfTriangles_t tris; Material* material; @@ -2935,7 +2935,7 @@ namespace T5 ITEM_TYPE_MENUMODEL = 0x27 }; - struct type_align(8) itemDef_s + struct type_align32(8) itemDef_s { windowDef_t window; int type; @@ -2949,15 +2949,15 @@ namespace T5 menuDef_t* parent; rectData_s* rectExpData; ExpressionStatement visibleExp; - gcc_align(8) uint64_t showBits; - gcc_align(8) uint64_t hideBits; + gcc_align32(8) uint64_t showBits; + gcc_align32(8) uint64_t hideBits; ExpressionStatement forecolorAExp; int ui3dWindowId; GenericEventHandler* onEvent; UIAnimInfo* animInfo; }; - struct type_align(8) menuDef_t + struct type_align32(8) menuDef_t { windowDef_t window; const char* font; @@ -2984,8 +2984,8 @@ namespace T5 GenericEventHandler* onEvent; ItemKeyHandler* onKey; ExpressionStatement visibleExp; - gcc_align(8) uint64_t showBits; - gcc_align(8) uint64_t hideBits; + gcc_align32(8) uint64_t showBits; + gcc_align32(8) uint64_t hideBits; const char* allowedBinding; const char* soundName; int imageTrack; diff --git a/src/Common/Game/T6/T6_Assets.h b/src/Common/Game/T6/T6_Assets.h index 628ce514..c61a3885 100644 --- a/src/Common/Game/T6/T6_Assets.h +++ b/src/Common/Game/T6/T6_Assets.h @@ -10,17 +10,17 @@ namespace T6 { #endif - typedef tdef_align(16) char char16; - typedef tdef_align(32) char byte32; - typedef tdef_align(128) char byte128; + typedef tdef_align32(16) char char16; + typedef tdef_align32(32) char byte32; + typedef tdef_align32(128) char byte128; - typedef tdef_align(4) char char_align4; - typedef tdef_align(128) char char_align128; + typedef tdef_align32(4) char char_align4; + typedef tdef_align32(128) char char_align128; - typedef tdef_align(16) char raw_byte16; - typedef tdef_align(128) char raw_byte128; + typedef tdef_align32(16) char raw_byte16; + typedef tdef_align32(128) char raw_byte128; - typedef tdef_align(128) float float_align128; + typedef tdef_align32(128) float float_align128; typedef uint16_t ScriptString; @@ -643,7 +643,7 @@ namespace T6 float lightingOriginRange; }; - struct gcc_align(8) GfxDrawSurfFields + struct gcc_align32(8) GfxDrawSurfFields { uint64_t objectId : 16; uint64_t customIndex : 9; @@ -658,8 +658,8 @@ namespace T6 union GfxDrawSurf { - gcc_align(8) GfxDrawSurfFields fields; - gcc_align(8) uint64_t packed; + gcc_align32(8) GfxDrawSurfFields fields; + gcc_align32(8) uint64_t packed; }; // The sort key is translated to a numeric value inside the material templates @@ -702,7 +702,7 @@ namespace T6 MTL_GAMEFLAG_1000 = 0x1000, }; - struct type_align(8) MaterialInfo + struct type_align32(8) MaterialInfo { const char* name; unsigned int gameFlags; @@ -735,7 +735,7 @@ namespace T6 CAMERA_REGION_NONE = CAMERA_REGION_COUNT, }; - typedef tdef_align(8) GfxStateBits GfxStateBitsTable; + typedef tdef_align32(8) GfxStateBits GfxStateBitsTable; struct Material { @@ -960,9 +960,9 @@ namespace T6 unsigned int entryCount; unsigned int dependencyCount; unsigned int pad32; - gcc_align(8) int64_t fileSize; - gcc_align(8) int64_t entryOffset; - gcc_align(8) int64_t checksumOffset; + gcc_align32(8) int64_t fileSize; + gcc_align32(8) int64_t entryOffset; + gcc_align32(8) int64_t checksumOffset; char checksumChecksum[16]; char dependencies[512]; char padding[1464]; @@ -970,7 +970,7 @@ namespace T6 #pragma pack(push, 1) - struct type_align(2) SndRuntimeAssetBank + struct type_align32(2) SndRuntimeAssetBank { const char* zone; const char* language; @@ -985,7 +985,7 @@ namespace T6 #pragma pack(pop) - typedef tdef_align(2048) char SndChar2048; + typedef tdef_align32(2048) char SndChar2048; struct SndLoadedAssets { @@ -1041,8 +1041,8 @@ namespace T6 }; typedef unsigned short LeafBrush; - typedef tdef_align(128) cbrush_t cbrush_array_t; - typedef tdef_align(128) Bounds BoundsArray; + typedef tdef_align32(128) cbrush_t cbrush_array_t; + typedef tdef_align32(128) Bounds BoundsArray; struct ClipInfo { @@ -1066,7 +1066,7 @@ namespace T6 int* brushContents; }; - struct type_align(4) cLeaf_s + struct type_align32(4) cLeaf_s { uint16_t firstCollAabbIndex; uint16_t collAabbCount; @@ -1273,8 +1273,8 @@ namespace T6 void /*ID3D11Buffer*/* indexBuffer; }; - typedef tdef_align(4) char aligned_byte_pointer; - typedef tdef_align(4) GfxCompressedLightGridCoeffs GfxCompressedLightGridCoeffs_align4; + typedef tdef_align32(4) char aligned_byte_pointer; + typedef tdef_align32(4) GfxCompressedLightGridCoeffs GfxCompressedLightGridCoeffs_align4; struct GfxLightGrid { @@ -1323,7 +1323,7 @@ namespace T6 vec3_t sunFxPosition; }; - typedef tdef_align(4) GfxDrawSurf GfxDrawSurf_align4; + typedef tdef_align32(4) GfxDrawSurf GfxDrawSurf_align4; struct GfxWorldDpvsStatic { @@ -1449,7 +1449,7 @@ namespace T6 int lightingQuality; }; - struct type_align(4) GfxLightImage + struct type_align32(4) GfxLightImage { GfxImage* image; char samplerState; @@ -1535,7 +1535,7 @@ namespace T6 expressionRpn* rpn; }; - struct type_align(8) menuDef_t + struct type_align32(8) menuDef_t { windowDef_t window; const char* font; @@ -1562,8 +1562,8 @@ namespace T6 GenericEventHandler* onEvent; ItemKeyHandler* onKey; ExpressionStatement visibleExp; - gcc_align(8) uint64_t showBits; - gcc_align(8) uint64_t hideBits; + gcc_align32(8) uint64_t showBits; + gcc_align32(8) uint64_t hideBits; const char* allowedBinding; const char* soundName; int imageTrack; @@ -2753,9 +2753,9 @@ namespace T6 uint16_t i[3]; }; - typedef tdef_align(16) XSurfaceTri XSurfaceTri16; + typedef tdef_align32(16) XSurfaceTri XSurfaceTri16; - struct type_align(16) XSurface + struct type_align32(16) XSurface { char tileMode; unsigned char vertListCount; @@ -2783,7 +2783,7 @@ namespace T6 int surfFlags; }; - struct type_align(4) XBoneInfo + struct type_align32(4) XBoneInfo { vec3_t bounds[2]; vec3_t offset; @@ -2883,7 +2883,7 @@ namespace T6 GfxImage* image; }; - struct type_align(16) MaterialConstantDef + struct type_align32(16) MaterialConstantDef { unsigned int nameHash; char name[12]; @@ -3058,7 +3058,7 @@ namespace T6 { };*/ - struct type_align(4) GfxImageLoadDef + struct type_align32(4) GfxImageLoadDef { char levelCount; char flags; @@ -3076,7 +3076,7 @@ namespace T6 int sequence; }; - struct type_align(4) SndIndexEntry + struct type_align32(4) SndIndexEntry { uint16_t value; uint16_t next; @@ -3104,7 +3104,7 @@ namespace T6 float returnHighpass; }; - typedef tdef_align(16) float SndFloatAlign16; + typedef tdef_align32(16) float SndFloatAlign16; struct SndDuck { @@ -3206,7 +3206,7 @@ namespace T6 cLeafBrushNodeData_t data; }; - struct type_align(16) cbrush_t + struct type_align32(16) cbrush_t { vec3_t mins; int contents; @@ -3261,7 +3261,7 @@ namespace T6 int partitionIndex; }; - struct type_align(16) CollisionAabbTree + struct type_align32(16) CollisionAabbTree { vec3_t origin; uint16_t materialIndex; @@ -3352,7 +3352,7 @@ namespace T6 ROPE_CENTITY_CONSTRAINT = 0x3, }; - struct type_align(4) constraint_t + struct type_align32(4) constraint_t { vec3_t p; rope_constraint_e type; @@ -3374,7 +3374,7 @@ namespace T6 unsigned int frame_index; }; - struct type_align(4) rope_t + struct type_align32(4) rope_t { par_t m_particles[25]; constraint_t m_constraints[30]; @@ -3489,7 +3489,7 @@ namespace T6 uint16_t infoIndex; }; - struct type_align(4) pathnode_dynamic_t + struct type_align32(4) pathnode_dynamic_t { SentientHandle pOwner; int iFreeTime; @@ -3526,7 +3526,7 @@ namespace T6 pathnode_transient_t transient; }; - struct type_align(16) pathbasenode_t + struct type_align32(16) pathbasenode_t { vec3_t vOrigin; unsigned int type; @@ -3573,7 +3573,7 @@ namespace T6 float halfSize; }; - struct type_align(16) GfxStreamingAabbTree + struct type_align32(16) GfxStreamingAabbTree { vec4_t mins; vec4_t maxs; @@ -3586,7 +3586,7 @@ namespace T6 uint16_t surfaceCount; }; - struct type_align(16) float44 + struct type_align32(16) float44 { union { @@ -3595,7 +3595,7 @@ namespace T6 }; }; - struct type_align(16) GfxLight + struct type_align32(16) GfxLight { char type; char canUseShadowMap; @@ -3734,14 +3734,14 @@ namespace T6 { };*/ - struct type_align(4) GfxLightGridEntry + struct type_align32(4) GfxLightGridEntry { uint16_t colorsIndex; char primaryLightIndex; char visibility; }; - struct type_align(4) GfxCompressedLightGridColors + struct type_align32(4) GfxCompressedLightGridColors { char rgb[56][3]; }; @@ -3769,7 +3769,7 @@ namespace T6 float padding2; }; - struct type_align(16) GfxBrushModel + struct type_align32(16) GfxBrushModel { GfxBrushModelWritable writable; vec3_t bounds[2]; @@ -3808,14 +3808,14 @@ namespace T6 uint16_t surfId; }; - struct type_align(4) GfxSceneDynBrush + struct type_align32(4) GfxSceneDynBrush { BModelDrawInfo info; uint16_t dynEntId; }; // Usually __m128, but that is not portable - union gcc_align(8) custom_m128 + union gcc_align32(8) custom_m128 { float m128_f32[4]; uint64_t m128_u64[2]; @@ -3836,7 +3836,7 @@ namespace T6 custom_m128 w; }; - struct type_align(16) SSkinInstance + struct type_align32(16) SSkinInstance { union { @@ -3888,7 +3888,7 @@ namespace T6 int baseIndex; }; - struct type_align(16) GfxSurface + struct type_align32(16) GfxSurface { srfTriangles_t tris; Material* material; @@ -3913,7 +3913,7 @@ namespace T6 uint16_t V2[4]; }; - struct type_align(4) GfxStaticModelLmapVertexInfo + struct type_align32(4) GfxStaticModelLmapVertexInfo { unsigned int* lmapVertexColors; void /*ID3D11Buffer*/* lmapVertexColorsVB; @@ -4113,7 +4113,7 @@ namespace T6 void* data; }; - struct type_align(8) itemDef_s + struct type_align32(8) itemDef_s { windowDef_t window; int type; @@ -5587,7 +5587,7 @@ namespace T6 LOCAL_CLIENT_COUNT = 0x1, }; - struct type_align(4) DevGraph + struct type_align32(4) DevGraph { vec2_t* knots; int* knotCount; @@ -5609,7 +5609,7 @@ namespace T6 }; typedef char ByteVec[3]; - typedef tdef_align(4) uint16_t UShortVec[3]; + typedef tdef_align32(4) uint16_t UShortVec[3]; union XAnimDynamicFrames { @@ -5623,7 +5623,7 @@ namespace T6 uint16_t _2[1]; }; - struct type_align(4) XAnimPartTransFrames + struct type_align32(4) XAnimPartTransFrames { vec3_t mins; vec3_t size; @@ -5650,9 +5650,9 @@ namespace T6 uint16_t _2[1]; }; - typedef tdef_align(4) int16_t XQuat2[2]; + typedef tdef_align32(4) int16_t XQuat2[2]; - struct type_align(4) XAnimDeltaPartQuatDataFrames2 + struct type_align32(4) XAnimDeltaPartQuatDataFrames2 { XQuat2* frames; XAnimDynamicIndicesDeltaQuat2 indices; @@ -5676,9 +5676,9 @@ namespace T6 uint16_t _2[1]; }; - typedef tdef_align(4) int16_t XQuat[4]; + typedef tdef_align32(4) int16_t XQuat[4]; - struct type_align(4) XAnimDeltaPartQuatDataFrames + struct type_align32(4) XAnimDeltaPartQuatDataFrames { XQuat* frames; XAnimDynamicIndicesDeltaQuat indices; @@ -5712,7 +5712,7 @@ namespace T6 unsigned int packed; }; - struct type_align(16) GfxPackedVertex + struct type_align32(16) GfxPackedVertex { vec3_t xyz; float binormalSign; @@ -5738,7 +5738,7 @@ namespace T6 vec4_t tvec; }; - typedef tdef_align(16) PhysGeomInfo PhysGeomInfo16; + typedef tdef_align32(16) PhysGeomInfo PhysGeomInfo16; struct PhysGeomList { @@ -6295,7 +6295,7 @@ namespace T6 static_assert(sizeof(SndAliasFlags) == 8); #endif - struct type_align(4) pathlink_s + struct type_align32(4) pathlink_s { float fDist; uint16_t nodeNum; @@ -6404,7 +6404,7 @@ namespace T6 unsigned int v; }; - struct type_align(4) SSkinVert + struct type_align32(4) SSkinVert { half4 pos_bone; PackedUnitVec normal; @@ -6495,7 +6495,7 @@ namespace T6 } vector; }; - struct type_align(8) dvar_t + struct type_align32(8) dvar_t { const char* name; const char* description; @@ -6994,7 +6994,7 @@ namespace T6 uint16_t maxs[3]; }; - struct type_align(16) XSurfaceCollisionNode + struct type_align32(16) XSurfaceCollisionNode { XSurfaceCollisionAabb aabb; uint16_t childBeginIndex; @@ -7006,7 +7006,7 @@ namespace T6 uint16_t triangleBeginIndex; }; - struct type_align(16) BrushWrapper + struct type_align32(16) BrushWrapper { vec3_t mins; int contents; diff --git a/src/Common/Utils/TypeAlignment.h b/src/Common/Utils/TypeAlignment.h index e3eabcd4..4e2c2bd4 100644 --- a/src/Common/Utils/TypeAlignment.h +++ b/src/Common/Utils/TypeAlignment.h @@ -7,9 +7,6 @@ #ifdef tdef_align #undef tdef_align #endif -#ifdef memb_align -#undef memb_align -#endif #ifdef gcc_align #undef gcc_align #endif @@ -17,25 +14,44 @@ #ifdef __zonecodegenerator #define type_align(x) alignas(x) #define tdef_align(x) alignas(x) -#define memb_align(x) alignas(x) #define gcc_align(x) #else #ifdef __ida #define type_align(x) __declspec(align(x)) #define tdef_align(x) __declspec(align(x)) -#define memb_align(x) __declspec(align(x)) #define gcc_align(x) #else #ifdef _MSVC_LANG -#define type_align(x) /* __declspec(align(x)) */ -#define tdef_align(x) /* __declspec(align(x)) */ -#define memb_align(x) /* __declspec(align(x)) */ +#define type_align(x) __declspec(align(x)) +#define tdef_align(x) __declspec(align(x)) #define gcc_align(x) #else #define type_align(x) __attribute__((__aligned__(x))) #define tdef_align(x) -#define memb_align(x) __attribute__((__aligned__(x))) #define gcc_align(x) __attribute__((__aligned__(x))) #endif #endif #endif + +#if defined(__zonecodegenerator) || defined(__ida) +#define type_align32(x) type_align(x) +#define tdef_align32(x) tdef_align(x) +#define gcc_align32(x) gcc_align(x) +#define type_align64(x) type_align(x) +#define tdef_align64(x) tdef_align(x) +#define gcc_align64(x) gcc_align(x) +#elif defined(ARCH_x86) +#define type_align32(x) type_align(x) +#define tdef_align32(x) tdef_align(x) +#define gcc_align32(x) gcc_align(x) +#define type_align64(x) +#define tdef_align64(x) +#define gcc_align64(x) +#elif defined(ARCH_x64) +#define type_align32(x) +#define tdef_align32(x) +#define gcc_align32(x) +#define type_align64(x) type_align(x) +#define tdef_align64(x) tdef_align(x) +#define gcc_align64(x) gcc_align(x) +#endif From 365b627523f5b213548b27c7512cfce422ddf2e7 Mon Sep 17 00:00:00 2001 From: Jan Date: Sat, 26 Apr 2025 12:38:43 +0100 Subject: [PATCH 08/11] refactor: fix remaining x64 compilation issues --- src/Linker/LinkerPaths.cpp | 4 +- .../IW3/AssetDumpers/AssetDumperXModel.cpp | 45 ++++++------ .../IW4/AssetDumpers/AssetDumperXModel.cpp | 47 ++++++------ .../Game/IW4/Menu/MenuDumperIW4.cpp | 6 +- .../Game/IW5/Menu/MenuDumperIW5.cpp | 6 +- .../XModel/Export/XModelBinWriter.cpp | 4 +- .../XModel/Export/XModelExportWriter.cpp | 4 +- .../XModel/GenericXModelDumper.inc.h | 2 +- src/ObjWriting/XModel/Gltf/GltfBinOutput.cpp | 2 +- src/ObjWriting/XModel/Gltf/GltfWriter.cpp | 72 +++++++++---------- .../XModel/XModelDumper.cpp.template | 2 +- src/Unlinker/Unlinker.cpp | 4 +- src/Unlinker/UnlinkerArgs.cpp | 2 +- src/ZoneLoading/Game/IW4/ContentLoaderIW4.h | 14 ++-- .../Zone/Stream/IZoneInputStream.h | 2 +- .../Processor/OutputProcessorDeflate.cpp | 25 +++---- .../Processor/OutputProcessorDeflate.h | 2 +- .../Writing/Steps/StepWriteZero.cpp | 4 +- .../Zone/Stream/IZoneOutputStream.h | 2 +- .../SearchPath/MockOutputPath.cpp | 2 +- 20 files changed, 128 insertions(+), 123 deletions(-) diff --git a/src/Linker/LinkerPaths.cpp b/src/Linker/LinkerPaths.cpp index 730f71c7..37631e49 100644 --- a/src/Linker/LinkerPaths.cpp +++ b/src/Linker/LinkerPaths.cpp @@ -56,8 +56,8 @@ namespace void CreateFromString(const std::string& templateString) { const auto templateStringLength = templateString.size(); - auto partStart = 0u; - for (auto i = 0u; i < templateStringLength; i++) + auto partStart = 0uz; + for (auto i = 0uz; i < templateStringLength; i++) { if (templateString[i] != '?') continue; diff --git a/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperXModel.cpp b/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperXModel.cpp index 0382088e..e95b1d47 100644 --- a/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperXModel.cpp +++ b/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperXModel.cpp @@ -126,10 +126,10 @@ namespace bone.globalOffset[1] = model->baseMat[boneNum].trans[1]; bone.globalOffset[2] = model->baseMat[boneNum].trans[2]; bone.globalRotation = { - model->baseMat[boneNum].quat[0], - model->baseMat[boneNum].quat[1], - model->baseMat[boneNum].quat[2], - model->baseMat[boneNum].quat[3], + .x = model->baseMat[boneNum].quat[0], + .y = model->baseMat[boneNum].quat[1], + .z = model->baseMat[boneNum].quat[2], + .w = model->baseMat[boneNum].quat[3], }; if (boneNum < model->numRootBones) @@ -137,7 +137,7 @@ namespace bone.localOffset[0] = 0; bone.localOffset[1] = 0; bone.localOffset[2] = 0; - bone.localRotation = {0, 0, 0, 1}; + bone.localRotation = {.x = 0, .y = 0, .z = 0, .w = 1}; } else { @@ -145,10 +145,10 @@ namespace bone.localOffset[1] = model->trans[boneNum - model->numRootBones][1]; bone.localOffset[2] = model->trans[boneNum - model->numRootBones][2]; bone.localRotation = { - QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][0]), - QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][1]), - QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][2]), - QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][3]), + .x = QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][0]), + .y = QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][1]), + .z = QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][2]), + .w = QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][3]), }; } @@ -166,7 +166,7 @@ namespace void AddXModelMaterials(XModelCommon& out, DistinctMapper& materialMapper, const XModel* model) { - for (auto surfaceMaterialNum = 0; surfaceMaterialNum < model->numsurfs; surfaceMaterialNum++) + for (auto surfaceMaterialNum = 0u; surfaceMaterialNum < model->numsurfs; surfaceMaterialNum++) { Material* material = model->materialHandles[surfaceMaterialNum]; if (materialMapper.Add(material)) @@ -271,7 +271,7 @@ namespace const auto surfCount = model->lodInfo[lod].numsurfs; auto& weightCollection = out.m_bone_weight_data; - size_t weightOffset = 0u; + auto weightOffset = 0u; for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) { @@ -285,7 +285,8 @@ namespace const auto& vertList = surface.vertList[vertListIndex]; const auto boneWeightOffset = weightOffset; - weightCollection.weights[weightOffset++] = XModelBoneWeight{static_cast(vertList.boneOffset / sizeof(DObjSkelMat)), 1.0f}; + weightCollection.weights[weightOffset++] = + XModelBoneWeight{.boneIndex = static_cast(vertList.boneOffset / sizeof(DObjSkelMat)), .weight = 1.0f}; for (auto vertListVertexOffset = 0u; vertListVertexOffset < vertList.vertCount; vertListVertexOffset++) { @@ -303,7 +304,7 @@ namespace { const auto boneWeightOffset = weightOffset; const unsigned boneIndex0 = surface.vertInfo.vertsBlend[vertsBlendOffset + 0] / sizeof(DObjSkelMat); - weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex0, 1.0f}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{.boneIndex = boneIndex0, .weight = 1.0f}; vertsBlendOffset += 1; @@ -319,8 +320,8 @@ namespace const auto boneWeight1 = BoneWeight16(surface.vertInfo.vertsBlend[vertsBlendOffset + 2]); const auto boneWeight0 = 1.0f - boneWeight1; - weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex0, boneWeight0}; - weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex1, boneWeight1}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{.boneIndex = boneIndex0, .weight = boneWeight0}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{.boneIndex = boneIndex1, .weight = boneWeight1}; vertsBlendOffset += 3; @@ -338,9 +339,9 @@ namespace const auto boneWeight2 = BoneWeight16(surface.vertInfo.vertsBlend[vertsBlendOffset + 4]); const auto boneWeight0 = 1.0f - boneWeight1 - boneWeight2; - weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex0, boneWeight0}; - weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex1, boneWeight1}; - weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex2, boneWeight2}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{.boneIndex = boneIndex0, .weight = boneWeight0}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{.boneIndex = boneIndex1, .weight = boneWeight1}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{.boneIndex = boneIndex2, .weight = boneWeight2}; vertsBlendOffset += 5; @@ -360,10 +361,10 @@ namespace const auto boneWeight3 = BoneWeight16(surface.vertInfo.vertsBlend[vertsBlendOffset + 6]); const auto boneWeight0 = 1.0f - boneWeight1 - boneWeight2 - boneWeight3; - weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex0, boneWeight0}; - weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex1, boneWeight1}; - weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex2, boneWeight2}; - weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex3, boneWeight3}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{.boneIndex = boneIndex0, .weight = boneWeight0}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{.boneIndex = boneIndex1, .weight = boneWeight1}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{.boneIndex = boneIndex2, .weight = boneWeight2}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{.boneIndex = boneIndex3, .weight = boneWeight3}; vertsBlendOffset += 7; diff --git a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperXModel.cpp b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperXModel.cpp index 3b9987e6..efb8dfd3 100644 --- a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperXModel.cpp +++ b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperXModel.cpp @@ -121,10 +121,10 @@ namespace bone.globalOffset[1] = model->baseMat[boneNum].trans[1]; bone.globalOffset[2] = model->baseMat[boneNum].trans[2]; bone.globalRotation = { - model->baseMat[boneNum].quat[0], - model->baseMat[boneNum].quat[1], - model->baseMat[boneNum].quat[2], - model->baseMat[boneNum].quat[3], + .x = model->baseMat[boneNum].quat[0], + .y = model->baseMat[boneNum].quat[1], + .z = model->baseMat[boneNum].quat[2], + .w = model->baseMat[boneNum].quat[3], }; if (boneNum < model->numRootBones) @@ -132,7 +132,7 @@ namespace bone.localOffset[0] = 0; bone.localOffset[1] = 0; bone.localOffset[2] = 0; - bone.localRotation = {0, 0, 0, 1}; + bone.localRotation = {.x = 0, .y = 0, .z = 0, .w = 1}; } else { @@ -140,10 +140,10 @@ namespace bone.localOffset[1] = model->trans[boneNum - model->numRootBones][1]; bone.localOffset[2] = model->trans[boneNum - model->numRootBones][2]; bone.localRotation = { - QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][0]), - QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][1]), - QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][2]), - QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][3]), + .x = QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][0]), + .y = QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][1]), + .z = QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][2]), + .w = QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][3]), }; } @@ -161,7 +161,7 @@ namespace void AddXModelMaterials(XModelCommon& out, DistinctMapper& materialMapper, const XModel* model) { - for (auto surfaceMaterialNum = 0; surfaceMaterialNum < model->numsurfs; surfaceMaterialNum++) + for (auto surfaceMaterialNum = 0u; surfaceMaterialNum < model->numsurfs; surfaceMaterialNum++) { Material* material = model->materialHandles[surfaceMaterialNum]; if (materialMapper.Add(material)) @@ -254,7 +254,7 @@ namespace void AddXModelVertexBoneWeights(XModelCommon& out, const XModelSurfs* modelSurfs) { auto& weightCollection = out.m_bone_weight_data; - size_t weightOffset = 0u; + auto weightOffset = 0u; for (auto surfIndex = 0u; surfIndex < modelSurfs->numsurfs; surfIndex++) { @@ -268,11 +268,12 @@ namespace const auto& vertList = surface.vertList[vertListIndex]; const auto boneWeightOffset = weightOffset; - weightCollection.weights[weightOffset++] = XModelBoneWeight{static_cast(vertList.boneOffset / sizeof(DObjSkelMat)), 1.0f}; + weightCollection.weights[weightOffset++] = + XModelBoneWeight{.boneIndex = static_cast(vertList.boneOffset / sizeof(DObjSkelMat)), .weight = 1.0f}; for (auto vertListVertexOffset = 0u; vertListVertexOffset < vertList.vertCount; vertListVertexOffset++) { - out.m_vertex_bone_weights.emplace_back(boneWeightOffset, 1); + out.m_vertex_bone_weights.emplace_back(boneWeightOffset, 1u); } handledVertices += vertList.vertCount; } @@ -286,7 +287,7 @@ namespace { const auto boneWeightOffset = weightOffset; const unsigned boneIndex0 = surface.vertInfo.vertsBlend[vertsBlendOffset + 0] / sizeof(DObjSkelMat); - weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex0, 1.0f}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{.boneIndex = boneIndex0, .weight = 1.0f}; vertsBlendOffset += 1; @@ -302,8 +303,8 @@ namespace const auto boneWeight1 = BoneWeight16(surface.vertInfo.vertsBlend[vertsBlendOffset + 2]); const auto boneWeight0 = 1.0f - boneWeight1; - weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex0, boneWeight0}; - weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex1, boneWeight1}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{.boneIndex = boneIndex0, .weight = boneWeight0}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{.boneIndex = boneIndex1, .weight = boneWeight1}; vertsBlendOffset += 3; @@ -321,9 +322,9 @@ namespace const auto boneWeight2 = BoneWeight16(surface.vertInfo.vertsBlend[vertsBlendOffset + 4]); const auto boneWeight0 = 1.0f - boneWeight1 - boneWeight2; - weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex0, boneWeight0}; - weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex1, boneWeight1}; - weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex2, boneWeight2}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{.boneIndex = boneIndex0, .weight = boneWeight0}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{.boneIndex = boneIndex1, .weight = boneWeight1}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{.boneIndex = boneIndex2, .weight = boneWeight2}; vertsBlendOffset += 5; @@ -343,10 +344,10 @@ namespace const auto boneWeight3 = BoneWeight16(surface.vertInfo.vertsBlend[vertsBlendOffset + 6]); const auto boneWeight0 = 1.0f - boneWeight1 - boneWeight2 - boneWeight3; - weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex0, boneWeight0}; - weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex1, boneWeight1}; - weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex2, boneWeight2}; - weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex3, boneWeight3}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{.boneIndex = boneIndex0, .weight = boneWeight0}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{.boneIndex = boneIndex1, .weight = boneWeight1}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{.boneIndex = boneIndex2, .weight = boneWeight2}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{.boneIndex = boneIndex3, .weight = boneWeight3}; vertsBlendOffset += 7; diff --git a/src/ObjWriting/Game/IW4/Menu/MenuDumperIW4.cpp b/src/ObjWriting/Game/IW4/Menu/MenuDumperIW4.cpp index 63da316b..5d65da59 100644 --- a/src/ObjWriting/Game/IW4/Menu/MenuDumperIW4.cpp +++ b/src/ObjWriting/Game/IW4/Menu/MenuDumperIW4.cpp @@ -271,13 +271,13 @@ void MenuDumper::WriteStatementSkipInitialUnnecessaryParenthesis(const Statement void MenuDumper::WriteStatementNaive(const Statement_s* statement) const { - const auto entryCount = static_cast(statement->numEntries); + const auto entryCount = static_cast(statement->numEntries); const auto missingClosingParenthesis = statement->numEntries > 0 && statement->entries[0].type == EET_OPERATOR && statement->entries[0].data.op == OP_LEFTPAREN && FindStatementClosingParenthesis(statement, 0) >= static_cast(statement->numEntries); - for (auto i = 0u; i < entryCount; i++) + for (auto i = 0uz; i < entryCount; i++) { const auto& entry = statement->entries[i]; if (entry.type == EET_OPERAND) @@ -314,7 +314,7 @@ void MenuDumper::WriteStatementNaive(const Statement_s* statement) const const auto closingParenPos = FindStatementClosingParenthesis(statement, i); m_stream << "("; - if (closingParenPos - i + 1 >= 1) + if (closingParenPos - i + 1u >= 1u) { const auto& staticDvarEntry = statement->entries[i + 1]; if (staticDvarEntry.type == EET_OPERAND && staticDvarEntry.data.operand.dataType == VAL_INT) diff --git a/src/ObjWriting/Game/IW5/Menu/MenuDumperIW5.cpp b/src/ObjWriting/Game/IW5/Menu/MenuDumperIW5.cpp index 3b36a004..d96e3c0b 100644 --- a/src/ObjWriting/Game/IW5/Menu/MenuDumperIW5.cpp +++ b/src/ObjWriting/Game/IW5/Menu/MenuDumperIW5.cpp @@ -240,7 +240,7 @@ void MenuDumper::WriteStatementEntryRange(const Statement_s* statement, size_t s void MenuDumper::WriteStatementNaive(const Statement_s* statement) const { const auto entryCount = static_cast(statement->numEntries); - for (auto i = 0u; i < entryCount; i++) + for (auto i = 0uz; i < entryCount; i++) { const auto& entry = statement->entries[i]; if (entry.type == EET_OPERAND) @@ -277,9 +277,9 @@ void MenuDumper::WriteStatementNaive(const Statement_s* statement) const const auto closingParenPos = FindStatementClosingParenthesis(statement, i); m_stream << "("; - if (closingParenPos - i + 1 >= 1) + if (closingParenPos - i + 1u >= 1u) { - const auto& staticDvarEntry = statement->entries[i + 1]; + const auto& staticDvarEntry = statement->entries[i + 1u]; if (staticDvarEntry.type == EET_OPERAND && staticDvarEntry.data.operand.dataType == VAL_INT) { if (statement->supportingData && statement->supportingData->staticDvarList.staticDvars && staticDvarEntry.data.operand.internals.intVal >= 0 diff --git a/src/ObjWriting/XModel/Export/XModelBinWriter.cpp b/src/ObjWriting/XModel/Export/XModelBinWriter.cpp index 2387f937..f9370d32 100644 --- a/src/ObjWriting/XModel/Export/XModelBinWriter.cpp +++ b/src/ObjWriting/XModel/Export/XModelBinWriter.cpp @@ -297,12 +297,12 @@ class XModelBinWriter7 final : public XModelBinWriterBase void WriteFaces(const XModelCommon& xmodel) { - auto totalFaceCount = 0u; + auto totalFaceCount = 0uz; for (const auto& object : xmodel.m_objects) totalFaceCount += object.m_faces.size(); XModelBinWriterBase::Write(static_cast(XModelBinHash::FACE_COUNT)); - XModelBinWriterBase::Write(totalFaceCount); + XModelBinWriterBase::Write(static_cast(totalFaceCount)); auto objectIndex = 0u; for (const auto& object : xmodel.m_objects) diff --git a/src/ObjWriting/XModel/Export/XModelExportWriter.cpp b/src/ObjWriting/XModel/Export/XModelExportWriter.cpp index 8cb6419d..45f4a021 100644 --- a/src/ObjWriting/XModel/Export/XModelExportWriter.cpp +++ b/src/ObjWriting/XModel/Export/XModelExportWriter.cpp @@ -122,11 +122,11 @@ class XModelExportWriter6 final : public XModelExportWriterBase void WriteFaces(const XModelCommon& xmodel) const { - auto totalFaceCount = 0u; + auto totalFaceCount = 0uz; for (const auto& object : xmodel.m_objects) totalFaceCount += object.m_faces.size(); - m_stream << "NUMFACES " << totalFaceCount << "\n"; + m_stream << std::format("NUMFACES {}\n", totalFaceCount); auto objectIndex = 0u; for (const auto& object : xmodel.m_objects) diff --git a/src/ObjWriting/XModel/GenericXModelDumper.inc.h b/src/ObjWriting/XModel/GenericXModelDumper.inc.h index 9e44946e..07f4fd88 100644 --- a/src/ObjWriting/XModel/GenericXModelDumper.inc.h +++ b/src/ObjWriting/XModel/GenericXModelDumper.inc.h @@ -343,7 +343,7 @@ namespace GAME_NAMESPACE if (!surfs) return; - size_t weightOffset = 0u; + auto weightOffset = 0u; for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) { diff --git a/src/ObjWriting/XModel/Gltf/GltfBinOutput.cpp b/src/ObjWriting/XModel/Gltf/GltfBinOutput.cpp index 7bce3561..f57356c5 100644 --- a/src/ObjWriting/XModel/Gltf/GltfBinOutput.cpp +++ b/src/ObjWriting/XModel/Gltf/GltfBinOutput.cpp @@ -64,7 +64,7 @@ void BinOutput::EmitJson(const nlohmann::json& json) const void BinOutput::EmitBuffer(const void* buffer, const size_t bufferSize) const { - const auto chunkLength = utils::Align(bufferSize, 4u); + const auto chunkLength = utils::Align(static_cast(bufferSize), 4u); Write(&chunkLength, sizeof(chunkLength)); Write(&CHUNK_MAGIC_BIN, sizeof(CHUNK_MAGIC_BIN)); diff --git a/src/ObjWriting/XModel/Gltf/GltfWriter.cpp b/src/ObjWriting/XModel/Gltf/GltfWriter.cpp index 18eaf323..6ac7dea7 100644 --- a/src/ObjWriting/XModel/Gltf/GltfWriter.cpp +++ b/src/ObjWriting/XModel/Gltf/GltfWriter.cpp @@ -74,7 +74,7 @@ namespace if (!gltf.nodes.has_value()) gltf.nodes.emplace(); - m_first_mesh_node = gltf.nodes->size(); + m_first_mesh_node = static_cast(gltf.nodes->size()); auto meshIndex = 0u; for (const auto& object : xmodel.m_objects) @@ -123,7 +123,7 @@ namespace rootNode.children->push_back(m_first_bone_node); - m_root_node = gltf.nodes->size(); + m_root_node = static_cast(gltf.nodes->size()); gltf.nodes->emplace_back(std::move(rootNode)); } @@ -211,12 +211,12 @@ namespace JsonImage image; image.uri = std::move(uri); - const auto imageIndex = gltf.images->size(); + const auto imageIndex = static_cast(gltf.images->size()); gltf.images->emplace_back(std::move(image)); JsonTexture texture; texture.source = imageIndex; - const auto textureIndex = gltf.textures->size(); + const auto textureIndex = static_cast(gltf.textures->size()); gltf.textures->emplace_back(texture); return textureIndex; @@ -231,7 +231,7 @@ namespace gltf.nodes.emplace(); const auto boneCount = common.m_bones.size(); - m_first_bone_node = gltf.nodes->size(); + m_first_bone_node = static_cast(gltf.nodes->size()); for (auto boneIndex = 0u; boneIndex < boneCount; boneIndex++) { JsonNode boneNode; @@ -319,12 +319,12 @@ namespace JsonBufferView vertexBufferView; vertexBufferView.buffer = 0u; vertexBufferView.byteOffset = bufferOffset; - vertexBufferView.byteStride = sizeof(GltfVertex); - vertexBufferView.byteLength = sizeof(GltfVertex) * xmodel.m_vertices.size(); + vertexBufferView.byteStride = static_cast(sizeof(GltfVertex)); + vertexBufferView.byteLength = static_cast(sizeof(GltfVertex) * xmodel.m_vertices.size()); vertexBufferView.target = JsonBufferViewTarget::ARRAY_BUFFER; bufferOffset += vertexBufferView.byteLength; - m_vertex_buffer_view = gltf.bufferViews->size(); + m_vertex_buffer_view = static_cast(gltf.bufferViews->size()); gltf.bufferViews->emplace_back(vertexBufferView); if (!xmodel.m_bone_weight_data.weights.empty()) @@ -332,40 +332,40 @@ namespace JsonBufferView jointsBufferView; jointsBufferView.buffer = 0u; jointsBufferView.byteOffset = bufferOffset; - jointsBufferView.byteLength = sizeof(uint8_t) * xmodel.m_vertices.size() * 4u; + jointsBufferView.byteLength = static_cast(sizeof(uint8_t) * xmodel.m_vertices.size() * 4u); jointsBufferView.target = JsonBufferViewTarget::ARRAY_BUFFER; bufferOffset += jointsBufferView.byteLength; - m_joints_buffer_view = gltf.bufferViews->size(); + m_joints_buffer_view = static_cast(gltf.bufferViews->size()); gltf.bufferViews->emplace_back(jointsBufferView); JsonBufferView weightsBufferView; weightsBufferView.buffer = 0u; weightsBufferView.byteOffset = bufferOffset; - weightsBufferView.byteLength = sizeof(float) * xmodel.m_vertices.size() * 4u; + weightsBufferView.byteLength = static_cast(sizeof(float) * xmodel.m_vertices.size() * 4u); weightsBufferView.target = JsonBufferViewTarget::ARRAY_BUFFER; bufferOffset += weightsBufferView.byteLength; - m_weights_buffer_view = gltf.bufferViews->size(); + m_weights_buffer_view = static_cast(gltf.bufferViews->size()); gltf.bufferViews->emplace_back(weightsBufferView); JsonBufferView inverseBindMatricesBufferView; inverseBindMatricesBufferView.buffer = 0u; inverseBindMatricesBufferView.byteOffset = bufferOffset; - inverseBindMatricesBufferView.byteLength = sizeof(float) * xmodel.m_bones.size() * 16u; + inverseBindMatricesBufferView.byteLength = static_cast(sizeof(float) * xmodel.m_bones.size() * 16u); bufferOffset += inverseBindMatricesBufferView.byteLength; - m_inverse_bind_matrices_buffer_view = gltf.bufferViews->size(); + m_inverse_bind_matrices_buffer_view = static_cast(gltf.bufferViews->size()); gltf.bufferViews->emplace_back(inverseBindMatricesBufferView); } - m_first_index_buffer_view = gltf.bufferViews->size(); + m_first_index_buffer_view = static_cast(gltf.bufferViews->size()); for (const auto& object : xmodel.m_objects) { JsonBufferView indicesBufferView; indicesBufferView.buffer = 0u; indicesBufferView.byteOffset = bufferOffset; - indicesBufferView.byteLength = sizeof(unsigned short) * object.m_faces.size() * 3u; + indicesBufferView.byteLength = static_cast(sizeof(unsigned short) * object.m_faces.size() * 3u); indicesBufferView.target = JsonBufferViewTarget::ELEMENT_ARRAY_BUFFER; bufferOffset += indicesBufferView.byteLength; @@ -380,29 +380,29 @@ namespace JsonAccessor positionAccessor; positionAccessor.bufferView = m_vertex_buffer_view; - positionAccessor.byteOffset = offsetof(GltfVertex, coordinates); + positionAccessor.byteOffset = static_cast(offsetof(GltfVertex, coordinates)); positionAccessor.componentType = JsonAccessorComponentType::FLOAT; - positionAccessor.count = xmodel.m_vertices.size(); + positionAccessor.count = static_cast(xmodel.m_vertices.size()); positionAccessor.type = JsonAccessorType::VEC3; - m_position_accessor = gltf.accessors->size(); + m_position_accessor = static_cast(gltf.accessors->size()); gltf.accessors->emplace_back(positionAccessor); JsonAccessor normalAccessor; normalAccessor.bufferView = m_vertex_buffer_view; - normalAccessor.byteOffset = offsetof(GltfVertex, normal); + normalAccessor.byteOffset = static_cast(offsetof(GltfVertex, normal)); normalAccessor.componentType = JsonAccessorComponentType::FLOAT; - normalAccessor.count = xmodel.m_vertices.size(); + normalAccessor.count = static_cast(xmodel.m_vertices.size()); normalAccessor.type = JsonAccessorType::VEC3; - m_normal_accessor = gltf.accessors->size(); + m_normal_accessor = static_cast(gltf.accessors->size()); gltf.accessors->emplace_back(normalAccessor); JsonAccessor uvAccessor; uvAccessor.bufferView = m_vertex_buffer_view; - uvAccessor.byteOffset = offsetof(GltfVertex, uv); + uvAccessor.byteOffset = static_cast(offsetof(GltfVertex, uv)); uvAccessor.componentType = JsonAccessorComponentType::FLOAT; - uvAccessor.count = xmodel.m_vertices.size(); + uvAccessor.count = static_cast(xmodel.m_vertices.size()); uvAccessor.type = JsonAccessorType::VEC2; - m_uv_accessor = gltf.accessors->size(); + m_uv_accessor = static_cast(gltf.accessors->size()); gltf.accessors->emplace_back(uvAccessor); if (!xmodel.m_bone_weight_data.weights.empty()) @@ -410,29 +410,29 @@ namespace JsonAccessor jointsAccessor; jointsAccessor.bufferView = m_joints_buffer_view; jointsAccessor.componentType = JsonAccessorComponentType::UNSIGNED_BYTE; - jointsAccessor.count = xmodel.m_vertices.size(); + jointsAccessor.count = static_cast(xmodel.m_vertices.size()); jointsAccessor.type = JsonAccessorType::VEC4; - m_joints_accessor = gltf.accessors->size(); + m_joints_accessor = static_cast(gltf.accessors->size()); gltf.accessors->emplace_back(jointsAccessor); JsonAccessor weightsAccessor; weightsAccessor.bufferView = m_weights_buffer_view; weightsAccessor.componentType = JsonAccessorComponentType::FLOAT; - weightsAccessor.count = xmodel.m_vertices.size(); + weightsAccessor.count = static_cast(xmodel.m_vertices.size()); weightsAccessor.type = JsonAccessorType::VEC4; - m_weights_accessor = gltf.accessors->size(); + m_weights_accessor = static_cast(gltf.accessors->size()); gltf.accessors->emplace_back(weightsAccessor); JsonAccessor inverseBindMatricesAccessor; inverseBindMatricesAccessor.bufferView = m_inverse_bind_matrices_buffer_view; inverseBindMatricesAccessor.componentType = JsonAccessorComponentType::FLOAT; - inverseBindMatricesAccessor.count = xmodel.m_bones.size(); + inverseBindMatricesAccessor.count = static_cast(xmodel.m_bones.size()); inverseBindMatricesAccessor.type = JsonAccessorType::MAT4; - m_inverse_bind_matrices_accessor = gltf.accessors->size(); + m_inverse_bind_matrices_accessor = static_cast(gltf.accessors->size()); gltf.accessors->emplace_back(inverseBindMatricesAccessor); } - m_first_index_accessor = gltf.accessors->size(); + m_first_index_accessor = static_cast(gltf.accessors->size()); for (auto i = 0u; i < xmodel.m_objects.size(); i++) { const auto& object = xmodel.m_objects[i]; @@ -440,7 +440,7 @@ namespace JsonAccessor indicesAccessor; indicesAccessor.bufferView = m_first_index_buffer_view + i; indicesAccessor.componentType = JsonAccessorComponentType::UNSIGNED_SHORT; - indicesAccessor.count = object.m_faces.size() * 3u; + indicesAccessor.count = static_cast(object.m_faces.size() * 3u); indicesAccessor.type = JsonAccessorType::SCALAR; gltf.accessors->emplace_back(indicesAccessor); @@ -452,7 +452,7 @@ namespace const auto expectedBufferSize = GetExpectedBufferSize(xmodel); bufferData.resize(expectedBufferSize); - auto currentBufferOffset = 0u; + auto currentBufferOffset = 0uz; float minPosition[3]{ std::numeric_limits::max(), @@ -576,7 +576,7 @@ namespace static size_t GetExpectedBufferSize(const XModelCommon& xmodel) { - auto result = 0u; + auto result = 0uz; result += xmodel.m_vertices.size() * sizeof(GltfVertex); @@ -603,7 +603,7 @@ namespace gltf.buffers.emplace(); JsonBuffer jsonBuffer; - jsonBuffer.byteLength = bufferData.size(); + jsonBuffer.byteLength = static_cast(bufferData.size()); if (!bufferData.empty()) jsonBuffer.uri = m_output->CreateBufferUri(bufferData.data(), bufferData.size()); diff --git a/src/ObjWriting/XModel/XModelDumper.cpp.template b/src/ObjWriting/XModel/XModelDumper.cpp.template index 2e6e00f5..eebab624 100644 --- a/src/ObjWriting/XModel/XModelDumper.cpp.template +++ b/src/ObjWriting/XModel/XModelDumper.cpp.template @@ -380,7 +380,7 @@ namespace return; auto& weightCollection = out.m_bone_weight_data; - size_t weightOffset = 0u; + auto weightOffset = 0u; for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) { diff --git a/src/Unlinker/Unlinker.cpp b/src/Unlinker/Unlinker.cpp index d21c1e2f..c79d0d7b 100644 --- a/src/Unlinker/Unlinker.cpp +++ b/src/Unlinker/Unlinker.cpp @@ -106,7 +106,7 @@ private: ObjWriting::Configuration.AssetTypesToHandleBitfield = std::vector(assetTypeCount); std::vector handledSpecifiedAssets(m_args.m_specified_asset_types.size()); - for (auto i = 0; i < assetTypeCount; i++) + for (auto i = 0u; i < assetTypeCount; i++) { const auto assetTypeName = std::string(*context.m_zone.m_pools->GetAssetTypeName(i)); @@ -136,7 +136,7 @@ private: std::cerr << "Valid asset types are:\n"; auto first = true; - for (auto i = 0; i < assetTypeCount; i++) + for (auto i = 0u; i < assetTypeCount; i++) { const auto assetTypeName = std::string(*context.m_zone.m_pools->GetAssetTypeName(i)); diff --git a/src/Unlinker/UnlinkerArgs.cpp b/src/Unlinker/UnlinkerArgs.cpp index 18e66f32..08746e50 100644 --- a/src/Unlinker/UnlinkerArgs.cpp +++ b/src/Unlinker/UnlinkerArgs.cpp @@ -251,7 +251,7 @@ void UnlinkerArgs::AddSpecifiedAssetType(std::string value) void UnlinkerArgs::ParseCommaSeparatedAssetTypeString(const std::string& input) { - auto currentPos = 0u; + auto currentPos = 0uz; size_t endPos; std::string lowerInput(input); diff --git a/src/ZoneLoading/Game/IW4/ContentLoaderIW4.h b/src/ZoneLoading/Game/IW4/ContentLoaderIW4.h index 4ba9f1b8..8a3fd944 100644 --- a/src/ZoneLoading/Game/IW4/ContentLoaderIW4.h +++ b/src/ZoneLoading/Game/IW4/ContentLoaderIW4.h @@ -1,4 +1,5 @@ #pragma once + #include "Game/IW4/IW4.h" #include "Loading/ContentLoaderBase.h" #include "Loading/IContentLoadingEntryPoint.h" @@ -7,17 +8,18 @@ namespace IW4 { class ContentLoader final : public ContentLoaderBase, public IContentLoadingEntryPoint { - XAsset* varXAsset; - ScriptStringList* varScriptStringList; + public: + ContentLoader(); + void Load(Zone* zone, IZoneInputStream* stream) override; + + private: void LoadScriptStringList(bool atStreamStart); void LoadXAsset(bool atStreamStart) const; void LoadXAssetArray(bool atStreamStart, size_t count); - public: - ContentLoader(); - - void Load(Zone* zone, IZoneInputStream* stream) override; + XAsset* varXAsset; + ScriptStringList* varScriptStringList; }; } // namespace IW4 diff --git a/src/ZoneLoading/Zone/Stream/IZoneInputStream.h b/src/ZoneLoading/Zone/Stream/IZoneInputStream.h index b1158e17..c363b759 100644 --- a/src/ZoneLoading/Zone/Stream/IZoneInputStream.h +++ b/src/ZoneLoading/Zone/Stream/IZoneInputStream.h @@ -25,7 +25,7 @@ public: LoadDataInBlock(const_cast(reinterpret_cast(dst)), sizeof(T)); } - template void Load(T* dst, const uint32_t count) + template void Load(T* dst, const size_t count) { LoadDataInBlock(const_cast(reinterpret_cast(dst)), count * sizeof(T)); } diff --git a/src/ZoneWriting/Writing/Processor/OutputProcessorDeflate.cpp b/src/ZoneWriting/Writing/Processor/OutputProcessorDeflate.cpp index 07abf230..1355fd9b 100644 --- a/src/ZoneWriting/Writing/Processor/OutputProcessorDeflate.cpp +++ b/src/ZoneWriting/Writing/Processor/OutputProcessorDeflate.cpp @@ -10,12 +10,6 @@ class OutputProcessorDeflate::Impl { - z_stream m_stream{}; - OutputProcessorDeflate* m_base; - - std::unique_ptr m_buffer; - size_t m_buffer_size; - public: Impl(OutputProcessorDeflate* baseClass, const size_t bufferSize) : m_buffer(std::make_unique(bufferSize)), @@ -29,7 +23,7 @@ public: m_stream.avail_in = 0; m_stream.next_in = Z_NULL; m_stream.next_out = m_buffer.get(); - m_stream.avail_out = m_buffer_size; + m_stream.avail_out = static_cast(m_buffer_size); const int ret = deflateInit(&m_stream, Z_DEFAULT_COMPRESSION); @@ -52,7 +46,7 @@ public: void Write(const void* buffer, const size_t length) { m_stream.next_in = static_cast(buffer); - m_stream.avail_in = length; + m_stream.avail_in = static_cast(length); while (m_stream.avail_in > 0) { @@ -60,7 +54,7 @@ public: { m_base->m_base_stream->Write(m_buffer.get(), m_buffer_size); m_stream.next_out = m_buffer.get(); - m_stream.avail_out = m_buffer_size; + m_stream.avail_out = static_cast(m_buffer_size); } const auto ret = deflate(&m_stream, Z_NO_FLUSH); @@ -79,7 +73,7 @@ public: { m_base->m_base_stream->Write(m_buffer.get(), m_buffer_size - m_stream.avail_out); m_stream.next_out = m_buffer.get(); - m_stream.avail_out = m_buffer_size; + m_stream.avail_out = static_cast(m_buffer_size); } const auto ret = deflate(&m_stream, Z_FINISH); @@ -96,14 +90,21 @@ public: { m_base->m_base_stream->Write(m_buffer.get(), m_buffer_size - m_stream.avail_out); m_stream.next_out = m_buffer.get(); - m_stream.avail_out = m_buffer_size; + m_stream.avail_out = static_cast(m_buffer_size); } } - _NODISCARD int64_t Pos() const + [[nodiscard]] int64_t Pos() const { return m_base->m_base_stream->Pos(); } + +private: + z_stream m_stream{}; + OutputProcessorDeflate* m_base; + + std::unique_ptr m_buffer; + size_t m_buffer_size; }; OutputProcessorDeflate::OutputProcessorDeflate() diff --git a/src/ZoneWriting/Writing/Processor/OutputProcessorDeflate.h b/src/ZoneWriting/Writing/Processor/OutputProcessorDeflate.h index 69a27b0f..c3ee5ce9 100644 --- a/src/ZoneWriting/Writing/Processor/OutputProcessorDeflate.h +++ b/src/ZoneWriting/Writing/Processor/OutputProcessorDeflate.h @@ -13,7 +13,7 @@ class OutputProcessorDeflate final : public OutputStreamProcessor public: OutputProcessorDeflate(); - OutputProcessorDeflate(size_t bufferSize); + explicit OutputProcessorDeflate(size_t bufferSize); ~OutputProcessorDeflate() override; OutputProcessorDeflate(const OutputProcessorDeflate& other) = delete; OutputProcessorDeflate(OutputProcessorDeflate&& other) noexcept = default; diff --git a/src/ZoneWriting/Writing/Steps/StepWriteZero.cpp b/src/ZoneWriting/Writing/Steps/StepWriteZero.cpp index 5fc42368..46bff10d 100644 --- a/src/ZoneWriting/Writing/Steps/StepWriteZero.cpp +++ b/src/ZoneWriting/Writing/Steps/StepWriteZero.cpp @@ -9,10 +9,10 @@ StepWriteZero::StepWriteZero(const size_t count) void StepWriteZero::PerformStep(ZoneWriter* zoneWriter, IWritingStream* stream) { - const uint64_t num = 0; + constexpr uint64_t num = 0; size_t toWrite; - for (auto i = 0u; i < m_count; i += toWrite) + for (auto i = 0uz; i < m_count; i += toWrite) { toWrite = std::min(sizeof(uint64_t), m_count - i); stream->Write(&num, toWrite); diff --git a/src/ZoneWriting/Zone/Stream/IZoneOutputStream.h b/src/ZoneWriting/Zone/Stream/IZoneOutputStream.h index b1c890bc..43b795bd 100644 --- a/src/ZoneWriting/Zone/Stream/IZoneOutputStream.h +++ b/src/ZoneWriting/Zone/Stream/IZoneOutputStream.h @@ -43,7 +43,7 @@ public: return static_cast(WriteDataInBlock(reinterpret_cast(dst), sizeof(T))); } - template T* Write(T* dst, const uint32_t count) + template T* Write(T* dst, const size_t count) { return static_cast(WriteDataInBlock(reinterpret_cast(dst), count * sizeof(T))); } diff --git a/test/ObjCommonTestUtils/SearchPath/MockOutputPath.cpp b/test/ObjCommonTestUtils/SearchPath/MockOutputPath.cpp index 25993a48..93ddd6b0 100644 --- a/test/ObjCommonTestUtils/SearchPath/MockOutputPath.cpp +++ b/test/ObjCommonTestUtils/SearchPath/MockOutputPath.cpp @@ -66,7 +66,7 @@ namespace pos_type seekpos(const pos_type pos, std::ios_base::openmode) override { - if (pos > m_data.size()) + if (pos > static_cast(m_data.size())) m_data.resize(static_cast(pos)); m_pos = static_cast(pos); From 088d14f89417348f98d2c025262f681b0714ac31 Mon Sep 17 00:00:00 2001 From: Jan Laupetin Date: Sat, 26 Apr 2025 19:14:52 +0200 Subject: [PATCH 09/11] chore: add x64 build to ci --- .github/workflows/ci.yaml | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 68a7a71f..047661c3 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -10,6 +10,9 @@ on: jobs: build-test-linux: + strategy: + matrix: + build_arch: [x86, x64] runs-on: ubuntu-latest container: ubuntu:24.04 steps: @@ -35,10 +38,10 @@ jobs: - name: Build working-directory: ${{ github.workspace }} - run: make -C build -j$(nproc) config=release_x86 all + run: make -C build -j$(nproc) config=release_${{ matrix.build_arch }} all - name: Test - working-directory: ${{ github.workspace }}/build/lib/Release_x86/tests + working-directory: ${{ github.workspace }}/build/lib/Release_${{ matrix.build_arch }}/tests run: | ./ObjCommonTests ./ObjCompilingTests @@ -48,6 +51,14 @@ jobs: ./ZoneCommonTests build-test-windows: + strategy: + matrix: + build_arch: [x86, x64] + include: + - build_arch: x86 + msbuild_config: Win32 + - build_arch: x64 + msbuild_config: x64 runs-on: windows-latest steps: - name: Checkout repository @@ -66,10 +77,10 @@ jobs: - name: Build working-directory: ${{ github.workspace }} - run: msbuild /m /p:Configuration=Release /p:Platform=Win32 build + run: msbuild /m /p:Configuration=Release /p:Platform=${{ matrix.msbuild_config }} build - name: Test - working-directory: ${{ github.workspace }}/build/lib/Release_x86/tests + working-directory: ${{ github.workspace }}/build/lib/Release_${{ matrix.build_arch }}/tests run: | $combinedExitCode = 0 ./ObjCommonTests From 4e9599aabfa9945230dc34bc3b5a79a8b813bbe4 Mon Sep 17 00:00:00 2001 From: Jan Laupetin Date: Sun, 27 Apr 2025 21:04:41 +0200 Subject: [PATCH 10/11] chore: detect structs that differ on different architectures * and exclude them from assetstructtests --- .../Domain/Environment/Architecture.h | 8 +++ .../Information/StructureInformation.cpp | 1 + .../Domain/Information/StructureInformation.h | 1 + .../Templates/AssetStructTestsTemplate.cpp | 6 +- .../Parsing/Header/HeaderFileReader.cpp | 2 + .../CrossPlatformStructurePostProcessor.cpp | 58 +++++++++++++++++++ .../CrossPlatformStructurePostProcessor.h | 11 ++++ 7 files changed, 85 insertions(+), 2 deletions(-) create mode 100644 src/ZoneCodeGeneratorLib/Parsing/PostProcessing/CrossPlatformStructurePostProcessor.cpp create mode 100644 src/ZoneCodeGeneratorLib/Parsing/PostProcessing/CrossPlatformStructurePostProcessor.h diff --git a/src/ZoneCodeGeneratorLib/Domain/Environment/Architecture.h b/src/ZoneCodeGeneratorLib/Domain/Environment/Architecture.h index b9bfc8a1..80d06532 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Environment/Architecture.h +++ b/src/ZoneCodeGeneratorLib/Domain/Environment/Architecture.h @@ -6,3 +6,11 @@ enum class Architecture X86, X64 }; + +static constexpr Architecture OWN_ARCHITECTURE = +#if defined(ARCH_x86) + Architecture::X86 +#elif defined(ARCH_x64) + Architecture::X64 +#endif + ; diff --git a/src/ZoneCodeGeneratorLib/Domain/Information/StructureInformation.cpp b/src/ZoneCodeGeneratorLib/Domain/Information/StructureInformation.cpp index 75ae23e9..da546082 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Information/StructureInformation.cpp +++ b/src/ZoneCodeGeneratorLib/Domain/Information/StructureInformation.cpp @@ -5,6 +5,7 @@ StructureInformation::StructureInformation(DefinitionWithMembers* definition) m_asset_enum_entry(nullptr), m_is_leaf(false), m_requires_marking(false), + m_has_matching_cross_platform_structure(false), m_non_embedded_reference_exists(false), m_single_pointer_reference_exists(false), m_array_pointer_reference_exists(false), diff --git a/src/ZoneCodeGeneratorLib/Domain/Information/StructureInformation.h b/src/ZoneCodeGeneratorLib/Domain/Information/StructureInformation.h index 301c9098..2abb0b76 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Information/StructureInformation.h +++ b/src/ZoneCodeGeneratorLib/Domain/Information/StructureInformation.h @@ -24,6 +24,7 @@ public: bool m_is_leaf; bool m_requires_marking; + bool m_has_matching_cross_platform_structure; bool m_non_embedded_reference_exists; bool m_single_pointer_reference_exists; diff --git a/src/ZoneCodeGeneratorLib/Generating/Templates/AssetStructTestsTemplate.cpp b/src/ZoneCodeGeneratorLib/Generating/Templates/AssetStructTestsTemplate.cpp index bb2bb11e..1646dcbb 100644 --- a/src/ZoneCodeGeneratorLib/Generating/Templates/AssetStructTestsTemplate.cpp +++ b/src/ZoneCodeGeneratorLib/Generating/Templates/AssetStructTestsTemplate.cpp @@ -37,11 +37,13 @@ namespace LINE("{") m_intendation++; - TestMethod(m_env.m_asset); + if (m_env.m_asset->m_has_matching_cross_platform_structure) + TestMethod(m_env.m_asset); + for (auto* structure : m_env.m_used_structures) { StructureComputations computations(structure->m_info); - if (!structure->m_info->m_definition->m_anonymous && !computations.IsAsset()) + if (!structure->m_info->m_definition->m_anonymous && !computations.IsAsset() && structure->m_info->m_has_matching_cross_platform_structure) TestMethod(structure->m_info); } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/HeaderFileReader.cpp b/src/ZoneCodeGeneratorLib/Parsing/Header/HeaderFileReader.cpp index 4913e089..605c9226 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/HeaderFileReader.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/HeaderFileReader.cpp @@ -9,6 +9,7 @@ #include "Parsing/Impl/ParserFilesystemStream.h" #include "Parsing/PostProcessing/CreateMemberInformationPostProcessor.h" #include "Parsing/PostProcessing/CreateStructureInformationPostProcessor.h" +#include "Parsing/PostProcessing/CrossPlatformStructurePostProcessor.h" #include "Parsing/PostProcessing/IPostProcessor.h" #include @@ -67,6 +68,7 @@ void HeaderFileReader::SetupPostProcessors() // Order is important m_post_processors.emplace_back(std::make_unique()); m_post_processors.emplace_back(std::make_unique()); + m_post_processors.emplace_back(std::make_unique()); } bool HeaderFileReader::ReadHeaderFile(IDataRepository* repository) diff --git a/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/CrossPlatformStructurePostProcessor.cpp b/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/CrossPlatformStructurePostProcessor.cpp new file mode 100644 index 00000000..397e9844 --- /dev/null +++ b/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/CrossPlatformStructurePostProcessor.cpp @@ -0,0 +1,58 @@ +#include "CrossPlatformStructurePostProcessor.h" + +#include "Domain/Definition/PointerDeclarationModifier.h" + +#include + +namespace +{ + bool CalculateHasMatchingCrossPlatformStructure(std::unordered_set& visitedStructures, StructureInformation* info) + { + if (visitedStructures.find(info) != visitedStructures.end()) + return info->m_has_matching_cross_platform_structure; + + visitedStructures.emplace(info); + + for (const auto& member : info->m_ordered_members) + { + for (const auto& modifier : member->m_member->m_type_declaration->m_declaration_modifiers) + { + if (modifier->GetType() == DeclarationModifierType::POINTER) + { + info->m_has_matching_cross_platform_structure = false; + return false; + } + } + + if (member->m_type != nullptr && member->m_type != info && !CalculateHasMatchingCrossPlatformStructure(visitedStructures, member->m_type)) + { + info->m_has_matching_cross_platform_structure = false; + return false; + } + } + + info->m_has_matching_cross_platform_structure = true; + return true; + } +} // namespace + +bool CrossPlatformStructurePostProcessor::PostProcess(IDataRepository* repository) +{ + const auto& allInfos = repository->GetAllStructureInformation(); + + if (repository->GetArchitecture() == OWN_ARCHITECTURE) + { + for (const auto& info : allInfos) + info->m_has_matching_cross_platform_structure = true; + } + else + { + std::unordered_set visitedStructures; + for (const auto& info : allInfos) + { + CalculateHasMatchingCrossPlatformStructure(visitedStructures, info); + } + } + + return true; +} diff --git a/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/CrossPlatformStructurePostProcessor.h b/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/CrossPlatformStructurePostProcessor.h new file mode 100644 index 00000000..26caa2d1 --- /dev/null +++ b/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/CrossPlatformStructurePostProcessor.h @@ -0,0 +1,11 @@ +#pragma once + +#include "IPostProcessor.h" + +#include + +class CrossPlatformStructurePostProcessor final : public IPostProcessor +{ +public: + bool PostProcess(IDataRepository* repository) override; +}; From 4ccd0a55cfdddaf73573bbe4fb842fbfa3457460 Mon Sep 17 00:00:00 2001 From: Jan Laupetin Date: Sun, 27 Apr 2025 21:05:22 +0200 Subject: [PATCH 11/11] chore: adjust game structs to have custom alignment when they are platform independent --- src/Common/Game/IW3/IW3_Assets.h | 14 +++++++------- src/Common/Game/IW4/IW4_Assets.h | 18 +++++++++--------- src/Common/Game/IW5/IW5_Assets.h | 18 +++++++++--------- src/Common/Game/T5/T5_Assets.h | 22 +++++++++++----------- src/Common/Game/T6/T6_Assets.h | 24 ++++++++++++------------ 5 files changed, 48 insertions(+), 48 deletions(-) diff --git a/src/Common/Game/IW3/IW3_Assets.h b/src/Common/Game/IW3/IW3_Assets.h index 772b757c..510aead7 100644 --- a/src/Common/Game/IW3/IW3_Assets.h +++ b/src/Common/Game/IW3/IW3_Assets.h @@ -296,7 +296,7 @@ namespace IW3 uint16_t maxs[3]; }; - struct type_align32(16) XSurfaceCollisionNode + struct type_align(16) XSurfaceCollisionNode { XSurfaceCollisionAabb aabb; uint16_t childBeginIndex; @@ -344,7 +344,7 @@ namespace IW3 char array[4]; }; - struct type_align32(16) GfxPackedVertex + struct type_align(16) GfxPackedVertex { float xyz[3]; float binormalSign; @@ -633,7 +633,7 @@ namespace IW3 unsigned int loadBits[2]; }; - struct type_align32(16) MaterialConstantDef + struct type_align(16) MaterialConstantDef { unsigned int nameHash; char name[12]; @@ -1775,7 +1775,7 @@ namespace IW3 pathnode_tree_info_t u; }; - struct type_align32(16) pathbasenode_t + struct type_align(16) pathbasenode_t { float vOrigin[3]; unsigned int type; @@ -2044,14 +2044,14 @@ namespace IW3 GfxImage* secondary; }; - struct type_align32(4) GfxLightGridEntry + struct type_align(4) GfxLightGridEntry { uint16_t colorsIndex; char primaryLightIndex; char needsTrace; }; - struct type_align32(4) GfxLightGridColors + struct type_align(4) GfxLightGridColors { char rgb[56][3]; }; @@ -2137,7 +2137,7 @@ namespace IW3 uint16_t surfId; }; - struct type_align32(4) GfxSceneDynBrush + struct type_align(4) GfxSceneDynBrush { BModelDrawInfo info; uint16_t dynEntId; diff --git a/src/Common/Game/IW4/IW4_Assets.h b/src/Common/Game/IW4/IW4_Assets.h index 0b8c44c0..03493a12 100644 --- a/src/Common/Game/IW4/IW4_Assets.h +++ b/src/Common/Game/IW4/IW4_Assets.h @@ -442,7 +442,7 @@ namespace IW4 char array[4]; }; - struct type_align32(16) GfxPackedVertex + struct type_align(16) GfxPackedVertex { float xyz[3]; float binormalSign; @@ -458,7 +458,7 @@ namespace IW4 uint16_t maxs[3]; }; - struct type_align32(16) XSurfaceCollisionNode + struct type_align(16) XSurfaceCollisionNode { XSurfaceCollisionAabb aabb; uint16_t childBeginIndex; @@ -673,7 +673,7 @@ namespace IW4 MaterialTextureDefInfo u; }; - struct type_align32(16) MaterialConstantDef + struct type_align(16) MaterialConstantDef { unsigned int nameHash; char name[12]; @@ -2824,7 +2824,7 @@ namespace IW4 int partitionIndex; }; - struct type_align32(16) CollisionAabbTree + struct type_align(16) CollisionAabbTree { float midPoint[3]; uint16_t materialIndex; @@ -3116,7 +3116,7 @@ namespace IW4 pathnode_transient_t transient; }; - struct type_align32(16) pathbasenode_t + struct type_align(16) pathbasenode_t { float vOrigin[3]; unsigned int type; @@ -3313,7 +3313,7 @@ namespace IW4 char endVertIndex; }; - union type_align32(4) FxGlassGeometryData + union type_align(4) FxGlassGeometryData { FxGlassVertex vert; FxGlassHoleHeader hole; @@ -3505,14 +3505,14 @@ namespace IW4 r_index_t* indices; }; - struct type_align32(4) GfxLightGridEntry + struct type_align(4) GfxLightGridEntry { uint16_t colorsIndex; char primaryLightIndex; char needsTrace; }; - struct type_align32(4) GfxLightGridColors + struct type_align(4) GfxLightGridColors { char rgb[56][3]; }; @@ -3599,7 +3599,7 @@ namespace IW4 uint16_t surfId; }; - struct type_align32(4) GfxSceneDynBrush + struct type_align(4) GfxSceneDynBrush { BModelDrawInfo info; uint16_t dynEntId; diff --git a/src/Common/Game/IW5/IW5_Assets.h b/src/Common/Game/IW5/IW5_Assets.h index 1e52e7af..ef9a37b6 100644 --- a/src/Common/Game/IW5/IW5_Assets.h +++ b/src/Common/Game/IW5/IW5_Assets.h @@ -491,7 +491,7 @@ namespace IW5 unsigned char array[4]; }; - struct type_align32(16) GfxPackedVertex + struct type_align(16) GfxPackedVertex { vec3_t xyz; float binormalSign; @@ -507,7 +507,7 @@ namespace IW5 unsigned short maxs[3]; }; - struct type_align32(16) XSurfaceCollisionNode + struct type_align(16) XSurfaceCollisionNode { XSurfaceCollisionAabb aabb; unsigned short childBeginIndex; @@ -822,7 +822,7 @@ namespace IW5 MaterialTextureDefInfo u; }; - struct type_align32(16) MaterialConstantDef + struct type_align(16) MaterialConstantDef { unsigned int nameHash; char name[12]; @@ -1410,7 +1410,7 @@ namespace IW5 int partitionIndex; }; - struct type_align32(16) CollisionAabbTree + struct type_align(16) CollisionAabbTree { float midPoint[3]; unsigned short materialIndex; @@ -1761,7 +1761,7 @@ namespace IW5 pathnode_transient_t transient; }; - struct type_align32(16) pathbasenode_t + struct type_align(16) pathbasenode_t { float vOrigin[3]; unsigned int type; @@ -1948,7 +1948,7 @@ namespace IW5 unsigned char endVertIndex; }; - union type_align32(4) FxGlassGeometryData + union type_align(4) FxGlassGeometryData { FxGlassVertex vert; FxGlassHoleHeader hole; @@ -2155,14 +2155,14 @@ namespace IW5 r_index_t* indices; }; - struct type_align32(4) GfxLightGridEntry + struct type_align(4) GfxLightGridEntry { unsigned short colorsIndex; unsigned char primaryLightIndex; unsigned char needsTrace; }; - struct type_align32(4) GfxLightGridColors + struct type_align(4) GfxLightGridColors { unsigned char rgb[56][3]; }; @@ -2250,7 +2250,7 @@ namespace IW5 unsigned short surfId; }; - struct type_align32(4) GfxSceneDynBrush + struct type_align(4) GfxSceneDynBrush { BModelDrawInfo info; unsigned short dynEntId; diff --git a/src/Common/Game/T5/T5_Assets.h b/src/Common/Game/T5/T5_Assets.h index 95da5a75..fa562d38 100644 --- a/src/Common/Game/T5/T5_Assets.h +++ b/src/Common/Game/T5/T5_Assets.h @@ -490,7 +490,7 @@ namespace T5 char array[4]; }; - struct type_align32(16) GfxPackedVertex + struct type_align(16) GfxPackedVertex { vec3_t xyz; float binormalSign; @@ -511,7 +511,7 @@ namespace T5 uint16_t maxs[3]; }; - struct type_align32(16) XSurfaceCollisionNode + struct type_align(16) XSurfaceCollisionNode { XSurfaceCollisionAabb aabb; uint16_t childBeginIndex; @@ -796,7 +796,7 @@ namespace T5 MaterialTextureDefInfo u; }; - struct type_align32(16) MaterialConstantDef + struct type_align(16) MaterialConstantDef { unsigned int nameHash; char name[12]; @@ -1254,7 +1254,7 @@ namespace T5 int sequence; }; - struct type_align32(4) SndIndexEntry + struct type_align(4) SndIndexEntry { uint16_t value; uint16_t next; @@ -1409,7 +1409,7 @@ namespace T5 int partitionIndex; }; - struct type_align32(16) CollisionAabbTree + struct type_align(16) CollisionAabbTree { float origin[3]; uint16_t materialIndex; @@ -1687,7 +1687,7 @@ namespace T5 int maxy; }; - struct type_align32(4) ComWaterCell + struct type_align(4) ComWaterCell { int16_t waterheight; char flooroffset; @@ -1826,7 +1826,7 @@ namespace T5 pathnode_transient_t transient; }; - struct type_align32(16) pathbasenode_t + struct type_align(16) pathbasenode_t { float vOrigin[3]; unsigned int type; @@ -1926,7 +1926,7 @@ namespace T5 GfxWorldSunColor sunSettings[1]; }; - struct type_align32(16) float44 + struct type_align(16) float44 { union { @@ -2130,14 +2130,14 @@ namespace T5 uint16_t* indices; }; - struct type_align32(4) GfxLightGridEntry + struct type_align(4) GfxLightGridEntry { uint16_t colorsIndex; char primaryLightIndex; char needsTrace; }; - struct type_align32(4) GfxCompressedLightGridColors + struct type_align(4) GfxCompressedLightGridColors { char rgb[56][3]; }; @@ -2227,7 +2227,7 @@ namespace T5 uint16_t surfId; }; - struct type_align32(4) GfxSceneDynBrush + struct type_align(4) GfxSceneDynBrush { BModelDrawInfo info; uint16_t dynEntId; diff --git a/src/Common/Game/T6/T6_Assets.h b/src/Common/Game/T6/T6_Assets.h index c61a3885..b607c7cc 100644 --- a/src/Common/Game/T6/T6_Assets.h +++ b/src/Common/Game/T6/T6_Assets.h @@ -2883,7 +2883,7 @@ namespace T6 GfxImage* image; }; - struct type_align32(16) MaterialConstantDef + struct type_align(16) MaterialConstantDef { unsigned int nameHash; char name[12]; @@ -3076,7 +3076,7 @@ namespace T6 int sequence; }; - struct type_align32(4) SndIndexEntry + struct type_align(4) SndIndexEntry { uint16_t value; uint16_t next; @@ -3261,7 +3261,7 @@ namespace T6 int partitionIndex; }; - struct type_align32(16) CollisionAabbTree + struct type_align(16) CollisionAabbTree { vec3_t origin; uint16_t materialIndex; @@ -3526,7 +3526,7 @@ namespace T6 pathnode_transient_t transient; }; - struct type_align32(16) pathbasenode_t + struct type_align(16) pathbasenode_t { vec3_t vOrigin; unsigned int type; @@ -3573,7 +3573,7 @@ namespace T6 float halfSize; }; - struct type_align32(16) GfxStreamingAabbTree + struct type_align(16) GfxStreamingAabbTree { vec4_t mins; vec4_t maxs; @@ -3586,7 +3586,7 @@ namespace T6 uint16_t surfaceCount; }; - struct type_align32(16) float44 + struct type_align(16) float44 { union { @@ -3734,14 +3734,14 @@ namespace T6 { };*/ - struct type_align32(4) GfxLightGridEntry + struct type_align(4) GfxLightGridEntry { uint16_t colorsIndex; char primaryLightIndex; char visibility; }; - struct type_align32(4) GfxCompressedLightGridColors + struct type_align(4) GfxCompressedLightGridColors { char rgb[56][3]; }; @@ -3769,7 +3769,7 @@ namespace T6 float padding2; }; - struct type_align32(16) GfxBrushModel + struct type_align(16) GfxBrushModel { GfxBrushModelWritable writable; vec3_t bounds[2]; @@ -3808,7 +3808,7 @@ namespace T6 uint16_t surfId; }; - struct type_align32(4) GfxSceneDynBrush + struct type_align(4) GfxSceneDynBrush { BModelDrawInfo info; uint16_t dynEntId; @@ -5712,7 +5712,7 @@ namespace T6 unsigned int packed; }; - struct type_align32(16) GfxPackedVertex + struct type_align(16) GfxPackedVertex { vec3_t xyz; float binormalSign; @@ -6994,7 +6994,7 @@ namespace T6 uint16_t maxs[3]; }; - struct type_align32(16) XSurfaceCollisionNode + struct type_align(16) XSurfaceCollisionNode { XSurfaceCollisionAabb aabb; uint16_t childBeginIndex;