diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index edd7585cea..712cf60115 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -36,7 +36,7 @@ variables: Ubuntu_GCC_preprocess: extends: .Ubuntu_Image cache: - key: Ubuntu_GCC_preprocess.ubuntu_24.04.v1 + key: Ubuntu_GCC_preprocess.ubuntu_24.04.v2 paths: - apt-cache/ - .cache/pip/ @@ -105,7 +105,7 @@ Coverity: rules: - if: $CI_PIPELINE_SOURCE == "schedule" cache: - key: Coverity.ubuntu_24.04.v1 + key: Coverity.ubuntu_24.04.v2 paths: - apt-cache/ - ccache/ @@ -161,7 +161,7 @@ Coverity_Upload: Ubuntu_GCC: extends: .Ubuntu cache: - key: Ubuntu_GCC.ubuntu_24.04.v1 + key: Ubuntu_GCC.ubuntu_24.04.v2 before_script: - CI/install_debian_deps.sh gcc openmw-deps openmw-deps-dynamic variables: @@ -174,7 +174,7 @@ Ubuntu_GCC: Ubuntu_GCC_asan: extends: Ubuntu_GCC cache: - key: Ubuntu_GCC_asan.ubuntu_24.04.v1 + key: Ubuntu_GCC_asan.ubuntu_24.04.v2 variables: CMAKE_BUILD_TYPE: Debug CMAKE_CXX_FLAGS_DEBUG: -g -O1 -fno-omit-frame-pointer -fsanitize=address -fsanitize=pointer-subtract -fsanitize=leak @@ -187,7 +187,7 @@ Clang_Format: extends: .Ubuntu_Image stage: checks cache: - key: Ubuntu_Clang_Format.ubuntu_24.04.v1 + key: Ubuntu_Clang_Format.ubuntu_24.04.v2 paths: - apt-cache/ variables: @@ -203,7 +203,7 @@ Lupdate: extends: .Ubuntu_Image stage: checks cache: - key: Ubuntu_lupdate.ubuntu_24.04.v1 + key: Ubuntu_lupdate.ubuntu_24.04.v2 paths: - apt-cache/ variables: @@ -229,7 +229,7 @@ Teal: Ubuntu_GCC_Debug: extends: .Ubuntu cache: - key: Ubuntu_GCC_Debug.ubuntu_24.04.v2 + key: Ubuntu_GCC_Debug.ubuntu_24.04.v3 before_script: - CI/install_debian_deps.sh gcc openmw-deps openmw-deps-dynamic variables: @@ -245,7 +245,7 @@ Ubuntu_GCC_Debug: Ubuntu_GCC_tests: extends: Ubuntu_GCC cache: - key: Ubuntu_GCC_tests.ubuntu_24.04.v1 + key: Ubuntu_GCC_tests.ubuntu_24.04.v2 variables: CCACHE_SIZE: 1G BUILD_TESTS_ONLY: 1 @@ -259,7 +259,7 @@ Ubuntu_GCC_tests: .Ubuntu_GCC_tests_Debug: extends: Ubuntu_GCC cache: - key: Ubuntu_GCC_tests_Debug.ubuntu_24.04.v1 + key: Ubuntu_GCC_tests_Debug.ubuntu_24.04.v2 variables: CCACHE_SIZE: 1G BUILD_TESTS_ONLY: 1 @@ -275,7 +275,7 @@ Ubuntu_GCC_tests: Ubuntu_GCC_tests_asan: extends: Ubuntu_GCC cache: - key: Ubuntu_GCC_tests_asan.ubuntu_24.04.v1 + key: Ubuntu_GCC_tests_asan.ubuntu_24.04.v2 variables: CCACHE_SIZE: 1G BUILD_TESTS_ONLY: 1 @@ -298,7 +298,7 @@ Ubuntu_GCC_tests_asan: Ubuntu_GCC_tests_ubsan: extends: Ubuntu_GCC cache: - key: Ubuntu_GCC_tests_ubsan.ubuntu_24.04.v1 + key: Ubuntu_GCC_tests_ubsan.ubuntu_24.04.v2 variables: CCACHE_SIZE: 1G BUILD_TESTS_ONLY: 1 @@ -318,7 +318,7 @@ Ubuntu_GCC_tests_ubsan: .Ubuntu_GCC_tests_tsan: extends: Ubuntu_GCC cache: - key: Ubuntu_GCC_tests_tsan.ubuntu_24.04.v1 + key: Ubuntu_GCC_tests_tsan.ubuntu_24.04.v2 variables: CCACHE_SIZE: 1G BUILD_TESTS_ONLY: 1 @@ -336,7 +336,7 @@ Ubuntu_GCC_tests_ubsan: Ubuntu_GCC_tests_coverage: extends: .Ubuntu_GCC_tests_Debug cache: - key: Ubuntu_GCC_tests_coverage.ubuntu_24.04.v1 + key: Ubuntu_GCC_tests_coverage.ubuntu_24.04.v2 paths: - .cache/pip variables: @@ -369,7 +369,7 @@ Ubuntu_GCC_tests_coverage: - "CI/**/*" - ".gitlab-ci.yml" cache: - key: Ubuntu_Static_Deps.ubuntu_24.04.v1 + key: Ubuntu_Static_Deps.ubuntu_24.04.v2 paths: - apt-cache/ - ccache/ @@ -386,7 +386,7 @@ Ubuntu_GCC_tests_coverage: .Ubuntu_Static_Deps_tests: extends: .Ubuntu_Static_Deps cache: - key: Ubuntu_Static_Deps_tests.ubuntu_24.04.v1 + key: Ubuntu_Static_Deps_tests.ubuntu_24.04.v2 variables: CCACHE_SIZE: 1G BUILD_TESTS_ONLY: 1 @@ -405,7 +405,7 @@ Ubuntu_Clang: before_script: - CI/install_debian_deps.sh clang openmw-deps openmw-deps-dynamic cache: - key: Ubuntu_Clang.ubuntu_24.04.v2 + key: Ubuntu_Clang.ubuntu_24.04.v3 variables: CC: clang CXX: clang++ @@ -418,7 +418,7 @@ Ubuntu_Clang: before_script: - CI/install_debian_deps.sh clang clang-tidy openmw-deps openmw-deps-dynamic cache: - key: Ubuntu_Clang_Tidy.ubuntu_24.04.v1 + key: Ubuntu_Clang_Tidy.ubuntu_24.04.v2 variables: CMAKE_BUILD_TYPE: Debug CMAKE_CXX_FLAGS_DEBUG: -O0 @@ -480,7 +480,7 @@ Ubuntu_Clang_Tidy_other: .Ubuntu_Clang_tests: extends: Ubuntu_Clang cache: - key: Ubuntu_Clang_tests.ubuntu_24.04.v1 + key: Ubuntu_Clang_tests.ubuntu_24.04.v2 variables: CCACHE_SIZE: 1G BUILD_TESTS_ONLY: 1 @@ -494,7 +494,7 @@ Ubuntu_Clang_Tidy_other: Ubuntu_Clang_tests_Debug: extends: Ubuntu_Clang cache: - key: Ubuntu_Clang_tests_Debug.ubuntu_24.04.v1 + key: Ubuntu_Clang_tests_Debug.ubuntu_24.04.v2 variables: CCACHE_SIZE: 1G BUILD_TESTS_ONLY: 1 @@ -529,7 +529,7 @@ Ubuntu_Clang_integration_tests: needs: - Ubuntu_Clang cache: - key: Ubuntu_Clang_integration_tests.ubuntu_24.04.v2 + key: Ubuntu_Clang_integration_tests.ubuntu_24.04.v3 variables: OPENMW_DEPS: openmw-integration-tests @@ -538,7 +538,7 @@ Ubuntu_GCC_integration_tests_asan: needs: - Ubuntu_GCC_asan cache: - key: Ubuntu_GCC_integration_tests_asan.ubuntu_24.04.v1 + key: Ubuntu_GCC_integration_tests_asan.ubuntu_24.04.v2 variables: OPENMW_DEPS: openmw-integration-tests libasan ASAN_OPTIONS: halt_on_error=1:strict_string_checks=1:detect_stack_use_after_return=1:check_initialization_order=1:strict_init_order=1:detect_leaks=0 @@ -591,7 +591,7 @@ Ubuntu_GCC_integration_tests_asan: macOS15_Xcode16_amd64: extends: .MacOS cache: - key: macOS15_Xcode16_amd64.v1 + key: macOS15_Xcode16_amd64.v2 variables: CCACHE_SIZE: 3G DMG_IDENTIFIER: amd64 @@ -603,7 +603,7 @@ macOS15_Xcode16_amd64: macOS15_Xcode16_arm64: extends: .MacOS cache: - key: macOS15_Xcode16_arm64.v1 + key: macOS15_Xcode16_arm64.v2 variables: DMG_IDENTIFIER: arm64 CCACHE_SIZE: 3G diff --git a/CMakeLists.txt b/CMakeLists.txt index 9604c720fb..34c8a2f3de 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -482,7 +482,6 @@ set(SOL_CONFIG_DIR ${OpenMW_SOURCE_DIR}/extern/sol_config) include_directories( BEFORE SYSTEM - "." ${MyGUI_INCLUDE_DIRS} ${OPENAL_INCLUDE_DIR} ${OPENGL_INCLUDE_DIR} @@ -492,6 +491,7 @@ include_directories( ${SOL_CONFIG_DIR} ${ICU_INCLUDE_DIRS} ) +include_directories(".") link_directories(${COLLADA_DOM_LIBRARY_DIRS}) diff --git a/apps/components_tests/detournavigator/navigator.cpp b/apps/components_tests/detournavigator/navigator.cpp index d2b48ce623..4a9f2eaef1 100644 --- a/apps/components_tests/detournavigator/navigator.cpp +++ b/apps/components_tests/detournavigator/navigator.cpp @@ -104,7 +104,7 @@ namespace surface.mHeights = values.data(); surface.mMinHeight = -greater; surface.mMaxHeight = greater; - surface.mSize = static_cast(std::sqrt(size)); + surface.mSize = static_cast(std::sqrt(size)); return surface; } @@ -331,7 +331,7 @@ namespace TEST_F(DetourNavigatorNavigatorTest, only_one_heightfield_per_cell_is_allowed) { const HeightfieldSurface surface1 = makeSquareHeightfieldSurface(defaultHeightfieldData); - const int cellSize1 = heightfieldTileSize * (surface1.mSize - 1); + const int cellSize1 = heightfieldTileSize * static_cast(surface1.mSize - 1); const std::array heightfieldData2{ { -25, -25, -25, -25, -25, // row 0 @@ -341,7 +341,7 @@ namespace -25, -25, -25, -25, -25, // row 4 } }; const HeightfieldSurface surface2 = makeSquareHeightfieldSurface(heightfieldData2); - const int cellSize2 = heightfieldTileSize * (surface2.mSize - 1); + const int cellSize2 = heightfieldTileSize * static_cast(surface2.mSize - 1); ASSERT_TRUE(mNavigator->addAgent(mAgentBounds)); mNavigator->addHeightfield(mCellPosition, cellSize1, surface1, nullptr); @@ -639,8 +639,9 @@ namespace for (std::size_t i = 0; i < boxes.size(); ++i) { + const btScalar diameter = static_cast(i) * 10; const btTransform transform( - btMatrix3x3::getIdentity(), btVector3(shift.x() + i * 10, shift.y() + i * 10, i * 10)); + btMatrix3x3::getIdentity(), btVector3(shift.x() + diameter, shift.y() + diameter, diameter)); mNavigator->addObject( ObjectId(&boxes[i].shape()), ObjectShapes(boxes[i].instance(), mObjectTransform), transform, nullptr); } @@ -649,8 +650,9 @@ namespace for (std::size_t i = 0; i < boxes.size(); ++i) { + const btScalar diameter = static_cast(i) * 10 + 1; const btTransform transform( - btMatrix3x3::getIdentity(), btVector3(shift.x() + i * 10 + 1, shift.y() + i * 10 + 1, i * 10 + 1)); + btMatrix3x3::getIdentity(), btVector3(shift.x() + diameter, shift.y() + diameter, diameter)); mNavigator->updateObject( ObjectId(&boxes[i].shape()), ObjectShapes(boxes[i].instance(), mObjectTransform), transform, nullptr); } @@ -680,7 +682,8 @@ namespace for (std::size_t i = 0; i < shapes.size(); ++i) { - const btTransform transform(btMatrix3x3::getIdentity(), btVector3(i * 32, i * 32, i * 32)); + const btScalar diameter = static_cast(i) * 32; + const btTransform transform(btMatrix3x3::getIdentity(), btVector3(diameter, diameter, diameter)); mNavigator->addObject( ObjectId(&shapes[i].shape()), ObjectShapes(shapes[i].instance(), mObjectTransform), transform, nullptr); } @@ -690,7 +693,8 @@ namespace const auto start = std::chrono::steady_clock::now(); for (std::size_t i = 0; i < shapes.size(); ++i) { - const btTransform transform(btMatrix3x3::getIdentity(), btVector3(i * 32 + 1, i * 32 + 1, i * 32 + 1)); + const btScalar diameter = static_cast(i) * 32 + 1; + const btTransform transform(btMatrix3x3::getIdentity(), btVector3(diameter, diameter, diameter)); mNavigator->updateObject( ObjectId(&shapes[i].shape()), ObjectShapes(shapes[i].instance(), mObjectTransform), transform, nullptr); } @@ -699,7 +703,8 @@ namespace for (std::size_t i = 0; i < shapes.size(); ++i) { - const btTransform transform(btMatrix3x3::getIdentity(), btVector3(i * 32 + 2, i * 32 + 2, i * 32 + 2)); + const btScalar diameter = static_cast(i) * 32 + 2; + const btTransform transform(btMatrix3x3::getIdentity(), btVector3(diameter, diameter, diameter)); mNavigator->updateObject( ObjectId(&shapes[i].shape()), ObjectShapes(shapes[i].instance(), mObjectTransform), transform, nullptr); } diff --git a/apps/components_tests/detournavigator/navmeshtilescache.cpp b/apps/components_tests/detournavigator/navmeshtilescache.cpp index 3bd3deba65..a6ad4828d9 100644 --- a/apps/components_tests/detournavigator/navmeshtilescache.cpp +++ b/apps/components_tests/detournavigator/navmeshtilescache.cpp @@ -21,7 +21,7 @@ namespace using namespace DetourNavigator::Tests; template - void generateRecastArray(T*& values, int size, Random& random) + void generateRecastArray(T*& values, size_t size, Random& random) { values = static_cast(permRecastAlloc(size * sizeof(T))); generateRange(values, values + static_cast(size), random); diff --git a/apps/components_tests/nifloader/testbulletnifloader.cpp b/apps/components_tests/nifloader/testbulletnifloader.cpp index 4143e1d127..9b73f6f2c0 100644 --- a/apps/components_tests/nifloader/testbulletnifloader.cpp +++ b/apps/components_tests/nifloader/testbulletnifloader.cpp @@ -1,6 +1,7 @@ #include "../nif/node.hpp" #include +#include #include #include #include @@ -300,10 +301,10 @@ namespace void copy(const btTransform& src, Nif::NiTransform& dst) { - dst.mTranslation = osg::Vec3f(src.getOrigin().x(), src.getOrigin().y(), src.getOrigin().z()); + dst.mTranslation = Misc::Convert::makeOsgVec3f(src.getOrigin()); for (int row = 0; row < 3; ++row) for (int column = 0; column < 3; ++column) - dst.mRotation.mValues[row][column] = src.getBasis().getRow(row)[column]; + dst.mRotation.mValues[row][column] = static_cast(src.getBasis().getRow(row)[column]); } struct TestBulletNifLoader : Test diff --git a/apps/esmtool/esmtool.cpp b/apps/esmtool/esmtool.cpp index 181dd5360f..b99c47a14e 100644 --- a/apps/esmtool/esmtool.cpp +++ b/apps/esmtool/esmtool.cpp @@ -482,7 +482,7 @@ namespace int digitCount = 1; // For a nicer output if (recordCount > 0) - digitCount = (int)std::log10(recordCount) + 1; + digitCount = static_cast(std::log10(recordCount)) + 1; std::cout << "Loaded " << recordCount << " records:\n\n"; @@ -507,7 +507,7 @@ namespace esm.setEncoder(&encoder); esm.setHeader(data.mHeader); esm.setVersion(ESM::VER_130); - esm.setRecordCount(recordCount); + esm.setRecordCount(static_cast(recordCount)); std::fstream save(info.outname, std::fstream::out | std::fstream::binary); esm.save(save); diff --git a/apps/esmtool/record.cpp b/apps/esmtool/record.cpp index cbc8667056..3e45b6eead 100644 --- a/apps/esmtool/record.cpp +++ b/apps/esmtool/record.cpp @@ -660,7 +660,8 @@ namespace EsmTool std::cout << " Attributes:" << std::endl; for (size_t i = 0; i < mData.mData.mAttributes.size(); ++i) - std::cout << " " << ESM::Attribute::indexToRefId(i) << ": " << mData.mData.mAttributes[i] << std::endl; + std::cout << " " << ESM::Attribute::indexToRefId(static_cast(i)) << ": " + << mData.mData.mAttributes[i] << std::endl; std::cout << " Health: " << mData.mData.mHealth << std::endl; std::cout << " Magicka: " << mData.mData.mMana << std::endl; @@ -1049,11 +1050,13 @@ namespace EsmTool std::cout << " Attributes:" << std::endl; for (size_t i = 0; i != mData.mNpdt.mAttributes.size(); i++) - std::cout << " " << attributeLabel(i) << ": " << int(mData.mNpdt.mAttributes[i]) << std::endl; + std::cout << " " << attributeLabel(static_cast(i)) << ": " << int(mData.mNpdt.mAttributes[i]) + << std::endl; std::cout << " Skills:" << std::endl; for (size_t i = 0; i != mData.mNpdt.mSkills.size(); i++) - std::cout << " " << skillLabel(i) << ": " << int(mData.mNpdt.mSkills[i]) << std::endl; + std::cout << " " << skillLabel(static_cast(i)) << ": " << int(mData.mNpdt.mSkills[i]) + << std::endl; std::cout << " Health: " << mData.mNpdt.mHealth << std::endl; std::cout << " Magicka: " << mData.mNpdt.mMana << std::endl; diff --git a/apps/essimporter/convertacdt.cpp b/apps/essimporter/convertacdt.cpp index d9823a6c2a..defdab8a1a 100644 --- a/apps/essimporter/convertacdt.cpp +++ b/apps/essimporter/convertacdt.cpp @@ -48,8 +48,8 @@ namespace ESSImport for (int i = 0; i < ESM::Skill::Length; ++i) { npcStats.mSkills[i].mMod = 0.f; - npcStats.mSkills[i].mCurrent = actorData.mSkills[i][1]; - npcStats.mSkills[i].mBase = actorData.mSkills[i][0]; + npcStats.mSkills[i].mCurrent = static_cast(actorData.mSkills[i][1]); + npcStats.mSkills[i].mBase = static_cast(actorData.mSkills[i][0]); } npcStats.mTimeToStartDrowning = actorData.mACDT.mBreathMeter; diff --git a/apps/essimporter/converter.cpp b/apps/essimporter/converter.cpp index d439552d53..3e6b293f2c 100644 --- a/apps/essimporter/converter.cpp +++ b/apps/essimporter/converter.cpp @@ -18,7 +18,7 @@ namespace { - void convertImage(char* data, int size, int width, int height, GLenum pf, const std::string& out) + void convertImage(char* data, size_t size, int width, int height, GLenum pf, const std::string& out) { osg::ref_ptr image(new osg::Image); image->allocateImage(width, height, 1, pf, GL_UNSIGNED_BYTE); diff --git a/apps/launcher/datafilespage.cpp b/apps/launcher/datafilespage.cpp index 7bd9c9bd65..057f595df8 100644 --- a/apps/launcher/datafilespage.cpp +++ b/apps/launcher/datafilespage.cpp @@ -145,7 +145,7 @@ namespace Launcher int getMaxNavMeshDbFileSizeMiB() { - return Settings::navigator().mMaxNavmeshdbFileSize / (1024 * 1024); + return static_cast(Settings::navigator().mMaxNavmeshdbFileSize / (1024 * 1024)); } } } diff --git a/apps/opencs/model/doc/savingstages.cpp b/apps/opencs/model/doc/savingstages.cpp index 492807eb93..6db00c593f 100644 --- a/apps/opencs/model/doc/savingstages.cpp +++ b/apps/opencs/model/doc/savingstages.cpp @@ -406,7 +406,7 @@ void CSMDoc::WriteCellCollectionStage::perform(int stage, Messages& messages) if (references != nullptr) { writeReferences(persistentRefs, interior); - cellRecord.saveTempMarker(writer, static_cast(references->size()) - persistentRefs.size()); + cellRecord.saveTempMarker(writer, static_cast(references->size() - persistentRefs.size())); writeReferences(tempRefs, interior); } diff --git a/apps/opencs/model/tools/referenceablecheck.cpp b/apps/opencs/model/tools/referenceablecheck.cpp index b9ed2cec0d..4ebf626f51 100644 --- a/apps/opencs/model/tools/referenceablecheck.cpp +++ b/apps/opencs/model/tools/referenceablecheck.cpp @@ -462,7 +462,7 @@ void CSMTools::ReferenceableCheckStage::creatureCheck( for (size_t i = 0; i < creature.mData.mAttributes.size(); ++i) { if (creature.mData.mAttributes[i] < 0) - messages.add(id, ESM::Attribute::indexToRefId(i).toDebugString() + " is negative", {}, + messages.add(id, ESM::Attribute::indexToRefId(static_cast(i)).toDebugString() + " is negative", {}, CSMDoc::Message::Severity_Warning); } diff --git a/apps/opencs/model/world/actoradapter.cpp b/apps/opencs/model/world/actoradapter.cpp index f7796acd76..ce489aee19 100644 --- a/apps/opencs/model/world/actoradapter.cpp +++ b/apps/opencs/model/world/actoradapter.cpp @@ -640,7 +640,7 @@ namespace CSMWorld reservedList.emplace_back(pr); } - int priority = parts.size(); + int priority = static_cast(parts.size()); addParts(clothing.mParts.mParts, priority); addParts(reservedList, priority); diff --git a/apps/opencs/model/world/cellselection.cpp b/apps/opencs/model/world/cellselection.cpp index e6b346be98..d0f9497dcf 100644 --- a/apps/opencs/model/world/cellselection.cpp +++ b/apps/opencs/model/world/cellselection.cpp @@ -34,7 +34,7 @@ bool CSMWorld::CellSelection::has(const CellCoordinates& coordinates) const int CSMWorld::CellSelection::getSize() const { - return mCells.size(); + return static_cast(mCells.size()); } CSMWorld::CellCoordinates CSMWorld::CellSelection::getCentre() const diff --git a/apps/opencs/model/world/collection.hpp b/apps/opencs/model/world/collection.hpp index 18fb73330c..9d3658cdf0 100644 --- a/apps/opencs/model/world/collection.hpp +++ b/apps/opencs/model/world/collection.hpp @@ -367,7 +367,7 @@ namespace CSMWorld template int Collection::getSize() const { - return mRecords.size(); + return static_cast(mRecords.size()); } template @@ -391,7 +391,7 @@ namespace CSMWorld template int Collection::getColumns() const { - return mColumns.size(); + return static_cast(mColumns.size()); } template diff --git a/apps/opencs/model/world/nestedcoladapterimp.cpp b/apps/opencs/model/world/nestedcoladapterimp.cpp index 181c7d80e8..185ebd7e4c 100644 --- a/apps/opencs/model/world/nestedcoladapterimp.cpp +++ b/apps/opencs/model/world/nestedcoladapterimp.cpp @@ -41,7 +41,7 @@ namespace CSMWorld point.mConnectionNum = 0; points.insert(points.begin() + position, point); - pathgrid.mData.mPoints = pathgrid.mPoints.size(); + pathgrid.mData.mPoints = static_cast(pathgrid.mPoints.size()); record.setModified(pathgrid); } @@ -58,7 +58,7 @@ namespace CSMWorld // Do not remove dangling edges, does not work with current undo mechanism // Do not automatically adjust indices, what would be done with dangling edges? points.erase(points.begin() + rowToRemove); - pathgrid.mData.mPoints = pathgrid.mPoints.size(); + pathgrid.mData.mPoints = static_cast(pathgrid.mPoints.size()); record.setModified(pathgrid); } @@ -67,7 +67,7 @@ namespace CSMWorld { Pathgrid pathgrid = record.get(); pathgrid.mPoints = static_cast&>(nestedTable).mNestedTable; - pathgrid.mData.mPoints = pathgrid.mPoints.size(); + pathgrid.mData.mPoints = static_cast(pathgrid.mPoints.size()); record.setModified(pathgrid); } @@ -462,7 +462,7 @@ namespace CSMWorld soundRef.mSound = ESM::RefId::stringRefId(value.toString().toUtf8().constData()); break; case 1: - soundRef.mChance = static_cast(value.toInt()); + soundRef.mChance = static_cast(value.toInt()); break; default: throw std::runtime_error("Region sounds subcolumn index out of range"); @@ -543,7 +543,7 @@ namespace CSMWorld // default row ESM::DialogueCondition condStruct; - condStruct.mIndex = conditions.size(); + condStruct.mIndex = static_cast(conditions.size()); conditions.insert(conditions.begin() + position, condStruct); @@ -855,7 +855,7 @@ namespace CSMWorld int RaceSkillsBonusAdapter::getRowsCount(const Record& record) const { - return record.get().mData.mBonus.size(); + return static_cast(record.get().mData.mBonus.size()); } void CellListAdapter::addRow(Record& record, int position) const diff --git a/apps/opencs/model/world/nestedtablewrapper.hpp b/apps/opencs/model/world/nestedtablewrapper.hpp index 69a00bf9c7..b96e05fa09 100644 --- a/apps/opencs/model/world/nestedtablewrapper.hpp +++ b/apps/opencs/model/world/nestedtablewrapper.hpp @@ -7,9 +7,7 @@ namespace CSMWorld { virtual ~NestedTableWrapperBase() = default; - virtual int size() const { return -5; } - - NestedTableWrapperBase() = default; + virtual size_t size() const = 0; }; template @@ -24,7 +22,7 @@ namespace CSMWorld ~NestedTableWrapper() override = default; - int size() const override + size_t size() const override { return mNestedTable.size(); // i hope that this will be enough } diff --git a/apps/opencs/model/world/refidcollection.cpp b/apps/opencs/model/world/refidcollection.cpp index 6fff14674f..b10340de62 100644 --- a/apps/opencs/model/world/refidcollection.cpp +++ b/apps/opencs/model/world/refidcollection.cpp @@ -665,7 +665,7 @@ int CSMWorld::RefIdCollection::getIndex(const ESM::RefId& id) const int CSMWorld::RefIdCollection::getColumns() const { - return mColumns.size(); + return static_cast(mColumns.size()); } const CSMWorld::ColumnBase& CSMWorld::RefIdCollection::getColumn(int column) const diff --git a/apps/opencs/model/world/refiddata.cpp b/apps/opencs/model/world/refiddata.cpp index bab9ae38d6..4af538bad4 100644 --- a/apps/opencs/model/world/refiddata.cpp +++ b/apps/opencs/model/world/refiddata.cpp @@ -275,7 +275,7 @@ void CSMWorld::RefIdData::erase(const LocalIndex& index, int count) int CSMWorld::RefIdData::getSize() const { - return mIndex.size(); + return static_cast(mIndex.size()); } std::vector CSMWorld::RefIdData::getIds(bool listDeleted) const diff --git a/apps/opencs/view/filter/editwidget.cpp b/apps/opencs/view/filter/editwidget.cpp index 54ed388441..feaa4d4465 100644 --- a/apps/opencs/view/filter/editwidget.cpp +++ b/apps/opencs/view/filter/editwidget.cpp @@ -115,7 +115,7 @@ void CSVFilter::EditWidget::createFilterRequest(const std::vector& s newFilter.emplace_back(newFilterData); } - const unsigned count = newFilter.size(); + const size_t count = newFilter.size(); bool multipleElements = false; switch (count) // setting multipleElements; @@ -181,7 +181,7 @@ void CSVFilter::EditWidget::createFilterRequest(const std::vector& s ss << orAnd << oldContent.toUtf8().constData() << ','; } - for (unsigned i = 0; i < count; ++i) + for (size_t i = 0; i < count; ++i) { ss << generateFilter(newFilter[i], filterType); @@ -221,13 +221,13 @@ void CSVFilter::EditWidget::createFilterRequest(const std::vector& s std::string CSVFilter::EditWidget::generateFilter(const FilterData& filterData, FilterType filterType) const { - const unsigned columns = filterData.columns.size(); + const size_t columns = filterData.columns.size(); bool multipleColumns = false; switch (columns) { case 0: // empty - return ""; // no column to filter + return {}; // no column to filter case 1: // one column to look for multipleColumns = false; @@ -244,7 +244,7 @@ std::string CSVFilter::EditWidget::generateFilter(const FilterData& filterData, else { Log(Debug::Warning) << "Generating record filter failed."; - return ""; + return {}; } if (filterType == FilterType::String) quotesResolved = '"' + quotesResolved + '"'; @@ -254,7 +254,7 @@ std::string CSVFilter::EditWidget::generateFilter(const FilterData& filterData, if (multipleColumns) { ss << "or("; - for (unsigned i = 0; i < columns; ++i) + for (size_t i = 0; i < columns; ++i) { ss << filterTypeName(filterType) << "(" << '"' << filterData.columns[i] << '"' << ',' << quotesResolved << ')'; diff --git a/apps/opencs/view/render/brushdraw.cpp b/apps/opencs/view/render/brushdraw.cpp index 3f33ae4d1b..ec2a6c4689 100644 --- a/apps/opencs/view/render/brushdraw.cpp +++ b/apps/opencs/view/render/brushdraw.cpp @@ -190,7 +190,7 @@ void CSVRender::BrushDraw::buildCircleGeometry(const float& radius, const osg::V osg::ref_ptr colors(new osg::Vec4Array()); const int amountOfPoints = 128; - const float step((osg::PI * 2.0f) / static_cast(amountOfPoints)); + const float step((osg::PIf * 2.0f) / static_cast(amountOfPoints)); const float brushOutlineHeight(1.0f); osg::Vec4f lineColor(1.0f, 1.0f, 1.0f, 0.6f); diff --git a/apps/opencs/view/render/cellborder.cpp b/apps/opencs/view/render/cellborder.cpp index 704db13e89..49a2ca8fa5 100644 --- a/apps/opencs/view/render/cellborder.cpp +++ b/apps/opencs/view/render/cellborder.cpp @@ -17,13 +17,16 @@ #include "../../model/world/cellcoordinates.hpp" -const int CSVRender::CellBorder::CellSize = ESM::Land::REAL_SIZE; +namespace +{ + constexpr int CellSize = ESM::Land::REAL_SIZE; -/* - The number of vertices per cell border is equal to the number of vertices per edge - minus the duplicated corner vertices. An additional vertex to close the loop is NOT needed. -*/ -const int CSVRender::CellBorder::VertexCount = (ESM::Land::LAND_SIZE * 4) - 4; + /* + The number of vertices per cell border is equal to the number of vertices per edge + minus the duplicated corner vertices. An additional vertex to close the loop is NOT needed. + */ + constexpr unsigned VertexCount = (ESM::Land::LAND_SIZE * 4) - 4; +} CSVRender::CellBorder::CellBorder(osg::Group* cellNode, const CSMWorld::CellCoordinates& coords) : mParentNode(cellNode) @@ -105,7 +108,7 @@ void CSVRender::CellBorder::buildShape(const ESM::Land& esmLand) = new osg::DrawElementsUShort(osg::PrimitiveSet::LINE_STRIP, VertexCount + 1); // Assign one primitive to each vertex. - for (size_t i = 0; i < VertexCount; ++i) + for (unsigned i = 0; i < VertexCount; ++i) primitives->setElement(i, i); // Assign the last primitive to the first vertex to close the loop. diff --git a/apps/opencs/view/render/cellborder.hpp b/apps/opencs/view/render/cellborder.hpp index e1201a1f39..1d10aecf12 100644 --- a/apps/opencs/view/render/cellborder.hpp +++ b/apps/opencs/view/render/cellborder.hpp @@ -34,9 +34,6 @@ namespace CSVRender void buildShape(const ESM::Land& esmLand); private: - static const int CellSize; - static const int VertexCount; - size_t landIndex(int x, int y); float scaleToWorld(int val); diff --git a/apps/opencs/view/render/lighting.cpp b/apps/opencs/view/render/lighting.cpp index 3c5bbb4fb0..9e6a48c678 100644 --- a/apps/opencs/view/render/lighting.cpp +++ b/apps/opencs/view/render/lighting.cpp @@ -27,16 +27,16 @@ public: void apply(osg::Switch& switchNode) override { - constexpr int noIndex = -1; + constexpr unsigned noIndex = static_cast(-1); - int initialIndex = noIndex; + unsigned initialIndex = noIndex; if (!switchNode.getUserValue("initialIndex", initialIndex)) { for (size_t i = 0; i < switchNode.getValueList().size(); ++i) { if (switchNode.getValueList()[i]) { - initialIndex = i; + initialIndex = static_cast(i); break; } } diff --git a/apps/opencs/view/render/objectmarker.cpp b/apps/opencs/view/render/objectmarker.cpp index e21436430f..9737bda5cc 100644 --- a/apps/opencs/view/render/objectmarker.cpp +++ b/apps/opencs/view/render/objectmarker.cpp @@ -203,11 +203,11 @@ namespace CSVRender void ObjectMarker::detachMarker() { - for (std::size_t index = mRootNode->getNumParents(); index > 0;) + for (unsigned index = mRootNode->getNumParents(); index > 0;) mRootNode->getParent(--index)->removeChild(mRootNode); osg::ref_ptr widgetRoot = mMarkerNodes["unitArrows"]->asGroup(); - for (std::size_t index = widgetRoot->getNumChildren(); index > 0;) + for (unsigned index = widgetRoot->getNumChildren(); index > 0;) widgetRoot->getChild(--index)->setNodeMask(Mask_Hidden); } diff --git a/apps/opencs/view/render/pathgrid.cpp b/apps/opencs/view/render/pathgrid.cpp index a8b2c81659..989f5b6b1b 100644 --- a/apps/opencs/view/render/pathgrid.cpp +++ b/apps/opencs/view/render/pathgrid.cpp @@ -306,15 +306,17 @@ namespace CSVRender commands.push(new CSMWorld::RevertCommand(*model, idString)); int parentColumn = mPathgridCollection.findColumnIndex(CSMWorld::Columns::ColumnId_PathgridPoints); - for (int row = source->mPoints.size() - 1; row >= 0; --row) + for (size_t row = source->mPoints.size(); row > 0; --row) { - commands.push(new CSMWorld::DeleteNestedCommand(*model, idString, row, parentColumn)); + commands.push( + new CSMWorld::DeleteNestedCommand(*model, idString, static_cast(row - 1), parentColumn)); } parentColumn = mPathgridCollection.findColumnIndex(CSMWorld::Columns::ColumnId_PathgridEdges); - for (int row = source->mEdges.size() - 1; row >= 0; --row) + for (size_t row = source->mEdges.size(); row > 0; --row) { - commands.push(new CSMWorld::DeleteNestedCommand(*model, idString, row, parentColumn)); + commands.push( + new CSMWorld::DeleteNestedCommand(*model, idString, static_cast(row - 1), parentColumn)); } } } @@ -420,8 +422,8 @@ namespace CSVRender for (size_t edge = 0; edge < source->mEdges.size(); ++edge) { - int adjustment0 = 0; - int adjustment1 = 0; + size_t adjustment0 = 0; + size_t adjustment1 = 0; // Determine necessary adjustment for (const auto point : mSelected) @@ -436,24 +438,24 @@ namespace CSVRender } if (source->mEdges[edge].mV0 > point) - --adjustment0; + ++adjustment0; if (source->mEdges[edge].mV1 > point) - --adjustment1; + ++adjustment1; } if (adjustment0 != 0) { - int adjustedEdge = source->mEdges[edge].mV0 + adjustment0; - commands.push( - new CSMWorld::ModifyCommand(*model, model->index(edge, edge0Column, parent), adjustedEdge)); + int adjustedEdge = static_cast(source->mEdges[edge].mV0 - adjustment0); + commands.push(new CSMWorld::ModifyCommand( + *model, model->index(static_cast(edge), edge0Column, parent), adjustedEdge)); } if (adjustment1 != 0) { - int adjustedEdge = source->mEdges[edge].mV1 + adjustment1; - commands.push( - new CSMWorld::ModifyCommand(*model, model->index(edge, edge1Column, parent), adjustedEdge)); + int adjustedEdge = static_cast(source->mEdges[edge].mV1 - adjustment1); + commands.push(new CSMWorld::ModifyCommand( + *model, model->index(static_cast(edge), edge1Column, parent), adjustedEdge)); } } diff --git a/apps/opencs/view/render/scenewidget.cpp b/apps/opencs/view/render/scenewidget.cpp index 5e8db03cf8..bd1f2c2d30 100644 --- a/apps/opencs/view/render/scenewidget.cpp +++ b/apps/opencs/view/render/scenewidget.cpp @@ -14,8 +14,8 @@ #include #include -#include -#include +#include +#include #include #include diff --git a/apps/opencs/view/render/terrainselection.cpp b/apps/opencs/view/render/terrainselection.cpp index bdeb1a0958..672b35d688 100644 --- a/apps/opencs/view/render/terrainselection.cpp +++ b/apps/opencs/view/render/terrainselection.cpp @@ -112,8 +112,8 @@ void CSVRender::TerrainSelection::update() mGeometry->setVertexArray(vertices); osg::ref_ptr drawArrays = new osg::DrawArrays(osg::PrimitiveSet::LINES); - drawArrays->setCount(vertices->size()); - if (vertices->size() != 0) + drawArrays->setCount(static_cast(vertices->size())); + if (!vertices->empty()) mGeometry->addPrimitiveSet(drawArrays); mSelectionNode->addChild(mGeometry); } diff --git a/apps/opencs/view/widget/scenetooltexturebrush.cpp b/apps/opencs/view/widget/scenetooltexturebrush.cpp index 27d628a384..e8d965334a 100644 --- a/apps/opencs/view/widget/scenetooltexturebrush.cpp +++ b/apps/opencs/view/widget/scenetooltexturebrush.cpp @@ -308,24 +308,27 @@ void CSVWidget::SceneToolTextureBrush::showPanel(const QPoint& position) void CSVWidget::SceneToolTextureBrush::updatePanel() { - mTable->setRowCount(mBrushHistory.size()); + mTable->setRowCount(static_cast(mBrushHistory.size())); - for (int i = mBrushHistory.size() - 1; i >= 0; --i) + for (size_t i = mBrushHistory.size(); i > 0; --i) { CSMWorld::IdCollection& landtexturesCollection = mDocument.getData().getLandTextures(); int landTextureFilename = landtexturesCollection.findColumnIndex(CSMWorld::Columns::ColumnId_Texture); - const int index = landtexturesCollection.searchId(mBrushHistory[i]); + const int index = landtexturesCollection.searchId(mBrushHistory[i - 1]); + const int row = static_cast(i - 1); if (index != -1 && !landtexturesCollection.getRecord(index).isDeleted()) { - mTable->setItem(i, 1, + mTable->setItem(row, 1, new QTableWidgetItem(landtexturesCollection.getData(index, landTextureFilename).value())); - mTable->setItem(i, 0, new QTableWidgetItem(QString::fromStdString(mBrushHistory[i].getRefIdString()))); + mTable->setItem( + row, 0, new QTableWidgetItem(QString::fromStdString(mBrushHistory[i - 1].getRefIdString()))); } else { - mTable->setItem(i, 1, new QTableWidgetItem("Invalid/deleted texture")); - mTable->setItem(i, 0, new QTableWidgetItem(QString::fromStdString(mBrushHistory[i].getRefIdString()))); + mTable->setItem(row, 1, new QTableWidgetItem("Invalid/deleted texture")); + mTable->setItem( + row, 0, new QTableWidgetItem(QString::fromStdString(mBrushHistory[i - 1].getRefIdString()))); } } } diff --git a/apps/opencs/view/world/scripterrortable.cpp b/apps/opencs/view/world/scripterrortable.cpp index 4bd8c3f390..4db785fea4 100644 --- a/apps/opencs/view/world/scripterrortable.cpp +++ b/apps/opencs/view/world/scripterrortable.cpp @@ -28,7 +28,7 @@ void CSVWorld::ScriptErrorTable::report(const std::string& message, const Compil addMessage(stream.str(), type == Compiler::ErrorHandler::WarningMessage ? CSMDoc::Message::Severity_Warning : CSMDoc::Message::Severity_Error, - loc.mLine, loc.mColumn - loc.mLiteral.length()); + loc.mLine, loc.mColumn - static_cast(loc.mLiteral.length())); } void CSVWorld::ScriptErrorTable::report(const std::string& message, Type type) diff --git a/apps/openmw/CMakeLists.txt b/apps/openmw/CMakeLists.txt index 9a5669c870..8570d9df60 100644 --- a/apps/openmw/CMakeLists.txt +++ b/apps/openmw/CMakeLists.txt @@ -170,8 +170,8 @@ target_link_libraries(openmw-lib ${MyGUI_LIBRARIES} SDL2::SDL2 ${RecastNavigation_LIBRARIES} - "osg-ffmpeg-videoplayer" - "oics" + osg-ffmpeg-videoplayer + oics components ) diff --git a/apps/openmw/engine.cpp b/apps/openmw/engine.cpp index e851fbe254..cabcf3e883 100644 --- a/apps/openmw/engine.cpp +++ b/apps/openmw/engine.cpp @@ -319,7 +319,7 @@ bool OMW::Engine::frame(unsigned frameNumber, float frametime) const bool reportResource = stats->collectStats("resource"); if (reportResource) - stats->setAttribute(frameNumber, "UnrefQueue", mUnrefQueue->getSize()); + stats->setAttribute(frameNumber, "UnrefQueue", static_cast(mUnrefQueue->getSize())); mUnrefQueue->flush(*mWorkQueue); @@ -329,8 +329,8 @@ bool OMW::Engine::frame(unsigned frameNumber, float frametime) mResourceSystem->reportStats(frameNumber, stats); - stats->setAttribute(frameNumber, "WorkQueue", mWorkQueue->getNumItems()); - stats->setAttribute(frameNumber, "WorkThread", mWorkQueue->getNumActiveThreads()); + stats->setAttribute(frameNumber, "WorkQueue", static_cast(mWorkQueue->getNumItems())); + stats->setAttribute(frameNumber, "WorkThread", static_cast(mWorkQueue->getNumActiveThreads())); mMechanicsManager->reportStats(frameNumber, *stats); mWorld->reportStats(frameNumber, *stats); @@ -740,7 +740,8 @@ void OMW::Engine::prepareEngine() mResourceSystem->getSceneManager()->setUnRefImageDataAfterApply( false); // keep to Off for now to allow better state sharing mResourceSystem->getSceneManager()->setFilterSettings(Settings::general().mTextureMagFilter, - Settings::general().mTextureMinFilter, Settings::general().mTextureMipmap, Settings::general().mAnisotropy); + Settings::general().mTextureMinFilter, Settings::general().mTextureMipmap, + static_cast(Settings::general().mAnisotropy)); mEnvironment.setResourceSystem(*mResourceSystem); mWorkQueue = new SceneUtil::WorkQueue(Settings::cells().mPreloadNumThreads); @@ -1039,7 +1040,7 @@ void OMW::Engine::go() const unsigned frameNumber = mViewer->getFrameStamp()->getFrameNumber(); - if (!frame(frameNumber, dt)) + if (!frame(frameNumber, static_cast(dt))) { std::this_thread::sleep_for(std::chrono::milliseconds(5)); continue; diff --git a/apps/openmw/mwbase/dialoguemanager.hpp b/apps/openmw/mwbase/dialoguemanager.hpp index e4c60e596d..17645ff5e5 100644 --- a/apps/openmw/mwbase/dialoguemanager.hpp +++ b/apps/openmw/mwbase/dialoguemanager.hpp @@ -100,7 +100,7 @@ namespace MWBase /// @note Controlled by an option, gets discarded when dialogue ends by default virtual void applyBarterDispositionChange(int delta) = 0; - virtual int countSavedGameRecords() const = 0; + virtual size_t countSavedGameRecords() const = 0; virtual void write(ESM::ESMWriter& writer, Loading::Listener& progress) const = 0; diff --git a/apps/openmw/mwbase/inputmanager.hpp b/apps/openmw/mwbase/inputmanager.hpp index 2861ab88e9..400189c7ab 100644 --- a/apps/openmw/mwbase/inputmanager.hpp +++ b/apps/openmw/mwbase/inputmanager.hpp @@ -86,7 +86,7 @@ namespace MWBase virtual std::string getControllerButtonIcon(int button) = 0; virtual std::string getControllerAxisIcon(int axis) = 0; - virtual int countSavedGameRecords() const = 0; + virtual size_t countSavedGameRecords() const = 0; virtual void write(ESM::ESMWriter& writer, Loading::Listener& progress) = 0; virtual void readRecord(ESM::ESMReader& reader, uint32_t type) = 0; diff --git a/apps/openmw/mwbase/journal.hpp b/apps/openmw/mwbase/journal.hpp index 50be0959bf..9e73d03709 100644 --- a/apps/openmw/mwbase/journal.hpp +++ b/apps/openmw/mwbase/journal.hpp @@ -74,7 +74,7 @@ namespace MWBase virtual const TQuestContainer& getQuests() const = 0; - virtual int countSavedGameRecords() const = 0; + virtual size_t countSavedGameRecords() const = 0; virtual void write(ESM::ESMWriter& writer, Loading::Listener& progress) const = 0; diff --git a/apps/openmw/mwbase/luamanager.hpp b/apps/openmw/mwbase/luamanager.hpp index 5772c555a3..f44e680cd2 100644 --- a/apps/openmw/mwbase/luamanager.hpp +++ b/apps/openmw/mwbase/luamanager.hpp @@ -141,7 +141,7 @@ namespace MWBase virtual void setupPlayer(const MWWorld::Ptr&) = 0; // Saving - int countSavedGameRecords() const { return 1; } + size_t countSavedGameRecords() const { return 1; } virtual void write(ESM::ESMWriter& writer, Loading::Listener& progress) = 0; virtual void saveLocalScripts(const MWWorld::Ptr& ptr, ESM::LuaScripts& data) = 0; diff --git a/apps/openmw/mwbase/mechanicsmanager.hpp b/apps/openmw/mwbase/mechanicsmanager.hpp index 091b851261..59cf81f71d 100644 --- a/apps/openmw/mwbase/mechanicsmanager.hpp +++ b/apps/openmw/mwbase/mechanicsmanager.hpp @@ -245,7 +245,7 @@ namespace MWBase virtual void playerLoaded() = 0; - virtual int countSavedGameRecords() const = 0; + virtual size_t countSavedGameRecords() const = 0; virtual void write(ESM::ESMWriter& writer, Loading::Listener& listener) const = 0; diff --git a/apps/openmw/mwbase/windowmanager.hpp b/apps/openmw/mwbase/windowmanager.hpp index 2e0e9a7b7d..8385e85b5f 100644 --- a/apps/openmw/mwbase/windowmanager.hpp +++ b/apps/openmw/mwbase/windowmanager.hpp @@ -311,7 +311,7 @@ namespace MWBase virtual void write(ESM::ESMWriter& writer, Loading::Listener& progress) = 0; virtual void readRecord(ESM::ESMReader& reader, uint32_t type) = 0; - virtual int countSavedGameRecords() const = 0; + virtual size_t countSavedGameRecords() const = 0; /// Does the current stack of GUI-windows permit saving? virtual bool isSavingAllowed() const = 0; @@ -391,7 +391,7 @@ namespace MWBase virtual int getControllerMenuHeight() = 0; /// Cycle to the next window to receive controller events virtual void cycleActiveControllerWindow(bool next) = 0; - virtual void setActiveControllerWindow(MWGui::GuiMode mode, int activeIndex) = 0; + virtual void setActiveControllerWindow(MWGui::GuiMode mode, size_t activeIndex) = 0; virtual bool getControllerTooltipVisible() const = 0; virtual void setControllerTooltipVisible(bool visible) = 0; virtual bool getControllerTooltipEnabled() const = 0; diff --git a/apps/openmw/mwbase/world.hpp b/apps/openmw/mwbase/world.hpp index e67e21c175..fe2803a28c 100644 --- a/apps/openmw/mwbase/world.hpp +++ b/apps/openmw/mwbase/world.hpp @@ -120,7 +120,7 @@ namespace MWBase World() {} - virtual ~World() {} + virtual ~World() = default; virtual void setRandomSeed(uint32_t seed) = 0; ///< \param seed The seed used when starting a new game. @@ -130,8 +130,8 @@ namespace MWBase virtual void clear() = 0; - virtual int countSavedGameRecords() const = 0; - virtual int countSavedGameCells() const = 0; + virtual size_t countSavedGameRecords() const = 0; + virtual size_t countSavedGameCells() const = 0; virtual void write(ESM::ESMWriter& writer, Loading::Listener& listener) const = 0; diff --git a/apps/openmw/mwclass/armor.cpp b/apps/openmw/mwclass/armor.cpp index b45e0b25b9..7e0afb0214 100644 --- a/apps/openmw/mwclass/armor.cpp +++ b/apps/openmw/mwclass/armor.cpp @@ -339,7 +339,7 @@ namespace MWClass ->mValue.getInteger(); if (ref->mBase->mData.mWeight == 0) - return ref->mBase->mData.mArmor; + return static_cast(ref->mBase->mData.mArmor); else return ref->mBase->mData.mArmor * armorSkill / static_cast(iBaseArmorSkill); } diff --git a/apps/openmw/mwclass/clothing.cpp b/apps/openmw/mwclass/clothing.cpp index 32f00b4110..83309af272 100644 --- a/apps/openmw/mwclass/clothing.cpp +++ b/apps/openmw/mwclass/clothing.cpp @@ -190,7 +190,7 @@ namespace MWClass ESM::Clothing newItem = *ref->mBase; newItem.mId = ESM::RefId(); newItem.mName = newName; - newItem.mData.mEnchant = enchCharge; + newItem.mData.mEnchant = static_cast(enchCharge); newItem.mEnchant = enchId; const ESM::Clothing* record = MWBase::Environment::get().getESMStore()->insert(newItem); return record->mId; diff --git a/apps/openmw/mwclass/creature.cpp b/apps/openmw/mwclass/creature.cpp index e847ba9d0e..c2c930ce1b 100644 --- a/apps/openmw/mwclass/creature.cpp +++ b/apps/openmw/mwclass/creature.cpp @@ -132,7 +132,8 @@ namespace MWClass // creature stats for (size_t i = 0; i < ref->mBase->mData.mAttributes.size(); ++i) - data->mCreatureStats.setAttribute(ESM::Attribute::indexToRefId(i), ref->mBase->mData.mAttributes[i]); + data->mCreatureStats.setAttribute(ESM::Attribute::indexToRefId(static_cast(i)), + static_cast(ref->mBase->mData.mAttributes[i])); data->mCreatureStats.setHealth(static_cast(ref->mBase->mData.mHealth)); data->mCreatureStats.setMagicka(static_cast(ref->mBase->mData.mMana)); data->mCreatureStats.setFatigue(static_cast(ref->mBase->mData.mFatigue)); @@ -757,11 +758,11 @@ namespace MWClass switch (skillRecord->mData.mSpecialization) { case ESM::Class::Combat: - return ref->mBase->mData.mCombat; + return static_cast(ref->mBase->mData.mCombat); case ESM::Class::Magic: - return ref->mBase->mData.mMagic; + return static_cast(ref->mBase->mData.mMagic); case ESM::Class::Stealth: - return ref->mBase->mData.mStealth; + return static_cast(ref->mBase->mData.mStealth); default: throw std::runtime_error("invalid specialisation"); } @@ -887,7 +888,7 @@ namespace MWClass void Creature::setBaseAISetting(const ESM::RefId& id, MWMechanics::AiSetting setting, int value) const { - MWMechanics::setBaseAISetting(id, setting, value); + MWMechanics::setBaseAISetting(id, setting, static_cast(value)); } void Creature::modifyBaseInventory(const ESM::RefId& actorId, const ESM::RefId& itemId, int amount) const diff --git a/apps/openmw/mwclass/door.cpp b/apps/openmw/mwclass/door.cpp index d6df1bba5d..3de05a9296 100644 --- a/apps/openmw/mwclass/door.cpp +++ b/apps/openmw/mwclass/door.cpp @@ -215,14 +215,14 @@ namespace MWClass MWBase::Environment::get().getSoundManager()->fadeOutSound3D(ptr, closeSound, 0.5f); // Doors rotate at 90 degrees per second, so start the sound at // where it would be at the current rotation. - float offset = doorRot / (osg::PI * 0.5f); + float offset = doorRot / (osg::PIf * 0.5f); action->setSoundOffset(offset); action->setSound(openSound); } else { MWBase::Environment::get().getSoundManager()->fadeOutSound3D(ptr, openSound, 0.5f); - float offset = 1.0f - doorRot / (osg::PI * 0.5f); + float offset = 1.0f - doorRot / (osg::PIf * 0.5f); action->setSoundOffset(std::max(offset, 0.0f)); action->setSound(closeSound); } diff --git a/apps/openmw/mwclass/ingredient.cpp b/apps/openmw/mwclass/ingredient.cpp index 94a1e8cc89..235d3b14b7 100644 --- a/apps/openmw/mwclass/ingredient.cpp +++ b/apps/openmw/mwclass/ingredient.cpp @@ -134,7 +134,7 @@ namespace MWClass if (ref->mBase->mData.mEffectID[i] < 0) continue; MWGui::Widgets::SpellEffectParams params; - params.mEffectID = ref->mBase->mData.mEffectID[i]; + params.mEffectID = static_cast(ref->mBase->mData.mEffectID[i]); params.mAttribute = ESM::Attribute::indexToRefId(ref->mBase->mData.mAttributes[i]); params.mSkill = ESM::Skill::indexToRefId(ref->mBase->mData.mSkills[i]); params.mKnown = alchemySkill >= fWortChanceValue * (i + 1); diff --git a/apps/openmw/mwclass/misc.cpp b/apps/openmw/mwclass/misc.cpp index cd97ecf216..2b42bb7df5 100644 --- a/apps/openmw/mwclass/misc.cpp +++ b/apps/openmw/mwclass/misc.cpp @@ -90,13 +90,13 @@ namespace MWClass if (Settings::game().mRebalanceSoulGemValues) { // use the 'soul gem value rebalance' formula from the Morrowind Code Patch - float soulValue = 0.0001 * pow(soul, 3) + 2 * soul; + double soulValue = 0.0001 * std::pow(soul, 3) + 2 * soul; // for Azura's star add the unfilled value if (ptr.getCellRef().getRefId() == "Misc_SoulGem_Azura") - value += soulValue; + value += static_cast(soulValue); else - value = soulValue; + value = static_cast(soulValue); } else value *= soul; diff --git a/apps/openmw/mwclass/npc.cpp b/apps/openmw/mwclass/npc.cpp index 3295c6586c..fd62765e61 100644 --- a/apps/openmw/mwclass/npc.cpp +++ b/apps/openmw/mwclass/npc.cpp @@ -85,24 +85,24 @@ namespace const NpcParts npcParts; - int is_even(double d) + bool isEven(double d) { double intPart; - modf(d / 2.0, &intPart); + std::modf(d / 2.0, &intPart); return 2.0 * intPart == d; } - int round_ieee_754(double d) + float round_ieee_754(float f) { - double i = floor(d); - d -= i; - if (d < 0.5) - return static_cast(i); - if (d > 0.5) - return static_cast(i) + 1; - if (is_even(i)) - return static_cast(i); - return static_cast(i) + 1; + float i = std::floor(f); + f -= i; + if (f < 0.5) + return i; + if (f > 0.5) + return i + 1.f; + if (isEven(i)) + return i; + return i + 1.f; } void autoCalculateAttributes(const ESM::NPC* npc, MWMechanics::CreatureStats& creatureStats) @@ -115,7 +115,8 @@ namespace const auto& attributes = MWBase::Environment::get().getESMStore()->get(); int level = creatureStats.getLevel(); for (const ESM::Attribute& attribute : attributes) - creatureStats.setAttribute(attribute.mId, race->mData.getAttribute(attribute.mId, male)); + creatureStats.setAttribute( + attribute.mId, static_cast(race->mData.getAttribute(attribute.mId, male))); // class bonus const ESM::Class* npcClass = MWBase::Environment::get().getESMStore()->get().find(npc->mClass); @@ -155,7 +156,7 @@ namespace creatureStats.setAttribute(attribute.mId, std::min( round_ieee_754(creatureStats.getAttribute(attribute.mId).getBase() + (level - 1) * modifierSum), - 100)); + 100.f)); } // initial health @@ -248,7 +249,7 @@ namespace npcStats.getSkill(skill.mId).setBase( std::min(round_ieee_754(npcStats.getSkill(skill.mId).getBase() + 5 + raceBonus + specBonus + (int(level) - 1) * (majorMultiplier + specMultiplier)), - 100)); // Must gracefully handle level 0 + 100.f)); // Must gracefully handle level 0 } if (!spellsInitialised) @@ -334,10 +335,12 @@ namespace MWClass gold = ref->mBase->mNpdt.mGold; for (size_t i = 0; i < ref->mBase->mNpdt.mSkills.size(); ++i) - data->mNpcStats.getSkill(ESM::Skill::indexToRefId(i)).setBase(ref->mBase->mNpdt.mSkills[i]); + data->mNpcStats.getSkill(ESM::Skill::indexToRefId(static_cast(i))) + .setBase(ref->mBase->mNpdt.mSkills[i]); for (size_t i = 0; i < ref->mBase->mNpdt.mAttributes.size(); ++i) - data->mNpcStats.setAttribute(ESM::Attribute::indexToRefId(i), ref->mBase->mNpdt.mAttributes[i]); + data->mNpcStats.setAttribute( + ESM::Attribute::indexToRefId(static_cast(i)), ref->mBase->mNpdt.mAttributes[i]); data->mNpcStats.setHealth(ref->mBase->mNpdt.mHealth); data->mNpcStats.setMagicka(ref->mBase->mNpdt.mMana); @@ -589,7 +592,7 @@ namespace MWClass if (!weapon.isEmpty()) weapskill = weapon.getClass().getEquipmentSkill(weapon); - float hitchance = MWMechanics::getHitChance(ptr, victim, getSkill(ptr, weapskill)); + float hitchance = MWMechanics::getHitChance(ptr, victim, static_cast(getSkill(ptr, weapskill))); return Misc::Rng::roll0to99(world->getPrng()) < hitchance; } @@ -1405,7 +1408,7 @@ namespace MWClass void Npc::setBaseAISetting(const ESM::RefId& id, MWMechanics::AiSetting setting, int value) const { - MWMechanics::setBaseAISetting(id, setting, value); + MWMechanics::setBaseAISetting(id, setting, static_cast(value)); } void Npc::modifyBaseInventory(const ESM::RefId& actorId, const ESM::RefId& itemId, int amount) const diff --git a/apps/openmw/mwclass/weapon.cpp b/apps/openmw/mwclass/weapon.cpp index 197c3ff1b3..475505dca1 100644 --- a/apps/openmw/mwclass/weapon.cpp +++ b/apps/openmw/mwclass/weapon.cpp @@ -261,7 +261,7 @@ namespace MWClass ESM::Weapon newItem = *ref->mBase; newItem.mId = ESM::RefId(); newItem.mName = newName; - newItem.mData.mEnchant = enchCharge; + newItem.mData.mEnchant = static_cast(enchCharge); newItem.mEnchant = enchId; newItem.mData.mFlags |= ESM::Weapon::Magical; const ESM::Weapon* record = MWBase::Environment::get().getESMStore()->insert(newItem); diff --git a/apps/openmw/mwdialogue/dialoguemanagerimp.cpp b/apps/openmw/mwdialogue/dialoguemanagerimp.cpp index f57519f29d..20da682208 100644 --- a/apps/openmw/mwdialogue/dialoguemanagerimp.cpp +++ b/apps/openmw/mwdialogue/dialoguemanagerimp.cpp @@ -441,8 +441,9 @@ namespace MWDialogue // Get the sum of disposition effects minus charm (shouldn't be made permanent) npcStats.setBaseDisposition(0); - int zero = MWBase::Environment::get().getMechanicsManager()->getDerivedDisposition(mActor, false) - - npcStats.getMagicEffects().getOrDefault(ESM::MagicEffect::Charm).getMagnitude(); + int zero = static_cast( + MWBase::Environment::get().getMechanicsManager()->getDerivedDisposition(mActor, false) + - npcStats.getMagicEffects().getOrDefault(ESM::MagicEffect::Charm).getMagnitude()); // Clamp new permanent disposition to avoid negative derived disposition (can be caused by intimidate) int disposition = std::clamp(mOriginalDisposition + mPermanentDispositionChange, -zero, 100 - zero); @@ -652,7 +653,7 @@ namespace MWDialogue return info != nullptr; } - int DialogueManager::countSavedGameRecords() const + size_t DialogueManager::countSavedGameRecords() const { return 1; // known topics } diff --git a/apps/openmw/mwdialogue/dialoguemanagerimp.hpp b/apps/openmw/mwdialogue/dialoguemanagerimp.hpp index a735c57fef..ce3f3d1bda 100644 --- a/apps/openmw/mwdialogue/dialoguemanagerimp.hpp +++ b/apps/openmw/mwdialogue/dialoguemanagerimp.hpp @@ -112,7 +112,7 @@ namespace MWDialogue /// @note Controlled by an option, gets discarded when dialogue ends by default void applyBarterDispositionChange(int delta) override; - int countSavedGameRecords() const override; + size_t countSavedGameRecords() const override; void write(ESM::ESMWriter& writer, Loading::Listener& progress) const override; diff --git a/apps/openmw/mwdialogue/filter.cpp b/apps/openmw/mwdialogue/filter.cpp index a5a3be85f9..4b42d67a03 100644 --- a/apps/openmw/mwdialogue/filter.cpp +++ b/apps/openmw/mwdialogue/filter.cpp @@ -400,7 +400,7 @@ int MWDialogue::Filter::getSelectStructInteger(const SelectWrapper& select) cons case ESM::DialogueCondition::Function_PcLuck: { ESM::RefId attribute = ESM::Attribute::indexToRefId(select.getArgument()); - return player.getClass().getCreatureStats(player).getAttribute(attribute).getModified(); + return static_cast(player.getClass().getCreatureStats(player).getAttribute(attribute).getModified()); } case ESM::DialogueCondition::Function_PcBlock: case ESM::DialogueCondition::Function_PcArmorer: diff --git a/apps/openmw/mwdialogue/journalimp.cpp b/apps/openmw/mwdialogue/journalimp.cpp index c607c5aa25..c318dc6644 100644 --- a/apps/openmw/mwdialogue/journalimp.cpp +++ b/apps/openmw/mwdialogue/journalimp.cpp @@ -151,7 +151,7 @@ namespace MWDialogue return iter->second.getIndex(); } - int Journal::countSavedGameRecords() const + size_t Journal::countSavedGameRecords() const { std::size_t count = mQuests.size(); @@ -163,7 +163,7 @@ namespace MWDialogue for (const auto& [_, topic] : mTopics) count += topic.size(); - return static_cast(count); + return count; } void Journal::write(ESM::ESMWriter& writer, Loading::Listener& progress) const diff --git a/apps/openmw/mwdialogue/journalimp.hpp b/apps/openmw/mwdialogue/journalimp.hpp index 9531652222..58c1f94371 100644 --- a/apps/openmw/mwdialogue/journalimp.hpp +++ b/apps/openmw/mwdialogue/journalimp.hpp @@ -53,7 +53,7 @@ namespace MWDialogue const TQuestContainer& getQuests() const override { return mQuests; } - int countSavedGameRecords() const override; + size_t countSavedGameRecords() const override; void write(ESM::ESMWriter& writer, Loading::Listener& progress) const override; diff --git a/apps/openmw/mwgui/alchemywindow.cpp b/apps/openmw/mwgui/alchemywindow.cpp index 62cc1d0854..da7e1dff78 100644 --- a/apps/openmw/mwgui/alchemywindow.cpp +++ b/apps/openmw/mwgui/alchemywindow.cpp @@ -216,7 +216,7 @@ namespace MWGui std::set itemNames, itemEffects; for (size_t i = 0; i < mModel->getItemCount(); ++i) { - MWWorld::Ptr item = mModel->getItem(i).mBase; + MWWorld::Ptr item = mModel->getItem(static_cast(i)).mBase; if (item.getType() != ESM::Ingredient::sRecordId) continue; @@ -376,7 +376,7 @@ namespace MWGui mItemSelectionDialog->eventDialogCanceled += MyGUI::newDelegate(this, &AlchemyWindow::onItemCancel); mItemSelectionDialog->setVisible(true); mItemSelectionDialog->openContainer(MWMechanics::getPlayer()); - mItemSelectionDialog->getSortModel()->setApparatusTypeFilter(i); + mItemSelectionDialog->getSortModel()->setApparatusTypeFilter(static_cast(i)); mItemSelectionDialog->setFilter(SortFilterItemModel::Filter_OnlyAlchemyTools); } else @@ -459,7 +459,7 @@ namespace MWGui for (const MWMechanics::EffectKey& effectKey : effectIds) { Widgets::SpellEffectParams params; - params.mEffectID = effectKey.mId; + params.mEffectID = static_cast(effectKey.mId); const ESM::MagicEffect* magicEffect = MWBase::Environment::get().getESMStore()->get().find(effectKey.mId); if (magicEffect->mData.mFlags & ESM::MagicEffect::TargetSkill) @@ -589,11 +589,11 @@ namespace MWGui if (arg.button == SDL_CONTROLLER_BUTTON_B) { // Remove active ingredients or close the window, starting with right-most slot. - for (int i = mIngredients.size() - 1; i >= 0; --i) + for (size_t i = mIngredients.size(); i > 0; --i) { - if (mIngredients[i]->isUserString("ToolTipType")) + if (mIngredients[i - 1]->isUserString("ToolTipType")) { - onIngredientSelected(mIngredients[i]); + onIngredientSelected(mIngredients[i - 1]); return true; } } diff --git a/apps/openmw/mwgui/bookpage.cpp b/apps/openmw/mwgui/bookpage.cpp index 008c935c73..d2b9ea55f8 100644 --- a/apps/openmw/mwgui/bookpage.cpp +++ b/apps/openmw/mwgui/bookpage.cpp @@ -12,28 +12,108 @@ #include #include +namespace +{ + std::optional getGlyphInfo(MyGUI::IFont* font, MyGUI::Char ch) + { + const MyGUI::GlyphInfo* gi = font->getGlyphInfo(ch); + if (!gi) + return {}; + const float scale = font->getDefaultHeight() / static_cast(Settings::gui().mFontSize); + MyGUI::GlyphInfo info = *gi; + info.bearingX /= scale; + info.bearingY /= scale; + info.width /= scale; + info.height /= scale; + info.advance /= scale; + return info; + } + + bool ucsLineBreak(Utf8Stream::UnicodeChar codePoint) + { + return codePoint == '\n'; + } + + bool ucsCarriageReturn(Utf8Stream::UnicodeChar codePoint) + { + return codePoint == '\r'; + } + + // Normal no-break space (0x00A0) is ignored here + // because Morrowind compatibility requires us to render its glyph + bool ucsSpace(Utf8Stream::UnicodeChar codePoint) + { + switch (codePoint) + { + case 0x0020: // SPACE + case 0x1680: // OGHAM SPACE MARK + case 0x180E: // MONGOLIAN VOWEL SEPARATOR + case 0x2000: // EN QUAD + case 0x2001: // EM QUAD + case 0x2002: // EN SPACE + case 0x2003: // EM SPACE + case 0x2004: // THREE-PER-EM SPACE + case 0x2005: // FOUR-PER-EM SPACE + case 0x2006: // SIX-PER-EM SPACE + case 0x2007: // FIGURE SPACE + case 0x2008: // PUNCTUATION SPACE + case 0x2009: // THIN SPACE + case 0x200A: // HAIR SPACE + case 0x200B: // ZERO WIDTH SPACE + case 0x202F: // NARROW NO-BREAK SPACE + case 0x205F: // MEDIUM MATHEMATICAL SPACE + case 0x3000: // IDEOGRAPHIC SPACE + case 0xFEFF: // ZERO WIDTH NO-BREAK SPACE + return true; + default: + return false; + } + } + + // No-break spaces (0x00A0, 0x202F, 0xFEFF - normal, narrow, zero width) + // are ignored here for obvious reasons + // Figure space (0x2007) is not a breaking space either + bool ucsBreakingSpace(int codePoint) + { + switch (codePoint) + { + case 0x0020: // SPACE + case 0x1680: // OGHAM SPACE MARK + case 0x180E: // MONGOLIAN VOWEL SEPARATOR + case 0x2000: // EN QUAD + case 0x2001: // EM QUAD + case 0x2002: // EN SPACE + case 0x2003: // EM SPACE + case 0x2004: // THREE-PER-EM SPACE + case 0x2005: // FOUR-PER-EM SPACE + case 0x2006: // SIX-PER-EM SPACE + case 0x2008: // PUNCTUATION SPACE + case 0x2009: // THIN SPACE + case 0x200A: // HAIR SPACE + case 0x200B: // ZERO WIDTH SPACE + case 0x205F: // MEDIUM MATHEMATICAL SPACE + case 0x3000: // IDEOGRAPHIC SPACE + return true; + default: + return false; + } + } +} + namespace MWGui { struct TypesetBookImpl; class PageDisplay; class BookPageImpl; - static bool ucsSpace(int codePoint); - static bool ucsLineBreak(int codePoint); - static bool ucsCarriageReturn(int codePoint); - static bool ucsBreakingSpace(int codePoint); - struct BookTypesetter::Style { - virtual ~Style() {} + virtual ~Style() = default; }; struct TypesetBookImpl : TypesetBook { - typedef std::vector Content; - typedef std::list Contents; - typedef Utf8Stream::Point Utf8Point; - typedef std::pair Range; + typedef std::pair Range; struct StyleImpl : BookTypesetter::Style { @@ -44,29 +124,28 @@ namespace MWGui InteractiveId mInteractiveId; bool match(MyGUI::IFont* tstFont, const MyGUI::Colour& tstHotColour, const MyGUI::Colour& tstActiveColour, - const MyGUI::Colour& tstNormalColour, intptr_t tstInteractiveId) + const MyGUI::Colour& tstNormalColour, InteractiveId tstInteractiveId) const { return (mFont == tstFont) - && partal_match(tstHotColour, tstActiveColour, tstNormalColour, tstInteractiveId); + && partialMatch(tstHotColour, tstActiveColour, tstNormalColour, tstInteractiveId); } bool match(std::string_view tstFont, const MyGUI::Colour& tstHotColour, - const MyGUI::Colour& tstActiveColour, const MyGUI::Colour& tstNormalColour, intptr_t tstInteractiveId) + const MyGUI::Colour& tstActiveColour, const MyGUI::Colour& tstNormalColour, + InteractiveId tstInteractiveId) const { return (mFont->getResourceName() == tstFont) - && partal_match(tstHotColour, tstActiveColour, tstNormalColour, tstInteractiveId); + && partialMatch(tstHotColour, tstActiveColour, tstNormalColour, tstInteractiveId); } - bool partal_match(const MyGUI::Colour& tstHotColour, const MyGUI::Colour& tstActiveColour, - const MyGUI::Colour& tstNormalColour, intptr_t tstInteractiveId) + bool partialMatch(const MyGUI::Colour& tstHotColour, const MyGUI::Colour& tstActiveColour, + const MyGUI::Colour& tstNormalColour, InteractiveId tstInteractiveId) const { return (mHotColour == tstHotColour) && (mActiveColour == tstActiveColour) && (mNormalColour == tstNormalColour) && (mInteractiveId == tstInteractiveId); } }; - typedef std::list Styles; - struct Run { StyleImpl* mStyle; @@ -75,19 +154,15 @@ namespace MWGui int mPrintableChars; }; - typedef std::vector Runs; - struct Line { - Runs mRuns; + std::vector mRuns; MyGUI::IntRect mRect; }; - typedef std::vector Lines; - struct Section { - Lines mLines; + std::vector mLines; MyGUI::IntRect mRect; }; @@ -97,12 +172,10 @@ namespace MWGui // A page is basically a "window" into a portion of the source text, similar to a ScrollView. typedef std::pair Page; - typedef std::vector Pages; - - Pages mPages; + std::vector mPages; Sections mSections; - Contents mContents; - Styles mStyles; + std::list mContents; + std::list mStyles; MyGUI::IntRect mRect; void setColour(size_t section, size_t line, size_t run, const MyGUI::Colour& colour) const override @@ -117,16 +190,16 @@ namespace MWGui mSections[section].mLines[line].mRuns[run].mStyle->mNormalColour = colour; } - virtual ~TypesetBookImpl() {} + virtual ~TypesetBookImpl() = default; - Range addContent(const BookTypesetter::Utf8Span& text) + Range addContent(std::string_view text) { - Contents::iterator i = mContents.insert(mContents.end(), Content(text.first, text.second)); + Content& content = mContents.emplace_back(text.begin(), text.end()); - if (i->empty()) - return Range(Utf8Point(nullptr), Utf8Point(nullptr)); + if (content.empty()) + return Range(nullptr, nullptr); - return Range(i->data(), i->data() + i->size()); + return Range(content.data(), content.data() + content.size()); } size_t pageCount() const override { return mPages.size(); } @@ -139,19 +212,19 @@ namespace MWGui template void visitRuns(int top, int bottom, MyGUI::IFont* font, Visitor const& visitor) const { - for (Sections::const_iterator i = mSections.begin(); i != mSections.end(); ++i) + for (const Section& section : mSections) { - if (top >= mRect.bottom || bottom <= i->mRect.top) + if (top >= mRect.bottom || bottom <= section.mRect.top) continue; - - for (Lines::const_iterator j = i->mLines.begin(); j != i->mLines.end(); ++j) + for (const Line& line : section.mLines) { - if (top >= j->mRect.bottom || bottom <= j->mRect.top) + if (top >= line.mRect.bottom || bottom <= line.mRect.top) continue; - - for (Runs::const_iterator k = j->mRuns.begin(); k != j->mRuns.end(); ++k) - if (!font || k->mStyle->mFont == font) - visitor(*i, *j, *k); + for (const Run& run : line.mRuns) + { + if (!font || run.mStyle->mFont == font) + visitor(section, line, run); + } } } } @@ -192,26 +265,26 @@ namespace MWGui StyleImpl* hitTest(int left, int top) const { - for (Sections::const_iterator i = mSections.begin(); i != mSections.end(); ++i) + for (const Section& section : mSections) { - if (top < i->mRect.top || top >= i->mRect.bottom) + if (top < section.mRect.top || top >= section.mRect.bottom) continue; - int left1 = left - i->mRect.left; + int left1 = left - section.mRect.left; - for (Lines::const_iterator j = i->mLines.begin(); j != i->mLines.end(); ++j) + for (const Line& line : section.mLines) { - if (top < j->mRect.top || top >= j->mRect.bottom) + if (top < line.mRect.top || top >= line.mRect.bottom) continue; - int left2 = left1 - j->mRect.left; + int left2 = left1 - line.mRect.left; - for (Runs::const_iterator k = j->mRuns.begin(); k != j->mRuns.end(); ++k) + for (const Run& run : line.mRuns) { - if (left2 < k->mLeft || left2 >= k->mRight) + if (left2 < run.mLeft || left2 >= run.mRight) continue; - return k->mStyle; + return run.mStyle; } } } @@ -221,9 +294,9 @@ namespace MWGui MyGUI::IFont* affectedFont(StyleImpl* style) { - for (Styles::iterator i = mStyles.begin(); i != mStyles.end(); ++i) - if (&*i == style) - return i->mFont; + for (const StyleImpl& s : mStyles) + if (&s == style) + return s.mFont; return nullptr; } @@ -248,14 +321,10 @@ namespace MWGui } }; - typedef TypesetBookImpl Book; - typedef std::shared_ptr BookPtr; - typedef std::vector::const_iterator PartialTextConstIterator; - int mPageWidth; int mPageHeight; - BookPtr mBook; + std::shared_ptr mBook; Section* mSection; Line* mLine; Run* mRun; @@ -264,10 +333,10 @@ namespace MWGui std::vector mPartialWhitespace; std::vector mPartialWord; - Book::Content const* mCurrentContent; + TypesetBookImpl::Content const* mCurrentContent; Alignment mCurrentAlignment; - Typesetter(size_t width, size_t height) + Typesetter(int width, int height) : mPageWidth(width) , mPageHeight(height) , mSection(nullptr) @@ -276,12 +345,12 @@ namespace MWGui , mCurrentContent(nullptr) , mCurrentAlignment(AlignLeft) { - mBook = std::make_shared(); + mBook = std::make_shared(); } - virtual ~Typesetter() {} + virtual ~Typesetter() = default; - Style* createStyle(const std::string& fontName, const Colour& fontColour, bool useBookFont) override + Style* createStyle(const std::string& fontName, const MyGUI::Colour& fontColour, bool useBookFont) override { std::string fullFontName; if (fontName.empty()) @@ -292,9 +361,9 @@ namespace MWGui if (useBookFont) fullFontName = "Journalbook " + fullFontName; - for (Styles::iterator i = mBook->mStyles.begin(); i != mBook->mStyles.end(); ++i) - if (i->match(fullFontName, fontColour, fontColour, fontColour, 0)) - return &*i; + for (StyleImpl& style : mBook->mStyles) + if (style.match(fullFontName, fontColour, fontColour, fontColour, 0)) + return &style; MyGUI::IFont* font = MyGUI::FontManager::getInstance().getByName(fullFontName); if (!font) @@ -310,15 +379,15 @@ namespace MWGui return &style; } - Style* createHotStyle(Style* baseStyle, const Colour& normalColour, const Colour& hoverColour, - const Colour& activeColour, InteractiveId id, bool unique) override + Style* createHotStyle(Style* baseStyle, const MyGUI::Colour& normalColour, const MyGUI::Colour& hoverColour, + const MyGUI::Colour& activeColour, InteractiveId id, bool unique) override { StyleImpl* const baseStyleImpl = static_cast(baseStyle); if (!unique) - for (Styles::iterator i = mBook->mStyles.begin(); i != mBook->mStyles.end(); ++i) - if (i->match(baseStyleImpl->mFont, hoverColour, activeColour, normalColour, id)) - return &*i; + for (StyleImpl& style : mBook->mStyles) + if (style.match(baseStyleImpl->mFont, hoverColour, activeColour, normalColour, id)) + return &style; StyleImpl& style = *mBook->mStyles.insert(mBook->mStyles.end(), StyleImpl()); @@ -331,30 +400,30 @@ namespace MWGui return &style; } - void write(Style* style, Utf8Span text) override + void write(Style* style, std::string_view text) override { Range range = mBook->addContent(text); - writeImpl(static_cast(style), range.first, range.second); + writeImpl(static_cast(style), Utf8Stream(range.first, range.second)); } - intptr_t addContent(Utf8Span text, bool select) override + const Content* addContent(std::string_view text, bool select) override { add_partial_text(); - Contents::iterator i = mBook->mContents.insert(mBook->mContents.end(), Content(text.first, text.second)); + Content& content = mBook->mContents.emplace_back(text.begin(), text.end()); if (select) - mCurrentContent = &(*i); + mCurrentContent = &content; - return reinterpret_cast(&(*i)); + return &content; } - void selectContent(intptr_t contentHandle) override + void selectContent(const Content* contentHandle) override { add_partial_text(); - mCurrentContent = reinterpret_cast(contentHandle); + mCurrentContent = contentHandle; } void write(Style* style, size_t begin, size_t end) override @@ -363,10 +432,10 @@ namespace MWGui assert(end <= mCurrentContent->size()); assert(begin <= mCurrentContent->size()); - const Utf8Point contentBegin = mCurrentContent->data() + begin; - const Utf8Point contentEnd = mCurrentContent->data() + end; + const Utf8Stream::Point contentBegin = mCurrentContent->data() + begin; + const Utf8Stream::Point contentEnd = mCurrentContent->data() + end; - writeImpl(static_cast(style), contentBegin, contentEnd); + writeImpl(static_cast(style), Utf8Stream(contentBegin, contentEnd)); } void lineBreak(float margin) override @@ -403,7 +472,7 @@ namespace MWGui mCurrentAlignment = sectionAlignment; } - TypesetBook::Ptr complete() override + std::shared_ptr complete() override { int curPageStart = 0; int curPageStop = 0; @@ -414,26 +483,26 @@ namespace MWGui for (Sections::iterator i = mBook->mSections.begin(); i != mBook->mSections.end(); ++i, ++sa) { // apply alignment to individual lines... - for (Lines::iterator j = i->mLines.begin(); j != i->mLines.end(); ++j) + for (Line& line : i->mLines) { - int width = j->mRect.width(); + int width = line.mRect.width(); int excess = mPageWidth - width; switch (*sa) { default: case AlignLeft: - j->mRect.left = 0; + line.mRect.left = 0; break; case AlignCenter: - j->mRect.left = excess / 2; + line.mRect.left = excess / 2; break; case AlignRight: - j->mRect.left = excess; + line.mRect.left = excess; break; } - j->mRect.right = j->mRect.left + width; + line.mRect.right = line.mRect.left + width; } if (curPageStop == curPageStart) @@ -458,7 +527,7 @@ namespace MWGui // one. assert(curPageStart != curPageStop); - mBook->mPages.push_back(Page(curPageStart, curPageStop)); + mBook->mPages.emplace_back(curPageStart, curPageStop); curPageStart = i->mRect.top; curPageStop = i->mRect.bottom; @@ -470,7 +539,7 @@ namespace MWGui { // The section won't completely fit on the current page. Finish the current page and start a new // one. - mBook->mPages.push_back(Page(curPageStart, curPageStop)); + mBook->mPages.emplace_back(curPageStart, curPageStop); curPageStart = i->mRect.top; curPageStop = i->mRect.bottom; @@ -481,16 +550,16 @@ namespace MWGui { // Adjust to the top of the first line that does not fit on the current page anymore int splitPos = curPageStop; - for (Lines::iterator j = i->mLines.begin(); j != i->mLines.end(); ++j) + for (const Line& line : i->mLines) { - if (j->mRect.bottom > curPageStart + mPageHeight) + if (line.mRect.bottom > curPageStart + mPageHeight) { - splitPos = j->mRect.top; + splitPos = line.mRect.top; break; } } - mBook->mPages.push_back(Page(curPageStart, splitPos)); + mBook->mPages.emplace_back(curPageStart, splitPos); curPageStart = splitPos; curPageStop = splitPos; @@ -501,15 +570,13 @@ namespace MWGui } if (curPageStart != curPageStop) - mBook->mPages.push_back(Page(curPageStart, curPageStop)); + mBook->mPages.emplace_back(curPageStart, curPageStop); return mBook; } - void writeImpl(StyleImpl* style, Utf8Stream::Point begin, Utf8Stream::Point end) + void writeImpl(StyleImpl* style, Utf8Stream&& stream) { - Utf8Stream stream(begin, end); - while (!stream.eof()) { if (ucsLineBreak(stream.peek())) @@ -531,9 +598,9 @@ namespace MWGui while (!stream.eof() && !ucsLineBreak(stream.peek()) && ucsBreakingSpace(stream.peek())) { - MWGui::GlyphInfo info = GlyphInfo(style->mFont, stream.peek()); - if (info.charFound) - spaceWidth += static_cast(info.advance + info.bearingX); + std::optional info = getGlyphInfo(style->mFont, stream.peek()); + if (info) + spaceWidth += static_cast(info->advance + info->bearingX); stream.consume(); } @@ -541,9 +608,9 @@ namespace MWGui while (!stream.eof() && !ucsLineBreak(stream.peek()) && !ucsBreakingSpace(stream.peek())) { - MWGui::GlyphInfo info = GlyphInfo(style->mFont, stream.peek()); - if (info.charFound) - wordWidth += static_cast(info.advance + info.bearingX); + std::optional info = getGlyphInfo(style->mFont, stream.peek()); + if (info) + wordWidth += static_cast(info->advance + info->bearingX); stream.consume(); } @@ -568,10 +635,10 @@ namespace MWGui int spaceWidth = 0; int wordWidth = 0; - for (PartialTextConstIterator i = mPartialWhitespace.begin(); i != mPartialWhitespace.end(); ++i) - spaceWidth += i->mWidth; - for (PartialTextConstIterator i = mPartialWord.begin(); i != mPartialWord.end(); ++i) - wordWidth += i->mWidth; + for (const PartialText& partialText : mPartialWhitespace) + spaceWidth += partialText.mWidth; + for (const PartialText& partialText : mPartialWord) + wordWidth += partialText.mWidth; int left = mLine ? mLine->mRect.right : 0; @@ -583,21 +650,23 @@ namespace MWGui } else { - for (PartialTextConstIterator i = mPartialWhitespace.begin(); i != mPartialWhitespace.end(); ++i) + for (const PartialText& partialText : mPartialWhitespace) { int top = mLine ? mLine->mRect.top : mBook->mRect.bottom; - append_run(i->mStyle, i->mBegin, i->mEnd, 0, left + i->mWidth, top + fontHeight); + appendRun(partialText.mStyle, partialText.mBegin, partialText.mEnd, 0, left + partialText.mWidth, + top + fontHeight); left = mLine->mRect.right; } } - for (PartialTextConstIterator i = mPartialWord.begin(); i != mPartialWord.end(); ++i) + for (const PartialText& partialText : mPartialWord) { int top = mLine ? mLine->mRect.top : mBook->mRect.bottom; - - append_run(i->mStyle, i->mBegin, i->mEnd, i->mEnd - i->mBegin, left + i->mWidth, top + fontHeight); + const int numChars = static_cast(partialText.mEnd - partialText.mBegin); + appendRun(partialText.mStyle, partialText.mBegin, partialText.mEnd, numChars, left + partialText.mWidth, + top + fontHeight); left = mLine->mRect.right; } @@ -606,7 +675,7 @@ namespace MWGui mPartialWord.clear(); } - void append_run(StyleImpl* style, Utf8Stream::Point begin, Utf8Stream::Point end, int pc, int right, int bottom) + void appendRun(StyleImpl* style, Utf8Stream::Point begin, Utf8Stream::Point end, int pc, int right, int bottom) { if (mSection == nullptr) { @@ -664,7 +733,7 @@ namespace MWGui } }; - BookTypesetter::Ptr BookTypesetter::create(int pageWidth, int pageHeight) + std::shared_ptr BookTypesetter::create(int pageWidth, int pageHeight) { return std::make_shared(pageWidth, pageHeight); } @@ -788,34 +857,34 @@ namespace MWGui mCursor.top = mOrigin.top + top; } - void emitGlyph(wchar_t ch) + void emitGlyph(MyGUI::Char ch) { - MWGui::GlyphInfo info = GlyphInfo(mFont, ch); + std::optional info = getGlyphInfo(mFont, ch); - if (!info.charFound) + if (!info) return; MyGUI::FloatRect vr; - vr.left = mCursor.left + info.bearingX; - vr.top = mCursor.top + info.bearingY; - vr.right = vr.left + info.width; - vr.bottom = vr.top + info.height; + vr.left = mCursor.left + info->bearingX; + vr.top = mCursor.top + info->bearingY; + vr.right = vr.left + info->width; + vr.bottom = vr.top + info->height; - MyGUI::FloatRect tr = info.uvRect; + MyGUI::FloatRect tr = info->uvRect; if (mRenderXform.clip(vr, tr)) quad(vr, tr); - mCursor.left += static_cast(info.bearingX + info.advance); + mCursor.left += static_cast(info->bearingX + info->advance); } - void emitSpace(wchar_t ch) + void emitSpace(MyGUI::Char ch) { - MWGui::GlyphInfo info = GlyphInfo(mFont, ch); + std::optional info = getGlyphInfo(mFont, ch); - if (info.charFound) - mCursor.left += static_cast(info.bearingX + info.advance); + if (info) + mCursor.left += static_cast(info->bearingX + info->advance); } private: @@ -849,17 +918,12 @@ namespace MWGui { MYGUI_RTTI_DERIVED(PageDisplay) protected: - typedef TypesetBookImpl::Section Section; - typedef TypesetBookImpl::Line Line; - typedef TypesetBookImpl::Run Run; bool mIsPageReset; size_t mPage; struct TextFormat : ISubWidget { - typedef MyGUI::IFont* Id; - - Id mFont; + MyGUI::IFont* mFont; int mCountVertex; MyGUI::ITexture* mTexture; MyGUI::RenderItem* mRenderItem; @@ -934,16 +998,15 @@ namespace MWGui } public: - typedef TypesetBookImpl::StyleImpl Style; - typedef std::map> ActiveTextFormats; + typedef std::map> ActiveTextFormats; int mViewTop; int mViewBottom; - Style* mFocusItem; + TypesetBookImpl::StyleImpl* mFocusItem; bool mItemActive; MyGUI::MouseButton mLastDown; - std::function mLinkClicked; + std::function mLinkClicked; std::shared_ptr mBook; @@ -989,7 +1052,7 @@ namespace MWGui void onMouseMove(int left, int top) { - Style* hit = nullptr; + TypesetBookImpl::StyleImpl* hit = nullptr; if (auto pos = getAdjustedPos(left, top, true)) if (pos->top <= mViewBottom) hit = mBook->hitTestWithMargin(pos->left, pos->top); @@ -1040,7 +1103,8 @@ namespace MWGui if (pos && mLastDown == id) { - Style* item = pos->top <= mViewBottom ? mBook->hitTestWithMargin(pos->left, pos->top) : nullptr; + TypesetBookImpl::StyleImpl* item + = pos->top <= mViewBottom ? mBook->hitTestWithMargin(pos->left, pos->top) : nullptr; bool clicked = mFocusItem == item; @@ -1055,7 +1119,7 @@ namespace MWGui } } - void showPage(TypesetBook::Ptr book, size_t newPage) + void showPage(std::shared_ptr book, size_t newPage) { std::shared_ptr newBook = std::dynamic_pointer_cast(book); @@ -1129,7 +1193,8 @@ namespace MWGui { } - void operator()(Section const& section, Line const& line, Run const& run) const + void operator()(const TypesetBookImpl::Section& section, const TypesetBookImpl::Line& line, + const TypesetBookImpl::Run& run) const { MyGUI::IFont* const font = run.mStyle->mFont; @@ -1198,7 +1263,8 @@ namespace MWGui { } - void operator()(Section const& section, Line const& line, Run const& run) const + void operator()(const TypesetBookImpl::Section& section, const TypesetBookImpl::Line& line, + const TypesetBookImpl::Run& run) const { bool isActive = run.mStyle->mInteractiveId && (run.mStyle == mPageDisplay->mFocusItem); @@ -1291,14 +1357,20 @@ namespace MWGui { } - void showPage(TypesetBook::Ptr book, size_t page) override { mPageDisplay->showPage(std::move(book), page); } + void showPage(std::shared_ptr book, size_t page) override + { + mPageDisplay->showPage(std::move(book), page); + } - void adviseLinkClicked(std::function linkClicked) override + void adviseLinkClicked(std::function linkClicked) override { mPageDisplay->mLinkClicked = std::move(linkClicked); } - void unadviseLinkClicked() override { mPageDisplay->mLinkClicked = std::function(); } + void unadviseLinkClicked() override + { + mPageDisplay->mLinkClicked = std::function(); + } void setFocusItem(BookTypesetter::Style* itemStyle) override { @@ -1350,75 +1422,4 @@ namespace MWGui factory.registerFactory("Widget"); factory.registerFactory("BasisSkin"); } - - static bool ucsLineBreak(int codePoint) - { - return codePoint == '\n'; - } - - static bool ucsCarriageReturn(int codePoint) - { - return codePoint == '\r'; - } - - // Normal no-break space (0x00A0) is ignored here - // because Morrowind compatibility requires us to render its glyph - static bool ucsSpace(int codePoint) - { - switch (codePoint) - { - case 0x0020: // SPACE - case 0x1680: // OGHAM SPACE MARK - case 0x180E: // MONGOLIAN VOWEL SEPARATOR - case 0x2000: // EN QUAD - case 0x2001: // EM QUAD - case 0x2002: // EN SPACE - case 0x2003: // EM SPACE - case 0x2004: // THREE-PER-EM SPACE - case 0x2005: // FOUR-PER-EM SPACE - case 0x2006: // SIX-PER-EM SPACE - case 0x2007: // FIGURE SPACE - case 0x2008: // PUNCTUATION SPACE - case 0x2009: // THIN SPACE - case 0x200A: // HAIR SPACE - case 0x200B: // ZERO WIDTH SPACE - case 0x202F: // NARROW NO-BREAK SPACE - case 0x205F: // MEDIUM MATHEMATICAL SPACE - case 0x3000: // IDEOGRAPHIC SPACE - case 0xFEFF: // ZERO WIDTH NO-BREAK SPACE - return true; - default: - return false; - } - } - - // No-break spaces (0x00A0, 0x202F, 0xFEFF - normal, narrow, zero width) - // are ignored here for obvious reasons - // Figure space (0x2007) is not a breaking space either - static bool ucsBreakingSpace(int codePoint) - { - switch (codePoint) - { - case 0x0020: // SPACE - case 0x1680: // OGHAM SPACE MARK - case 0x180E: // MONGOLIAN VOWEL SEPARATOR - case 0x2000: // EN QUAD - case 0x2001: // EM QUAD - case 0x2002: // EN SPACE - case 0x2003: // EM SPACE - case 0x2004: // THREE-PER-EM SPACE - case 0x2005: // FOUR-PER-EM SPACE - case 0x2006: // SIX-PER-EM SPACE - case 0x2008: // PUNCTUATION SPACE - case 0x2009: // THIN SPACE - case 0x200A: // HAIR SPACE - case 0x200B: // ZERO WIDTH SPACE - case 0x205F: // MEDIUM MATHEMATICAL SPACE - case 0x3000: // IDEOGRAPHIC SPACE - return true; - default: - return false; - } - } - } diff --git a/apps/openmw/mwgui/bookpage.hpp b/apps/openmw/mwgui/bookpage.hpp index 92e169e0e4..ca5beae2dc 100644 --- a/apps/openmw/mwgui/bookpage.hpp +++ b/apps/openmw/mwgui/bookpage.hpp @@ -8,6 +8,7 @@ #include #include #include +#include #include @@ -17,7 +18,7 @@ namespace MWGui /// the book page widget. struct TypesetBook { - typedef std::shared_ptr Ptr; + using Content = std::vector; typedef intptr_t InteractiveId; /// Returns the number of pages in the document. @@ -37,55 +38,9 @@ namespace MWGui virtual ~TypesetBook() = default; }; - struct GlyphInfo - { - char codePoint; - float width; - float height; - float advance; - float bearingX; - float bearingY; - bool charFound; - MyGUI::FloatRect uvRect; - - GlyphInfo(MyGUI::IFont* font, MyGUI::Char ch) - { - const MyGUI::GlyphInfo* gi = font->getGlyphInfo(ch); - if (gi) - { - const float scale = font->getDefaultHeight() / static_cast(Settings::gui().mFontSize); - - codePoint = gi->codePoint; - bearingX = (int)gi->bearingX / scale; - bearingY = (int)gi->bearingY / scale; - width = (int)gi->width / scale; - height = (int)gi->height / scale; - advance = (int)gi->advance / scale; - uvRect = gi->uvRect; - charFound = true; - } - else - { - codePoint = 0; - bearingX = 0; - bearingY = 0; - width = 0; - height = 0; - advance = 0; - charFound = false; - } - } - }; - /// A factory class for creating a typeset book instance. struct BookTypesetter { - typedef std::shared_ptr Ptr; - typedef TypesetBook::InteractiveId InteractiveId; - typedef MyGUI::Colour Colour; - typedef uint8_t const* Utf8Point; - typedef std::pair Utf8Span; - virtual ~BookTypesetter() = default; enum Alignment @@ -102,16 +57,18 @@ namespace MWGui struct Style; /// A factory function for creating the default implementation of a book typesetter - static Ptr create(int pageWidth, int pageHeight); + static std::shared_ptr create(int pageWidth, int pageHeight); /// Create a simple text style consisting of a font and a text color. - virtual Style* createStyle(const std::string& fontName, const Colour& colour, bool useBookFont = true) = 0; + virtual Style* createStyle(const std::string& fontName, const MyGUI::Colour& colour, bool useBookFont = true) + = 0; /// Create a hyper-link style with a user-defined identifier based on an /// existing style. The unique flag forces a new instance of this style /// to be created even if an existing instance is present. - virtual Style* createHotStyle(Style* baseStyle, const Colour& normalColour, const Colour& hoverColour, - const Colour& activeColour, InteractiveId id, bool unique = true) + virtual Style* createHotStyle(Style* baseStyle, const MyGUI::Colour& normalColour, + const MyGUI::Colour& hoverColour, const MyGUI::Colour& activeColour, TypesetBook::InteractiveId id, + bool unique = true) = 0; /// Insert a line break into the document. Newline characters in the input @@ -129,22 +86,22 @@ namespace MWGui virtual void setSectionAlignment(Alignment sectionAlignment) = 0; // Layout a block of text with the specified style into the document. - virtual void write(Style* style, Utf8Span text) = 0; + virtual void write(Style* style, std::string_view text) = 0; /// Adds a content block to the document without laying it out. An /// identifier is returned that can be used to refer to it. If select /// is true, the block is activated to be references by future writes. - virtual intptr_t addContent(Utf8Span text, bool select = true) = 0; + virtual const TypesetBook::Content* addContent(std::string_view text, bool select = true) = 0; /// Select a previously created content block for future writes. - virtual void selectContent(intptr_t contentHandle) = 0; + virtual void selectContent(const TypesetBook::Content* contentHandle) = 0; /// Layout a span of the selected content block into the document /// using the specified style. virtual void write(Style* style, size_t begin, size_t end) = 0; /// Finalize the document layout, and return a pointer to it. - virtual TypesetBook::Ptr complete() = 0; + virtual std::shared_ptr complete() = 0; }; /// An interface to the BookPage widget. @@ -152,11 +109,10 @@ namespace MWGui { MYGUI_RTTI_DERIVED(BookPage) public: - typedef TypesetBook::InteractiveId InteractiveId; - typedef std::function ClickCallback; + using ClickCallback = std::function; /// Make the widget display the specified page from the specified book. - virtual void showPage(TypesetBook::Ptr book, size_t page) = 0; + virtual void showPage(std::shared_ptr book, size_t page) = 0; /// Set the callback for a clicking a hyper-link in the document. virtual void adviseLinkClicked(ClickCallback callback) = 0; diff --git a/apps/openmw/mwgui/bookwindow.cpp b/apps/openmw/mwgui/bookwindow.cpp index 12a40a27b9..56ae70ac8c 100644 --- a/apps/openmw/mwgui/bookwindow.cpp +++ b/apps/openmw/mwgui/bookwindow.cpp @@ -62,8 +62,8 @@ namespace MWGui { // english button has a 7 pixel wide strip of garbage on its right edge mNextPageButton->setSize(64 - 7, mNextPageButton->getSize().height); - mNextPageButton->setImageCoord( - MyGUI::IntCoord(0, 0, (64 - 7) * scale, mNextPageButton->getSize().height * scale)); + mNextPageButton->setImageCoord(MyGUI::IntCoord( + 0, 0, static_cast((64 - 7) * scale), static_cast(mNextPageButton->getSize().height * scale))); } mControllerButtons.mL1 = "#{Interface:Prev}"; diff --git a/apps/openmw/mwgui/charactercreation.cpp b/apps/openmw/mwgui/charactercreation.cpp index 61d1132a28..42109a7c28 100644 --- a/apps/openmw/mwgui/charactercreation.cpp +++ b/apps/openmw/mwgui/charactercreation.cpp @@ -151,13 +151,14 @@ namespace MWGui mReviewDialog->onFrame(duration); } - void CharacterCreation::spawnDialog(const char id) + void CharacterCreation::spawnDialog(const GuiMode id) { try { switch (id) { case GM_Name: + { MWBase::Environment::get().getWindowManager()->removeDialog(std::move(mNameDialog)); mNameDialog = std::make_unique(); mNameDialog->setTextLabel( @@ -167,8 +168,9 @@ namespace MWGui mNameDialog->eventDone += MyGUI::newDelegate(this, &CharacterCreation::onNameDialogDone); mNameDialog->setVisible(true); break; - + } case GM_Race: + { MWBase::Environment::get().getWindowManager()->removeDialog(std::move(mRaceDialog)); mRaceDialog = std::make_unique(mParent, mResourceSystem); mRaceDialog->setNextButtonShow(mCreationStage >= CSE_RaceChosen); @@ -179,8 +181,9 @@ namespace MWGui if (mCreationStage < CSE_NameChosen) mCreationStage = CSE_NameChosen; break; - + } case GM_Class: + { MWBase::Environment::get().getWindowManager()->removeDialog(std::move(mClassChoiceDialog)); mClassChoiceDialog = std::make_unique(); mClassChoiceDialog->eventButtonSelected @@ -189,8 +192,9 @@ namespace MWGui if (mCreationStage < CSE_RaceChosen) mCreationStage = CSE_RaceChosen; break; - + } case GM_ClassPick: + { MWBase::Environment::get().getWindowManager()->removeDialog(std::move(mPickClassDialog)); mPickClassDialog = std::make_unique(); mPickClassDialog->setNextButtonShow(mCreationStage >= CSE_ClassChosen); @@ -201,8 +205,9 @@ namespace MWGui if (mCreationStage < CSE_RaceChosen) mCreationStage = CSE_RaceChosen; break; - + } case GM_Birth: + { MWBase::Environment::get().getWindowManager()->removeDialog(std::move(mBirthSignDialog)); mBirthSignDialog = std::make_unique(); mBirthSignDialog->setNextButtonShow(mCreationStage >= CSE_BirthSignChosen); @@ -213,8 +218,9 @@ namespace MWGui if (mCreationStage < CSE_ClassChosen) mCreationStage = CSE_ClassChosen; break; - + } case GM_ClassCreate: + { if (mCreateClassDialog == nullptr) { mCreateClassDialog = std::make_unique(); @@ -228,7 +234,9 @@ namespace MWGui if (mCreationStage < CSE_RaceChosen) mCreationStage = CSE_RaceChosen; break; + } case GM_ClassGenerate: + { mGenerateClassStep = 0; mGenerateClass = ESM::RefId(); mGenerateClassSpecializations[0] = 0; @@ -238,7 +246,9 @@ namespace MWGui if (mCreationStage < CSE_RaceChosen) mCreationStage = CSE_RaceChosen; break; + } case GM_Review: + { MWBase::Environment::get().getWindowManager()->removeDialog(std::move(mReviewDialog)); mReviewDialog = std::make_unique(); @@ -279,6 +289,11 @@ namespace MWGui if (mCreationStage < CSE_BirthSignChosen) mCreationStage = CSE_BirthSignChosen; break; + } + default: + { + Log(Debug::Error) << "Unexpected GuiMode in CharacterCreation::spawnDialog: " << id; + } } } catch (std::exception& e) diff --git a/apps/openmw/mwgui/charactercreation.hpp b/apps/openmw/mwgui/charactercreation.hpp index b92e3c2f5b..c888e94422 100644 --- a/apps/openmw/mwgui/charactercreation.hpp +++ b/apps/openmw/mwgui/charactercreation.hpp @@ -7,6 +7,7 @@ #include #include +#include "mode.hpp" #include "statswatcher.hpp" namespace osg @@ -42,7 +43,7 @@ namespace MWGui virtual ~CharacterCreation(); // Show a dialog - void spawnDialog(const char id); + void spawnDialog(const GuiMode id); void setAttribute(ESM::RefId id, const MWMechanics::AttributeValue& value) override; void setValue(std::string_view id, const MWMechanics::DynamicStat& value) override; diff --git a/apps/openmw/mwgui/class.cpp b/apps/openmw/mwgui/class.cpp index 072a7f35a3..0c8c9548df 100644 --- a/apps/openmw/mwgui/class.cpp +++ b/apps/openmw/mwgui/class.cpp @@ -129,7 +129,7 @@ namespace MWGui for (int i = 0; i < 5; i++) { - char theIndex = '0' + i; + char theIndex = '0' + static_cast(i); getWidget(mMajorSkill[i], std::string("MajorSkill").append(1, theIndex)); getWidget(mMinorSkill[i], std::string("MinorSkill").append(1, theIndex)); } @@ -483,7 +483,7 @@ namespace MWGui return true; setControllerFocus(mButtons, mControllerFocus, false); - mControllerFocus = wrap(mControllerFocus - 1, mButtons.size()); + mControllerFocus = wrap(mControllerFocus, mButtons.size(), -1); setControllerFocus(mButtons, mControllerFocus, true); } else if (arg.button == SDL_CONTROLLER_BUTTON_DPAD_DOWN) @@ -494,7 +494,7 @@ namespace MWGui return true; setControllerFocus(mButtons, mControllerFocus, false); - mControllerFocus = wrap(mControllerFocus + 1, mButtons.size()); + mControllerFocus = wrap(mControllerFocus, mButtons.size(), 1); setControllerFocus(mButtons, mControllerFocus, true); } @@ -546,7 +546,7 @@ namespace MWGui "MajorSkillT", MWBase::Environment::get().getWindowManager()->getGameSettingString("sSkillClassMajor", {})); setText( "MinorSkillT", MWBase::Environment::get().getWindowManager()->getGameSettingString("sSkillClassMinor", {})); - for (int i = 0; i < 5; i++) + for (char i = 0; i < 5; i++) { char theIndex = '0' + i; getWidget(mMajorSkill[i], std::string("MajorSkill").append(1, theIndex)); @@ -713,13 +713,13 @@ namespace MWGui else if (arg.button == SDL_CONTROLLER_BUTTON_DPAD_LEFT) { setControllerFocus(mButtons, mControllerFocus, false); - mControllerFocus = wrap(mControllerFocus - 1, mButtons.size()); + mControllerFocus = wrap(mControllerFocus, mButtons.size(), -1); setControllerFocus(mButtons, mControllerFocus, true); } else if (arg.button == SDL_CONTROLLER_BUTTON_DPAD_RIGHT) { setControllerFocus(mButtons, mControllerFocus, false); - mControllerFocus = wrap(mControllerFocus + 1, mButtons.size()); + mControllerFocus = wrap(mControllerFocus, mButtons.size(), 1); setControllerFocus(mButtons, mControllerFocus, true); } return true; @@ -1001,13 +1001,13 @@ namespace MWGui else if (arg.button == SDL_CONTROLLER_BUTTON_DPAD_UP) { mAttributeButtons[mControllerFocus]->setStateSelected(false); - mControllerFocus = wrap(mControllerFocus - 1, mAttributeButtons.size()); + mControllerFocus = wrap(mControllerFocus, mAttributeButtons.size(), -1); mAttributeButtons[mControllerFocus]->setStateSelected(true); } else if (arg.button == SDL_CONTROLLER_BUTTON_DPAD_DOWN) { mAttributeButtons[mControllerFocus]->setStateSelected(false); - mControllerFocus = wrap(mControllerFocus + 1, mAttributeButtons.size()); + mControllerFocus = wrap(mControllerFocus, mAttributeButtons.size(), 1); mAttributeButtons[mControllerFocus]->setStateSelected(true); } @@ -1103,13 +1103,13 @@ namespace MWGui else if (arg.button == SDL_CONTROLLER_BUTTON_DPAD_UP) { mSkillButtons[mControllerFocus]->setStateSelected(false); - mControllerFocus = wrap(mControllerFocus - 1, mSkillButtons.size()); + mControllerFocus = wrap(mControllerFocus, mSkillButtons.size(), -1); mSkillButtons[mControllerFocus]->setStateSelected(true); } else if (arg.button == SDL_CONTROLLER_BUTTON_DPAD_DOWN) { mSkillButtons[mControllerFocus]->setStateSelected(false); - mControllerFocus = wrap(mControllerFocus + 1, mSkillButtons.size()); + mControllerFocus = wrap(mControllerFocus, mSkillButtons.size(), 1); mSkillButtons[mControllerFocus]->setStateSelected(true); } else if (arg.button == SDL_CONTROLLER_BUTTON_DPAD_LEFT || arg.button == SDL_CONTROLLER_BUTTON_DPAD_RIGHT) diff --git a/apps/openmw/mwgui/companionitemmodel.cpp b/apps/openmw/mwgui/companionitemmodel.cpp index 6bae8aef52..c438dbb822 100644 --- a/apps/openmw/mwgui/companionitemmodel.cpp +++ b/apps/openmw/mwgui/companionitemmodel.cpp @@ -28,7 +28,7 @@ namespace MWGui MWWorld::Ptr CompanionItemModel::addItem(const ItemStack& item, size_t count, bool allowAutoEquip) { if (hasProfit(mActor)) - modifyProfit(mActor, item.mBase.getClass().getValue(item.mBase) * count); + modifyProfit(mActor, static_cast(item.mBase.getClass().getValue(item.mBase) * count)); return InventoryItemModel::addItem(item, count, allowAutoEquip); } @@ -36,7 +36,7 @@ namespace MWGui MWWorld::Ptr CompanionItemModel::copyItem(const ItemStack& item, size_t count, bool allowAutoEquip) { if (hasProfit(mActor)) - modifyProfit(mActor, item.mBase.getClass().getValue(item.mBase) * count); + modifyProfit(mActor, static_cast(item.mBase.getClass().getValue(item.mBase) * count)); return InventoryItemModel::copyItem(item, count, allowAutoEquip); } @@ -44,7 +44,7 @@ namespace MWGui void CompanionItemModel::removeItem(const ItemStack& item, size_t count) { if (hasProfit(mActor)) - modifyProfit(mActor, -item.mBase.getClass().getValue(item.mBase) * count); + modifyProfit(mActor, -static_cast(item.mBase.getClass().getValue(item.mBase) * count)); InventoryItemModel::removeItem(item, count); } diff --git a/apps/openmw/mwgui/companionwindow.cpp b/apps/openmw/mwgui/companionwindow.cpp index 21ed339c5d..a206be01be 100644 --- a/apps/openmw/mwgui/companionwindow.cpp +++ b/apps/openmw/mwgui/companionwindow.cpp @@ -89,7 +89,7 @@ namespace MWGui } MWWorld::Ptr object = item.mBase; - int count = item.mCount; + size_t count = item.mCount; bool shift = MyGUI::InputManager::getInstance().isShiftPressed(); if (MyGUI::InputManager::getInstance().isControlPressed()) count = 1; @@ -101,7 +101,7 @@ namespace MWGui CountDialog* dialog = MWBase::Environment::get().getWindowManager()->getCountDialog(); std::string name{ object.getClass().getName(object) }; name += MWGui::ToolTips::getSoulString(object.getCellRef()); - dialog->openCountDialog(name, "#{sTake}", count); + dialog->openCountDialog(name, "#{sTake}", static_cast(count)); dialog->eventOkClicked.clear(); if (Settings::gui().mControllerMenus || MyGUI::InputManager::getInstance().isAltPressed()) dialog->eventOkClicked += MyGUI::newDelegate(this, &CompanionWindow::transferItem); @@ -174,9 +174,9 @@ namespace MWGui { if (mPtr.isEmpty()) return; - float capacity = mPtr.getClass().getCapacity(mPtr); - float encumbrance = mPtr.getClass().getEncumbrance(mPtr); - mEncumbranceBar->setValue(std::ceil(encumbrance), static_cast(capacity)); + int capacity = static_cast(mPtr.getClass().getCapacity(mPtr)); + float encumbrance = std::ceil(mPtr.getClass().getEncumbrance(mPtr)); + mEncumbranceBar->setValue(static_cast(encumbrance), capacity); if (mModel && mModel->hasProfit(mPtr)) { diff --git a/apps/openmw/mwgui/console.cpp b/apps/openmw/mwgui/console.cpp index 886b4d381e..aa63ed3371 100644 --- a/apps/openmw/mwgui/console.cpp +++ b/apps/openmw/mwgui/console.cpp @@ -32,6 +32,14 @@ #include "../mwworld/class.hpp" #include "../mwworld/esmstore.hpp" +namespace +{ + bool isWhitespace(MyGUI::UString::code_point c) + { + return c == ' ' || c == '\t'; + } +} + namespace MWGui { class ConsoleInterpreterContext : public MWScript::InterpreterContext @@ -275,11 +283,6 @@ namespace MWGui resetReference(); } - bool isWhitespace(char c) - { - return c == ' ' || c == '\t'; - } - void Console::commandBoxKeyPress(MyGUI::Widget* /*sender*/, MyGUI::KeyCode key, MyGUI::Char /*value*/) { if (MyGUI::InputManager::getInstance().isControlPressed()) @@ -697,7 +700,7 @@ namespace MWGui /* Is there still something in the input string? If not just display all commands and return the unchanged * input. */ - if (tmp.length() == 0) + if (tmp.empty()) { matches = mNames; return input; @@ -756,10 +759,9 @@ namespace MWGui } /* Check if all matching strings match further than input. If yes complete to this match. */ - int i = tmp.length(); + size_t i = tmp.length(); - for (std::string::iterator iter = matches.front().begin() + tmp.length(); iter < matches.front().end(); - ++iter, ++i) + for (auto iter = matches.front().begin() + tmp.length(); iter < matches.front().end(); ++iter, ++i) { for (std::string& match : matches) { diff --git a/apps/openmw/mwgui/container.cpp b/apps/openmw/mwgui/container.cpp index f49f96a400..1b6dd4cbfb 100644 --- a/apps/openmw/mwgui/container.cpp +++ b/apps/openmw/mwgui/container.cpp @@ -84,7 +84,7 @@ namespace MWGui } MWWorld::Ptr object = item.mBase; - int count = item.mCount; + size_t count = item.mCount; bool shift = MyGUI::InputManager::getInstance().isShiftPressed(); if (MyGUI::InputManager::getInstance().isControlPressed()) count = 1; @@ -96,7 +96,7 @@ namespace MWGui CountDialog* dialog = MWBase::Environment::get().getWindowManager()->getCountDialog(); std::string name{ object.getClass().getName(object) }; name += MWGui::ToolTips::getSoulString(object.getCellRef()); - dialog->openCountDialog(name, "#{sTake}", count); + dialog->openCountDialog(name, "#{sTake}", static_cast(count)); dialog->eventOkClicked.clear(); if (Settings::gui().mControllerMenus || MyGUI::InputManager::getInstance().isAltPressed()) dialog->eventOkClicked += MyGUI::newDelegate(this, &ContainerWindow::transferItem); @@ -116,7 +116,7 @@ namespace MWGui const ItemStack item = mModel->getItem(mSelectedItem); - if (!mModel->onTakeItem(item.mBase, count)) + if (!mModel->onTakeItem(item.mBase, static_cast(count))) return; mDragAndDrop->startDrag(mSelectedItem, mSortModel, mModel, mItemView, count); @@ -129,7 +129,7 @@ namespace MWGui const ItemStack item = mModel->getItem(mSelectedItem); - if (!mModel->onTakeItem(item.mBase, count)) + if (!mModel->onTakeItem(item.mBase, static_cast(count))) return; mItemTransfer->apply(item, count, *mItemView); @@ -140,7 +140,7 @@ namespace MWGui if (mModel == nullptr) return; - bool success = mModel->onDropItem(mDragAndDrop->mItem.mBase, mDragAndDrop->mDraggedCount); + bool success = mModel->onDropItem(mDragAndDrop->mItem.mBase, static_cast(mDragAndDrop->mDraggedCount)); if (success) mDragAndDrop->drop(mModel, mItemView); @@ -248,7 +248,7 @@ namespace MWGui MWWorld::InventoryStore& invStore = mPtr.getClass().getInventoryStore(mPtr); for (size_t i = 0; i < mModel->getItemCount(); ++i) { - const ItemStack& item = mModel->getItem(i); + const ItemStack& item = mModel->getItem(static_cast(i)); if (invStore.isEquipped(item.mBase) == false) continue; @@ -263,14 +263,14 @@ namespace MWGui if (i == 0) { // play the sound of the first object - MWWorld::Ptr item = mModel->getItem(i).mBase; + MWWorld::Ptr item = mModel->getItem(static_cast(i)).mBase; const ESM::RefId& sound = item.getClass().getUpSoundId(item); MWBase::Environment::get().getWindowManager()->playSound(sound); } - const ItemStack item = mModel->getItem(i); + const ItemStack item = mModel->getItem(static_cast(i)); - if (!mModel->onTakeItem(item.mBase, item.mCount)) + if (!mModel->onTakeItem(item.mBase, static_cast(item.mCount))) break; mModel->moveItem(item, item.mCount, playerModel); diff --git a/apps/openmw/mwgui/containeritemmodel.cpp b/apps/openmw/mwgui/containeritemmodel.cpp index ff50431d86..84d88c48b0 100644 --- a/apps/openmw/mwgui/containeritemmodel.cpp +++ b/apps/openmw/mwgui/containeritemmodel.cpp @@ -90,7 +90,7 @@ namespace MWGui ItemModel::ModelIndex ContainerItemModel::getIndex(const ItemStack& item) { - size_t i = 0; + ModelIndex i = 0; for (ItemStack& itemStack : mItems) { if (itemStack == item) @@ -106,7 +106,7 @@ namespace MWGui MWWorld::ContainerStore& store = source.first.getClass().getContainerStore(source.first); if (item.mBase.getContainerStore() == &store) throw std::runtime_error("Item to add needs to be from a different container!"); - return *store.add(item.mBase, count, allowAutoEquip); + return *store.add(item.mBase, static_cast(count), allowAutoEquip); } MWWorld::Ptr ContainerItemModel::copyItem(const ItemStack& item, size_t count, bool allowAutoEquip) @@ -115,13 +115,13 @@ namespace MWGui MWWorld::ContainerStore& store = source.first.getClass().getContainerStore(source.first); if (item.mBase.getContainerStore() == &store) throw std::runtime_error("Item to copy needs to be from a different container!"); - MWWorld::ManualRef newRef(*MWBase::Environment::get().getESMStore(), item.mBase, count); - return *store.add(newRef.getPtr(), count, allowAutoEquip); + MWWorld::ManualRef newRef(*MWBase::Environment::get().getESMStore(), item.mBase, static_cast(count)); + return *store.add(newRef.getPtr(), static_cast(count), allowAutoEquip); } void ContainerItemModel::removeItem(const ItemStack& item, size_t count) { - int toRemove = count; + int toRemove = static_cast(count); for (auto& source : mItemSources) { diff --git a/apps/openmw/mwgui/countdialog.cpp b/apps/openmw/mwgui/countdialog.cpp index 608257a0e7..08372093f6 100644 --- a/apps/openmw/mwgui/countdialog.cpp +++ b/apps/openmw/mwgui/countdialog.cpp @@ -93,7 +93,7 @@ namespace MWGui void CountDialog::onSliderMoved(MyGUI::ScrollBar* sender, size_t position) { - mItemEdit->setValue(position + 1); + mItemEdit->setValue(static_cast(position + 1)); } bool CountDialog::onControllerButtonEvent(const SDL_ControllerButtonEvent& arg) diff --git a/apps/openmw/mwgui/dialogue.cpp b/apps/openmw/mwgui/dialogue.cpp index 8de39ca4ff..d9a675acc5 100644 --- a/apps/openmw/mwgui/dialogue.cpp +++ b/apps/openmw/mwgui/dialogue.cpp @@ -32,8 +32,6 @@ #include "bookpage.hpp" #include "textcolours.hpp" -#include "journalbooks.hpp" // to_utf8_span - namespace MWGui { void ResponseCallback::addResponse(std::string_view title, std::string_view text) @@ -186,13 +184,13 @@ namespace MWGui else if (arg.button == SDL_CONTROLLER_BUTTON_DPAD_UP) { setControllerFocus(mButtons, mControllerFocus, false); - mControllerFocus = wrap(mControllerFocus - 1, mButtons.size()); + mControllerFocus = wrap(mControllerFocus, mButtons.size(), -1); setControllerFocus(mButtons, mControllerFocus, true); } else if (arg.button == SDL_CONTROLLER_BUTTON_DPAD_DOWN) { setControllerFocus(mButtons, mControllerFocus, false); - mControllerFocus = wrap(mControllerFocus + 1, mButtons.size()); + mControllerFocus = wrap(mControllerFocus, mButtons.size(), 1); setControllerFocus(mButtons, mControllerFocus, true); } @@ -208,7 +206,7 @@ namespace MWGui mText = text; } - void Response::write(BookTypesetter::Ptr typesetter, KeywordSearchT* keywordSearch, + void Response::write(std::shared_ptr typesetter, const TopicSearch& keywordSearch, std::map>& topicLinks) const { typesetter->sectionBreak(mNeedMargin ? 9 : 0); @@ -218,12 +216,11 @@ namespace MWGui { const MyGUI::Colour& headerColour = windowManager->getTextColours().header; BookTypesetter::Style* title = typesetter->createStyle({}, headerColour, false); - typesetter->write(title, to_utf8_span(mTitle)); + typesetter->write(title, mTitle); typesetter->sectionBreak(); } - typedef std::pair Range; - std::map hyperLinks; + std::map, const Link*> hyperLinks; // We need this copy for when @# hyperlinks are replaced std::string text = mText; @@ -250,14 +247,13 @@ namespace MWGui text.replace(posBegin, posEnd + 1 - posBegin, displayName); if (topicLinks.find(topicName) != topicLinks.end()) - hyperLinks[std::make_pair(posBegin, posBegin + displayName.size())] - = intptr_t(topicLinks[topicName].get()); + hyperLinks[std::make_pair(posBegin, posBegin + displayName.size())] = topicLinks[topicName].get(); } else break; } - typesetter->addContent(to_utf8_span(text)); + typesetter->addContent(text); if (hyperLinks.size() && MWBase::Environment::get().getWindowManager()->getTranslationDataStorage().hasTranslation()) @@ -266,48 +262,48 @@ namespace MWGui BookTypesetter::Style* style = typesetter->createStyle({}, textColours.normal, false); size_t formatted = 0; // points to the first character that is not laid out yet - for (auto& hyperLink : hyperLinks) + for (const auto& [range, link] : hyperLinks) { - intptr_t topicId = hyperLink.second; - BookTypesetter::Style* hotStyle = typesetter->createHotStyle( - style, textColours.link, textColours.linkOver, textColours.linkPressed, topicId); - if (formatted < hyperLink.first.first) - typesetter->write(style, formatted, hyperLink.first.first); - typesetter->write(hotStyle, hyperLink.first.first, hyperLink.first.second); - formatted = hyperLink.first.second; + BookTypesetter::Style* hotStyle = typesetter->createHotStyle(style, textColours.link, + textColours.linkOver, textColours.linkPressed, TypesetBook::InteractiveId(link)); + if (formatted < range.first) + typesetter->write(style, formatted, range.first); + typesetter->write(hotStyle, range.first, range.second); + formatted = range.second; } if (formatted < text.size()) typesetter->write(style, formatted, text.size()); } else { - std::vector matches; - keywordSearch->highlightKeywords(text.begin(), text.end(), matches); + std::vector matches; + keywordSearch.highlightKeywords(text.begin(), text.end(), matches); std::string::const_iterator i = text.begin(); - for (KeywordSearchT::Match& match : matches) + for (TopicSearch::Match& match : matches) { if (i != match.mBeg) - addTopicLink(typesetter, 0, i - text.begin(), match.mBeg - text.begin()); + addTopicLink(typesetter, nullptr, i - text.begin(), match.mBeg - text.begin()); addTopicLink(typesetter, match.mValue, match.mBeg - text.begin(), match.mEnd - text.begin()); i = match.mEnd; } if (i != text.end()) - addTopicLink(std::move(typesetter), 0, i - text.begin(), text.size()); + addTopicLink(std::move(typesetter), nullptr, i - text.begin(), text.size()); } } - void Response::addTopicLink(BookTypesetter::Ptr typesetter, intptr_t topicId, size_t begin, size_t end) const + void Response::addTopicLink( + std::shared_ptr typesetter, const MWGui::Topic* topic, size_t begin, size_t end) const { const TextColours& textColours = MWBase::Environment::get().getWindowManager()->getTextColours(); BookTypesetter::Style* style = typesetter->createStyle({}, textColours.normal, false); - if (topicId) - style = typesetter->createHotStyle( - style, textColours.link, textColours.linkOver, textColours.linkPressed, topicId); + if (topic) + style = typesetter->createHotStyle(style, textColours.link, textColours.linkOver, textColours.linkPressed, + TypesetBook::InteractiveId(topic)); typesetter->write(style, begin, end); } @@ -316,13 +312,13 @@ namespace MWGui mText = text; } - void Message::write(BookTypesetter::Ptr typesetter, KeywordSearchT* keywordSearch, - std::map>& topicLinks) const + void Message::write(std::shared_ptr typesetter, const TopicSearch&, + std::map>&) const { const MyGUI::Colour& textColour = MWBase::Environment::get().getWindowManager()->getTextColours().notify; BookTypesetter::Style* title = typesetter->createStyle({}, textColour, false); typesetter->sectionBreak(9); - typesetter->write(title, to_utf8_span(mText)); + typesetter->write(title, mText); } // -------------------------------------------------------------------------------------------------- @@ -428,8 +424,8 @@ namespace MWGui { if (!mScrollBar->getVisible()) return; - mScrollBar->setScrollPosition( - std::clamp(mScrollBar->getScrollPosition() - rel * 0.3, 0, mScrollBar->getScrollRange() - 1)); + mScrollBar->setScrollPosition(std::clamp( + static_cast(mScrollBar->getScrollPosition() - rel * 0.3), 0, mScrollBar->getScrollRange() - 1)); onScrollbarMoved(mScrollBar, mScrollBar->getScrollPosition()); } @@ -441,7 +437,7 @@ namespace MWGui } } - void DialogueWindow::onSelectListItem(const std::string& topic, int id) + void DialogueWindow::onSelectListItem(const std::string& topic, int /*id*/) { MWBase::DialogueManager* dialogueManager = MWBase::Environment::get().getDialogueManager(); @@ -607,7 +603,7 @@ namespace MWGui void DialogueWindow::updateTopicsPane() { std::string focusedTopic; - if (Settings::gui().mControllerMenus && mControllerFocus < static_cast(mTopicsList->getItemCount())) + if (Settings::gui().mControllerMenus && mControllerFocus < mTopicsList->getItemCount()) focusedTopic = mTopicsList->getItemNameAt(mControllerFocus); mTopicsList->clear(); @@ -661,7 +657,7 @@ namespace MWGui mTopicsList->addItem(keyword, sVerticalPadding); auto t = std::make_unique(keyword); - mKeywordSearch.seed(topicId, intptr_t(t.get())); + mKeywordSearch.seed(topicId, t.get()); t->eventTopicActivated += MyGUI::newDelegate(this, &DialogueWindow::onTopicActivated); mTopicLinks[topicId] = std::move(t); @@ -689,10 +685,11 @@ namespace MWGui mScrollBar->setVisible(true); } - BookTypesetter::Ptr typesetter = BookTypesetter::create(mHistory->getWidth(), std::numeric_limits::max()); + std::shared_ptr typesetter + = BookTypesetter::create(mHistory->getWidth(), std::numeric_limits::max()); for (const auto& text : mHistoryContents) - text->write(typesetter, &mKeywordSearch, mTopicLinks); + text->write(typesetter, mKeywordSearch, mTopicLinks); BookTypesetter::Style* body = typesetter->createStyle({}, MyGUI::Colour::White, false); @@ -712,7 +709,7 @@ namespace MWGui typesetter->lineBreak(); BookTypesetter::Style* questionStyle = typesetter->createHotStyle( body, textColours.answer, textColours.answerOver, textColours.answerPressed, interactiveId); - typesetter->write(questionStyle, to_utf8_span(choice.first)); + typesetter->write(questionStyle, choice.first); mChoiceStyles.push_back(questionStyle); } @@ -731,10 +728,10 @@ namespace MWGui BookTypesetter::Style* questionStyle = typesetter->createHotStyle( body, textColours.answer, textColours.answerOver, textColours.answerPressed, interactiveId); typesetter->lineBreak(); - typesetter->write(questionStyle, to_utf8_span(goodbye)); + typesetter->write(questionStyle, goodbye); } - TypesetBook::Ptr book = typesetter->complete(); + std::shared_ptr book = typesetter->complete(); mHistory->showPage(book, 0); size_t viewHeight = mHistory->getParent()->getHeight(); if (!scrollbar && book->getSize().second > viewHeight) @@ -970,10 +967,10 @@ namespace MWGui else if (mControllerChoice >= 0 && mControllerChoice < static_cast(mChoices.size())) onChoiceActivated(mChoices[mControllerChoice].second); } - else if (mControllerFocus == static_cast(mTopicsList->getItemCount())) + else if (mControllerFocus == mTopicsList->getItemCount()) onGoodbyeActivated(); else - onSelectListItem(mTopicsList->getItemNameAt(mControllerFocus), mControllerFocus); + onSelectListItem(mTopicsList->getItemNameAt(mControllerFocus), static_cast(mControllerFocus)); MWBase::Environment::get().getWindowManager()->playSound(ESM::RefId::stringRefId("Menu Click")); } else if (arg.button == SDL_CONTROLLER_BUTTON_B && mChoices.empty()) @@ -1013,9 +1010,9 @@ namespace MWGui { // Number of items is mTopicsList.length+1 because of "Goodbye" button. setControllerFocus(mControllerFocus, false); - if (mControllerFocus >= static_cast(mTopicsList->getItemCount())) + if (mControllerFocus >= mTopicsList->getItemCount()) mControllerFocus = 0; - else if (mControllerFocus == static_cast(mTopicsList->getItemCount()) - 1) + else if (mControllerFocus == mTopicsList->getItemCount() - 1) mControllerFocus = mTopicsList->getItemCount(); // "Goodbye" button else if (mTopicsList->getItemNameAt(mControllerFocus + 1).empty()) mControllerFocus += 2; // Skip separator @@ -1027,13 +1024,13 @@ namespace MWGui else if (arg.button == SDL_CONTROLLER_BUTTON_LEFTSHOULDER && mChoices.size() == 0) { setControllerFocus(mControllerFocus, false); - mControllerFocus = std::max(mControllerFocus - 5, 0); + mControllerFocus = mControllerFocus > 5 ? mControllerFocus - 5 : 0; setControllerFocus(mControllerFocus, true); } else if (arg.button == SDL_CONTROLLER_BUTTON_RIGHTSHOULDER && mChoices.size() == 0) { setControllerFocus(mControllerFocus, false); - mControllerFocus = std::min(mControllerFocus + 5, static_cast(mTopicsList->getItemCount())); + mControllerFocus = std::min(mControllerFocus + 5, mTopicsList->getItemCount()); setControllerFocus(mControllerFocus, true); } diff --git a/apps/openmw/mwgui/dialogue.hpp b/apps/openmw/mwgui/dialogue.hpp index bb0fcd6f0e..81011ee24a 100644 --- a/apps/openmw/mwgui/dialogue.hpp +++ b/apps/openmw/mwgui/dialogue.hpp @@ -69,7 +69,7 @@ namespace MWGui Gui::AutoSizedTextBox* mGoldLabel; std::vector mButtons; - int mControllerFocus = 0; + size_t mControllerFocus = 0; void adjustAction(MyGUI::Widget* action, int& totalHeight); @@ -79,14 +79,13 @@ namespace MWGui struct Link { - virtual ~Link() {} + virtual ~Link() = default; virtual void activated() = 0; }; struct Topic : Link { - typedef MyGUI::delegates::MultiDelegate EventHandle_TopicId; - EventHandle_TopicId eventTopicActivated; + MyGUI::delegates::MultiDelegate eventTopicActivated; Topic(const std::string& id) : mTopicId(id) { @@ -97,8 +96,7 @@ namespace MWGui struct Choice : Link { - typedef MyGUI::delegates::MultiDelegate EventHandle_ChoiceId; - EventHandle_ChoiceId eventChoiceActivated; + MyGUI::delegates::MultiDelegate eventChoiceActivated; Choice(int id) : mChoiceId(id) { @@ -109,17 +107,16 @@ namespace MWGui struct Goodbye : Link { - typedef MyGUI::delegates::MultiDelegate<> Event_Activated; - Event_Activated eventActivated; + MyGUI::delegates::MultiDelegate<> eventActivated; void activated() override; }; - typedef MWDialogue::KeywordSearch KeywordSearchT; + using TopicSearch = MWDialogue::KeywordSearch; struct DialogueText { virtual ~DialogueText() = default; - virtual void write(BookTypesetter::Ptr typesetter, KeywordSearchT* keywordSearch, + virtual void write(std::shared_ptr typesetter, const TopicSearch& keywordSearch, std::map>& topicLinks) const = 0; std::string mText; }; @@ -127,9 +124,10 @@ namespace MWGui struct Response : DialogueText { Response(std::string_view text, std::string_view title = {}, bool needMargin = true); - void write(BookTypesetter::Ptr typesetter, KeywordSearchT* keywordSearch, + void write(std::shared_ptr typesetter, const TopicSearch& keywordSearch, std::map>& topicLinks) const override; - void addTopicLink(BookTypesetter::Ptr typesetter, intptr_t topicId, size_t begin, size_t end) const; + void addTopicLink( + std::shared_ptr typesetter, const Topic* topic, size_t begin, size_t end) const; std::string mTitle; bool mNeedMargin; }; @@ -137,7 +135,7 @@ namespace MWGui struct Message : DialogueText { Message(std::string_view text); - void write(BookTypesetter::Ptr typesetter, KeywordSearchT* keywordSearch, + void write(std::shared_ptr typesetter, const TopicSearch& keywordSearch, std::map>& topicLinks) const override; }; @@ -150,9 +148,6 @@ namespace MWGui bool exit() override; - // Events - typedef MyGUI::delegates::MultiDelegate<> EventHandle_Void; - void notifyLinkClicked(TypesetBook::InteractiveId link); void setPtr(const MWWorld::Ptr& actor) override; @@ -213,7 +208,7 @@ namespace MWGui std::vector> mDeleteLater; - KeywordSearchT mKeywordSearch; + TopicSearch mKeywordSearch; BookPage* mHistory; Gui::MWList* mTopicsList; @@ -230,7 +225,7 @@ namespace MWGui std::unique_ptr mGreetingCallback; void setControllerFocus(size_t index, bool focused); - int mControllerFocus = 0; + size_t mControllerFocus = 0; int mControllerChoice = -1; void updateTopicFormat(); diff --git a/apps/openmw/mwgui/draganddrop.cpp b/apps/openmw/mwgui/draganddrop.cpp index 85229d0a13..5a0c10c5d8 100644 --- a/apps/openmw/mwgui/draganddrop.cpp +++ b/apps/openmw/mwgui/draganddrop.cpp @@ -48,9 +48,9 @@ namespace MWGui ItemModel::ModelIndex newIndex = -1; for (size_t i = 0; i < playerModel->getItemCount(); ++i) { - if (playerModel->getItem(i).mBase == item) + if (playerModel->getItem(static_cast(i)).mBase == item) { - newIndex = i; + newIndex = static_cast(i); break; } } @@ -82,7 +82,7 @@ namespace MWGui mDraggedWidget->setItem(mItem.mBase); mDraggedWidget->setNeedMouseFocus(false); - mDraggedWidget->setCount(count); + mDraggedWidget->setCount(static_cast(count)); MWBase::Environment::get().getWindowManager()->setDragDrop(true); @@ -134,7 +134,7 @@ namespace MWGui mItem.mCount = count; mDraggedCount = count; - mDraggedWidget->setCount(mDraggedCount); + mDraggedWidget->setCount(static_cast(mDraggedCount)); mSourceSortModel->clearDragItems(); mSourceSortModel->addDragItem(mItem.mBase, mDraggedCount); } diff --git a/apps/openmw/mwgui/hud.cpp b/apps/openmw/mwgui/hud.cpp index e157f291e8..167bf28fc5 100644 --- a/apps/openmw/mwgui/hud.cpp +++ b/apps/openmw/mwgui/hud.cpp @@ -349,7 +349,7 @@ namespace MWGui if (mIsDrowning) { - mDrowningFlashTheta += dt * osg::PI * 2; + mDrowningFlashTheta += dt * osg::PIf * 2; float intensity = (cos(mDrowningFlashTheta) + 2.0f) / 3.0f; diff --git a/apps/openmw/mwgui/inventoryitemmodel.cpp b/apps/openmw/mwgui/inventoryitemmodel.cpp index 7464290947..97d8ac8921 100644 --- a/apps/openmw/mwgui/inventoryitemmodel.cpp +++ b/apps/openmw/mwgui/inventoryitemmodel.cpp @@ -37,7 +37,7 @@ namespace MWGui ItemModel::ModelIndex InventoryItemModel::getIndex(const ItemStack& item) { - size_t i = 0; + ModelIndex i = 0; for (ItemStack& itemStack : mItems) { if (itemStack == item) @@ -51,7 +51,7 @@ namespace MWGui { if (item.mBase.getContainerStore() == &mActor.getClass().getContainerStore(mActor)) throw std::runtime_error("Item to add needs to be from a different container!"); - return *mActor.getClass().getContainerStore(mActor).add(item.mBase, count, allowAutoEquip); + return *mActor.getClass().getContainerStore(mActor).add(item.mBase, static_cast(count), allowAutoEquip); } MWWorld::Ptr InventoryItemModel::copyItem(const ItemStack& item, size_t count, bool allowAutoEquip) @@ -59,8 +59,9 @@ namespace MWGui if (item.mBase.getContainerStore() == &mActor.getClass().getContainerStore(mActor)) throw std::runtime_error("Item to copy needs to be from a different container!"); - MWWorld::ManualRef newRef(*MWBase::Environment::get().getESMStore(), item.mBase, count); - return *mActor.getClass().getContainerStore(mActor).add(newRef.getPtr(), count, allowAutoEquip); + MWWorld::ManualRef newRef(*MWBase::Environment::get().getESMStore(), item.mBase, static_cast(count)); + return *mActor.getClass().getContainerStore(mActor).add( + newRef.getPtr(), static_cast(count), allowAutoEquip); } void InventoryItemModel::removeItem(const ItemStack& item, size_t count) @@ -70,12 +71,12 @@ namespace MWGui if (mActor.getClass().hasInventoryStore(mActor)) { MWWorld::InventoryStore& store = mActor.getClass().getInventoryStore(mActor); - removed = store.remove(item.mBase, count, true); + removed = store.remove(item.mBase, static_cast(count), true); } else { MWWorld::ContainerStore& store = mActor.getClass().getContainerStore(mActor); - removed = store.remove(item.mBase, count); + removed = store.remove(item.mBase, static_cast(count)); } std::stringstream error; diff --git a/apps/openmw/mwgui/inventorytabsoverlay.cpp b/apps/openmw/mwgui/inventorytabsoverlay.cpp index d95079ab53..9affdee800 100644 --- a/apps/openmw/mwgui/inventorytabsoverlay.cpp +++ b/apps/openmw/mwgui/inventorytabsoverlay.cpp @@ -14,9 +14,9 @@ namespace MWGui : WindowBase("openmw_inventory_tabs.layout") { MyGUI::Button* tab; - static const char* kTabIds[] = { "TabMap", "TabInventory", "TabSpells", "TabStats" }; + constexpr std::string_view kTabIds[] = { "TabMap", "TabInventory", "TabSpells", "TabStats" }; - for (const char* id : kTabIds) + for (const std::string_view id : kTabIds) { getWidget(tab, id); tab->eventMouseButtonClick += MyGUI::newDelegate(this, &InventoryTabsOverlay::onTabClicked); @@ -44,7 +44,7 @@ namespace MWGui if (!MWBase::Environment::get().getWindowManager()->getJournalAllowed()) return; - for (int i = 0; i < static_cast(mTabs.size()); i++) + for (size_t i = 0; i < mTabs.size(); ++i) { if (mTabs[i] == sender) { @@ -55,9 +55,9 @@ namespace MWGui } } - void InventoryTabsOverlay::setTab(int index) + void InventoryTabsOverlay::setTab(size_t index) { - for (int i = 0; i < static_cast(mTabs.size()); i++) + for (size_t i = 0; i < mTabs.size(); ++i) mTabs[i]->setStateSelected(i == index); } } diff --git a/apps/openmw/mwgui/inventorytabsoverlay.hpp b/apps/openmw/mwgui/inventorytabsoverlay.hpp index 26544aa310..7211e87cf8 100644 --- a/apps/openmw/mwgui/inventorytabsoverlay.hpp +++ b/apps/openmw/mwgui/inventorytabsoverlay.hpp @@ -16,7 +16,7 @@ namespace MWGui InventoryTabsOverlay(); int getHeight(); - void setTab(int index); + void setTab(size_t index); private: std::vector mTabs; diff --git a/apps/openmw/mwgui/inventorywindow.cpp b/apps/openmw/mwgui/inventorywindow.cpp index 726ff23996..6b9deffbf9 100644 --- a/apps/openmw/mwgui/inventorywindow.cpp +++ b/apps/openmw/mwgui/inventorywindow.cpp @@ -218,10 +218,10 @@ namespace MWGui const WindowRectSettingValues& rect = settings.mIsMaximized ? settings.mRegular : settings.mMaximized; MyGUI::IntSize viewSize = MyGUI::RenderManager::getInstance().getViewSize(); - const float x = rect.mX * viewSize.width; - const float y = rect.mY * viewSize.height; - const float w = rect.mW * viewSize.width; - const float h = rect.mH * viewSize.height; + const int x = static_cast(rect.mX * viewSize.width); + const int y = static_cast(rect.mY * viewSize.height); + const int w = static_cast(rect.mW * viewSize.width); + const int h = static_cast(rect.mH * viewSize.height); MyGUI::Window* window = mMainWidget->castType(); window->setCoord(x, y, w, h); @@ -296,7 +296,7 @@ namespace MWGui const ESM::RefId& sound = item.mBase.getClass().getDownSoundId(item.mBase); MWWorld::Ptr object = item.mBase; - int count = item.mCount; + size_t count = item.mCount; bool shift = MyGUI::InputManager::getInstance().isShiftPressed(); if (MyGUI::InputManager::getInstance().isControlPressed()) @@ -347,7 +347,7 @@ namespace MWGui message = "#{sDrop}"; std::string name{ object.getClass().getName(object) }; name += MWGui::ToolTips::getSoulString(object.getCellRef()); - dialog->openCountDialog(name, message, count); + dialog->openCountDialog(name, message, static_cast(count)); dialog->eventOkClicked.clear(); if (mTrading || mPendingControllerAction == ControllerAction::Sell) dialog->eventOkClicked += MyGUI::newDelegate(this, &InventoryWindow::sellItem); @@ -414,9 +414,9 @@ namespace MWGui int newIndex = -1; for (size_t i = 0; i < mTradeModel->getItemCount(); ++i) { - if (mTradeModel->getItem(i).mBase == newStack) + if (mTradeModel->getItem(static_cast(i)).mBase == newStack) { - newIndex = i; + newIndex = static_cast(i); break; } } @@ -431,21 +431,21 @@ namespace MWGui void InventoryWindow::dragItem(MyGUI::Widget* /*sender*/, std::size_t count) { - ensureSelectedItemUnequipped(count); + ensureSelectedItemUnequipped(static_cast(count)); mDragAndDrop->startDrag(mSelectedItem, mSortModel, mTradeModel, mItemView, count); notifyContentChanged(); } void InventoryWindow::transferItem(MyGUI::Widget* /*sender*/, std::size_t count) { - ensureSelectedItemUnequipped(count); + ensureSelectedItemUnequipped(static_cast(count)); mItemTransfer->apply(mTradeModel->getItem(mSelectedItem), count, *mItemView); notifyContentChanged(); } void InventoryWindow::sellItem(MyGUI::Widget* /*sender*/, std::size_t count) { - ensureSelectedItemUnequipped(count); + ensureSelectedItemUnequipped(static_cast(count)); const ItemStack& item = mTradeModel->getItem(mSelectedItem); const ESM::RefId& sound = item.mBase.getClass().getUpSoundId(item.mBase); MWBase::Environment::get().getWindowManager()->playSound(sound); @@ -652,7 +652,7 @@ namespace MWGui MWWorld::InventoryStore& invStore = mPtr.getClass().getInventoryStore(mPtr); auto [eqSlots, canStack] = ptr.getClass().getEquipmentSlots(ptr); - int useCount = isFromDragAndDrop ? mDragAndDrop->mDraggedCount : ptr.getCellRef().getCount(); + int useCount = isFromDragAndDrop ? static_cast(mDragAndDrop->mDraggedCount) : ptr.getCellRef().getCount(); if (!eqSlots.empty()) { @@ -714,9 +714,9 @@ namespace MWGui for (size_t i = 0; i < mTradeModel->getItemCount(); ++i) { - if (mTradeModel->getItem(i).mBase == itemSelected) + if (mTradeModel->getItem(static_cast(i)).mBase == itemSelected) { - onItemSelectedFromSourceModel(i); + onItemSelectedFromSourceModel(static_cast(i)); return; } } @@ -726,7 +726,7 @@ namespace MWGui MWWorld::Ptr InventoryWindow::getAvatarSelectedItem(int x, int y) { - const osg::Vec2f viewportCoords = mapPreviewWindowToViewport(x, y); + const osg::Vec2i viewportCoords = mapPreviewWindowToViewport(x, y); int slot = mPreview->getSlotSelected(viewportCoords.x(), viewportCoords.y()); if (slot == -1) @@ -748,10 +748,10 @@ namespace MWGui { MWWorld::Ptr player = MWMechanics::getPlayer(); - float capacity = player.getClass().getCapacity(player); + int capacity = static_cast(player.getClass().getCapacity(player)); float encumbrance = player.getClass().getEncumbrance(player); mTradeModel->adjustEncumbrance(encumbrance); - mEncumbranceBar->setValue(std::ceil(encumbrance), static_cast(capacity)); + mEncumbranceBar->setValue(static_cast(std::ceil(encumbrance)), capacity); } void InventoryWindow::onFrame(float dt) @@ -844,7 +844,7 @@ namespace MWGui size_t i = 0; for (; i < mTradeModel->getItemCount(); ++i) { - if (mTradeModel->getItem(i).mBase == newObject) + if (mTradeModel->getItem(static_cast(i)).mBase == newObject) break; } if (i == mTradeModel->getItemCount()) @@ -855,13 +855,13 @@ namespace MWGui if (MyGUI::InputManager::getInstance().isAltPressed()) { - const MWWorld::Ptr item = mTradeModel->getItem(i).mBase; + const MWWorld::Ptr item = mTradeModel->getItem(static_cast(i)).mBase; MWBase::Environment::get().getWindowManager()->playSound(item.getClass().getDownSoundId(item)); mItemView->update(); } else { - mDragAndDrop->startDrag(i, mSortModel, mTradeModel, mItemView, count); + mDragAndDrop->startDrag(static_cast(i), mSortModel, mTradeModel, mItemView, count); } MWBase::Environment::get().getWindowManager()->updateSpellWindow(); @@ -902,7 +902,7 @@ namespace MWGui for (size_t i = 0; i < model.getItemCount(); ++i) { cycled += incr; - cycled = (cycled + model.getItemCount()) % model.getItemCount(); + cycled = static_cast((cycled + model.getItemCount()) % model.getItemCount()); MWWorld::Ptr item = model.getItem(cycled).mBase; @@ -947,18 +947,19 @@ namespace MWGui const MyGUI::IntSize previewWindowSize = mAvatarImage->getSize(); const float scale = MWBase::Environment::get().getWindowManager()->getScalingFactor(); - return MyGUI::IntSize(std::min(mPreview->getTextureWidth(), previewWindowSize.width * scale), - std::min(mPreview->getTextureHeight(), previewWindowSize.height * scale)); + return MyGUI::IntSize(std::min(mPreview->getTextureWidth(), static_cast(previewWindowSize.width * scale)), + std::min(mPreview->getTextureHeight(), static_cast(previewWindowSize.height * scale))); } - osg::Vec2f InventoryWindow::mapPreviewWindowToViewport(int x, int y) const + osg::Vec2i InventoryWindow::mapPreviewWindowToViewport(int x, int y) const { const MyGUI::IntSize previewWindowSize = mAvatarImage->getSize(); - const float normalisedX = x / std::max(1.0f, previewWindowSize.width); - const float normalisedY = y / std::max(1.0f, previewWindowSize.height); + const float normalisedX = x / std::max(1.f, static_cast(previewWindowSize.width)); + const float normalisedY = y / std::max(1.f, static_cast(previewWindowSize.height)); const MyGUI::IntSize viewport = getPreviewViewportSize(); - return osg::Vec2f(normalisedX * float(viewport.width - 1), (1.0 - normalisedY) * float(viewport.height - 1)); + return osg::Vec2i(static_cast(normalisedX * (viewport.width - 1)), + static_cast((1 - normalisedY) * (viewport.height - 1))); } ControllerButtons* InventoryWindow::getControllerButtons() diff --git a/apps/openmw/mwgui/inventorywindow.hpp b/apps/openmw/mwgui/inventorywindow.hpp index 1b0392d28b..5442b3271f 100644 --- a/apps/openmw/mwgui/inventorywindow.hpp +++ b/apps/openmw/mwgui/inventorywindow.hpp @@ -158,7 +158,7 @@ namespace MWGui void updateArmorRating(); MyGUI::IntSize getPreviewViewportSize() const; - osg::Vec2f mapPreviewWindowToViewport(int x, int y) const; + osg::Vec2i mapPreviewWindowToViewport(int x, int y) const; void adjustPanes(); diff --git a/apps/openmw/mwgui/itemchargeview.cpp b/apps/openmw/mwgui/itemchargeview.cpp index 59731717e1..06d77ed268 100644 --- a/apps/openmw/mwgui/itemchargeview.cpp +++ b/apps/openmw/mwgui/itemchargeview.cpp @@ -161,7 +161,7 @@ namespace MWGui mScrollView->setVisibleVScroll(true); if (Settings::gui().mControllerMenus) - updateControllerFocus(-1, mControllerFocus); + updateControllerFocus(mLines.size(), mControllerFocus); } void ItemChargeView::resetScrollbars() @@ -242,37 +242,37 @@ namespace MWGui if (mLines.empty()) return; - int prevFocus = mControllerFocus; + size_t prevFocus = mControllerFocus; if (button == SDL_CONTROLLER_BUTTON_A) { // Select the focused item, if any. - if (mControllerFocus >= 0 && mControllerFocus < static_cast(mLines.size())) + if (mControllerFocus < mLines.size()) onIconClicked(mLines[mControllerFocus].mIcon); } else if (button == SDL_CONTROLLER_BUTTON_DPAD_UP) - mControllerFocus = wrap(mControllerFocus - 1, mLines.size()); + mControllerFocus = wrap(mControllerFocus, mLines.size(), -1); else if (button == SDL_CONTROLLER_BUTTON_DPAD_DOWN) - mControllerFocus = wrap(mControllerFocus + 1, mLines.size()); + mControllerFocus = wrap(mControllerFocus, mLines.size(), 1); if (prevFocus != mControllerFocus) updateControllerFocus(prevFocus, mControllerFocus); } - void ItemChargeView::updateControllerFocus(int prevFocus, int newFocus) + void ItemChargeView::updateControllerFocus(size_t prevFocus, size_t newFocus) { if (mLines.empty()) return; const TextColours& textColours{ MWBase::Environment::get().getWindowManager()->getTextColours() }; - if (prevFocus >= 0 && prevFocus < static_cast(mLines.size())) + if (prevFocus < mLines.size()) { mLines[prevFocus].mText->setTextColour(textColours.normal); mLines[prevFocus].mIcon->setControllerFocus(false); } - if (newFocus >= 0 && newFocus < static_cast(mLines.size())) + if (newFocus < mLines.size()) { mLines[newFocus].mText->setTextColour(textColours.link); mLines[newFocus].mIcon->setControllerFocus(true); @@ -281,7 +281,7 @@ namespace MWGui if (newFocus <= 3) mScrollView->setViewOffset(MyGUI::IntPoint(0, 0)); else - mScrollView->setViewOffset(MyGUI::IntPoint(0, -55 * (newFocus - 3))); + mScrollView->setViewOffset(MyGUI::IntPoint(0, -55 * static_cast(newFocus - 3))); } } } diff --git a/apps/openmw/mwgui/itemchargeview.hpp b/apps/openmw/mwgui/itemchargeview.hpp index fd0388d83a..ecfefc1a34 100644 --- a/apps/openmw/mwgui/itemchargeview.hpp +++ b/apps/openmw/mwgui/itemchargeview.hpp @@ -75,8 +75,8 @@ namespace MWGui MyGUI::ScrollView* mScrollView; DisplayMode mDisplayMode; - int mControllerFocus = 0; - void updateControllerFocus(int prevFocus, int newFocus); + size_t mControllerFocus = 0; + void updateControllerFocus(size_t prevFocus, size_t newFocus); }; } diff --git a/apps/openmw/mwgui/itemmodel.cpp b/apps/openmw/mwgui/itemmodel.cpp index a4cf48fcbe..617014303e 100644 --- a/apps/openmw/mwgui/itemmodel.cpp +++ b/apps/openmw/mwgui/itemmodel.cpp @@ -109,9 +109,9 @@ namespace MWGui const ItemStack& itemToSearch = getItem(index); for (size_t i = 0; i < mSourceModel->getItemCount(); ++i) { - const ItemStack& item = mSourceModel->getItem(i); + const ItemStack& item = mSourceModel->getItem(static_cast(i)); if (item.mBase == itemToSearch.mBase) - return i; + return static_cast(i); } return -1; } @@ -121,9 +121,9 @@ namespace MWGui const ItemStack& itemToSearch = mSourceModel->getItem(index); for (size_t i = 0; i < getItemCount(); ++i) { - const ItemStack& item = getItem(i); + const ItemStack& item = getItem(static_cast(i)); if (item.mBase == itemToSearch.mBase) - return i; + return static_cast(i); } return -1; } diff --git a/apps/openmw/mwgui/itemtransfer.hpp b/apps/openmw/mwgui/itemtransfer.hpp index fbd37bf136..31f489f751 100644 --- a/apps/openmw/mwgui/itemtransfer.hpp +++ b/apps/openmw/mwgui/itemtransfer.hpp @@ -55,7 +55,7 @@ namespace MWGui WorldItemModel worldItemModel(0.5f, 0.5f); ItemModel* const targetModel = targetView == nullptr ? &worldItemModel : targetView->getModel(); - if (!targetModel->onDropItem(item.mBase, count)) + if (!targetModel->onDropItem(item.mBase, static_cast(count))) return; sourceView.getModel()->moveItem(item, count, targetModel); diff --git a/apps/openmw/mwgui/itemview.cpp b/apps/openmw/mwgui/itemview.cpp index 8fdb0b387d..ceaedf3b75 100644 --- a/apps/openmw/mwgui/itemview.cpp +++ b/apps/openmw/mwgui/itemview.cpp @@ -54,7 +54,7 @@ namespace MWGui int maxHeight = mScrollView->getHeight(); mRows = std::max(maxHeight / 42, 1); - mItemCount = dragArea->getChildCount(); + mItemCount = static_cast(dragArea->getChildCount()); bool showScrollbar = static_cast(std::ceil(mItemCount / float(mRows))) > mScrollView->getWidth() / 42; if (showScrollbar) { @@ -129,7 +129,7 @@ namespace MWGui if (item.mType == ItemStack::Type_Equipped) state = ItemWidget::Equip; itemWidget->setItem(item.mBase, state); - itemWidget->setCount(item.mCount); + itemWidget->setCount(static_cast(item.mCount)); itemWidget->eventMouseButtonClick += MyGUI::newDelegate(this, &ItemView::onSelectedItem); itemWidget->eventMouseWheel += MyGUI::newDelegate(this, &ItemView::onMouseWheelMoved); diff --git a/apps/openmw/mwgui/itemwidget.cpp b/apps/openmw/mwgui/itemwidget.cpp index 5e47577b27..801ec2d0c2 100644 --- a/apps/openmw/mwgui/itemwidget.cpp +++ b/apps/openmw/mwgui/itemwidget.cpp @@ -207,10 +207,12 @@ namespace MWGui scale = found->second; } + const int diameter = static_cast(44 * scale); if (state == Barter && !isMagic) - setFrame(backgroundTex, MyGUI::IntCoord(2 * scale, 2 * scale, 44 * scale, 44 * scale)); + setFrame(backgroundTex, + MyGUI::IntCoord(static_cast(2 * scale), static_cast(2 * scale), diameter, diameter)); else - setFrame(backgroundTex, MyGUI::IntCoord(0, 0, 44 * scale, 44 * scale)); + setFrame(backgroundTex, MyGUI::IntCoord(0, 0, diameter, diameter)); setIcon(ptr); } diff --git a/apps/openmw/mwgui/journalbooks.cpp b/apps/openmw/mwgui/journalbooks.cpp index 3e9916c345..c0b0708382 100644 --- a/apps/openmw/mwgui/journalbooks.cpp +++ b/apps/openmw/mwgui/journalbooks.cpp @@ -12,10 +12,10 @@ namespace { struct AddContent { - MWGui::BookTypesetter::Ptr mTypesetter; + std::shared_ptr mTypesetter; MWGui::BookTypesetter::Style* mBodyStyle; - explicit AddContent(MWGui::BookTypesetter::Ptr typesetter, MWGui::BookTypesetter::Style* bodyStyle) + explicit AddContent(std::shared_ptr typesetter, MWGui::BookTypesetter::Style* bodyStyle) : mTypesetter(std::move(typesetter)) , mBodyStyle(bodyStyle) { @@ -24,19 +24,19 @@ namespace struct AddSpan : AddContent { - explicit AddSpan(MWGui::BookTypesetter::Ptr typesetter, MWGui::BookTypesetter::Style* bodyStyle) + explicit AddSpan(std::shared_ptr typesetter, MWGui::BookTypesetter::Style* bodyStyle) : AddContent(std::move(typesetter), bodyStyle) { } - void operator()(intptr_t topicId, size_t begin, size_t end) + void operator()(const MWDialogue::Topic* topic, size_t begin, size_t end) { MWGui::BookTypesetter::Style* style = mBodyStyle; const MWGui::TextColours& textColours = MWBase::Environment::get().getWindowManager()->getTextColours(); - if (topicId) + if (topic) style = mTypesetter->createHotStyle(mBodyStyle, textColours.journalLink, textColours.journalLinkOver, - textColours.journalLinkPressed, topicId); + textColours.journalLinkPressed, MWGui::TypesetBook::InteractiveId(topic)); mTypesetter->write(style, begin, end); } @@ -44,10 +44,10 @@ namespace struct AddEntry { - MWGui::BookTypesetter::Ptr mTypesetter; + std::shared_ptr mTypesetter; MWGui::BookTypesetter::Style* mBodyStyle; - AddEntry(MWGui::BookTypesetter::Ptr typesetter, MWGui::BookTypesetter::Style* bodyStyle) + AddEntry(std::shared_ptr typesetter, MWGui::BookTypesetter::Style* bodyStyle) : mTypesetter(std::move(typesetter)) , mBodyStyle(bodyStyle) { @@ -66,8 +66,8 @@ namespace bool mAddHeader; MWGui::BookTypesetter::Style* mHeaderStyle; - explicit AddJournalEntry(MWGui::BookTypesetter::Ptr typesetter, MWGui::BookTypesetter::Style* bodyStyle, - MWGui::BookTypesetter::Style* headerStyle, bool addHeader) + explicit AddJournalEntry(std::shared_ptr typesetter, + MWGui::BookTypesetter::Style* bodyStyle, MWGui::BookTypesetter::Style* headerStyle, bool addHeader) : AddEntry(std::move(typesetter), bodyStyle) , mAddHeader(addHeader) , mHeaderStyle(headerStyle) @@ -90,11 +90,12 @@ namespace struct AddTopicEntry : AddEntry { - intptr_t mContentId; + const MWGui::TypesetBook::Content* mContentId; MWGui::BookTypesetter::Style* mHeaderStyle; - explicit AddTopicEntry(MWGui::BookTypesetter::Ptr typesetter, MWGui::BookTypesetter::Style* bodyStyle, - MWGui::BookTypesetter::Style* headerStyle, intptr_t contentId) + explicit AddTopicEntry(std::shared_ptr typesetter, + MWGui::BookTypesetter::Style* bodyStyle, MWGui::BookTypesetter::Style* headerStyle, + const MWGui::TypesetBook::Content* contentId) : AddEntry(std::move(typesetter), bodyStyle) , mContentId(contentId) , mHeaderStyle(headerStyle) @@ -117,12 +118,12 @@ namespace struct AddTopicName : AddContent { - AddTopicName(MWGui::BookTypesetter::Ptr typesetter, MWGui::BookTypesetter::Style* style) + AddTopicName(std::shared_ptr typesetter, MWGui::BookTypesetter::Style* style) : AddContent(std::move(typesetter), style) { } - void operator()(MWGui::JournalViewModel::Utf8Span topicName) + void operator()(std::string_view topicName) { mTypesetter->write(mBodyStyle, topicName); mTypesetter->sectionBreak(); @@ -131,12 +132,12 @@ namespace struct AddQuestName : AddContent { - AddQuestName(MWGui::BookTypesetter::Ptr typesetter, MWGui::BookTypesetter::Style* style) + AddQuestName(std::shared_ptr typesetter, MWGui::BookTypesetter::Style* style) : AddContent(std::move(typesetter), style) { } - void operator()(MWGui::JournalViewModel::Utf8Span topicName) + void operator()(std::string_view topicName) { mTypesetter->write(mBodyStyle, topicName); mTypesetter->sectionBreak(); @@ -147,15 +148,6 @@ namespace namespace MWGui { - MWGui::BookTypesetter::Utf8Span to_utf8_span(std::string_view text) - { - typedef MWGui::BookTypesetter::Utf8Point point; - - point begin = reinterpret_cast(text.data()); - - return MWGui::BookTypesetter::Utf8Span(begin, begin + text.length()); - } - int getCyrillicIndexPageCount() { // For small font size split alphabet to two columns (2x15 characers), for big font size split it to three @@ -163,33 +155,30 @@ namespace MWGui return Settings::gui().mFontSize < 18 ? 2 : 3; } - typedef TypesetBook::Ptr book; - - JournalBooks::JournalBooks(JournalViewModel::Ptr model, ToUTF8::FromType encoding) + JournalBooks::JournalBooks(std::shared_ptr model, ToUTF8::FromType encoding) : mModel(std::move(model)) , mEncoding(encoding) , mIndexPagesCount(0) { } - book JournalBooks::createEmptyJournalBook() + std::shared_ptr JournalBooks::createEmptyJournalBook() { - BookTypesetter::Ptr typesetter = createTypesetter(); + std::shared_ptr typesetter = createTypesetter(); BookTypesetter::Style* header = typesetter->createStyle({}, journalHeaderColour); BookTypesetter::Style* body = typesetter->createStyle({}, MyGUI::Colour::Black); - typesetter->write(header, to_utf8_span("You have no journal entries!")); + typesetter->write(header, "You have no journal entries!"); typesetter->lineBreak(); - typesetter->write( - body, to_utf8_span("You should have gone though the starting quest and got an initial quest.")); + typesetter->write(body, "You should have gone though the starting quest and got an initial quest."); return typesetter->complete(); } - book JournalBooks::createJournalBook() + std::shared_ptr JournalBooks::createJournalBook() { - BookTypesetter::Ptr typesetter = createTypesetter(); + std::shared_ptr typesetter = createTypesetter(); BookTypesetter::Style* header = typesetter->createStyle({}, journalHeaderColour); BookTypesetter::Style* body = typesetter->createStyle({}, MyGUI::Colour::Black); @@ -199,49 +188,50 @@ namespace MWGui return typesetter->complete(); } - book JournalBooks::createTopicBook(uintptr_t topicId) + std::shared_ptr JournalBooks::createTopicBook(const MWDialogue::Topic& topic) { - BookTypesetter::Ptr typesetter = createTypesetter(); + std::shared_ptr typesetter = createTypesetter(); BookTypesetter::Style* header = typesetter->createStyle({}, journalHeaderColour); BookTypesetter::Style* body = typesetter->createStyle({}, MyGUI::Colour::Black); - mModel->visitTopicName(topicId, AddTopicName(typesetter, header)); + mModel->visitTopicName(topic, AddTopicName(typesetter, header)); - intptr_t contentId = typesetter->addContent(to_utf8_span(", \"")); + const TypesetBook::Content* contentId = typesetter->addContent(", \""); - mModel->visitTopicEntries(topicId, AddTopicEntry(typesetter, body, header, contentId)); + mModel->visitTopicEntries(topic, AddTopicEntry(typesetter, body, header, contentId)); return typesetter->complete(); } - book JournalBooks::createQuestBook(std::string_view questName) + std::shared_ptr JournalBooks::createQuestBook(std::string_view questName) { - BookTypesetter::Ptr typesetter = createTypesetter(); + std::shared_ptr typesetter = createTypesetter(); BookTypesetter::Style* header = typesetter->createStyle({}, journalHeaderColour); BookTypesetter::Style* body = typesetter->createStyle({}, MyGUI::Colour::Black); AddQuestName addName(typesetter, header); - addName(to_utf8_span(questName)); + addName(questName); mModel->visitJournalEntries(questName, AddJournalEntry(typesetter, body, header, false)); return typesetter->complete(); } - book JournalBooks::createTopicIndexBook() + std::shared_ptr JournalBooks::createTopicIndexBook() { bool isRussian = (mEncoding == ToUTF8::WINDOWS_1251); - BookTypesetter::Ptr typesetter = isRussian ? createCyrillicJournalIndex() : createLatinJournalIndex(); + std::shared_ptr typesetter + = isRussian ? createCyrillicJournalIndex() : createLatinJournalIndex(); return typesetter->complete(); } - BookTypesetter::Ptr JournalBooks::createLatinJournalIndex() + std::shared_ptr JournalBooks::createLatinJournalIndex() { - BookTypesetter::Ptr typesetter = BookTypesetter::create(92, 260); + std::shared_ptr typesetter = BookTypesetter::create(92, 260); typesetter->setSectionAlignment(BookTypesetter::AlignCenter); @@ -260,12 +250,12 @@ namespace MWGui const MWGui::TextColours& textColours = MWBase::Environment::get().getWindowManager()->getTextColours(); BookTypesetter::Style* style = typesetter->createHotStyle(body, textColours.journalTopic, - textColours.journalTopicOver, textColours.journalTopicPressed, (Utf8Stream::UnicodeChar)ch); + textColours.journalTopicOver, textColours.journalTopicPressed, Utf8Stream::UnicodeChar(ch)); if (i == 13) typesetter->sectionBreak(); - typesetter->write(style, to_utf8_span(buffer)); + typesetter->write(style, buffer); typesetter->lineBreak(); ch++; @@ -274,9 +264,9 @@ namespace MWGui return typesetter; } - BookTypesetter::Ptr JournalBooks::createCyrillicJournalIndex() + std::shared_ptr JournalBooks::createCyrillicJournalIndex() { - BookTypesetter::Ptr typesetter = BookTypesetter::create(92, 260); + std::shared_ptr typesetter = BookTypesetter::create(92, 260); typesetter->setSectionAlignment(BookTypesetter::AlignCenter); @@ -314,14 +304,14 @@ namespace MWGui if (i % sectionBreak == 0) typesetter->sectionBreak(); - typesetter->write(style, to_utf8_span(buffer)); + typesetter->write(style, buffer); typesetter->lineBreak(); } return typesetter; } - BookTypesetter::Ptr JournalBooks::createTypesetter() + std::shared_ptr JournalBooks::createTypesetter() { // TODO: determine page size from layout... return BookTypesetter::create(240, 320); diff --git a/apps/openmw/mwgui/journalbooks.hpp b/apps/openmw/mwgui/journalbooks.hpp index 3d55135d9c..73348d7beb 100644 --- a/apps/openmw/mwgui/journalbooks.hpp +++ b/apps/openmw/mwgui/journalbooks.hpp @@ -8,31 +8,29 @@ namespace MWGui { - MWGui::BookTypesetter::Utf8Span to_utf8_span(std::string_view text); int getCyrillicIndexPageCount(); const MyGUI::Colour journalHeaderColour = MyGUI::Colour(0.60f, 0.00f, 0.00f); struct JournalBooks { - typedef TypesetBook::Ptr Book; - JournalViewModel::Ptr mModel; + std::shared_ptr mModel; - JournalBooks(JournalViewModel::Ptr model, ToUTF8::FromType encoding); + JournalBooks(std::shared_ptr model, ToUTF8::FromType encoding); - Book createEmptyJournalBook(); - Book createJournalBook(); - Book createTopicBook(uintptr_t topicId); - Book createQuestBook(std::string_view questName); - Book createTopicIndexBook(); + std::shared_ptr createEmptyJournalBook(); + std::shared_ptr createJournalBook(); + std::shared_ptr createTopicBook(const MWDialogue::Topic& topic); + std::shared_ptr createQuestBook(std::string_view questName); + std::shared_ptr createTopicIndexBook(); ToUTF8::FromType mEncoding; int mIndexPagesCount; private: - BookTypesetter::Ptr createTypesetter(); - BookTypesetter::Ptr createLatinJournalIndex(); - BookTypesetter::Ptr createCyrillicJournalIndex(); + std::shared_ptr createTypesetter(); + std::shared_ptr createLatinJournalIndex(); + std::shared_ptr createCyrillicJournalIndex(); }; } diff --git a/apps/openmw/mwgui/journalviewmodel.cpp b/apps/openmw/mwgui/journalviewmodel.cpp index 8c47edc9ea..b3108be4cc 100644 --- a/apps/openmw/mwgui/journalviewmodel.cpp +++ b/apps/openmw/mwgui/journalviewmodel.cpp @@ -22,26 +22,15 @@ namespace MWGui struct JournalViewModelImpl : JournalViewModel { - typedef MWDialogue::KeywordSearch KeywordSearchT; + using TopicSearch = MWDialogue::KeywordSearch; mutable bool mKeywordSearchLoaded; - mutable KeywordSearchT mKeywordSearch; + mutable TopicSearch mKeywordSearch; JournalViewModelImpl() { mKeywordSearchLoaded = false; } virtual ~JournalViewModelImpl() = default; - /// \todo replace this nasty BS - static Utf8Span toUtf8Span(std::string_view str) - { - if (str.empty()) - return Utf8Span(Utf8Point(nullptr), Utf8Point(nullptr)); - - Utf8Point point = reinterpret_cast(str.data()); - - return Utf8Span(point, point + str.size()); - } - void load() override {} void unload() override @@ -57,7 +46,7 @@ namespace MWGui MWBase::Journal* journal = MWBase::Environment::get().getJournal(); for (const auto& [_, topic] : journal->getTopics()) - mKeywordSearch.seed(topic.getName(), intptr_t(&topic)); + mKeywordSearch.seed(topic.getName(), &topic); mKeywordSearchLoaded = true; } @@ -88,10 +77,8 @@ namespace MWGui mutable bool loaded; mutable std::string utf8text; - typedef std::pair Range; - // hyperlinks in @link# notation - mutable std::map mHyperLinks; + mutable std::map, const MWDialogue::Topic*> mHyperLinks; virtual std::string getText() const = 0; @@ -126,7 +113,7 @@ namespace MWGui utf8text.replace(posBegin, posEnd + 1 - posBegin, displayName); - intptr_t value = 0; + const MWDialogue::Topic* value = nullptr; if (mModel->mKeywordSearch.containsKeyword(topicName, value)) mHyperLinks[std::make_pair(posBegin, posBegin + displayName.size())] = value; } @@ -138,14 +125,14 @@ namespace MWGui } } - Utf8Span body() const override + std::string_view body() const override { ensureLoaded(); - return toUtf8Span(utf8text); + return utf8text; } - void visitSpans(std::function visitor) const override + void visitSpans(std::function visitor) const override { ensureLoaded(); mModel->ensureKeyWordSearchLoaded(); @@ -154,29 +141,24 @@ namespace MWGui && MWBase::Environment::get().getWindowManager()->getTranslationDataStorage().hasTranslation()) { size_t formatted = 0; // points to the first character that is not laid out yet - for (std::map::const_iterator it = mHyperLinks.begin(); it != mHyperLinks.end(); - ++it) + for (const auto& [range, topicId] : mHyperLinks) { - intptr_t topicId = it->second; - if (formatted < it->first.first) - visitor(0, formatted, it->first.first); - visitor(topicId, it->first.first, it->first.second); - formatted = it->first.second; + if (formatted < range.first) + visitor(0, formatted, range.first); + visitor(topicId, range.first, range.second); + formatted = range.second; } if (formatted < utf8text.size()) visitor(0, formatted, utf8text.size()); } else { - std::vector matches; + std::vector matches; mModel->mKeywordSearch.highlightKeywords(utf8text.begin(), utf8text.end(), matches); std::string::const_iterator i = utf8text.begin(); - for (std::vector::const_iterator it = matches.begin(); it != matches.end(); - ++it) + for (const TopicSearch::Match& match : matches) { - const KeywordSearchT::Match& match = *it; - if (i != match.mBeg) visitor(0, i - utf8text.begin(), match.mBeg - utf8text.begin()); @@ -234,7 +216,7 @@ namespace MWGui std::string getText() const override { return mEntry->getText(); } - Utf8Span timestamp() const override + std::string_view timestamp() const override { if (timestamp_buffer.empty()) { @@ -249,7 +231,7 @@ namespace MWGui timestamp_buffer = os.str(); } - return toUtf8Span(timestamp_buffer); + return timestamp_buffer; } }; @@ -291,10 +273,10 @@ namespace MWGui } } - void visitTopicName(TopicId topicId, std::function visitor) const override + void visitTopicName( + const MWDialogue::Topic& topic, std::function visitor) const override { - MWDialogue::Topic const& topic = *reinterpret_cast(topicId); - visitor(toUtf8Span(topic.getName())); + visitor(topic.getName()); } void visitTopicNamesStartingWith( @@ -327,19 +309,18 @@ namespace MWGui std::string getText() const override { return mEntry->getText(); } - Utf8Span source() const override { return toUtf8Span(mEntry->mActorName); } + std::string_view source() const override { return mEntry->mActorName; } }; - void visitTopicEntries(TopicId topicId, std::function visitor) const override + void visitTopicEntries( + const MWDialogue::Topic& topic, std::function visitor) const override { - MWDialogue::Topic const& topic = *reinterpret_cast(topicId); - for (const MWDialogue::Entry& entry : topic) visitor(TopicEntryImpl(this, topic, entry)); } }; - JournalViewModel::Ptr JournalViewModel::create() + std::shared_ptr JournalViewModel::create() { return std::make_shared(); } diff --git a/apps/openmw/mwgui/journalviewmodel.hpp b/apps/openmw/mwgui/journalviewmodel.hpp index 9b06ae465b..57cd3c3374 100644 --- a/apps/openmw/mwgui/journalviewmodel.hpp +++ b/apps/openmw/mwgui/journalviewmodel.hpp @@ -8,6 +8,11 @@ #include +namespace MWDialogue +{ + class Topic; +} + namespace MWGui { /// View-Model for the journal GUI @@ -18,13 +23,6 @@ namespace MWGui /// game data store. struct JournalViewModel { - typedef std::shared_ptr Ptr; - - typedef intptr_t QuestId; - typedef intptr_t TopicId; - typedef uint8_t const* Utf8Point; - typedef std::pair Utf8Span; - /// The base interface for both journal entries and topics. struct Entry { @@ -33,12 +31,12 @@ namespace MWGui /// This function returns a borrowed reference to the body of the /// journal entry. The returned reference becomes invalid when the /// entry is destroyed. - virtual Utf8Span body() const = 0; + virtual std::string_view body() const = 0; /// Visits each subset of text in the body, delivering the beginning /// and end of the span relative to the body, and a valid topic ID if /// the span represents a keyword, or zero if not. - virtual void visitSpans(std::function visitor) const = 0; + virtual void visitSpans(std::function visitor) const = 0; virtual ~Entry() = default; }; @@ -48,7 +46,7 @@ namespace MWGui { /// Returns a pre-formatted span of UTF8 encoded text representing /// the name of the NPC this portion of dialog was heard from. - virtual Utf8Span source() const = 0; + virtual std::string_view source() const = 0; virtual ~TopicEntry() = default; }; @@ -58,7 +56,7 @@ namespace MWGui { /// Returns a pre-formatted span of UTF8 encoded text representing /// the in-game date this entry was added to the journal. - virtual Utf8Span timestamp() const = 0; + virtual std::string_view timestamp() const = 0; virtual ~JournalEntry() = default; }; @@ -81,17 +79,19 @@ namespace MWGui std::string_view questName, std::function visitor) const = 0; /// provides the name of the topic specified by its id - virtual void visitTopicName(TopicId topicId, std::function visitor) const = 0; + virtual void visitTopicName( + const MWDialogue::Topic& topic, std::function visitor) const = 0; /// walks over the topics whose names start with the character virtual void visitTopicNamesStartingWith( Utf8Stream::UnicodeChar character, std::function visitor) const = 0; /// walks over the topic entries for the topic specified by its identifier - virtual void visitTopicEntries(TopicId topicId, std::function visitor) const = 0; + virtual void visitTopicEntries( + const MWDialogue::Topic& topic, std::function visitor) const = 0; // create an instance of the default journal view model implementation - static Ptr create(); + static std::shared_ptr create(); virtual ~JournalViewModel() = default; }; diff --git a/apps/openmw/mwgui/journalwindow.cpp b/apps/openmw/mwgui/journalwindow.cpp index c1fba27cfb..f7f76cfb6c 100644 --- a/apps/openmw/mwgui/journalwindow.cpp +++ b/apps/openmw/mwgui/journalwindow.cpp @@ -49,14 +49,12 @@ namespace { struct DisplayState { - unsigned int mPage; - Book mBook; + size_t mPage; + std::shared_ptr mBook; }; - typedef std::stack DisplayStateStack; - - DisplayStateStack mStates; - Book mTopicIndexBook; + std::stack mStates; + std::shared_ptr mTopicIndexBook; bool mQuestMode; bool mOptionsMode; bool mTopicsMode; @@ -91,7 +89,7 @@ namespace MWGui::BookPage* getPage(std::string_view name) { return getWidget(name); } - JournalWindowImpl(MWGui::JournalViewModel::Ptr model, bool questList, ToUTF8::FromType encoding) + JournalWindowImpl(std::shared_ptr model, bool questList, ToUTF8::FromType encoding) : JournalBooks(std::move(model), encoding) , JournalWindow() { @@ -123,7 +121,10 @@ namespace topicsList->eventItemSelected += MyGUI::newDelegate(this, &JournalWindowImpl::notifyTopicSelected); { - MWGui::BookPage::ClickCallback callback = [this](intptr_t linkId) { notifyTopicClicked(linkId); }; + MWGui::BookPage::ClickCallback callback = [this](MWGui::TypesetBook::InteractiveId linkId) { + const MWDialogue::Topic& topic = *reinterpret_cast(linkId); + notifyTopicClicked(topic); + }; getPage(LeftBookPage)->adviseLinkClicked(callback); getPage(RightBookPage)->adviseLinkClicked(std::move(callback)); @@ -135,8 +136,9 @@ namespace } { - MWGui::BookPage::ClickCallback callback - = [this](MWGui::TypesetBook::InteractiveId index) { notifyIndexLinkClicked(index); }; + MWGui::BookPage::ClickCallback callback = [this](MWGui::TypesetBook::InteractiveId index) { + notifyIndexLinkClicked(static_cast(index)); + }; getPage(LeftTopicIndex)->adviseLinkClicked(callback); getPage(CenterTopicIndex)->adviseLinkClicked(callback); @@ -159,8 +161,8 @@ namespace { // english button has a 7 pixel wide strip of garbage on its right edge nextButton->setSize(64 - 7, nextButton->getSize().height); - nextButton->setImageCoord( - MyGUI::IntCoord(0, 0, (64 - 7) * nextButtonScale, nextButton->getSize().height * nextButtonScale)); + nextButton->setImageCoord(MyGUI::IntCoord(0, 0, static_cast((64 - 7) * nextButtonScale), + static_cast(nextButton->getSize().height * nextButtonScale))); } if (!questList) @@ -240,18 +242,18 @@ namespace setBookMode(); - Book journalBook; + std::shared_ptr journalBook; if (mModel->isEmpty()) journalBook = createEmptyJournalBook(); else journalBook = createJournalBook(); - pushBook(journalBook, 0); + pushBook(journalBook); // fast forward to the last page if (!mStates.empty()) { - unsigned int& page = mStates.top().mPage; + size_t& page = mStates.top().mPage; page = mStates.top().mBook->pageCount() - 1; if (page % 2) --page; @@ -268,8 +270,8 @@ namespace { mModel->unload(); - getPage(LeftBookPage)->showPage(Book(), 0); - getPage(RightBookPage)->showPage(Book(), 0); + getPage(LeftBookPage)->showPage({}, 0); + getPage(RightBookPage)->showPage({}, 0); while (!mStates.empty()) mStates.pop(); @@ -315,7 +317,7 @@ namespace // TODO: figure out how to make "options" page overlay book page // correctly, so that text may show underneath - getPage(RightBookPage)->showPage(Book(), 0); + getPage(RightBookPage)->showPage({}, 0); // If in quest mode, ensure the quest list is updated if (mQuestMode) @@ -326,21 +328,21 @@ namespace MWBase::Environment::get().getWindowManager()->updateControllerButtonsOverlay(); } - void pushBook(Book& book, unsigned int page) + void pushBook(std::shared_ptr& book) { DisplayState bs; - bs.mPage = page; + bs.mPage = 0; bs.mBook = book; mStates.push(bs); updateShowingPages(); updateCloseJournalButton(); } - void replaceBook(Book& book, unsigned int page) + void replaceBook(std::shared_ptr& book) { assert(!mStates.empty()); mStates.top().mBook = book; - mStates.top().mPage = page; + mStates.top().mPage = 0; updateShowingPages(); } @@ -360,9 +362,9 @@ namespace void updateShowingPages() { - Book book; - unsigned int page; - unsigned int relPages; + std::shared_ptr book; + size_t page; + size_t relPages; if (!mStates.empty()) { @@ -393,8 +395,16 @@ namespace setVisible(PageOneNum, relPages > 0); setVisible(PageTwoNum, relPages > 1); - getPage(LeftBookPage)->showPage((relPages > 0) ? book : Book(), page + 0); - getPage(RightBookPage)->showPage((relPages > 0) ? std::move(book) : Book(), page + 1); + if (relPages > 0) + { + getPage(LeftBookPage)->showPage(book, page + 0); + getPage(RightBookPage)->showPage(std::move(book), page + 1); + } + else + { + getPage(LeftBookPage)->showPage({}, page + 0); + getPage(RightBookPage)->showPage({}, page + 1); + } setText(PageOneNum, page + 1); setText(PageTwoNum, page + 2); @@ -410,14 +420,14 @@ namespace notifyNextPage(sender); } - void notifyTopicClicked(intptr_t linkId) + void notifyTopicClicked(const MWDialogue::Topic& topic) { - Book topicBook = createTopicBook(linkId); + std::shared_ptr topicBook = createTopicBook(topic); if (mStates.size() > 1) - replaceBook(topicBook, 0); + replaceBook(topicBook); else - pushBook(topicBook, 0); + pushBook(topicBook); setVisible(OptionsOverlay, false); setVisible(OptionsBTN, true); @@ -434,22 +444,19 @@ namespace { ESM::RefId topic = ESM::RefId::stringRefId(topicIdString); const MWBase::Journal* journal = MWBase::Environment::get().getJournal(); - intptr_t topicId = 0; /// \todo get rid of intptr ids const auto it = journal->getTopics().find(topic); if (it != journal->getTopics().end()) - topicId = intptr_t(&it->second); - - notifyTopicClicked(topicId); + notifyTopicClicked(it->second); } void notifyQuestClicked(const std::string& name, int id) { - Book book = createQuestBook(name); + std::shared_ptr book = createQuestBook(name); if (mStates.size() > 1) - replaceBook(book, 0); + replaceBook(book); else - pushBook(book, 0); + pushBook(book); setVisible(OptionsOverlay, false); setVisible(OptionsBTN, true); @@ -508,7 +515,7 @@ namespace } } - void notifyIndexLinkClicked(MWGui::TypesetBook::InteractiveId index) + void notifyIndexLinkClicked(Utf8Stream::UnicodeChar index) { setVisible(LeftTopicIndex, false); setVisible(CenterTopicIndex, false); @@ -604,7 +611,7 @@ namespace if (Settings::gui().mControllerMenus) { addControllerButtons(list, mSelectedQuest); - setControllerFocusedQuest(MWGui::wrap(mSelectedQuest, mButtons.size())); + setControllerFocusedQuest(std::min(mSelectedQuest, mButtons.size())); } if (mAllQuests) @@ -663,8 +670,8 @@ namespace return; if (!mStates.empty()) { - unsigned int& page = mStates.top().mPage; - Book book = mStates.top().mBook; + size_t& page = mStates.top().mPage; + std::shared_ptr book = mStates.top().mBook; if (page + 2 < book->pageCount()) { @@ -682,7 +689,7 @@ namespace return; if (!mStates.empty()) { - unsigned int& page = mStates.top().mPage; + size_t& page = mStates.top().mPage; if (page >= 2) { @@ -718,8 +725,8 @@ namespace void setIndexControllerFocus(bool focused) { - int col = mSelectedIndex / mIndexRowCount; - int row = mSelectedIndex % mIndexRowCount; + size_t col = mSelectedIndex / mIndexRowCount; + size_t row = mSelectedIndex % mIndexRowCount; mTopicIndexBook->setColour(col, row, 0, focused ? MWGui::journalHeaderColour : MyGUI::Colour::Black); } @@ -728,7 +735,7 @@ namespace setIndexControllerFocus(false); int numChars = mEncoding == ToUTF8::WINDOWS_1251 ? 30 : 26; - int col = mSelectedIndex / mIndexRowCount; + size_t col = mSelectedIndex / mIndexRowCount; if (offset == -1) // Up { @@ -785,7 +792,8 @@ namespace if (mSelectedIndex >= 27) russianOffset++; // 27, not 28, because of skipping char 26 bool isRussian = (mEncoding == ToUTF8::WINDOWS_1251); - notifyIndexLinkClicked(isRussian ? mSelectedIndex + russianOffset : mSelectedIndex + 'A'); + size_t ch = isRussian ? mSelectedIndex + russianOffset : mSelectedIndex + 'A'; + notifyIndexLinkClicked(static_cast(ch)); } } else if (arg.button == SDL_CONTROLLER_BUTTON_B) // B: Back @@ -836,7 +844,7 @@ namespace return true; // Scroll through the list of quests or topics - setControllerFocusedQuest(MWGui::wrap(mSelectedQuest - 1, mButtons.size())); + setControllerFocusedQuest(MWGui::wrap(mSelectedQuest, mButtons.size(), -1)); } else moveSelectedIndex(-1); @@ -849,19 +857,19 @@ namespace return true; // Scroll through the list of quests or topics - setControllerFocusedQuest(MWGui::wrap(mSelectedQuest + 1, mButtons.size())); + setControllerFocusedQuest(MWGui::wrap(mSelectedQuest, mButtons.size(), 1)); } else moveSelectedIndex(1); } else if (arg.button == SDL_CONTROLLER_BUTTON_DPAD_LEFT && !mQuestMode && !mTopicsMode) - moveSelectedIndex(-mIndexRowCount); + moveSelectedIndex(-static_cast(mIndexRowCount)); else if (arg.button == SDL_CONTROLLER_BUTTON_DPAD_RIGHT && !mQuestMode && !mTopicsMode) - moveSelectedIndex(mIndexRowCount); + moveSelectedIndex(static_cast(mIndexRowCount)); else if (arg.button == SDL_CONTROLLER_BUTTON_LEFTSHOULDER && (mQuestMode || mTopicsMode)) { // Scroll up 5 items in the list of quests or topics - setControllerFocusedQuest(std::max(static_cast(mSelectedQuest) - 5, 0)); + setControllerFocusedQuest(mSelectedQuest >= 5 ? mSelectedQuest - 5 : 0); } else if (arg.button == SDL_CONTROLLER_BUTTON_RIGHTSHOULDER && (mQuestMode || mTopicsMode)) { @@ -945,7 +953,7 @@ namespace // glue the implementation to the interface std::unique_ptr MWGui::JournalWindow::create( - JournalViewModel::Ptr model, bool questList, ToUTF8::FromType encoding) + std::shared_ptr model, bool questList, ToUTF8::FromType encoding) { return std::make_unique(model, questList, encoding); } diff --git a/apps/openmw/mwgui/journalwindow.hpp b/apps/openmw/mwgui/journalwindow.hpp index 472065d565..ec8fae2106 100644 --- a/apps/openmw/mwgui/journalwindow.hpp +++ b/apps/openmw/mwgui/journalwindow.hpp @@ -36,10 +36,6 @@ namespace MWGui size_t mIndexRowCount = 1; size_t mSelectedQuest = 0; size_t mSelectedIndex = 0; - void moveSelectedIndex(int offset); - void setIndexControllerFocus(bool focused); - void setControllerFocusedQuest(size_t index); - bool optionsModeButtonHandler(const SDL_ControllerButtonEvent& arg); }; } diff --git a/apps/openmw/mwgui/levelupdialog.cpp b/apps/openmw/mwgui/levelupdialog.cpp index 149489e798..e4fa4fb95a 100644 --- a/apps/openmw/mwgui/levelupdialog.cpp +++ b/apps/openmw/mwgui/levelupdialog.cpp @@ -111,7 +111,7 @@ namespace MWGui for (const ESM::Attribute& attribute : MWBase::Environment::get().getESMStore()->get()) { - int val = creatureStats.getAttribute(attribute.mId).getBase(); + int val = static_cast(creatureStats.getAttribute(attribute.mId).getBase()); if (std::find(mSpentAttributes.begin(), mSpentAttributes.end(), attribute.mId) != mSpentAttributes.end()) { val += pcStats.getLevelupAttributeMultiplier(attribute.mId); @@ -202,8 +202,8 @@ namespace MWGui widgets.mValue->setEnabled(true); availableAttributes++; - float mult = pcStats.getLevelupAttributeMultiplier(attribute.mId); - mult = std::min(mult, 100 - pcStats.getAttribute(attribute.mId).getBase()); + int mult = pcStats.getLevelupAttributeMultiplier(attribute.mId); + mult = std::min(mult, static_cast(100 - pcStats.getAttribute(attribute.mId).getBase())); if (mult <= 1) widgets.mMultiplier->setCaption({}); else @@ -231,7 +231,7 @@ namespace MWGui { mControllerFocus = 0; for (size_t i = 0; i < mAttributeButtons.size(); i++) - setControllerFocus(mAttributeButtons, i, i == 0); + mAttributeButtons[i]->setStateSelected(i == 0); } // Play LevelUp Music diff --git a/apps/openmw/mwgui/loadingscreen.cpp b/apps/openmw/mwgui/loadingscreen.cpp index cae195e9aa..c1aeeb9518 100644 --- a/apps/openmw/mwgui/loadingscreen.cpp +++ b/apps/openmw/mwgui/loadingscreen.cpp @@ -120,8 +120,9 @@ namespace MWGui void operator()(osg::RenderInfo& renderInfo) const override { - int w = renderInfo.getCurrentCamera()->getViewport()->width(); - int h = renderInfo.getCurrentCamera()->getViewport()->height(); + const osg::Viewport* viewPort = renderInfo.getCurrentCamera()->getViewport(); + int w = static_cast(viewPort->width()); + int h = static_cast(viewPort->height()); mTexture->copyTexImage2D(*renderInfo.getState(), 0, 0, w, h); mOneshot = false; @@ -259,10 +260,10 @@ namespace MWGui return false; // the minimal delay before a loading screen shows - const float initialDelay = 0.05; + constexpr float initialDelay = 0.05f; bool alreadyShown = (mLastRenderTime > mLoadingOnTime); - float diff = (mTimer.time_m() - mLoadingOnTime); + double diff = (mTimer.time_m() - mLoadingOnTime); if (!alreadyShown) { diff --git a/apps/openmw/mwgui/loadingscreen.hpp b/apps/openmw/mwgui/loadingscreen.hpp index 35de331ee0..268e676b01 100644 --- a/apps/openmw/mwgui/loadingscreen.hpp +++ b/apps/openmw/mwgui/loadingscreen.hpp @@ -71,7 +71,7 @@ namespace MWGui size_t mProgress; bool mShowWallpaper; - float mOldIcoMin = 0.f; + double mOldIcoMin = 0.0; unsigned int mOldIcoMax = 0; MyGUI::Widget* mLoadingBox; diff --git a/apps/openmw/mwgui/mainmenu.cpp b/apps/openmw/mwgui/mainmenu.cpp index d9d5b5c33b..1e1a9e72cb 100644 --- a/apps/openmw/mwgui/mainmenu.cpp +++ b/apps/openmw/mwgui/mainmenu.cpp @@ -364,10 +364,10 @@ namespace MWGui // Trim off some of the excessive padding // TODO: perhaps do this within ImageButton? int height = requested.height; - button->setImageTile(MyGUI::IntSize(requested.width, requested.height - 16 * scale)); - button->setCoord( - (maxwidth - requested.width / scale) / 2, curH, requested.width / scale, height / scale - 16); - curH += height / scale - 16; + button->setImageTile(MyGUI::IntSize(requested.width, static_cast(requested.height - 16 * scale))); + button->setCoord(static_cast((maxwidth - requested.width / scale) / 2), curH, + static_cast(requested.width / scale), static_cast(height / scale - 16)); + curH += static_cast(height / scale - 16); } if (state == MWBase::StateManager::State_NoGame) diff --git a/apps/openmw/mwgui/mapwindow.cpp b/apps/openmw/mwgui/mapwindow.cpp index c6dc54c886..49e98f816d 100644 --- a/apps/openmw/mwgui/mapwindow.cpp +++ b/apps/openmw/mwgui/mapwindow.cpp @@ -92,7 +92,8 @@ namespace return Constants::CellGridRadius; if (!Settings::terrain().mDistantTerrain) return Constants::CellGridRadius; - const int viewingDistanceInCells = Settings::camera().mViewingDistance / Constants::CellSizeInUnits; + const int viewingDistanceInCells + = static_cast(Settings::camera().mViewingDistance / Constants::CellSizeInUnits); return std::clamp( viewingDistanceInCells, Constants::CellGridRadius, Settings::map().mMaxLocalViewingDistance.get()); } @@ -255,8 +256,8 @@ namespace MWGui { // normalized cell coordinates auto mapWidgetSize = getWidgetSize(); - return MyGUI::IntPoint(std::round((nX + cellX - mGrid.left) * mapWidgetSize), - std::round((nY - cellY + mGrid.bottom) * mapWidgetSize)); + return MyGUI::IntPoint(static_cast(std::round((nX + cellX - mGrid.left) * mapWidgetSize)), + static_cast(std::round((nY - cellY + mGrid.bottom) * mapWidgetSize))); } MyGUI::IntPoint LocalMapBase::getMarkerPosition(float worldX, float worldY, MarkerUserData& markerPos) const @@ -286,7 +287,7 @@ namespace MWGui } MyGUI::IntCoord LocalMapBase::getMarkerCoordinates( - float worldX, float worldY, MarkerUserData& markerPos, size_t markerSize) const + float worldX, float worldY, MarkerUserData& markerPos, unsigned short markerSize) const { int halfMarkerSize = markerSize / 2; auto position = getMarkerPosition(worldX, worldY, markerPos); @@ -320,7 +321,7 @@ namespace MWGui mLocalMap->setViewOffset(viewOffset); } - MyGUI::IntCoord LocalMapBase::getMarkerCoordinates(MyGUI::Widget* widget, size_t markerSize) const + MyGUI::IntCoord LocalMapBase::getMarkerCoordinates(MyGUI::Widget* widget, unsigned short markerSize) const { MarkerUserData& markerPos(*widget->getUserData()); auto position = getPosition(markerPos.cellX, markerPos.cellY, markerPos.nX, markerPos.nY); @@ -453,7 +454,7 @@ namespace MWGui } if (oldSize != MyGUI::IntSize{ mGrid.width(), mGrid.height() }) - setCanvasSize(mLocalMap, mGrid, getWidgetSize()); + setCanvasSize(mLocalMap, mGrid, static_cast(getWidgetSize())); // Delay the door markers update until scripts have been given a chance to run. // If we don't do this, door markers that should be disabled will still appear on the map. @@ -665,8 +666,7 @@ namespace MWGui { std::vector destNotes; CustomMarkerCollection::RangeType markers = mCustomMarkers.getMarkers(marker.dest); - for (CustomMarkerCollection::ContainerType::const_iterator iter = markers.first; iter != markers.second; - ++iter) + for (auto iter = markers.first; iter != markers.second; ++iter) destNotes.push_back(iter->second.mNote); MyGUI::Widget* markerWidget = nullptr; @@ -733,9 +733,10 @@ namespace MWGui void LocalMapBase::updateLocalMap() { auto mapWidgetSize = getWidgetSize(); - setCanvasSize(mLocalMap, mGrid, getWidgetSize()); + setCanvasSize(mLocalMap, mGrid, static_cast(getWidgetSize())); - const auto size = MyGUI::IntSize(std::ceil(mapWidgetSize), std::ceil(mapWidgetSize)); + const auto size + = MyGUI::IntSize(static_cast(std::ceil(mapWidgetSize)), static_cast(std::ceil(mapWidgetSize))); for (auto& entry : mMaps) { const auto position = getPosition(entry.mCellX, entry.mCellY, 0, 0); @@ -917,7 +918,7 @@ namespace MWGui const int localWidgetSize = Settings::map().mLocalMapWidgetSize; const bool zoomOut = rel < 0; const bool zoomIn = !zoomOut; - const double speedDiff = zoomOut ? 1.0 / speed : speed; + const float speedDiff = zoomOut ? 1.f / speed : speed; const float currentMinLocalMapZoom = std::max({ (float(Settings::map().mGlobalMapCellSize) * 4.f) / float(localWidgetSize), @@ -985,8 +986,8 @@ namespace MWGui Settings::map().mGlobal ? updateGlobalMap() : updateLocalMap(); - map->setViewOffset(MyGUI::IntPoint(std::round(centerView.left * speedDiff) + cursor.left, - std::round(centerView.top * speedDiff) + cursor.top)); + map->setViewOffset(MyGUI::IntPoint(static_cast(std::round(centerView.left * speedDiff) + cursor.left), + static_cast(std::round(centerView.top * speedDiff) + cursor.top))); } void MapWindow::updateGlobalMap() @@ -1004,7 +1005,8 @@ namespace MWGui for (auto& [marker, col] : mGlobalMapMarkers) { - marker.widget->setCoord(createMarkerCoords(marker.position.x(), marker.position.y(), col.size())); + marker.widget->setCoord( + createMarkerCoords(marker.position.x(), marker.position.y(), static_cast(col.size()))); marker.widget->setVisible(marker.widget->getHeight() >= 6); } } @@ -1036,10 +1038,10 @@ namespace MWGui // Restore the window to pinned size. MyGUI::Window* window = mMainWidget->castType(); MyGUI::IntSize viewSize = MyGUI::RenderManager::getInstance().getViewSize(); - const float x = Settings::windows().mMapX * viewSize.width; - const float y = Settings::windows().mMapY * viewSize.height; - const float w = Settings::windows().mMapW * viewSize.width; - const float h = Settings::windows().mMapH * viewSize.height; + const int x = static_cast(Settings::windows().mMapX * viewSize.width); + const int y = static_cast(Settings::windows().mMapY * viewSize.height); + const int w = static_cast(Settings::windows().mMapW * viewSize.width); + const int h = static_cast(Settings::windows().mMapH * viewSize.height); window->setCoord(x, y, w, h); } } @@ -1063,10 +1065,10 @@ namespace MWGui worldPosToGlobalMapImageSpace( (x + 0.5f) * Constants::CellSizeInUnits, (y + 0.5f) * Constants::CellSizeInUnits, worldX, worldY); - const float markerSize = getMarkerSize(agregatedWeight); + const float markerSize = getMarkerSize(static_cast(agregatedWeight)); const float halfMarkerSize = markerSize / 2.0f; return MyGUI::IntCoord(static_cast(worldX - halfMarkerSize), static_cast(worldY - halfMarkerSize), - markerSize, markerSize); + static_cast(markerSize), static_cast(markerSize)); } MyGUI::Widget* MapWindow::createMarker(const std::string& name, float x, float y, float agregatedWeight) @@ -1075,7 +1077,7 @@ namespace MWGui "MarkerButton", createMarkerCoords(x, y, agregatedWeight), MyGUI::Align::Default); markerWidget->setVisible(markerWidget->getHeight() >= 6.0); markerWidget->setUserString("Caption_TextOneLine", "#{sCell=" + name + "}"); - setGlobalMapMarkerTooltip(markerWidget, x, y); + setGlobalMapMarkerTooltip(markerWidget, static_cast(x), static_cast(y)); markerWidget->setUserString("ToolTipLayout", "TextToolTipOneLine"); @@ -1098,14 +1100,15 @@ namespace MWGui cell.second = y; if (mMarkers.insert(cell).second) { - MapMarkerType mapMarkerWidget = { osg::Vec2f(x, y), createMarker(name, x, y, 0) }; + const osg::Vec2f pos(static_cast(x), static_cast(y)); + MapMarkerType mapMarkerWidget = { pos, createMarker(name, pos.x(), pos.y(), 0) }; mGlobalMapMarkers.emplace(mapMarkerWidget, std::vector()); const std::string markerName = name.substr(0, name.find(',')); auto& entry = mGlobalMapMarkersByName[markerName]; if (!entry.widget) { - entry = { osg::Vec2f(x, y), entry.widget }; // update the coords + entry = { pos, entry.widget }; // update the coords entry.widget = createMarker(markerName, entry.position.x(), entry.position.y(), 1); mGlobalMapMarkers.emplace(entry, std::vector{ entry }); @@ -1123,7 +1126,8 @@ namespace MWGui [](const auto& left, const auto& right) { return left + right.position; }) / float(elements.size()); - marker.widget->setCoord(createMarkerCoords(marker.position.x(), marker.position.y(), elements.size())); + marker.widget->setCoord( + createMarkerCoords(marker.position.x(), marker.position.y(), static_cast(elements.size()))); marker.widget->setVisible(marker.widget->getHeight() >= 6); } } @@ -1167,16 +1171,16 @@ namespace MWGui { float markerSize = 12.f * mGlobalMapZoom; if (mGlobalMapZoom < 1) - return markerSize * std::sqrt(agregatedWeight); // we want to see agregated object + return static_cast(markerSize * std::sqrt(agregatedWeight)); // we want to see agregated object return agregatedWeight ? 0 : markerSize; // we want to see only original markers (i.e. non agregated) } void MapWindow::resizeGlobalMap() { - mGlobalMap->setCanvasSize( - mGlobalMapRender->getWidth() * mGlobalMapZoom, mGlobalMapRender->getHeight() * mGlobalMapZoom); - mGlobalMapImage->setSize( - mGlobalMapRender->getWidth() * mGlobalMapZoom, mGlobalMapRender->getHeight() * mGlobalMapZoom); + int width = static_cast(mGlobalMapRender->getWidth() * mGlobalMapZoom); + int height = static_cast(mGlobalMapRender->getHeight() * mGlobalMapZoom); + mGlobalMap->setCanvasSize(width, height); + mGlobalMapImage->setSize(width, height); } void MapWindow::worldPosToGlobalMapImageSpace(float x, float y, float& imageX, float& imageY) const @@ -1191,7 +1195,8 @@ namespace MWGui LocalMapBase::updateCustomMarkers(); for (auto& [widgetPair, ignore] : mGlobalMapMarkers) - setGlobalMapMarkerTooltip(widgetPair.widget, widgetPair.position.x(), widgetPair.position.y()); + setGlobalMapMarkerTooltip(widgetPair.widget, static_cast(widgetPair.position.x()), + static_cast(widgetPair.position.y())); } void MapWindow::onDragStart(MyGUI::Widget* /*sender*/, int left, int top, MyGUI::MouseButton id) @@ -1574,7 +1579,7 @@ namespace MWGui { if (getDeleteButtonShown()) { - mControllerFocus = wrap(mControllerFocus - 1, 3); + mControllerFocus = wrap(mControllerFocus, 3, -1); mDeleteButton->setStateSelected(mControllerFocus == 0); mOkButton->setStateSelected(mControllerFocus == 1); mCancelButton->setStateSelected(mControllerFocus == 2); @@ -1590,7 +1595,7 @@ namespace MWGui { if (getDeleteButtonShown()) { - mControllerFocus = wrap(mControllerFocus + 1, 3); + mControllerFocus = wrap(mControllerFocus, 3, 1); mDeleteButton->setStateSelected(mControllerFocus == 0); mOkButton->setStateSelected(mControllerFocus == 1); mCancelButton->setStateSelected(mControllerFocus == 2); diff --git a/apps/openmw/mwgui/mapwindow.hpp b/apps/openmw/mwgui/mapwindow.hpp index eb49f8673e..c4e9998e5a 100644 --- a/apps/openmw/mwgui/mapwindow.hpp +++ b/apps/openmw/mwgui/mapwindow.hpp @@ -163,9 +163,9 @@ namespace MWGui MyGUI::IntPoint getPosition(int cellX, int cellY, float nx, float ny) const; MyGUI::IntPoint getMarkerPosition(float worldX, float worldY, MarkerUserData& markerPos) const; MyGUI::IntCoord getMarkerCoordinates( - float worldX, float worldY, MarkerUserData& markerPos, size_t markerSize) const; + float worldX, float worldY, MarkerUserData& markerPos, unsigned short markerSize) const; MyGUI::Widget* createDoorMarker(const std::string& name, float x, float y) const; - MyGUI::IntCoord getMarkerCoordinates(MyGUI::Widget* widget, size_t markerSize) const; + MyGUI::IntCoord getMarkerCoordinates(MyGUI::Widget* widget, unsigned short markerSize) const; virtual void notifyPlayerUpdate() {} virtual void centerView(); @@ -225,7 +225,7 @@ namespace MWGui MyGUI::Button* mDeleteButton; bool onControllerButtonEvent(const SDL_ControllerButtonEvent& arg) override; - int mControllerFocus = 0; + size_t mControllerFocus = 0; }; class MapWindow : public MWGui::WindowPinnableBase, public LocalMapBase, public NoDrop diff --git a/apps/openmw/mwgui/merchantrepair.cpp b/apps/openmw/mwgui/merchantrepair.cpp index 20c17aa701..dcd9b6b615 100644 --- a/apps/openmw/mwgui/merchantrepair.cpp +++ b/apps/openmw/mwgui/merchantrepair.cpp @@ -191,7 +191,7 @@ namespace MWGui return true; mButtons[mControllerFocus].first->setStateSelected(false); - mControllerFocus = wrap(mControllerFocus - 1, mButtons.size()); + mControllerFocus = wrap(mControllerFocus, mButtons.size(), -1); mButtons[mControllerFocus].first->setStateSelected(true); } else if (arg.button == SDL_CONTROLLER_BUTTON_DPAD_DOWN) @@ -200,7 +200,7 @@ namespace MWGui return true; mButtons[mControllerFocus].first->setStateSelected(false); - mControllerFocus = wrap(mControllerFocus + 1, mButtons.size()); + mControllerFocus = wrap(mControllerFocus, mButtons.size(), 1); mButtons[mControllerFocus].first->setStateSelected(true); } @@ -213,7 +213,7 @@ namespace MWGui else { const int lineHeight = Settings::gui().mFontSize + 2; - mList->setViewOffset(MyGUI::IntPoint(0, -lineHeight * (line - 5))); + mList->setViewOffset(MyGUI::IntPoint(0, -lineHeight * static_cast(line - 5))); } } diff --git a/apps/openmw/mwgui/messagebox.cpp b/apps/openmw/mwgui/messagebox.cpp index 1e2c7aa0d7..986f77b6ee 100644 --- a/apps/openmw/mwgui/messagebox.cpp +++ b/apps/openmw/mwgui/messagebox.cpp @@ -473,7 +473,7 @@ namespace MWGui return true; setControllerFocus(mButtons, mControllerFocus, false); - mControllerFocus = wrap(mControllerFocus - 1, mButtons.size()); + mControllerFocus = wrap(mControllerFocus, mButtons.size(), -1); setControllerFocus(mButtons, mControllerFocus, true); } else if (arg.button == SDL_CONTROLLER_BUTTON_DPAD_DOWN || arg.button == SDL_CONTROLLER_BUTTON_DPAD_RIGHT) @@ -484,7 +484,7 @@ namespace MWGui return true; setControllerFocus(mButtons, mControllerFocus, false); - mControllerFocus = wrap(mControllerFocus + 1, mButtons.size()); + mControllerFocus = wrap(mControllerFocus, mButtons.size(), 1); setControllerFocus(mButtons, mControllerFocus, true); } diff --git a/apps/openmw/mwgui/pickpocketitemmodel.cpp b/apps/openmw/mwgui/pickpocketitemmodel.cpp index 8756427589..c2caeac8ea 100644 --- a/apps/openmw/mwgui/pickpocketitemmodel.cpp +++ b/apps/openmw/mwgui/pickpocketitemmodel.cpp @@ -34,7 +34,7 @@ namespace MWGui for (size_t i = 0; i < mSourceModel->getItemCount(); ++i) { if (Misc::Rng::roll0to99(prng) > chance) - mHiddenItems.push_back(mSourceModel->getItem(i)); + mHiddenItems.push_back(mSourceModel->getItem(static_cast(i))); } } } @@ -64,7 +64,7 @@ namespace MWGui mItems.clear(); for (size_t i = 0; i < mSourceModel->getItemCount(); ++i) { - const ItemStack& item = mSourceModel->getItem(i); + const ItemStack& item = mSourceModel->getItem(static_cast(i)); // Bound items may not be stolen if (item.mFlags & ItemStack::Flag_Bound) diff --git a/apps/openmw/mwgui/postprocessorhud.cpp b/apps/openmw/mwgui/postprocessorhud.cpp index 401770179d..1d1bd6a2f2 100644 --- a/apps/openmw/mwgui/postprocessorhud.cpp +++ b/apps/openmw/mwgui/postprocessorhud.cpp @@ -172,16 +172,16 @@ namespace MWGui if (selected == MyGUI::ITEM_NONE) return; - int index = direction == Direction::Up ? static_cast(selected) - 1 : selected + 1; - index = std::clamp(index, 0, mActiveList->getItemCount() - 1); + size_t index = direction == Direction::Up ? selected - 1 : selected + 1; + index = std::clamp(index, 0, mActiveList->getItemCount() - 1); - if (static_cast(index) != selected) + if (index != selected) { auto technique = getTechnique(*mActiveList, selected); if (technique->getDynamic() || technique->getInternal()) return; - if (processor->enableTechnique(std::move(technique), index - mOffset) + if (processor->enableTechnique(std::move(technique), static_cast(index) - mOffset) != MWRender::PostProcessor::Status_Error) processor->saveChain(); } @@ -279,7 +279,7 @@ namespace MWGui void PostProcessorHud::notifyMouseWheel(MyGUI::Widget* /*sender*/, int rel) { - int offset = mConfigLayout->getViewOffset().top + rel * 0.3; + double offset = mConfigLayout->getViewOffset().top + rel * 0.3; if (offset > 0) mConfigLayout->setViewOffset(MyGUI::IntPoint(0, 0)); else diff --git a/apps/openmw/mwgui/quickkeysmenu.cpp b/apps/openmw/mwgui/quickkeysmenu.cpp index 0b33c6fa0f..a42ea5e566 100644 --- a/apps/openmw/mwgui/quickkeysmenu.cpp +++ b/apps/openmw/mwgui/quickkeysmenu.cpp @@ -290,8 +290,8 @@ namespace MWGui if (texture) scale = texture->getHeight() / 64.f; - mSelected->button->setFrame( - "textures\\menu_icon_select_magic_magic.dds", MyGUI::IntCoord(0, 0, 44 * scale, 44 * scale)); + mSelected->button->setFrame("textures\\menu_icon_select_magic_magic.dds", + MyGUI::IntCoord(0, 0, static_cast(44 * scale), static_cast(44 * scale))); mSelected->button->setIcon(item); mSelected->button->setUserString("ToolTipType", "ItemPtr"); @@ -324,8 +324,7 @@ namespace MWGui std::string path = effect->mIcon; std::replace(path.begin(), path.end(), '/', '\\'); - int slashPos = path.rfind('\\'); - path.insert(slashPos + 1, "b_"); + path.insert(path.rfind('\\') + 1, "b_"); path = Misc::ResourceHelpers::correctIconPath(path, MWBase::Environment::get().getResourceSystem()->getVFS()); float scale = 1.f; @@ -334,8 +333,8 @@ namespace MWGui if (texture) scale = texture->getHeight() / 64.f; - mSelected->button->setFrame( - "textures\\menu_icon_select_magic.dds", MyGUI::IntCoord(0, 0, 44 * scale, 44 * scale)); + const int diameter = static_cast(44 * scale); + mSelected->button->setFrame("textures\\menu_icon_select_magic.dds", MyGUI::IntCoord(0, 0, diameter, diameter)); mSelected->button->setIcon(path); if (mMagicSelectionDialog) @@ -562,9 +561,9 @@ namespace MWGui else if (arg.button == SDL_CONTROLLER_BUTTON_B) mParent->onCancelButtonClicked(mCancelButton); else if (arg.button == SDL_CONTROLLER_BUTTON_DPAD_UP) - mControllerFocus = wrap(mControllerFocus - 1, 4); + mControllerFocus = wrap(mControllerFocus, 4, -1); else if (arg.button == SDL_CONTROLLER_BUTTON_DPAD_DOWN) - mControllerFocus = wrap(mControllerFocus + 1, 4); + mControllerFocus = wrap(mControllerFocus, 4, 1); mItemButton->setStateSelected(mControllerFocus == 0); mMagicButton->setStateSelected(mControllerFocus == 1); diff --git a/apps/openmw/mwgui/quickkeysmenu.hpp b/apps/openmw/mwgui/quickkeysmenu.hpp index db20f13ad8..cfb75388d7 100644 --- a/apps/openmw/mwgui/quickkeysmenu.hpp +++ b/apps/openmw/mwgui/quickkeysmenu.hpp @@ -96,7 +96,7 @@ namespace MWGui QuickKeysMenu* mParent; bool onControllerButtonEvent(const SDL_ControllerButtonEvent& arg) override; - int mControllerFocus = 0; + size_t mControllerFocus = 0; }; class MagicSelectionDialog : public WindowModal @@ -117,7 +117,7 @@ namespace MWGui void onModelIndexSelected(SpellModel::ModelIndex index); bool onControllerButtonEvent(const SDL_ControllerButtonEvent& arg) override; - int mControllerFocus = 0; + size_t mControllerFocus = 0; }; } diff --git a/apps/openmw/mwgui/race.cpp b/apps/openmw/mwgui/race.cpp index ddcb843bf7..32754d9b2a 100644 --- a/apps/openmw/mwgui/race.cpp +++ b/apps/openmw/mwgui/race.cpp @@ -248,7 +248,7 @@ namespace MWGui void RaceDialog::onHeadRotate(MyGUI::ScrollBar* scroll, size_t position) { - float angle = (float(position) / (scroll->getScrollRange() - 1) - 0.5f) * osg::PI * 2; + float angle = (float(position) / (scroll->getScrollRange() - 1) - 0.5f) * osg::PIf * 2; mPreview->setAngle(angle); mCurrentAngle = angle; @@ -256,7 +256,7 @@ namespace MWGui void RaceDialog::onSelectPreviousGender(MyGUI::Widget*) { - mGenderIndex = wrap(mGenderIndex - 1, 2); + mGenderIndex = wrap(mGenderIndex, 2, -1); recountParts(); updatePreview(); @@ -264,7 +264,7 @@ namespace MWGui void RaceDialog::onSelectNextGender(MyGUI::Widget*) { - mGenderIndex = wrap(mGenderIndex + 1, 2); + mGenderIndex = wrap(mGenderIndex, 2, 1); recountParts(); updatePreview(); @@ -272,25 +272,25 @@ namespace MWGui void RaceDialog::onSelectPreviousFace(MyGUI::Widget*) { - mFaceIndex = wrap(mFaceIndex - 1, mAvailableHeads.size()); + mFaceIndex = wrap(mFaceIndex, mAvailableHeads.size(), -1); updatePreview(); } void RaceDialog::onSelectNextFace(MyGUI::Widget*) { - mFaceIndex = wrap(mFaceIndex + 1, mAvailableHeads.size()); + mFaceIndex = wrap(mFaceIndex, mAvailableHeads.size(), 1); updatePreview(); } void RaceDialog::onSelectPreviousHair(MyGUI::Widget*) { - mHairIndex = wrap(mHairIndex - 1, mAvailableHairs.size()); + mHairIndex = wrap(mHairIndex, mAvailableHairs.size(), -1); updatePreview(); } void RaceDialog::onSelectNextHair(MyGUI::Widget*) { - mHairIndex = wrap(mHairIndex + 1, mAvailableHairs.size()); + mHairIndex = wrap(mHairIndex, mAvailableHairs.size(), 1); updatePreview(); } @@ -359,10 +359,10 @@ namespace MWGui record.mRace = mCurrentRaceId; record.setIsMale(mGenderIndex == 0); - if (mFaceIndex >= 0 && mFaceIndex < int(mAvailableHeads.size())) + if (mFaceIndex < mAvailableHeads.size()) record.mHead = mAvailableHeads[mFaceIndex]; - if (mHairIndex >= 0 && mHairIndex < int(mAvailableHairs.size())) + if (mHairIndex < mAvailableHairs.size()) record.mHair = mAvailableHairs[mHairIndex]; try diff --git a/apps/openmw/mwgui/race.hpp b/apps/openmw/mwgui/race.hpp index e825bc4f72..71509f69ec 100644 --- a/apps/openmw/mwgui/race.hpp +++ b/apps/openmw/mwgui/race.hpp @@ -110,7 +110,7 @@ namespace MWGui MyGUI::Widget* mSpellPowerList; std::vector mSpellPowerItems; - int mGenderIndex, mFaceIndex, mHairIndex; + size_t mGenderIndex, mFaceIndex, mHairIndex; ESM::RefId mCurrentRaceId; diff --git a/apps/openmw/mwgui/review.cpp b/apps/openmw/mwgui/review.cpp index 53e5020dcf..08b9b80677 100644 --- a/apps/openmw/mwgui/review.cpp +++ b/apps/openmw/mwgui/review.cpp @@ -381,8 +381,8 @@ namespace MWGui } const MWMechanics::SkillValue& stat = skillValue->second; - int base = stat.getBase(); - int modified = stat.getModified(); + float base = stat.getBase(); + float modified = stat.getModified(); std::string state = "normal"; if (modified > base) @@ -577,13 +577,13 @@ namespace MWGui else if (arg.button == SDL_CONTROLLER_BUTTON_DPAD_UP || arg.button == SDL_CONTROLLER_BUTTON_DPAD_LEFT) { setControllerFocus(mButtons, mControllerFocus, false); - mControllerFocus = wrap(mControllerFocus - 1, mButtons.size()); + mControllerFocus = wrap(mControllerFocus, mButtons.size(), -1); setControllerFocus(mButtons, mControllerFocus, true); } else if (arg.button == SDL_CONTROLLER_BUTTON_DPAD_DOWN || arg.button == SDL_CONTROLLER_BUTTON_DPAD_RIGHT) { setControllerFocus(mButtons, mControllerFocus, false); - mControllerFocus = wrap(mControllerFocus + 1, mButtons.size()); + mControllerFocus = wrap(mControllerFocus, mButtons.size(), 1); setControllerFocus(mButtons, mControllerFocus, true); } diff --git a/apps/openmw/mwgui/review.hpp b/apps/openmw/mwgui/review.hpp index c3912606bc..91f808548e 100644 --- a/apps/openmw/mwgui/review.hpp +++ b/apps/openmw/mwgui/review.hpp @@ -104,7 +104,7 @@ namespace MWGui // 0 = Name, 1 = Race, 2 = Class, 3 = BirthSign, 4 = Back, 5 = OK std::vector mButtons; - int mControllerFocus = 0; + size_t mControllerFocus = 0; }; } #endif diff --git a/apps/openmw/mwgui/savegamedialog.cpp b/apps/openmw/mwgui/savegamedialog.cpp index b5bcc2c334..edd0949fb3 100644 --- a/apps/openmw/mwgui/savegamedialog.cpp +++ b/apps/openmw/mwgui/savegamedialog.cpp @@ -549,7 +549,7 @@ namespace MWGui else if (arg.button == SDL_CONTROLLER_BUTTON_Y) { size_t index = mCharacterSelection->getIndexSelected(); - index = wrap(index + 1, mCharacterSelection->getItemCount()); + index = wrap(index, mCharacterSelection->getItemCount(), 1); mCharacterSelection->setIndexSelected(index); onCharacterSelected(mCharacterSelection, index); MWBase::Environment::get().getWindowManager()->playSound(ESM::RefId::stringRefId("Menu Click")); diff --git a/apps/openmw/mwgui/settingswindow.cpp b/apps/openmw/mwgui/settingswindow.cpp index d292c84a74..0e13e4df49 100644 --- a/apps/openmw/mwgui/settingswindow.cpp +++ b/apps/openmw/mwgui/settingswindow.cpp @@ -241,7 +241,7 @@ namespace MWGui SettingsWindow::SettingsWindow(Files::ConfigurationManager& cfgMgr) : WindowBase("openmw_settings_window.layout") , mKeyboardMode(true) - , mCurrentPage(-1) + , mCurrentPage(static_cast(-1)) , mCfgMgr(cfgMgr) { const bool terrain = Settings::terrain().mDistantTerrain; @@ -629,7 +629,7 @@ namespace MWGui void SettingsWindow::onMaxLightsChanged(MyGUI::ComboBox* /*sender*/, size_t pos) { - Settings::shaders().mMaxLights.set(8 * (pos + 1)); + Settings::shaders().mMaxLights.set(8 * static_cast(pos + 1)); apply(); configureWidgets(mMainWidget, false); } @@ -752,7 +752,7 @@ namespace MWGui } else { - Settings::get(getSettingCategory(scroller), getSettingName(scroller)).set(pos); + Settings::get(getSettingCategory(scroller), getSettingName(scroller)).set(static_cast(pos)); valueStr = MyGUI::utility::toString(pos); } updateSliderLabel(scroller, valueStr); @@ -927,12 +927,12 @@ namespace MWGui const int h = Settings::gui().mFontSize + 2; const int w = mControlsBox->getWidth() - 28; const int noWidgetsInRow = 2; - const int totalH = mControlsBox->getChildCount() / noWidgetsInRow * h; + const int totalH = static_cast(mControlsBox->getChildCount() / noWidgetsInRow) * h; for (size_t i = 0; i < mControlsBox->getChildCount(); i++) { MyGUI::Widget* widget = mControlsBox->getChildAt(i); - widget->setCoord(0, i / noWidgetsInRow * h, w, h); + widget->setCoord(0, static_cast(i / noWidgetsInRow * h), w, h); } // Canvas size must be expressed with VScroll disabled, otherwise MyGUI would expand the scroll area when the @@ -1030,7 +1030,7 @@ namespace MWGui void SettingsWindow::onScriptListSelection(MyGUI::ListBox*, size_t index) { mScriptAdapter->detach(); - mCurrentPage = -1; + mCurrentPage = static_cast(-1); if (index < mScriptList->getItemCount()) { mCurrentPage = *mScriptList->getItemDataAt(index); @@ -1144,7 +1144,7 @@ namespace MWGui else if (arg.button == SDL_CONTROLLER_BUTTON_LEFTSHOULDER) { size_t index = mSettingsTab->getIndexSelected(); - index = wrap(index - 1, mSettingsTab->getItemCount()); + index = wrap(index, mSettingsTab->getItemCount(), -1); mSettingsTab->setIndexSelected(index); MWBase::Environment::get().getWindowManager()->playSound(ESM::RefId::stringRefId("Menu Click")); return true; @@ -1152,7 +1152,7 @@ namespace MWGui else if (arg.button == SDL_CONTROLLER_BUTTON_RIGHTSHOULDER) { size_t index = mSettingsTab->getIndexSelected(); - index = wrap(index + 1, mSettingsTab->getItemCount()); + index = wrap(index, mSettingsTab->getItemCount(), 1); mSettingsTab->setIndexSelected(index); MWBase::Environment::get().getWindowManager()->playSound(ESM::RefId::stringRefId("Menu Click")); return true; diff --git a/apps/openmw/mwgui/settingswindow.hpp b/apps/openmw/mwgui/settingswindow.hpp index d13d23e43b..45eda0f315 100644 --- a/apps/openmw/mwgui/settingswindow.hpp +++ b/apps/openmw/mwgui/settingswindow.hpp @@ -72,7 +72,7 @@ namespace MWGui MyGUI::Widget* mScriptDisabled; MyGUI::ScrollView* mScriptView; LuaUi::LuaAdapter* mScriptAdapter; - int mCurrentPage; + size_t mCurrentPage; void onTabChanged(MyGUI::TabControl* sender, size_t index); void onOkButtonClicked(MyGUI::Widget* sender); diff --git a/apps/openmw/mwgui/sortfilteritemmodel.cpp b/apps/openmw/mwgui/sortfilteritemmodel.cpp index 8c6277db4d..c660feb171 100644 --- a/apps/openmw/mwgui/sortfilteritemmodel.cpp +++ b/apps/openmw/mwgui/sortfilteritemmodel.cpp @@ -79,8 +79,6 @@ namespace if (mSortByType && left.mType != right.mType) return left.mType < right.mType; - float result = 0; - // compare items by type auto leftType = left.mBase.getType(); auto rightType = right.mBase.getType(); @@ -92,9 +90,11 @@ namespace std::string leftName = Utf8Stream::lowerCaseUtf8(left.mBase.getClass().getName(left.mBase)); std::string rightName = Utf8Stream::lowerCaseUtf8(right.mBase.getClass().getName(right.mBase)); - result = leftName.compare(rightName); - if (result != 0) - return result < 0; + { + int result = leftName.compare(rightName); + if (result != 0) + return result < 0; + } // compare items by enchantment: // 1. enchanted items showed before non-enchanted @@ -133,32 +133,38 @@ namespace } } - result = leftChargePercent - rightChargePercent; - if (result != 0) - return result > 0; + { + int result = leftChargePercent - rightChargePercent; + if (result != 0) + return result > 0; + } // compare items by condition if (left.mBase.getClass().hasItemHealth(left.mBase) && right.mBase.getClass().hasItemHealth(right.mBase)) { - result = left.mBase.getClass().getItemHealth(left.mBase) + int result = left.mBase.getClass().getItemHealth(left.mBase) - right.mBase.getClass().getItemHealth(right.mBase); if (result != 0) return result > 0; } // compare items by remaining usage time - result = left.mBase.getClass().getRemainingUsageTime(left.mBase) - - right.mBase.getClass().getRemainingUsageTime(right.mBase); - if (result != 0) - return result > 0; + { + float result = left.mBase.getClass().getRemainingUsageTime(left.mBase) + - right.mBase.getClass().getRemainingUsageTime(right.mBase); + if (result != 0) + return result > 0; + } // compare items by value - result = left.mBase.getClass().getValue(left.mBase) - right.mBase.getClass().getValue(right.mBase); - if (result != 0) - return result > 0; + { + int result = left.mBase.getClass().getValue(left.mBase) - right.mBase.getClass().getValue(right.mBase); + if (result != 0) + return result > 0; + } // compare items by weight - result = left.mBase.getClass().getWeight(left.mBase) - right.mBase.getClass().getWeight(right.mBase); + float result = left.mBase.getClass().getWeight(left.mBase) - right.mBase.getClass().getWeight(right.mBase); if (result != 0) return result > 0; @@ -377,16 +383,15 @@ namespace MWGui mItems.clear(); for (size_t i = 0; i < count; ++i) { - ItemStack item = mSourceModel->getItem(i); + ItemStack item = mSourceModel->getItem(static_cast(i)); - for (std::vector>::iterator it = mDragItems.begin(); it != mDragItems.end(); - ++it) + for (const std::pair& drag : mDragItems) { - if (item.mBase == it->first) + if (item.mBase == drag.first) { - if (item.mCount < it->second) + if (item.mCount < drag.second) throw std::runtime_error("Dragging more than present in the model"); - item.mCount -= it->second; + item.mCount -= drag.second; } } diff --git a/apps/openmw/mwgui/spellbuyingwindow.cpp b/apps/openmw/mwgui/spellbuyingwindow.cpp index a1e5fecd1e..0b9e5e3391 100644 --- a/apps/openmw/mwgui/spellbuyingwindow.cpp +++ b/apps/openmw/mwgui/spellbuyingwindow.cpp @@ -254,7 +254,7 @@ namespace MWGui return true; mSpellButtons[mControllerFocus].first->setStateSelected(false); - mControllerFocus = wrap(mControllerFocus - 1, mSpellButtons.size()); + mControllerFocus = wrap(mControllerFocus, mSpellButtons.size(), -1); mSpellButtons[mControllerFocus].first->setStateSelected(true); } else if (arg.button == SDL_CONTROLLER_BUTTON_DPAD_DOWN) @@ -265,7 +265,7 @@ namespace MWGui return true; mSpellButtons[mControllerFocus].first->setStateSelected(false); - mControllerFocus = wrap(mControllerFocus + 1, mSpellButtons.size()); + mControllerFocus = wrap(mControllerFocus, mSpellButtons.size(), 1); mSpellButtons[mControllerFocus].first->setStateSelected(true); } else @@ -280,7 +280,7 @@ namespace MWGui else { const int lineHeight = Settings::gui().mFontSize + 2; - mSpellsView->setViewOffset(MyGUI::IntPoint(0, -lineHeight * (line - 5))); + mSpellsView->setViewOffset(MyGUI::IntPoint(0, -lineHeight * static_cast(line - 5))); } // Warp the mouse to the selected spell to show the tooltip diff --git a/apps/openmw/mwgui/spellcreationdialog.cpp b/apps/openmw/mwgui/spellcreationdialog.cpp index bd4728928b..c471c036e3 100644 --- a/apps/openmw/mwgui/spellcreationdialog.cpp +++ b/apps/openmw/mwgui/spellcreationdialog.cpp @@ -224,7 +224,7 @@ namespace MWGui mEffectName->setCaptionWithReplacing("#{" + ESM::MagicEffect::indexToGmstString(effect->mIndex) + "}"); - mEffect.mEffectID = effect->mIndex; + mEffect.mEffectID = static_cast(effect->mIndex); mMagicEffect = effect; @@ -333,20 +333,20 @@ namespace MWGui void EditEffectDialog::setSkill(ESM::RefId skill) { - mEffect.mSkill = ESM::Skill::refIdToIndex(skill); + mEffect.mSkill = static_cast(ESM::Skill::refIdToIndex(skill)); eventEffectModified(mEffect); } void EditEffectDialog::setAttribute(ESM::RefId attribute) { - mEffect.mAttribute = ESM::Attribute::refIdToIndex(attribute); + mEffect.mAttribute = static_cast(ESM::Attribute::refIdToIndex(attribute)); eventEffectModified(mEffect); } void EditEffectDialog::onMagnitudeMinChanged(MyGUI::ScrollBar* sender, size_t pos) { mMagnitudeMinValue->setCaption(MyGUI::utility::toString(pos + 1)); - mEffect.mMagnMin = pos + 1; + mEffect.mMagnMin = static_cast(pos + 1); // trigger the check again (see below) onMagnitudeMaxChanged(mMagnitudeMaxSlider, mMagnitudeMaxSlider->getScrollPosition()); @@ -364,7 +364,7 @@ namespace MWGui sender->setScrollPosition(pos); } - mEffect.mMagnMax = pos + 1; + mEffect.mMagnMax = static_cast(pos + 1); const std::string to{ MWBase::Environment::get().getWindowManager()->getGameSettingString("sTo", "-") }; mMagnitudeMaxValue->setCaption(to + " " + MyGUI::utility::toString(pos + 1)); @@ -375,14 +375,14 @@ namespace MWGui void EditEffectDialog::onDurationChanged(MyGUI::ScrollBar* sender, size_t pos) { mDurationValue->setCaption(MyGUI::utility::toString(pos + 1)); - mEffect.mDuration = pos + 1; + mEffect.mDuration = static_cast(pos + 1); eventEffectModified(mEffect); } void EditEffectDialog::onAreaChanged(MyGUI::ScrollBar* sender, size_t pos) { mAreaValue->setCaption(MyGUI::utility::toString(pos)); - mEffect.mArea = pos; + mEffect.mArea = static_cast(pos); eventEffectModified(mEffect); } @@ -772,7 +772,7 @@ namespace MWGui mAddEffectDialog.setVisible(false); } - EffectEditorBase::~EffectEditorBase() {} + EffectEditorBase::~EffectEditorBase() = default; void EffectEditorBase::startEditing() { @@ -1014,7 +1014,7 @@ namespace MWGui void EffectEditorBase::onEffectAdded(ESM::ENAMstruct effect) { mEffects.push_back(effect); - mSelectedEffect = mEffects.size() - 1; + mSelectedEffect = static_cast(mEffects.size() - 1); updateEffectsView(); } @@ -1044,12 +1044,12 @@ namespace MWGui if (arg.button == SDL_CONTROLLER_BUTTON_A) { - if (!mRightColumn && mAvailableFocus >= 0 && mAvailableFocus < static_cast(mAvailableButtons.size())) + if (!mRightColumn && mAvailableFocus < mAvailableButtons.size()) { onAvailableEffectClicked(mAvailableButtons[mAvailableFocus]); winMgr->playSound(ESM::RefId::stringRefId("Menu Click")); } - else if (mRightColumn && mEffectFocus >= 0 && mEffectFocus < static_cast(mEffectButtons.size())) + else if (mRightColumn && mEffectFocus < mEffectButtons.size()) { onEditEffect(mEffectButtons[mEffectFocus].second); winMgr->playSound(ESM::RefId::stringRefId("Menu Click")); @@ -1062,44 +1062,44 @@ namespace MWGui } else if (arg.button == SDL_CONTROLLER_BUTTON_DPAD_UP) { - if (mRightColumn && mEffectButtons.size() > 0) + if (mRightColumn && !mEffectButtons.empty()) { - if (mEffectFocus >= 0 && mEffectFocus < static_cast(mEffectButtons.size())) + if (mEffectFocus < mEffectButtons.size()) mEffectButtons[mEffectFocus].first->setStateSelected(false); - mEffectFocus = wrap(mEffectFocus - 1, mEffectButtons.size()); + mEffectFocus = wrap(mEffectFocus, mEffectButtons.size(), -1); mEffectButtons[mEffectFocus].first->setStateSelected(true); } - else if (!mRightColumn && mAvailableButtons.size() > 0) + else if (!mRightColumn && !mAvailableButtons.empty()) { - if (mAvailableFocus >= 0 && mAvailableFocus < static_cast(mAvailableButtons.size())) + if (mAvailableFocus < mAvailableButtons.size()) mAvailableButtons[mAvailableFocus]->setStateSelected(false); - mAvailableFocus = wrap(mAvailableFocus - 1, mAvailableButtons.size()); + mAvailableFocus = wrap(mAvailableFocus, mAvailableButtons.size(), -1); mAvailableButtons[mAvailableFocus]->setStateSelected(true); } } else if (arg.button == SDL_CONTROLLER_BUTTON_DPAD_DOWN) { - if (mRightColumn && mEffectButtons.size() > 0) + if (mRightColumn && !mEffectButtons.empty()) { - if (mEffectFocus >= 0 && mEffectFocus < static_cast(mEffectButtons.size())) + if (mEffectFocus < mEffectButtons.size()) mEffectButtons[mEffectFocus].first->setStateSelected(false); - mEffectFocus = wrap(mEffectFocus + 1, mEffectButtons.size()); + mEffectFocus = wrap(mEffectFocus, mEffectButtons.size(), 1); mEffectButtons[mEffectFocus].first->setStateSelected(true); } - else if (!mRightColumn && mAvailableButtons.size() > 0) + else if (!mRightColumn && !mAvailableButtons.empty()) { - if (mAvailableFocus >= 0 && mAvailableFocus < static_cast(mAvailableButtons.size())) + if (mAvailableFocus < mAvailableButtons.size()) mAvailableButtons[mAvailableFocus]->setStateSelected(false); - mAvailableFocus = wrap(mAvailableFocus + 1, mAvailableButtons.size()); + mAvailableFocus = wrap(mAvailableFocus, mAvailableButtons.size(), 1); mAvailableButtons[mAvailableFocus]->setStateSelected(true); } } else if (arg.button == SDL_CONTROLLER_BUTTON_DPAD_LEFT && mRightColumn) { mRightColumn = false; - if (mEffectFocus >= 0 && mEffectFocus < static_cast(mEffectButtons.size())) + if (mEffectFocus < mEffectButtons.size()) mEffectButtons[mEffectFocus].first->setStateSelected(false); - if (mAvailableFocus >= 0 && mAvailableFocus < static_cast(mAvailableButtons.size())) + if (mAvailableFocus < mAvailableButtons.size()) mAvailableButtons[mAvailableFocus]->setStateSelected(true); winMgr->setControllerTooltipVisible(Settings::gui().mControllerTooltips); @@ -1107,9 +1107,9 @@ namespace MWGui else if (arg.button == SDL_CONTROLLER_BUTTON_DPAD_RIGHT && !mRightColumn && mEffectButtons.size() > 0) { mRightColumn = true; - if (mAvailableFocus >= 0 && mAvailableFocus < static_cast(mAvailableButtons.size())) + if (mAvailableFocus < mAvailableButtons.size()) mAvailableButtons[mAvailableFocus]->setStateSelected(false); - if (mEffectFocus >= 0 && mEffectFocus < static_cast(mEffectButtons.size())) + if (mEffectFocus < mEffectButtons.size()) mEffectButtons[mEffectFocus].first->setStateSelected(true); winMgr->setControllerTooltipVisible(false); @@ -1123,10 +1123,10 @@ namespace MWGui else { const int lineHeight = Settings::gui().mFontSize + 3; - mAvailableEffectsList->setViewOffset(-lineHeight * (mAvailableFocus - 5)); + mAvailableEffectsList->setViewOffset(-lineHeight * static_cast(mAvailableFocus - 5)); } - if (!mRightColumn && mAvailableFocus >= 0 && mAvailableFocus < static_cast(mAvailableButtons.size())) + if (!mRightColumn && mAvailableFocus < mAvailableButtons.size()) { // Warp the mouse to the selected spell to show the tooltip if (winMgr->getControllerTooltipVisible()) diff --git a/apps/openmw/mwgui/spellcreationdialog.hpp b/apps/openmw/mwgui/spellcreationdialog.hpp index 8d96a9727d..f3382817e7 100644 --- a/apps/openmw/mwgui/spellcreationdialog.hpp +++ b/apps/openmw/mwgui/spellcreationdialog.hpp @@ -153,9 +153,9 @@ namespace MWGui private: Type mType; - int mAvailableFocus; - int mEffectFocus; - bool mRightColumn; + size_t mAvailableFocus = 0; + size_t mEffectFocus = 0; + bool mRightColumn = false; std::vector mAvailableButtons; std::vector> mEffectButtons; }; diff --git a/apps/openmw/mwgui/spellview.cpp b/apps/openmw/mwgui/spellview.cpp index 8c64c92ce6..de18b25248 100644 --- a/apps/openmw/mwgui/spellview.cpp +++ b/apps/openmw/mwgui/spellview.cpp @@ -19,8 +19,6 @@ namespace MWGui { - const char* SpellView::sSpellModelIndex = "SpellModelIndex"; - SpellView::LineInfo::LineInfo( MyGUI::Widget* leftWidget, MyGUI::Widget* rightWidget, SpellModel::ModelIndex spellIndex) : mLeftWidget(leftWidget) @@ -29,15 +27,6 @@ namespace MWGui { } - SpellView::SpellView() - : mScrollView(nullptr) - , mShowCostColumn(true) - , mHighlightSelected(true) - , mControllerActiveWindow(false) - , mControllerFocus(0) - { - } - void SpellView::initialiseOverride() { Base::initialiseOverride(); @@ -126,7 +115,7 @@ namespace MWGui t->setCaption(spell.mName + captionSuffix); t->setTextAlign(MyGUI::Align::Left); adjustSpellWidget(spell, i, t); - mButtons.emplace_back(std::make_pair(t, i)); + mButtons.emplace_back(t, i); if (!spell.mCostColumn.empty() && mShowCostColumn) { @@ -199,7 +188,7 @@ namespace MWGui } // special case, look for spells added to model that are beyond last updatable item - SpellModel::ModelIndex topSpellIndex = mModel->getItemCount() - 1; + auto topSpellIndex = static_cast(mModel->getItemCount() - 1); if (fullUpdateRequired || ((0 <= topSpellIndex) && (maxSpellIndexFound < topSpellIndex))) { update(); @@ -235,8 +224,8 @@ namespace MWGui if (Settings::gui().mControllerMenus) { - mControllerFocus = wrap(mControllerFocus, mButtons.size()); - updateControllerFocus(-1, mControllerFocus); + mControllerFocus = std::min(mControllerFocus, mButtons.size()); + updateControllerFocus(mButtons.size(), mControllerFocus); } // Canvas size must be expressed with VScroll disabled, otherwise MyGUI would expand the scroll area when the @@ -307,7 +296,7 @@ namespace MWGui widget->setUserString("Spell", spell.mId.serialize()); } - widget->setUserString(sSpellModelIndex, MyGUI::utility::toString(index)); + widget->setUserString("SpellModelIndex", MyGUI::utility::toString(index)); widget->eventMouseWheel += MyGUI::newDelegate(this, &SpellView::onMouseWheelMoved); widget->eventMouseButtonClick += MyGUI::newDelegate(this, &SpellView::onSpellSelected); @@ -315,7 +304,7 @@ namespace MWGui SpellModel::ModelIndex SpellView::getSpellModelIndex(MyGUI::Widget* widget) { - return MyGUI::utility::parseInt(widget->getUserString(sSpellModelIndex)); + return MyGUI::utility::parseInt(widget->getUserString("SpellModelIndex")); } void SpellView::onSpellSelected(MyGUI::Widget* sender) @@ -349,14 +338,14 @@ namespace MWGui if (mButtons.empty()) return; - int prevFocus = mControllerFocus; + size_t prevFocus = mControllerFocus; MWBase::WindowManager* winMgr = MWBase::Environment::get().getWindowManager(); - + int delta = 0; switch (button) { case SDL_CONTROLLER_BUTTON_A: // Select the focused item, if any. - if (mControllerFocus >= 0 && mControllerFocus < static_cast(mButtons.size())) + if (mControllerFocus < mButtons.size()) { onSpellSelected(mButtons[mControllerFocus].first); MWBase::Environment::get().getWindowManager()->playSound(ESM::RefId::stringRefId("Menu Click")); @@ -368,25 +357,25 @@ namespace MWGui break; case SDL_CONTROLLER_BUTTON_DPAD_UP: winMgr->restoreControllerTooltips(); - mControllerFocus--; + delta = -1; break; case SDL_CONTROLLER_BUTTON_DPAD_DOWN: winMgr->restoreControllerTooltips(); - mControllerFocus++; + delta = 1; break; case SDL_CONTROLLER_BUTTON_DPAD_LEFT: winMgr->restoreControllerTooltips(); - mControllerFocus = std::max(0, mControllerFocus - 10); + delta = -10; break; case SDL_CONTROLLER_BUTTON_DPAD_RIGHT: winMgr->restoreControllerTooltips(); - mControllerFocus = std::min(mControllerFocus + 10, static_cast(mButtons.size()) - 1); + delta = 10; break; case SDL_CONTROLLER_BUTTON_LEFTSHOULDER: { // Jump to first item in previous group - int prevGroupIndex = 0; - for (int groupIndex : mGroupIndices) + size_t prevGroupIndex = 0; + for (size_t groupIndex : mGroupIndices) { if (groupIndex >= mControllerFocus) break; @@ -399,8 +388,8 @@ namespace MWGui case SDL_CONTROLLER_BUTTON_RIGHTSHOULDER: { // Jump to first item in next group - int newFocus = mControllerFocus; - for (int groupIndex : mGroupIndices) + size_t newFocus = mControllerFocus; + for (size_t groupIndex : mGroupIndices) { if (groupIndex > mControllerFocus) { @@ -418,27 +407,27 @@ namespace MWGui return; } - mControllerFocus = wrap(mControllerFocus, mButtons.size()); + mControllerFocus = wrap(mControllerFocus, mButtons.size(), delta); if (prevFocus != mControllerFocus) updateControllerFocus(prevFocus, mControllerFocus); else - updateControllerFocus(-1, mControllerFocus); + updateControllerFocus(mButtons.size(), mControllerFocus); } - void SpellView::updateControllerFocus(int prevFocus, int newFocus) + void SpellView::updateControllerFocus(size_t prevFocus, size_t newFocus) { if (mButtons.empty()) return; - if (prevFocus >= 0 && prevFocus < static_cast(mButtons.size())) + if (prevFocus < mButtons.size()) { Gui::SharedStateButton* prev = mButtons[prevFocus].first; if (prev) prev->onMouseLostFocus(nullptr); } - if (mControllerActiveWindow && newFocus >= 0 && newFocus < static_cast(mButtons.size())) + if (mControllerActiveWindow && newFocus < mButtons.size()) { Gui::SharedStateButton* focused = mButtons[newFocus].first; if (focused) diff --git a/apps/openmw/mwgui/spellview.hpp b/apps/openmw/mwgui/spellview.hpp index d1b9b53f7d..e054334b95 100644 --- a/apps/openmw/mwgui/spellview.hpp +++ b/apps/openmw/mwgui/spellview.hpp @@ -28,7 +28,7 @@ namespace MWGui { MYGUI_RTTI_DERIVED(SpellView) public: - SpellView(); + SpellView() {} /// Register needed components with MyGUI's factory manager static void registerComponents(); @@ -63,8 +63,6 @@ namespace MWGui void onControllerButton(const unsigned char button); private: - MyGUI::ScrollView* mScrollView; - std::unique_ptr mModel; /// tracks a row in the spell view @@ -90,28 +88,27 @@ namespace MWGui std::vector mLines; - bool mShowCostColumn; - bool mHighlightSelected; + /// Keep a list of buttons for controller navigation and their index in the full list. + std::vector> mButtons; + /// Keep a list of group offsets for controller navigation + std::vector mGroupIndices; + MyGUI::ScrollView* mScrollView = nullptr; + size_t mControllerFocus = 0; + + bool mShowCostColumn = true; + bool mHighlightSelected = true; + bool mControllerActiveWindow = false; void layoutWidgets(); void addGroup(const std::string& label1, const std::string& label2); void adjustSpellWidget(const Spell& spell, SpellModel::ModelIndex index, MyGUI::Widget* widget); - /// Keep a list of buttons for controller navigation and their index in the full list. - std::vector> mButtons; - /// Keep a list of group offsets for controller navigation - std::vector mGroupIndices; - - bool mControllerActiveWindow; - int mControllerFocus; - void updateControllerFocus(int prevFocus, int newFocus); + void updateControllerFocus(size_t prevFocus, size_t newFocus); void onSpellSelected(MyGUI::Widget* sender); void onMouseWheelMoved(MyGUI::Widget* sender, int rel); SpellModel::ModelIndex getSpellModelIndex(MyGUI::Widget* sender); - - static const char* sSpellModelIndex; }; } diff --git a/apps/openmw/mwgui/spellwindow.cpp b/apps/openmw/mwgui/spellwindow.cpp index 01b4a94e93..dfbb863795 100644 --- a/apps/openmw/mwgui/spellwindow.cpp +++ b/apps/openmw/mwgui/spellwindow.cpp @@ -255,7 +255,7 @@ namespace MWGui return; mSpellView->setModel(new SpellModel(MWMechanics::getPlayer())); - int itemCount = mSpellView->getModel()->getItemCount(); + int itemCount = static_cast(mSpellView->getModel()->getItemCount()); if (itemCount == 0) return; diff --git a/apps/openmw/mwgui/statswindow.cpp b/apps/openmw/mwgui/statswindow.cpp index 656adcb4b7..4323e7f25f 100644 --- a/apps/openmw/mwgui/statswindow.cpp +++ b/apps/openmw/mwgui/statswindow.cpp @@ -258,8 +258,8 @@ namespace MWGui MyGUI::TextBox* nameWidget = widgets.first; if (valueWidget && nameWidget) { - int modified = value.getModified(), base = value.getBase(); - std::string text = MyGUI::utility::toString(modified); + float modified = value.getModified(), base = value.getBase(); + std::string text = MyGUI::utility::toString(static_cast(modified)); std::string state = "normal"; if (modified > base) state = "increased"; @@ -341,8 +341,8 @@ namespace MWGui bool first = true; for (const auto& attribute : store->get()) { - float mult = playerStats.getLevelupAttributeMultiplier(attribute.mId); - mult = std::min(mult, 100 - playerStats.getAttribute(attribute.mId).getBase()); + int mult = playerStats.getLevelupAttributeMultiplier(attribute.mId); + mult = std::min(mult, static_cast(100 - playerStats.getAttribute(attribute.mId).getBase())); if (mult > 1) { if (!first) diff --git a/apps/openmw/mwgui/tooltips.cpp b/apps/openmw/mwgui/tooltips.cpp index 3abd238344..ec56644aa4 100644 --- a/apps/openmw/mwgui/tooltips.cpp +++ b/apps/openmw/mwgui/tooltips.cpp @@ -196,7 +196,8 @@ namespace MWGui = *focus->getUserData>(); mFocusObject = pair.second->getItem(pair.first).mBase; bool isAllowedToUse = pair.second->allowedToUseItems(); - tooltipSize = getToolTipViaPtr(pair.second->getItem(pair.first).mCount, false, !isAllowedToUse); + tooltipSize = getToolTipViaPtr( + static_cast(pair.second->getItem(pair.first).mCount), false, !isAllowedToUse); } else if (type == "ToolTipInfo") { @@ -960,8 +961,7 @@ namespace MWGui const std::string& name = ESM::MagicEffect::indexToGmstString(id); std::string icon = effect->mIcon; - int slashPos = icon.rfind('\\'); - icon.insert(slashPos + 1, "b_"); + icon.insert(icon.rfind('\\') + 1, "b_"); icon = Misc::ResourceHelpers::correctIconPath(icon, MWBase::Environment::get().getResourceSystem()->getVFS()); widget->setUserString("ToolTipType", "Layout"); diff --git a/apps/openmw/mwgui/tradeitemmodel.cpp b/apps/openmw/mwgui/tradeitemmodel.cpp index 660e940367..d4af1dc991 100644 --- a/apps/openmw/mwgui/tradeitemmodel.cpp +++ b/apps/openmw/mwgui/tradeitemmodel.cpp @@ -152,14 +152,14 @@ namespace MWGui size_t i = 0; for (; i < sourceModel->getItemCount(); ++i) { - if (itemStack.mBase == sourceModel->getItem(i).mBase) + if (itemStack.mBase == sourceModel->getItem(static_cast(i)).mBase) break; } if (i == sourceModel->getItemCount()) throw std::runtime_error("The borrowed item disappeared"); - sourceModel->moveItem( - sourceModel->getItem(i), itemStack.mCount, this, !Settings::game().mPreventMerchantEquipping); + sourceModel->moveItem(sourceModel->getItem(static_cast(i)), itemStack.mCount, this, + !Settings::game().mPreventMerchantEquipping); } mBorrowedToUs.clear(); mBorrowedFromUs.clear(); @@ -177,7 +177,7 @@ namespace MWGui // add regular items for (size_t i = 0; i < mSourceModel->getItemCount(); ++i) { - ItemStack item = mSourceModel->getItem(i); + ItemStack item = mSourceModel->getItem(static_cast(i)); if (!mMerchant.isEmpty()) { MWWorld::Ptr base = item.mBase; diff --git a/apps/openmw/mwgui/tradewindow.cpp b/apps/openmw/mwgui/tradewindow.cpp index d238db70c9..00d8f37fc8 100644 --- a/apps/openmw/mwgui/tradewindow.cpp +++ b/apps/openmw/mwgui/tradewindow.cpp @@ -298,7 +298,7 @@ namespace MWGui const ItemStack& item = mSortModel->getItem(index); MWWorld::Ptr object = item.mBase; - int count = item.mCount; + size_t count = item.mCount; bool shift = MyGUI::InputManager::getInstance().isShiftPressed(); if (MyGUI::InputManager::getInstance().isControlPressed()) count = 1; @@ -309,7 +309,7 @@ namespace MWGui std::string message = "#{sQuanityMenuMessage02}"; std::string name{ object.getClass().getName(object) }; name += MWGui::ToolTips::getSoulString(object.getCellRef()); - dialog->openCountDialog(name, message, count); + dialog->openCountDialog(name, message, static_cast(count)); dialog->eventOkClicked.clear(); dialog->eventOkClicked += MyGUI::newDelegate(this, &TradeWindow::sellItem); mItemToSell = mSortModel->mapToSource(index); @@ -335,14 +335,14 @@ namespace MWGui // this was an item borrowed to us by the player mTradeModel->returnItemBorrowedToUs(mItemToSell, count); playerTradeModel->returnItemBorrowedFromUs(mItemToSell, mTradeModel, count); - buyFromNpc(item.mBase, count, true); + updateOffer(); } else { // borrow item to player playerTradeModel->borrowItemToUs(mItemToSell, mTradeModel, count); mTradeModel->borrowItemFromUs(mItemToSell, count); - buyFromNpc(item.mBase, count, false); + updateOffer(); } MWBase::Environment::get().getWindowManager()->getInventoryWindow()->updateItemView(); @@ -355,17 +355,16 @@ namespace MWGui = MWBase::Environment::get().getWindowManager()->getInventoryWindow()->getTradeModel(); mTradeModel->borrowItemToUs(index, playerTradeModel, count); mItemView->update(); - sellToNpc(playerTradeModel->getItem(index).mBase, count, false); + updateOffer(); } void TradeWindow::returnItem(int index, size_t count) { TradeItemModel* playerTradeModel = MWBase::Environment::get().getWindowManager()->getInventoryWindow()->getTradeModel(); - const ItemStack& item = playerTradeModel->getItem(index); mTradeModel->returnItemBorrowedFromUs(index, playerTradeModel, count); mItemView->update(); - sellToNpc(item.mBase, count, true); + updateOffer(); } void TradeWindow::addOrRemoveGold(int amount, const MWWorld::Ptr& actor) @@ -384,7 +383,7 @@ namespace MWGui void TradeWindow::onOfferSubmitted(MyGUI::Widget* /*sender*/, size_t offerAmount) { - mCurrentBalance = offerAmount * (mCurrentBalance < 0 ? -1 : 1); + mCurrentBalance = static_cast(offerAmount) * (mCurrentBalance < 0 ? -1 : 1); updateLabels(); onOfferButtonClicked(mOfferButton); } @@ -440,7 +439,7 @@ namespace MWGui MWBase::Environment::get().getWindowManager()->messageBox(msg); MWBase::Environment::get().getMechanicsManager()->confiscateStolenItemToOwner( - player, itemStack.mBase, mPtr, itemStack.mCount); + player, itemStack.mBase, mPtr, static_cast(itemStack.mCount)); onCancelButtonClicked(mCancelButton); MWBase::Environment::get().getWindowManager()->exitCurrentGuiMode(); @@ -623,7 +622,7 @@ namespace MWGui const std::vector& playerBorrowed = playerTradeModel->getItemsBorrowedToUs(); for (const ItemStack& itemStack : playerBorrowed) { - const int basePrice = getEffectiveValue(itemStack.mBase, itemStack.mCount); + const int basePrice = getEffectiveValue(itemStack.mBase, static_cast(itemStack.mCount)); const int cap = static_cast(std::max(1.f, 0.75f * basePrice)); // Minimum buying price -- 75% of the base const int buyingPrice @@ -634,7 +633,7 @@ namespace MWGui const std::vector& merchantBorrowed = mTradeModel->getItemsBorrowedToUs(); for (const ItemStack& itemStack : merchantBorrowed) { - const int basePrice = getEffectiveValue(itemStack.mBase, itemStack.mCount); + const int basePrice = getEffectiveValue(itemStack.mBase, static_cast(itemStack.mCount)); const int cap = static_cast(std::max(1.f, 0.75f * basePrice)); // Maximum selling price -- 75% of the base const int sellingPrice @@ -648,16 +647,6 @@ namespace MWGui updateLabels(); } - void TradeWindow::sellToNpc(const MWWorld::Ptr& item, int count, bool boughtItem) - { - updateOffer(); - } - - void TradeWindow::buyFromNpc(const MWWorld::Ptr& item, int count, bool soldItem) - { - updateOffer(); - } - void TradeWindow::onReferenceUnavailable() { // remove both Trade and Dialogue (since you always trade with the NPC/creature that you have previously talked diff --git a/apps/openmw/mwgui/tradewindow.hpp b/apps/openmw/mwgui/tradewindow.hpp index 938246a345..ab7b965cd8 100644 --- a/apps/openmw/mwgui/tradewindow.hpp +++ b/apps/openmw/mwgui/tradewindow.hpp @@ -90,11 +90,6 @@ namespace MWGui bool mUpdateNextFrame; - void sellToNpc( - const MWWorld::Ptr& item, int count, bool boughtItem); ///< only used for adjusting the gold balance - void buyFromNpc( - const MWWorld::Ptr& item, int count, bool soldItem); ///< only used for adjusting the gold balance - void updateOffer(); void onItemSelected(int index); diff --git a/apps/openmw/mwgui/trainingwindow.cpp b/apps/openmw/mwgui/trainingwindow.cpp index 0d60e20e67..01b552b720 100644 --- a/apps/openmw/mwgui/trainingwindow.cpp +++ b/apps/openmw/mwgui/trainingwindow.cpp @@ -123,7 +123,7 @@ namespace MWGui MyGUI::Button* button = mTrainingOptions->createWidget(price <= playerGold ? "SandTextButton" : "SandTextButtonDisabled", // can't use setEnabled since that removes tooltip - MyGUI::IntCoord(4, 3 + i * lineHeight, mTrainingOptions->getWidth() - 10, lineHeight), + MyGUI::IntCoord(4, static_cast(3 + i * lineHeight), mTrainingOptions->getWidth() - 10, lineHeight), MyGUI::Align::Default); button->setUserData(skills[i].first); @@ -169,8 +169,8 @@ namespace MWGui const MWWorld::ESMStore& store = *MWBase::Environment::get().getESMStore(); - int price = pcStats.getSkill(skill->mId).getBase() - * store.get().find("iTrainingMod")->mValue.getInteger(); + int price = static_cast(pcStats.getSkill(skill->mId).getBase() + * store.get().find("iTrainingMod")->mValue.getInteger()); price = MWBase::Environment::get().getMechanicsManager()->getBarterOffer(mPtr, price, true); if (price > player.getClass().getContainerStore(player).count(MWWorld::ContainerStore::sGoldId)) @@ -263,7 +263,7 @@ namespace MWGui return true; setControllerFocus(mTrainingButtons, mControllerFocus, false); - mControllerFocus = wrap(mControllerFocus - 1, mTrainingButtons.size()); + mControllerFocus = wrap(mControllerFocus, mTrainingButtons.size(), -1); setControllerFocus(mTrainingButtons, mControllerFocus, true); } else if (arg.button == SDL_CONTROLLER_BUTTON_DPAD_DOWN) @@ -272,7 +272,7 @@ namespace MWGui return true; setControllerFocus(mTrainingButtons, mControllerFocus, false); - mControllerFocus = wrap(mControllerFocus + 1, mTrainingButtons.size()); + mControllerFocus = wrap(mControllerFocus, mTrainingButtons.size(), 1); setControllerFocus(mTrainingButtons, mControllerFocus, true); } diff --git a/apps/openmw/mwgui/travelwindow.cpp b/apps/openmw/mwgui/travelwindow.cpp index e83c327125..c97d392ff6 100644 --- a/apps/openmw/mwgui/travelwindow.cpp +++ b/apps/openmw/mwgui/travelwindow.cpp @@ -63,8 +63,8 @@ namespace MWGui else { const ESM::Position playerPos = player.getRefData().getPosition(); - float d = sqrt(pow(pos.pos[0] - playerPos.pos[0], 2) + pow(pos.pos[1] - playerPos.pos[1], 2) - + pow(pos.pos[2] - playerPos.pos[2], 2)); + double d = std::sqrt(std::pow(pos.pos[0] - playerPos.pos[0], 2) + std::pow(pos.pos[1] - playerPos.pos[1], 2) + + std::pow(pos.pos[2] - playerPos.pos[2], 2)); float fTravelMult = gmst.find("fTravelMult")->mValue.getFloat(); if (fTravelMult != 0) price = static_cast(d / fTravelMult); @@ -203,14 +203,13 @@ namespace MWGui if (mPtr.getCell()->isExterior()) { ESM::Position playerPos = player.getRefData().getPosition(); - float d - = (osg::Vec3f(pos.pos[0], pos.pos[1], 0) - osg::Vec3f(playerPos.pos[0], playerPos.pos[1], 0)).length(); - int hours = static_cast(d - / MWBase::Environment::get() - .getESMStore() - ->get() - .find("fTravelTimeMult") - ->mValue.getFloat()); + float d = (osg::Vec2f(pos.pos[0], pos.pos[1]) - osg::Vec2f(playerPos.pos[0], playerPos.pos[1])).length(); + const float fTravelTimeMult = MWBase::Environment::get() + .getESMStore() + ->get() + .find("fTravelTimeMult") + ->mValue.getFloat(); + int hours = static_cast(d / fTravelTimeMult); MWBase::Environment::get().getMechanicsManager()->rest(hours, true); MWBase::Environment::get().getWorld()->advanceTime(hours); } @@ -279,7 +278,7 @@ namespace MWGui return true; setControllerFocus(mDestinationButtons, mControllerFocus, false); - mControllerFocus = wrap(mControllerFocus - 1, mDestinationButtons.size()); + mControllerFocus = wrap(mControllerFocus, mDestinationButtons.size(), -1); setControllerFocus(mDestinationButtons, mControllerFocus, true); } else if (arg.button == SDL_CONTROLLER_BUTTON_DPAD_DOWN) @@ -288,7 +287,7 @@ namespace MWGui return true; setControllerFocus(mDestinationButtons, mControllerFocus, false); - mControllerFocus = wrap(mControllerFocus + 1, mDestinationButtons.size()); + mControllerFocus = wrap(mControllerFocus, mDestinationButtons.size(), 1); setControllerFocus(mDestinationButtons, mControllerFocus, true); } @@ -298,7 +297,7 @@ namespace MWGui else { const int lineHeight = Settings::gui().mFontSize + 2; - mDestinationsView->setViewOffset(MyGUI::IntPoint(0, -lineHeight * (mControllerFocus - 5))); + mDestinationsView->setViewOffset(MyGUI::IntPoint(0, -lineHeight * static_cast(mControllerFocus - 5))); } return true; diff --git a/apps/openmw/mwgui/videowidget.cpp b/apps/openmw/mwgui/videowidget.cpp index 0fc555ab27..0e3ba06049 100644 --- a/apps/openmw/mwgui/videowidget.cpp +++ b/apps/openmw/mwgui/videowidget.cpp @@ -1,6 +1,6 @@ #include "videowidget.hpp" -#include +#include #include diff --git a/apps/openmw/mwgui/waitdialog.cpp b/apps/openmw/mwgui/waitdialog.cpp index 8663ea1071..3f41a78d38 100644 --- a/apps/openmw/mwgui/waitdialog.cpp +++ b/apps/openmw/mwgui/waitdialog.cpp @@ -239,7 +239,7 @@ namespace MWGui void WaitDialog::onHourSliderChangedPosition(MyGUI::ScrollBar* sender, size_t position) { mHourText->setCaptionWithReplacing(MyGUI::utility::toString(position + 1) + " #{sRestMenu2}"); - mManualHours = position + 1; + mManualHours = static_cast(position + 1); MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(mWaitButton); } diff --git a/apps/openmw/mwgui/widgets.cpp b/apps/openmw/mwgui/widgets.cpp index 496fa2ea50..1d14aa4af9 100644 --- a/apps/openmw/mwgui/widgets.cpp +++ b/apps/openmw/mwgui/widgets.cpp @@ -147,8 +147,9 @@ namespace MWGui::Widgets } if (mAttributeValueWidget) { - int modified = mValue.getModified(), base = mValue.getBase(); - mAttributeValueWidget->setCaption(MyGUI::utility::toString(modified)); + float modified = mValue.getModified(); + float base = mValue.getBase(); + mAttributeValueWidget->setCaption(MyGUI::utility::toString(static_cast(modified))); if (modified > base) mAttributeValueWidget->_setWidgetState("increased"); else if (modified < base) diff --git a/apps/openmw/mwgui/windowbase.cpp b/apps/openmw/mwgui/windowbase.cpp index 89a27c5eef..82053e6197 100644 --- a/apps/openmw/mwgui/windowbase.cpp +++ b/apps/openmw/mwgui/windowbase.cpp @@ -15,19 +15,29 @@ using namespace MWGui; -int MWGui::wrap(int index, int max) +size_t MWGui::wrap(size_t index, size_t max, int delta) { - if (index < 0) - return max - 1; - else if (index >= max) + if (max == 0) return 0; - else - return index; + if (delta >= 0) + { + unsigned absDelta = static_cast(delta); + if (absDelta >= max) + return 0; + else if (index >= max - absDelta) + return 0; + return index + absDelta; + } + size_t absDelta = static_cast(-static_cast(delta)); + index = std::min(index, max); + if (index >= absDelta) + return index - absDelta; + return max - 1; } -void MWGui::setControllerFocus(const std::vector& buttons, int index, bool focused) +void MWGui::setControllerFocus(const std::vector& buttons, size_t index, bool focused) { - if (index >= 0 && index < static_cast(buttons.size())) + if (index < buttons.size()) buttons[index]->setStateSelected(focused); } @@ -199,16 +209,14 @@ float BookWindowBase::adjustButton(std::string_view name) WindowBase::getWidget(button, name); MyGUI::IntSize requested = button->getRequestedSize(); float scale = float(requested.height) / button->getSize().height; - MyGUI::IntSize newSize = requested; - newSize.width /= scale; - newSize.height /= scale; + MyGUI::IntSize newSize(static_cast(requested.width / scale), static_cast(requested.height / scale)); button->setSize(newSize); if (button->getAlign().isRight()) { MyGUI::IntSize diff = (button->getSize() - requested); - diff.width /= scale; - diff.height /= scale; + diff.width = static_cast(diff.width / scale); + diff.height = static_cast(diff.height / scale); button->setPosition(button->getPosition() + MyGUI::IntPoint(diff.width, 0)); } diff --git a/apps/openmw/mwgui/windowbase.hpp b/apps/openmw/mwgui/windowbase.hpp index 2a091c303d..0ba05aeb79 100644 --- a/apps/openmw/mwgui/windowbase.hpp +++ b/apps/openmw/mwgui/windowbase.hpp @@ -14,8 +14,8 @@ namespace MWGui { class DragAndDrop; - int wrap(int index, int max); - void setControllerFocus(const std::vector& buttons, int index, bool selected); + size_t wrap(size_t index, size_t max, int delta); + void setControllerFocus(const std::vector& buttons, size_t index, bool selected); struct ControllerButtons { diff --git a/apps/openmw/mwgui/windowmanagerimp.cpp b/apps/openmw/mwgui/windowmanagerimp.cpp index 15b5b20258..ac8c0475a0 100644 --- a/apps/openmw/mwgui/windowmanagerimp.cpp +++ b/apps/openmw/mwgui/windowmanagerimp.cpp @@ -492,7 +492,7 @@ namespace MWGui if (!mResourceSystem->getVFS()->exists(hitFaderTexture)) { hitFaderTexture = "textures\\player_hit_01.dds"; - hitFaderCoord = MyGUI::FloatCoord(0.2, 0.25, 0.6, 0.5); + hitFaderCoord = MyGUI::FloatCoord(0.2f, 0.25f, 0.6f, 0.5f); } auto hitFader = std::make_unique(hitFaderTexture, hitFaderLayout, hitFaderCoord); mHitFader = hitFader.get(); @@ -790,8 +790,8 @@ namespace MWGui while (mMessageBoxManager->readPressedButton(false) == -1 && !MWBase::Environment::get().getStateManager()->hasQuitRequest()) { - const double dt - = std::chrono::duration_cast>(frameRateLimiter.getLastFrameDuration()) + const float dt + = std::chrono::duration_cast>(frameRateLimiter.getLastFrameDuration()) .count(); mKeyboardNavigation->onFrame(); @@ -903,11 +903,10 @@ namespace MWGui { GuiMode mode = mGuiModes.back(); GuiModeState& state = mGuiModeStates[mode]; - if (state.mWindows.size() == 0) + if (state.mWindows.empty()) return nullptr; - int activeIndex - = std::clamp(mActiveControllerWindows[mode], 0, static_cast(state.mWindows.size()) - 1); + size_t activeIndex = std::clamp(mActiveControllerWindows[mode], 0, state.mWindows.size() - 1); // If the active window is no longer visible, find the next visible window. if (!state.mWindows[activeIndex]->isVisible()) @@ -925,18 +924,18 @@ namespace MWGui return; GuiMode mode = mGuiModes.back(); - int winCount = mGuiModeStates[mode].mWindows.size(); + size_t winCount = mGuiModeStates[mode].mWindows.size(); - int activeIndex = 0; + size_t activeIndex = 0; if (winCount > 1) { // Find next/previous visible window activeIndex = mActiveControllerWindows[mode]; int delta = next ? 1 : -1; - for (int i = 0; i < winCount; i++) + for (size_t i = 0; i < winCount; ++i) { - activeIndex = wrap(activeIndex + delta, winCount); + activeIndex = wrap(activeIndex, winCount, delta); if (mGuiModeStates[mode].mWindows[activeIndex]->isVisible()) break; } @@ -952,9 +951,9 @@ namespace MWGui return; const GuiMode mode = mGuiModes.back(); - int winCount = mGuiModeStates[mode].mWindows.size(); + size_t winCount = mGuiModeStates[mode].mWindows.size(); - for (int i = 0; i < winCount; i++) + for (size_t i = 0; i < winCount; i++) { // Set active window last so inactive windows don't stomp on changes it makes, e.g. to tooltips. if (i != mActiveControllerWindows[mode]) @@ -964,16 +963,16 @@ namespace MWGui mGuiModeStates[mode].mWindows[mActiveControllerWindows[mode]]->setActiveControllerWindow(true); } - void WindowManager::setActiveControllerWindow(GuiMode mode, int activeIndex) + void WindowManager::setActiveControllerWindow(GuiMode mode, size_t activeIndex) { if (!Settings::gui().mControllerMenus) return; - int winCount = mGuiModeStates[mode].mWindows.size(); + size_t winCount = mGuiModeStates[mode].mWindows.size(); if (winCount == 0) return; - activeIndex = std::clamp(activeIndex, 0, winCount - 1); + activeIndex = std::clamp(activeIndex, 0, winCount - 1); mActiveControllerWindows[mode] = activeIndex; reapplyActiveControllerWindow(); @@ -1437,7 +1436,8 @@ namespace MWGui if (mode == GM_Container) mActiveControllerWindows[mode] = 0; // Ensure controller focus is on container // Activate first visible window. This needs to be called after updateVisible. - mActiveControllerWindows[mode] = std::max(mActiveControllerWindows[mode] - 1, -1); + if (mActiveControllerWindows[mode] != 0) + mActiveControllerWindows[mode] = mActiveControllerWindows[mode] - 1; cycleActiveControllerWindow(true); } } @@ -1919,10 +1919,10 @@ namespace MWGui const WindowRectSettingValues& rect = settings.mIsMaximized ? settings.mRegular : settings.mMaximized; MyGUI::IntSize viewSize = MyGUI::RenderManager::getInstance().getViewSize(); - const float x = rect.mX * viewSize.width; - const float y = rect.mY * viewSize.height; - const float w = rect.mW * viewSize.width; - const float h = rect.mH * viewSize.height; + const int x = static_cast(rect.mX * viewSize.width); + const int y = static_cast(rect.mY * viewSize.height); + const int w = static_cast(rect.mW * viewSize.width); + const int h = static_cast(rect.mH * viewSize.height); window->setCoord(x, y, w, h); settings.mIsMaximized.set(!settings.mIsMaximized.get()); @@ -1996,11 +1996,10 @@ namespace MWGui writer.endRecord(ESM::REC_ASPL); } - for (CustomMarkerCollection::ContainerType::const_iterator it = mCustomMarkers.begin(); - it != mCustomMarkers.end(); ++it) + for (const auto& [_, marker] : mCustomMarkers) { writer.startRecord(ESM::REC_MARK); - it->second.save(writer); + marker.save(writer); writer.endRecord(ESM::REC_MARK); } } @@ -2026,7 +2025,7 @@ namespace MWGui } } - int WindowManager::countSavedGameRecords() const + size_t WindowManager::countSavedGameRecords() const { return 1 // Global map + 1 // QuickKeysMenu @@ -2074,8 +2073,8 @@ namespace MWGui = Misc::makeFrameRateLimiter(MWBase::Environment::get().getFrameRateLimit()); while (mVideoWidget->update() && !MWBase::Environment::get().getStateManager()->hasQuitRequest()) { - const double dt - = std::chrono::duration_cast>(frameRateLimiter.getLastFrameDuration()) + const float dt + = std::chrono::duration_cast>(frameRateLimiter.getLastFrameDuration()) .count(); MWBase::Environment::get().getInputManager()->update(dt, true, false); @@ -2424,8 +2423,8 @@ namespace MWGui if (image.valid()) { // everything looks good, send it to the cursor manager - const Uint8 hotspotX = imgSetPointer->getHotSpot().left; - const Uint8 hotspotY = imgSetPointer->getHotSpot().top; + const Uint8 hotspotX = static_cast(imgSetPointer->getHotSpot().left); + const Uint8 hotspotY = static_cast(imgSetPointer->getHotSpot().top); int rotation = imgSetPointer->getRotation(); MyGUI::IntSize pointerSize = imgSetPointer->getSize(); diff --git a/apps/openmw/mwgui/windowmanagerimp.hpp b/apps/openmw/mwgui/windowmanagerimp.hpp index a9acaffcf0..03f0ea5572 100644 --- a/apps/openmw/mwgui/windowmanagerimp.hpp +++ b/apps/openmw/mwgui/windowmanagerimp.hpp @@ -331,7 +331,7 @@ namespace MWGui void write(ESM::ESMWriter& writer, Loading::Listener& progress) override; void readRecord(ESM::ESMReader& reader, uint32_t type) override; - int countSavedGameRecords() const override; + size_t countSavedGameRecords() const override; /// Does the current stack of GUI-windows permit saving? bool isSavingAllowed() const override; @@ -394,7 +394,7 @@ namespace MWGui WindowBase* getActiveControllerWindow() override; int getControllerMenuHeight() override; void cycleActiveControllerWindow(bool next) override; - void setActiveControllerWindow(GuiMode mode, int activeIndex) override; + void setActiveControllerWindow(GuiMode mode, size_t activeIndex) override; bool getControllerTooltipVisible() const override { return mControllerTooltipVisible; } void setControllerTooltipVisible(bool visible) override; bool getControllerTooltipEnabled() const override { return mControllerTooltipEnabled; } @@ -513,7 +513,7 @@ namespace MWGui // The currently active stack of GUI modes (top mode is the one we are in). std::vector mGuiModes; // The active window for controller mode for each GUI mode. - std::map mActiveControllerWindows; + std::map mActiveControllerWindows; // Current tooltip visibility state (can be disabled by mouse movement) bool mControllerTooltipVisible = false; // User preference for tooltips (persists across mouse/controller switches) diff --git a/apps/openmw/mwgui/worlditemmodel.hpp b/apps/openmw/mwgui/worlditemmodel.hpp index 137062eeb4..1999cb40ed 100644 --- a/apps/openmw/mwgui/worlditemmodel.hpp +++ b/apps/openmw/mwgui/worlditemmodel.hpp @@ -18,14 +18,7 @@ namespace MWGui // Makes it possible to use ItemModel::moveItem to move an item from an inventory to the world. class WorldItemModel : public ItemModel { - public: - explicit WorldItemModel(float cursorX, float cursorY) - : mCursorX(cursorX) - , mCursorY(cursorY) - { - } - - MWWorld::Ptr dropItemImpl(const ItemStack& item, size_t count, bool copy) + MWWorld::Ptr dropItemImpl(const ItemStack& item, int count, bool copy) { MWBase::World& world = *MWBase::Environment::get().getWorld(); @@ -42,14 +35,21 @@ namespace MWGui return dropped; } + public: + explicit WorldItemModel(float cursorX, float cursorY) + : mCursorX(cursorX) + , mCursorY(cursorY) + { + } + MWWorld::Ptr addItem(const ItemStack& item, size_t count, bool /*allowAutoEquip*/) override { - return dropItemImpl(item, count, false); + return dropItemImpl(item, static_cast(count), false); } MWWorld::Ptr copyItem(const ItemStack& item, size_t count, bool /*allowAutoEquip*/) override { - return dropItemImpl(item, count, true); + return dropItemImpl(item, static_cast(count), true); } void removeItem(const ItemStack& /*item*/, size_t /*count*/) override diff --git a/apps/openmw/mwinput/bindingsmanager.cpp b/apps/openmw/mwinput/bindingsmanager.cpp index 9523d7ccc2..ac5d9b5730 100644 --- a/apps/openmw/mwinput/bindingsmanager.cpp +++ b/apps/openmw/mwinput/bindingsmanager.cpp @@ -4,8 +4,8 @@ #include -#include -#include +#include +#include #include #include diff --git a/apps/openmw/mwinput/controlswitch.cpp b/apps/openmw/mwinput/controlswitch.cpp index 974cfbbbb5..744c2f4632 100644 --- a/apps/openmw/mwinput/controlswitch.cpp +++ b/apps/openmw/mwinput/controlswitch.cpp @@ -78,7 +78,7 @@ namespace MWInput set("playermagic", !controls.mSpellDrawingDisabled); } - int ControlSwitch::countSavedGameRecords() const + size_t ControlSwitch::countSavedGameRecords() const { return 1; } diff --git a/apps/openmw/mwinput/controlswitch.hpp b/apps/openmw/mwinput/controlswitch.hpp index b86744a06f..7ec72c321c 100644 --- a/apps/openmw/mwinput/controlswitch.hpp +++ b/apps/openmw/mwinput/controlswitch.hpp @@ -31,7 +31,7 @@ namespace MWInput void write(ESM::ESMWriter& writer, Loading::Listener& progress); void readRecord(ESM::ESMReader& reader, uint32_t type); - int countSavedGameRecords() const; + size_t countSavedGameRecords() const; private: std::map> mSwitches; diff --git a/apps/openmw/mwinput/inputmanagerimp.cpp b/apps/openmw/mwinput/inputmanagerimp.cpp index 250b25aeaa..c1dda59e51 100644 --- a/apps/openmw/mwinput/inputmanagerimp.cpp +++ b/apps/openmw/mwinput/inputmanagerimp.cpp @@ -211,7 +211,7 @@ namespace MWInput mBindingsManager->enableDetectingBindingMode(action, keyboard); } - int InputManager::countSavedGameRecords() const + size_t InputManager::countSavedGameRecords() const { return mControlSwitch->countSavedGameRecords(); } diff --git a/apps/openmw/mwinput/inputmanagerimp.hpp b/apps/openmw/mwinput/inputmanagerimp.hpp index 3e964ae2a8..611679ac9d 100644 --- a/apps/openmw/mwinput/inputmanagerimp.hpp +++ b/apps/openmw/mwinput/inputmanagerimp.hpp @@ -95,7 +95,7 @@ namespace MWInput std::string getControllerButtonIcon(int button) override; std::string getControllerAxisIcon(int axis) override; - int countSavedGameRecords() const override; + size_t countSavedGameRecords() const override; void write(ESM::ESMWriter& writer, Loading::Listener& progress) override; void readRecord(ESM::ESMReader& reader, uint32_t type) override; diff --git a/apps/openmw/mwinput/mousemanager.cpp b/apps/openmw/mwinput/mousemanager.cpp index ced69fbe79..4186b5a023 100644 --- a/apps/openmw/mwinput/mousemanager.cpp +++ b/apps/openmw/mwinput/mousemanager.cpp @@ -266,14 +266,14 @@ namespace MWInput { mGuiCursorX += xMove; mGuiCursorY += yMove; - mMouseWheel += mouseWheelMove; + mMouseWheel += static_cast(mouseWheelMove); const MyGUI::IntSize& viewSize = MyGUI::RenderManager::getInstance().getViewSize(); - mGuiCursorX = std::clamp(mGuiCursorX, 0.f, viewSize.width - 1); - mGuiCursorY = std::clamp(mGuiCursorY, 0.f, viewSize.height - 1); + mGuiCursorX = std::clamp(mGuiCursorX, 0.f, viewSize.width - 1.f); + mGuiCursorY = std::clamp(mGuiCursorY, 0.f, viewSize.height - 1.f); MyGUI::InputManager::getInstance().injectMouseMove( - static_cast(mGuiCursorX), static_cast(mGuiCursorY), static_cast(mMouseWheel)); + static_cast(mGuiCursorX), static_cast(mGuiCursorY), mMouseWheel); } void MouseManager::warpMouse() @@ -285,8 +285,8 @@ namespace MWInput void MouseManager::warpMouseToWidget(MyGUI::Widget* widget) { - float widgetX = widget->getAbsoluteCoord().left + widget->getWidth() / 2; - float widgetY = widget->getAbsoluteCoord().top + widget->getHeight() / 4; + float widgetX = widget->getAbsoluteCoord().left + widget->getWidth() / 2.f; + float widgetY = widget->getAbsoluteCoord().top + widget->getHeight() / 4.f; if (std::abs(mGuiCursorX - widgetX) > 1 || std::abs(mGuiCursorY - widgetY) > 1) { mGuiCursorX = widgetX; diff --git a/apps/openmw/mwlua/animationbindings.cpp b/apps/openmw/mwlua/animationbindings.cpp index 3e22af85d9..545df19a70 100644 --- a/apps/openmw/mwlua/animationbindings.cpp +++ b/apps/openmw/mwlua/animationbindings.cpp @@ -166,8 +166,8 @@ namespace MWLua return completion; return sol::nullopt; }; - api["getLoopCount"] = [](const LObject& object, std::string groupname) -> sol::optional { - size_t loops = 0; + api["getLoopCount"] = [](const LObject& object, std::string groupname) -> sol::optional { + uint32_t loops = 0; if (getConstAnimationOrThrow(object)->getInfo(groupname, nullptr, nullptr, &loops)) return loops; return sol::nullopt; diff --git a/apps/openmw/mwlua/camerabindings.cpp b/apps/openmw/mwlua/camerabindings.cpp index 454f966538..c2e2cac4ff 100644 --- a/apps/openmw/mwlua/camerabindings.cpp +++ b/apps/openmw/mwlua/camerabindings.cpp @@ -105,14 +105,14 @@ namespace MWLua double fovTan = std::tan(osg::DegreesToRadians(renderingManager->getFieldOfView()) / 2); osg::Matrixf invertedViewMatrix; invertedViewMatrix.invert(camera->getViewMatrix()); - float x = (pos.x() * 2 - 1) * aspect * fovTan; - float y = (1 - pos.y() * 2) * fovTan; + float x = static_cast((pos.x() * 2 - 1) * aspect * fovTan); + float y = static_cast((1 - pos.y() * 2) * fovTan); return invertedViewMatrix.preMult(osg::Vec3f(x, y, -1)) - camera->getPosition(); }; api["worldToViewportVector"] = [camera](osg::Vec3f pos) { - const double width = Settings::video().mResolutionX; - const double height = Settings::video().mResolutionY; + const int width = Settings::video().mResolutionX; + const int height = Settings::video().mResolutionY; osg::Matrix windowMatrix = osg::Matrix::translate(1.0, 1.0, 1.0) * osg::Matrix::scale(0.5 * width, 0.5 * height, 0.5); diff --git a/apps/openmw/mwlua/cellbindings.cpp b/apps/openmw/mwlua/cellbindings.cpp index 1efcbb89e5..8132bf20ea 100644 --- a/apps/openmw/mwlua/cellbindings.cpp +++ b/apps/openmw/mwlua/cellbindings.cpp @@ -40,6 +40,8 @@ #include #include +#include + #include #include "../mwbase/environment.hpp" @@ -313,7 +315,7 @@ namespace MWLua { sol::table table(lua, sol::create); table["autoGenerated"] = point.mAutogenerated == 0; - table["relativePosition"] = osg::Vec3f(point.mX, point.mY, point.mZ); + table["relativePosition"] = Misc::Convert::makeOsgVec3f(point); sol::table edges(lua, sol::create); table["connections"] = edges; points.add(table); diff --git a/apps/openmw/mwlua/corebindings.cpp b/apps/openmw/mwlua/corebindings.cpp index cce3aa8eed..2c77990f75 100644 --- a/apps/openmw/mwlua/corebindings.cpp +++ b/apps/openmw/mwlua/corebindings.cpp @@ -41,10 +41,10 @@ namespace MWLua list[LuaUtil::toLuaIndex(i)] = Misc::StringUtils::lowerCase(contentList[i]); sol::table res(lua, sol::create); res["list"] = LuaUtil::makeReadOnly(list); - res["indexOf"] = [&contentList](std::string_view contentFile) -> sol::optional { + res["indexOf"] = [&contentList](std::string_view contentFile) -> sol::optional { for (size_t i = 0; i < contentList.size(); ++i) if (Misc::StringUtils::ciEqual(contentList[i], contentFile)) - return LuaUtil::toLuaIndex(i); + return LuaUtil::toLuaIndex(static_cast(i)); return sol::nullopt; }; res["has"] = [&contentList](std::string_view contentFile) -> bool { diff --git a/apps/openmw/mwlua/dialoguebindings.cpp b/apps/openmw/mwlua/dialoguebindings.cpp index d0ca799cb6..6028d0e1b2 100644 --- a/apps/openmw/mwlua/dialoguebindings.cpp +++ b/apps/openmw/mwlua/dialoguebindings.cpp @@ -220,7 +220,7 @@ namespace return rec.mFaction.serializeText(); }); recordInfoBindingsClass["filterActorFactionRank"] - = sol::readonly_property([](const ESM::DialInfo& rec) -> sol::optional { + = sol::readonly_property([](const ESM::DialInfo& rec) -> sol::optional { if (rec.mData.mType == ESM::Dialogue::Type::Journal || rec.mData.mRank == -1) { return sol::nullopt; @@ -260,7 +260,7 @@ namespace return rec.mPcFaction.serializeText(); }); recordInfoBindingsClass["filterPlayerFactionRank"] - = sol::readonly_property([](const ESM::DialInfo& rec) -> sol::optional { + = sol::readonly_property([](const ESM::DialInfo& rec) -> sol::optional { if (rec.mData.mType == ESM::Dialogue::Type::Journal || rec.mData.mPCrank == -1) { return sol::nullopt; diff --git a/apps/openmw/mwlua/itemdata.cpp b/apps/openmw/mwlua/itemdata.cpp index 1b809383db..75848e477b 100644 --- a/apps/openmw/mwlua/itemdata.cpp +++ b/apps/openmw/mwlua/itemdata.cpp @@ -130,7 +130,7 @@ namespace MWLua { // if the value set is less than 0, chargeInt and chargeIntRemainder is set to 0 ptr.getCellRef().setChargeIntRemainder(std::max(0.f, std::modf(cond, &cond))); - ptr.getCellRef().setCharge(std::max(0.f, cond)); + ptr.getCellRef().setCharge(std::max(0, static_cast(cond))); } } else diff --git a/apps/openmw/mwlua/landbindings.cpp b/apps/openmw/mwlua/landbindings.cpp index 2b053802db..6458eba6c0 100644 --- a/apps/openmw/mwlua/landbindings.cpp +++ b/apps/openmw/mwlua/landbindings.cpp @@ -89,8 +89,8 @@ namespace MWLua if (worldspace != ESM::Cell::sDefaultWorldspaceId) return values; - const float cellSize = ESM::getCellSize(worldspace); - const float offset = (cellSize / ESM::LandRecordData::sLandTextureSize) * 0.25; + const int cellSize = ESM::getCellSize(worldspace); + const float offset = (cellSize / ESM::LandRecordData::sLandTextureSize) * 0.25f; const osg::Vec3f correctedPos = pos + osg::Vec3f{ -offset, +offset, 0.0f }; const ESM::Land* land = nullptr; @@ -110,7 +110,7 @@ namespace MWLua return values; const ESMTerrain::UniqueTextureId textureId - = getTextureAt(landData->mTextures, land->getPlugin(), correctedPos, cellSize); + = getTextureAt(landData->mTextures, land->getPlugin(), correctedPos, static_cast(cellSize)); // Need to check for 0, 0 so that we can safely subtract 1 later, as per documentation on UniqueTextureId if (textureId.first != 0) diff --git a/apps/openmw/mwlua/luamanagerimp.cpp b/apps/openmw/mwlua/luamanagerimp.cpp index 7aef11caa4..520f09cad0 100644 --- a/apps/openmw/mwlua/luamanagerimp.cpp +++ b/apps/openmw/mwlua/luamanagerimp.cpp @@ -299,8 +299,8 @@ namespace MWLua } mInputEvents.clear(); mLuaEvents.callMenuEventHandlers(); - double frameDuration = MWBase::Environment::get().getWorld()->getTimeManager()->isPaused() - ? 0.0 + float frameDuration = MWBase::Environment::get().getWorld()->getTimeManager()->isPaused() + ? 0.f : MWBase::Environment::get().getFrameDuration(); mInputActions.update(frameDuration); mMenuScripts.onFrame(frameDuration); @@ -843,7 +843,7 @@ namespace MWLua void LuaManager::reportStats(unsigned int frameNumber, osg::Stats& stats) const { - stats.setAttribute(frameNumber, "Lua UsedMemory", mLua.getTotalMemoryUsage()); + stats.setAttribute(frameNumber, "Lua UsedMemory", static_cast(mLua.getTotalMemoryUsage())); } std::string LuaManager::formatResourceUsageStats() const @@ -853,11 +853,11 @@ namespace MWLua std::stringstream out; - constexpr int nameW = 50; + constexpr unsigned nameW = 50; constexpr int valueW = 12; - auto outMemSize = [&](int64_t bytes) { - constexpr int64_t limit = 10000; + auto outMemSize = [&](size_t bytes) { + constexpr size_t limit = 10000; out << std::right << std::setw(valueW - 3); if (bytes < limit) out << bytes << " B "; @@ -941,21 +941,22 @@ namespace MWLua out << "\n " << std::setw(nameW) << ""; // if path is too long, break line out << std::right; out << std::setw(valueW) << static_cast(activeStats[i].mAvgInstructionCount); - outMemSize(activeStats[i].mMemoryUsage); - outMemSize(mLua.getMemoryUsageByScriptIndex(i) - activeStats[i].mMemoryUsage); + outMemSize(static_cast(activeStats[i].mMemoryUsage)); + outMemSize(mLua.getMemoryUsageByScriptIndex(static_cast(i)) + - static_cast(activeStats[i].mMemoryUsage)); if (isGlobal) out << std::setw(valueW * 2) << "NA (global script)"; - else if (isMenu && (!selectedScripts || !selectedScripts->hasScript(i))) + else if (isMenu && (!selectedScripts || !selectedScripts->hasScript(static_cast(i)))) out << std::setw(valueW * 2) << "NA (menu script)"; else if (selectedPtr.isEmpty()) out << std::setw(valueW * 2) << "NA (not selected) "; - else if (!selectedScripts || !selectedScripts->hasScript(i)) + else if (!selectedScripts || !selectedScripts->hasScript(static_cast(i))) out << std::setw(valueW * 2) << "NA"; else { out << std::setw(valueW) << static_cast(selectedStats[i].mAvgInstructionCount); - outMemSize(selectedStats[i].mMemoryUsage); + outMemSize(static_cast(selectedStats[i].mMemoryUsage)); } out << "\n"; } diff --git a/apps/openmw/mwlua/magicbindings.cpp b/apps/openmw/mwlua/magicbindings.cpp index 26dedcab6b..3cfc84bc3c 100644 --- a/apps/openmw/mwlua/magicbindings.cpp +++ b/apps/openmw/mwlua/magicbindings.cpp @@ -776,7 +776,7 @@ namespace MWLua resetEnchantItem(); if (objPtr == MWBase::Environment::get().getWorld()->getPlayerPtr()) { - int chance = MWMechanics::getSpellSuccessChance(spellId, objPtr); + int chance = static_cast(MWMechanics::getSpellSuccessChance(spellId, objPtr)); MWBase::Environment::get().getWindowManager()->setSelectedSpell(spellId, chance); } else @@ -969,9 +969,9 @@ namespace MWLua effect.mEffectId = enam.mData.mEffectID; effect.mArg = MWMechanics::EffectKey(enam.mData).mArg; effect.mMagnitude = 0.f; - effect.mMinMagnitude = enam.mData.mMagnMin; - effect.mMaxMagnitude = enam.mData.mMagnMax; - effect.mEffectIndex = enam.mIndex; + effect.mMinMagnitude = static_cast(enam.mData.mMagnMin); + effect.mMaxMagnitude = static_cast(enam.mData.mMagnMax); + effect.mEffectIndex = static_cast(enam.mIndex); effect.mFlags = ESM::ActiveEffect::Flag_None; if (ignoreReflect) effect.mFlags |= ESM::ActiveEffect::Flag_Ignore_Reflect; @@ -1095,7 +1095,7 @@ namespace MWLua throw std::runtime_error("Local scripts can modify effect only on the actor they are attached to."); MWMechanics::EffectKey key = getEffectKey(idStr, argStr); - int currentValue = effects.getStore()->getOrDefault(key).getMagnitude(); + int currentValue = static_cast(effects.getStore()->getOrDefault(key).getMagnitude()); effects.getStore()->modifyBase(key, value - currentValue); }; diff --git a/apps/openmw/mwlua/mwscriptbindings.cpp b/apps/openmw/mwlua/mwscriptbindings.cpp index 179b35aa5c..b8d14faa09 100644 --- a/apps/openmw/mwlua/mwscriptbindings.cpp +++ b/apps/openmw/mwlua/mwscriptbindings.cpp @@ -90,7 +90,7 @@ namespace MWLua } else if (varType == 's' || varType == 'l') { - MWBase::Environment::get().getWorld()->setGlobalInt(globalId, value); + MWBase::Environment::get().getWorld()->setGlobalInt(globalId, static_cast(value)); } } diff --git a/apps/openmw/mwlua/nearbybindings.cpp b/apps/openmw/mwlua/nearbybindings.cpp index 2436dd887e..48b1663e84 100644 --- a/apps/openmw/mwlua/nearbybindings.cpp +++ b/apps/openmw/mwlua/nearbybindings.cpp @@ -365,9 +365,9 @@ namespace MWLua if (!searchAreaHalfExtents.has_value()) { const bool isEsm4 = MWBase::Environment::get().getWorldScene()->getCurrentCell()->getCell()->isEsm4(); - const float halfExtents = isEsm4 - ? (1 + 2 * Constants::ESM4CellGridRadius) * Constants::ESM4CellSizeInUnits - : (1 + 2 * Constants::CellGridRadius) * Constants::CellSizeInUnits; + const float halfExtents = static_cast(isEsm4 + ? (1 + 2 * Constants::ESM4CellGridRadius) * Constants::ESM4CellSizeInUnits + : (1 + 2 * Constants::CellGridRadius) * Constants::CellSizeInUnits); searchAreaHalfExtents = osg::Vec3f(halfExtents, halfExtents, halfExtents); } diff --git a/apps/openmw/mwlua/objectbindings.cpp b/apps/openmw/mwlua/objectbindings.cpp index ace9722bbe..e03280c87c 100644 --- a/apps/openmw/mwlua/objectbindings.cpp +++ b/apps/openmw/mwlua/objectbindings.cpp @@ -259,16 +259,17 @@ namespace MWLua }; ownerT["factionId"] = sol::property(getOwnerFactionId, setOwnerFactionId); - auto getOwnerFactionRank = [](const OwnerT& o) -> sol::optional { + auto getOwnerFactionRank = [](const OwnerT& o) -> sol::optional { int rank = o.mObj.ptr().getCellRef().getFactionRank(); if (rank < 0) return sol::nullopt; return LuaUtil::toLuaIndex(rank); }; - auto setOwnerFactionRank = [](const OwnerT& o, sol::optional factionRank) { + auto setOwnerFactionRank = [](const OwnerT& o, sol::optional factionRank) { if (std::is_same_v && !dynamic_cast(&o.mObj)) throw std::runtime_error("Local scripts can set an owner faction rank only on self"); - o.mObj.ptr().getCellRef().setFactionRank(LuaUtil::fromLuaIndex(factionRank.value_or(0))); + int64_t rank = std::max(0, LuaUtil::fromLuaIndex(factionRank.value_or(0))); + o.mObj.ptr().getCellRef().setFactionRank(static_cast(rank)); }; ownerT["factionRank"] = sol::property(getOwnerFactionRank, setOwnerFactionRank); diff --git a/apps/openmw/mwlua/types/armor.cpp b/apps/openmw/mwlua/types/armor.cpp index 8668d0cc13..8ef0496d7e 100644 --- a/apps/openmw/mwlua/types/armor.cpp +++ b/apps/openmw/mwlua/types/armor.cpp @@ -61,7 +61,7 @@ namespace if (rec["baseArmor"] != sol::nil) armor.mData.mArmor = rec["baseArmor"]; if (rec["enchantCapacity"] != sol::nil) - armor.mData.mEnchant = std::round(rec["enchantCapacity"].get() * 10); + armor.mData.mEnchant = static_cast(std::round(rec["enchantCapacity"].get() * 10)); return armor; } diff --git a/apps/openmw/mwlua/types/book.cpp b/apps/openmw/mwlua/types/book.cpp index ebcc7a06fd..5bb03de71a 100644 --- a/apps/openmw/mwlua/types/book.cpp +++ b/apps/openmw/mwlua/types/book.cpp @@ -49,7 +49,7 @@ namespace } if (rec["enchantCapacity"] != sol::nil) - book.mData.mEnchant = std::round(rec["enchantCapacity"].get() * 10); + book.mData.mEnchant = static_cast(std::round(rec["enchantCapacity"].get() * 10)); if (rec["mwscript"] != sol::nil) { std::string_view scriptId = rec["mwscript"].get(); diff --git a/apps/openmw/mwlua/types/clothing.cpp b/apps/openmw/mwlua/types/clothing.cpp index 40c2246825..31ba1c2904 100644 --- a/apps/openmw/mwlua/types/clothing.cpp +++ b/apps/openmw/mwlua/types/clothing.cpp @@ -46,7 +46,7 @@ namespace clothing.mEnchant = ESM::RefId::deserializeText(enchantId); } if (rec["enchantCapacity"] != sol::nil) - clothing.mData.mEnchant = std::round(rec["enchantCapacity"].get() * 10); + clothing.mData.mEnchant = static_cast(std::round(rec["enchantCapacity"].get() * 10)); if (rec["weight"] != sol::nil) clothing.mData.mWeight = rec["weight"]; if (rec["value"] != sol::nil) diff --git a/apps/openmw/mwlua/types/ingredient.cpp b/apps/openmw/mwlua/types/ingredient.cpp index ed017da9d1..9deb49e492 100644 --- a/apps/openmw/mwlua/types/ingredient.cpp +++ b/apps/openmw/mwlua/types/ingredient.cpp @@ -44,14 +44,14 @@ namespace MWLua record["value"] = sol::readonly_property([](const ESM::Ingredient& rec) -> int { return rec.mData.mValue; }); record["effects"] = sol::readonly_property([lua = lua.lua_state()](const ESM::Ingredient& rec) -> sol::table { sol::table res(lua, sol::create); - for (size_t i = 0; i < 4; ++i) + for (uint32_t i = 0; i < 4; ++i) { if (rec.mData.mEffectID[i] < 0) continue; ESM::IndexedENAMstruct effect; - effect.mData.mEffectID = rec.mData.mEffectID[i]; - effect.mData.mSkill = rec.mData.mSkills[i]; - effect.mData.mAttribute = rec.mData.mAttributes[i]; + effect.mData.mEffectID = static_cast(rec.mData.mEffectID[i]); + effect.mData.mSkill = static_cast(rec.mData.mSkills[i]); + effect.mData.mAttribute = static_cast(rec.mData.mAttributes[i]); effect.mData.mRange = ESM::RT_Self; effect.mData.mArea = 0; effect.mData.mDuration = 0; diff --git a/apps/openmw/mwlua/types/npc.cpp b/apps/openmw/mwlua/types/npc.cpp index b71ad28fc0..1b4161d923 100644 --- a/apps/openmw/mwlua/types/npc.cpp +++ b/apps/openmw/mwlua/types/npc.cpp @@ -120,7 +120,7 @@ namespace } if (rec["baseDisposition"] != sol::nil) - npc.mNpdt.mDisposition = rec["baseDisposition"].get(); + npc.mNpdt.mDisposition = rec["baseDisposition"].get(); if (rec["baseGold"] != sol::nil) npc.mNpdt.mGold = rec["baseGold"].get(); @@ -136,7 +136,7 @@ namespace = MWBase::Environment::get().getESMStore()->get().find(npc.mFaction); int luaValue = rec["primaryFactionRank"]; - int rank = LuaUtil::fromLuaIndex(luaValue); + int64_t rank = LuaUtil::fromLuaIndex(luaValue); int maxRank = static_cast(getValidRanksCount(faction)); @@ -144,7 +144,7 @@ namespace throw std::runtime_error("primaryFactionRank: Requested rank " + std::to_string(rank) + " is out of bounds for faction " + npc.mFaction.toDebugString()); - npc.mNpdt.mRank = rank; + npc.mNpdt.mRank = static_cast(rank); } } @@ -217,7 +217,7 @@ namespace MWLua = sol::readonly_property([](const ESM::NPC& rec) -> std::string { return rec.mHead.serializeText(); }); record["primaryFaction"] = sol::readonly_property([](const ESM::NPC& rec) -> ESM::RefId { return rec.mFaction; }); - record["primaryFactionRank"] = sol::readonly_property([](const ESM::NPC& rec, sol::this_state s) -> int { + record["primaryFactionRank"] = sol::readonly_property([](const ESM::NPC& rec, sol::this_state s) -> int64_t { if (rec.mFaction.empty()) return 0; return LuaUtil::toLuaIndex(rec.mNpdt.mRank); @@ -331,7 +331,7 @@ namespace MWLua if (!npcStats.isInFaction(factionId)) throw std::runtime_error("Target actor is not a member of faction " + factionId.toDebugString()); - npcStats.setFactionRank(factionId, targetRank); + npcStats.setFactionRank(factionId, static_cast(targetRank)); }; npc["modifyFactionRank"] = [](Object& actor, std::string_view faction, int value) { diff --git a/apps/openmw/mwlua/types/weapon.cpp b/apps/openmw/mwlua/types/weapon.cpp index 96477bc0bb..32b983a6f7 100644 --- a/apps/openmw/mwlua/types/weapon.cpp +++ b/apps/openmw/mwlua/types/weapon.cpp @@ -64,7 +64,7 @@ namespace { int weaponType = rec["type"].get(); if (weaponType >= 0 && weaponType <= ESM::Weapon::Last) - weapon.mData.mType = weaponType; + weapon.mData.mType = static_cast(weaponType); else throw std::runtime_error("Invalid Weapon Type provided: " + std::to_string(weaponType)); } @@ -79,7 +79,7 @@ namespace if (rec["reach"] != sol::nil) weapon.mData.mReach = rec["reach"]; if (rec["enchantCapacity"] != sol::nil) - weapon.mData.mEnchant = std::round(rec["enchantCapacity"].get() * 10); + weapon.mData.mEnchant = static_cast(std::round(rec["enchantCapacity"].get() * 10)); if (rec["chopMinDamage"] != sol::nil) weapon.mData.mChop[0] = rec["chopMinDamage"]; if (rec["chopMaxDamage"] != sol::nil) diff --git a/apps/openmw/mwlua/uibindings.cpp b/apps/openmw/mwlua/uibindings.cpp index 05d3910f42..e0bed6f8a1 100644 --- a/apps/openmw/mwlua/uibindings.cpp +++ b/apps/openmw/mwlua/uibindings.cpp @@ -229,7 +229,10 @@ namespace MWLua return luaManager->uiResourceManager()->registerTexture(std::move(data)); }; - api["screenSize"] = []() { return osg::Vec2f(Settings::video().mResolutionX, Settings::video().mResolutionY); }; + api["screenSize"] = []() { + return osg::Vec2f( + static_cast(Settings::video().mResolutionX), static_cast(Settings::video().mResolutionY)); + }; api["_getAllUiModes"] = [](sol::this_state thisState) { sol::table res(thisState, sol::create); @@ -255,16 +258,16 @@ namespace MWLua if (arg.has_value()) ptr = arg->ptr(); const std::vector& stack = windowManager->getGuiModeStack(); - unsigned common = 0; + size_t common = 0; while (common < std::min(stack.size(), newStack.size()) && stack[common] == newStack[common]) common++; // TODO: Maybe disallow opening/closing special modes (main menu, settings, loading screen) // from player scripts. Add new Lua context "menu" that can do it. - for (unsigned i = stack.size() - common; i > 0; i--) + for (size_t i = stack.size() - common; i > 0; i--) windowManager->popGuiMode(true); if (common == newStack.size() && !newStack.empty() && arg.has_value()) windowManager->pushGuiMode(newStack.back(), ptr); - for (unsigned i = common; i < newStack.size(); ++i) + for (size_t i = common; i < newStack.size(); ++i) windowManager->pushGuiMode(newStack[i], ptr); }, "Set UI modes"); diff --git a/apps/openmw/mwmechanics/activespells.cpp b/apps/openmw/mwmechanics/activespells.cpp index 78d335738c..109b75e1d4 100644 --- a/apps/openmw/mwmechanics/activespells.cpp +++ b/apps/openmw/mwmechanics/activespells.cpp @@ -58,9 +58,9 @@ namespace effect.mEffectId = enam.mData.mEffectID; effect.mArg = MWMechanics::EffectKey(enam.mData).mArg; effect.mMagnitude = 0.f; - effect.mMinMagnitude = enam.mData.mMagnMin; - effect.mMaxMagnitude = enam.mData.mMagnMax; - effect.mEffectIndex = enam.mIndex; + effect.mMinMagnitude = static_cast(enam.mData.mMagnMin); + effect.mMaxMagnitude = static_cast(enam.mData.mMagnMax); + effect.mEffectIndex = static_cast(enam.mIndex); effect.mFlags = ESM::ActiveEffect::Flag_None; if (ignoreResistances) effect.mFlags |= ESM::ActiveEffect::Flag_Ignore_Resistances; diff --git a/apps/openmw/mwmechanics/actors.cpp b/apps/openmw/mwmechanics/actors.cpp index 04f4e12b65..786539e585 100644 --- a/apps/openmw/mwmechanics/actors.cpp +++ b/apps/openmw/mwmechanics/actors.cpp @@ -584,8 +584,8 @@ namespace MWMechanics float to = dir.y(); float angle = std::atan2(from, to); actorState.setAngleToPlayer(angle); - float deltaAngle = Misc::normalizeAngle(angle - actor.getRefData().getPosition().rot[2]); - if (!Settings::game().mSmoothMovement || std::abs(deltaAngle) > osg::DegreesToRadians(60.f)) + double deltaAngle = Misc::normalizeAngle(angle - actor.getRefData().getPosition().rot[2]); + if (!Settings::game().mSmoothMovement || std::abs(deltaAngle) > osg::DegreesToRadians(60.0)) actorState.setTurningToPlayer(true); } } @@ -849,7 +849,7 @@ namespace MWMechanics const auto [health, magicka] = getRestorationPerHourOfSleep(ptr); DynamicStat stat = stats.getHealth(); - stat.setCurrent(stat.getCurrent() + health * hours); + stat.setCurrent(static_cast(stat.getCurrent() + health * hours)); stats.setHealth(stat); double restoreHours = hours; @@ -876,7 +876,7 @@ namespace MWMechanics if (restoreHours > 0) { stat = stats.getMagicka(); - stat.setCurrent(stat.getCurrent() + magicka * restoreHours); + stat.setCurrent(static_cast(stat.getCurrent() + magicka * restoreHours)); stats.setMagicka(stat); } } @@ -901,7 +901,7 @@ namespace MWMechanics const float x = (fFatigueReturnBase + fFatigueReturnMult * (1 - normalizedEncumbrance)) * (fEndFatigueMult * endurance); - fatigue.setCurrent(fatigue.getCurrent() + 3600 * x * hours); + fatigue.setCurrent(static_cast(fatigue.getCurrent() + 3600 * x * hours)); stats.setFatigue(fatigue); } @@ -1156,9 +1156,8 @@ namespace MWMechanics if (playerStats.getBounty() >= cutoff * iCrimeThresholdMultiplier) { mechanicsManager->startCombat(ptr, player, &cachedAllies.getActorsSidingWith(player)); - creatureStats.setHitAttemptActorId( - playerClass.getCreatureStats(player) - .getActorId()); // Stops the guard from quitting combat if player is unreachable + // Stops the guard from quitting combat if player is unreachable + creatureStats.setHitAttemptActorId(playerClass.getCreatureStats(player).getActorId()); } else creatureStats.getAiSequence().stack(AiPursue(player), ptr); @@ -1234,7 +1233,7 @@ namespace MWMechanics // Fade away actors on large distance (>90% of actor's processing distance) float visibilityRatio = 1.0; const float fadeStartDistance = actorsProcessingRange * 0.9f; - const float fadeEndDistance = actorsProcessingRange; + const float fadeEndDistance = static_cast(actorsProcessingRange); const float fadeRatio = (dist - fadeStartDistance) / (fadeEndDistance - fadeStartDistance); if (fadeRatio > 0) visibilityRatio -= std::max(0.f, fadeRatio); @@ -1278,7 +1277,7 @@ namespace MWMechanics // Otherwise check if any actor in AI processing range sees the target actor std::vector neighbors; osg::Vec3f position(actor.getRefData().getPosition().asVec3()); - getObjectsInRange(position, Settings::game().mActorsProcessingRange, neighbors); + getObjectsInRange(position, static_cast(Settings::game().mActorsProcessingRange), neighbors); for (const MWWorld::Ptr& neighbor : neighbors) { if (neighbor == actor) @@ -1877,7 +1876,7 @@ namespace MWMechanics void Actors::rest(double hours, bool sleep) const { - float duration = hours * 3600.f; + float duration = static_cast(hours * 3600); const float timeScale = MWBase::Environment::get().getWorld()->getTimeManager()->getGameTimeScale(); if (timeScale != 0.f) duration /= timeScale; @@ -1952,7 +1951,7 @@ namespace MWMechanics std::vector observers; const osg::Vec3f position(player.getRefData().getPosition().asVec3()); - const float radius = std::min(fSneakUseDist, Settings::game().mActorsProcessingRange); + const float radius = std::min(fSneakUseDist, static_cast(Settings::game().mActorsProcessingRange)); getObjectsInRange(position, radius, observers); std::set sidingActors; @@ -2256,7 +2255,7 @@ namespace MWMechanics std::vector list; std::vector neighbors; const osg::Vec3f position(actor.getRefData().getPosition().asVec3()); - getObjectsInRange(position, Settings::game().mActorsProcessingRange, neighbors); + getObjectsInRange(position, static_cast(Settings::game().mActorsProcessingRange), neighbors); for (const MWWorld::Ptr& neighbor : neighbors) { if (neighbor == actor) @@ -2277,7 +2276,7 @@ namespace MWMechanics std::vector list; std::vector neighbors; osg::Vec3f position(actor.getRefData().getPosition().asVec3()); - getObjectsInRange(position, Settings::game().mActorsProcessingRange, neighbors); + getObjectsInRange(position, static_cast(Settings::game().mActorsProcessingRange), neighbors); std::set followers; getActorsFollowing(actor, followers); diff --git a/apps/openmw/mwmechanics/aiavoiddoor.cpp b/apps/openmw/mwmechanics/aiavoiddoor.cpp index 1f229f61bf..79e765711c 100644 --- a/apps/openmw/mwmechanics/aiavoiddoor.cpp +++ b/apps/openmw/mwmechanics/aiavoiddoor.cpp @@ -88,5 +88,5 @@ void MWMechanics::AiAvoidDoor::adjustDirection() float MWMechanics::AiAvoidDoor::getAdjustedAngle() const { - return 2 * osg::PI / MAX_DIRECTIONS * mDirection; + return 2 * osg::PIf / MAX_DIRECTIONS * mDirection; } diff --git a/apps/openmw/mwmechanics/aicombat.cpp b/apps/openmw/mwmechanics/aicombat.cpp index 4eb0c762eb..0ddcf409b6 100644 --- a/apps/openmw/mwmechanics/aicombat.cpp +++ b/apps/openmw/mwmechanics/aicombat.cpp @@ -432,7 +432,7 @@ namespace MWMechanics storage.mFleeBlindRunTimer += duration; storage.mMovement.mRotation[0] = -actor.getRefData().getPosition().rot[0]; - storage.mMovement.mRotation[2] = osg::PI + storage.mMovement.mRotation[2] = osg::PIf + getZAngleToDir( target.getRefData().getPosition().asVec3() - actor.getRefData().getPosition().asVec3()); storage.mMovement.mPosition[1] = 1; @@ -486,7 +486,7 @@ namespace MWMechanics actorMovementSettings.mRotation[axis] = 0; bool isRangedCombat = false; storage.mCurrentAction->getCombatRange(isRangedCombat); - float eps = isRangedCombat ? osg::DegreesToRadians(0.5) : osg::DegreesToRadians(3.f); + float eps = isRangedCombat ? osg::DegreesToRadians(0.5f) : osg::DegreesToRadians(3.f); float targetAngleRadians = storage.mMovement.mRotation[axis]; storage.mRotateMove = !smoothTurn(actor, targetAngleRadians, axis, eps); } @@ -567,7 +567,7 @@ namespace MWMechanics else if (actor.getClass().isBipedal(actor) && !isDistantCombat) { float moveDuration = 0; - float angleToTarget + double angleToTarget = Misc::normalizeAngle(mMovement.mRotation[2] - actor.getRefData().getPosition().rot[2]); // Apply a big side step if enemy tries to get around and come from behind. // Otherwise apply a random side step (kind of dodging) with some probability @@ -683,7 +683,7 @@ namespace MWMechanics MWBase::Environment::get().getDialogueManager()->say(actor, ESM::RefId::stringRefId("attack")); } } - mAttackCooldown = std::min(baseDelay + 0.01 * Misc::Rng::roll0to99(prng), baseDelay + 0.9); + mAttackCooldown = std::min(baseDelay + 0.01f * Misc::Rng::roll0to99(prng), baseDelay + 0.9f); } else mAttackCooldown -= AI_REACTION_TIME; diff --git a/apps/openmw/mwmechanics/aicombataction.cpp b/apps/openmw/mwmechanics/aicombataction.cpp index ac59de0426..334da834cd 100644 --- a/apps/openmw/mwmechanics/aicombataction.cpp +++ b/apps/openmw/mwmechanics/aicombataction.cpp @@ -514,7 +514,7 @@ namespace MWMechanics const int flee = stats.getAiSetting(AiSetting::Flee).getModified(); if (flee >= 100) - return flee; + return static_cast(flee); static const float fAIFleeHealthMult = gmst.find("fAIFleeHealthMult")->mValue.getFloat(); static const float fAIFleeFleeMult = gmst.find("fAIFleeFleeMult")->mValue.getFloat(); @@ -529,7 +529,7 @@ namespace MWMechanics if (enemy.getClass().getNpcStats(enemy).isWerewolf() && stats.getLevel() < iWereWolfLevelToAttack) { static const int iWereWolfFleeMod = gmst.find("iWereWolfFleeMod")->mValue.getInteger(); - rating = iWereWolfFleeMod; + rating = static_cast(iWereWolfFleeMod); } } diff --git a/apps/openmw/mwmechanics/aiescort.cpp b/apps/openmw/mwmechanics/aiescort.cpp index 9e6df46340..a375aea33c 100644 --- a/apps/openmw/mwmechanics/aiescort.cpp +++ b/apps/openmw/mwmechanics/aiescort.cpp @@ -29,7 +29,7 @@ namespace MWMechanics , mX(x) , mY(y) , mZ(z) - , mDuration(duration) + , mDuration(static_cast(duration)) , mRemainingDuration(static_cast(duration)) { mTargetActorRefId = actorId; @@ -42,7 +42,7 @@ namespace MWMechanics , mX(x) , mY(y) , mZ(z) - , mDuration(duration) + , mDuration(static_cast(duration)) , mRemainingDuration(static_cast(duration)) { mTargetActorRefId = actorId; @@ -129,7 +129,7 @@ namespace MWMechanics escort->mData.mX = mX; escort->mData.mY = mY; escort->mData.mZ = mZ; - escort->mData.mDuration = mDuration; + escort->mData.mDuration = static_cast(mDuration); escort->mTargetId = mTargetActorRefId; escort->mTargetActorId = mTargetActorId; escort->mRemainingDuration = mRemainingDuration; diff --git a/apps/openmw/mwmechanics/aifollow.cpp b/apps/openmw/mwmechanics/aifollow.cpp index b4779dc900..ec128ae2a9 100644 --- a/apps/openmw/mwmechanics/aifollow.cpp +++ b/apps/openmw/mwmechanics/aifollow.cpp @@ -244,7 +244,7 @@ namespace MWMechanics follow->mData.mX = mX; follow->mData.mY = mY; follow->mData.mZ = mZ; - follow->mData.mDuration = mDuration; + follow->mData.mDuration = static_cast(mDuration); follow->mTargetId = mTargetActorRefId; follow->mTargetActorId = mTargetActorId; follow->mRemainingDuration = mRemainingDuration; diff --git a/apps/openmw/mwmechanics/aipackage.cpp b/apps/openmw/mwmechanics/aipackage.cpp index 3fcb28307c..146124fcbf 100644 --- a/apps/openmw/mwmechanics/aipackage.cpp +++ b/apps/openmw/mwmechanics/aipackage.cpp @@ -37,7 +37,7 @@ namespace float getPointTolerance(float speed, float duration, const osg::Vec3f& halfExtents) { - const float actorTolerance = 2 * speed * duration + 1.2 * std::max(halfExtents.x(), halfExtents.y()); + const float actorTolerance = 2 * speed * duration + 1.2f * std::max(halfExtents.x(), halfExtents.y()); return std::max(MWMechanics::MIN_TOLERANCE, actorTolerance); } diff --git a/apps/openmw/mwmechanics/aiwander.cpp b/apps/openmw/mwmechanics/aiwander.cpp index 4499304303..ff937305ae 100644 --- a/apps/openmw/mwmechanics/aiwander.cpp +++ b/apps/openmw/mwmechanics/aiwander.cpp @@ -65,10 +65,10 @@ namespace MWMechanics osg::Vec3f getRandomPointAround(const osg::Vec3f& position, const float distance) { auto& prng = MWBase::Environment::get().getWorld()->getPrng(); - const float randomDirection = Misc::Rng::rollClosedProbability(prng) * 2.0f * osg::PI; + const float randomDirection = Misc::Rng::rollClosedProbability(prng) * 2.f * osg::PIf; osg::Matrixf rotation; - rotation.makeRotate(randomDirection, osg::Vec3f(0.0, 0.0, 1.0)); - return position + osg::Vec3f(distance, 0.0, 0.0) * rotation; + rotation.makeRotate(randomDirection, osg::Vec3f(0.f, 0.f, 1.f)); + return position + osg::Vec3f(distance, 0.f, 0.f) * rotation; } bool isDestinationHidden(const MWWorld::ConstPtr& actor, const osg::Vec3f& destination) @@ -158,13 +158,11 @@ namespace MWMechanics : TypedAiPackage(repeat) , mDistance(static_cast(std::max(0, distance))) , mDuration(static_cast(std::max(0, duration))) - , mRemainingDuration(duration) + , mRemainingDuration(static_cast(duration)) , mTimeOfDay(timeOfDay) , mIdle(getInitialIdle(idle)) , mStoredInitialActorPosition(false) - , mInitialActorPosition(osg::Vec3f(0, 0, 0)) , mHasDestination(false) - , mDestination(osg::Vec3f(0, 0, 0)) , mUsePathgrid(false) { } @@ -283,7 +281,7 @@ namespace MWMechanics { stopWalking(actor); // Reset package so it can be used again - mRemainingDuration = mDuration; + mRemainingDuration = static_cast(mDuration); return true; } @@ -628,8 +626,7 @@ namespace MWMechanics { MWBase::World& world = *MWBase::Environment::get().getWorld(); Misc::Rng::Generator& prng = world.getPrng(); - const std::size_t randomAllowedPositionIndex - = static_cast(Misc::Rng::rollDice(storage.mAllowedPositions.size(), prng)); + const std::size_t randomAllowedPositionIndex = Misc::Rng::rollDice(storage.mAllowedPositions.size(), prng); const osg::Vec3f randomAllowedPosition = storage.mAllowedPositions[randomAllowedPositionIndex]; const osg::Vec3f start = actorPos.asVec3(); @@ -734,7 +731,7 @@ namespace MWMechanics } } - int AiWander::getRandomIdle() const + unsigned short AiWander::getRandomIdle() const { MWBase::World* world = MWBase::Environment::get().getWorld(); static const float fIdleChanceMultiplier @@ -742,14 +739,14 @@ namespace MWMechanics if (Misc::Rng::rollClosedProbability(world->getPrng()) > fIdleChanceMultiplier) return 0; - int newIdle = 0; + unsigned short newIdle = 0; float maxRoll = 0.f; for (size_t i = 0; i < mIdle.size(); i++) { float roll = Misc::Rng::rollClosedProbability(world->getPrng()) * 100.f; if (roll <= mIdle[i] && roll > maxRoll) { - newIdle = GroupIndex_MinIdle + i; + newIdle = static_cast(GroupIndex_MinIdle + i); maxRoll = roll; } } @@ -772,7 +769,7 @@ namespace MWMechanics return; auto& prng = MWBase::Environment::get().getWorld()->getPrng(); - int index = Misc::Rng::rollDice(storage.mAllowedPositions.size(), prng); + size_t index = Misc::Rng::rollDice(storage.mAllowedPositions.size(), prng); const osg::Vec3f worldDest = storage.mAllowedPositions[index]; const Misc::CoordinateConverter converter = Misc::makeCoordinateConverter(*actor.getCell()->getCell()); osg::Vec3f dest = converter.toLocalVec3(worldDest); @@ -794,7 +791,7 @@ namespace MWMechanics // AI will try to move the NPC towards every neighboring node until suitable place will be found while (!points.empty()) { - int randomIndex = Misc::Rng::rollDice(points.size(), prng); + size_t randomIndex = Misc::Rng::rollDice(points.size(), prng); const ESM::Pathgrid::Point& connDest = points[randomIndex]; // add an offset towards random neighboring node @@ -940,7 +937,7 @@ namespace MWMechanics // must not travel longer than distance between waypoints or NPC goes past waypoint distance = std::min(distance, static_cast(length)); - delta *= distance; + delta *= static_cast(distance); storage.mAllowedPositions.push_back(vectorStart + delta); } @@ -968,12 +965,12 @@ namespace MWMechanics if (mRemainingDuration > 0 && mRemainingDuration < 24) remainingDuration = mRemainingDuration; else - remainingDuration = mDuration; + remainingDuration = static_cast(mDuration); auto wander = std::make_unique(); - wander->mData.mDistance = mDistance; - wander->mData.mDuration = mDuration; - wander->mData.mTimeOfDay = mTimeOfDay; + wander->mData.mDistance = static_cast(mDistance); + wander->mData.mDuration = static_cast(mDuration); + wander->mData.mTimeOfDay = static_cast(mTimeOfDay); wander->mDurationData.mRemainingDuration = remainingDuration; assert(mIdle.size() == 8); for (int i = 0; i < 8; ++i) @@ -998,12 +995,11 @@ namespace MWMechanics , mIdle(getInitialIdle(wander->mData.mIdle)) , mStoredInitialActorPosition(wander->mStoredInitialActorPosition) , mHasDestination(false) - , mDestination(osg::Vec3f(0, 0, 0)) , mUsePathgrid(false) { if (mStoredInitialActorPosition) mInitialActorPosition = wander->mInitialActorPosition; if (mRemainingDuration <= 0 || mRemainingDuration >= 24) - mRemainingDuration = mDuration; + mRemainingDuration = static_cast(mDuration); } } diff --git a/apps/openmw/mwmechanics/aiwander.hpp b/apps/openmw/mwmechanics/aiwander.hpp index 3e0b704524..b99d2638a4 100644 --- a/apps/openmw/mwmechanics/aiwander.hpp +++ b/apps/openmw/mwmechanics/aiwander.hpp @@ -131,7 +131,7 @@ namespace MWMechanics /// @return Success or error bool playIdle(const MWWorld::Ptr& actor, unsigned short idleSelect); bool checkIdle(const MWWorld::Ptr& actor, unsigned short idleSelect); - int getRandomIdle() const; + unsigned short getRandomIdle() const; void setPathToAnAllowedPosition( const MWWorld::Ptr& actor, AiWanderStorage& storage, const ESM::Position& actorPos); void evadeObstacles(const MWWorld::Ptr& actor, AiWanderStorage& storage); diff --git a/apps/openmw/mwmechanics/alchemy.cpp b/apps/openmw/mwmechanics/alchemy.cpp index e2edf5f9cf..3c08279463 100644 --- a/apps/openmw/mwmechanics/alchemy.cpp +++ b/apps/openmw/mwmechanics/alchemy.cpp @@ -217,15 +217,15 @@ void MWMechanics::Alchemy::updateEffects() if (magnitude > 0 && duration > 0) { ESM::ENAMstruct effect; - effect.mEffectID = effectKey.mId; + effect.mEffectID = static_cast(effectKey.mId); effect.mAttribute = -1; effect.mSkill = -1; if (magicEffect->mData.mFlags & ESM::MagicEffect::TargetSkill) - effect.mSkill = ESM::Skill::refIdToIndex(effectKey.mArg); + effect.mSkill = static_cast(ESM::Skill::refIdToIndex(effectKey.mArg)); else if (magicEffect->mData.mFlags & ESM::MagicEffect::TargetAttribute) - effect.mAttribute = ESM::Attribute::refIdToIndex(effectKey.mArg); + effect.mAttribute = static_cast(ESM::Attribute::refIdToIndex(effectKey.mArg)); effect.mRange = 0; effect.mArea = 0; @@ -395,8 +395,7 @@ void MWMechanics::Alchemy::setAlchemist(const MWWorld::Ptr& npc) MWWorld::ContainerStore& store = npc.getClass().getContainerStore(npc); - for (MWWorld::ContainerStoreIterator iter(store.begin(MWWorld::ContainerStore::Type_Apparatus)); - iter != store.end(); ++iter) + for (auto iter(store.begin(MWWorld::ContainerStore::Type_Apparatus)); iter != store.end(); ++iter) { MWWorld::LiveCellRef* ref = iter->get(); @@ -515,7 +514,7 @@ MWMechanics::Alchemy::TEffectsIterator MWMechanics::Alchemy::endEffects() const return mEffects.end(); } -bool MWMechanics::Alchemy::knownEffect(unsigned int potionEffectIndex, const MWWorld::Ptr& npc) +bool MWMechanics::Alchemy::knownEffect(size_t potionEffectIndex, const MWWorld::Ptr& npc) { float alchemySkill = npc.getClass().getSkill(npc, ESM::Skill::Alchemy); static const float fWortChanceValue @@ -604,7 +603,8 @@ std::string MWMechanics::Alchemy::suggestPotionName() return effects.begin()->toString(); } -std::vector MWMechanics::Alchemy::effectsDescription(const MWWorld::ConstPtr& ptr, const int alchemySkill) +std::vector MWMechanics::Alchemy::effectsDescription( + const MWWorld::ConstPtr& ptr, const float alchemySkill) { std::vector effects; diff --git a/apps/openmw/mwmechanics/alchemy.hpp b/apps/openmw/mwmechanics/alchemy.hpp index 373ca8b887..eca7014c84 100644 --- a/apps/openmw/mwmechanics/alchemy.hpp +++ b/apps/openmw/mwmechanics/alchemy.hpp @@ -86,7 +86,7 @@ namespace MWMechanics int countPotionsToBrew() const; ///< calculates maximum amount of potions, which you can make from selected ingredients - static bool knownEffect(unsigned int potionEffectIndex, const MWWorld::Ptr& npc); + static bool knownEffect(size_t potionEffectIndex, const MWWorld::Ptr& npc); ///< Does npc have sufficient alchemy skill to know about this potion effect? void setAlchemist(const MWWorld::Ptr& npc); @@ -135,7 +135,7 @@ namespace MWMechanics /// adjust the skills of the alchemist accordingly. /// \param name must not be an empty string, or Result_NoName is returned - static std::vector effectsDescription(const MWWorld::ConstPtr& ptr, const int alchemySKill); + static std::vector effectsDescription(const MWWorld::ConstPtr& ptr, const float alchemySKill); }; } diff --git a/apps/openmw/mwmechanics/autocalcspell.cpp b/apps/openmw/mwmechanics/autocalcspell.cpp index 5bab25fbe5..dcd3ec7dcb 100644 --- a/apps/openmw/mwmechanics/autocalcspell.cpp +++ b/apps/openmw/mwmechanics/autocalcspell.cpp @@ -278,10 +278,10 @@ namespace MWMechanics .find("fEffectCostMult") ->mValue.getFloat(); - float x = 0.5 * (std::max(1, minMagn) + std::max(1, maxMagn)); - x *= 0.1 * magicEffect->mData.mBaseCost; + float x = 0.5f * (std::max(1, minMagn) + std::max(1, maxMagn)); + x *= 0.1f * magicEffect->mData.mBaseCost; x *= 1 + duration; - x += 0.05 * std::max(1, effect.mData.mArea) * magicEffect->mData.mBaseCost; + x += 0.05f * std::max(1, effect.mData.mArea) * magicEffect->mData.mBaseCost; x *= fEffectCostMult; if (effect.mData.mRange == ESM::RT_Target) diff --git a/apps/openmw/mwmechanics/character.cpp b/apps/openmw/mwmechanics/character.cpp index 86cfd96e0b..c87ad8ef15 100644 --- a/apps/openmw/mwmechanics/character.cpp +++ b/apps/openmw/mwmechanics/character.cpp @@ -828,8 +828,8 @@ namespace MWMechanics clearStateAnimation(mCurrentIdle); mCurrentIdle = std::move(idleGroup); - playBlendedAnimation( - mCurrentIdle, priority, MWRender::BlendMask_All, false, 1.0f, "start", "stop", startPoint, numLoops, true); + playBlendedAnimation(mCurrentIdle, priority, MWRender::BlendMask_All, false, 1.0f, "start", "stop", startPoint, + static_cast(numLoops), true); } void CharacterController::refreshCurrentAnims( @@ -851,7 +851,8 @@ namespace MWMechanics { mDeathState = death; mCurrentDeath = deathStateToAnimGroup(mDeathState); - mPtr.getClass().getCreatureStats(mPtr).setDeathAnimation(mDeathState - CharState_Death1); + mPtr.getClass().getCreatureStats(mPtr).setDeathAnimation( + static_cast(mDeathState - CharState_Death1)); // For dead actors, refreshCurrentAnims is no longer called, so we need to disable the movement state manually. // Note that these animations wouldn't actually be visible (due to the Death animation's priority being higher). @@ -1920,7 +1921,7 @@ namespace MWMechanics else { float complete; - size_t loopcount; + uint32_t loopcount; mAnimation->getInfo(mAnimQueue.front().mGroup, &complete, nullptr, &loopcount); mAnimQueue.front().mLoopCount = loopcount; mAnimQueue.front().mTime = complete; @@ -2006,10 +2007,10 @@ namespace MWMechanics { // Force Jump if (stats.getMovementFlag(MWMechanics::CreatureStats::Flag_ForceJump)) - movementSettings.mPosition[2] = onground ? 1 : 0; + movementSettings.mPosition[2] = onground ? 1.f : 0.f; // Force Move Jump, only jump if they're otherwise moving if (stats.getMovementFlag(MWMechanics::CreatureStats::Flag_ForceMoveJump) && isMoving) - movementSettings.mPosition[2] = onground ? 1 : 0; + movementSettings.mPosition[2] = onground ? 1.f : 0.f; } osg::Vec3f rot = cls.getRotationVector(mPtr); @@ -2032,7 +2033,7 @@ namespace MWMechanics maxDelta = 1; else if (std::abs(speedDelta) < deltaLen / 2) // Turning is smooth for player and less smooth for NPCs (otherwise NPC can miss a path point). - maxDelta = duration * (isPlayer ? 1.0 / Settings::game().mSmoothMovementPlayerTurningDelay : 6.f); + maxDelta = duration * (isPlayer ? 1.0f / Settings::game().mSmoothMovementPlayerTurningDelay : 6.f); else if (isPlayer && speedDelta < -deltaLen / 2) // As soon as controls are released, mwinput switches player from running to walking. // So stopping should be instant for player, otherwise it causes a small twitch. @@ -2090,7 +2091,7 @@ namespace MWMechanics if (std::abs(delta) < osg::DegreesToRadians(20.0f)) mIsMovingBackward = vec.y() < 0; - float maxDelta = osg::PI * duration * (2.5f - cosDelta); + float maxDelta = osg::PIf * duration * (2.5f - cosDelta); delta = std::clamp(delta, -maxDelta, maxDelta); stats.setSideMovementAngle(stats.getSideMovementAngle() + delta); effectiveRotation += delta; @@ -2516,7 +2517,7 @@ namespace MWMechanics if (iter == mAnimQueue.begin() && mAnimation) { float complete; - size_t loopcount; + uint32_t loopcount; mAnimation->getInfo(anim.mGroup, &complete, nullptr, &loopcount); anim.mTime = complete; anim.mLoopCount = loopcount; @@ -2538,24 +2539,23 @@ namespace MWMechanics if (!state.mScriptedAnims.empty()) { clearAnimQueue(); - for (ESM::AnimationState::ScriptedAnimations::const_iterator iter = state.mScriptedAnims.begin(); - iter != state.mScriptedAnims.end(); ++iter) + for (const ESM::AnimationState::ScriptedAnimation& animation : state.mScriptedAnims) { AnimationQueueEntry entry; - entry.mGroup = iter->mGroup; - entry.mLoopCount - = static_cast(std::min(iter->mLoopCount, std::numeric_limits::max())); + entry.mGroup = animation.mGroup; + entry.mLoopCount = static_cast( + std::min(animation.mLoopCount, std::numeric_limits::max())); entry.mLooping = mAnimation->isLoopingAnimation(entry.mGroup); entry.mScripted = true; entry.mStartKey = "start"; entry.mStopKey = "stop"; entry.mSpeed = 1.f; - entry.mTime = iter->mTime; - if (iter->mAbsolute) + entry.mTime = animation.mTime; + if (animation.mAbsolute) { - float start = mAnimation->getTextKeyTime(iter->mGroup + ": start"); - float stop = mAnimation->getTextKeyTime(iter->mGroup + ": stop"); - float time = std::clamp(iter->mTime, start, stop); + float start = mAnimation->getTextKeyTime(animation.mGroup + ": start"); + float stop = mAnimation->getTextKeyTime(animation.mGroup + ": stop"); + float time = std::clamp(animation.mTime, start, stop); entry.mTime = (time - start) / (stop - start); } @@ -3083,8 +3083,8 @@ namespace MWMechanics if (!head) return; - double zAngleRadians = 0.f; - double xAngleRadians = 0.f; + float zAngleRadians = 0.f; + float xAngleRadians = 0.f; if (!mHeadTrackTarget.isEmpty()) { @@ -3118,14 +3118,15 @@ namespace MWMechanics zAngleRadians = std::atan2(actorDirection.x(), actorDirection.y()) - std::atan2(direction.x(), direction.y()); - zAngleRadians = Misc::normalizeAngle(zAngleRadians - mAnimation->getHeadYaw()) + mAnimation->getHeadYaw(); + zAngleRadians = static_cast( + Misc::normalizeAngle(zAngleRadians - mAnimation->getHeadYaw()) + mAnimation->getHeadYaw()); zAngleRadians *= (1 - direction.z() * direction.z()); xAngleRadians = std::asin(direction.z()); } - const double xLimit = osg::DegreesToRadians(40.0); - const double zLimit = osg::DegreesToRadians(30.0); - double zLimitOffset = mAnimation->getUpperBodyYawRadians(); + const float xLimit = osg::DegreesToRadians(40.f); + const float zLimit = osg::DegreesToRadians(30.f); + float zLimitOffset = mAnimation->getUpperBodyYawRadians(); xAngleRadians = std::clamp(xAngleRadians, -xLimit, xLimit); zAngleRadians = std::clamp(zAngleRadians, -zLimit + zLimitOffset, zLimit + zLimitOffset); diff --git a/apps/openmw/mwmechanics/combat.cpp b/apps/openmw/mwmechanics/combat.cpp index cd25a4f4ea..e82ff0c8d2 100644 --- a/apps/openmw/mwmechanics/combat.cpp +++ b/apps/openmw/mwmechanics/combat.cpp @@ -133,7 +133,7 @@ namespace MWMechanics static const int iBlockMaxChance = gmst.find("iBlockMaxChance")->mValue.getInteger(); static const int iBlockMinChance = gmst.find("iBlockMinChance")->mValue.getInteger(); - int x = std::clamp(blockerTerm - attackerTerm, iBlockMinChance, iBlockMaxChance); + int x = std::clamp(static_cast(blockerTerm - attackerTerm), iBlockMinChance, iBlockMaxChance); auto& prng = MWBase::Environment::get().getWorld()->getPrng(); if (Misc::Rng::roll0to99(prng) < x) @@ -239,7 +239,7 @@ namespace MWMechanics if (attacker == getPlayer()) MWBase::Environment::get().getWindowManager()->setEnemy(victim); - int skillValue = attacker.getClass().getSkill(attacker, weaponSkill); + int skillValue = static_cast(attacker.getClass().getSkill(attacker, weaponSkill)); if (Misc::Rng::roll0to99(world->getPrng()) >= getHitChance(attacker, victim, skillValue)) { @@ -375,7 +375,7 @@ namespace MWMechanics float x = std::max(0.f, saveTerm - Misc::Rng::roll0to99(prng)); - int element = ESM::MagicEffect::FireDamage; + short element = ESM::MagicEffect::FireDamage; if (i == 1) element = ESM::MagicEffect::ShockDamage; if (i == 2) @@ -633,7 +633,7 @@ namespace MWMechanics actor.getClass().getCreatureStats(actor).getAiSequence().getCombatTargets(targets); else MWBase::Environment::get().getMechanicsManager()->getActorsInRange( - actorPos, Settings::game().mActorsProcessingRange, targets); + actorPos, static_cast(Settings::game().mActorsProcessingRange), targets); for (MWWorld::Ptr& target : targets) { diff --git a/apps/openmw/mwmechanics/creaturestats.cpp b/apps/openmw/mwmechanics/creaturestats.cpp index 0a14d46097..24b5891c1c 100644 --- a/apps/openmw/mwmechanics/creaturestats.cpp +++ b/apps/openmw/mwmechanics/creaturestats.cpp @@ -407,8 +407,8 @@ namespace MWMechanics else base = world->getStore().get().find("fNPCbaseMagickaMult")->mValue.getFloat(); - double magickaFactor = base - + mMagicEffects.getOrDefault(EffectKey(ESM::MagicEffect::FortifyMaximumMagicka)).getMagnitude() * 0.1; + float magickaFactor = base + + mMagicEffects.getOrDefault(EffectKey(ESM::MagicEffect::FortifyMaximumMagicka)).getMagnitude() * 0.1f; DynamicStat magicka = getMagicka(); float currentToBaseRatio = magicka.getBase() > 0 ? magicka.getCurrent() / magicka.getBase() : 0; @@ -507,7 +507,7 @@ namespace MWMechanics void CreatureStats::writeState(ESM::CreatureStats& state) const { for (size_t i = 0; i < state.mAttributes.size(); ++i) - getAttribute(ESM::Attribute::indexToRefId(i)).writeState(state.mAttributes[i]); + getAttribute(ESM::Attribute::indexToRefId(static_cast(i))).writeState(state.mAttributes[i]); for (size_t i = 0; i < state.mDynamic.size(); ++i) mDynamic[i].writeState(state.mDynamic[i]); @@ -564,7 +564,7 @@ namespace MWMechanics if (!state.mMissingACDT) { for (size_t i = 0; i < state.mAttributes.size(); ++i) - mAttributes[ESM::Attribute::indexToRefId(i)].readState(state.mAttributes[i]); + mAttributes[ESM::Attribute::indexToRefId(static_cast(i))].readState(state.mAttributes[i]); for (size_t i = 0; i < state.mDynamic.size(); ++i) mDynamic[i].readState(state.mDynamic[i]); diff --git a/apps/openmw/mwmechanics/enchanting.cpp b/apps/openmw/mwmechanics/enchanting.cpp index 66bef89e2c..0efb6aa641 100644 --- a/apps/openmw/mwmechanics/enchanting.cpp +++ b/apps/openmw/mwmechanics/enchanting.cpp @@ -300,7 +300,7 @@ namespace MWMechanics ->mValue.getFloat(); int price = MWBase::Environment::get().getMechanicsManager()->getBarterOffer( mEnchanter, static_cast(finalEffectCost * priceMultipler), true); - price *= count * getTypeMultiplier(); + price *= static_cast(count * getTypeMultiplier()); return std::max(1, price); } @@ -381,8 +381,9 @@ namespace MWMechanics { MWWorld::Ptr player = getPlayer(); count = player.getClass().getContainerStore(player).count(mOldItemPtr.getCellRef().getRefId()); - count = std::clamp( - getGemCharge() * Settings::game().mProjectilesEnchantMultiplier / enchantPoints, 1, count); + count = std::clamp( + static_cast(getGemCharge() * Settings::game().mProjectilesEnchantMultiplier / enchantPoints), + 1, count); } } diff --git a/apps/openmw/mwmechanics/mechanicsmanagerimp.cpp b/apps/openmw/mwmechanics/mechanicsmanagerimp.cpp index f70605b809..2d2f5057b0 100644 --- a/apps/openmw/mwmechanics/mechanicsmanagerimp.cpp +++ b/apps/openmw/mwmechanics/mechanicsmanagerimp.cpp @@ -135,10 +135,10 @@ namespace MWMechanics creatureStats.getActiveSpells().clear(ptr); for (size_t i = 0; i < player->mNpdt.mSkills.size(); ++i) - npcStats.getSkill(ESM::Skill::indexToRefId(i)).setBase(player->mNpdt.mSkills[i]); + npcStats.getSkill(ESM::Skill::indexToRefId(static_cast(i))).setBase(player->mNpdt.mSkills[i]); for (size_t i = 0; i < player->mNpdt.mAttributes.size(); ++i) - npcStats.setAttribute(ESM::Attribute::indexToRefId(i), player->mNpdt.mSkills[i]); + npcStats.setAttribute(ESM::Attribute::indexToRefId(static_cast(i)), player->mNpdt.mSkills[i]); const MWWorld::ESMStore& esmStore = *MWBase::Environment::get().getESMStore(); @@ -150,7 +150,8 @@ namespace MWMechanics bool male = (player->mFlags & ESM::NPC::Female) == 0; for (const ESM::Attribute& attribute : esmStore.get()) - creatureStats.setAttribute(attribute.mId, race->mData.getAttribute(attribute.mId, male)); + creatureStats.setAttribute( + attribute.mId, static_cast(race->mData.getAttribute(attribute.mId, male))); for (const ESM::Skill& skill : esmStore.get()) { @@ -161,7 +162,7 @@ namespace MWMechanics if (bonusIt != race->mData.mBonus.end()) bonus = bonusIt->mBonus; - npcStats.getSkill(skill.mId).setBase(5 + bonus); + npcStats.getSkill(skill.mId).setBase(5.f + bonus); } for (const ESM::RefId& power : race->mPowers.mList) @@ -566,7 +567,7 @@ namespace MWMechanics .getMagnitude(); if (clamp) - return std::clamp(x, 0, 100); //, normally clamped to [0..100] when used + return std::clamp(static_cast(x), 0, 100); //, normally clamped to [0..100] when used return static_cast(x); } @@ -1733,10 +1734,8 @@ namespace MWMechanics // if guard starts combat with player, guards pursuing player should do the same if (ptr.getClass().isClass(ptr, "Guard")) { - stats.setHitAttemptActorId( - target.getClass() - .getCreatureStats(target) - .getActorId()); // Stops guard from ending combat if player is unreachable + // Stops guard from ending combat if player is unreachable + stats.setHitAttemptActorId(target.getClass().getCreatureStats(target).getActorId()); for (const Actor& actor : mActors) { if (actor.isInvalid()) @@ -1749,13 +1748,11 @@ namespace MWMechanics { aiSeq.stopPursuit(); aiSeq.stack(MWMechanics::AiCombat(target), ptr); + // Stops guard from ending combat if player is unreachable actor.getPtr() .getClass() .getCreatureStats(actor.getPtr()) - .setHitAttemptActorId( - target.getClass() - .getCreatureStats(target) - .getActorId()); // Stops guard from ending combat if player is unreachable + .setHitAttemptActorId(target.getClass().getCreatureStats(target).getActorId()); } } } @@ -1830,7 +1827,7 @@ namespace MWMechanics mActors.getActorsSidingWith(actor, out); } - int MechanicsManager::countSavedGameRecords() const + size_t MechanicsManager::countSavedGameRecords() const { return 1 // Death counter + 1; // Stolen items @@ -2051,8 +2048,8 @@ namespace MWMechanics void MechanicsManager::reportStats(unsigned int frameNumber, osg::Stats& stats) const { - stats.setAttribute(frameNumber, "Mechanics Actors", mActors.size()); - stats.setAttribute(frameNumber, "Mechanics Objects", mObjects.size()); + stats.setAttribute(frameNumber, "Mechanics Actors", static_cast(mActors.size())); + stats.setAttribute(frameNumber, "Mechanics Objects", static_cast(mObjects.size())); } int MechanicsManager::getGreetingTimer(const MWWorld::Ptr& ptr) const diff --git a/apps/openmw/mwmechanics/mechanicsmanagerimp.hpp b/apps/openmw/mwmechanics/mechanicsmanagerimp.hpp index 11ef21852c..4e310e451e 100644 --- a/apps/openmw/mwmechanics/mechanicsmanagerimp.hpp +++ b/apps/openmw/mwmechanics/mechanicsmanagerimp.hpp @@ -182,7 +182,7 @@ namespace MWMechanics bool onOpen(const MWWorld::Ptr& ptr) override; void onClose(const MWWorld::Ptr& ptr) override; - int countSavedGameRecords() const override; + size_t countSavedGameRecords() const override; void write(ESM::ESMWriter& writer, Loading::Listener& listener) const override; diff --git a/apps/openmw/mwmechanics/npcstats.cpp b/apps/openmw/mwmechanics/npcstats.cpp index a55374411a..6f0fe667f1 100644 --- a/apps/openmw/mwmechanics/npcstats.cpp +++ b/apps/openmw/mwmechanics/npcstats.cpp @@ -493,7 +493,7 @@ void MWMechanics::NpcStats::readState(const ESM::NpcStats& state) for (size_t i = 0; i < state.mSkills.size(); ++i) { // TODO extend format - ESM::RefId id = ESM::Skill::indexToRefId(i); + ESM::RefId id = ESM::Skill::indexToRefId(static_cast(i)); assert(!id.empty()); mSkills[id].readState(state.mSkills[i]); } @@ -507,7 +507,7 @@ void MWMechanics::NpcStats::readState(const ESM::NpcStats& state) mLevelProgress = state.mLevelProgress; for (size_t i = 0; i < state.mSkillIncrease.size(); ++i) - mSkillIncreases[ESM::Attribute::indexToRefId(i)] = state.mSkillIncrease[i]; + mSkillIncreases[ESM::Attribute::indexToRefId(static_cast(i))] = state.mSkillIncrease[i]; for (size_t i = 0; i < state.mSpecIncreases.size(); ++i) mSpecIncreases[i] = state.mSpecIncreases[i]; diff --git a/apps/openmw/mwmechanics/pathfinding.cpp b/apps/openmw/mwmechanics/pathfinding.cpp index 6c30f43cef..c14b9ddffd 100644 --- a/apps/openmw/mwmechanics/pathfinding.cpp +++ b/apps/openmw/mwmechanics/pathfinding.cpp @@ -80,7 +80,7 @@ namespace { const auto world = MWBase::Environment::get().getWorld(); const auto halfExtents = world->getHalfExtents(actor); - return 2.0 * halfExtents.z(); + return 2.f * halfExtents.z(); } // Returns true if turn in `p2` is less than 10 degrees and all the 3 points are almost on one line. @@ -93,7 +93,7 @@ namespace float crossProduct = v1.x() * v3.y() - v1.y() * v3.x(); // Check that the angle between v1 and v3 is less or equal than 5 degrees. - static const float cos175 = std::cos(osg::PI * (175.0 / 180)); + static const float cos175 = std::cos(osg::PIf * (175.f / 180)); bool checkAngle = dotProduct <= cos175 * v1.length() * v3.length(); // Check that distance from p2 to the line (p1, p3) is less or equal than `pointTolerance`. @@ -246,12 +246,11 @@ namespace MWMechanics // Add Z offset since path node can overlap with other objects. // Also ignore doors in raytesting. const int mask = MWPhysics::CollisionType_World; - bool isPathClear = !MWBase::Environment::get() - .getWorld() - ->getRayCasting() - ->castRay(osg::Vec3f(startPoint.x(), startPoint.y(), startPoint.z() + 16), - osg::Vec3f(temp.mX, temp.mY, temp.mZ + 16), mask) - .mHit; + const osg::Vec3f zOffset(0.f, 0.f, 16.f); + const osg::Vec3f from = startPoint + zOffset; + const osg::Vec3f to = Misc::Convert::makeOsgVec3f(temp) + zOffset; + bool isPathClear + = !MWBase::Environment::get().getWorld()->getRayCasting()->castRay(from, to, mask).mHit; if (isPathClear) path.pop_front(); } diff --git a/apps/openmw/mwmechanics/setbaseaisetting.hpp b/apps/openmw/mwmechanics/setbaseaisetting.hpp index c7624c30e4..342f3b026f 100644 --- a/apps/openmw/mwmechanics/setbaseaisetting.hpp +++ b/apps/openmw/mwmechanics/setbaseaisetting.hpp @@ -12,7 +12,7 @@ namespace MWMechanics { template - void setBaseAISetting(const ESM::RefId& id, MWMechanics::AiSetting setting, int value) + void setBaseAISetting(const ESM::RefId& id, MWMechanics::AiSetting setting, unsigned char value) { T copy = *MWBase::Environment::get().getESMStore()->get().find(id); switch (setting) diff --git a/apps/openmw/mwmechanics/spellcasting.cpp b/apps/openmw/mwmechanics/spellcasting.cpp index bf9d6aa025..d17bd97744 100644 --- a/apps/openmw/mwmechanics/spellcasting.cpp +++ b/apps/openmw/mwmechanics/spellcasting.cpp @@ -92,7 +92,7 @@ namespace MWMechanics } // Get the actors in range of the effect std::vector objects; - static const int unitsPerFoot = ceil(Constants::UnitsPerFoot); + static const int unitsPerFoot = static_cast(std::ceil(Constants::UnitsPerFoot)); MWBase::Environment::get().getMechanicsManager()->getObjectsInRange( mHitPosition, static_cast(effectInfo.mData.mArea * unitsPerFoot), objects); for (const MWWorld::Ptr& affected : objects) @@ -204,8 +204,8 @@ namespace MWMechanics effect.mEffectId = enam.mData.mEffectID; effect.mArg = MWMechanics::EffectKey(enam.mData).mArg; effect.mMagnitude = 0.f; - effect.mMinMagnitude = enam.mData.mMagnMin; - effect.mMaxMagnitude = enam.mData.mMagnMax; + effect.mMinMagnitude = static_cast(enam.mData.mMagnMin); + effect.mMaxMagnitude = static_cast(enam.mData.mMagnMax); effect.mTimeLeft = 0.f; effect.mEffectIndex = enam.mIndex; effect.mFlags = ESM::ActiveEffect::Flag_None; diff --git a/apps/openmw/mwmechanics/spelleffects.cpp b/apps/openmw/mwmechanics/spelleffects.cpp index 6c8bc292ec..a1beca14bb 100644 --- a/apps/openmw/mwmechanics/spelleffects.cpp +++ b/apps/openmw/mwmechanics/spelleffects.cpp @@ -41,7 +41,8 @@ namespace if (effect.mMinMagnitude == effect.mMaxMagnitude) return effect.mMinMagnitude; auto& prng = MWBase::Environment::get().getWorld()->getPrng(); - return effect.mMinMagnitude + Misc::Rng::rollDice(effect.mMaxMagnitude - effect.mMinMagnitude + 1, prng); + return effect.mMinMagnitude + + Misc::Rng::rollDice(static_cast(effect.mMaxMagnitude - effect.mMinMagnitude + 1), prng); } ESM::ActiveEffect::Flags modifyAiSetting(const MWWorld::Ptr& target, const ESM::ActiveEffect& effect, @@ -363,8 +364,8 @@ namespace { const ESM::Spell* spell = spellParams.hasFlag(ESM::ActiveSpells::Flag_Temporary) ? spellParams.getSpell() : nullptr; - float magnitudeMult - = MWMechanics::getEffectMultiplier(effect.mEffectId, target, caster, spell, &magnitudes); + float magnitudeMult = MWMechanics::getEffectMultiplier( + static_cast(effect.mEffectId), target, caster, spell, &magnitudes); if (magnitudeMult == 0) { // Fully resisted, show message diff --git a/apps/openmw/mwmechanics/spellutil.cpp b/apps/openmw/mwmechanics/spellutil.cpp index fc7637afc1..8dca5f3a00 100644 --- a/apps/openmw/mwmechanics/spellutil.cpp +++ b/apps/openmw/mwmechanics/spellutil.cpp @@ -75,10 +75,10 @@ namespace MWMechanics costMult = iAlchemyMod; } - float x = 0.5 * (minMagn + maxMagn); - x *= 0.1 * magicEffect->mData.mBaseCost; + float x = 0.5f * (minMagn + maxMagn); + x *= 0.1f * magicEffect->mData.mBaseCost; x *= durationOffset + duration; - x += 0.05 * std::max(minArea, effect.mArea) * magicEffect->mData.mBaseCost; + x += 0.05f * std::max(minArea, effect.mArea) * magicEffect->mData.mBaseCost; return x * costMult; } @@ -90,7 +90,7 @@ namespace MWMechanics float cost = getTotalCost(spell.mEffects); - return std::round(cost); + return static_cast(std::round(cost)); } int getEffectiveEnchantmentCastCost(float castCost, const MWWorld::Ptr& actor) @@ -99,7 +99,7 @@ namespace MWMechanics * Each point of enchant skill above/under 10 subtracts/adds * one percent of enchantment cost while minimum is 1. */ - int eSkill = actor.getClass().getSkill(actor, ESM::Skill::Enchant); + float eSkill = actor.getClass().getSkill(actor, ESM::Skill::Enchant); const float result = castCost - (castCost / 100) * (eSkill - 10); return static_cast((result < 1) ? 1 : result); @@ -154,7 +154,7 @@ namespace MWMechanics if (potion.mData.mFlags & ESM::Potion::Autocalc) { float cost = getTotalCost(potion.mEffects, EffectCostMethod::GamePotion); - return std::round(cost); + return static_cast(std::round(cost)); } return potion.mData.mValue; } @@ -166,9 +166,9 @@ namespace MWMechanics throw std::range_error("Index out of range"); ESM::ENAMstruct effect; - effect.mEffectID = ingredient->mData.mEffectID[index]; - effect.mSkill = ingredient->mData.mSkills[index]; - effect.mAttribute = ingredient->mData.mAttributes[index]; + effect.mEffectID = static_cast(ingredient->mData.mEffectID[index]); + effect.mSkill = static_cast(ingredient->mData.mSkills[index]); + effect.mAttribute = static_cast(ingredient->mData.mAttributes[index]); effect.mRange = ESM::RT_Self; effect.mArea = 0; @@ -275,22 +275,22 @@ namespace MWMechanics CreatureStats& stats = actor.getClass().getCreatureStats(actor); if (spell->mData.mType == ESM::Spell::ST_Power) - return stats.getSpells().canUsePower(spell) ? 100 : 0; + return stats.getSpells().canUsePower(spell) ? 100.f : 0.f; if (godmode) - return 100; + return 100.f; if (stats.getMagicEffects().getOrDefault(ESM::MagicEffect::Silence).getMagnitude()) - return 0; + return 0.f; if (spell->mData.mType != ESM::Spell::ST_Spell) - return 100; + return 100.f; if (checkMagicka && calcSpellCost(*spell) > 0 && stats.getMagicka().getCurrent() < calcSpellCost(*spell)) - return 0; + return 0.f; if (spell->mData.mFlags & ESM::Spell::F_Always) - return 100; + return 100.f; float castBonus = -stats.getMagicEffects().getOrDefault(ESM::MagicEffect::Sound).getMagnitude(); float castChance = baseChance + castBonus; diff --git a/apps/openmw/mwmechanics/steering.cpp b/apps/openmw/mwmechanics/steering.cpp index fe7d12e6df..a5a02d3574 100644 --- a/apps/openmw/mwmechanics/steering.cpp +++ b/apps/openmw/mwmechanics/steering.cpp @@ -16,7 +16,8 @@ namespace MWMechanics bool smoothTurn(const MWWorld::Ptr& actor, float targetAngleRadians, int axis, float epsilonRadians) { MWMechanics::Movement& movement = actor.getClass().getMovementSettings(actor); - float diff = Misc::normalizeAngle(targetAngleRadians - actor.getRefData().getPosition().rot[axis]); + float diff + = static_cast(Misc::normalizeAngle(targetAngleRadians - actor.getRefData().getPosition().rot[axis])); float absDiff = std::abs(diff); // The turning animation actually moves you slightly, so the angle will be wrong again. @@ -27,7 +28,7 @@ namespace MWMechanics float limit = getAngularVelocity(actor.getClass().getMaxSpeed(actor)) * MWBase::Environment::get().getFrameDuration(); if (Settings::game().mSmoothMovement) - limit *= std::min(absDiff / osg::PI + 0.1, 0.5); + limit *= std::min(absDiff / osg::PIf + 0.1f, 0.5f); if (absDiff > limit) diff = osg::sign(diff) * limit; diff --git a/apps/openmw/mwmechanics/weaponpriority.cpp b/apps/openmw/mwmechanics/weaponpriority.cpp index dd83db286f..c44e5f842d 100644 --- a/apps/openmw/mwmechanics/weaponpriority.cpp +++ b/apps/openmw/mwmechanics/weaponpriority.cpp @@ -117,12 +117,12 @@ namespace MWMechanics } } - int value = 50.f; + int value = 50; ESM::RefId skill = item.getClass().getEquipmentSkill(item); if (!skill.empty()) - value = actor.getClass().getSkill(actor, skill); + value = static_cast(actor.getClass().getSkill(actor, skill)); // Prefer hand-to-hand if our skill is 0 (presumably due to magic) - if (value <= 0.f) + if (value <= 0) return 0.f; // Note that a creature with a dagger and 0 Stealth will forgo the weapon despite using Combat for hit chance. // The same creature will use a sword provided its Combat stat isn't 0. We're using the "skill" value here to diff --git a/apps/openmw/mwphysics/actor.cpp b/apps/openmw/mwphysics/actor.cpp index e1efe6d242..4e6fe13d64 100644 --- a/apps/openmw/mwphysics/actor.cpp +++ b/apps/openmw/mwphysics/actor.cpp @@ -50,9 +50,9 @@ namespace MWPhysics btVector3 max; shape->mCollisionShape->getAabb(transform, min, max); - mOriginalHalfExtents.x() = (max[0] - min[0]) / 2.f; - mOriginalHalfExtents.y() = (max[1] - min[1]) / 2.f; - mOriginalHalfExtents.z() = (max[2] - min[2]) / 2.f; + mOriginalHalfExtents.x() = static_cast((max[0] - min[0]) / 2.f); + mOriginalHalfExtents.y() = static_cast((max[1] - min[1]) / 2.f); + mOriginalHalfExtents.z() = static_cast((max[2] - min[2]) / 2.f); mMeshTranslation = osg::Vec3f(0.f, 0.f, mOriginalHalfExtents.z()); } diff --git a/apps/openmw/mwphysics/mtphysics.cpp b/apps/openmw/mwphysics/mtphysics.cpp index aafefe7019..310061cfd7 100644 --- a/apps/openmw/mwphysics/mtphysics.cpp +++ b/apps/openmw/mwphysics/mtphysics.cpp @@ -458,10 +458,10 @@ namespace MWPhysics thread.join(); } - std::tuple PhysicsTaskScheduler::calculateStepConfig(float timeAccum) const + std::tuple PhysicsTaskScheduler::calculateStepConfig(float timeAccum) const { - int maxAllowedSteps = 2; - int numSteps = timeAccum / mDefaultPhysicsDt; + unsigned maxAllowedSteps = 2; + unsigned numSteps = static_cast(timeAccum / mDefaultPhysicsDt); // adjust maximum step count based on whether we're likely physics bottlenecked or not // if maxAllowedSteps ends up higher than numSteps, we will not invoke delta time @@ -478,13 +478,13 @@ namespace MWPhysics // ensure sane minimum value budgetMeasurement = std::max(0.00001f, budgetMeasurement); // we're spending almost or more than realtime per physics frame; limit to a single step - if (budgetMeasurement > 0.95) + if (budgetMeasurement > 0.95f) maxAllowedSteps = 1; // physics is fairly cheap; limit based on expense - if (budgetMeasurement < 0.5) - maxAllowedSteps = std::ceil(1.0 / budgetMeasurement); + if (budgetMeasurement < 0.5f) + maxAllowedSteps = static_cast(std::ceil(1.f / budgetMeasurement)); // limit to a reasonable amount - maxAllowedSteps = std::min(10, maxAllowedSteps); + maxAllowedSteps = std::min(10u, maxAllowedSteps); // fall back to delta time for this frame if fixed timestep physics would fall behind float actualDelta = mDefaultPhysicsDt; @@ -523,7 +523,7 @@ namespace MWPhysics MaybeExclusiveLock lock(mSimulationMutex, mLockingPolicy); - double timeStart = mTimer->tick(); + auto timeStart = mTimer->tick(); // start by finishing previous background computation if (mNumThreads != 0) @@ -550,7 +550,7 @@ namespace MWPhysics mPhysicsDt = newDelta; mSimulations = &simulations; mAdvanceSimulation = (mRemainingSteps != 0); - mNumJobs = mSimulations->size(); + mNumJobs = static_cast(mSimulations->size()); mNextLOS.store(0, std::memory_order_relaxed); mNextJob.store(0, std::memory_order_release); @@ -699,7 +699,7 @@ namespace MWPhysics { MaybeSharedLock lock(mLOSCacheMutex, mLockingPolicy); int job = 0; - int numLOS = mLOSCache.size(); + int numLOS = static_cast(mLOSCache.size()); while ((job = mNextLOS.fetch_add(1, std::memory_order_relaxed)) < numLOS) { auto& req = mLOSCache[job]; @@ -764,9 +764,9 @@ namespace MWPhysics bool PhysicsTaskScheduler::hasLineOfSight(const Actor* actor1, const Actor* actor2) { btVector3 pos1 = Misc::Convert::toBullet( - actor1->getCollisionObjectPosition() + osg::Vec3f(0, 0, actor1->getHalfExtents().z() * 0.9)); // eye level + actor1->getCollisionObjectPosition() + osg::Vec3f(0, 0, actor1->getHalfExtents().z() * 0.9f)); // eye level btVector3 pos2 = Misc::Convert::toBullet( - actor2->getCollisionObjectPosition() + osg::Vec3f(0, 0, actor2->getHalfExtents().z() * 0.9)); + actor2->getCollisionObjectPosition() + osg::Vec3f(0, 0, actor2->getHalfExtents().z() * 0.9f)); btCollisionWorld::ClosestRayResultCallback resultCallback(pos1, pos2); resultCallback.m_collisionFilterGroup = CollisionType_AnyPhysical; diff --git a/apps/openmw/mwphysics/mtphysics.hpp b/apps/openmw/mwphysics/mtphysics.hpp index 579211b489..e25ac13ccc 100644 --- a/apps/openmw/mwphysics/mtphysics.hpp +++ b/apps/openmw/mwphysics/mtphysics.hpp @@ -83,7 +83,7 @@ namespace MWPhysics void updateAabbs(); void updatePtrAabb(const std::shared_ptr& ptr); void updateStats(osg::Timer_t frameStart, unsigned int frameNumber, osg::Stats& stats); - std::tuple calculateStepConfig(float timeAccum) const; + std::tuple calculateStepConfig(float timeAccum) const; void afterPreStep(); void afterPostStep(); void afterPostSim(); @@ -111,7 +111,7 @@ namespace MWPhysics LockingPolicy mLockingPolicy; unsigned mNumThreads; int mNumJobs; - int mRemainingSteps; + unsigned mRemainingSteps; int mLOSCacheExpiry; bool mAdvanceSimulation; std::atomic mNextJob; @@ -126,7 +126,7 @@ namespace MWPhysics unsigned int mFrameNumber; const osg::Timer* mTimer; - int mPrevStepCount; + unsigned mPrevStepCount; Misc::BudgetMeasurement mBudget; Misc::BudgetMeasurement mAsyncBudget; unsigned int mBudgetCursor; diff --git a/apps/openmw/mwphysics/physicssystem.cpp b/apps/openmw/mwphysics/physicssystem.cpp index 9620befe6e..3c2238bac3 100644 --- a/apps/openmw/mwphysics/physicssystem.cpp +++ b/apps/openmw/mwphysics/physicssystem.cpp @@ -865,10 +865,10 @@ namespace MWPhysics void PhysicsSystem::reportStats(unsigned int frameNumber, osg::Stats& stats) const { - stats.setAttribute(frameNumber, "Physics Actors", mActors.size()); - stats.setAttribute(frameNumber, "Physics Objects", mObjects.size()); - stats.setAttribute(frameNumber, "Physics Projectiles", mProjectiles.size()); - stats.setAttribute(frameNumber, "Physics HeightFields", mHeightFields.size()); + stats.setAttribute(frameNumber, "Physics Actors", static_cast(mActors.size())); + stats.setAttribute(frameNumber, "Physics Objects", static_cast(mObjects.size())); + stats.setAttribute(frameNumber, "Physics Projectiles", static_cast(mProjectiles.size())); + stats.setAttribute(frameNumber, "Physics HeightFields", static_cast(mHeightFields.size())); } void PhysicsSystem::reportCollision(const btVector3& position, const btVector3& normal) diff --git a/apps/openmw/mwphysics/trace.cpp b/apps/openmw/mwphysics/trace.cpp index 93aa5086ba..6eed92bb95 100644 --- a/apps/openmw/mwphysics/trace.cpp +++ b/apps/openmw/mwphysics/trace.cpp @@ -67,10 +67,10 @@ namespace MWPhysics // Copy the hit data over to our trace results struct: if (traceCallback.hasHit()) { - mFraction = traceCallback.m_closestHitFraction; + mFraction = static_cast(traceCallback.m_closestHitFraction); // ensure fraction is correct (covers intended distance traveled instead of actual distance traveled) if (doingShortTrace && (end - start).length2() > 0.0) - mFraction *= (btend - btstart).length() / (end - start).length(); + mFraction *= static_cast((btend - btstart).length() / (end - start).length()); mPlaneNormal = Misc::Convert::toOsg(traceCallback.m_hitNormalWorld); mEndPos = (end - start) * mFraction + start; mHitPoint = Misc::Convert::toOsg(traceCallback.m_hitPointWorld); @@ -85,7 +85,7 @@ namespace MWPhysics if (newTraceCallback.hasHit()) { - mFraction = newTraceCallback.m_closestHitFraction; + mFraction = static_cast(newTraceCallback.m_closestHitFraction); mPlaneNormal = Misc::Convert::toOsg(newTraceCallback.m_hitNormalWorld); mEndPos = (end - start) * mFraction + start; mHitPoint = Misc::Convert::toOsg(newTraceCallback.m_hitPointWorld); @@ -109,7 +109,7 @@ namespace MWPhysics actor->getCollisionObject(), Misc::Convert::toBullet(start), Misc::Convert::toBullet(end), world, true); if (traceCallback.hasHit()) { - mFraction = traceCallback.m_closestHitFraction; + mFraction = static_cast(traceCallback.m_closestHitFraction); mPlaneNormal = Misc::Convert::toOsg(traceCallback.m_hitNormalWorld); mEndPos = (end - start) * mFraction + start; } diff --git a/apps/openmw/mwrender/animation.cpp b/apps/openmw/mwrender/animation.cpp index 5912895855..0aee682598 100644 --- a/apps/openmw/mwrender/animation.cpp +++ b/apps/openmw/mwrender/animation.cpp @@ -516,7 +516,7 @@ namespace MWRender double duration = newTime - mStartingTime; mStartingTime = newTime; - mParams.mAnimTime->addTime(duration); + mParams.mAnimTime->addTime(static_cast(duration)); if (mParams.mAnimTime->getTime() >= mParams.mMaxControllerLength) { if (mParams.mLoop) @@ -1223,7 +1223,7 @@ namespace MWRender return false; } - bool Animation::getInfo(std::string_view groupname, float* complete, float* speedmult, size_t* loopcount) const + bool Animation::getInfo(std::string_view groupname, float* complete, float* speedmult, uint32_t* loopcount) const { AnimStateMap::const_iterator iter = mStates.find(groupname); if (iter == mStates.end()) diff --git a/apps/openmw/mwrender/animation.hpp b/apps/openmw/mwrender/animation.hpp index 807f785b1b..45b3c75f2a 100644 --- a/apps/openmw/mwrender/animation.hpp +++ b/apps/openmw/mwrender/animation.hpp @@ -411,7 +411,7 @@ namespace MWRender * \return True if the animation is active, false otherwise. */ bool getInfo(std::string_view groupname, float* complete = nullptr, float* speedmult = nullptr, - size_t* loopcount = nullptr) const; + uint32_t* loopcount = nullptr) const; /// Returns the group name of the animation currently active on that bone group. std::string_view getActiveGroup(BoneGroup boneGroup) const; diff --git a/apps/openmw/mwrender/animblendcontroller.cpp b/apps/openmw/mwrender/animblendcontroller.cpp index 3d8b7b59d7..bfd4c0041d 100644 --- a/apps/openmw/mwrender/animblendcontroller.cpp +++ b/apps/openmw/mwrender/animblendcontroller.cpp @@ -279,7 +279,7 @@ namespace MWRender // such as bip01, bip01 spine1 etc. The child bones of these controllers have their own callback wrapper // which will call this instance's applyBoneBlend for each child bone. The order of update is important // as the blending calculations expect the bone's skeleton matrix to be at the sample point - float time = nv->getFrameStamp()->getSimulationTime(); + float time = static_cast(nv->getFrameStamp()->getSimulationTime()); assert(node != nullptr); if (mBlendTrigger) @@ -308,7 +308,7 @@ namespace MWRender auto [translation, rotation, scale] = mKeyframeTrack->getCurrentTransformation(nv); - float time = nv->getFrameStamp()->getSimulationTime(); + float time = static_cast(nv->getFrameStamp()->getSimulationTime()); if (mBlendTrigger) { diff --git a/apps/openmw/mwrender/bulletdebugdraw.cpp b/apps/openmw/mwrender/bulletdebugdraw.cpp index 3e0383b567..e662d0a5f4 100644 --- a/apps/openmw/mwrender/bulletdebugdraw.cpp +++ b/apps/openmw/mwrender/bulletdebugdraw.cpp @@ -68,7 +68,7 @@ namespace MWRender new osg::PolygonMode(osg::PolygonMode::FRONT_AND_BACK, osg::PolygonMode::LINE), osg::StateAttribute::ON); stateSet->setAttributeAndModes(new osg::PolygonOffset( - SceneUtil::AutoDepth::isReversed() ? 1.0 : -1.0, SceneUtil::AutoDepth::isReversed() ? 1.0 : -1.0)); + SceneUtil::AutoDepth::isReversed() ? 1.f : -1.f, SceneUtil::AutoDepth::isReversed() ? 1.f : -1.f)); osg::ref_ptr material = new osg::Material; material->setColorMode(osg::Material::AMBIENT_AND_DIFFUSE); stateSet->setAttribute(material); @@ -118,8 +118,8 @@ namespace MWRender mShapesRoot->removeChildren(0, mShapesRoot->getNumChildren()); mWorld->debugDrawWorld(); showCollisions(); - mLinesDrawArrays->setCount(mLinesVertices->size()); - mTrisDrawArrays->setCount(mTrisVertices->size()); + mLinesDrawArrays->setCount(static_cast(mLinesVertices->size())); + mTrisDrawArrays->setCount(static_cast(mTrisVertices->size())); mLinesVertices->dirty(); mTrisVertices->dirty(); mLinesColors->dirty(); @@ -194,7 +194,8 @@ namespace MWRender void DebugDrawer::drawSphere(btScalar radius, const btTransform& transform, const btVector3& color) { - auto* geom = new osg::ShapeDrawable(new osg::Sphere(Misc::Convert::toOsg(transform.getOrigin()), radius)); + auto* geom = new osg::ShapeDrawable( + new osg::Sphere(Misc::Convert::toOsg(transform.getOrigin()), static_cast(radius))); geom->setColor(osg::Vec4(1, 1, 1, 1)); mShapesRoot->addChild(geom); } diff --git a/apps/openmw/mwrender/camera.cpp b/apps/openmw/mwrender/camera.cpp index 1c163a6701..9a22409158 100644 --- a/apps/openmw/mwrender/camera.cpp +++ b/apps/openmw/mwrender/camera.cpp @@ -179,7 +179,7 @@ namespace MWRender osg::Vec3d focal = mTrackedPosition + focalOffset; focalOffset.z() += 10.f; // Needed to avoid camera clipping through the ceiling because // character's head can be a bit higher than the collision area. - float offsetLen = focalOffset.length(); + double offsetLen = focalOffset.length(); if (offsetLen > 0) { MWPhysics::RayCastingResult result @@ -280,9 +280,9 @@ namespace MWRender osg::Vec2d delta = mFocalPointTargetOffset - mFocalPointCurrentOffset; if (delta.length2() > 0) { - float coef = duration * (1.0 + 5.0 / delta.length()) * mFocalPointTransitionSpeedCoef + double coef = duration * (1.0 + 5.0 / delta.length()) * mFocalPointTransitionSpeedCoef * (1.0f - mPreviousTransitionInfluence); - mFocalPointCurrentOffset += delta * std::min(coef, 1.0f); + mFocalPointCurrentOffset += delta * std::min(coef, 1.0); } else { @@ -315,7 +315,7 @@ namespace MWRender void Camera::setYaw(float angle, bool force) { if (!mLockYaw || force) - mYaw = Misc::normalizeAngle(angle); + mYaw = static_cast(Misc::normalizeAngle(angle)); if (force) mLockYaw = true; } @@ -433,8 +433,9 @@ namespace MWRender return; } - mDeferredRotation.x() = Misc::normalizeAngle(-ptr.getRefData().getPosition().rot[0] - mPitch); - mDeferredRotation.z() = Misc::normalizeAngle(-ptr.getRefData().getPosition().rot[2] - mYaw); + mDeferredRotation.x() + = static_cast(Misc::normalizeAngle(-ptr.getRefData().getPosition().rot[0] - mPitch)); + mDeferredRotation.z() = static_cast(Misc::normalizeAngle(-ptr.getRefData().getPosition().rot[2] - mYaw)); if (!mDeferredRotationAllowed) mDeferredRotationDisabled = true; } diff --git a/apps/openmw/mwrender/characterpreview.cpp b/apps/openmw/mwrender/characterpreview.cpp index 18604e78ca..ef50c1145d 100644 --- a/apps/openmw/mwrender/characterpreview.cpp +++ b/apps/openmw/mwrender/characterpreview.cpp @@ -479,8 +479,8 @@ namespace MWRender { if (!mViewport) return -1; - float projX = (posX / mViewport->width()) * 2 - 1.f; - float projY = (posY / mViewport->height()) * 2 - 1.f; + double projX = (posX / mViewport->width()) * 2 - 1; + double projY = (posY / mViewport->height()) * 2 - 1; // With Intersector::WINDOW, the intersection ratios are slightly inaccurate. Seems to be a // precision issue - compiling with OSG_USE_FLOAT_MATRIX=0, Intersector::WINDOW works ok. // Using Intersector::PROJECTION results in better precision because the start/end points and the model matrices diff --git a/apps/openmw/mwrender/distortion.cpp b/apps/openmw/mwrender/distortion.cpp index 5df2bfb703..3466df8125 100644 --- a/apps/openmw/mwrender/distortion.cpp +++ b/apps/openmw/mwrender/distortion.cpp @@ -10,7 +10,7 @@ namespace MWRender osgUtil::RenderBin* bin, osg::RenderInfo& renderInfo, osgUtil::RenderLeaf*& previous) { osg::State* state = renderInfo.getState(); - size_t frameId = state->getFrameStamp()->getFrameNumber() % 2; + unsigned frameId = state->getFrameStamp()->getFrameNumber() % 2; PostProcessor* postProcessor = dynamic_cast(renderInfo.getCurrentCamera()->getUserData()); diff --git a/apps/openmw/mwrender/groundcover.cpp b/apps/openmw/mwrender/groundcover.cpp index 9fc40f3e19..d7e65a99b5 100644 --- a/apps/openmw/mwrender/groundcover.cpp +++ b/apps/openmw/mwrender/groundcover.cpp @@ -106,7 +106,7 @@ namespace MWRender for (const auto& instanceMatrix : mInstanceMatrices) { osg::Matrix fullMatrix = instanceMatrix * matrix; - osg::Vec3 instanceLookVector(-fullMatrix(0, 2), -fullMatrix(1, 2), -fullMatrix(2, 2)); + osg::Vec3d instanceLookVector(-fullMatrix(0, 2), -fullMatrix(1, 2), -fullMatrix(2, 2)); unsigned int instanceBbCornerFar = (instanceLookVector.x() >= 0 ? 1 : 0) | (instanceLookVector.y() >= 0 ? 2 : 0) | (instanceLookVector.z() >= 0 ? 4 : 0); unsigned int instanceBbCornerNear = (~instanceBbCornerFar) & 7; @@ -146,7 +146,7 @@ namespace MWRender for (const auto& instanceMatrix : mInstanceMatrices) { osg::Matrix fullMatrix = instanceMatrix * matrix; - osg::Vec3 instanceLookVector(-fullMatrix(0, 2), -fullMatrix(1, 2), -fullMatrix(2, 2)); + osg::Vec3d instanceLookVector(-fullMatrix(0, 2), -fullMatrix(1, 2), -fullMatrix(2, 2)); unsigned int instanceBbCornerFar = (instanceLookVector.x() >= 0 ? 1 : 0) | (instanceLookVector.y() >= 0 ? 2 : 0) | (instanceLookVector.z() >= 0 ? 4 : 0); unsigned int instanceBbCornerNear = (~instanceBbCornerFar) & 7; @@ -217,10 +217,10 @@ namespace MWRender { for (unsigned int i = 0; i < geom.getNumPrimitiveSets(); ++i) { - geom.getPrimitiveSet(i)->setNumInstances(mInstances.size()); + geom.getPrimitiveSet(i)->setNumInstances(static_cast(mInstances.size())); } - osg::ref_ptr transforms = new osg::Vec4Array(mInstances.size()); + osg::ref_ptr transforms = new osg::Vec4Array(static_cast(mInstances.size())); osg::BoundingBox box; osg::BoundingBox originalBox = geom.getBoundingBox(); float radius = originalBox.radius(); @@ -238,7 +238,7 @@ namespace MWRender geom.setInitialBound(box); - osg::ref_ptr rotations = new osg::Vec3Array(mInstances.size()); + osg::ref_ptr rotations = new osg::Vec3Array(static_cast(mInstances.size())); for (unsigned int i = 0; i < rotations->getNumElements(); i++) { (*rotations)[i] = mInstances[i].mPos.asRotationVec3(); @@ -368,7 +368,7 @@ namespace MWRender mProgramTemplate->addBindAttribLocation("aRotation", 7); } - Groundcover::~Groundcover() {} + Groundcover::~Groundcover() = default; void Groundcover::collectInstances(InstanceMap& instances, float size, const osg::Vec2f& center) { @@ -379,7 +379,8 @@ namespace MWRender osg::Vec2f maxBound = (center + osg::Vec2f(size / 2.f, size / 2.f)); DensityCalculator calculator(mDensity); ESM::ReadersCache readers; - osg::Vec2i startCell = osg::Vec2i(std::floor(center.x() - size / 2.f), std::floor(center.y() - size / 2.f)); + osg::Vec2i startCell = osg::Vec2i(static_cast(std::floor(center.x() - size / 2.f)), + static_cast(std::floor(center.y() - size / 2.f))); for (int cellX = startCell.x(); cellX < startCell.x() + size; ++cellX) { for (int cellY = startCell.y(); cellY < startCell.y() + size; ++cellY) diff --git a/apps/openmw/mwrender/localmap.cpp b/apps/openmw/mwrender/localmap.cpp index 86999d753c..65c3add82d 100644 --- a/apps/openmw/mwrender/localmap.cpp +++ b/apps/openmw/mwrender/localmap.cpp @@ -40,7 +40,7 @@ namespace return val * val; } - std::pair divideIntoSegments(const osg::BoundingBox& bounds, float mapSize) + std::pair divideIntoSegments(const osg::BoundingBox& bounds, int mapSize) { osg::Vec2f min(bounds.xMin(), bounds.yMin()); osg::Vec2f max(bounds.xMax(), bounds.yMax()); @@ -76,8 +76,8 @@ namespace MWRender LocalMap::LocalMap(osg::Group* root) : mRoot(root) - , mMapResolution( - Settings::map().mLocalMapResolution * MWBase::Environment::get().getWindowManager()->getScalingFactor()) + , mMapResolution(static_cast( + Settings::map().mLocalMapResolution * MWBase::Environment::get().getWindowManager()->getScalingFactor())) , mMapWorldSize(Constants::CellSizeInUnits) , mCellDistance(Constants::CellGridRadius) , mAngle(0.f) @@ -352,7 +352,7 @@ namespace MWRender else if (fog->mBounds.mMinX > mBounds.xMin()) { float diff = fog->mBounds.mMinX - mBounds.xMin(); - xOffset = std::ceil(diff / mMapWorldSize); + xOffset = static_cast(std::ceil(diff / mMapWorldSize)); mBounds.xMin() = fog->mBounds.mMinX - xOffset * mMapWorldSize; } if (fog->mBounds.mMinY < mBounds.yMin()) @@ -362,7 +362,7 @@ namespace MWRender else if (fog->mBounds.mMinY > mBounds.yMin()) { float diff = fog->mBounds.mMinY - mBounds.yMin(); - yOffset = std::ceil(diff / mMapWorldSize); + yOffset = static_cast(std::ceil(diff / mMapWorldSize)); mBounds.yMin() = fog->mBounds.mMinY - yOffset * mMapWorldSize; } if (fog->mBounds.mMaxX > mBounds.xMax()) @@ -388,7 +388,8 @@ namespace MWRender { for (int y = 0; y < segments.second; ++y) { - osg::Vec2f start = min + osg::Vec2f(mMapWorldSize * x, mMapWorldSize * y); + osg::Vec2f start + = min + osg::Vec2f(static_cast(mMapWorldSize * x), static_cast(mMapWorldSize * y)); osg::Vec2f newcenter = start + osg::Vec2f(mMapWorldSize / 2.f, mMapWorldSize / 2.f); osg::Vec2f a = newcenter - mCenter; @@ -535,8 +536,8 @@ namespace MWRender float sqrDist = square((texU + mx * (sFogOfWarResolution - 1)) - u * (sFogOfWarResolution - 1)) + square((texV + my * (sFogOfWarResolution - 1)) - v * (sFogOfWarResolution - 1)); - const std::uint8_t alpha = std::min( - *data >> 24, std::clamp(sqrDist / sqrExploreRadius, 0.f, 1.f) * 255); + const std::uint8_t alpha = std::min(*data >> 24, + static_cast(std::clamp(sqrDist / sqrExploreRadius, 0.f, 1.f) * 255)); std::uint32_t val = static_cast(alpha << 24); if (*data != val) { diff --git a/apps/openmw/mwrender/localmap.hpp b/apps/openmw/mwrender/localmap.hpp index bf7844f2c1..f890733888 100644 --- a/apps/openmw/mwrender/localmap.hpp +++ b/apps/openmw/mwrender/localmap.hpp @@ -144,7 +144,7 @@ namespace MWRender static const int sFogOfWarResolution = 32; // size of a map segment (for exteriors, 1 cell) - float mMapWorldSize; + int mMapWorldSize; int mCellDistance; diff --git a/apps/openmw/mwrender/objectpaging.cpp b/apps/openmw/mwrender/objectpaging.cpp index 9f8b1ed86c..c7c92f61c9 100644 --- a/apps/openmw/mwrender/objectpaging.cpp +++ b/apps/openmw/mwrender/objectpaging.cpp @@ -261,7 +261,7 @@ namespace MWRender for (const osg::Callback* callback = node->getCullCallback(); callback != nullptr; callback = callback->getNestedCallback()) { - if (callback->className() == std::string("BillboardCallback")) + if (callback->className() == std::string_view("BillboardCallback")) { if (mOptimizeBillboards) { @@ -310,8 +310,8 @@ namespace MWRender const osg::Matrix& oldMatrix = matrixTransform->getMatrix(); float mag[3]; // attempt to preserve scale for (int i = 0; i < 3; ++i) - mag[i] = std::sqrt(oldMatrix(0, i) * oldMatrix(0, i) + oldMatrix(1, i) * oldMatrix(1, i) - + oldMatrix(2, i) * oldMatrix(2, i)); + mag[i] = static_cast(std::sqrt(oldMatrix(0, i) * oldMatrix(0, i) + + oldMatrix(1, i) * oldMatrix(1, i) + oldMatrix(2, i) * oldMatrix(2, i))); osg::Matrix newMatrix; worldToLocal.setTrans(0, 0, 0); newMatrix *= worldToLocal; @@ -651,7 +651,8 @@ namespace MWRender osg::ref_ptr ObjectPaging::createChunk(float size, const osg::Vec2f& center, bool activeGrid, const osg::Vec3f& viewPoint, bool compile, unsigned char lod) { - const osg::Vec2i startCell(std::floor(center.x() - size / 2.f), std::floor(center.y() - size / 2.f)); + const osg::Vec2i startCell(static_cast(std::floor(center.x() - size / 2.f)), + static_cast(std::floor(center.y() - size / 2.f))); const MWBase::World& world = *MWBase::Environment::get().getWorld(); const MWWorld::ESMStore& store = world.getStore(); @@ -683,8 +684,10 @@ namespace MWRender const osg::Vec2f minBound = (center - osg::Vec2f(size / 2.f, size / 2.f)); const osg::Vec2f maxBound = (center + osg::Vec2f(size / 2.f, size / 2.f)); - const osg::Vec2i floorMinBound(std::floor(minBound.x()), std::floor(minBound.y())); - const osg::Vec2i ceilMaxBound(std::ceil(maxBound.x()), std::ceil(maxBound.y())); + const osg::Vec2i floorMinBound( + static_cast(std::floor(minBound.x())), static_cast(std::floor(minBound.y()))); + const osg::Vec2i ceilMaxBound( + static_cast(std::ceil(maxBound.x())), static_cast(std::ceil(maxBound.y()))); struct InstanceList { std::vector mInstances; @@ -712,7 +715,7 @@ namespace MWRender { if (size < 1.f) { - const osg::Vec3f cellPos = ref.mPosition / cellSize; + const osg::Vec3f cellPos = ref.mPosition / static_cast(cellSize); if ((minBound.x() > floorMinBound.x() && cellPos.x() < minBound.x()) || (minBound.y() > floorMinBound.y() && cellPos.y() < minBound.y()) || (maxBound.x() < ceilMaxBound.x() && cellPos.x() >= maxBound.x()) @@ -808,7 +811,8 @@ namespace MWRender emplaced.first->second.mInstances.push_back(&ref); } - const osg::Vec3f worldCenter = osg::Vec3f(center.x(), center.y(), 0) * getCellSize(mWorldspace); + const osg::Vec3f worldCenter + = osg::Vec3f(center.x(), center.y(), 0) * static_cast(getCellSize(mWorldspace)); osg::ref_ptr group = new osg::Group; osg::ref_ptr mergeGroup = new osg::Group; osg::ref_ptr templateRefs = new Resource::TemplateMultiRef; @@ -980,8 +984,8 @@ namespace MWRender { osg::Vec2f clampToCell(const osg::Vec3f& cellPos, const osg::Vec2i& cell) { - return osg::Vec2f(std::clamp(cellPos.x(), cell.x(), cell.x() + 1), - std::clamp(cellPos.y(), cell.y(), cell.y() + 1)); + return osg::Vec2f(std::clamp(cellPos.x(), static_cast(cell.x()), cell.x() + 1.f), + std::clamp(cellPos.y(), static_cast(cell.y()), cell.y() + 1.f)); } class CollectIntersecting @@ -990,7 +994,7 @@ namespace MWRender explicit CollectIntersecting( bool activeGridOnly, const osg::Vec3f& position, const osg::Vec2i& cell, ESM::RefId worldspace) : mActiveGridOnly(activeGridOnly) - , mPosition(clampToCell(position / getCellSize(worldspace), cell)) + , mPosition(clampToCell(position / static_cast(getCellSize(worldspace)), cell)) { } diff --git a/apps/openmw/mwrender/pingpongcull.cpp b/apps/openmw/mwrender/pingpongcull.cpp index 497c6c734a..03653f25f8 100644 --- a/apps/openmw/mwrender/pingpongcull.cpp +++ b/apps/openmw/mwrender/pingpongcull.cpp @@ -34,8 +34,8 @@ namespace MWRender void PingPongCull::operator()(osg::Node* node, osgUtil::CullVisitor* cv) { osgUtil::RenderStage* renderStage = cv->getCurrentRenderStage(); - size_t frame = cv->getTraversalNumber(); - size_t frameId = frame % 2; + unsigned frame = cv->getTraversalNumber(); + unsigned frameId = frame % 2; if (Stereo::getStereo()) { diff --git a/apps/openmw/mwrender/postprocessor.cpp b/apps/openmw/mwrender/postprocessor.cpp index a06b9a83de..ce7c2b7765 100644 --- a/apps/openmw/mwrender/postprocessor.cpp +++ b/apps/openmw/mwrender/postprocessor.cpp @@ -135,7 +135,7 @@ namespace MWRender mHUDCamera->setReferenceFrame(osg::Camera::ABSOLUTE_RF); mHUDCamera->setRenderOrder(osg::Camera::POST_RENDER); - mHUDCamera->setClearColor(osg::Vec4(0.45, 0.45, 0.14, 1.0)); + mHUDCamera->setClearColor(osg::Vec4(0.45f, 0.45f, 0.14f, 1.f)); mHUDCamera->setClearMask(0); mHUDCamera->setProjectionMatrix(osg::Matrix::ortho2D(0, 1, 0, 1)); mHUDCamera->setAllowEventFocus(false); @@ -205,7 +205,7 @@ namespace MWRender else Log(Debug::Error) << "'glDisablei' unsupported, pass normals will not be available to shaders."; - mGLSLVersion = ext->glslLanguageVersion * 100; + mGLSLVersion = static_cast(ext->glslLanguageVersion * 100); mUBO = ext->isUniformBufferObjectSupported && mGLSLVersion >= 330; mStateUpdater = new Fx::StateUpdater(mUBO); @@ -275,7 +275,7 @@ namespace MWRender void PostProcessor::traverse(osg::NodeVisitor& nv) { - size_t frameId = nv.getTraversalNumber() % 2; + unsigned frameId = nv.getTraversalNumber() % 2; if (nv.getVisitorType() == osg::NodeVisitor::CULL_VISITOR) cull(frameId, static_cast(&nv)); @@ -285,7 +285,7 @@ namespace MWRender osg::Group::traverse(nv); } - void PostProcessor::cull(size_t frameId, osgUtil::CullVisitor* cv) + void PostProcessor::cull(unsigned frameId, osgUtil::CullVisitor* cv) { if (const auto& fbo = getFbo(FBO_Intercept, frameId)) { @@ -312,7 +312,8 @@ namespace MWRender size_t frame = cv->getTraversalNumber(); - mStateUpdater->setResolution(osg::Vec2f(cv->getViewport()->width(), cv->getViewport()->height())); + mStateUpdater->setResolution(osg::Vec2f( + static_cast(cv->getViewport()->width()), static_cast(cv->getViewport()->height()))); // per-frame data if (frame != mLastFrameNumber) @@ -467,8 +468,8 @@ namespace MWRender textures[Tex_Distortion]->setSourceFormat(GL_RGB); textures[Tex_Distortion]->setInternalFormat(GL_RGB); - Stereo::setMultiviewCompatibleTextureSize( - textures[Tex_Distortion], width * DistortionRatio, height * DistortionRatio); + Stereo::setMultiviewCompatibleTextureSize(textures[Tex_Distortion], static_cast(width * DistortionRatio), + static_cast(height * DistortionRatio)); textures[Tex_Distortion]->dirtyTextureObject(); auto setupDepth = [](osg::Texture* tex) { @@ -632,7 +633,7 @@ namespace MWRender if (auto type = uniform->getType()) uniform->setUniform(node.mRootStateSet->getOrCreateUniform( - uniform->mName.c_str(), *type, uniform->getNumElements())); + uniform->mName, *type, static_cast(uniform->getNumElements()))); } for (const auto& pass : technique->getPasses()) @@ -724,7 +725,7 @@ namespace MWRender disableTechnique(technique, false); - int pos = std::min(location.value_or(mTechniques.size()) + mInternalTechniques.size(), mTechniques.size()); + size_t pos = std::min(location.value_or(mTechniques.size()) + mInternalTechniques.size(), mTechniques.size()); mTechniques.insert(mTechniques.begin() + pos, technique); dirtyTechniques(Settings::ShaderManager::get().getMode() == Settings::ShaderManager::Mode::Debug); diff --git a/apps/openmw/mwrender/postprocessor.hpp b/apps/openmw/mwrender/postprocessor.hpp index f81a50e9d6..962ec920ff 100644 --- a/apps/openmw/mwrender/postprocessor.hpp +++ b/apps/openmw/mwrender/postprocessor.hpp @@ -220,7 +220,7 @@ namespace MWRender void updateLiveReload(); - void cull(size_t frameId, osgUtil::CullVisitor* cv); + void cull(unsigned frameId, osgUtil::CullVisitor* cv); osg::ref_ptr mRootNode; osg::ref_ptr mHUDCamera; @@ -241,7 +241,7 @@ namespace MWRender size_t mDirtyFrameId = 0; size_t mLastFrameNumber = 0; - float mLastSimulationTime = 0.f; + double mLastSimulationTime = 0.0; bool mDirty = false; bool mReload = true; diff --git a/apps/openmw/mwrender/renderingmanager.cpp b/apps/openmw/mwrender/renderingmanager.cpp index 67d1cfb587..8b62daba4a 100644 --- a/apps/openmw/mwrender/renderingmanager.cpp +++ b/apps/openmw/mwrender/renderingmanager.cpp @@ -711,9 +711,9 @@ namespace MWRender if (needsAdjusting) { - constexpr float pR = 0.2126; - constexpr float pG = 0.7152; - constexpr float pB = 0.0722; + constexpr float pR = 0.2126f; + constexpr float pG = 0.7152f; + constexpr float pB = 0.0722f; // we already work in linear RGB so no conversions are needed for the luminosity function float relativeLuminance = pR * ambient.r() + pG * ambient.g() + pB * ambient.b(); @@ -1053,14 +1053,13 @@ namespace MWRender PtrHolder* ptrHolder = nullptr; std::vector refnumMarkers; bool hitNonObjectWorld = false; - for (osg::NodePath::const_iterator it = intersection.nodePath.begin(); it != intersection.nodePath.end(); - ++it) + for (osg::Node* node : intersection.nodePath) { - const auto& nodeMask = (*it)->getNodeMask(); + const auto& nodeMask = node->getNodeMask(); if (!hitNonObjectWorld) hitNonObjectWorld = nodeMask & nonObjectWorldMask; - osg::UserDataContainer* userDataContainer = (*it)->getUserDataContainer(); + osg::UserDataContainer* userDataContainer = node->getUserDataContainer(); if (!userDataContainer) continue; for (unsigned int i = 0; i < userDataContainer->getNumUserObjects(); ++i) @@ -1110,7 +1109,7 @@ namespace MWRender result.mHit = true; result.mHitPointWorld = intersection.getWorldIntersectPoint(); result.mHitNormalWorld = intersection.getWorldIntersectNormal(); - result.mRatio = intersection.ratio; + result.mRatio = static_cast(intersection.ratio); } }; @@ -1362,10 +1361,10 @@ namespace MWRender if (mViewDistance < mNearClip) throw std::runtime_error("Viewing distance is less than near clip"); - const double width = Settings::video().mResolutionX; - const double height = Settings::video().mResolutionY; + const int width = Settings::video().mResolutionX; + const int height = Settings::video().mResolutionY; - double aspect = (height == 0.0) ? 1.0 : width / height; + double aspect = (height == 0) ? 1.0 : static_cast(width) / height; float fov = mFieldOfView; if (mFieldOfViewOverridden) fov = mFieldOfViewOverride; @@ -1385,12 +1384,12 @@ namespace MWRender if (Stereo::getStereo()) { auto res = Stereo::Manager::instance().eyeResolution(); - mSharedUniformStateUpdater->setScreenRes(res.x(), res.y()); + setScreenRes(res.x(), res.y()); Stereo::Manager::instance().setMasterProjectionMatrix(mPerViewUniformStateUpdater->getProjectionMatrix()); } else { - mSharedUniformStateUpdater->setScreenRes(width, height); + setScreenRes(width, height); } // Since our fog is not radial yet, we should take FOV in account, otherwise terrain near viewing distance may @@ -1407,7 +1406,7 @@ namespace MWRender void RenderingManager::setScreenRes(int width, int height) { - mSharedUniformStateUpdater->setScreenRes(width, height); + mSharedUniformStateUpdater->setScreenRes(static_cast(width), static_cast(height)); } void RenderingManager::updateTextureFiltering() @@ -1415,7 +1414,8 @@ namespace MWRender mViewer->stopThreading(); mResourceSystem->getSceneManager()->setFilterSettings(Settings::general().mTextureMagFilter, - Settings::general().mTextureMinFilter, Settings::general().mTextureMipmap, Settings::general().mAnisotropy); + Settings::general().mTextureMinFilter, Settings::general().mTextureMipmap, + static_cast(Settings::general().mAnisotropy)); mTerrain->updateTextureFiltering(); mWater->processChangedSettings({}); @@ -1428,7 +1428,7 @@ namespace MWRender osg::Vec4f color = mAmbientColor; if (mNightEyeFactor > 0.f) - color += osg::Vec4f(0.7, 0.7, 0.7, 0.0) * mNightEyeFactor; + color += osg::Vec4f(0.7f, 0.7f, 0.7f, 0.0f) * mNightEyeFactor; mPostProcessor->getStateUpdater()->setAmbientColor(color); mStateUpdater->setAmbientColor(color); @@ -1456,7 +1456,7 @@ namespace MWRender { const int compMapResolution = Settings::terrain().mCompositeMapResolution; const int compMapPower = Settings::terrain().mCompositeMapLevel; - const float compMapLevel = std::pow(2, compMapPower); + const float compMapLevel = static_cast(std::pow(2, compMapPower)); const int vertexLodMod = Settings::terrain().mVertexLodMod; const float maxCompGeometrySize = Settings::terrain().mMaxCompositeGeometrySize; const bool debugChunks = Settings::terrain().mDebugChunks; diff --git a/apps/openmw/mwrender/ripples.cpp b/apps/openmw/mwrender/ripples.cpp index b19863d695..5b468c7cdc 100644 --- a/apps/openmw/mwrender/ripples.cpp +++ b/apps/openmw/mwrender/ripples.cpp @@ -43,7 +43,7 @@ namespace MWRender // we can not trust Apple :) mUseCompute = false; #else - constexpr float minimumGLVersionRequiredForCompute = 4.4; + constexpr float minimumGLVersionRequiredForCompute = 4.4f; osg::GLExtensions& exts = SceneUtil::getGLExtensions(); mUseCompute = exts.glVersion >= minimumGLVersionRequiredForCompute && exts.glslLanguageVersion >= minimumGLVersionRequiredForCompute; @@ -183,7 +183,7 @@ namespace MWRender - osg::Vec3f(mCurrentPlayerPos.x() * sWorldScaleFactor, mCurrentPlayerPos.y() * sWorldScaleFactor, 0.0) + osg::Vec3f(sRTTSize * sWorldScaleFactor / 2, sRTTSize * sWorldScaleFactor / 2, 0.0); pos /= sWorldScaleFactor; - positions->setElement(i, pos); + positions->setElement(static_cast(i), pos); } positions->dirty(); @@ -217,7 +217,7 @@ namespace MWRender } osg::GLExtensions& ext = *state.get(); - const std::size_t contextID = state.getContextID(); + const unsigned contextID = state.getContextID(); const auto bindImage = [&](osg::Texture2D* texture, GLuint index, GLenum access) { osg::Texture::TextureObject* to = texture->getTextureObject(contextID); diff --git a/apps/openmw/mwrender/ripplesimulation.cpp b/apps/openmw/mwrender/ripplesimulation.cpp index 88a620efd0..232dd99f6b 100644 --- a/apps/openmw/mwrender/ripplesimulation.cpp +++ b/apps/openmw/mwrender/ripplesimulation.cpp @@ -64,8 +64,8 @@ namespace stateset->setAttributeAndModes(depth, osg::StateAttribute::ON); osg::ref_ptr polygonOffset(new osg::PolygonOffset); - polygonOffset->setUnits(SceneUtil::AutoDepth::isReversed() ? 1 : -1); - polygonOffset->setFactor(SceneUtil::AutoDepth::isReversed() ? 1 : -1); + polygonOffset->setUnits(SceneUtil::AutoDepth::isReversed() ? 1.f : -1.f); + polygonOffset->setFactor(SceneUtil::AutoDepth::isReversed() ? 1.f : -1.f); stateset->setAttributeAndModes(polygonOffset, osg::StateAttribute::ON); stateset->setRenderingHint(osg::StateSet::TRANSPARENT_BIN); @@ -84,13 +84,13 @@ namespace int findOldestParticleAlive(const osgParticle::ParticleSystem* partsys) { int oldest = -1; - float oldestAge = 0.f; + double oldestAge = 0.f; for (int i = 0; i < partsys->numParticles(); ++i) { const osgParticle::Particle* particle = partsys->getParticle(i); if (!particle->isAlive()) continue; - const float age = particle->getAge(); + const double age = particle->getAge(); if (oldest == -1 || age > oldestAge) { oldest = i; @@ -116,7 +116,7 @@ namespace MWRender osgParticle::Particle& particleTemplate = mParticleSystem->getDefaultParticleTemplate(); particleTemplate.setSizeRange(osgParticle::rangef(15, 180)); - particleTemplate.setColorRange(osgParticle::rangev4(osg::Vec4f(1, 1, 1, 0.7), osg::Vec4f(1, 1, 1, 0.7))); + particleTemplate.setColorRange(osgParticle::rangev4(osg::Vec4f(1, 1, 1, 0.7f), osg::Vec4f(1, 1, 1, 0.7f))); particleTemplate.setAlphaRange(osgParticle::rangef(1.f, 0.f)); particleTemplate.setAngularVelocity(osg::Vec3f(0, 0, Fallback::Map::getFloat("Water_RippleRotSpeed"))); particleTemplate.setLifeTime(Fallback::Map::getFloat("Water_RippleLifetime")); @@ -169,7 +169,7 @@ namespace MWRender { // Ripple simulation needs to continously apply impulses to keep simulation alive. // Adding a timer delay will introduce many smaller ripples around actor instead of a smooth wake - currentPos.z() = mParticleNode->getPosition().z(); + currentPos.z() = static_cast(mParticleNode->getPosition().z()); emitRipple(currentPos); } else if (emitter.mTimer <= 0.f || (currentPos - emitter.mLastEmitPosition).length() > 10) @@ -177,7 +177,7 @@ namespace MWRender emitter.mLastEmitPosition = currentPos; emitter.mTimer = 1.5f; - currentPos.z() = mParticleNode->getPosition().z(); + currentPos.z() = static_cast(mParticleNode->getPosition().z()); emitRipple(currentPos); } @@ -258,7 +258,7 @@ namespace MWRender } osgParticle::Particle* p = mParticleSystem->createParticle(nullptr); p->setPosition(osg::Vec3f(pos.x(), pos.y(), 0.f)); - p->setAngle(osg::Vec3f(0, 0, Misc::Rng::rollProbability() * osg::PI * 2 - osg::PI)); + p->setAngle(osg::Vec3f(0, 0, Misc::Rng::rollProbability() * osg::PIf * 2 - osg::PIf)); } } } diff --git a/apps/openmw/mwrender/screenshotmanager.cpp b/apps/openmw/mwrender/screenshotmanager.cpp index 2c86a70f23..d55daa09b8 100644 --- a/apps/openmw/mwrender/screenshotmanager.cpp +++ b/apps/openmw/mwrender/screenshotmanager.cpp @@ -65,15 +65,15 @@ namespace MWRender } void drawImplementation(osg::RenderInfo& renderInfo, const osg::Drawable* /*drawable*/) const override { - int screenW = renderInfo.getCurrentCamera()->getViewport()->width(); - int screenH = renderInfo.getCurrentCamera()->getViewport()->height(); + int screenW = static_cast(renderInfo.getCurrentCamera()->getViewport()->width()); + int screenH = static_cast(renderInfo.getCurrentCamera()->getViewport()->height()); if (Stereo::getStereo()) { auto eyeRes = Stereo::Manager::instance().eyeResolution(); screenW = eyeRes.x(); screenH = eyeRes.y(); } - double imageaspect = (double)mWidth / (double)mHeight; + double imageaspect = double(mWidth) / double(mHeight); int leftPadding = std::max(0, static_cast(screenW - screenH * imageaspect) / 2); int topPadding = std::max(0, static_cast(screenH - screenW / imageaspect) / 2); int width = screenW - leftPadding * 2; diff --git a/apps/openmw/mwrender/sky.cpp b/apps/openmw/mwrender/sky.cpp index 244e1035ed..7e485862a9 100644 --- a/apps/openmw/mwrender/sky.cpp +++ b/apps/openmw/mwrender/sky.cpp @@ -391,7 +391,7 @@ namespace MWRender osg::Vec3 rainRange = osg::Vec3(mRainDiameter, mRainDiameter, (mRainMinHeight + mRainMaxHeight) / 2.f); mRainParticleSystem->setParticleAlignment(osgParticle::ParticleSystem::FIXED); - mRainParticleSystem->setAlignVectorX(osg::Vec3f(0.1, 0, 0)); + mRainParticleSystem->setAlignVectorX(osg::Vec3f(0.1f, 0, 0)); mRainParticleSystem->setAlignVectorY(osg::Vec3f(0, 0, 1)); osg::ref_ptr stateset = mRainParticleSystem->getOrCreateStateSet(); diff --git a/apps/openmw/mwrender/skyutil.cpp b/apps/openmw/mwrender/skyutil.cpp index dacf628a2c..8523499a83 100644 --- a/apps/openmw/mwrender/skyutil.cpp +++ b/apps/openmw/mwrender/skyutil.cpp @@ -57,10 +57,10 @@ namespace osg::ref_ptr geom = new osg::Geometry; osg::ref_ptr verts = new osg::Vec3Array; - verts->push_back(osg::Vec3f(-0.5 * scale, -0.5 * scale, 0)); - verts->push_back(osg::Vec3f(-0.5 * scale, 0.5 * scale, 0)); - verts->push_back(osg::Vec3f(0.5 * scale, 0.5 * scale, 0)); - verts->push_back(osg::Vec3f(0.5 * scale, -0.5 * scale, 0)); + verts->push_back(osg::Vec3f(-0.5f * scale, -0.5f * scale, 0.f)); + verts->push_back(osg::Vec3f(-0.5f * scale, 0.5f * scale, 0.f)); + verts->push_back(osg::Vec3f(0.5f * scale, 0.5f * scale, 0.f)); + verts->push_back(osg::Vec3f(0.5f * scale, -0.5f * scale, 0.f)); geom->setVertexArray(verts); @@ -179,7 +179,7 @@ namespace MWRender if (visibleRatio > 0.f) { - const float fadeThreshold = 0.1; + const float fadeThreshold = 0.1f; if (visibleRatio < fadeThreshold) { float fade = 1.f - (fadeThreshold - visibleRatio) / fadeThreshold; @@ -190,7 +190,7 @@ namespace MWRender } else if (visibleRatio < 1.f) { - const float threshold = 0.6; + const float threshold = 0.6f; visibleRatio = visibleRatio * (1.f - threshold) + threshold; } } @@ -304,8 +304,8 @@ namespace MWRender forward.normalize(); sun.normalize(); - float angleRadians = std::acos(forward * sun); - return angleRadians; + double angleRadians = std::acos(forward * sun); + return static_cast(angleRadians); } osg::ref_ptr mSunTransform; @@ -787,7 +787,7 @@ namespace MWRender if (!sceneManager.getForceShaders()) { osg::ref_ptr alphaFunc = new osg::AlphaFunc; - alphaFunc->setFunction(osg::AlphaFunc::GREATER, 0.8); + alphaFunc->setFunction(osg::AlphaFunc::GREATER, 0.8f); stateset->setAttributeAndModes(alphaFunc); } stateset->setTextureAttributeAndModes(0, sunTex); @@ -1146,7 +1146,7 @@ namespace MWRender void RainShooter::shoot(osgParticle::Particle* particle) const { particle->setVelocity(mVelocity); - particle->setAngle(osg::Vec3f(-mAngle, 0, (Misc::Rng::rollProbability() * 2 - 1) * osg::PI)); + particle->setAngle(osg::Vec3f(-mAngle, 0, (Misc::Rng::rollProbability() * 2 - 1) * osg::PIf)); } void RainShooter::setVelocity(const osg::Vec3f& velocity) @@ -1195,7 +1195,7 @@ namespace MWRender if (i >= 49 && i <= 64) alpha = 0.f; // bottom-most row else if (i >= 33 && i <= 48) - alpha = 0.25098; // second row + alpha = 0.25098f; // second row else alpha = 1.f; break; diff --git a/apps/openmw/mwrender/water.cpp b/apps/openmw/mwrender/water.cpp index 81688a3444..e6828107a7 100644 --- a/apps/openmw/mwrender/water.cpp +++ b/apps/openmw/mwrender/water.cpp @@ -114,10 +114,11 @@ namespace MWRender } // move the plane back along its normal a little bit to prevent bleeding at the water shore - float fov = Settings::camera().mFieldOfView; - const float clipFudgeMin = 2.5; // minimum offset of clip plane - const float clipFudgeScale = -15000.0; - float clipFudge = abs(abs((*mCullPlane)[3]) - eyePoint.z()) * fov / clipFudgeScale - clipFudgeMin; + const float fov = Settings::camera().mFieldOfView; + constexpr double clipFudgeMin = 2.5; // minimum offset of clip plane + constexpr double clipFudgeScale = -15000.0; + double clipFudge + = std::abs(std::abs((*mCullPlane)[3]) - eyePoint.z()) * fov / clipFudgeScale - clipFudgeMin; modelViewMatrix->preMultTranslate(mCullPlane->getNormal() * clipFudge); cv->pushModelViewMatrix(modelViewMatrix, osg::Transform::RELATIVE_RF); @@ -188,7 +189,7 @@ namespace MWRender public: void operator()(osg::Node* node, osgUtil::CullVisitor* cv) { - const float fudge = 0.2; + const float fudge = 0.2f; if (std::abs(cv->getEyeLocal().z()) < fudge) { float diff = fudge - cv->getEyeLocal().z(); @@ -422,7 +423,7 @@ namespace MWRender void drawImplementation(osg::RenderInfo& renderInfo, const osg::Drawable* drawable) const override { static bool supported = osg::isGLExtensionOrVersionSupported( - renderInfo.getState()->getContextID(), "GL_ARB_depth_clamp", 3.3); + renderInfo.getState()->getContextID(), "GL_ARB_depth_clamp", 3.3f); if (!supported) { drawable->drawImplementation(renderInfo); diff --git a/apps/openmw/mwscript/aiextensions.cpp b/apps/openmw/mwscript/aiextensions.cpp index e5aa3b1f91..55717a4a5d 100644 --- a/apps/openmw/mwscript/aiextensions.cpp +++ b/apps/openmw/mwscript/aiextensions.cpp @@ -226,7 +226,7 @@ namespace MWScript { if (!repeat) repeat = true; - Interpreter::Type_Integer idleValue = std::clamp(runtime[0].mInteger, 0, 255); + auto idleValue = static_cast(std::clamp(runtime[0].mInteger, 0, 255)); idleList.push_back(idleValue); runtime.pop(); --arg0; diff --git a/apps/openmw/mwscript/globalscripts.cpp b/apps/openmw/mwscript/globalscripts.cpp index c20e2fe255..8e4e7c05be 100644 --- a/apps/openmw/mwscript/globalscripts.cpp +++ b/apps/openmw/mwscript/globalscripts.cpp @@ -217,7 +217,7 @@ namespace MWScript } } - int GlobalScripts::countSavedGameRecords() const + size_t GlobalScripts::countSavedGameRecords() const { return mScripts.size(); } diff --git a/apps/openmw/mwscript/globalscripts.hpp b/apps/openmw/mwscript/globalscripts.hpp index 47c3f1ef6c..7013beddbe 100644 --- a/apps/openmw/mwscript/globalscripts.hpp +++ b/apps/openmw/mwscript/globalscripts.hpp @@ -76,7 +76,7 @@ namespace MWScript void addStartup(); ///< Add startup script - int countSavedGameRecords() const; + size_t countSavedGameRecords() const; void write(ESM::ESMWriter& writer, Loading::Listener& progress) const; diff --git a/apps/openmw/mwscript/interpretercontext.cpp b/apps/openmw/mwscript/interpretercontext.cpp index 4c890db12b..ec4018d94f 100644 --- a/apps/openmw/mwscript/interpretercontext.cpp +++ b/apps/openmw/mwscript/interpretercontext.cpp @@ -171,7 +171,7 @@ namespace MWScript if (!mLocals) throw std::runtime_error("local variables not available in this context"); - mLocals->mShorts.at(index) = value; + mLocals->mShorts.at(index) = static_cast(value); } void InterpreterContext::setLocalLong(int index, int value) @@ -483,7 +483,7 @@ namespace MWScript { Locals& locals = getMemberLocals(global, id); - locals.mShorts[findLocalVariableIndex(id, name, 's')] = value; + locals.mShorts[findLocalVariableIndex(id, name, 's')] = static_cast(value); } void InterpreterContext::setMemberLong(ESM::RefId id, std::string_view name, int value, bool global) diff --git a/apps/openmw/mwscript/locals.cpp b/apps/openmw/mwscript/locals.cpp index 3bd4e82059..9e072e79bb 100644 --- a/apps/openmw/mwscript/locals.cpp +++ b/apps/openmw/mwscript/locals.cpp @@ -187,29 +187,28 @@ namespace MWScript const Compiler::Locals& declarations = MWBase::Environment::get().getScriptManager()->getLocals(script); int index = 0, numshorts = 0, numlongs = 0; - for (unsigned int v = 0; v < locals.mVariables.size(); ++v) + for (const auto& [_, value] : locals.mVariables) { - ESM::VarType type = locals.mVariables[v].second.getType(); + ESM::VarType type = value.getType(); if (type == ESM::VT_Short) ++numshorts; else if (type == ESM::VT_Int) ++numlongs; } - for (std::vector>::const_iterator iter = locals.mVariables.begin(); - iter != locals.mVariables.end(); ++iter, ++index) + for (const auto& [name, value] : locals.mVariables) { - if (iter->first.empty()) + if (name.empty()) { // no variable names available (this will happen for legacy, i.e. ESS-imported savegames only) try { if (index >= numshorts + numlongs) - mFloats.at(index - (numshorts + numlongs)) = iter->second.getFloat(); + mFloats.at(index - (numshorts + numlongs)) = value.getFloat(); else if (index >= numshorts) - mLongs.at(index - numshorts) = iter->second.getInteger(); + mLongs.at(index - numshorts) = value.getInteger(); else - mShorts.at(index) = iter->second.getInteger(); + mShorts.at(index) = static_cast(value.getInteger()); } catch (std::exception& e) { @@ -220,8 +219,8 @@ namespace MWScript } else { - char type = declarations.getType(iter->first); - int index2 = declarations.getIndex(iter->first); + char type = declarations.getType(name); + int index2 = declarations.getIndex(name); // silently ignore locals that don't exist anymore if (type == ' ' || index2 == -1) @@ -232,13 +231,13 @@ namespace MWScript switch (type) { case 's': - mShorts.at(index2) = iter->second.getInteger(); + mShorts.at(index2) = static_cast(value.getInteger()); break; case 'l': - mLongs.at(index2) = iter->second.getInteger(); + mLongs.at(index2) = value.getInteger(); break; case 'f': - mFloats.at(index2) = iter->second.getFloat(); + mFloats.at(index2) = value.getFloat(); break; } } diff --git a/apps/openmw/mwscript/miscextensions.cpp b/apps/openmw/mwscript/miscextensions.cpp index 3880f8e640..cbc76e8743 100644 --- a/apps/openmw/mwscript/miscextensions.cpp +++ b/apps/openmw/mwscript/miscextensions.cpp @@ -95,7 +95,7 @@ namespace if (stateset) { const osg::StateSet::TextureAttributeList& texAttributes = stateset->getTextureAttributeList(); - for (size_t i = 0; i < texAttributes.size(); i++) + for (unsigned i = 0; i < static_cast(texAttributes.size()); i++) { const osg::StateAttribute* attr = stateset->getTextureAttribute(i, osg::StateAttribute::TEXTURE); if (!attr) @@ -115,7 +115,7 @@ namespace } }; - void addToLevList(ESM::LevelledListBase* list, const ESM::RefId& itemId, int level) + void addToLevList(ESM::LevelledListBase* list, const ESM::RefId& itemId, uint16_t level) { for (auto& levelItem : list->mList) { @@ -1578,7 +1578,7 @@ namespace MWScript ESM::CreatureLevList listCopy = *MWBase::Environment::get().getESMStore()->get().find(levId); - addToLevList(&listCopy, creatureId, level); + addToLevList(&listCopy, creatureId, static_cast(level)); MWBase::Environment::get().getESMStore()->overrideRecord(listCopy); } }; @@ -1616,7 +1616,7 @@ namespace MWScript ESM::ItemLevList listCopy = *MWBase::Environment::get().getESMStore()->get().find(levId); - addToLevList(&listCopy, itemId, level); + addToLevList(&listCopy, itemId, static_cast(level)); MWBase::Environment::get().getESMStore()->overrideRecord(listCopy); } }; diff --git a/apps/openmw/mwscript/skyextensions.cpp b/apps/openmw/mwscript/skyextensions.cpp index b354bb5ce2..35faf6cc99 100644 --- a/apps/openmw/mwscript/skyextensions.cpp +++ b/apps/openmw/mwscript/skyextensions.cpp @@ -106,7 +106,7 @@ namespace MWScript chances.reserve(10); while (arg0 > 0) { - chances.push_back(std::clamp(runtime[0].mInteger, 0, 100)); + chances.push_back(static_cast(std::clamp(runtime[0].mInteger, 0, 100))); runtime.pop(); arg0--; } diff --git a/apps/openmw/mwsound/ffmpegdecoder.cpp b/apps/openmw/mwsound/ffmpegdecoder.cpp index df0f42bd7d..d780db8f07 100644 --- a/apps/openmw/mwsound/ffmpegdecoder.cpp +++ b/apps/openmw/mwsound/ffmpegdecoder.cpp @@ -8,8 +8,8 @@ #include #include -#include -#include +#include +#include #if OPENMW_FFMPEG_5_OR_GREATER #include diff --git a/apps/openmw/mwsound/ffmpegdecoder.hpp b/apps/openmw/mwsound/ffmpegdecoder.hpp index 519d160cd2..17f1301c3e 100644 --- a/apps/openmw/mwsound/ffmpegdecoder.hpp +++ b/apps/openmw/mwsound/ffmpegdecoder.hpp @@ -3,8 +3,8 @@ #include -#include -#include +#include +#include #if defined(_MSC_VER) #pragma warning(push) diff --git a/apps/openmw/mwsound/movieaudiofactory.cpp b/apps/openmw/mwsound/movieaudiofactory.cpp index 6e479f5af2..647619d9ed 100644 --- a/apps/openmw/mwsound/movieaudiofactory.cpp +++ b/apps/openmw/mwsound/movieaudiofactory.cpp @@ -1,8 +1,8 @@ #include "movieaudiofactory.hpp" -#include -#include -#include +#include +#include +#include #include "../mwbase/environment.hpp" #include "../mwbase/soundmanager.hpp" diff --git a/apps/openmw/mwsound/movieaudiofactory.hpp b/apps/openmw/mwsound/movieaudiofactory.hpp index 0af1066af5..71dca9e889 100644 --- a/apps/openmw/mwsound/movieaudiofactory.hpp +++ b/apps/openmw/mwsound/movieaudiofactory.hpp @@ -1,7 +1,7 @@ #ifndef OPENMW_MWSOUND_MOVIEAUDIOFACTORY_H #define OPENMW_MWSOUND_MOVIEAUDIOFACTORY_H -#include +#include namespace MWSound { diff --git a/apps/openmw/mwsound/openaloutput.cpp b/apps/openmw/mwsound/openaloutput.cpp index 4b0e6ff72b..90668fe35a 100644 --- a/apps/openmw/mwsound/openaloutput.cpp +++ b/apps/openmw/mwsound/openaloutput.cpp @@ -311,7 +311,7 @@ namespace MWSound bool isPlaying(); double getStreamDelay() const; - double getStreamOffset() const; + float getStreamOffset() const; float getCurrentLoudness() const; @@ -469,7 +469,7 @@ namespace MWSound OpenAL_SoundStream::~OpenAL_SoundStream() { if (mBuffers[0] && alIsBuffer(mBuffers[0])) - alDeleteBuffers(mBuffers.size(), mBuffers.data()); + alDeleteBuffers(static_cast(mBuffers.size()), mBuffers.data()); alGetError(); mDecoder->close(); @@ -477,7 +477,7 @@ namespace MWSound bool OpenAL_SoundStream::init(bool getLoudnessData) { - alGenBuffers(mBuffers.size(), mBuffers.data()); + alGenBuffers(static_cast(mBuffers.size()), mBuffers.data()); ALenum err = getALError(); if (err != AL_NO_ERROR) return false; @@ -509,7 +509,7 @@ namespace MWSound break; } - mFrameSize = framesToBytes(1, chans, type); + mFrameSize = static_cast(framesToBytes(1, chans, type)); mBufferSize = static_cast(sBufferLength * mSampleRate); mBufferSize *= mFrameSize; @@ -552,11 +552,11 @@ namespace MWSound return d; } - double OpenAL_SoundStream::getStreamOffset() const + float OpenAL_SoundStream::getStreamOffset() const { ALint state = AL_STOPPED; ALint offset; - double t; + float t; alGetSourcei(mSource, AL_SAMPLE_OFFSET, &offset); alGetSourcei(mSource, AL_SOURCE_STATE, &state); @@ -565,13 +565,13 @@ namespace MWSound ALint queued; alGetSourcei(mSource, AL_BUFFERS_QUEUED, &queued); ALint inqueue = mBufferSize / mFrameSize * queued - offset; - t = (double)(mDecoder->getSampleOffset() - inqueue) / (double)mSampleRate; + t = (mDecoder->getSampleOffset() - inqueue) / static_cast(mSampleRate); } else { /* Underrun, or not started yet. The decoder offset is where we'll play * next. */ - t = (double)mDecoder->getSampleOffset() / (double)mSampleRate; + t = mDecoder->getSampleOffset() / static_cast(mSampleRate); } getALError(); @@ -642,7 +642,7 @@ namespace MWSound mLoudnessAnalyzer->analyzeLoudness(data); ALuint bufid = mBuffers[mCurrentBufIdx]; - alBufferData(bufid, mFormat, data.data(), data.size(), mSampleRate); + alBufferData(bufid, mFormat, data.data(), static_cast(data.size()), mSampleRate); alSourceQueueBuffers(mSource, 1, &bufid); mCurrentBufIdx = (mCurrentBufIdx + 1) % mBuffers.size(); } @@ -801,7 +801,7 @@ namespace MWSound if (alEventControlSOFT) { static const std::array events{ { AL_EVENT_TYPE_DISCONNECTED_SOFT } }; - alEventControlSOFT(events.size(), events.data(), AL_TRUE); + alEventControlSOFT(static_cast(events.size()), events.data(), AL_TRUE); alEventCallbackSOFT(&OpenALOutput::eventCallback, this); } else @@ -1065,7 +1065,7 @@ namespace MWSound ALint size; ALuint buf = 0; alGenBuffers(1, &buf); - alBufferData(buf, format, data.data(), data.size(), srate); + alBufferData(buf, format, data.data(), static_cast(data.size()), srate); alGetBufferi(buf, AL_SIZE, &size); if (getALError() != AL_NO_ERROR) { @@ -1412,10 +1412,10 @@ namespace MWSound return stream->getStreamDelay(); } - double OpenALOutput::getStreamOffset(Stream* sound) + float OpenALOutput::getStreamOffset(Stream* sound) { if (!sound->mHandle) - return 0.0; + return 0.f; OpenAL_SoundStream* stream = reinterpret_cast(sound->mHandle); std::lock_guard lock(mStreamThread->mMutex); return stream->getStreamOffset(); @@ -1523,7 +1523,7 @@ namespace MWSound } if (!sources.empty()) { - alSourcePausev(sources.size(), sources.data()); + alSourcePausev(static_cast(sources.size()), sources.data()); getALError(); } } @@ -1578,7 +1578,7 @@ namespace MWSound } if (!sources.empty()) { - alSourcePlayv(sources.size(), sources.data()); + alSourcePlayv(static_cast(sources.size()), sources.data()); getALError(); } } diff --git a/apps/openmw/mwsound/openaloutput.hpp b/apps/openmw/mwsound/openaloutput.hpp index d689d08546..107c3f4c61 100644 --- a/apps/openmw/mwsound/openaloutput.hpp +++ b/apps/openmw/mwsound/openaloutput.hpp @@ -101,7 +101,7 @@ namespace MWSound bool streamSound3D(DecoderPtr decoder, Stream* sound, bool getLoudnessData) override; void finishStream(Stream* sound) override; double getStreamDelay(Stream* sound) override; - double getStreamOffset(Stream* sound) override; + float getStreamOffset(Stream* sound) override; float getStreamLoudness(Stream* sound) override; bool isStreamPlaying(Stream* sound) override; void updateStream(Stream* sound) override; diff --git a/apps/openmw/mwsound/soundoutput.hpp b/apps/openmw/mwsound/soundoutput.hpp index 4b24f159d3..def95ac693 100644 --- a/apps/openmw/mwsound/soundoutput.hpp +++ b/apps/openmw/mwsound/soundoutput.hpp @@ -53,7 +53,7 @@ namespace MWSound virtual bool streamSound3D(DecoderPtr decoder, Stream* sound, bool getLoudnessData) = 0; virtual void finishStream(Stream* sound) = 0; virtual double getStreamDelay(Stream* sound) = 0; - virtual double getStreamOffset(Stream* sound) = 0; + virtual float getStreamOffset(Stream* sound) = 0; virtual float getStreamLoudness(Stream* sound) = 0; virtual bool isStreamPlaying(Stream* sound) = 0; virtual void updateStream(Stream* sound) = 0; diff --git a/apps/openmw/mwstate/statemanagerimp.cpp b/apps/openmw/mwstate/statemanagerimp.cpp index d6cdf99bff..549bacb887 100644 --- a/apps/openmw/mwstate/statemanagerimp.cpp +++ b/apps/openmw/mwstate/statemanagerimp.cpp @@ -289,7 +289,7 @@ void MWState::StateManager::saveGame(std::string_view description, const Slot* s writer.setAuthor(""); writer.setDescription(""); - int recordCount = 1 // saved game header + size_t recordCount = 1 // saved game header + MWBase::Environment::get().getJournal()->countSavedGameRecords() + MWBase::Environment::get().getLuaManager()->countSavedGameRecords() + MWBase::Environment::get().getWorld()->countSavedGameRecords() @@ -298,7 +298,7 @@ void MWState::StateManager::saveGame(std::string_view description, const Slot* s + MWBase::Environment::get().getMechanicsManager()->countSavedGameRecords() + MWBase::Environment::get().getInputManager()->countSavedGameRecords() + MWBase::Environment::get().getWindowManager()->countSavedGameRecords(); - writer.setRecordCount(recordCount); + writer.setRecordCount(static_cast(recordCount)); writer.save(stream); @@ -325,7 +325,7 @@ void MWState::StateManager::saveGame(std::string_view description, const Slot* s MWBase::Environment::get().getWindowManager()->write(writer, listener); // Ensure we have written the number of records that was estimated - if (writer.getRecordCount() != recordCount + 1) // 1 extra for TES3 record + if (static_cast(writer.getRecordCount()) != recordCount + 1) // 1 extra for TES3 record Log(Debug::Warning) << "Warning: number of written savegame records does not match. Estimated: " << recordCount + 1 << ", written: " << writer.getRecordCount(); diff --git a/apps/openmw/mwworld/cellpreloader.cpp b/apps/openmw/mwworld/cellpreloader.cpp index 5540982f26..8aa95878f6 100644 --- a/apps/openmw/mwworld/cellpreloader.cpp +++ b/apps/openmw/mwworld/cellpreloader.cpp @@ -402,7 +402,7 @@ namespace MWWorld mTerrainViews.resize(positions.size()); else if (mTerrainViews.size() < positions.size()) { - for (unsigned int i = mTerrainViews.size(); i < positions.size(); ++i) + for (size_t i = mTerrainViews.size(); i < positions.size(); ++i) mTerrainViews.emplace_back(mTerrain->createView()); } @@ -456,10 +456,10 @@ namespace MWWorld void CellPreloader::reportStats(unsigned int frameNumber, osg::Stats& stats) const { - stats.setAttribute(frameNumber, "CellPreloader Count", mPreloadCells.size()); - stats.setAttribute(frameNumber, "CellPreloader Added", mAdded); - stats.setAttribute(frameNumber, "CellPreloader Evicted", mEvicted); - stats.setAttribute(frameNumber, "CellPreloader Loaded", mLoaded); - stats.setAttribute(frameNumber, "CellPreloader Expired", mExpired); + stats.setAttribute(frameNumber, "CellPreloader Count", static_cast(mPreloadCells.size())); + stats.setAttribute(frameNumber, "CellPreloader Added", static_cast(mAdded)); + stats.setAttribute(frameNumber, "CellPreloader Evicted", static_cast(mEvicted)); + stats.setAttribute(frameNumber, "CellPreloader Loaded", static_cast(mLoaded)); + stats.setAttribute(frameNumber, "CellPreloader Expired", static_cast(mExpired)); } } diff --git a/apps/openmw/mwworld/cellref.cpp b/apps/openmw/mwworld/cellref.cpp index 854348c2a8..82270f3276 100644 --- a/apps/openmw/mwworld/cellref.cpp +++ b/apps/openmw/mwworld/cellref.cpp @@ -308,7 +308,7 @@ namespace MWWorld { mChanged = true; std::visit(ESM::VisitOverload{ - [&](ESM4::Reference& ref) { ref.mLockLevel = lockLevel; }, + [&](ESM4::Reference& ref) { ref.mLockLevel = static_cast(lockLevel); }, [&](ESM4::ActorCharacter&) {}, [&](ESM::CellRef& ref) { ref.mLockLevel = lockLevel; }, }, diff --git a/apps/openmw/mwworld/esmstore.cpp b/apps/openmw/mwworld/esmstore.cpp index 91d30c91d1..773e4a80e8 100644 --- a/apps/openmw/mwworld/esmstore.cpp +++ b/apps/openmw/mwworld/esmstore.cpp @@ -681,7 +681,7 @@ namespace MWWorld } } - int ESMStore::countSavedGameRecords() const + size_t ESMStore::countSavedGameRecords() const { return 1 // DYNA (dynamic name counter) + get().getDynamicSize() + get().getDynamicSize() diff --git a/apps/openmw/mwworld/esmstore.hpp b/apps/openmw/mwworld/esmstore.hpp index 56a8e57bcc..bab0fb81d1 100644 --- a/apps/openmw/mwworld/esmstore.hpp +++ b/apps/openmw/mwworld/esmstore.hpp @@ -286,7 +286,7 @@ namespace MWWorld void setUp(); void validateRecords(ESM::ReadersCache& readers); - int countSavedGameRecords() const; + size_t countSavedGameRecords() const; void write(ESM::ESMWriter& writer, Loading::Listener& progress) const; diff --git a/apps/openmw/mwworld/globals.cpp b/apps/openmw/mwworld/globals.cpp index 4977df56c0..5e7888eab0 100644 --- a/apps/openmw/mwworld/globals.cpp +++ b/apps/openmw/mwworld/globals.cpp @@ -72,7 +72,7 @@ namespace MWWorld } } - int Globals::countSavedGameRecords() const + size_t Globals::countSavedGameRecords() const { return mVariables.size(); } diff --git a/apps/openmw/mwworld/globals.hpp b/apps/openmw/mwworld/globals.hpp index ab94f0f8dd..22c3e319ef 100644 --- a/apps/openmw/mwworld/globals.hpp +++ b/apps/openmw/mwworld/globals.hpp @@ -64,7 +64,7 @@ namespace MWWorld void fill(const MWWorld::ESMStore& store); ///< Replace variables with variables from \a store with default values. - int countSavedGameRecords() const; + size_t countSavedGameRecords() const; void write(ESM::ESMWriter& writer, Loading::Listener& progress) const; diff --git a/apps/openmw/mwworld/inventorystore.cpp b/apps/openmw/mwworld/inventorystore.cpp index d7fd58c6c1..eb39d42bbb 100644 --- a/apps/openmw/mwworld/inventorystore.cpp +++ b/apps/openmw/mwworld/inventorystore.cpp @@ -64,7 +64,7 @@ void MWWorld::InventoryStore::readEquipmentState( if (index == inventory.mSelectedEnchantItem) mSelectedEnchantItem = iter; - auto found = inventory.mEquipmentSlots.find(index); + auto found = inventory.mEquipmentSlots.find(static_cast(index)); if (found != inventory.mEquipmentSlots.end()) { if (found->second < 0 || found->second >= MWWorld::InventoryStore::Slots) diff --git a/apps/openmw/mwworld/magiceffects.cpp b/apps/openmw/mwworld/magiceffects.cpp index c1d0508fe1..6323dcb772 100644 --- a/apps/openmw/mwworld/magiceffects.cpp +++ b/apps/openmw/mwworld/magiceffects.cpp @@ -93,8 +93,8 @@ namespace MWWorld else { effect.mMagnitude = 0.f; - effect.mMinMagnitude = enam.mData.mMagnMin; - effect.mMaxMagnitude = enam.mData.mMagnMax; + effect.mMinMagnitude = static_cast(enam.mData.mMagnMin); + effect.mMaxMagnitude = static_cast(enam.mData.mMagnMax); effect.mFlags = ESM::ActiveEffect::Flag_None; } params.mEffects.emplace_back(effect); @@ -106,7 +106,7 @@ namespace MWWorld for (std::size_t i = 0; i < inventory.mItems.size(); ++i) { ESM::ObjectState& item = inventory.mItems[i]; - auto slot = inventory.mEquipmentSlots.find(i); + auto slot = inventory.mEquipmentSlots.find(static_cast(i)); if (slot != inventory.mEquipmentSlots.end()) { MWBase::Environment::get().getWorldModel()->assignSaveFileRefNum(item.mRef); @@ -216,7 +216,7 @@ namespace MWWorld dynamic.mMod = 0.f; } for (auto& setting : creatureStats.mAiSettings) - setting.mMod = 0.f; + setting.mMod = 0; if (npcStats) { for (auto& skill : npcStats->mSkills) @@ -231,7 +231,7 @@ namespace MWWorld for (auto& dynamic : creatureStats.mDynamic) dynamic.mMod = 0.f; for (auto& setting : creatureStats.mAiSettings) - setting.mMod = 0.f; + setting.mMod = 0; } // Versions 17-27 wrote an equipment slot index to mItem diff --git a/apps/openmw/mwworld/player.cpp b/apps/openmw/mwworld/player.cpp index fca3a30a2c..7bbc469e07 100644 --- a/apps/openmw/mwworld/player.cpp +++ b/apps/openmw/mwworld/player.cpp @@ -68,9 +68,9 @@ namespace MWWorld MWMechanics::NpcStats& stats = getPlayer().getClass().getNpcStats(getPlayer()); for (size_t i = 0; i < mSaveSkills.size(); ++i) - mSaveSkills[i] = stats.getSkill(ESM::Skill::indexToRefId(i)).getModified(); + mSaveSkills[i] = stats.getSkill(ESM::Skill::indexToRefId(static_cast(i))).getModified(); for (size_t i = 0; i < mSaveAttributes.size(); ++i) - mSaveAttributes[i] = stats.getAttribute(ESM::Attribute::indexToRefId(i)).getModified(); + mSaveAttributes[i] = stats.getAttribute(ESM::Attribute::indexToRefId(static_cast(i))).getModified(); } void Player::restoreStats() @@ -83,13 +83,13 @@ namespace MWWorld creatureStats.setHealth(health.getBase() / gmst.find("fWereWolfHealth")->mValue.getFloat()); for (size_t i = 0; i < mSaveSkills.size(); ++i) { - auto& skill = npcStats.getSkill(ESM::Skill::indexToRefId(i)); + auto& skill = npcStats.getSkill(ESM::Skill::indexToRefId(static_cast(i))); skill.restore(skill.getDamage()); skill.setModifier(mSaveSkills[i] - skill.getBase()); } for (size_t i = 0; i < mSaveAttributes.size(); ++i) { - auto id = ESM::Attribute::indexToRefId(i); + auto id = ESM::Attribute::indexToRefId(static_cast(i)); auto attribute = npcStats.getAttribute(id); attribute.restore(attribute.getDamage()); attribute.setModifier(mSaveAttributes[i] - attribute.getBase()); diff --git a/apps/openmw/mwworld/projectilemanager.cpp b/apps/openmw/mwworld/projectilemanager.cpp index 1186316bb1..f4d7569fe9 100644 --- a/apps/openmw/mwworld/projectilemanager.cpp +++ b/apps/openmw/mwworld/projectilemanager.cpp @@ -144,8 +144,8 @@ namespace = MWBase::Environment::get().getESMStore()->get().find(enam.mData.mEffectID); lightDiffuseColor += magicEffect->getColor(); } - int numberOfEffects = effects.mList.size(); - lightDiffuseColor /= numberOfEffects; + size_t numberOfEffects = effects.mList.size(); + lightDiffuseColor /= static_cast(numberOfEffects); return lightDiffuseColor; } @@ -581,7 +581,7 @@ namespace MWWorld assert(target != caster); MWMechanics::CastSpell cast(caster, target); - cast.mHitPosition = !active ? Misc::Convert::toOsg(projectile->getHitPosition()) : pos; + cast.mHitPosition = !active ? Misc::Convert::makeOsgVec3f(projectile->getHitPosition()) : pos; cast.mId = magicBoltState.mSpellId; cast.mSourceName = magicBoltState.mSourceName; cast.mItem = magicBoltState.mItem; @@ -793,7 +793,7 @@ namespace MWWorld return false; } - int ProjectileManager::countSavedGameRecords() const + size_t ProjectileManager::countSavedGameRecords() const { return mMagicBolts.size() + mProjectiles.size(); } diff --git a/apps/openmw/mwworld/projectilemanager.hpp b/apps/openmw/mwworld/projectilemanager.hpp index 3003136ffc..432f463dbd 100644 --- a/apps/openmw/mwworld/projectilemanager.hpp +++ b/apps/openmw/mwworld/projectilemanager.hpp @@ -67,7 +67,7 @@ namespace MWWorld void write(ESM::ESMWriter& writer, Loading::Listener& progress) const; bool readRecord(ESM::ESMReader& reader, uint32_t type); - int countSavedGameRecords() const; + size_t countSavedGameRecords() const; private: osg::ref_ptr mParent; diff --git a/apps/openmw/mwworld/scene.cpp b/apps/openmw/mwworld/scene.cpp index 7e55bc8ba9..a7b9179839 100644 --- a/apps/openmw/mwworld/scene.cpp +++ b/apps/openmw/mwworld/scene.cpp @@ -178,13 +178,13 @@ namespace const btTransform closedDoorTransform( Misc::Convert::makeBulletQuaternion(ptr.getCellRef().getPosition()), transform.getOrigin()); - const auto start = Misc::Convert::toOsg(closedDoorTransform(center + toPoint)); + const auto start = Misc::Convert::makeOsgVec3f(closedDoorTransform(center + toPoint)); const auto startPoint = physics.castRay(start, start - osg::Vec3f(0, 0, 1000), { ptr }, {}, MWPhysics::CollisionType_World | MWPhysics::CollisionType_HeightMap | MWPhysics::CollisionType_Water); const auto connectionStart = startPoint.mHit ? startPoint.mHitPos : start; - const auto end = Misc::Convert::toOsg(closedDoorTransform(center - toPoint)); + const auto end = Misc::Convert::makeOsgVec3f(closedDoorTransform(center - toPoint)); const auto endPoint = physics.castRay(end, end - osg::Vec3f(0, 0, 1000), { ptr }, {}, MWPhysics::CollisionType_World | MWPhysics::CollisionType_HeightMap | MWPhysics::CollisionType_Water); @@ -460,8 +460,6 @@ namespace MWWorld if (const auto heightField = mPhysics->getHeightField(cellX, cellY)) { const osg::Vec2i cellPosition(cellX, cellY); - const btVector3& origin = heightField->getCollisionObject()->getWorldTransform().getOrigin(); - const osg::Vec3f shift(origin.x(), origin.y(), origin.z()); const HeightfieldShape shape = [&]() -> HeightfieldShape { if (data == nullptr) { @@ -562,7 +560,7 @@ namespace MWWorld const osg::Vec2f center = ESM::indexToPosition( ESM::ExteriorCellLocation(currentGridCenter->x(), currentGridCenter->y(), worldspace), true); float distance = std::max(std::abs(center.x() - pos.x()), std::abs(center.y() - pos.y())); - float cellSize = ESM::getCellSize(worldspace); + int cellSize = ESM::getCellSize(worldspace); const float maxDistance = cellSize / 2 + mCellLoadingThreshold; // 1/2 cell size + threshold if (distance <= maxDistance) return *currentGridCenter; @@ -1226,7 +1224,7 @@ namespace MWWorld cellY = mCurrentGridCenter.y(); ESM::RefId extWorldspace = mWorld.getCurrentWorldspace(); - float cellSize = ESM::getCellSize(extWorldspace); + int cellSize = ESM::getCellSize(extWorldspace); for (int dx = -halfGridSizePlusOne; dx <= halfGridSizePlusOne; ++dx) { diff --git a/apps/openmw/mwworld/store.cpp b/apps/openmw/mwworld/store.cpp index b5b3e807fa..64f30aa809 100644 --- a/apps/openmw/mwworld/store.cpp +++ b/apps/openmw/mwworld/store.cpp @@ -81,7 +81,7 @@ namespace MWWorld mStatic.insert_or_assign(idx, std::move(record)); } template - int IndexedStore::getSize() const + size_t IndexedStore::getSize() const { return mStatic.size(); } @@ -255,7 +255,7 @@ namespace MWWorld } template - int TypedDynamicStore::getDynamicSize() const + size_t TypedDynamicStore::getDynamicSize() const { return mDynamic.size(); } diff --git a/apps/openmw/mwworld/store.hpp b/apps/openmw/mwworld/store.hpp index 5ce287c34e..ecb22c1d33 100644 --- a/apps/openmw/mwworld/store.hpp +++ b/apps/openmw/mwworld/store.hpp @@ -61,7 +61,7 @@ namespace MWWorld class DynamicStoreBase : public StoreBase { public: - virtual ~DynamicStoreBase() {} + virtual ~DynamicStoreBase() = default; virtual void setUp() {} @@ -70,7 +70,7 @@ namespace MWWorld virtual void listIdentifier(std::vector& list) const {} virtual size_t getSize() const = 0; - virtual int getDynamicSize() const { return 0; } + virtual size_t getDynamicSize() const { return 0; } virtual RecordId load(ESM::ESMReader& esm) = 0; virtual bool eraseStatic(const Id& id) { return false; } @@ -102,7 +102,7 @@ namespace MWWorld void load(ESM::ESMReader& esm); - int getSize() const; + size_t getSize() const; void setUp(); const T* search(int index) const; @@ -230,7 +230,7 @@ namespace MWWorld const T* at(size_t index) const { return mShared.at(index); } size_t getSize() const override; - int getDynamicSize() const override; + size_t getDynamicSize() const override; /// @note The record identifiers are listed in the order that the records were defined by the content files. void listIdentifier(std::vector& list) const override; diff --git a/apps/openmw/mwworld/weather.cpp b/apps/openmw/mwworld/weather.cpp index 60d63fe46b..45d3138ce0 100644 --- a/apps/openmw/mwworld/weather.cpp +++ b/apps/openmw/mwworld/weather.cpp @@ -175,7 +175,7 @@ namespace MWWorld , mIsStorm(mWindSpeed > stormWindSpeed) , mRainSpeed(rainSpeed) , mRainEntranceSpeed(Fallback::Map::getFloat("Weather_" + name + "_Rain_Entrance_Speed")) - , mRainMaxRaindrops(Fallback::Map::getFloat("Weather_" + name + "_Max_Raindrops")) + , mRainMaxRaindrops(Fallback::Map::getInt("Weather_" + name + "_Max_Raindrops")) , mRainDiameter(Fallback::Map::getFloat("Weather_" + name + "_Rain_Diameter")) , mRainThreshold(Fallback::Map::getFloat("Weather_" + name + "_Rain_Threshold")) , mRainMinHeight(Fallback::Map::getFloat("Weather_" + name + "_Rain_Height_Min")) @@ -709,7 +709,7 @@ namespace MWWorld auto rIt = mRegions.find(regionID); if (rIt != mRegions.end()) { - rIt->second.setWeather(std::distance(mWeatherSettings.begin(), wIt)); + rIt->second.setWeather(wIt->mScriptId); regionalWeatherChanged(rIt->first, rIt->second); } } @@ -981,7 +981,7 @@ namespace MWWorld { // In Morrowind, when the player sleeps/waits, serves jail time, travels, or trains, all weather transitions are // immediately applied, regardless of whatever transition time might have been remaining. - mTimePassed += hours; + mTimePassed += static_cast(hours); mFastForward = !incremental ? true : mFastForward; } @@ -1093,8 +1093,8 @@ namespace MWWorld { static const float fStromWindSpeed = mStore.get().find("fStromWindSpeed")->mValue.getFloat(); ESM::StringRefId id(name); - Weather weather( - id, mWeatherSettings.size(), name, fStromWindSpeed, mRainSpeed, dlFactor, dlOffset, particleEffect); + Weather weather(id, static_cast(mWeatherSettings.size()), name, fStromWindSpeed, mRainSpeed, dlFactor, + dlOffset, particleEffect); mWeatherSettings.push_back(std::move(weather)); } diff --git a/apps/openmw/mwworld/worldimp.cpp b/apps/openmw/mwworld/worldimp.cpp index e01896fec3..e542873713 100644 --- a/apps/openmw/mwworld/worldimp.cpp +++ b/apps/openmw/mwworld/worldimp.cpp @@ -443,7 +443,7 @@ namespace MWWorld fillGlobalVariables(); } - int World::countSavedGameRecords() const + size_t World::countSavedGameRecords() const { return mWorldModel.countSavedGameRecords() + mStore.countSavedGameRecords() + mGlobalVariables.countSavedGameRecords() + mProjectileManager->countSavedGameRecords() @@ -455,7 +455,7 @@ namespace MWWorld + 1; // random state. } - int World::countSavedGameCells() const + size_t World::countSavedGameCells() const { return mWorldModel.countSavedGameRecords(); } @@ -900,7 +900,7 @@ namespace MWWorld { // When we fast-forward time, we should recharge magic items // in all loaded cells, using game world time - float duration = hours * 3600; + float duration = static_cast(hours * 3600); const float timeScaleFactor = mTimeManager->getGameTimeScale(); if (timeScaleFactor != 0.0f) duration /= timeScaleFactor; @@ -1281,9 +1281,9 @@ namespace MWWorld * currently it's done so for rotating the camera, which needs * clamping. */ - objRot[0] = std::clamp(objRot[0], -osg::PI_2, osg::PI_2); - objRot[1] = Misc::normalizeAngle(objRot[1]); - objRot[2] = Misc::normalizeAngle(objRot[2]); + objRot[0] = std::clamp(objRot[0], -osg::PI_2f, osg::PI_2f); + objRot[1] = static_cast(Misc::normalizeAngle(objRot[1])); + objRot[2] = static_cast(Misc::normalizeAngle(objRot[2])); } ptr.getRefData().setPosition(pos); @@ -1336,8 +1336,8 @@ namespace MWWorld && !(ptr.getClass().isPersistent(ptr) && ptr.getClass().getCreatureStats(ptr).isDeathAnimationFinished()); if (force || !ptr.getClass().isActor() || (!isFlying(ptr) && !swims && isActorCollisionEnabled(ptr))) { - osg::Vec3f traced - = mPhysics->traceDown(ptr, pos, ESM::getCellSize(ptr.getCell()->getCell()->getWorldSpace())); + float height = static_cast(ESM::getCellSize(ptr.getCell()->getCell()->getWorldSpace())); + osg::Vec3f traced = mPhysics->traceDown(ptr, pos, height); pos.z() = std::min(pos.z(), traced.z()); } @@ -1373,8 +1373,8 @@ namespace MWWorld break; } targetPos.z() += distance / 2.f; // move up a bit to get out from geometry, will snap down later - osg::Vec3f traced - = mPhysics->traceDown(actor, targetPos, ESM::getCellSize(actor.getCell()->getCell()->getWorldSpace())); + float height = static_cast(ESM::getCellSize(actor.getCell()->getCell()->getWorldSpace())); + osg::Vec3f traced = mPhysics->traceDown(actor, targetPos, height); if (traced != pos) { esmPos.pos[0] = traced.x(); @@ -2380,7 +2380,7 @@ namespace MWWorld result |= Rest_PlayerIsUnderwater; float fallHeight = player.getClass().getCreatureStats(player).getFallHeight(); - float epsilon = 1e-4; + float epsilon = 1e-4f; if ((actor->getCollisionMode() && (!mPhysics->isOnSolidGround(player) || fallHeight >= epsilon)) || isFlying(player)) result |= Rest_PlayerIsInAir; @@ -3365,7 +3365,7 @@ namespace MWWorld mWorldModel.forEachLoadedCellStore([hours](CellStore& store) { store.rest(hours); }); } - void World::rechargeItems(double duration, bool activeOnly) + void World::rechargeItems(float duration, bool activeOnly) { MWWorld::Ptr player = getPlayerPtr(); player.getClass().getInventoryStore(player).rechargeItems(duration); @@ -3530,7 +3530,7 @@ namespace MWWorld float World::feetToGameUnits(float feet) { // Original engine rounds size upward - static const int unitsPerFoot = ceil(Constants::UnitsPerFoot); + static const float unitsPerFoot = std::ceil(Constants::UnitsPerFoot); return feet * unitsPerFoot; } diff --git a/apps/openmw/mwworld/worldimp.hpp b/apps/openmw/mwworld/worldimp.hpp index b5dbc19de9..54ad5ab636 100644 --- a/apps/openmw/mwworld/worldimp.hpp +++ b/apps/openmw/mwworld/worldimp.hpp @@ -214,8 +214,8 @@ namespace MWWorld void clear() override; - int countSavedGameRecords() const override; - int countSavedGameCells() const override; + size_t countSavedGameRecords() const override; + size_t countSavedGameCells() const override; void write(ESM::ESMWriter& writer, Loading::Listener& progress) const override; @@ -516,7 +516,7 @@ namespace MWWorld ///< check if the player is allowed to rest void rest(double hours) override; - void rechargeItems(double duration, bool activeOnly); + void rechargeItems(float duration, bool activeOnly); /// \todo Probably shouldn't be here MWRender::Animation* getAnimation(const MWWorld::Ptr& ptr) override; diff --git a/apps/openmw/mwworld/worldmodel.cpp b/apps/openmw/mwworld/worldmodel.cpp index 39ed27e96b..8d550b1855 100644 --- a/apps/openmw/mwworld/worldmodel.cpp +++ b/apps/openmw/mwworld/worldmodel.cpp @@ -449,7 +449,7 @@ std::vector MWWorld::WorldModel::getAll(const ESM::RefId& id) return result; } -int MWWorld::WorldModel::countSavedGameRecords() const +size_t MWWorld::WorldModel::countSavedGameRecords() const { return std::count_if(mCells.begin(), mCells.end(), [](const auto& v) { return v.second.hasState(); }); } diff --git a/apps/openmw/mwworld/worldmodel.hpp b/apps/openmw/mwworld/worldmodel.hpp index 0b555c4b9e..68d3c6d198 100644 --- a/apps/openmw/mwworld/worldmodel.hpp +++ b/apps/openmw/mwworld/worldmodel.hpp @@ -97,7 +97,7 @@ namespace MWWorld std::vector getAll(const ESM::RefId& id); - int countSavedGameRecords() const; + size_t countSavedGameRecords() const; void write(ESM::ESMWriter& writer, Loading::Listener& progress) const; diff --git a/components/bsa/bsafile.cpp b/components/bsa/bsafile.cpp index 979ea4376a..20dc09af37 100644 --- a/components/bsa/bsafile.cpp +++ b/components/bsa/bsafile.cpp @@ -336,8 +336,8 @@ void Bsa::BSAFile::addFile(const std::string& filename, std::istream& file) newFile.mOffset = static_cast(stream.tellp()); } - newFile.mNameOffset = mStringBuf.size(); - newFile.mNameSize = filename.size(); + newFile.mNameOffset = static_cast(mStringBuf.size()); + newFile.mNameSize = static_cast(filename.size()); newFile.mNamesBuffer = &mStringBuf; mStringBuf.insert(mStringBuf.end(), filename.begin(), filename.end()); diff --git a/components/debug/debugdraw.cpp b/components/debug/debugdraw.cpp index e013af0e11..37f7e6de65 100644 --- a/components/debug/debugdraw.cpp +++ b/components/debug/debugdraw.cpp @@ -13,7 +13,7 @@ static osg::Vec3 sphereCoordToCartesian(float theta, float phi, float r) { osg::Vec3 returnVec = osg::Vec3(0.0, 0.0, 0.0); - float phiToHorizontal = osg::PI_2 - phi; + float phiToHorizontal = osg::PI_2f - phi; returnVec.x() = std::cos(theta); returnVec.y() = std::sin(theta); returnVec.z() = std::sin(phiToHorizontal); @@ -36,9 +36,9 @@ static void generateWireCube(osg::Geometry& geom, float dim) for (int i = 0; i < 4; i++) { - osg::Vec3 vert1 = osg::Vec3(indexPos[i].x() - 0.5, indexPos[i].y() - 0.5, 0.5); + osg::Vec3 vert1 = osg::Vec3(indexPos[i].x() - 0.5f, indexPos[i].y() - 0.5f, 0.5f); int next = (i + 1) % 4; - osg::Vec3 vert2 = osg::Vec3(indexPos[next].x() - 0.5, indexPos[next].y() - 0.5, 0.5); + osg::Vec3 vert2 = osg::Vec3(indexPos[next].x() - 0.5f, indexPos[next].y() - 0.5f, 0.5f); vertices->push_back(vert1 * dim); vertices->push_back(vert2 * dim); @@ -59,7 +59,7 @@ static void generateWireCube(osg::Geometry& geom, float dim) geom.setVertexArray(vertices); geom.setNormalArray(normals, osg::Array::BIND_PER_VERTEX); - geom.addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::LINES, 0, vertices->size())); + geom.addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::LINES, 0, static_cast(vertices->size()))); } static void generateCube(osg::Geometry& geom, float dim) @@ -68,14 +68,13 @@ static void generateCube(osg::Geometry& geom, float dim) osg::ref_ptr normals = new osg::Vec3Array; osg::ref_ptr indices = new osg::DrawElementsUShort(osg::DrawElementsUShort::TRIANGLES, 0); - for (int iFace = 0; iFace < 6; iFace++) + for (GLushort iFace = 0; iFace < 6; iFace++) { osg::Vec3f normale(0., 0., 0.); osg::Vec3f u(0., 0., 0.); osg::Vec3f v(0., 0., 0.); - int axis = iFace / 2; - int dir = iFace % 2 == 0 ? -1 : 1; - float floatDir = dir; + GLushort axis = iFace / 2; + float floatDir = iFace % 2 == 0 ? -1.f : 1.f; normale[axis] = floatDir; u[(axis + 1) % 3] = 1.0; v[(axis + 2) % 3] = 1.0; @@ -85,20 +84,22 @@ static void generateCube(osg::Geometry& geom, float dim) float iu = iPoint % 2 == 1 ? floatDir : -floatDir; // This is to get the right triangle orientation when the normal changes* - float iv = iPoint / 2 == 1 ? 1.0 : -1.0; + float iv = iPoint / 2 == 1 ? 1.f : -1.f; osg::Vec3f point = (u * iu) + (v * iv); point = (point + normale); point = point * (dim * 0.5f); vertices->push_back(point); normals->push_back(normale); } - int startVertex(iFace * 4); - int newFace1[] = { startVertex, startVertex + 1, startVertex + 2 }; + GLushort startVertex(iFace * 4); + GLushort newFace1[] + = { startVertex, static_cast(startVertex + 1u), static_cast(startVertex + 2u) }; for (int i = 0; i < 3; i++) { indices->push_back(newFace1[i]); } - int newFace2[] = { startVertex + 2, startVertex + 1, startVertex + 3 }; + GLushort newFace2[] = { static_cast(startVertex + 2u), static_cast(startVertex + 1u), + static_cast(startVertex + 3u) }; for (int i = 0; i < 3; i++) { indices->push_back(newFace2[i]); @@ -123,25 +124,25 @@ static void generateCylinder(osg::Geometry& geom, float radius, float height, in // top disk for (int i = 0; i < subdiv; i++) { - float theta = (float(i) / float(subdiv)) * osg::PI * 2.; - osg::Vec3 pos = sphereCoordToCartesian(theta, osg::PI_2f, 1.); + float theta = (float(i) / float(subdiv)) * osg::PIf * 2.f; + osg::Vec3 pos = sphereCoordToCartesian(theta, osg::PI_2f, 1.f); pos *= radius; - pos.z() = height / 2.; + pos.z() = height / 2.f; vertices->push_back(pos); normals->push_back(topNormal); iVertex += 1; } - auto centerTop = iVertex; + auto centerTop = static_cast(iVertex); // centerTop { - vertices->push_back(osg::Vec3(0., 0., height / 2.)); + vertices->push_back(osg::Vec3(0.f, 0.f, height / 2.f)); normals->push_back(topNormal); iVertex += 1; } - auto centerBot = iVertex; + auto centerBot = static_cast(iVertex); // centerBot { - vertices->push_back(osg::Vec3(0., 0., -height / 2)); + vertices->push_back(osg::Vec3(0.f, 0.f, -height / 2)); normals->push_back(-topNormal); iVertex += 1; } @@ -149,10 +150,10 @@ static void generateCylinder(osg::Geometry& geom, float radius, float height, in auto beginBot = iVertex; for (int i = 0; i < subdiv; i++) { - float theta = float(i) / float(subdiv) * osg::PI * 2.; - osg::Vec3 pos = sphereCoordToCartesian(theta, osg::PI_2f, 1.); + float theta = float(i) / float(subdiv) * osg::PIf * 2.f; + osg::Vec3 pos = sphereCoordToCartesian(theta, osg::PI_2f, 1.f); pos *= radius; - pos.z() = -height / 2.; + pos.z() = -height / 2.f; vertices->push_back(pos); normals->push_back(-topNormal); iVertex += 1; @@ -161,13 +162,13 @@ static void generateCylinder(osg::Geometry& geom, float radius, float height, in int beginSide = iVertex; for (int i = 0; i < subdiv; i++) { - float theta = float(i) / float(subdiv) * osg::PI * 2.; - osg::Vec3 normal = sphereCoordToCartesian(theta, osg::PI_2f, 1.); + float theta = float(i) / float(subdiv) * osg::PIf * 2.f; + osg::Vec3 normal = sphereCoordToCartesian(theta, osg::PI_2f, 1.f); auto posTop = normal; posTop *= radius; auto posBot = posTop; - posTop.z() = height / 2.; - posBot.z() = -height / 2.; + posTop.z() = height / 2.f; + posBot.z() = -height / 2.f; vertices->push_back(posTop); normals->push_back(normal); iVertex += 1; @@ -180,10 +181,10 @@ static void generateCylinder(osg::Geometry& geom, float radius, float height, in for (int i = 0; i < subdiv; i++) { auto nextVert = (i + 1) % subdiv; - auto v1 = (beginSide + 2 * i); - auto v2 = (beginSide + 2 * i + 1); - auto v3 = (beginSide + 2 * nextVert); - auto v4 = (beginSide + 2 * nextVert + 1); + auto v1 = static_cast(beginSide + 2 * i); + auto v2 = static_cast(beginSide + 2 * i + 1); + auto v3 = static_cast(beginSide + 2 * nextVert); + auto v4 = static_cast(beginSide + 2 * nextVert + 1); indices->push_back(v1); indices->push_back(v2); indices->push_back(v4); @@ -195,11 +196,11 @@ static void generateCylinder(osg::Geometry& geom, float radius, float height, in for (int i = 0; i < subdiv; i++) { auto nextVert = (i + 1) % subdiv; - auto top1 = (beginTop + i); - auto top2 = (beginTop + nextVert); + auto top1 = static_cast(beginTop + i); + auto top2 = static_cast(beginTop + nextVert); - auto bot1 = (beginBot + i); - auto bot2 = (beginBot + nextVert); + auto bot1 = static_cast(beginBot + i); + auto bot2 = static_cast(beginBot + nextVert); indices->push_back(top2); indices->push_back(centerTop); @@ -239,7 +240,7 @@ namespace Debug lines.setVertexArray(vertices); lines.setNormalArray(color, osg::Array::BIND_PER_VERTEX); - lines.addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::LINES, 0, vertices->size())); + lines.addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::LINES, 0, static_cast(vertices->size()))); } DebugCustomDraw::DebugCustomDraw() @@ -395,5 +396,5 @@ void Debug::DebugDrawer::addLine(const osg::Vec3& start, const osg::Vec3& end, c colors->push_back(color); colors->dirty(); - primitive->setCount(vertices->size()); + primitive->setCount(static_cast(vertices->size())); } diff --git a/components/debug/gldebug.cpp b/components/debug/gldebug.cpp index 482755b761..b9bebb675d 100644 --- a/components/debug/gldebug.cpp +++ b/components/debug/gldebug.cpp @@ -273,7 +273,8 @@ namespace Debug void DebugGroup::push(osg::State& state) const { if (isValid()) - PushDebugGroup::sInstance->glPushDebugGroup(mSource, mId, mMessage.size(), mMessage.c_str()); + PushDebugGroup::sInstance->glPushDebugGroup( + mSource, mId, static_cast(mMessage.size()), mMessage.c_str()); } void DebugGroup::pop(osg::State& state) const diff --git a/components/detournavigator/asyncnavmeshupdater.cpp b/components/detournavigator/asyncnavmeshupdater.cpp index 4a4137170a..d7eaafce9a 100644 --- a/components/detournavigator/asyncnavmeshupdater.cpp +++ b/components/detournavigator/asyncnavmeshupdater.cpp @@ -1039,7 +1039,7 @@ namespace DetourNavigator if (const auto& cachedTileData = job->mCachedTileData) { Log(Debug::Debug) << "Update db tile by job " << job->mId; - job->mGeneratedNavMeshData->mUserId = cachedTileData->mTileId; + job->mGeneratedNavMeshData->mUserId = static_cast(cachedTileData->mTileId); mDb->updateTile(cachedTileData->mTileId, mVersion, serialize(*job->mGeneratedNavMeshData)); return; } @@ -1051,7 +1051,7 @@ namespace DetourNavigator return; } - job->mGeneratedNavMeshData->mUserId = mNextTileId; + job->mGeneratedNavMeshData->mUserId = static_cast(mNextTileId); Log(Debug::Debug) << "Insert db tile by job " << job->mId; mDb->insertTile(mNextTileId, job->mWorldspace, job->mChangedTile, mVersion, job->mInput, serialize(*job->mGeneratedNavMeshData)); diff --git a/components/detournavigator/raycast.cpp b/components/detournavigator/raycast.cpp index 7456912c08..431ac731ab 100644 --- a/components/detournavigator/raycast.cpp +++ b/components/detournavigator/raycast.cpp @@ -22,7 +22,7 @@ namespace DetourNavigator std::array path; dtRaycastHit hit; hit.path = path.data(); - hit.maxPath = path.size(); + hit.maxPath = static_cast(path.size()); if (dtStatus status = navMeshQuery.raycast(ref, start.ptr(), end.ptr(), &queryFilter, options, &hit); dtStatusFailed(status) || hit.pathCount == 0) return {}; diff --git a/components/detournavigator/recastmeshbuilder.cpp b/components/detournavigator/recastmeshbuilder.cpp index d443a5e5b2..eb03ee569b 100644 --- a/components/detournavigator/recastmeshbuilder.cpp +++ b/components/detournavigator/recastmeshbuilder.cpp @@ -122,10 +122,10 @@ namespace DetourNavigator triangles.emplace_back(makeRecastMeshTriangle(vertices, AreaType_ground)); }); shape.processAllTriangles(&callback, aabbMin, aabbMax); - const osg::Vec2f aabbShift - = (osg::Vec2f(aabbMax.x(), aabbMax.y()) - osg::Vec2f(aabbMin.x(), aabbMin.y())) * 0.5; + const btVector3 aabbShift = (aabbMax - aabbMin) * 0.5; const osg::Vec2f tileShift = osg::Vec2f(heightfield.mMinX, heightfield.mMinY) * scale; - const osg::Vec2f localShift = aabbShift + tileShift; + const osg::Vec2f localShift + = osg::Vec2f(static_cast(aabbShift.x()), static_cast(aabbShift.y())) + tileShift; const float cellSize = static_cast(heightfield.mCellSize); const osg::Vec3f cellShift(heightfield.mCellPosition.x() * cellSize, heightfield.mCellPosition.y() * cellSize, (heightfield.mMinHeight + heightfield.mMaxHeight) * 0.5f); @@ -238,7 +238,8 @@ namespace DetourNavigator const float stepSize = getHeightfieldScale(cellSize, size); const int halfCellSize = cellSize / 2; const auto local = [&](float v, float offset) { return (v - offset + halfCellSize) / stepSize; }; - const auto index = [&](float v, int add) { return std::clamp(static_cast(v) + add, 0, size); }; + const auto index + = [&](float v, int add) { return std::clamp(static_cast(v) + add, 0, static_cast(size)); }; const std::size_t minX = index(std::round(local(intersection->mMin.x(), shift.x())), -1); const std::size_t minY = index(std::round(local(intersection->mMin.y(), shift.y())), -1); const std::size_t maxX = index(std::round(local(intersection->mMax.x(), shift.x())), 1); diff --git a/components/detournavigator/recastparams.hpp b/components/detournavigator/recastparams.hpp index 74af132bf6..0a99ad58f2 100644 --- a/components/detournavigator/recastparams.hpp +++ b/components/detournavigator/recastparams.hpp @@ -21,7 +21,7 @@ namespace DetourNavigator switch (agentBounds.mShapeType) { case CollisionShapeType::Aabb: - return std::max(agentBounds.mHalfExtents.x(), agentBounds.mHalfExtents.y()) * std::sqrt(2); + return std::max(agentBounds.mHalfExtents.x(), agentBounds.mHalfExtents.y()) * std::sqrt(2.0f); case CollisionShapeType::RotatingBox: return agentBounds.mHalfExtents.x(); case CollisionShapeType::Cylinder: diff --git a/components/detournavigator/settingsutils.hpp b/components/detournavigator/settingsutils.hpp index c9d8665d51..8e368ab46e 100644 --- a/components/detournavigator/settingsutils.hpp +++ b/components/detournavigator/settingsutils.hpp @@ -79,8 +79,10 @@ namespace DetourNavigator inline TileBounds makeTileBounds(const RecastSettings& settings, const TilePosition& tilePosition) { return TileBounds{ - osg::Vec2f(tilePosition.x(), tilePosition.y()) * getTileSize(settings), - osg::Vec2f(tilePosition.x() + 1, tilePosition.y() + 1) * getTileSize(settings), + osg::Vec2f(static_cast(tilePosition.x()), static_cast(tilePosition.y())) + * getTileSize(settings), + osg::Vec2f(static_cast(tilePosition.x() + 1), static_cast(tilePosition.y() + 1)) + * getTileSize(settings), }; } @@ -97,7 +99,7 @@ namespace DetourNavigator inline float getMaxNavmeshAreaRadius(const Settings& settings) { - return std::floor(std::sqrt(settings.mMaxTilesNumber / osg::PI)) - 1; + return std::floor(std::sqrt(settings.mMaxTilesNumber / osg::PIf)) - 1; } // Returns tile bounds in real coordinates diff --git a/components/detournavigator/tilebounds.hpp b/components/detournavigator/tilebounds.hpp index ef1181307c..8364f433e6 100644 --- a/components/detournavigator/tilebounds.hpp +++ b/components/detournavigator/tilebounds.hpp @@ -56,8 +56,10 @@ namespace DetourNavigator inline TileBounds maxCellTileBounds(const osg::Vec2i& position, int size) { - return TileBounds{ osg::Vec2f(position.x(), position.y()) * size, - osg::Vec2f(position.x() + 1, position.y() + 1) * size }; + return TileBounds{ osg::Vec2f(static_cast(position.x()), static_cast(position.y())) + * static_cast(size), + osg::Vec2f(static_cast(position.x() + 1), static_cast(position.y() + 1)) + * static_cast(size) }; } inline TileBounds makeObjectTileBounds(const btCollisionShape& shape, const btTransform& transform) diff --git a/components/esm/util.hpp b/components/esm/util.hpp index ae756baf6a..5015b3059d 100644 --- a/components/esm/util.hpp +++ b/components/esm/util.hpp @@ -29,7 +29,7 @@ namespace ESM inline ESM::ExteriorCellLocation positionToExteriorCellLocation( float x, float y, ESM::RefId worldspaceId = ESM::Cell::sDefaultWorldspaceId) { - const float cellSize = getCellSize(worldspaceId); + const float cellSize = static_cast(getCellSize(worldspaceId)); return { static_cast(std::floor(x / cellSize)), static_cast(std::floor(y / cellSize)), worldspaceId }; } diff --git a/components/esm3/aisequence.cpp b/components/esm3/aisequence.cpp index c316c2db86..ba28ca3e92 100644 --- a/components/esm3/aisequence.cpp +++ b/components/esm3/aisequence.cpp @@ -84,7 +84,7 @@ namespace ESM // The exact value of mDuration only matters for repeating packages. // Previously mRemainingDuration could be negative even when mDuration was 0. Checking for > 0 should // fix old saves. - mData.mDuration = std::max(mRemainingDuration > 0, mRemainingDuration); + mData.mDuration = static_cast(std::max(mRemainingDuration > 0, mRemainingDuration)); } } @@ -121,7 +121,7 @@ namespace ESM // The exact value of mDuration only matters for repeating packages. // Previously mRemainingDuration could be negative even when mDuration was 0. Checking for > 0 should // fix old saves. - mData.mDuration = std::max(mRemainingDuration > 0, mRemainingDuration); + mData.mDuration = static_cast(std::max(mRemainingDuration > 0, mRemainingDuration)); } } diff --git a/components/esm3/loadmgef.cpp b/components/esm3/loadmgef.cpp index 3ff725fcf7..fd75d071cb 100644 --- a/components/esm3/loadmgef.cpp +++ b/components/esm3/loadmgef.cpp @@ -141,11 +141,12 @@ namespace ESM effects[MagicEffect::Effects::DisintegrateArmor] = MagicEffect::Effects::Sanctuary; effects[MagicEffect::Effects::DisintegrateWeapon] = MagicEffect::Effects::Sanctuary; - for (int i = MagicEffect::Effects::DrainAttribute; i <= MagicEffect::Effects::DamageSkill; ++i) + for (short i = MagicEffect::Effects::DrainAttribute; i <= MagicEffect::Effects::DamageSkill; ++i) effects[i] = MagicEffect::Effects::ResistMagicka; - for (int i = MagicEffect::Effects::AbsorbAttribute; i <= MagicEffect::Effects::AbsorbSkill; ++i) + for (short i = MagicEffect::Effects::AbsorbAttribute; i <= MagicEffect::Effects::AbsorbSkill; ++i) effects[i] = MagicEffect::Effects::ResistMagicka; - for (int i = MagicEffect::Effects::WeaknessToFire; i <= MagicEffect::Effects::WeaknessToNormalWeapons; ++i) + for (short i = MagicEffect::Effects::WeaknessToFire; i <= MagicEffect::Effects::WeaknessToNormalWeapons; + ++i) effects[i] = MagicEffect::Effects::ResistMagicka; effects[MagicEffect::Effects::Burden] = MagicEffect::Effects::ResistMagicka; @@ -154,7 +155,7 @@ namespace ESM effects[MagicEffect::Effects::Blind] = MagicEffect::Effects::ResistMagicka; effects[MagicEffect::Effects::Sound] = MagicEffect::Effects::ResistMagicka; - for (int i = 0; i < 2; ++i) + for (short i = 0; i < 2; ++i) { effects[MagicEffect::Effects::CalmHumanoid + i] = MagicEffect::Effects::ResistMagicka; effects[MagicEffect::Effects::FrenzyHumanoid + i] = MagicEffect::Effects::ResistMagicka; @@ -194,11 +195,11 @@ namespace ESM static std::map effects; if (effects.empty()) { - for (int i = DrainAttribute; i <= DamageSkill; ++i) + for (short i = DrainAttribute; i <= DamageSkill; ++i) effects[i] = WeaknessToMagicka; - for (int i = AbsorbAttribute; i <= AbsorbSkill; ++i) + for (short i = AbsorbAttribute; i <= AbsorbSkill; ++i) effects[i] = WeaknessToMagicka; - for (int i = WeaknessToFire; i <= WeaknessToNormalWeapons; ++i) + for (short i = WeaknessToFire; i <= WeaknessToNormalWeapons; ++i) effects[i] = WeaknessToMagicka; effects[Burden] = WeaknessToMagicka; @@ -207,7 +208,7 @@ namespace ESM effects[Blind] = WeaknessToMagicka; effects[Sound] = WeaknessToMagicka; - for (int i = 0; i < 2; ++i) + for (short i = 0; i < 2; ++i) { effects[CalmHumanoid + i] = WeaknessToMagicka; effects[FrenzyHumanoid + i] = WeaknessToMagicka; @@ -541,7 +542,7 @@ namespace ESM { std::map map; for (size_t i = 0; i < strings.size(); i++) - map[strings[i]] = i; + map[strings[i]] = static_cast(i); return map; } diff --git a/components/esm3/loadmgef.hpp b/components/esm3/loadmgef.hpp index 25ec7d0655..9f028e4bdc 100644 --- a/components/esm3/loadmgef.hpp +++ b/components/esm3/loadmgef.hpp @@ -117,7 +117,7 @@ namespace ESM osg::Vec4f getColor() const; - enum Effects + enum Effects : short { WaterBreathing = 0, SwiftSwim = 1, diff --git a/components/esmterrain/storage.cpp b/components/esmterrain/storage.cpp index 73030ab96a..4ff61dc00a 100644 --- a/components/esmterrain/storage.cpp +++ b/components/esmterrain/storage.cpp @@ -130,11 +130,11 @@ namespace ESMTerrain osg::ref_ptr land = getLand(ESM::ExteriorCellLocation(cellX, cellY, worldspace)); const ESM::LandData* data = land ? land->getData(ESM::Land::DATA_VHGT) : nullptr; const int landSize = ESM::getLandSize(worldspace); - int startRow = (origin.x() - cellX) * landSize; - int startColumn = (origin.y() - cellY) * landSize; + int startRow = static_cast((origin.x() - cellX) * landSize); + int startColumn = static_cast((origin.y() - cellY) * landSize); - int endRow = startRow + size * (landSize - 1) + 1; - int endColumn = startColumn + size * (landSize - 1) + 1; + int endRow = static_cast(startRow + size * (landSize - 1) + 1); + int endColumn = static_cast(startColumn + size * (landSize - 1) + 1); if (data) { @@ -283,8 +283,8 @@ namespace ESMTerrain const auto handleSample = [&](std::size_t cellShiftX, std::size_t cellShiftY, std::size_t row, std::size_t col, std::size_t vertX, std::size_t vertY) { - const int cellX = startCellX + cellShiftX; - const int cellY = startCellY + cellShiftY; + const int cellX = startCellX + static_cast(cellShiftX); + const int cellY = startCellY + static_cast(cellShiftY); const std::pair cell{ cellX, cellY }; const ESM::ExteriorCellLocation cellLocation(cellX, cellY, worldspace); @@ -311,7 +311,7 @@ namespace ESMTerrain if (heightData != nullptr) height = heightData->getHeights()[col * cellSize + row]; if (alteration) - height += getAlteredHeight(col, row); + height += getAlteredHeight(static_cast(col), static_cast(row)); const std::size_t vertIndex = vertX * numVerts + vertY; @@ -325,7 +325,7 @@ namespace ESMTerrain if (normalData != nullptr) { - for (std::size_t i = 0; i < 3; ++i) + for (unsigned short i = 0; i < 3; ++i) normal[i] = normalData->getNormals()[srcArrayIndex + i]; normal.normalize(); @@ -333,11 +333,11 @@ namespace ESMTerrain // Normals apparently don't connect seamlessly between cells if (col == cellSize - 1 || row == cellSize - 1) - fixNormal(normal, cellLocation, col, row, cache); + fixNormal(normal, cellLocation, static_cast(col), static_cast(row), cache); // some corner normals appear to be complete garbage (z < 0) if ((row == 0 || row == cellSize - 1) && (col == 0 || col == cellSize - 1)) - averageNormal(normal, cellLocation, col, row, cache); + averageNormal(normal, cellLocation, static_cast(col), static_cast(row), cache); assert(normal.z() > 0); @@ -346,16 +346,16 @@ namespace ESMTerrain osg::Vec4ub color(255, 255, 255, 255); if (colourData != nullptr) - for (std::size_t i = 0; i < 3; ++i) + for (unsigned short i = 0; i < 3; ++i) color[i] = colourData->getColors()[srcArrayIndex + i]; // Does nothing by default, override in OpenMW-CS if (alteration) - adjustColor(col, row, heightData, color); + adjustColor(static_cast(col), static_cast(row), heightData, color); // Unlike normals, colors mostly connect seamlessly between cells, but not always... if (col == cellSize - 1 || row == cellSize - 1) - fixColour(color, cellLocation, col, row, cache); + fixColour(color, cellLocation, static_cast(col), static_cast(row), cache); colours[vertIndex] = color; }; @@ -445,7 +445,7 @@ namespace ESMTerrain unsigned char* const baseBlendmap = getOrCreateBlendmap(ESM::FormId::fromUint32(ltex.base.formId)); int starty = (static_cast(sample.mDstCol) - 1) * quadSize; - int startx = sample.mDstRow * quadSize; + int startx = static_cast(sample.mDstRow) * quadSize; for (int y = std::max(0, starty + 1); y <= starty + quadSize && y < blendmapSize; ++y) { unsigned char* const row = baseBlendmap + (blendmapSize - y - 1) * blendmapSize; @@ -465,9 +465,9 @@ namespace ESMTerrain { continue; } - int index = (blendmapSize - starty - y - 1) * blendmapSize + startx + x; - int delta = std::clamp(static_cast(v.opacity * 255), 0, 255); - baseBlendmap[index] = std::max(0, baseBlendmap[index] - delta); + size_t index = static_cast((blendmapSize - starty - y - 1) * blendmapSize + startx + x); + auto delta = static_cast(std::clamp(static_cast(v.opacity * 255.f), 0, 255)); + baseBlendmap[index] = std::max(0, baseBlendmap[index] - delta); layerBlendmap[index] = delta; } } @@ -567,7 +567,7 @@ namespace ESMTerrain float Storage::getHeightAt(const osg::Vec3f& worldPos, ESM::RefId worldspace) { - const float cellSize = ESM::getCellSize(worldspace); + const float cellSize = static_cast(ESM::getCellSize(worldspace)); int cellX = static_cast(std::floor(worldPos.x() / cellSize)); int cellY = static_cast(std::floor(worldPos.y() / cellSize)); @@ -645,7 +645,8 @@ namespace ESMTerrain */ // Solve plane equation for z - return (-plane.getNormal().x() * nX - plane.getNormal().y() * nY - plane[3]) / plane.getNormal().z() * cellSize; + return static_cast( + (-plane.getNormal().x() * nX - plane.getNormal().y() * nY - plane[3]) / plane.getNormal().z() * cellSize); } const LandObject* Storage::getLand(ESM::ExteriorCellLocation cellLocation, LandCache& cache) diff --git a/components/fallback/validate.cpp b/components/fallback/validate.cpp index 571f0f9b19..6c289c873d 100644 --- a/components/fallback/validate.cpp +++ b/components/fallback/validate.cpp @@ -5,14 +5,18 @@ #include #include -static const std::set allowedKeysInt = { "LightAttenuation_LinearMethod", - "LightAttenuation_OutQuadInLin", "LightAttenuation_QuadraticMethod", "LightAttenuation_UseConstant", - "LightAttenuation_UseLinear", "LightAttenuation_UseQuadratic", "Water_MaxNumberRipples", "Water_NearWaterRadius", - "Water_NearWaterPoints", "Water_RippleFrameCount", "Water_SurfaceTileCount", "Water_SurfaceFrameCount", - "Weather_Clear_Using_Precip", "Weather_Cloudy_Using_Precip", "Weather_Foggy_Using_Precip", - "Weather_Overcast_Using_Precip", "Weather_Rain_Using_Precip", "Weather_Thunderstorm_Using_Precip", - "Weather_Ashstorm_Using_Precip", "Weather_Blight_Using_Precip", "Weather_Snow_Using_Precip", - "Weather_Blizzard_Using_Precip", "Weather_Rain_Ripples", "Weather_Snow_Ripples", "Weather_Timescale_Clouds" }; +static const std::set allowedKeysInt + = { "LightAttenuation_LinearMethod", "LightAttenuation_OutQuadInLin", "LightAttenuation_QuadraticMethod", + "LightAttenuation_UseConstant", "LightAttenuation_UseLinear", "LightAttenuation_UseQuadratic", + "Water_MaxNumberRipples", "Water_NearWaterRadius", "Water_NearWaterPoints", "Water_RippleFrameCount", + "Water_SurfaceTileCount", "Water_SurfaceFrameCount", "Weather_Ashstorm_Max_Raindrops", + "Weather_Blight_Max_Raindrops", "Weather_Blizzard_Max_Raindrops", "Weather_Clear_Max_Raindrops", + "Weather_Cloudy_Max_Raindrops", "Weather_Foggy_Max_Raindrops", "Weather_Overcast_Max_Raindrops", + "Weather_Rain_Max_Raindrops", "Weather_Snow_Max_Raindrops", "Weather_Thunderstorm_Max_Raindrops", + "Weather_Clear_Using_Precip", "Weather_Cloudy_Using_Precip", "Weather_Foggy_Using_Precip", + "Weather_Overcast_Using_Precip", "Weather_Rain_Using_Precip", "Weather_Thunderstorm_Using_Precip", + "Weather_Ashstorm_Using_Precip", "Weather_Blight_Using_Precip", "Weather_Snow_Using_Precip", + "Weather_Blizzard_Using_Precip", "Weather_Rain_Ripples", "Weather_Snow_Ripples", "Weather_Timescale_Clouds" }; static const std::set allowedKeysFloat = { "General_Werewolf_FOV", "Inventory_DirectionalAmbientB", "Inventory_DirectionalAmbientG", "Inventory_DirectionalAmbientR", "Inventory_DirectionalDiffuseB", @@ -32,34 +36,32 @@ static const std::set allowedKeysFloat = { "General_Werewolf_F "Weather_Ambient_Post-Sunrise_Time", "Weather_Ambient_Post-Sunset_Time", "Weather_Ambient_Pre-Sunrise_Time", "Weather_Ambient_Pre-Sunset_Time", "Weather_Ashstorm_Clouds_Maximum_Percent", "Weather_Ashstorm_Cloud_Speed", "Weather_Ashstorm_Flash_Decrement", "Weather_Ashstorm_Glare_View", "Weather_Ashstorm_Land_Fog_Day_Depth", - "Weather_Ashstorm_Land_Fog_Night_Depth", "Weather_Ashstorm_Max_Raindrops", "Weather_Ashstorm_Rain_Diameter", - "Weather_Ashstorm_Rain_Entrance_Speed", "Weather_Ashstorm_Rain_Height_Max", "Weather_Ashstorm_Rain_Height_Min", - "Weather_Ashstorm_Rain_Threshold", "Weather_Ashstorm_Thunder_Frequency", "Weather_Ashstorm_Thunder_Threshold", - "Weather_Ashstorm_Transition_Delta", "Weather_Ashstorm_Wind_Speed", "Weather_Blight_Clouds_Maximum_Percent", - "Weather_Blight_Cloud_Speed", "Weather_Blight_Flash_Decrement", "Weather_Blight_Glare_View", - "Weather_Blight_Land_Fog_Day_Depth", "Weather_Blight_Land_Fog_Night_Depth", "Weather_Blight_Max_Raindrops", - "Weather_Blight_Rain_Diameter", "Weather_Blight_Rain_Entrance_Speed", "Weather_Blight_Rain_Height_Max", - "Weather_Blight_Rain_Height_Min", "Weather_Blight_Rain_Threshold", "Weather_Blight_Thunder_Frequency", - "Weather_Blight_Thunder_Threshold", "Weather_Blight_Transition_Delta", "Weather_Blight_Wind_Speed", - "Weather_Blizzard_Clouds_Maximum_Percent", "Weather_Blizzard_Cloud_Speed", "Weather_Blizzard_Flash_Decrement", - "Weather_Blizzard_Glare_View", "Weather_Blizzard_Land_Fog_Day_Depth", "Weather_Blizzard_Land_Fog_Night_Depth", - "Weather_Blizzard_Max_Raindrops", "Weather_Blizzard_Rain_Diameter", "Weather_Blizzard_Rain_Entrance_Speed", + "Weather_Ashstorm_Land_Fog_Night_Depth", "Weather_Ashstorm_Rain_Diameter", "Weather_Ashstorm_Rain_Entrance_Speed", + "Weather_Ashstorm_Rain_Height_Max", "Weather_Ashstorm_Rain_Height_Min", "Weather_Ashstorm_Rain_Threshold", + "Weather_Ashstorm_Thunder_Frequency", "Weather_Ashstorm_Thunder_Threshold", "Weather_Ashstorm_Transition_Delta", + "Weather_Ashstorm_Wind_Speed", "Weather_Blight_Clouds_Maximum_Percent", "Weather_Blight_Cloud_Speed", + "Weather_Blight_Flash_Decrement", "Weather_Blight_Glare_View", "Weather_Blight_Land_Fog_Day_Depth", + "Weather_Blight_Land_Fog_Night_Depth", "Weather_Blight_Rain_Diameter", "Weather_Blight_Rain_Entrance_Speed", + "Weather_Blight_Rain_Height_Max", "Weather_Blight_Rain_Height_Min", "Weather_Blight_Rain_Threshold", + "Weather_Blight_Thunder_Frequency", "Weather_Blight_Thunder_Threshold", "Weather_Blight_Transition_Delta", + "Weather_Blight_Wind_Speed", "Weather_Blizzard_Clouds_Maximum_Percent", "Weather_Blizzard_Cloud_Speed", + "Weather_Blizzard_Flash_Decrement", "Weather_Blizzard_Glare_View", "Weather_Blizzard_Land_Fog_Day_Depth", + "Weather_Blizzard_Land_Fog_Night_Depth", "Weather_Blizzard_Rain_Diameter", "Weather_Blizzard_Rain_Entrance_Speed", "Weather_Blizzard_Rain_Height_Max", "Weather_Blizzard_Rain_Height_Min", "Weather_Blizzard_Rain_Threshold", "Weather_Blizzard_Thunder_Frequency", "Weather_Blizzard_Thunder_Threshold", "Weather_Blizzard_Transition_Delta", "Weather_Blizzard_Wind_Speed", "Weather_Clear_Clouds_Maximum_Percent", "Weather_Clear_Cloud_Speed", "Weather_Clear_Flash_Decrement", "Weather_Clear_Glare_View", "Weather_Clear_Land_Fog_Day_Depth", - "Weather_Clear_Land_Fog_Night_Depth", "Weather_Clear_Max_Raindrops", "Weather_Clear_Rain_Diameter", - "Weather_Clear_Rain_Entrance_Speed", "Weather_Clear_Rain_Height_Max", "Weather_Clear_Rain_Height_Min", - "Weather_Clear_Rain_Threshold", "Weather_Clear_Thunder_Frequency", "Weather_Clear_Thunder_Threshold", - "Weather_Clear_Transition_Delta", "Weather_Clear_Wind_Speed", "Weather_Cloudy_Clouds_Maximum_Percent", - "Weather_Cloudy_Cloud_Speed", "Weather_Cloudy_Flash_Decrement", "Weather_Cloudy_Glare_View", - "Weather_Cloudy_Land_Fog_Day_Depth", "Weather_Cloudy_Land_Fog_Night_Depth", "Weather_Cloudy_Max_Raindrops", - "Weather_Cloudy_Rain_Diameter", "Weather_Cloudy_Rain_Entrance_Speed", "Weather_Cloudy_Rain_Height_Max", - "Weather_Cloudy_Rain_Height_Min", "Weather_Cloudy_Rain_Threshold", "Weather_Cloudy_Thunder_Frequency", - "Weather_Cloudy_Thunder_Threshold", "Weather_Cloudy_Transition_Delta", "Weather_Cloudy_Wind_Speed", - "Weather_Foggy_Clouds_Maximum_Percent", "Weather_Foggy_Cloud_Speed", "Weather_Foggy_Flash_Decrement", - "Weather_Foggy_Glare_View", "Weather_Foggy_Land_Fog_Day_Depth", "Weather_Foggy_Land_Fog_Night_Depth", - "Weather_Foggy_Max_Raindrops", "Weather_Foggy_Rain_Diameter", "Weather_Foggy_Rain_Entrance_Speed", + "Weather_Clear_Land_Fog_Night_Depth", "Weather_Clear_Rain_Diameter", "Weather_Clear_Rain_Entrance_Speed", + "Weather_Clear_Rain_Height_Max", "Weather_Clear_Rain_Height_Min", "Weather_Clear_Rain_Threshold", + "Weather_Clear_Thunder_Frequency", "Weather_Clear_Thunder_Threshold", "Weather_Clear_Transition_Delta", + "Weather_Clear_Wind_Speed", "Weather_Cloudy_Clouds_Maximum_Percent", "Weather_Cloudy_Cloud_Speed", + "Weather_Cloudy_Flash_Decrement", "Weather_Cloudy_Glare_View", "Weather_Cloudy_Land_Fog_Day_Depth", + "Weather_Cloudy_Land_Fog_Night_Depth", "Weather_Cloudy_Rain_Diameter", "Weather_Cloudy_Rain_Entrance_Speed", + "Weather_Cloudy_Rain_Height_Max", "Weather_Cloudy_Rain_Height_Min", "Weather_Cloudy_Rain_Threshold", + "Weather_Cloudy_Thunder_Frequency", "Weather_Cloudy_Thunder_Threshold", "Weather_Cloudy_Transition_Delta", + "Weather_Cloudy_Wind_Speed", "Weather_Foggy_Clouds_Maximum_Percent", "Weather_Foggy_Cloud_Speed", + "Weather_Foggy_Flash_Decrement", "Weather_Foggy_Glare_View", "Weather_Foggy_Land_Fog_Day_Depth", + "Weather_Foggy_Land_Fog_Night_Depth", "Weather_Foggy_Rain_Diameter", "Weather_Foggy_Rain_Entrance_Speed", "Weather_Foggy_Rain_Height_Max", "Weather_Foggy_Rain_Height_Min", "Weather_Foggy_Rain_Threshold", "Weather_Foggy_Thunder_Frequency", "Weather_Foggy_Thunder_Threshold", "Weather_Foggy_Transition_Delta", "Weather_Foggy_Wind_Speed", "Weather_Fog_Post-Sunrise_Time", "Weather_Fog_Post-Sunset_Time", @@ -67,19 +69,18 @@ static const std::set allowedKeysFloat = { "General_Werewolf_F "Weather_Maximum_Time_Between_Environmental_Sounds", "Weather_Minimum_Time_Between_Environmental_Sounds", "Weather_Overcast_Clouds_Maximum_Percent", "Weather_Overcast_Cloud_Speed", "Weather_Overcast_Flash_Decrement", "Weather_Overcast_Glare_View", "Weather_Overcast_Land_Fog_Day_Depth", "Weather_Overcast_Land_Fog_Night_Depth", - "Weather_Overcast_Max_Raindrops", "Weather_Overcast_Rain_Diameter", "Weather_Overcast_Rain_Entrance_Speed", - "Weather_Overcast_Rain_Height_Max", "Weather_Overcast_Rain_Height_Min", "Weather_Overcast_Rain_Threshold", - "Weather_Overcast_Thunder_Frequency", "Weather_Overcast_Thunder_Threshold", "Weather_Overcast_Transition_Delta", - "Weather_Overcast_Wind_Speed", "Weather_Precip_Gravity", "Weather_Rain_Clouds_Maximum_Percent", - "Weather_Rain_Cloud_Speed", "Weather_Rain_Flash_Decrement", "Weather_Rain_Glare_View", - "Weather_Rain_Land_Fog_Day_Depth", "Weather_Rain_Land_Fog_Night_Depth", "Weather_Rain_Max_Raindrops", - "Weather_Rain_Rain_Diameter", "Weather_Rain_Rain_Entrance_Speed", "Weather_Rain_Rain_Height_Max", - "Weather_Rain_Rain_Height_Min", "Weather_Rain_Rain_Threshold", "Weather_Rain_Thunder_Frequency", - "Weather_Rain_Thunder_Threshold", "Weather_Rain_Transition_Delta", "Weather_Rain_Wind_Speed", - "Weather_Sky_Post-Sunrise_Time", "Weather_Sky_Post-Sunset_Time", "Weather_Sky_Pre-Sunrise_Time", - "Weather_Sky_Pre-Sunset_Time", "Weather_Snow_Clouds_Maximum_Percent", "Weather_Snow_Cloud_Speed", - "Weather_Snow_Flash_Decrement", "Weather_Snow_Glare_View", "Weather_Snow_Land_Fog_Day_Depth", - "Weather_Snow_Land_Fog_Night_Depth", "Weather_Snow_Max_Raindrops", "Weather_Snow_Rain_Diameter", + "Weather_Overcast_Rain_Diameter", "Weather_Overcast_Rain_Entrance_Speed", "Weather_Overcast_Rain_Height_Max", + "Weather_Overcast_Rain_Height_Min", "Weather_Overcast_Rain_Threshold", "Weather_Overcast_Thunder_Frequency", + "Weather_Overcast_Thunder_Threshold", "Weather_Overcast_Transition_Delta", "Weather_Overcast_Wind_Speed", + "Weather_Precip_Gravity", "Weather_Rain_Clouds_Maximum_Percent", "Weather_Rain_Cloud_Speed", + "Weather_Rain_Flash_Decrement", "Weather_Rain_Glare_View", "Weather_Rain_Land_Fog_Day_Depth", + "Weather_Rain_Land_Fog_Night_Depth", "Weather_Rain_Rain_Diameter", "Weather_Rain_Rain_Entrance_Speed", + "Weather_Rain_Rain_Height_Max", "Weather_Rain_Rain_Height_Min", "Weather_Rain_Rain_Threshold", + "Weather_Rain_Thunder_Frequency", "Weather_Rain_Thunder_Threshold", "Weather_Rain_Transition_Delta", + "Weather_Rain_Wind_Speed", "Weather_Sky_Post-Sunrise_Time", "Weather_Sky_Post-Sunset_Time", + "Weather_Sky_Pre-Sunrise_Time", "Weather_Sky_Pre-Sunset_Time", "Weather_Snow_Clouds_Maximum_Percent", + "Weather_Snow_Cloud_Speed", "Weather_Snow_Flash_Decrement", "Weather_Snow_Glare_View", + "Weather_Snow_Land_Fog_Day_Depth", "Weather_Snow_Land_Fog_Night_Depth", "Weather_Snow_Rain_Diameter", "Weather_Snow_Rain_Entrance_Speed", "Weather_Snow_Rain_Height_Max", "Weather_Snow_Rain_Height_Min", "Weather_Snow_Rain_Threshold", "Weather_Snow_Thunder_Frequency", "Weather_Snow_Thunder_Threshold", "Weather_Snow_Transition_Delta", "Weather_Snow_Wind_Speed", "Weather_Stars_Fading_Duration", @@ -89,11 +90,11 @@ static const std::set allowedKeysFloat = { "General_Werewolf_F "Weather_Sunset_Duration", "Weather_Sunset_Time", "Weather_Thunderstorm_Clouds_Maximum_Percent", "Weather_Thunderstorm_Cloud_Speed", "Weather_Thunderstorm_Flash_Decrement", "Weather_Thunderstorm_Glare_View", "Weather_Thunderstorm_Land_Fog_Day_Depth", "Weather_Thunderstorm_Land_Fog_Night_Depth", - "Weather_Thunderstorm_Max_Raindrops", "Weather_Thunderstorm_Rain_Diameter", - "Weather_Thunderstorm_Rain_Entrance_Speed", "Weather_Thunderstorm_Rain_Height_Max", - "Weather_Thunderstorm_Rain_Height_Min", "Weather_Thunderstorm_Rain_Threshold", - "Weather_Thunderstorm_Thunder_Frequency", "Weather_Thunderstorm_Thunder_Threshold", - "Weather_Thunderstorm_Transition_Delta", "Weather_Thunderstorm_Wind_Speed" }; + "Weather_Thunderstorm_Rain_Diameter", "Weather_Thunderstorm_Rain_Entrance_Speed", + "Weather_Thunderstorm_Rain_Height_Max", "Weather_Thunderstorm_Rain_Height_Min", + "Weather_Thunderstorm_Rain_Threshold", "Weather_Thunderstorm_Thunder_Frequency", + "Weather_Thunderstorm_Thunder_Threshold", "Weather_Thunderstorm_Transition_Delta", + "Weather_Thunderstorm_Wind_Speed" }; static const std::set allowedKeysNonNumeric = { "Blood_Model_0", "Blood_Model_1", "Blood_Model_2", "FontColor_color_active", "FontColor_color_active_over", "FontColor_color_active_pressed", "FontColor_color_answer", diff --git a/components/files/configurationmanager.cpp b/components/files/configurationmanager.cpp index 7676d4d386..66904de130 100644 --- a/components/files/configurationmanager.cpp +++ b/components/files/configurationmanager.cpp @@ -22,9 +22,9 @@ namespace Files namespace { #if defined(_WIN32) || defined(__WINDOWS__) - constexpr auto applicationName = "OpenMW"; + constexpr auto sApplicationName = "OpenMW"; #else - constexpr auto applicationName = "openmw"; + constexpr auto sApplicationName = "openmw"; #endif using GetPath = const std::filesystem::path& (Files::FixedPath<>::*)() const; @@ -37,7 +37,7 @@ namespace Files } ConfigurationManager::ConfigurationManager(bool silent) - : mFixedPath(applicationName) + : mFixedPath(sApplicationName) , mSilent(silent) { // Initialize with fixed paths, will be overridden in `readConfiguration`. diff --git a/components/files/fixedpath.hpp b/components/files/fixedpath.hpp index 76e8574fa7..4496e83899 100644 --- a/components/files/fixedpath.hpp +++ b/components/files/fixedpath.hpp @@ -56,10 +56,10 @@ namespace Files /** * \brief Path constructor. * - * \param [in] application_name - Name of the application + * \param [in] applicationName - Name of the application */ - FixedPath(const std::string& application_name) - : mPath(application_name + "/") + FixedPath(const std::string& applicationName) + : mPath(applicationName + "/") , mUserConfigPath(mPath.getUserConfigPath()) , mUserDataPath(mPath.getUserDataPath()) , mGlobalConfigPath(mPath.getGlobalConfigPath()) diff --git a/components/files/hash.cpp b/components/files/hash.cpp index 1f1839ed0c..2f5751ac97 100644 --- a/components/files/hash.cpp +++ b/components/files/hash.cpp @@ -1,6 +1,6 @@ #include "hash.hpp" -#include +#include #include #include diff --git a/components/files/memorystream.hpp b/components/files/memorystream.hpp index bd226beb9a..964e3b6f4b 100644 --- a/components/files/memorystream.hpp +++ b/components/files/memorystream.hpp @@ -19,7 +19,7 @@ namespace Files pos_type seekoff(off_type off, std::ios_base::seekdir dir, std::ios_base::openmode which) override { if (dir == std::ios_base::cur) - gbump(off); + setg(bufferStart, gptr() + off, bufferEnd); else setg(bufferStart, (dir == std::ios_base::beg ? bufferStart : bufferEnd) + off, bufferEnd); diff --git a/components/fontloader/fontloader.cpp b/components/fontloader/fontloader.cpp index 14a3baa2e9..5a1198a54b 100644 --- a/components/fontloader/fontloader.cpp +++ b/components/fontloader/fontloader.cpp @@ -591,7 +591,7 @@ namespace Gui // Underscore, use for NotDefined marker (used for glyphs not existing in the font) additional.emplace(95, MyGUI::FontCodeType::NotDefined); - for (int i = 0; i < 256; i++) + for (unsigned i = 0; i < 256; i++) { float x1 = data[i].top_left.x * width; float y1 = data[i].top_left.y * height; @@ -599,7 +599,7 @@ namespace Gui float h = data[i].bottom_left.y * height - y1; ToUTF8::Utf8Encoder encoder(mEncoding); - unsigned long unicodeVal = getUnicode(i, encoder, mEncoding); + unsigned long unicodeVal = getUnicode(static_cast(i), encoder, mEncoding); const std::string coord = MyGUI::utility::toString(x1) + " " + MyGUI::utility::toString(y1) + " " + MyGUI::utility::toString(w) + " " + MyGUI::utility::toString(h); float advance = data[i].width + data[i].kerningRight; diff --git a/components/fx/stateupdater.hpp b/components/fx/stateupdater.hpp index f5921faadf..a3b2755fde 100644 --- a/components/fx/stateupdater.hpp +++ b/components/fx/stateupdater.hpp @@ -110,168 +110,168 @@ namespace Fx void apply(osg::StateSet* stateset, osg::NodeVisitor* nv) override; private: - struct ProjectionMatrix : std140::Mat4 + struct ProjectionMatrix : Std140::Mat4 { static constexpr std::string_view sName = "projectionMatrix"; }; - struct InvProjectionMatrix : std140::Mat4 + struct InvProjectionMatrix : Std140::Mat4 { static constexpr std::string_view sName = "invProjectionMatrix"; }; - struct ViewMatrix : std140::Mat4 + struct ViewMatrix : Std140::Mat4 { static constexpr std::string_view sName = "viewMatrix"; }; - struct PrevViewMatrix : std140::Mat4 + struct PrevViewMatrix : Std140::Mat4 { static constexpr std::string_view sName = "prevViewMatrix"; }; - struct InvViewMatrix : std140::Mat4 + struct InvViewMatrix : Std140::Mat4 { static constexpr std::string_view sName = "invViewMatrix"; }; - struct EyePos : std140::Vec4 + struct EyePos : Std140::Vec4 { static constexpr std::string_view sName = "eyePos"; }; - struct EyeVec : std140::Vec4 + struct EyeVec : Std140::Vec4 { static constexpr std::string_view sName = "eyeVec"; }; - struct AmbientColor : std140::Vec4 + struct AmbientColor : Std140::Vec4 { static constexpr std::string_view sName = "ambientColor"; }; - struct SkyColor : std140::Vec4 + struct SkyColor : Std140::Vec4 { static constexpr std::string_view sName = "skyColor"; }; - struct FogColor : std140::Vec4 + struct FogColor : Std140::Vec4 { static constexpr std::string_view sName = "fogColor"; }; - struct SunColor : std140::Vec4 + struct SunColor : Std140::Vec4 { static constexpr std::string_view sName = "sunColor"; }; - struct SunPos : std140::Vec4 + struct SunPos : Std140::Vec4 { static constexpr std::string_view sName = "sunPos"; }; - struct Resolution : std140::Vec2 + struct Resolution : Std140::Vec2 { static constexpr std::string_view sName = "resolution"; }; - struct RcpResolution : std140::Vec2 + struct RcpResolution : Std140::Vec2 { static constexpr std::string_view sName = "rcpResolution"; }; - struct FogNear : std140::Float + struct FogNear : Std140::Float { static constexpr std::string_view sName = "fogNear"; }; - struct FogFar : std140::Float + struct FogFar : Std140::Float { static constexpr std::string_view sName = "fogFar"; }; - struct Near : std140::Float + struct Near : Std140::Float { static constexpr std::string_view sName = "near"; }; - struct Far : std140::Float + struct Far : Std140::Float { static constexpr std::string_view sName = "far"; }; - struct Fov : std140::Float + struct Fov : Std140::Float { static constexpr std::string_view sName = "fov"; }; - struct GameHour : std140::Float + struct GameHour : Std140::Float { static constexpr std::string_view sName = "gameHour"; }; - struct SunVis : std140::Float + struct SunVis : Std140::Float { static constexpr std::string_view sName = "sunVis"; }; - struct WaterHeight : std140::Float + struct WaterHeight : Std140::Float { static constexpr std::string_view sName = "waterHeight"; }; - struct IsWaterEnabled : std140::Bool + struct IsWaterEnabled : Std140::Bool { static constexpr std::string_view sName = "isWaterEnabled"; }; - struct SimulationTime : std140::Float + struct SimulationTime : Std140::Float { static constexpr std::string_view sName = "simulationTime"; }; - struct DeltaSimulationTime : std140::Float + struct DeltaSimulationTime : Std140::Float { static constexpr std::string_view sName = "deltaSimulationTime"; }; - struct FrameNumber : std140::Int + struct FrameNumber : Std140::Int { static constexpr std::string_view sName = "frameNumber"; }; - struct WindSpeed : std140::Float + struct WindSpeed : Std140::Float { static constexpr std::string_view sName = "windSpeed"; }; - struct WeatherTransition : std140::Float + struct WeatherTransition : Std140::Float { static constexpr std::string_view sName = "weatherTransition"; }; - struct WeatherID : std140::Int + struct WeatherID : Std140::Int { static constexpr std::string_view sName = "weatherID"; }; - struct NextWeatherID : std140::Int + struct NextWeatherID : Std140::Int { static constexpr std::string_view sName = "nextWeatherID"; }; - struct IsUnderwater : std140::Bool + struct IsUnderwater : Std140::Bool { static constexpr std::string_view sName = "isUnderwater"; }; - struct IsInterior : std140::Bool + struct IsInterior : Std140::Bool { static constexpr std::string_view sName = "isInterior"; }; using UniformData - = std140::UBO; diff --git a/components/fx/technique.hpp b/components/fx/technique.hpp index 3db46447dd..1cc24d30cc 100644 --- a/components/fx/technique.hpp +++ b/components/fx/technique.hpp @@ -48,6 +48,10 @@ namespace Fx mPasses.emplace_back(subpass, copyOp); } + ~DispatchNode() = default; + + DispatchNode& operator=(const DispatchNode&) = default; + struct SubPass { SubPass() = default; @@ -70,6 +74,10 @@ namespace Fx if (other.mRenderTexture) mRenderTexture = new osg::Texture2D(*other.mRenderTexture, copyOp); } + + ~SubPass() = default; + + SubPass& operator=(const SubPass&) = default; }; void compile() diff --git a/components/fx/types.hpp b/components/fx/types.hpp index bdb46a76c1..a61e5dbeb7 100644 --- a/components/fx/types.hpp +++ b/components/fx/types.hpp @@ -29,12 +29,12 @@ namespace Fx int scaledHeight = height; if (mWidthRatio) - scaledWidth = width * mWidthRatio.value(); + scaledWidth = static_cast(width * mWidthRatio.value()); else if (mWidth) scaledWidth = mWidth.value(); if (mHeightRatio > 0.f) - scaledHeight = height * mHeightRatio.value(); + scaledHeight = static_cast(height * mHeightRatio.value()); else if (mHeight) scaledHeight = mHeight.value(); @@ -190,7 +190,7 @@ namespace Fx if (arg.isArray()) { for (size_t i = 0; i < arg.getArray().size(); ++i) - uniform->setElement(i, arg.getArray()[i]); + uniform->setElement(static_cast(i), arg.getArray()[i]); uniform->dirty(); } else diff --git a/components/fx/widgets.hpp b/components/fx/widgets.hpp index dd7b9343bf..2f563865d5 100644 --- a/components/fx/widgets.hpp +++ b/components/fx/widgets.hpp @@ -97,8 +97,8 @@ namespace Fx if constexpr (std::is_fundamental_v) { mUniform->template setValue(mValue); - range = mUniform->template getMax() - mUniform->template getMin(); - min = mUniform->template getMin(); + range = static_cast(mUniform->template getMax() - mUniform->template getMin()); + min = static_cast(mUniform->template getMin()); } else { @@ -155,9 +155,9 @@ namespace Fx void notifyMouseWheel(MyGUI::Widget* /*sender*/, int rel) { if (rel > 0) - increment(mUniform->mStep); + increment(static_cast(mUniform->mStep)); else - increment(-mUniform->mStep); + increment(static_cast(-mUniform->mStep)); } void notifyMouseButtonDragged(MyGUI::Widget* /*sender*/, int left, int top, MyGUI::MouseButton id) @@ -169,15 +169,15 @@ namespace Fx // allow finer tuning when shift is pressed constexpr double scaling = 20.0; - T step - = MyGUI::InputManager::getInstance().isShiftPressed() ? mUniform->mStep / scaling : mUniform->mStep; + T step = static_cast( + MyGUI::InputManager::getInstance().isShiftPressed() ? mUniform->mStep / scaling : mUniform->mStep); if (step == 0) { if constexpr (std::is_integral_v) step = 1; else - step = mUniform->mStep; + step = static_cast(mUniform->mStep); } if (delta > 0) @@ -209,9 +209,9 @@ namespace Fx void notifyButtonClicked(MyGUI::Widget* sender) { if (sender == mButtonDecrease) - increment(-mUniform->mStep); + increment(static_cast(-mUniform->mStep)); else if (sender == mButtonIncrease) - increment(mUniform->mStep); + increment(static_cast(mUniform->mStep)); } MyGUI::Button* mButtonDecrease{ nullptr }; diff --git a/components/lua/configuration.cpp b/components/lua/configuration.cpp index cbec2e4abc..5e3cdfe805 100644 --- a/components/lua/configuration.cpp +++ b/components/lua/configuration.cpp @@ -130,7 +130,7 @@ namespace LuaUtil { const ESM::LuaScriptCfg& script = mScripts[id]; if (script.mFlags & flag) - res[id] = script.mInitializationData; + res[static_cast(id)] = script.mInitializationData; } return res; } diff --git a/components/lua/configuration.hpp b/components/lua/configuration.hpp index 4a619019ba..caa8f27c6f 100644 --- a/components/lua/configuration.hpp +++ b/components/lua/configuration.hpp @@ -18,7 +18,7 @@ namespace LuaUtil void init(ESM::LuaScriptsCfg); size_t size() const { return mScripts.size(); } - const ESM::LuaScriptCfg& operator[](int id) const { return mScripts[id]; } + const ESM::LuaScriptCfg& operator[](size_t id) const { return mScripts[id]; } std::optional findId(VFS::Path::NormalizedView path) const; diff --git a/components/lua/luastate.cpp b/components/lua/luastate.cpp index b705dc0f5f..aa2f93d1c7 100644 --- a/components/lua/luastate.cpp +++ b/components/lua/luastate.cpp @@ -15,6 +15,10 @@ #include "scriptscontainer.hpp" #include "utf8.hpp" +#if SOL_IS_ON(SOL_PROPAGATE_EXCEPTIONS) +#error SOL_PROPAGATE_EXCEPTIONS inhibits error checking +#endif + namespace LuaUtil { static VFS::Path::Normalized packageNameToVfsPath(std::string_view packageName, const VFS::Manager& vfs) diff --git a/components/lua/scriptscontainer.cpp b/components/lua/scriptscontainer.cpp index 6f58e72dd0..82eaa47ec9 100644 --- a/components/lua/scriptscontainer.cpp +++ b/components/lua/scriptscontainer.cpp @@ -334,8 +334,8 @@ namespace LuaUtil void ScriptsContainer::insertHandler(std::vector& list, int scriptId, sol::function fn) { + size_t pos = list.size(); list.emplace_back(); - int pos = list.size() - 1; while (pos > 0 && list[pos - 1].mScriptId > scriptId) { list[pos] = std::move(list[pos - 1]); @@ -370,9 +370,9 @@ namespace LuaUtil return; } EventHandlerList& list = it->second; - for (int i = list.size() - 1; i >= 0; --i) + for (size_t i = list.size(); i > 0; --i) { - const Handler& h = list[i]; + const Handler& h = list[i - 1]; try { sol::object res = LuaUtil::call({ this, h.mScriptId }, h.mFn, object); diff --git a/components/lua/serialization.cpp b/components/lua/serialization.cpp index 2a66702589..8a878ae51a 100644 --- a/components/lua/serialization.cpp +++ b/components/lua/serialization.cpp @@ -68,7 +68,7 @@ namespace LuaUtil else { appendType(out, SerializedType::LONG_STRING); - appendValue(out, str.size()); + appendValue(out, static_cast(str.size())); } out.append(str.data(), str.size()); } @@ -83,14 +83,14 @@ namespace LuaUtil assert(!typeName.empty() && typeName.size() <= 64); if (typeName.size() <= 8 && dataSize < 16) { // Compact form: 0b1SSSSTTT. SSSS = dataSize, TTT = (typeName size - 1). - unsigned char t = CUSTOM_COMPACT_FLAG | (dataSize << 3) | (typeName.size() - 1); + auto t = static_cast(CUSTOM_COMPACT_FLAG | (dataSize << 3) | (typeName.size() - 1)); out.push_back(t); } else { // Full form: 0b01TTTTTT + 32bit dataSize. - unsigned char t = CUSTOM_FULL_FLAG | (typeName.size() - 1); + auto t = static_cast(CUSTOM_FULL_FLAG | (typeName.size() - 1)); out.push_back(t); - appendValue(out, dataSize); + appendValue(out, static_cast(dataSize)); } out.append(typeName.data(), typeName.size()); appendData(out, data, dataSize); @@ -156,8 +156,8 @@ namespace LuaUtil { appendType(out, SerializedType::TRANSFORM_M); osg::Matrixf matrix = data.as().mM; - for (size_t i = 0; i < 4; i++) - for (size_t j = 0; j < 4; j++) + for (int i = 0; i < 4; i++) + for (int j = 0; j < 4; j++) appendValue(out, matrix(i, j)); return; } @@ -165,7 +165,7 @@ namespace LuaUtil { appendType(out, SerializedType::TRANSFORM_Q); osg::Quat quat = data.as().mQ; - for (size_t i = 0; i < 4; i++) + for (int i = 0; i < 4; i++) appendValue(out, quat[i]); return; } @@ -304,16 +304,16 @@ namespace LuaUtil throw std::runtime_error("Unexpected end of table during deserialization."); case SerializedType::VEC2: { - float x = getValue(binaryData); - float y = getValue(binaryData); + float x = static_cast(getValue(binaryData)); + float y = static_cast(getValue(binaryData)); sol::stack::push(lua, osg::Vec2f(x, y)); return; } case SerializedType::VEC3: { - float x = getValue(binaryData); - float y = getValue(binaryData); - float z = getValue(binaryData); + float x = static_cast(getValue(binaryData)); + float y = static_cast(getValue(binaryData)); + float z = static_cast(getValue(binaryData)); sol::stack::push(lua, osg::Vec3f(x, y, z)); return; } @@ -322,7 +322,7 @@ namespace LuaUtil osg::Matrixf mat; for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) - mat(i, j) = getValue(binaryData); + mat(i, j) = static_cast(getValue(binaryData)); sol::stack::push(lua, asTransform(mat)); return; } @@ -336,10 +336,10 @@ namespace LuaUtil } case SerializedType::VEC4: { - float x = getValue(binaryData); - float y = getValue(binaryData); - float z = getValue(binaryData); - float w = getValue(binaryData); + float x = static_cast(getValue(binaryData)); + float y = static_cast(getValue(binaryData)); + float z = static_cast(getValue(binaryData)); + float w = static_cast(getValue(binaryData)); sol::stack::push(lua, osg::Vec4f(x, y, z, w)); return; } diff --git a/components/lua/utilpackage.cpp b/components/lua/utilpackage.cpp index c4a8230def..5b82ba2a24 100644 --- a/components/lua/utilpackage.cpp +++ b/components/lua/utilpackage.cpp @@ -247,7 +247,7 @@ namespace LuaUtil color["rgb"] = [](float r, float g, float b) { return Misc::Color(r, g, b, 1); }; color["hex"] = [](std::string_view hex) { return Misc::Color::fromHex(hex); }; color["commaString"] = [](std::string_view str) { - int wrongChars = std::count_if( + auto wrongChars = std::count_if( str.begin(), str.end(), [](unsigned char c) { return !std::isdigit(c) && c != ' ' && c != ','; }); if (wrongChars != 0) diff --git a/components/lua_ui/image.cpp b/components/lua_ui/image.cpp index 45e7843d61..f73f722699 100644 --- a/components/lua_ui/image.cpp +++ b/components/lua_ui/image.cpp @@ -20,9 +20,9 @@ namespace LuaUi // mCoord could be zero, prevent division by 0 // use arbitrary large numbers to prevent performance issues if (mTileSize.width <= 0) - mTileSize.width = 1e7; + mTileSize.width = 10000000; if (mTileSize.height <= 0) - mTileSize.height = 1e7; + mTileSize.height = 10000000; MyGUI::TileRect::_updateView(); } diff --git a/components/lua_ui/layers.hpp b/components/lua_ui/layers.hpp index 50fab79d6a..a5b09df4cf 100644 --- a/components/lua_ui/layers.hpp +++ b/components/lua_ui/layers.hpp @@ -26,7 +26,7 @@ namespace LuaUi { MyGUI::ILayer* p = refresh(); MyGUI::IntSize size = p->getSize(); - return osg::Vec2f(size.width, size.height); + return osg::Vec2f(static_cast(size.width), static_cast(size.height)); } struct Options diff --git a/components/lua_ui/properties.hpp b/components/lua_ui/properties.hpp index 81fb272f17..f6e81f7200 100644 --- a/components/lua_ui/properties.hpp +++ b/components/lua_ui/properties.hpp @@ -11,11 +11,16 @@ namespace LuaUi { + template + constexpr bool isMyGuiIntVector() + { + return std::is_same() || std::is_same(); + } + template constexpr bool isMyGuiVector() { - return std::is_same() || std::is_same() - || std::is_same() || std::is_same(); + return isMyGuiIntVector() || std::is_same() || std::is_same(); } template @@ -42,7 +47,9 @@ namespace LuaUi return sol::nullopt; LuaT luaT = opt.as(); - if constexpr (isMyGuiVector()) + if constexpr (isMyGuiIntVector()) + return T(static_cast(luaT.x()), static_cast(luaT.y())); + else if constexpr (isMyGuiVector()) return T(luaT.x(), luaT.y()); else if constexpr (isMyGuiColor()) return T(luaT.r(), luaT.g(), luaT.b(), luaT.a()); diff --git a/components/lua_ui/widget.cpp b/components/lua_ui/widget.cpp index ec951f3610..5b7d52bc51 100644 --- a/components/lua_ui/widget.cpp +++ b/components/lua_ui/widget.cpp @@ -174,16 +174,17 @@ namespace LuaUi auto keySym = SDL_Keysym(); keySym.sym = SDLUtil::myGuiKeyToSdl(code); keySym.scancode = SDL_GetScancodeFromKey(keySym.sym); - keySym.mod = SDL_GetModState(); + keySym.mod = static_cast(SDL_GetModState()); return sol::make_object(view.sol(), keySym); } sol::object WidgetExtension::mouseEvent( LuaUtil::LuaView& view, int left, int top, MyGUI::MouseButton button = MyGUI::MouseButton::None) const { - osg::Vec2f position(left, top); + osg::Vec2f position(static_cast(left), static_cast(top)); MyGUI::IntPoint absolutePosition = mWidget->getAbsolutePosition(); - osg::Vec2f offset = position - osg::Vec2f(absolutePosition.left, absolutePosition.top); + osg::Vec2f offset = position + - osg::Vec2f(static_cast(absolutePosition.left), static_cast(absolutePosition.top)); sol::table table = view.newTable(); int sdlButton = SDLUtil::myGuiMouseButtonToSdl(button); table["position"] = position; @@ -323,8 +324,8 @@ namespace LuaUi MyGUI::IntSize pSize = parentSize(); MyGUI::IntSize newSize; newSize = mAbsoluteCoord.size(); - newSize.width += mRelativeCoord.width * pSize.width; - newSize.height += mRelativeCoord.height * pSize.height; + newSize.width += static_cast(mRelativeCoord.width * pSize.width); + newSize.height += static_cast(mRelativeCoord.height * pSize.height); return newSize; } @@ -335,8 +336,8 @@ namespace LuaUi MyGUI::IntSize pSize = parentSize(); MyGUI::IntPoint newPosition; newPosition = mAbsoluteCoord.point(); - newPosition.left += mRelativeCoord.left * pSize.width - mAnchor.width * size.width; - newPosition.top += mRelativeCoord.top * pSize.height - mAnchor.height * size.height; + newPosition.left += static_cast(mRelativeCoord.left * pSize.width - mAnchor.width * size.width); + newPosition.top += static_cast(mRelativeCoord.top * pSize.height - mAnchor.height * size.height); return newPosition; } diff --git a/components/lua_ui/window.cpp b/components/lua_ui/window.cpp index ca8244394b..d86cbf9cb4 100644 --- a/components/lua_ui/window.cpp +++ b/components/lua_ui/window.cpp @@ -80,8 +80,8 @@ namespace LuaUi protectedCall([this](LuaUtil::LuaView& view) { sol::table table = view.newTable(); - table["position"] = osg::Vec2f(mCoord.left, mCoord.top); - table["size"] = osg::Vec2f(mCoord.width, mCoord.height); + table["position"] = osg::Vec2f(static_cast(mCoord.left), static_cast(mCoord.top)); + table["size"] = osg::Vec2f(static_cast(mCoord.width), static_cast(mCoord.height)); triggerEvent("windowDrag", table); }); } diff --git a/components/misc/budgetmeasurement.hpp b/components/misc/budgetmeasurement.hpp index 647ab3e61a..f5ea7dff8b 100644 --- a/components/misc/budgetmeasurement.hpp +++ b/components/misc/budgetmeasurement.hpp @@ -13,25 +13,25 @@ namespace Misc std::array mBudgetStepCount; public: - BudgetMeasurement(const float default_expense) + BudgetMeasurement(const float defaultExpense) { - mBudgetHistory = { default_expense, default_expense, default_expense, default_expense }; + mBudgetHistory = { defaultExpense, defaultExpense, defaultExpense, defaultExpense }; mBudgetStepCount = { 1, 1, 1, 1 }; } - void reset(const float default_expense) + void reset(const float defaultExpense) { - mBudgetHistory = { default_expense, default_expense, default_expense, default_expense }; + mBudgetHistory = { defaultExpense, defaultExpense, defaultExpense, defaultExpense }; mBudgetStepCount = { 1, 1, 1, 1 }; } void update(double delta, unsigned int stepCount, size_t cursor) { - mBudgetHistory[cursor % 4] = delta; + mBudgetHistory[cursor % 4] = static_cast(delta); mBudgetStepCount[cursor % 4] = stepCount; } - double get() const + float get() const { float sum = (mBudgetHistory[0] + mBudgetHistory[1] + mBudgetHistory[2] + mBudgetHistory[3]); unsigned int stepCountSum diff --git a/components/misc/color.cpp b/components/misc/color.cpp index 5ad52580d4..bfb711a5b1 100644 --- a/components/misc/color.cpp +++ b/components/misc/color.cpp @@ -28,10 +28,10 @@ namespace Misc throw std::logic_error(std::string("Invalid hex color: ") += hex); Color col; col.mValue.a() = 1; - for (size_t i = 0; i < 3; i++) + for (unsigned i = 0; i < 3; i++) { auto sub = hex.substr(i * 2, 2); - int v = 0; + unsigned char v = 0; auto [_, ec] = std::from_chars(sub.data(), sub.data() + sub.size(), v, 16); if (ec != std::errc()) throw std::logic_error(std::string("Invalid hex color: ") += hex); @@ -53,7 +53,7 @@ namespace Misc std::string Color::toHex() const { std::string result(6, '0'); - for (size_t i = 0; i < 3; i++) + for (unsigned i = 0; i < 3; i++) { int b = static_cast(mValue[i] * 255.0f); char* start = result.data() + i * 2; diff --git a/components/misc/convert.hpp b/components/misc/convert.hpp index 5d936b5d5f..2ed0baeaee 100644 --- a/components/misc/convert.hpp +++ b/components/misc/convert.hpp @@ -19,7 +19,7 @@ namespace Misc::Convert inline osg::Vec3f makeOsgVec3f(const ESM::Pathgrid::Point& value) { - return osg::Vec3f(value.mX, value.mY, value.mZ); + return osg::Vec3f(static_cast(value.mX), static_cast(value.mY), static_cast(value.mZ)); } inline btVector3 toBullet(const osg::Vec3f& vec) @@ -32,9 +32,14 @@ namespace Misc::Convert return btQuaternion(quat.x(), quat.y(), quat.z(), quat.w()); } - inline osg::Vec3f toOsg(const btVector3& vec) + inline osg::Vec3d toOsg(const btVector3& vec) { - return osg::Vec3f(vec.x(), vec.y(), vec.z()); + return osg::Vec3d(vec.x(), vec.y(), vec.z()); + } + + inline osg::Vec3f makeOsgVec3f(const btVector3& vec) + { + return toOsg(vec); } inline osg::Quat toOsg(const btQuaternion& quat) diff --git a/components/misc/rng.cpp b/components/misc/rng.cpp index 8da61b12a2..639ec19f5f 100644 --- a/components/misc/rng.cpp +++ b/components/misc/rng.cpp @@ -41,41 +41,16 @@ namespace Misc::Rng sGenerator.seed(seed); } - float rollProbability() - { - return std::uniform_real_distribution(0, 1 - std::numeric_limits::epsilon())(getGenerator()); - } - float rollProbability(Generator& prng) { return std::uniform_real_distribution(0, 1 - std::numeric_limits::epsilon())(prng); } - float rollClosedProbability() - { - return std::uniform_real_distribution(0, 1)(getGenerator()); - } - float rollClosedProbability(Generator& prng) { return std::uniform_real_distribution(0, 1)(prng); } - int rollDice(int max) - { - return max > 0 ? std::uniform_int_distribution(0, max - 1)(getGenerator()) : 0; - } - - int rollDice(int max, Generator& prng) - { - return max > 0 ? std::uniform_int_distribution(0, max - 1)(prng) : 0; - } - - float deviate(float mean, float deviation) - { - return std::uniform_real_distribution(mean - deviation, mean + deviation)(getGenerator()); - } - float deviate(float mean, float deviation, Generator& prng) { return std::uniform_real_distribution(mean - deviation, mean + deviation)(prng); diff --git a/components/misc/rng.hpp b/components/misc/rng.hpp index 9dd5a0da99..72f374cc35 100644 --- a/components/misc/rng.hpp +++ b/components/misc/rng.hpp @@ -2,6 +2,7 @@ #define OPENMW_COMPONENTS_MISC_RNG_H #include +#include #include #include @@ -25,29 +26,25 @@ namespace Misc::Rng void init(unsigned int seed = generateDefaultSeed()); /// return value in range [0.0f, 1.0f) <- note open upper range. - float rollProbability(); - float rollProbability(Generator& prng); + float rollProbability(Generator& prng = getGenerator()); /// return value in range [0.0f, 1.0f] <- note closed upper range. - float rollClosedProbability(); - float rollClosedProbability(Generator& prng); + float rollClosedProbability(Generator& prng = getGenerator()); /// return value in range [0, max) <- note open upper range. - int rollDice(int max); - int rollDice(int max, Generator& prng); + template + inline T rollDice(T max, Generator& prng = getGenerator()) + { + return max > 0 ? std::uniform_int_distribution(0, max - 1)(prng) : 0; + } /// return value in range [0, 99] - inline int roll0to99(Generator& prng) + inline int roll0to99(Generator& prng = getGenerator()) { return rollDice(100, prng); } - inline int roll0to99() - { - return rollDice(100); - } - float deviate(float mean, float deviation); - float deviate(float mean, float deviation, Generator& prng); + float deviate(float mean, float deviation, Generator& prng = getGenerator()); } #endif diff --git a/components/misc/utf8stream.hpp b/components/misc/utf8stream.hpp index 5eb5f99b84..d705ddb3a7 100644 --- a/components/misc/utf8stream.hpp +++ b/components/misc/utf8stream.hpp @@ -17,26 +17,26 @@ public: static UnicodeChar sBadChar() { return UnicodeChar(0xFFFFFFFF); } Utf8Stream(Point begin, Point end) - : cur(begin) - , nxt(begin) - , end(end) - , val(Utf8Stream::sBadChar()) + : mCur(begin) + , mNxt(begin) + , mEnd(end) + , mVal(Utf8Stream::sBadChar()) { } Utf8Stream(const char* str) - : cur(reinterpret_cast(str)) - , nxt(reinterpret_cast(str)) - , end(reinterpret_cast(str) + strlen(str)) - , val(Utf8Stream::sBadChar()) + : mCur(reinterpret_cast(str)) + , mNxt(reinterpret_cast(str)) + , mEnd(reinterpret_cast(str) + strlen(str)) + , mVal(Utf8Stream::sBadChar()) { } Utf8Stream(std::pair range) - : cur(range.first) - , nxt(range.first) - , end(range.second) - , val(Utf8Stream::sBadChar()) + : mCur(range.first) + , mNxt(range.first) + , mEnd(range.second) + , mVal(Utf8Stream::sBadChar()) { } @@ -45,23 +45,23 @@ public: { } - bool eof() const { return cur == end; } + bool eof() const { return mCur == mEnd; } - Point current() const { return cur; } + Point current() const { return mCur; } UnicodeChar peek() { - if (cur == nxt) + if (mCur == mNxt) next(); - return val; + return mVal; } UnicodeChar consume() { - if (cur == nxt) + if (mCur == mNxt) next(); - cur = nxt; - return val; + mCur = mNxt; + return mVal; } static bool isAscii(unsigned char value) { return (value & 0x80) == 0; } @@ -189,12 +189,12 @@ public: } private: - void next() { std::tie(val, nxt) = decode(nxt, end); } + void next() { std::tie(mVal, mNxt) = decode(mNxt, mEnd); } - Point cur; - Point nxt; - Point end; - UnicodeChar val; + Point mCur; + Point mNxt; + Point mEnd; + UnicodeChar mVal; }; #endif diff --git a/components/myguiplatform/myguirendermanager.cpp b/components/myguiplatform/myguirendermanager.cpp index 85afcde462..67781554d8 100644 --- a/components/myguiplatform/myguirendermanager.cpp +++ b/components/myguiplatform/myguirendermanager.cpp @@ -141,7 +141,7 @@ namespace MyGUIPlatform reinterpret_cast(vbo->getArray(0)->getDataPointer()) + 16); } - glDrawArrays(GL_TRIANGLES, 0, batch.mVertexCount); + glDrawArrays(GL_TRIANGLES, 0, static_cast(batch.mVertexCount)); if (batch.mStateSet) { @@ -328,7 +328,8 @@ namespace MyGUIPlatform osg::UByteArray* OSGVertexBuffer::create() { - mVertexArray[mCurrentBuffer] = new osg::UByteArray(mNeedVertexCount * sizeof(MyGUI::Vertex)); + mVertexArray[mCurrentBuffer] + = new osg::UByteArray(static_cast(mNeedVertexCount * sizeof(MyGUI::Vertex))); mBuffer[mCurrentBuffer] = new osg::VertexBufferObject; mBuffer[mCurrentBuffer]->setDataVariance(osg::Object::DYNAMIC); @@ -404,7 +405,7 @@ namespace MyGUIPlatform mSceneRoot->addChild(mGuiRoot.get()); osg::ref_ptr vp = mViewer->getCamera()->getViewport(); - setViewSize(vp->width(), vp->height()); + setViewSize(static_cast(vp->width()), static_cast(vp->height())); MYGUI_PLATFORM_LOG(Info, getClassTypeName() << " successfully initialized"); mIsInitialise = true; @@ -500,7 +501,7 @@ namespace MyGUIPlatform mGuiRoot->setViewport(0, 0, width, height); - mViewSize.set(width * mInvScalingFactor, height * mInvScalingFactor); + mViewSize.set(static_cast(width * mInvScalingFactor), static_cast(height * mInvScalingFactor)); mInfo.maximumDepth = 1; mInfo.hOffset = 0; diff --git a/components/nif/niffile.cpp b/components/nif/niffile.cpp index 02b110a5a6..02233a2b3c 100644 --- a/components/nif/niffile.cpp +++ b/components/nif/niffile.cpp @@ -699,7 +699,7 @@ namespace Nif assert(r != nullptr); assert(r->recType != RC_MISSING); r->recName = std::move(rec); - r->recIndex = i; + r->recIndex = static_cast(i); r->read(&nif); mRecords[i] = std::move(r); } diff --git a/components/nif/node.cpp b/components/nif/node.cpp index c2655a3e9c..7dba288164 100644 --- a/components/nif/node.cpp +++ b/components/nif/node.cpp @@ -664,13 +664,13 @@ namespace Nif mDynamicVertexSize = (data & 0xF0) >> 0x04; mUV1Offset = (data & 0xF00) >> 0x08; mUV2Offset = (data & 0xF000) >> 0x0C; - mNormalOffset = (data & 0xF0000) >> 0x10; - mTangentOffset = (data & 0xF00000) >> 0x14; + mNormalOffset = static_cast((data & 0xF0000) >> 0x10); + mTangentOffset = static_cast((data & 0xF00000) >> 0x14); mColorOffset = (data & 0xF000000) >> 0x18; mSkinningDataOffset = (data & 0xF0000000) >> 0x1C; - mLandscapeDataOffset = (data & 0xF00000000) >> 0x20; - mEyeDataOffset = (data & 0xF000000000) >> 0x24; - mFlags = (data & 0xFFF00000000000) >> 0x2C; + mLandscapeDataOffset = static_cast((data & 0xF00000000) >> 0x20); + mEyeDataOffset = static_cast((data & 0xF000000000) >> 0x24); + mFlags = static_cast((data & 0xFFF00000000000) >> 0x2C); if (nif->getBethVersion() == NIFFile::BethVersion::BETHVER_SSE) mFlags |= BSVertexDesc::VertexAttribute::Full_Precision; } diff --git a/components/nifosg/controller.cpp b/components/nifosg/controller.cpp index bd11344ed8..3ef288b209 100644 --- a/components/nifosg/controller.cpp +++ b/components/nifosg/controller.cpp @@ -263,7 +263,7 @@ namespace NifOsg if (mKeyFrames.size() <= 1) return; float input = getInputValue(nv); - size_t i = 1; + unsigned int i = 1; for (std::vector::iterator it = mKeyFrames.begin() + 1; it != mKeyFrames.end(); ++it, ++i) { diff --git a/components/nifosg/matrixtransform.cpp b/components/nifosg/matrixtransform.cpp index a59f10360a..8d7717eb49 100644 --- a/components/nifosg/matrixtransform.cpp +++ b/components/nifosg/matrixtransform.cpp @@ -40,7 +40,7 @@ namespace NifOsg for (int j = 0; j < 3; ++j) { // Update the current decomposed rotation and restore the known scale. - mRotationScale.mValues[j][i] = _matrix(i, j); // NB: column/row major difference + mRotationScale.mValues[j][i] = static_cast(_matrix(i, j)); // NB: column/row major difference _matrix(i, j) *= mScale; } } diff --git a/components/nifosg/nifloader.cpp b/components/nifosg/nifloader.cpp index 23fb9f7439..12aae46a49 100644 --- a/components/nifosg/nifloader.cpp +++ b/components/nifosg/nifloader.cpp @@ -165,7 +165,7 @@ namespace osg::Matrix modelView = *cv->getModelViewMatrix(); // attempt to preserve scale - float mag[3]; + double mag[3]; for (int i = 0; i < 3; ++i) { mag[i] = std::sqrt(modelView(0, i) * modelView(0, i) + modelView(1, i) * modelView(1, i) @@ -1083,7 +1083,7 @@ namespace NifOsg texture2d->setTextureSize(image->s(), image->t()); texture2d->setWrap(osg::Texture::WRAP_S, wrapS ? osg::Texture::REPEAT : osg::Texture::CLAMP_TO_EDGE); texture2d->setWrap(osg::Texture::WRAP_T, wrapT ? osg::Texture::REPEAT : osg::Texture::CLAMP_TO_EDGE); - unsigned int texUnit = boundTextures.size(); + auto texUnit = static_cast(boundTextures.size()); if (stateset) { stateset->setTextureAttributeAndModes(texUnit, texture2d, osg::StateAttribute::ON); @@ -1244,12 +1244,12 @@ namespace NifOsg auto particleNode = static_cast(nifNode); if (particleNode->mData.empty()) { - partsys->setQuota(partctrl->mParticles.size()); + partsys->setQuota(static_cast(partctrl->mParticles.size())); return; } auto particledata = static_cast(particleNode->mData.getPtr()); - partsys->setQuota(particledata->mNumParticles); + partsys->setQuota(static_cast(particledata->mNumParticles)); osg::BoundingBox box; @@ -1342,7 +1342,7 @@ namespace NifOsg { for (const auto& emitterPair : mEmitterQueue) { - size_t recIndex = emitterPair.first; + auto recIndex = static_cast(emitterPair.first); FindGroupByRecIndex findEmitterNode(recIndex); rootNode->accept(findEmitterNode); osg::Group* emitterNode = findEmitterNode.mFound; @@ -1488,15 +1488,15 @@ namespace NifOsg const std::vector& trueTriangles = partition.mTrueTriangles; if (!trueTriangles.empty()) { - geometry->addPrimitiveSet(new osg::DrawElementsUShort( - osg::PrimitiveSet::TRIANGLES, trueTriangles.size(), trueTriangles.data())); + geometry->addPrimitiveSet(new osg::DrawElementsUShort(osg::PrimitiveSet::TRIANGLES, + static_cast(trueTriangles.size()), trueTriangles.data())); } for (const auto& strip : partition.mTrueStrips) { if (strip.size() < 3) continue; geometry->addPrimitiveSet(new osg::DrawElementsUShort( - osg::PrimitiveSet::TRIANGLE_STRIP, strip.size(), strip.data())); + osg::PrimitiveSet::TRIANGLE_STRIP, static_cast(strip.size()), strip.data())); } } } @@ -1511,8 +1511,8 @@ namespace NifOsg const std::vector& triangles = data->mTriangles; if (triangles.empty()) return; - geometry->addPrimitiveSet( - new osg::DrawElementsUShort(osg::PrimitiveSet::TRIANGLES, triangles.size(), triangles.data())); + geometry->addPrimitiveSet(new osg::DrawElementsUShort( + osg::PrimitiveSet::TRIANGLES, static_cast(triangles.size()), triangles.data())); } else if (niGeometry->recType == Nif::RC_NiTriStrips) { @@ -1522,8 +1522,8 @@ namespace NifOsg { if (strip.size() < 3) continue; - geometry->addPrimitiveSet( - new osg::DrawElementsUShort(osg::PrimitiveSet::TRIANGLE_STRIP, strip.size(), strip.data())); + geometry->addPrimitiveSet(new osg::DrawElementsUShort( + osg::PrimitiveSet::TRIANGLE_STRIP, static_cast(strip.size()), strip.data())); hasGeometry = true; } if (!hasGeometry) @@ -1535,8 +1535,8 @@ namespace NifOsg const auto& line = data->mLines; if (line.empty()) return; - geometry->addPrimitiveSet( - new osg::DrawElementsUShort(osg::PrimitiveSet::LINES, line.size(), line.data())); + geometry->addPrimitiveSet(new osg::DrawElementsUShort( + osg::PrimitiveSet::LINES, static_cast(line.size()), line.data())); } } @@ -1544,17 +1544,17 @@ namespace NifOsg const auto& normals = niGeometryData->mNormals; const auto& colors = niGeometryData->mColors; if (!vertices.empty()) - geometry->setVertexArray(new osg::Vec3Array(vertices.size(), vertices.data())); + geometry->setVertexArray(new osg::Vec3Array(static_cast(vertices.size()), vertices.data())); if (!normals.empty()) - geometry->setNormalArray( - new osg::Vec3Array(normals.size(), normals.data()), osg::Array::BIND_PER_VERTEX); + geometry->setNormalArray(new osg::Vec3Array(static_cast(normals.size()), normals.data()), + osg::Array::BIND_PER_VERTEX); if (!colors.empty()) - geometry->setColorArray(new osg::Vec4Array(colors.size(), colors.data()), osg::Array::BIND_PER_VERTEX); + geometry->setColorArray(new osg::Vec4Array(static_cast(colors.size()), colors.data()), + osg::Array::BIND_PER_VERTEX); const auto& uvlist = niGeometryData->mUVList; int textureStage = 0; - for (std::vector::const_iterator it = boundTextures.begin(); it != boundTextures.end(); - ++it, ++textureStage) + for (auto it = boundTextures.begin(); it != boundTextures.end(); ++it, ++textureStage) { unsigned int uvSet = *it; if (uvSet >= uvlist.size()) @@ -1566,7 +1566,8 @@ namespace NifOsg uvSet = 0; } - geometry->setTexCoordArray(textureStage, new osg::Vec2Array(uvlist[uvSet].size(), uvlist[uvSet].data()), + geometry->setTexCoordArray(textureStage, + new osg::Vec2Array(static_cast(uvlist[uvSet].size()), uvlist[uvSet].data()), osg::Array::BIND_PER_VERTEX); } @@ -1650,8 +1651,9 @@ namespace NifOsg osg::ref_ptr morphGeom = new SceneUtil::MorphGeometry; morphGeom->setSourceGeometry(geom); for (unsigned int i = 0; i < morphs.size(); ++i) - morphGeom->addMorphTarget( - new osg::Vec3Array(morphs[i].mVertices.size(), morphs[i].mVertices.data()), 0.f); + morphGeom->addMorphTarget(new osg::Vec3Array(static_cast(morphs[i].mVertices.size()), + morphs[i].mVertices.data()), + 0.f); osg::ref_ptr morphctrl = new GeomMorpherController(nimorphctrl); setupController(ctrl.getPtr(), morphctrl, animflags); @@ -1678,8 +1680,8 @@ namespace NifOsg return; osg::ref_ptr geometry(new osg::Geometry); - geometry->addPrimitiveSet( - new osg::DrawElementsUShort(osg::PrimitiveSet::TRIANGLES, triangles.size(), triangles.data())); + geometry->addPrimitiveSet(new osg::DrawElementsUShort( + osg::PrimitiveSet::TRIANGLES, static_cast(triangles.size()), triangles.data())); osg::ref_ptr drawable = geometry; @@ -1743,16 +1745,16 @@ namespace NifOsg } if (!vertices.empty()) - geometry->setVertexArray(new osg::Vec3Array(vertices.size(), vertices.data())); + geometry->setVertexArray(new osg::Vec3Array(static_cast(vertices.size()), vertices.data())); if (!normals.empty()) - geometry->setNormalArray( - new osg::Vec3Array(normals.size(), normals.data()), osg::Array::BIND_PER_VERTEX); + geometry->setNormalArray(new osg::Vec3Array(static_cast(normals.size()), normals.data()), + osg::Array::BIND_PER_VERTEX); if (!colors.empty()) - geometry->setColorArray( - new osg::Vec4ubArray(colors.size(), colors.data()), osg::Array::BIND_PER_VERTEX); + geometry->setColorArray(new osg::Vec4ubArray(static_cast(colors.size()), colors.data()), + osg::Array::BIND_PER_VERTEX); if (!uvlist.empty()) - geometry->setTexCoordArray( - 0, new osg::Vec2Array(uvlist.size(), uvlist.data()), osg::Array::BIND_PER_VERTEX); + geometry->setTexCoordArray(0, new osg::Vec2Array(static_cast(uvlist.size()), uvlist.data()), + osg::Array::BIND_PER_VERTEX); // This is the skinning data Fallout 4 provides // TODO: support Skyrim SE skinning data @@ -2124,7 +2126,7 @@ namespace NifOsg } } - const unsigned int texUnit = boundTextures.size(); + const auto texUnit = static_cast(boundTextures.size()); if (tex.mEnabled) { if (tex.mSourceTexture.empty() && texprop->mController.empty()) @@ -2632,7 +2634,7 @@ namespace NifOsg if (!texprop->mSourceTexture.empty()) { const unsigned int uvSet = 0; - unsigned int texUnit = boundTextures.size(); + unsigned int texUnit = static_cast(boundTextures.size()); attachExternalTexture("diffuseMap", texprop->mSourceTexture, texprop->wrapS(), texprop->wrapT(), uvSet, stateset, boundTextures); { diff --git a/components/nifosg/particle.cpp b/components/nifosg/particle.cpp index 53830388a5..f64116eb9c 100644 --- a/components/nifosg/particle.cpp +++ b/components/nifosg/particle.cpp @@ -106,7 +106,7 @@ namespace NifOsg { mNormalArray = new osg::Vec3Array(1); mNormalArray->setBinding(osg::Array::BIND_OVERALL); - (*mNormalArray.get())[0] = osg::Vec3(0.3, 0.3, 0.3); + (*mNormalArray.get())[0] = osg::Vec3(0.3f, 0.3f, 0.3f); } ParticleSystem::ParticleSystem(const ParticleSystem& copy, const osg::CopyOp& copyop) @@ -115,7 +115,7 @@ namespace NifOsg { mNormalArray = new osg::Vec3Array(1); mNormalArray->setBinding(osg::Array::BIND_OVERALL); - (*mNormalArray.get())[0] = osg::Vec3(0.3, 0.3, 0.3); + (*mNormalArray.get())[0] = osg::Vec3(0.3f, 0.3f, 0.3f); // For some reason the osgParticle constructor doesn't copy the particles for (int i = 0; i < copy.numParticles() - copy.numDeadParticles(); ++i) @@ -247,9 +247,9 @@ namespace NifOsg { float size = mCachedDefaultSize; if (particle->getAge() < mGrowTime && mGrowTime != 0.f) - size *= particle->getAge() / mGrowTime; + size *= static_cast(particle->getAge() / mGrowTime); if (particle->getLifeTime() - particle->getAge() < mFadeTime && mFadeTime != 0.f) - size *= (particle->getLifeTime() - particle->getAge()) / mFadeTime; + size *= static_cast(particle->getLifeTime() - particle->getAge()) / mFadeTime; particle->setSizeRange(osgParticle::rangef(size, size)); } @@ -326,7 +326,7 @@ namespace NifOsg decayFactor = std::exp(-1.f * mDecay * distance); } - particle->addVelocity(mCachedWorldDirection * mForce * dt * decayFactor * magic); + particle->addVelocity(mCachedWorldDirection * mForce * static_cast(dt) * decayFactor * magic); break; } @@ -340,7 +340,7 @@ namespace NifOsg diff.normalize(); - particle->addVelocity(diff * mForce * dt * decayFactor * magic); + particle->addVelocity(diff * mForce * static_cast(dt) * decayFactor * magic); break; } } @@ -421,7 +421,7 @@ namespace NifOsg break; } - particle->addVelocity(explosionDir * mStrength * decay * dt); + particle->addVelocity(explosionDir * mStrength * decay * static_cast(dt)); } Emitter::Emitter() @@ -487,7 +487,7 @@ namespace NifOsg } else { - int randomIndex = Misc::Rng::rollClosedProbability() * (mTargets.size() - 1); + size_t randomIndex = Misc::Rng::rollDice(mTargets.size()); recIndex = mTargets[randomIndex]; } diff --git a/components/resource/bulletshapemanager.cpp b/components/resource/bulletshapemanager.cpp index 488624d2d2..94b22564a9 100644 --- a/components/resource/bulletshapemanager.cpp +++ b/components/resource/bulletshapemanager.cpp @@ -9,6 +9,7 @@ #include +#include #include #include #include @@ -37,14 +38,12 @@ namespace Resource void setMatrix(const osg::Matrixf& matrix) { mMatrix = matrix; } - inline btVector3 toBullet(const osg::Vec3f& vec) { return btVector3(vec.x(), vec.y(), vec.z()); } - void inline operator()(const osg::Vec3& v1, const osg::Vec3& v2, const osg::Vec3& v3, bool /*temp*/ = false) // Note: unused temp argument left here for OSG versions less than 3.5.6 { if (mTriMesh) - mTriMesh->addTriangle( - toBullet(mMatrix.preMult(v1)), toBullet(mMatrix.preMult(v2)), toBullet(mMatrix.preMult(v3))); + mTriMesh->addTriangle(Misc::Convert::toBullet(mMatrix.preMult(v1)), + Misc::Convert::toBullet(mMatrix.preMult(v2)), Misc::Convert::toBullet(mMatrix.preMult(v3))); } btTriangleMesh* mTriMesh; @@ -83,11 +82,11 @@ namespace Resource auto triangleMeshShape = std::make_unique(mTriangleMesh.release(), true); btVector3 aabbMin = triangleMeshShape->getLocalAabbMin(); btVector3 aabbMax = triangleMeshShape->getLocalAabbMax(); - shape->mCollisionBox.mExtents[0] = (aabbMax[0] - aabbMin[0]) / 2.0f; - shape->mCollisionBox.mExtents[1] = (aabbMax[1] - aabbMin[1]) / 2.0f; - shape->mCollisionBox.mExtents[2] = (aabbMax[2] - aabbMin[2]) / 2.0f; - shape->mCollisionBox.mCenter = osg::Vec3f( - (aabbMax[0] + aabbMin[0]) / 2.0f, (aabbMax[1] + aabbMin[1]) / 2.0f, (aabbMax[2] + aabbMin[2]) / 2.0f); + shape->mCollisionBox.mExtents[0] = static_cast(aabbMax[0] - aabbMin[0]) / 2.0f; + shape->mCollisionBox.mExtents[1] = static_cast(aabbMax[1] - aabbMin[1]) / 2.0f; + shape->mCollisionBox.mExtents[2] = static_cast(aabbMax[2] - aabbMin[2]) / 2.0f; + shape->mCollisionBox.mCenter = osg::Vec3f(static_cast(aabbMax[0] + aabbMin[0]) / 2.0f, + static_cast(aabbMax[1] + aabbMin[1]) / 2.0f, static_cast(aabbMax[2] + aabbMin[2]) / 2.0f); shape->mCollisionShape.reset(triangleMeshShape.release()); return shape; diff --git a/components/resource/keyframemanager.cpp b/components/resource/keyframemanager.cpp index f962ba03fb..e216271925 100644 --- a/components/resource/keyframemanager.cpp +++ b/components/resource/keyframemanager.cpp @@ -144,8 +144,8 @@ namespace Resource callback->addMergedAnimationTrack(std::move(mergedAnimationTrack)); - float startTime = animation->getStartTime(); - float stopTime = startTime + animation->getDuration(); + float startTime = static_cast(animation->getStartTime()); + float stopTime = static_cast(startTime + animation->getDuration()); SceneUtil::EmulatedAnimation emulatedAnimation; emulatedAnimation.mStartTime = startTime; @@ -168,7 +168,7 @@ namespace Resource { std::string line; while (getline(*textKeysFile, line)) - mTarget.mTextKeys.emplace(parseTimeSignature(line), parseTextKey(line)); + mTarget.mTextKeys.emplace(static_cast(parseTimeSignature(line)), parseTextKey(line)); } catch (const std::exception& e) { diff --git a/components/resource/scenemanager.cpp b/components/resource/scenemanager.cpp index ffa6abe58e..687d0730b3 100644 --- a/components/resource/scenemanager.cpp +++ b/components/resource/scenemanager.cpp @@ -141,9 +141,9 @@ namespace Resource class SharedStateManager : public osgDB::SharedStateManager { public: - unsigned int getNumSharedTextures() const { return _sharedTextureList.size(); } + size_t getNumSharedTextures() const { return _sharedTextureList.size(); } - unsigned int getNumSharedStateSets() const { return _sharedStateSetList.size(); } + size_t getNumSharedStateSets() const { return _sharedStateSetList.size(); } void clearCache() { @@ -158,7 +158,7 @@ namespace Resource { public: SetFilterSettingsControllerVisitor( - osg::Texture::FilterMode minFilter, osg::Texture::FilterMode magFilter, int maxAnisotropy) + osg::Texture::FilterMode minFilter, osg::Texture::FilterMode magFilter, float maxAnisotropy) : mMinFilter(minFilter) , mMagFilter(magFilter) , mMaxAnisotropy(maxAnisotropy) @@ -169,10 +169,8 @@ namespace Resource { if (NifOsg::FlipController* flipctrl = dynamic_cast(&ctrl)) { - for (std::vector>::iterator it = flipctrl->getTextures().begin(); - it != flipctrl->getTextures().end(); ++it) + for (const osg::ref_ptr& tex : flipctrl->getTextures()) { - osg::Texture* tex = *it; tex->setFilter(osg::Texture::MIN_FILTER, mMinFilter); tex->setFilter(osg::Texture::MAG_FILTER, mMagFilter); tex->setMaxAnisotropy(mMaxAnisotropy); @@ -183,7 +181,7 @@ namespace Resource private: osg::Texture::FilterMode mMinFilter; osg::Texture::FilterMode mMagFilter; - int mMaxAnisotropy; + float mMaxAnisotropy; }; /// Set texture filtering settings on textures contained in StateSets. @@ -191,7 +189,7 @@ namespace Resource { public: SetFilterSettingsVisitor( - osg::Texture::FilterMode minFilter, osg::Texture::FilterMode magFilter, int maxAnisotropy) + osg::Texture::FilterMode minFilter, osg::Texture::FilterMode magFilter, float maxAnisotropy) : osg::NodeVisitor(TRAVERSE_ALL_CHILDREN) , mMinFilter(minFilter) , mMagFilter(magFilter) @@ -233,7 +231,7 @@ namespace Resource private: osg::Texture::FilterMode mMinFilter; osg::Texture::FilterMode mMagFilter; - int mMaxAnisotropy; + float mMaxAnisotropy; }; // Check Collada extra descriptions @@ -452,7 +450,7 @@ namespace Resource , mBgsmFileManager(bgsmFileManager) , mMinFilter(osg::Texture::LINEAR_MIPMAP_LINEAR) , mMagFilter(osg::Texture::LINEAR) - , mMaxAnisotropy(1) + , mMaxAnisotropy(1.f) , mParticleSystemMask(~0u) , mLightingMethod(SceneUtil::LightingMethod::FFP) { @@ -1119,7 +1117,7 @@ namespace Resource } void SceneManager::setFilterSettings( - const std::string& magfilter, const std::string& minfilter, const std::string& mipmap, int maxAnisotropy) + const std::string& magfilter, const std::string& minfilter, const std::string& mipmap, float maxAnisotropy) { osg::Texture::FilterMode min = osg::Texture::LINEAR; osg::Texture::FilterMode mag = osg::Texture::LINEAR; @@ -1153,7 +1151,7 @@ namespace Resource mMinFilter = min; mMagFilter = mag; - mMaxAnisotropy = std::max(1, maxAnisotropy); + mMaxAnisotropy = std::max(1.f, maxAnisotropy); SetFilterSettingsControllerVisitor setFilterSettingsControllerVisitor(mMinFilter, mMagFilter, mMaxAnisotropy); SetFilterSettingsVisitor setFilterSettingsVisitor(mMinFilter, mMagFilter, mMaxAnisotropy); @@ -1215,13 +1213,16 @@ namespace Resource if (mIncrementalCompileOperation) { std::lock_guard lock(*mIncrementalCompileOperation->getToCompiledMutex()); - stats->setAttribute(frameNumber, "Compiling", mIncrementalCompileOperation->getToCompile().size()); + stats->setAttribute( + frameNumber, "Compiling", static_cast(mIncrementalCompileOperation->getToCompile().size())); } { std::lock_guard lock(mSharedStateMutex); - stats->setAttribute(frameNumber, "Texture", mSharedStateManager->getNumSharedTextures()); - stats->setAttribute(frameNumber, "StateSet", mSharedStateManager->getNumSharedStateSets()); + stats->setAttribute( + frameNumber, "Texture", static_cast(mSharedStateManager->getNumSharedTextures())); + stats->setAttribute( + frameNumber, "StateSet", static_cast(mSharedStateManager->getNumSharedStateSets())); } Resource::reportStats("Node", frameNumber, mCache->getStats(), *stats); diff --git a/components/resource/scenemanager.hpp b/components/resource/scenemanager.hpp index df37a6165a..aabfc2ee6d 100644 --- a/components/resource/scenemanager.hpp +++ b/components/resource/scenemanager.hpp @@ -207,7 +207,7 @@ namespace Resource /// @warning It is unsafe to call this method while the draw thread is using textures! call /// Viewer::stopThreading first. void setFilterSettings( - const std::string& magfilter, const std::string& minfilter, const std::string& mipmap, int maxAnisotropy); + const std::string& magfilter, const std::string& minfilter, const std::string& mipmap, float maxAnisotropy); /// Apply filter settings to the given texture. Note, when loading an object through this scene manager (i.e. /// calling getTemplate or createInstance) the filter settings are applied automatically. This method is @@ -256,7 +256,7 @@ namespace Resource osg::Texture::FilterMode mMinFilter; osg::Texture::FilterMode mMagFilter; - int mMaxAnisotropy; + float mMaxAnisotropy; unsigned int mParticleSystemMask; SceneUtil::LightingMethod mLightingMethod; diff --git a/components/resource/stats.cpp b/components/resource/stats.cpp index c902265448..d3bb721584 100644 --- a/components/resource/stats.cpp +++ b/components/resource/stats.cpp @@ -520,14 +520,14 @@ namespace Resource void StatsHandler::setUpScene(osgViewer::ViewerBase& viewer) { - const osg::Vec4 backgroundColor(0.0, 0.0, 0.0f, 0.3); - const osg::Vec4 staticTextColor(1.0, 1.0, 0.0f, 1.0); - const osg::Vec4 dynamicTextColor(1.0, 1.0, 1.0f, 1.0); + const osg::Vec4 backgroundColor(0.0f, 0.0f, 0.0f, 0.3f); + const osg::Vec4 staticTextColor(1.0f, 1.0f, 0.0f, 1.0f); + const osg::Vec4 dynamicTextColor(1.0f, 1.0f, 1.0f, 1.0f); const auto longest = std::max_element(mStatNames.begin(), mStatNames.end(), [](const std::string& lhs, const std::string& rhs) { return lhs.size() < rhs.size(); }); const std::size_t longestSize = longest->size(); - const float statNamesWidth = longestSize * characterSize * 0.6 + 2 * backgroundMargin; + const float statNamesWidth = longestSize * characterSize * 0.6f + 2 * backgroundMargin; const float statTextWidth = 7 * characterSize + 2 * backgroundMargin; const float statHeight = pageSize * characterSize + 2 * backgroundMargin; const float width = statNamesWidth + backgroundSpacing + statTextWidth; diff --git a/components/sceneutil/controller.cpp b/components/sceneutil/controller.cpp index e44c02741a..614795a55b 100644 --- a/components/sceneutil/controller.cpp +++ b/components/sceneutil/controller.cpp @@ -51,7 +51,7 @@ namespace SceneUtil float FrameTimeSource::getValue(osg::NodeVisitor* nv) { - return nv->getFrameStamp()->getSimulationTime(); + return static_cast(nv->getFrameStamp()->getSimulationTime()); } ControllerVisitor::ControllerVisitor() @@ -83,7 +83,7 @@ namespace SceneUtil visit(node, *ctrl); if (CompositeStateSetUpdater* composite = dynamic_cast(callback)) { - for (unsigned int i = 0; i < composite->getNumControllers(); ++i) + for (size_t i = 0; i < composite->getNumControllers(); ++i) { StateSetUpdater* statesetcontroller = composite->getController(i); if (Controller* ctrl = dynamic_cast(statesetcontroller)) diff --git a/components/sceneutil/cullsafeboundsvisitor.hpp b/components/sceneutil/cullsafeboundsvisitor.hpp index b3a9789206..075ee9ab5a 100644 --- a/components/sceneutil/cullsafeboundsvisitor.hpp +++ b/components/sceneutil/cullsafeboundsvisitor.hpp @@ -26,14 +26,14 @@ namespace SceneUtil mBoundingBox.init(); } - void apply(osg::Drawable& drawable) + void apply(osg::Drawable& drawable) override { osg::BoundingBox bbox = drawable.getInitialBound(); bbox.expandBy(drawable.computeBoundingBox()); applyBoundingBox(bbox); } - void apply(osg::Transform& transform) + void apply(osg::Transform& transform) override { osg::Matrix matrix; if (!mMatrixStack.empty()) @@ -63,4 +63,4 @@ namespace SceneUtil std::vector mMatrixStack; }; } -#endif // OPENMW_COMPONENTS_SCENEUTIL_CULLSAFEBOUNDSVISITOR_H \ No newline at end of file +#endif // OPENMW_COMPONENTS_SCENEUTIL_CULLSAFEBOUNDSVISITOR_H diff --git a/components/sceneutil/detourdebugdraw.cpp b/components/sceneutil/detourdebugdraw.cpp index 24d29b0b70..1dd6d344e6 100644 --- a/components/sceneutil/detourdebugdraw.cpp +++ b/components/sceneutil/detourdebugdraw.cpp @@ -114,8 +114,8 @@ namespace SceneUtil osg::ref_ptr material = new osg::Material; material->setColorMode(osg::Material::AMBIENT_AND_DIFFUSE); - const float polygonOffsetFactor = SceneUtil::AutoDepth::isReversed() ? 1.0 : -1.0; - const float polygonOffsetUnits = SceneUtil::AutoDepth::isReversed() ? 1.0 : -1.0; + const float polygonOffsetFactor = SceneUtil::AutoDepth::isReversed() ? 1.0f : -1.0f; + const float polygonOffsetUnits = SceneUtil::AutoDepth::isReversed() ? 1.0f : -1.0f; osg::ref_ptr polygonOffset = new osg::PolygonOffset(polygonOffsetFactor, polygonOffsetUnits); diff --git a/components/sceneutil/keyframe.hpp b/components/sceneutil/keyframe.hpp index e8d53c1876..1d0d338f17 100644 --- a/components/sceneutil/keyframe.hpp +++ b/components/sceneutil/keyframe.hpp @@ -17,7 +17,7 @@ namespace SceneUtil public: KeyframeController() {} - KeyframeController(const KeyframeController& copy) + KeyframeController(const KeyframeController& copy, const osg::CopyOp& copyop) : SceneUtil::Controller(copy) { } @@ -33,7 +33,7 @@ namespace SceneUtil virtual osg::Vec3f getTranslation(float time) const { return osg::Vec3f(); } - virtual KfTransform getCurrentTransformation(osg::NodeVisitor* nv) { return KfTransform(); }; + virtual KfTransform getCurrentTransformation(osg::NodeVisitor* nv) { return KfTransform(); } /// @note We could drop this function in favour of osg::Object::asCallback from OSG 3.6 on. virtual osg::Callback* getAsCallback() = 0; diff --git a/components/sceneutil/lightcommon.cpp b/components/sceneutil/lightcommon.cpp index 03d00811e2..f207de19c6 100644 --- a/components/sceneutil/lightcommon.cpp +++ b/components/sceneutil/lightcommon.cpp @@ -14,7 +14,7 @@ namespace SceneUtil , mPulseSlow(light.mData.mFlags & ESM::Light::PulseSlow) , mOffDefault(light.mData.mFlags & ESM::Light::OffDefault) , mColor(SceneUtil::colourFromRGB(light.mData.mColor)) - , mRadius(light.mData.mRadius) + , mRadius(static_cast(light.mData.mRadius)) { } @@ -26,7 +26,7 @@ namespace SceneUtil , mPulseSlow(light.mData.flags & ESM4::Light::PulseSlow) , mOffDefault(light.mData.flags & ESM4::Light::OffDefault) , mColor(SceneUtil::colourFromRGB(light.mData.colour)) - , mRadius(light.mData.radius) + , mRadius(static_cast(light.mData.radius)) { } diff --git a/components/sceneutil/lightmanager.cpp b/components/sceneutil/lightmanager.cpp index 178ea087c0..86482350e9 100644 --- a/components/sceneutil/lightmanager.cpp +++ b/components/sceneutil/lightmanager.cpp @@ -168,7 +168,7 @@ namespace SceneUtil void configureLayout(const LightBuffer* other) { mOffsets = other->mOffsets; - int size = other->mData->size(); + int size = static_cast(other->mData->size()); configureLayout(mOffsets, size); } @@ -192,7 +192,7 @@ namespace SceneUtil : mStride((offsetAttenuationRadius + sizeof(GLfloat) * osg::Vec4::num_components + stride) / 4) { constexpr auto sizeofFloat = sizeof(GLfloat); - const auto diffuseOffset = offsetColors / sizeofFloat; + const auto diffuseOffset = static_cast(offsetColors / sizeofFloat); mValues[Diffuse] = diffuseOffset; mValues[Ambient] = diffuseOffset + 1; @@ -310,11 +310,11 @@ namespace SceneUtil META_StateAttribute(SceneUtil, DisableLight, osg::StateAttribute::LIGHT) - unsigned int getMember() const override { return mIndex; } + unsigned int getMember() const override { return static_cast(mIndex); } bool getModeUsage(ModeUsage& usage) const override { - usage.usesMode(GL_LIGHT0 + mIndex); + usage.usesMode(static_cast(GL_LIGHT0 + mIndex)); return true; } @@ -325,7 +325,7 @@ namespace SceneUtil void apply(osg::State& state) const override { - int lightNum = GL_LIGHT0 + mIndex; + GLenum lightNum = static_cast(GL_LIGHT0 + mIndex); glLightfv(lightNum, GL_AMBIENT, mNullptr.ptr()); glLightfv(lightNum, GL_DIFFUSE, mNullptr.ptr()); glLightfv(lightNum, GL_SPECULAR, mNullptr.ptr()); @@ -360,12 +360,12 @@ namespace SceneUtil { } - unsigned int getMember() const override { return mIndex; } + unsigned int getMember() const override { return static_cast(mIndex); } bool getModeUsage(ModeUsage& usage) const override { for (size_t i = 0; i < mLights.size(); ++i) - usage.usesMode(GL_LIGHT0 + mIndex + i); + usage.usesMode(static_cast(GL_LIGHT0 + mIndex + i)); return true; } @@ -424,7 +424,7 @@ namespace SceneUtil { LightManager* mLightManager; - virtual ~StateSetGenerator() {} + virtual ~StateSetGenerator() = default; virtual osg::ref_ptr generate(const LightManager::LightList& lightList, size_t frameNum) = 0; @@ -451,7 +451,8 @@ namespace SceneUtil new FFPLightStateAttribute(mLightManager->getStartLight(), std::move(lights)), osg::StateAttribute::ON); for (size_t i = 0; i < lightList.size(); ++i) - stateset->setMode(GL_LIGHT0 + mLightManager->getStartLight() + i, osg::StateAttribute::ON); + stateset->setMode( + GL_LIGHT0 + mLightManager->getStartLight() + static_cast(i), osg::StateAttribute::ON); // need to push some dummy attributes to ensure proper state tracking // lights need to reset to their default when the StateSet is popped @@ -533,7 +534,7 @@ namespace SceneUtil configureAttenuation(lightMat, light->getConstantAttenuation(), light->getLinearAttenuation(), light->getQuadraticAttenuation(), lightList[i]->mLightSource->getRadius()); - data->setElement(i + 1, lightMat); + data->setElement(static_cast(i + 1), lightMat); } stateset->addUniform(data); @@ -774,7 +775,8 @@ namespace SceneUtil int stride = -1; ext->glGetActiveUniformBlockiv(handle, 0, GL_UNIFORM_BLOCK_DATA_SIZE, &totalBlockSize); - ext->glGetActiveUniformsiv(handle, index.size(), index.data(), GL_UNIFORM_ARRAY_STRIDE, &stride); + ext->glGetActiveUniformsiv( + handle, static_cast(index.size()), index.data(), GL_UNIFORM_ARRAY_STRIDE, &stride); std::array names = { "LightBuffer[0].packedColors", @@ -784,8 +786,9 @@ namespace SceneUtil std::vector indices(names.size()); std::vector offsets(names.size()); - ext->glGetUniformIndices(handle, names.size(), names.data(), indices.data()); - ext->glGetActiveUniformsiv(handle, indices.size(), indices.data(), GL_UNIFORM_OFFSET, offsets.data()); + ext->glGetUniformIndices(handle, static_cast(names.size()), names.data(), indices.data()); + ext->glGetActiveUniformsiv( + handle, static_cast(indices.size()), indices.data(), GL_UNIFORM_OFFSET, offsets.data()); mTemplate->configureLayout(offsets[0], offsets[1], offsets[2], totalBlockSize, stride); } @@ -1047,7 +1050,7 @@ namespace SceneUtil LightSourceTransform l; l.mLightSource = lightSource; l.mWorldMatrix = worldMat; - osg::Vec3f pos = osg::Vec3f(worldMat.getTrans().x(), worldMat.getTrans().y(), worldMat.getTrans().z()); + osg::Vec3f pos = worldMat.getTrans(); lightSource->getLight(frameNum)->setPosition(osg::Vec4f(pos, 1.f)); mLights.push_back(l); @@ -1094,7 +1097,7 @@ namespace SceneUtil if (getLightIndexMap(frameNum).find(id) != getLightIndexMap(frameNum).end()) continue; - int index = getLightIndexMap(frameNum).size() + 1; + int index = static_cast(getLightIndexMap(frameNum).size()) + 1; updateGPUPointLight(index, lightList[i]->mLightSource, frameNum, viewMatrix); getLightIndexMap(frameNum).emplace(id, index); } @@ -1291,7 +1294,7 @@ namespace SceneUtil const osg::Transform* transform = node->asTransform(); if (transform) { - for (size_t i = 0; i < transform->getNumChildren(); ++i) + for (unsigned int i = 0; i < transform->getNumChildren(); ++i) nodeBound.expandBy(transform->getChild(i)->getBound()); } else diff --git a/components/sceneutil/lightmanager.hpp b/components/sceneutil/lightmanager.hpp index 0b30a77e5c..d6b3771b39 100644 --- a/components/sceneutil/lightmanager.hpp +++ b/components/sceneutil/lightmanager.hpp @@ -55,7 +55,7 @@ namespace SceneUtil void setLight(size_t frame, const osg::Light* light, float radius) { size_t frameId = frame % 2; - size_t i = mIndex[frameId]; + int i = mIndex[frameId]; if (i >= (sMaxPPLights - 1)) return; @@ -74,11 +74,11 @@ namespace SceneUtil void updateCount(size_t frame) { size_t frameId = frame % 2; - mUniformCount[frameId]->set(static_cast(mIndex[frameId])); + mUniformCount[frameId]->set(mIndex[frameId]); } private: - std::array mIndex; + std::array mIndex; std::array, 2> mUniformBuffers; std::array, 2> mUniformCount; }; @@ -106,7 +106,7 @@ namespace SceneUtil float mActorFade; - unsigned int mLastAppliedFrame; + size_t mLastAppliedFrame; bool mEmpty = false; @@ -148,9 +148,9 @@ namespace SceneUtil /// Get the unique ID for this light source. int getId() const { return mId; } - void setLastAppliedFrame(unsigned int lastAppliedFrame) { mLastAppliedFrame = lastAppliedFrame; } + void setLastAppliedFrame(size_t lastAppliedFrame) { mLastAppliedFrame = lastAppliedFrame; } - unsigned int getLastAppliedFrame() const { return mLastAppliedFrame; } + size_t getLastAppliedFrame() const { return mLastAppliedFrame; } }; class UBOManager : public osg::StateAttribute diff --git a/components/sceneutil/lightutil.cpp b/components/sceneutil/lightutil.cpp index 90dc8237f2..2904acd00a 100644 --- a/components/sceneutil/lightutil.cpp +++ b/components/sceneutil/lightutil.cpp @@ -73,7 +73,7 @@ namespace SceneUtil linearAttenuation = linearMethod == 0 ? linearValue : 0.01f; float r = radius * linearRadiusMult; if (r > 0.f && (linearMethod == 1 || linearMethod == 2)) - linearAttenuation = linearValue / std::pow(r, linearMethod); + linearAttenuation = linearValue / std::pow(r, static_cast(linearMethod)); } if (useQuadratic && (!outQuadInLin || isExterior)) @@ -81,7 +81,7 @@ namespace SceneUtil quadraticAttenuation = quadraticMethod == 0 ? quadraticValue : 0.01f; float r = radius * quadraticRadiusMult; if (r > 0.f && (quadraticMethod == 1 || quadraticMethod == 2)) - quadraticAttenuation = quadraticValue / std::pow(r, quadraticMethod); + quadraticAttenuation = quadraticValue / std::pow(r, static_cast(quadraticMethod)); } // If the values are still nonsense, try to at least prevent UB and disable attenuation diff --git a/components/sceneutil/mwshadowtechnique.cpp b/components/sceneutil/mwshadowtechnique.cpp index 7ee4fb9511..fa0269776c 100644 --- a/components/sceneutil/mwshadowtechnique.cpp +++ b/components/sceneutil/mwshadowtechnique.cpp @@ -3341,10 +3341,10 @@ void SceneUtil::MWShadowTechnique::DebugHUD::setFrustumVertices(osg::ref_ptrsetViewport(200 * shadowMapNumber, 0, 200, 200); + mDebugCameras[shadowMapNumber]->setViewport(static_cast(200 * shadowMapNumber), 0, 200, 200); mDebugCameras[shadowMapNumber]->setRenderOrder(osg::Camera::POST_RENDER); mDebugCameras[shadowMapNumber]->setClearColor(osg::Vec4(1.0, 1.0, 0.0, 1.0)); mDebugCameras[shadowMapNumber]->getOrCreateStateSet()->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF); diff --git a/components/sceneutil/mwshadowtechnique.hpp b/components/sceneutil/mwshadowtechnique.hpp index 1b7307024a..a2e811b95e 100644 --- a/components/sceneutil/mwshadowtechnique.hpp +++ b/components/sceneutil/mwshadowtechnique.hpp @@ -300,12 +300,12 @@ namespace SceneUtil { double _splitPointUniformLogRatio = 0.5; double _splitPointDeltaBias = 0.0; - float _polygonOffsetFactor = 1.1; - float _polygonOffsetUnits = 4.0; + float _polygonOffsetFactor = 1.1f; + float _polygonOffsetUnits = 4.0f; bool _useFrontFaceCulling = true; - float _shadowFadeStart = 0.0; + float _shadowFadeStart = 0.0f; unsigned int _worldMask = ~0u; diff --git a/components/sceneutil/pathgridutil.cpp b/components/sceneutil/pathgridutil.cpp index 121ef068d8..013e45998d 100644 --- a/components/sceneutil/pathgridutil.cpp +++ b/components/sceneutil/pathgridutil.cpp @@ -47,16 +47,22 @@ namespace SceneUtil void addPathgridToGeometry(const size_t vertexCount, const size_t pointIndexCount, const size_t edgeIndexCount, osg::ref_ptr& gridGeometry, const ESM::Pathgrid& pathgrid) { - osg::ref_ptr vertices = new osg::Vec3Array(vertexCount); - osg::ref_ptr colors = new osg::Vec4Array(vertexCount); - osg::ref_ptr pointIndices = new PType(osg::PrimitiveSet::TRIANGLES, pointIndexCount); - osg::ref_ptr lineIndices = new LType(osg::PrimitiveSet::LINES, edgeIndexCount); + assert(vertexCount < std::numeric_limits::max()); + assert(pointIndexCount < std::numeric_limits::max()); + assert(edgeIndexCount < std::numeric_limits::max()); + osg::ref_ptr vertices = new osg::Vec3Array(static_cast(vertexCount)); + osg::ref_ptr colors = new osg::Vec4Array(static_cast(vertexCount)); + osg::ref_ptr pointIndices + = new PType(osg::PrimitiveSet::TRIANGLES, static_cast(pointIndexCount)); + osg::ref_ptr lineIndices + = new LType(osg::PrimitiveSet::LINES, static_cast(edgeIndexCount)); // Add each point/node for (size_t pointIndex = 0; pointIndex < pathgrid.mPoints.size(); ++pointIndex) { const ESM::Pathgrid::Point& point = pathgrid.mPoints[pointIndex]; - osg::Vec3f position = osg::Vec3f(point.mX, point.mY, point.mZ); + osg::Vec3f position = osg::Vec3f( + static_cast(point.mX), static_cast(point.mY), static_cast(point.mZ)); size_t vertexOffset = pointIndex * DiamondTotalVertexCount; size_t indexOffset = pointIndex * DiamondIndexCount; @@ -70,7 +76,8 @@ namespace SceneUtil for (unsigned short i = 0; i < DiamondIndexCount; ++i) { - pointIndices->setElement(indexOffset + i, vertexOffset + DiamondIndices[i]); + pointIndices->setElement(static_cast(indexOffset + i), + static_cast(vertexOffset + DiamondIndices[i])); } // Connectors @@ -93,8 +100,10 @@ namespace SceneUtil const ESM::Pathgrid::Point& from = pathgrid.mPoints[edge.mV0]; const ESM::Pathgrid::Point& to = pathgrid.mPoints[edge.mV1]; - osg::Vec3f fromPos = osg::Vec3f(from.mX, from.mY, from.mZ); - osg::Vec3f toPos = osg::Vec3f(to.mX, to.mY, to.mZ); + osg::Vec3f fromPos + = osg::Vec3f(static_cast(from.mX), static_cast(from.mY), static_cast(from.mZ)); + osg::Vec3f toPos + = osg::Vec3f(static_cast(to.mX), static_cast(to.mY), static_cast(to.mZ)); osg::Vec3f dir = toPos - fromPos; dir.normalize(); @@ -138,9 +147,11 @@ namespace SceneUtil osg::ref_ptr& wireframeGeometry, const ESM::Pathgrid& pathgrid, const std::vector& selected) { - osg::ref_ptr vertices = new osg::Vec3Array(vertexCount); - osg::ref_ptr colors = new osg::Vec4Array(vertexCount); - osg::ref_ptr indices = new T(osg::PrimitiveSet::LINES, indexCount); + assert(vertexCount < std::numeric_limits::max()); + assert(indexCount < std::numeric_limits::max()); + osg::ref_ptr vertices = new osg::Vec3Array(static_cast(vertexCount)); + osg::ref_ptr colors = new osg::Vec4Array(static_cast(vertexCount)); + osg::ref_ptr indices = new T(osg::PrimitiveSet::LINES, static_cast(indexCount)); osg::Vec3f wireOffset = osg::Vec3f(0, 0, (1 - DiamondWireframeScalar) * DiamondHalfHeight); @@ -148,7 +159,9 @@ namespace SceneUtil for (size_t it = 0; it < selected.size(); ++it) { const ESM::Pathgrid::Point& point = pathgrid.mPoints[selected[it]]; - osg::Vec3f position = osg::Vec3f(point.mX, point.mY, point.mZ) + wireOffset; + osg::Vec3f position = osg::Vec3f(static_cast(point.mX), static_cast(point.mY), + static_cast(point.mZ)) + + wireOffset; size_t vertexOffset = it * DiamondVertexCount; size_t indexOffset = it * DiamondWireframeIndexCount; @@ -166,7 +179,8 @@ namespace SceneUtil for (unsigned short i = 0; i < DiamondWireframeIndexCount; ++i) { - indices->setElement(indexOffset + i, vertexOffset + DiamondWireframeIndices[i]); + indices->setElement(static_cast(indexOffset + i), + static_cast(vertexOffset + DiamondWireframeIndices[i])); } } diff --git a/components/sceneutil/positionattitudetransform.cpp b/components/sceneutil/positionattitudetransform.cpp index 9e79d042f0..872f5c0827 100644 --- a/components/sceneutil/positionattitudetransform.cpp +++ b/components/sceneutil/positionattitudetransform.cpp @@ -34,13 +34,13 @@ namespace SceneUtil { matrix.postMultTranslate(-_position); matrix.postMultRotate(_attitude.inverse()); - matrix.postMultScale(osg::Vec3f(1.0 / _scale.x(), 1.0 / _scale.y(), 1.0 / _scale.z())); + matrix.postMultScale(osg::Vec3f(1.0f / _scale.x(), 1.0f / _scale.y(), 1.0f / _scale.z())); } else // absolute { matrix.makeRotate(_attitude.inverse()); matrix.preMultTranslate(-_position); - matrix.postMultScale(osg::Vec3f(1.0 / _scale.x(), 1.0 / _scale.y(), 1.0 / _scale.z())); + matrix.postMultScale(osg::Vec3f(1.0f / _scale.x(), 1.0f / _scale.y(), 1.0f / _scale.z())); } return true; } diff --git a/components/sceneutil/recastmesh.cpp b/components/sceneutil/recastmesh.cpp index 89712495f7..78bb26c162 100644 --- a/components/sceneutil/recastmesh.cpp +++ b/components/sceneutil/recastmesh.cpp @@ -32,7 +32,7 @@ namespace const osg::Vec3f e1 = v2 - v0; osg::Vec3f normal = e0 ^ e1; normal.normalize(); - for (std::size_t j = 0; j < 3; ++j) + for (int j = 0; j < 3; ++j) result[i + j] = normal[j]; } return result; diff --git a/components/sceneutil/shadow.cpp b/components/sceneutil/shadow.cpp index a03700578d..0e6abe3258 100644 --- a/components/sceneutil/shadow.cpp +++ b/components/sceneutil/shadow.cpp @@ -61,7 +61,7 @@ namespace SceneUtil else if (Misc::StringUtils::ciEqual(computeSceneBounds, "bounds")) mShadowSettings->setComputeNearFarModeOverride(osg::CullSettings::COMPUTE_NEAR_FAR_USING_BOUNDING_VOLUMES); - const int mapres = settings.mShadowMapResolution; + const short mapres = static_cast(settings.mShadowMapResolution); mShadowSettings->setTextureSize(osg::Vec2s(mapres, mapres)); mShadowTechnique->setSplitPointUniformLogarithmicRatio(settings.mSplitPointUniformLogarithmicRatio); diff --git a/components/sceneutil/statesetupdater.cpp b/components/sceneutil/statesetupdater.cpp index 42dab1cc98..03ab82d98c 100644 --- a/components/sceneutil/statesetupdater.cpp +++ b/components/sceneutil/statesetupdater.cpp @@ -88,14 +88,14 @@ namespace SceneUtil void CompositeStateSetUpdater::apply(osg::StateSet* stateset, osg::NodeVisitor* nv) { - for (unsigned int i = 0; i < mCtrls.size(); ++i) - mCtrls[i]->apply(stateset, nv); + for (const auto& ctrl : mCtrls) + ctrl->apply(stateset, nv); } void CompositeStateSetUpdater::setDefaults(osg::StateSet* stateset) { - for (unsigned int i = 0; i < mCtrls.size(); ++i) - mCtrls[i]->setDefaults(stateset); + for (const auto& ctrl : mCtrls) + ctrl->setDefaults(stateset); } CompositeStateSetUpdater::CompositeStateSetUpdater() {} @@ -103,16 +103,16 @@ namespace SceneUtil CompositeStateSetUpdater::CompositeStateSetUpdater(const CompositeStateSetUpdater& copy, const osg::CopyOp& copyop) : StateSetUpdater(copy, copyop) { - for (unsigned int i = 0; i < copy.mCtrls.size(); ++i) - mCtrls.emplace_back(osg::clone(copy.mCtrls[i].get(), copyop)); + for (const auto& ctrl : copy.mCtrls) + mCtrls.emplace_back(osg::clone(ctrl.get(), copyop)); } - unsigned int CompositeStateSetUpdater::getNumControllers() + size_t CompositeStateSetUpdater::getNumControllers() { return mCtrls.size(); } - StateSetUpdater* CompositeStateSetUpdater::getController(int i) + StateSetUpdater* CompositeStateSetUpdater::getController(size_t i) { return mCtrls[i]; } diff --git a/components/sceneutil/statesetupdater.hpp b/components/sceneutil/statesetupdater.hpp index 261721e3d6..5fa6f8a7c5 100644 --- a/components/sceneutil/statesetupdater.hpp +++ b/components/sceneutil/statesetupdater.hpp @@ -79,8 +79,8 @@ namespace SceneUtil META_Object(SceneUtil, CompositeStateSetUpdater) - unsigned int getNumControllers(); - StateSetUpdater* getController(int i); + size_t getNumControllers(); + StateSetUpdater* getController(size_t i); void addController(StateSetUpdater* ctrl); diff --git a/components/sceneutil/util.cpp b/components/sceneutil/util.cpp index e7a9cab730..a39d5ad9f0 100644 --- a/components/sceneutil/util.cpp +++ b/components/sceneutil/util.cpp @@ -131,8 +131,8 @@ namespace SceneUtil if ((mDuration >= 0) && mStartingTime == 0) mStartingTime = nv->getFrameStamp()->getSimulationTime(); - float time = nv->getFrameStamp()->getSimulationTime(); - int index = (int)(time * 16) % mTextures.size(); + double time = nv->getFrameStamp()->getSimulationTime(); + int index = static_cast(time * 16) % mTextures.size(); stateset->setTextureAttribute( mTexUnit, mTextures[index], osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); diff --git a/components/sceneutil/util.hpp b/components/sceneutil/util.hpp index 5a0280c661..dd29d46cb8 100644 --- a/components/sceneutil/util.hpp +++ b/components/sceneutil/util.hpp @@ -41,7 +41,7 @@ namespace SceneUtil float mDuration; float mOriginalDuration; // for recording that this is originally a permanent glow if it is changed to a // temporary one - float mStartingTime; + double mStartingTime; Resource::ResourceSystem* mResourceSystem; bool mColorChanged; bool mDone; diff --git a/components/sceneutil/waterutil.cpp b/components/sceneutil/waterutil.cpp index 7e739945aa..4066fd2319 100644 --- a/components/sceneutil/waterutil.cpp +++ b/components/sceneutil/waterutil.cpp @@ -58,7 +58,8 @@ namespace SceneUtil normal->push_back(osg::Vec3f(0, 0, 1)); waterGeom->setNormalArray(normal, osg::Array::BIND_OVERALL); - waterGeom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS, 0, verts->size())); + waterGeom->addPrimitiveSet( + new osg::DrawArrays(osg::PrimitiveSet::QUADS, 0, static_cast(verts->size()))); waterGeom->setComputeBoundingBoxCallback(new WaterBoundCallback); waterGeom->setCullingActive(false); return waterGeom; diff --git a/components/sceneutil/workqueue.cpp b/components/sceneutil/workqueue.cpp index c398324aa9..7c24d6d384 100644 --- a/components/sceneutil/workqueue.cpp +++ b/components/sceneutil/workqueue.cpp @@ -99,13 +99,13 @@ namespace SceneUtil return nullptr; } - unsigned int WorkQueue::getNumItems() const + size_t WorkQueue::getNumItems() const { std::unique_lock lock(mMutex); return mQueue.size(); } - unsigned int WorkQueue::getNumActiveThreads() const + size_t WorkQueue::getNumActiveThreads() const { return std::accumulate( mThreads.begin(), mThreads.end(), 0u, [](auto r, const auto& t) { return r + t->isActive(); }); diff --git a/components/sceneutil/workqueue.hpp b/components/sceneutil/workqueue.hpp index d167c4d7e4..8d7f5a9ec9 100644 --- a/components/sceneutil/workqueue.hpp +++ b/components/sceneutil/workqueue.hpp @@ -62,9 +62,9 @@ namespace SceneUtil /// @par Used internally by the WorkThread. osg::ref_ptr removeWorkItem(); - unsigned int getNumItems() const; + size_t getNumItems() const; - unsigned int getNumActiveThreads() const; + size_t getNumActiveThreads() const; private: bool mIsReleased; diff --git a/components/sdlutil/sdlinputwrapper.cpp b/components/sdlutil/sdlinputwrapper.cpp index 5786517b88..8bb802bb7c 100644 --- a/components/sdlutil/sdlinputwrapper.cpp +++ b/components/sdlutil/sdlinputwrapper.cpp @@ -39,7 +39,7 @@ namespace SDLUtil _setWindowScale(); } - InputWrapper::~InputWrapper() {} + InputWrapper::~InputWrapper() = default; void InputWrapper::_setWindowScale() { @@ -47,8 +47,8 @@ namespace SDLUtil SDL_GetWindowSize(mSDLWindow, &w, &h); int dw, dh; SDL_GL_GetDrawableSize(mSDLWindow, &dw, &dh); - mScaleX = dw / w; - mScaleY = dh / h; + mScaleX = static_cast(dw / w); + mScaleY = static_cast(dh / h); } void InputWrapper::capture(bool windowEventsOnly) @@ -320,8 +320,8 @@ namespace SDLUtil { SDL_WarpMouseInWindow(mSDLWindow, x, y); mWarpCompensate = true; - mWarpX = x; - mWarpY = y; + mWarpX = static_cast(x); + mWarpY = static_cast(y); } /// \brief Locks the pointer to the window diff --git a/components/settings/categories/stereoview.hpp b/components/settings/categories/stereoview.hpp index 7f08d9bc35..0c3c74846c 100644 --- a/components/settings/categories/stereoview.hpp +++ b/components/settings/categories/stereoview.hpp @@ -20,9 +20,9 @@ namespace Settings SettingValue mEyeResolutionX{ mIndex, "Stereo View", "eye resolution x", makeMaxSanitizerInt(1) }; SettingValue mEyeResolutionY{ mIndex, "Stereo View", "eye resolution y", makeMaxSanitizerInt(1) }; - SettingValue mLeftEyeOffsetX{ mIndex, "Stereo View", "left eye offset x" }; - SettingValue mLeftEyeOffsetY{ mIndex, "Stereo View", "left eye offset y" }; - SettingValue mLeftEyeOffsetZ{ mIndex, "Stereo View", "left eye offset z" }; + SettingValue mLeftEyeOffsetX{ mIndex, "Stereo View", "left eye offset x" }; + SettingValue mLeftEyeOffsetY{ mIndex, "Stereo View", "left eye offset y" }; + SettingValue mLeftEyeOffsetZ{ mIndex, "Stereo View", "left eye offset z" }; SettingValue mLeftEyeOrientationX{ mIndex, "Stereo View", "left eye orientation x", makeClampSanitizerDouble(-1, 1) }; SettingValue mLeftEyeOrientationY{ mIndex, "Stereo View", "left eye orientation y", @@ -39,9 +39,9 @@ namespace Settings makeClampSanitizerFloat(-osg::PIf, osg::PIf) }; SettingValue mLeftEyeFovDown{ mIndex, "Stereo View", "left eye fov down", makeClampSanitizerFloat(-osg::PIf, osg::PIf) }; - SettingValue mRightEyeOffsetX{ mIndex, "Stereo View", "right eye offset x" }; - SettingValue mRightEyeOffsetY{ mIndex, "Stereo View", "right eye offset y" }; - SettingValue mRightEyeOffsetZ{ mIndex, "Stereo View", "right eye offset z" }; + SettingValue mRightEyeOffsetX{ mIndex, "Stereo View", "right eye offset x" }; + SettingValue mRightEyeOffsetY{ mIndex, "Stereo View", "right eye offset y" }; + SettingValue mRightEyeOffsetZ{ mIndex, "Stereo View", "right eye offset z" }; SettingValue mRightEyeOrientationX{ mIndex, "Stereo View", "right eye orientation x", makeClampSanitizerDouble(-1, 1) }; SettingValue mRightEyeOrientationY{ mIndex, "Stereo View", "right eye orientation y", diff --git a/components/shader/shadermanager.cpp b/components/shader/shadermanager.cpp index f44c8f475d..82fbc90480 100644 --- a/components/shader/shadermanager.cpp +++ b/components/shader/shadermanager.cpp @@ -69,7 +69,8 @@ namespace { lineDirectivePosition = 0; } - lineNumber += std::count(source.begin() + lineDirectivePosition, source.begin() + foundPos, '\n'); + lineNumber + += static_cast(std::count(source.begin() + lineDirectivePosition, source.begin() + foundPos, '\n')); return lineNumber; } } diff --git a/components/shader/shadervisitor.cpp b/components/shader/shadervisitor.cpp index 0e6b5e79c6..40bba966d1 100644 --- a/components/shader/shadervisitor.cpp +++ b/components/shader/shadervisitor.cpp @@ -441,7 +441,7 @@ namespace Shader normalMapTex->setMaxAnisotropy(diffuseMap->getMaxAnisotropy()); normalMap = normalMapTex; - int unit = texAttributes.size(); + int unit = static_cast(texAttributes.size()); if (!writableStateSet) writableStateSet = getWritableStateSet(node); writableStateSet->setTextureAttributeAndModes(unit, normalMapTex, osg::StateAttribute::ON); @@ -487,7 +487,7 @@ namespace Shader osg::Texture::MAG_FILTER, diffuseMap->getFilter(osg::Texture::MAG_FILTER)); specularMapTex->setMaxAnisotropy(diffuseMap->getMaxAnisotropy()); - int unit = texAttributes.size(); + int unit = static_cast(texAttributes.size()); if (!writableStateSet) writableStateSet = getWritableStateSet(node); writableStateSet->setTextureAttributeAndModes(unit, specularMapTex, osg::StateAttribute::ON); diff --git a/components/std140/ubo.hpp b/components/std140/ubo.hpp index f000307a1c..e036219ca1 100644 --- a/components/std140/ubo.hpp +++ b/components/std140/ubo.hpp @@ -12,7 +12,7 @@ #include #include -namespace std140 +namespace Std140 { struct Mat4 { diff --git a/components/stereo/multiview.cpp b/components/stereo/multiview.cpp index 25b0ccfc21..3e76222955 100644 --- a/components/stereo/multiview.cpp +++ b/components/stereo/multiview.cpp @@ -52,7 +52,7 @@ namespace Stereo bool getTextureViewSupportedImpl(unsigned int contextID) { - if (!osg::isGLExtensionOrVersionSupported(contextID, "ARB_texture_view", 4.3)) + if (!osg::isGLExtensionOrVersionSupported(contextID, "ARB_texture_view", 4.3f)) { Log(Debug::Verbose) << "Disabling texture views (opengl extension \"ARB_texture_view\" not supported)"; return false; diff --git a/components/stereo/stereomanager.cpp b/components/stereo/stereomanager.cpp index a2b7b2c7f3..e089229699 100644 --- a/components/stereo/stereomanager.cpp +++ b/components/stereo/stereomanager.cpp @@ -114,7 +114,7 @@ namespace Stereo return *sInstance; } - Manager::Manager(osgViewer::Viewer* viewer, bool enableStereo, double near, double far) + Manager::Manager(osgViewer::Viewer* viewer, bool enableStereo, float near, float far) : mViewer(viewer) , mMainCamera(mViewer->getCamera()) , mUpdateCallback(new StereoUpdateCallback(this)) @@ -182,8 +182,8 @@ namespace Stereo { if (mEyeResolutionOverriden) return mEyeResolutionOverride; - auto width = mMainCamera->getViewport()->width() / 2; - auto height = mMainCamera->getViewport()->height(); + auto width = static_cast(mMainCamera->getViewport()->width() / 2); + auto height = static_cast(mMainCamera->getViewport()->height()); return osg::Vec2i(width, height); } diff --git a/components/stereo/stereomanager.hpp b/components/stereo/stereomanager.hpp index 8ed88da550..3e4c66f24d 100644 --- a/components/stereo/stereomanager.hpp +++ b/components/stereo/stereomanager.hpp @@ -78,13 +78,13 @@ namespace Stereo //! @Param enableMultiview whether or not to make use of the GL_OVR_Multiview extension, if supported. //! @Param near defines distance to near camera clipping plane from view point. //! @Param far defines distance to far camera clipping plane from view point. - explicit Manager(osgViewer::Viewer* viewer, bool enableStereo, double near, double far); + explicit Manager(osgViewer::Viewer* viewer, bool enableStereo, float near, float far); ~Manager(); //! Called during update traversal void update(); - void updateSettings(double near, double far) + void updateSettings(float near, float far) { mNear = near; mFar = far; @@ -146,8 +146,8 @@ namespace Stereo std::shared_ptr mMultiviewFramebuffer; bool mEyeResolutionOverriden; osg::Vec2i mEyeResolutionOverride; - double mNear; - double mFar; + float mNear; + float mFar; std::array mView; std::array mViewOffsetMatrix; diff --git a/components/stereo/types.cpp b/components/stereo/types.cpp index 99b7da5ad1..0c29e04795 100644 --- a/components/stereo/types.cpp +++ b/components/stereo/types.cpp @@ -60,15 +60,18 @@ namespace Stereo // that view matrix will already convert points to a camera space // with opengl conventions. So we need to convert offsets to opengl // conventions. - float y = position.y(); - float z = position.z(); - position.y() = z; - position.z() = -y; - - y = orientation.y(); - z = orientation.z(); - orientation.y() = z; - orientation.z() = -y; + { + float y = position.y(); + float z = position.z(); + position.y() = z; + position.z() = -y; + } + { + double y = orientation.y(); + double z = orientation.z(); + orientation.y() = z; + orientation.z() = -y; + } osg::Matrix viewMatrix; viewMatrix.setTrans(-position); diff --git a/components/terrain/buffercache.cpp b/components/terrain/buffercache.cpp index 6dc4f8dab9..4cbf435353 100644 --- a/components/terrain/buffercache.cpp +++ b/components/terrain/buffercache.cpp @@ -12,6 +12,7 @@ namespace template osg::ref_ptr createIndexBuffer(unsigned int flags, unsigned int verts) { + using IndexType = IndexArrayType::value_type; // LOD level n means every 2^n-th vertex is kept, but we currently handle LOD elsewhere. size_t lodLevel = 0; //(flags >> (4*4)); @@ -45,23 +46,23 @@ namespace // diamond pattern if ((row + col % 2) % 2 == 1) { - indices->push_back(verts * (col + increment) + row); - indices->push_back(verts * (col + increment) + row + increment); - indices->push_back(verts * col + row + increment); + indices->push_back(static_cast(verts * (col + increment) + row)); + indices->push_back(static_cast(verts * (col + increment) + row + increment)); + indices->push_back(static_cast(verts * col + row + increment)); - indices->push_back(verts * col + row); - indices->push_back(verts * (col + increment) + row); - indices->push_back(verts * (col) + row + increment); + indices->push_back(static_cast(verts * col + row)); + indices->push_back(static_cast(verts * (col + increment) + row)); + indices->push_back(static_cast(verts * (col) + row + increment)); } else { - indices->push_back(verts * col + row); - indices->push_back(verts * (col + increment) + row + increment); - indices->push_back(verts * col + row + increment); + indices->push_back(static_cast(verts * col + row)); + indices->push_back(static_cast(verts * (col + increment) + row + increment)); + indices->push_back(static_cast(verts * col + row + increment)); - indices->push_back(verts * col + row); - indices->push_back(verts * (col + increment) + row); - indices->push_back(verts * (col + increment) + row + increment); + indices->push_back(static_cast(verts * col + row)); + indices->push_back(static_cast(verts * (col + increment) + row)); + indices->push_back(static_cast(verts * (col + increment) + row + increment)); } } } @@ -77,22 +78,22 @@ namespace size_t outerStep = static_cast(1) << (lodDeltas[Terrain::South] + lodLevel); for (size_t col = 0; col < verts - 1; col += outerStep) { - indices->push_back(verts * col + row); - indices->push_back(verts * (col + outerStep) + row); + indices->push_back(static_cast(verts * col + row)); + indices->push_back(static_cast(verts * (col + outerStep) + row)); // Make sure not to touch the right edge if (col + outerStep == verts - 1) - indices->push_back(verts * (col + outerStep - innerStep) + row + innerStep); + indices->push_back(static_cast(verts * (col + outerStep - innerStep) + row + innerStep)); else - indices->push_back(verts * (col + outerStep) + row + innerStep); + indices->push_back(static_cast(verts * (col + outerStep) + row + innerStep)); for (size_t i = 0; i < outerStep; i += innerStep) { // Make sure not to touch the left or right edges if (col + i == 0 || col + i == verts - 1 - innerStep) continue; - indices->push_back(verts * (col) + row); - indices->push_back(verts * (col + i + innerStep) + row + innerStep); - indices->push_back(verts * (col + i) + row + innerStep); + indices->push_back(static_cast(verts * (col) + row)); + indices->push_back(static_cast(verts * (col + i + innerStep) + row + innerStep)); + indices->push_back(static_cast(verts * (col + i) + row + innerStep)); } } @@ -101,22 +102,22 @@ namespace outerStep = size_t(1) << (lodDeltas[Terrain::North] + lodLevel); for (size_t col = 0; col < verts - 1; col += outerStep) { - indices->push_back(verts * (col + outerStep) + row); - indices->push_back(verts * col + row); + indices->push_back(static_cast(verts * (col + outerStep) + row)); + indices->push_back(static_cast(verts * col + row)); // Make sure not to touch the left edge if (col == 0) - indices->push_back(verts * (col + innerStep) + row - innerStep); + indices->push_back(static_cast(verts * (col + innerStep) + row - innerStep)); else - indices->push_back(verts * col + row - innerStep); + indices->push_back(static_cast(verts * col + row - innerStep)); for (size_t i = 0; i < outerStep; i += innerStep) { // Make sure not to touch the left or right edges if (col + i == 0 || col + i == verts - 1 - innerStep) continue; - indices->push_back(verts * (col + i) + row - innerStep); - indices->push_back(verts * (col + i + innerStep) + row - innerStep); - indices->push_back(verts * (col + outerStep) + row); + indices->push_back(static_cast(verts * (col + i) + row - innerStep)); + indices->push_back(static_cast(verts * (col + i + innerStep) + row - innerStep)); + indices->push_back(static_cast(verts * (col + outerStep) + row)); } } @@ -125,22 +126,22 @@ namespace outerStep = size_t(1) << (lodDeltas[Terrain::West] + lodLevel); for (row = 0; row < verts - 1; row += outerStep) { - indices->push_back(verts * col + row + outerStep); - indices->push_back(verts * col + row); + indices->push_back(static_cast(verts * col + row + outerStep)); + indices->push_back(static_cast(verts * col + row)); // Make sure not to touch the top edge if (row + outerStep == verts - 1) - indices->push_back(verts * (col + innerStep) + row + outerStep - innerStep); + indices->push_back(static_cast(verts * (col + innerStep) + row + outerStep - innerStep)); else - indices->push_back(verts * (col + innerStep) + row + outerStep); + indices->push_back(static_cast(verts * (col + innerStep) + row + outerStep)); for (size_t i = 0; i < outerStep; i += innerStep) { // Make sure not to touch the top or bottom edges if (row + i == 0 || row + i == verts - 1 - innerStep) continue; - indices->push_back(verts * col + row); - indices->push_back(verts * (col + innerStep) + row + i); - indices->push_back(verts * (col + innerStep) + row + i + innerStep); + indices->push_back(static_cast(verts * col + row)); + indices->push_back(static_cast(verts * (col + innerStep) + row + i)); + indices->push_back(static_cast(verts * (col + innerStep) + row + i + innerStep)); } } @@ -149,22 +150,22 @@ namespace outerStep = size_t(1) << (lodDeltas[Terrain::East] + lodLevel); for (row = 0; row < verts - 1; row += outerStep) { - indices->push_back(verts * col + row); - indices->push_back(verts * col + row + outerStep); + indices->push_back(static_cast(verts * col + row)); + indices->push_back(static_cast(verts * col + row + outerStep)); // Make sure not to touch the bottom edge if (row == 0) - indices->push_back(verts * (col - innerStep) + row + innerStep); + indices->push_back(static_cast(verts * (col - innerStep) + row + innerStep)); else - indices->push_back(verts * (col - innerStep) + row); + indices->push_back(static_cast(verts * (col - innerStep) + row)); for (size_t i = 0; i < outerStep; i += innerStep) { // Make sure not to touch the top or bottom edges if (row + i == 0 || row + i == verts - 1 - innerStep) continue; - indices->push_back(verts * col + row + outerStep); - indices->push_back(verts * (col - innerStep) + row + i + innerStep); - indices->push_back(verts * (col - innerStep) + row + i); + indices->push_back(static_cast(verts * col + row + outerStep)); + indices->push_back(static_cast(verts * (col - innerStep) + row + i + innerStep)); + indices->push_back(static_cast(verts * (col - innerStep) + row + i)); } } } diff --git a/components/terrain/cellborder.cpp b/components/terrain/cellborder.cpp index b78691cd8d..bc257ab407 100644 --- a/components/terrain/cellborder.cpp +++ b/components/terrain/cellborder.cpp @@ -62,7 +62,7 @@ namespace Terrain border->setColorArray(colors.get()); border->setColorBinding(osg::Geometry::BIND_PER_VERTEX); - border->addPrimitiveSet(new osg::DrawArrays(GL_LINE_STRIP, 0, vertices->size())); + border->addPrimitiveSet(new osg::DrawArrays(GL_LINE_STRIP, 0, static_cast(vertices->size()))); osg::ref_ptr borderGroup = new osg::Group; borderGroup->addChild(border.get()); @@ -84,8 +84,8 @@ namespace Terrain void CellBorder::createCellBorderGeometry(int x, int y) { - auto borderGroup = createBorderGeometry( - x, y, 1.f, mWorld->getStorage(), mSceneManager, mBorderMask, mWorld->getWorldspace()); + auto borderGroup = createBorderGeometry(static_cast(x), static_cast(y), 1.f, mWorld->getStorage(), + mSceneManager, mBorderMask, mWorld->getWorldspace()); mRoot->addChild(borderGroup); mCellBorderNodes[std::make_pair(x, y)] = borderGroup; diff --git a/components/terrain/chunkmanager.cpp b/components/terrain/chunkmanager.cpp index 242f3e5700..dcb872ec55 100644 --- a/components/terrain/chunkmanager.cpp +++ b/components/terrain/chunkmanager.cpp @@ -206,10 +206,10 @@ namespace Terrain blendmapTextures.push_back(texture); } - float tileCount = mStorage->getTextureTileCount(chunkSize, mWorldspace); + int tileCount = mStorage->getTextureTileCount(chunkSize, mWorldspace); - return ::Terrain::createPasses( - useShaders, mSceneManager, layers, blendmapTextures, tileCount, tileCount, ESM::isEsm4Ext(mWorldspace)); + return ::Terrain::createPasses(useShaders, mSceneManager, layers, blendmapTextures, tileCount, + static_cast(tileCount), ESM::isEsm4Ext(mWorldspace)); } osg::ref_ptr ChunkManager::createChunk(float chunkSize, const osg::Vec2f& chunkCenter, unsigned char lod, @@ -261,7 +261,8 @@ namespace Terrain if (chunkSize <= 1.f) geometry->setLightListCallback(new SceneUtil::LightListCallback); - unsigned int numVerts = (mStorage->getCellVertices(mWorldspace) - 1) * chunkSize / (1 << lod) + 1; + unsigned int numVerts + = static_cast((mStorage->getCellVertices(mWorldspace) - 1) * chunkSize / (1 << lod) + 1); geometry->addPrimitiveSet(mBufferCache.getIndexBuffer(numVerts, lodFlags)); @@ -303,7 +304,7 @@ namespace Terrain layer.mSpecular = false; geometry->setPasses(::Terrain::createPasses( mSceneManager->getForceShaders() || !mSceneManager->getClampLighting(), mSceneManager, - std::vector(1, layer), std::vector>(), 1.f, 1.f)); + std::vector(1, layer), std::vector>(), 1, 1.f)); } else { diff --git a/components/terrain/compositemaprenderer.cpp b/components/terrain/compositemaprenderer.cpp index adf58162e8..7a03015344 100644 --- a/components/terrain/compositemaprenderer.cpp +++ b/components/terrain/compositemaprenderer.cpp @@ -21,7 +21,7 @@ namespace Terrain getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF); } - CompositeMapRenderer::~CompositeMapRenderer() {} + CompositeMapRenderer::~CompositeMapRenderer() = default; void CompositeMapRenderer::drawImplementation(osg::RenderInfo& renderInfo) const { @@ -104,7 +104,7 @@ namespace Terrain // should OSG be doing this on its own? state.haveAppliedTextureAttribute(state.getActiveTextureUnit(), osg::StateAttribute::TEXTURE); - for (unsigned int i = compositeMap.mCompiled; i < compositeMap.mDrawables.size(); ++i) + for (size_t i = compositeMap.mCompiled; i < compositeMap.mDrawables.size(); ++i) { osg::Drawable* drw = compositeMap.mDrawables[i]; osg::StateSet* stateset = drw->getStateSet(); @@ -165,7 +165,7 @@ namespace Terrain } } - unsigned int CompositeMapRenderer::getCompileSetSize() const + size_t CompositeMapRenderer::getCompileSetSize() const { std::lock_guard lock(mMutex); return mCompileSet.size(); diff --git a/components/terrain/compositemaprenderer.hpp b/components/terrain/compositemaprenderer.hpp index 1e33c717ec..24849e0e86 100644 --- a/components/terrain/compositemaprenderer.hpp +++ b/components/terrain/compositemaprenderer.hpp @@ -23,7 +23,7 @@ namespace Terrain ~CompositeMap(); std::vector> mDrawables; osg::ref_ptr mTexture; - unsigned int mCompiled; + size_t mCompiled; }; /** @@ -52,7 +52,7 @@ namespace Terrain /// Mark this composite map to be required for the current frame void setImmediate(CompositeMap* map); - unsigned int getCompileSetSize() const; + size_t getCompileSetSize() const; private: float mTargetFrameRate; diff --git a/components/terrain/material.cpp b/components/terrain/material.cpp index 350b174d69..c04d8d8da6 100644 --- a/components/terrain/material.cpp +++ b/components/terrain/material.cpp @@ -24,17 +24,17 @@ namespace static const osg::ref_ptr& value(const int blendmapScale) { static BlendmapTexMat instance; - return instance.get(blendmapScale); + return instance.get(static_cast(blendmapScale)); } - const osg::ref_ptr& get(const int blendmapScale) + const osg::ref_ptr& get(const float blendmapScale) { const std::lock_guard lock(mMutex); auto texMat = mTexMatMap.find(blendmapScale); if (texMat == mTexMatMap.end()) { osg::Matrixf matrix; - float scale = (blendmapScale / (static_cast(blendmapScale) + 1.f)); + float scale = (blendmapScale / (blendmapScale + 1.f)); matrix.preMultTranslate(osg::Vec3f(0.5f, 0.5f, 0.f)); matrix.preMultScale(osg::Vec3f(scale, scale, 1.f)); matrix.preMultTranslate(osg::Vec3f(-0.5f, -0.5f, 0.f)); @@ -43,8 +43,7 @@ namespace // blendmap, apparently. matrix.preMultTranslate(osg::Vec3f(1.0f / blendmapScale / 4.0f, 1.0f / blendmapScale / 4.0f, 0.f)); - texMat = mTexMatMap.insert(std::make_pair(static_cast(blendmapScale), new osg::TexMat(matrix))) - .first; + texMat = mTexMatMap.emplace(blendmapScale, new osg::TexMat(matrix)).first; } return texMat->second; } diff --git a/components/terrain/quadtreenode.hpp b/components/terrain/quadtreenode.hpp index abe92b1ba9..0f5c689682 100644 --- a/components/terrain/quadtreenode.hpp +++ b/components/terrain/quadtreenode.hpp @@ -44,7 +44,7 @@ namespace Terrain inline QuadTreeNode* getParent() { return mParent; } inline QuadTreeNode* getChild(unsigned int i) { return static_cast(Group::getChild(i)); } - inline unsigned int getNumChildren() const override { return _children.size(); } + inline unsigned int getNumChildren() const override { return static_cast(_children.size()); } // osg::Group::addChild() does a lot of unrelated stuff, but we just really want to add a child node. void addChildNode(QuadTreeNode* child) diff --git a/components/terrain/quadtreeworld.cpp b/components/terrain/quadtreeworld.cpp index 0d7f1b7762..8a91941fe0 100644 --- a/components/terrain/quadtreeworld.cpp +++ b/components/terrain/quadtreeworld.cpp @@ -145,7 +145,7 @@ namespace Terrain float centerX = (mMinX + mMaxX) / 2.f + (size - origSizeX) / 2.f; float centerY = (mMinY + mMaxY) / 2.f + (size - origSizeY) / 2.f; - mRootNode = new RootNode(size, osg::Vec2f(centerX, centerY)); + mRootNode = new RootNode(static_cast(size), osg::Vec2f(centerX, centerY)); addChildren(mRootNode); mRootNode->initNeighbours(); @@ -212,7 +212,8 @@ namespace Terrain // Do not add child nodes for default cells without data. // size = 1 means that the single shape covers the whole cell. if (node->getSize() == 1 - && !mStorage->hasData(ESM::ExteriorCellLocation(center.x() - 0.5, center.y() - 0.5, mWorldspace))) + && !mStorage->hasData(ESM::ExteriorCellLocation( + static_cast(center.x() - 0.5f), static_cast(center.y() - 0.5f), mWorldspace))) return node; if (node->getSize() <= mMinSize) @@ -259,14 +260,14 @@ namespace Terrain , mNodeMask(nodeMask) { } - osg::ref_ptr getChunk(float size, const osg::Vec2f& chunkCenter, unsigned char lod, + osg::ref_ptr getChunk(float size, const osg::Vec2f& chunkCenter, unsigned char /*lod*/, unsigned int lodFlags, bool activeGrid, const osg::Vec3f& viewPoint, bool compile) { osg::Vec3f center = { chunkCenter.x(), chunkCenter.y(), 0 }; auto chunkBorder = CellBorder::createBorderGeometry(center.x() - size / 2.f, center.y() - size / 2.f, size, mStorage, mSceneManager, mNodeMask, mWorldspace, 5.f, { 1, 0, 0, 0 }); osg::ref_ptr pat = new SceneUtil::PositionAttitudeTransform; - pat->setPosition(-center * ESM::getCellSize(mWorldspace)); + pat->setPosition(-center * static_cast(ESM::getCellSize(mWorldspace))); pat->addChild(chunkBorder); return pat; } @@ -396,8 +397,8 @@ namespace Terrain for (QuadTreeWorld::ChunkManager* m : mChunkManagers) { osg::ref_ptr n = m->getChunk(entry.mNode->getSize(), entry.mNode->getCenter(), - DefaultLodCallback::getNativeLodLevel(entry.mNode, mMinSize), entry.mLodFlags, activeGrid, - vd->getViewPoint(), compile); + static_cast(DefaultLodCallback::getNativeLodLevel(entry.mNode, mMinSize)), + entry.mLodFlags, activeGrid, vd->getViewPoint(), compile); if (n) pat->addChild(n); } @@ -487,7 +488,7 @@ namespace Terrain mRootNode->traverseNodes(vd, viewPoint, &lodCallback); } - const float cellWorldSize = ESM::getCellSize(mWorldspace); + const float cellWorldSize = static_cast(ESM::getCellSize(mWorldspace)); for (unsigned int i = 0; i < vd->getNumEntries(); ++i) { @@ -552,7 +553,7 @@ namespace Terrain vd->setViewPoint(viewPoint); vd->setActiveGrid(grid); - DefaultLodCallback lodCallback(mLodFactor, mMinSize, mViewDistance, grid, cellWorldSize); + DefaultLodCallback lodCallback(mLodFactor, mMinSize, mViewDistance, grid, static_cast(cellWorldSize)); mRootNode->traverseNodes(vd, viewPoint, &lodCallback); reporter.addTotal(vd->getNumEntries()); @@ -568,14 +569,15 @@ namespace Terrain void QuadTreeWorld::reportStats(unsigned int frameNumber, osg::Stats* stats) { if (mCompositeMapRenderer) - stats->setAttribute(frameNumber, "Composite", mCompositeMapRenderer->getCompileSetSize()); + stats->setAttribute( + frameNumber, "Composite", static_cast(mCompositeMapRenderer->getCompileSetSize())); } void QuadTreeWorld::loadCell(int x, int y) { // fallback behavior only for undefined cells (every other is already handled in quadtree) float dummy; - if (mChunkManager && !mStorage->getMinMaxHeights(1, osg::Vec2f(x + 0.5, y + 0.5), mWorldspace, dummy, dummy)) + if (mChunkManager && !mStorage->getMinMaxHeights(1, osg::Vec2f(x + 0.5f, y + 0.5f), mWorldspace, dummy, dummy)) TerrainGrid::loadCell(x, y); else World::loadCell(x, y); @@ -585,7 +587,7 @@ namespace Terrain { // fallback behavior only for undefined cells (every other is already handled in quadtree) float dummy; - if (mChunkManager && !mStorage->getMinMaxHeights(1, osg::Vec2f(x + 0.5, y + 0.5), mWorldspace, dummy, dummy)) + if (mChunkManager && !mStorage->getMinMaxHeights(1, osg::Vec2f(x + 0.5f, y + 0.5f), mWorldspace, dummy, dummy)) TerrainGrid::unloadCell(x, y); else World::unloadCell(x, y); @@ -598,7 +600,7 @@ namespace Terrain if (m->getViewDistance()) m->setMaxLodLevel( DefaultLodCallback::convertDistanceToLodLevel(m->getViewDistance() + mViewDataMap->getReuseDistance(), - mMinSize, ESM::getCellSize(mWorldspace), mLodFactor)); + mMinSize, mLodFactor, ESM::getCellSize(mWorldspace))); } void QuadTreeWorld::rebuildViews() diff --git a/components/terrain/quadtreeworld.hpp b/components/terrain/quadtreeworld.hpp index fa800d2655..56962a5529 100644 --- a/components/terrain/quadtreeworld.hpp +++ b/components/terrain/quadtreeworld.hpp @@ -59,7 +59,7 @@ namespace Terrain class ChunkManager { public: - virtual ~ChunkManager() {} + virtual ~ChunkManager() = default; ChunkManager() = default; ChunkManager(ESM::RefId worldspace) : ChunkManager() diff --git a/components/terrain/storage.hpp b/components/terrain/storage.hpp index 38aee20b8b..436efd8e31 100644 --- a/components/terrain/storage.hpp +++ b/components/terrain/storage.hpp @@ -25,7 +25,7 @@ namespace Terrain class Storage { public: - virtual ~Storage() {} + virtual ~Storage() = default; public: /// Get bounds of the whole terrain in cell units @@ -36,8 +36,8 @@ namespace Terrain virtual bool hasData(ESM::ExteriorCellLocation cellLocation) { float dummy; - return getMinMaxHeights( - 1, osg::Vec2f(cellLocation.mX + 0.5, cellLocation.mY + 0.5), cellLocation.mWorldspace, dummy, dummy); + return getMinMaxHeights(1.f, osg::Vec2f(cellLocation.mX + 0.5f, cellLocation.mY + 0.5f), + cellLocation.mWorldspace, dummy, dummy); } /// Get the minimum and maximum heights of a terrain region. diff --git a/components/terrain/terraindrawable.cpp b/components/terrain/terraindrawable.cpp index 65f7aaf98b..20df85b6ba 100644 --- a/components/terrain/terraindrawable.cpp +++ b/components/terrain/terraindrawable.cpp @@ -12,7 +12,7 @@ namespace Terrain TerrainDrawable::TerrainDrawable() {} - TerrainDrawable::~TerrainDrawable() {} + TerrainDrawable::~TerrainDrawable() = default; TerrainDrawable::TerrainDrawable(const TerrainDrawable& copy, const osg::CopyOp& copyop) : osg::Geometry(copy, copyop) @@ -37,8 +37,8 @@ namespace Terrain inline float distance(const osg::Vec3& coord, const osg::Matrix& matrix) { - return -((float)coord[0] * (float)matrix(0, 2) + (float)coord[1] * (float)matrix(1, 2) - + (float)coord[2] * (float)matrix(2, 2) + matrix(3, 2)); + return -(coord[0] * static_cast(matrix(0, 2)) + coord[1] * static_cast(matrix(1, 2)) + + coord[2] * static_cast(matrix(2, 2)) + static_cast(matrix(3, 2))); } // canot use ClusterCullingCallback::cull: viewpoint != eyepoint diff --git a/components/widgets/box.cpp b/components/widgets/box.cpp index 49e10b49e8..db939d3e3f 100644 --- a/components/widgets/box.cpp +++ b/components/widgets/box.cpp @@ -176,14 +176,14 @@ namespace Gui void HBox::align() { - unsigned int count = getChildCount(); - size_t hStretchedCount = 0; + const size_t count = getChildCount(); + int hStretchedCount = 0; int totalWidth = 0; int totalHeight = 0; std::vector> sizes; sizes.resize(count); - for (unsigned int i = 0; i < count; ++i) + for (size_t i = 0; i < count; ++i) { MyGUI::Widget* w = getChildAt(i); bool hstretch = w->getUserString("HStretch") == "true"; @@ -221,7 +221,7 @@ namespace Gui } int curX = 0; - for (unsigned int i = 0; i < count; ++i) + for (size_t i = 0; i < count; ++i) { if (i == 0) curX += mPadding; @@ -328,13 +328,13 @@ namespace Gui void VBox::align() { - unsigned int count = getChildCount(); - size_t vStretchedCount = 0; + const size_t count = getChildCount(); + int vStretchedCount = 0; int totalHeight = 0; int totalWidth = 0; std::vector> sizes; sizes.resize(count); - for (unsigned int i = 0; i < count; ++i) + for (size_t i = 0; i < count; ++i) { MyGUI::Widget* w = getChildAt(i); @@ -375,7 +375,7 @@ namespace Gui } int curY = 0; - for (unsigned int i = 0; i < count; ++i) + for (size_t i = 0; i < count; ++i) { if (i == 0) curY += mPadding; diff --git a/extern/oics/CMakeLists.txt b/extern/oics/CMakeLists.txt index 2d34f3f3e6..e9e08993dd 100644 --- a/extern/oics/CMakeLists.txt +++ b/extern/oics/CMakeLists.txt @@ -5,18 +5,27 @@ add_library(oics STATIC ICSInputControlSystem_keyboard.cpp ICSInputControlSystem_mouse.cpp ICSInputControlSystem_joystick.cpp - ICSPrerequisites.h + include/oics/ICSChannel.h + include/oics/ICSChannelListener.h + include/oics/ICSControl.h + include/oics/ICSControlListener.h + include/oics/ICSInputControlSystem.h + include/oics/ICSPrerequisites.h ) +target_include_directories(oics SYSTEM PUBLIC include) +target_include_directories(oics PRIVATE include/oics) + if(USE_SYSTEM_TINYXML) target_link_libraries(oics ${TinyXML_LIBRARIES}) else() add_library(local_tinyxml STATIC - tinyxml.cpp - tinyxmlparser.cpp - tinyxmlerror.cpp - tinystr.cpp + tinyxml/tinyxml.cpp + tinyxml/tinyxmlparser.cpp + tinyxml/tinyxmlerror.cpp + tinyxml/tinystr.cpp ) + target_include_directories(local_tinyxml SYSTEM PUBLIC tinyxml) target_link_libraries(oics local_tinyxml) endif() diff --git a/extern/oics/ICSChannel.h b/extern/oics/include/oics/ICSChannel.h similarity index 100% rename from extern/oics/ICSChannel.h rename to extern/oics/include/oics/ICSChannel.h diff --git a/extern/oics/ICSChannelListener.h b/extern/oics/include/oics/ICSChannelListener.h similarity index 100% rename from extern/oics/ICSChannelListener.h rename to extern/oics/include/oics/ICSChannelListener.h diff --git a/extern/oics/ICSControl.h b/extern/oics/include/oics/ICSControl.h similarity index 100% rename from extern/oics/ICSControl.h rename to extern/oics/include/oics/ICSControl.h diff --git a/extern/oics/ICSControlListener.h b/extern/oics/include/oics/ICSControlListener.h similarity index 100% rename from extern/oics/ICSControlListener.h rename to extern/oics/include/oics/ICSControlListener.h diff --git a/extern/oics/ICSInputControlSystem.h b/extern/oics/include/oics/ICSInputControlSystem.h similarity index 100% rename from extern/oics/ICSInputControlSystem.h rename to extern/oics/include/oics/ICSInputControlSystem.h diff --git a/extern/oics/ICSPrerequisites.h b/extern/oics/include/oics/ICSPrerequisites.h similarity index 100% rename from extern/oics/ICSPrerequisites.h rename to extern/oics/include/oics/ICSPrerequisites.h diff --git a/extern/oics/tinystr.cpp b/extern/oics/tinyxml/tinystr.cpp similarity index 100% rename from extern/oics/tinystr.cpp rename to extern/oics/tinyxml/tinystr.cpp diff --git a/extern/oics/tinystr.h b/extern/oics/tinyxml/tinystr.h similarity index 100% rename from extern/oics/tinystr.h rename to extern/oics/tinyxml/tinystr.h diff --git a/extern/oics/tinyxml.cpp b/extern/oics/tinyxml/tinyxml.cpp similarity index 100% rename from extern/oics/tinyxml.cpp rename to extern/oics/tinyxml/tinyxml.cpp diff --git a/extern/oics/tinyxml.h b/extern/oics/tinyxml/tinyxml.h similarity index 100% rename from extern/oics/tinyxml.h rename to extern/oics/tinyxml/tinyxml.h diff --git a/extern/oics/tinyxmlerror.cpp b/extern/oics/tinyxml/tinyxmlerror.cpp similarity index 100% rename from extern/oics/tinyxmlerror.cpp rename to extern/oics/tinyxml/tinyxmlerror.cpp diff --git a/extern/oics/tinyxmlparser.cpp b/extern/oics/tinyxml/tinyxmlparser.cpp similarity index 100% rename from extern/oics/tinyxmlparser.cpp rename to extern/oics/tinyxml/tinyxmlparser.cpp diff --git a/extern/osg-ffmpeg-videoplayer/CMakeLists.txt b/extern/osg-ffmpeg-videoplayer/CMakeLists.txt index 8ff608bf04..ce20e95af2 100644 --- a/extern/osg-ffmpeg-videoplayer/CMakeLists.txt +++ b/extern/osg-ffmpeg-videoplayer/CMakeLists.txt @@ -5,18 +5,23 @@ set(OSG_FFMPEG_VIDEOPLAYER_LIBRARY "osg-ffmpeg-videoplayer") set(OSG_FFMPEG_VIDEOPLAYER_SOURCE_FILES videoplayer.cpp videostate.cpp - videodefs.hpp audiodecoder.cpp - audiofactory.hpp + include/osg-ffmpeg-videoplayer/audiodecoder.hpp + include/osg-ffmpeg-videoplayer/audiofactory.hpp + include/osg-ffmpeg-videoplayer/libavformatdefines.hpp + include/osg-ffmpeg-videoplayer/libavutildefines.hpp + include/osg-ffmpeg-videoplayer/videodefs.hpp + include/osg-ffmpeg-videoplayer/videoplayer.hpp + include/osg-ffmpeg-videoplayer/videostate.hpp ) -include_directories(${FFmpeg_INCLUDE_DIRS}) add_library(${OSG_FFMPEG_VIDEOPLAYER_LIBRARY} STATIC ${OSG_FFMPEG_VIDEOPLAYER_SOURCE_FILES}) target_link_libraries(${OSG_FFMPEG_VIDEOPLAYER_LIBRARY} ${FFmpeg_LIBRARIES}) target_link_libraries(${OSG_FFMPEG_VIDEOPLAYER_LIBRARY} ${OSG_LIBRARIES}) target_link_libraries(${OSG_FFMPEG_VIDEOPLAYER_LIBRARY} SDL2::SDL2) -link_directories(${CMAKE_CURRENT_BINARY_DIR}) +target_include_directories(${OSG_FFMPEG_VIDEOPLAYER_LIBRARY} SYSTEM PUBLIC include ${FFmpeg_INCLUDE_DIRS}) +target_include_directories(${OSG_FFMPEG_VIDEOPLAYER_LIBRARY} PRIVATE include/osg-ffmpeg-videoplayer) if (MSVC AND PRECOMPILE_HEADERS_WITH_MSVC) target_precompile_headers(${OSG_FFMPEG_VIDEOPLAYER_LIBRARY} PUBLIC diff --git a/extern/osg-ffmpeg-videoplayer/audiodecoder.cpp b/extern/osg-ffmpeg-videoplayer/audiodecoder.cpp index 9a48dff459..db3f8dc2f0 100644 --- a/extern/osg-ffmpeg-videoplayer/audiodecoder.cpp +++ b/extern/osg-ffmpeg-videoplayer/audiodecoder.cpp @@ -1,7 +1,5 @@ #include "audiodecoder.hpp" -#include - #include #include #include @@ -24,6 +22,7 @@ extern "C" #include #endif +#include "libavutildefines.hpp" #include "videostate.hpp" namespace diff --git a/extern/osg-ffmpeg-videoplayer/audiodecoder.hpp b/extern/osg-ffmpeg-videoplayer/include/osg-ffmpeg-videoplayer/audiodecoder.hpp similarity index 98% rename from extern/osg-ffmpeg-videoplayer/audiodecoder.hpp rename to extern/osg-ffmpeg-videoplayer/include/osg-ffmpeg-videoplayer/audiodecoder.hpp index 250ba1db64..a89dca8cd7 100644 --- a/extern/osg-ffmpeg-videoplayer/audiodecoder.hpp +++ b/extern/osg-ffmpeg-videoplayer/include/osg-ffmpeg-videoplayer/audiodecoder.hpp @@ -6,7 +6,7 @@ #include #include -#include +#include #if defined(_MSC_VER) #pragma warning (push) diff --git a/extern/osg-ffmpeg-videoplayer/audiofactory.hpp b/extern/osg-ffmpeg-videoplayer/include/osg-ffmpeg-videoplayer/audiofactory.hpp similarity index 100% rename from extern/osg-ffmpeg-videoplayer/audiofactory.hpp rename to extern/osg-ffmpeg-videoplayer/include/osg-ffmpeg-videoplayer/audiofactory.hpp diff --git a/extern/osg-ffmpeg-videoplayer/libavformatdefines.hpp b/extern/osg-ffmpeg-videoplayer/include/osg-ffmpeg-videoplayer/libavformatdefines.hpp similarity index 100% rename from extern/osg-ffmpeg-videoplayer/libavformatdefines.hpp rename to extern/osg-ffmpeg-videoplayer/include/osg-ffmpeg-videoplayer/libavformatdefines.hpp diff --git a/extern/osg-ffmpeg-videoplayer/libavutildefines.hpp b/extern/osg-ffmpeg-videoplayer/include/osg-ffmpeg-videoplayer/libavutildefines.hpp similarity index 100% rename from extern/osg-ffmpeg-videoplayer/libavutildefines.hpp rename to extern/osg-ffmpeg-videoplayer/include/osg-ffmpeg-videoplayer/libavutildefines.hpp diff --git a/extern/osg-ffmpeg-videoplayer/videodefs.hpp b/extern/osg-ffmpeg-videoplayer/include/osg-ffmpeg-videoplayer/videodefs.hpp similarity index 100% rename from extern/osg-ffmpeg-videoplayer/videodefs.hpp rename to extern/osg-ffmpeg-videoplayer/include/osg-ffmpeg-videoplayer/videodefs.hpp diff --git a/extern/osg-ffmpeg-videoplayer/videoplayer.hpp b/extern/osg-ffmpeg-videoplayer/include/osg-ffmpeg-videoplayer/videoplayer.hpp similarity index 100% rename from extern/osg-ffmpeg-videoplayer/videoplayer.hpp rename to extern/osg-ffmpeg-videoplayer/include/osg-ffmpeg-videoplayer/videoplayer.hpp diff --git a/extern/osg-ffmpeg-videoplayer/videostate.hpp b/extern/osg-ffmpeg-videoplayer/include/osg-ffmpeg-videoplayer/videostate.hpp similarity index 100% rename from extern/osg-ffmpeg-videoplayer/videostate.hpp rename to extern/osg-ffmpeg-videoplayer/include/osg-ffmpeg-videoplayer/videostate.hpp diff --git a/extern/osgQt/CMakeLists.txt b/extern/osgQt/CMakeLists.txt index 1cfb8230a3..32d0142106 100644 --- a/extern/osgQt/CMakeLists.txt +++ b/extern/osgQt/CMakeLists.txt @@ -3,8 +3,8 @@ set(OSGQT_LIBRARY "osgQt") # Sources set(SOURCE_H - osgQOpenGLWidget.hpp - CompositeOsgRenderer.hpp + include/osgQt/osgQOpenGLWidget.hpp + include/osgQt/CompositeOsgRenderer.hpp ) qt_wrap_cpp(SOURCES_H_MOC ${SOURCE_H} ) @@ -16,9 +16,9 @@ set(OSGQT_SOURCE_FILES ) add_library(${OSGQT_LIBRARY} STATIC ${OSGQT_SOURCE_FILES}) +target_include_directories(${OSGQT_LIBRARY} SYSTEM PUBLIC include) +target_include_directories(${OSGQT_LIBRARY} PRIVATE include/osgQt) target_link_libraries(${OSGQT_LIBRARY} Qt::Core Qt::OpenGL Qt::OpenGLWidgets) -link_directories(${CMAKE_CURRENT_BINARY_DIR}) - set(EXTERN_OSGQT_LIBRARY ${OSGQT_LIBRARY} PARENT_SCOPE) diff --git a/extern/osgQt/CompositeOsgRenderer.hpp b/extern/osgQt/include/osgQt/CompositeOsgRenderer.hpp similarity index 100% rename from extern/osgQt/CompositeOsgRenderer.hpp rename to extern/osgQt/include/osgQt/CompositeOsgRenderer.hpp diff --git a/extern/osgQt/osgQOpenGLWidget.hpp b/extern/osgQt/include/osgQt/osgQOpenGLWidget.hpp similarity index 100% rename from extern/osgQt/osgQOpenGLWidget.hpp rename to extern/osgQt/include/osgQt/osgQOpenGLWidget.hpp diff --git a/extern/smhasher/CMakeLists.txt b/extern/smhasher/CMakeLists.txt index ee03e6c38e..b92f09e53d 100644 --- a/extern/smhasher/CMakeLists.txt +++ b/extern/smhasher/CMakeLists.txt @@ -1,2 +1,3 @@ -add_library(smhasher STATIC MurmurHash3.cpp) -target_include_directories(smhasher INTERFACE .) +add_library(smhasher STATIC MurmurHash3.cpp include/smhasher/MurmurHash3.h) +target_include_directories(smhasher SYSTEM PUBLIC include) +target_include_directories(smhasher PRIVATE include/smhasher) diff --git a/extern/smhasher/MurmurHash3.h b/extern/smhasher/include/smhasher/MurmurHash3.h similarity index 100% rename from extern/smhasher/MurmurHash3.h rename to extern/smhasher/include/smhasher/MurmurHash3.h