From 2323cc1596606a67152ccb1b5904fb7763c86c44 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Janiszewski?= Date: Wed, 22 Apr 2020 17:09:29 +0200 Subject: [PATCH] Use named casts instead of old-style casts Change prepared with clang-tidy and google-readability-casting check --- src/openrct2/actions/ClearAction.hpp | 4 +- src/openrct2/actions/GameAction.cpp | 4 +- src/openrct2/actions/GameActionCompat.cpp | 2 +- src/openrct2/actions/LandSmoothAction.hpp | 32 +++-- src/openrct2/actions/ParkMarketingAction.hpp | 2 +- src/openrct2/actions/RideCreateAction.hpp | 10 +- .../actions/RideEntranceExitPlaceAction.hpp | 6 +- src/openrct2/actions/StaffHireNewAction.hpp | 2 +- .../actions/SurfaceSetStyleAction.hpp | 8 +- src/openrct2/audio/Audio.cpp | 2 +- src/openrct2/audio/AudioMixer.cpp | 6 +- src/openrct2/cmdline/BenchGfxCommmands.cpp | 2 +- src/openrct2/cmdline/BenchSpriteSort.cpp | 8 +- src/openrct2/cmdline/CommandLine.cpp | 12 +- src/openrct2/cmdline/ScreenshotCommands.cpp | 2 +- src/openrct2/cmdline/SimulateCommands.cpp | 2 +- src/openrct2/cmdline/SpriteCommands.cpp | 2 +- src/openrct2/config/IniReader.cpp | 6 +- src/openrct2/core/Crypt.OpenSSL.cpp | 2 +- src/openrct2/core/DataSerialiserTraits.h | 2 +- src/openrct2/core/Endianness.h | 5 +- src/openrct2/core/File.cpp | 4 +- src/openrct2/core/FileIndex.hpp | 2 +- src/openrct2/core/FileScanner.cpp | 8 +- src/openrct2/core/FileStream.hpp | 6 +- src/openrct2/core/Imaging.cpp | 8 +- src/openrct2/core/Json.cpp | 2 +- src/openrct2/core/MemoryStream.cpp | 12 +- src/openrct2/core/MemoryStream.h | 4 +- src/openrct2/core/String.cpp | 20 +-- src/openrct2/core/StringBuilder.hpp | 4 +- src/openrct2/core/Zip.cpp | 2 +- src/openrct2/drawing/AVX2Drawing.cpp | 8 +- src/openrct2/drawing/Drawing.Sprite.cpp | 18 +-- src/openrct2/drawing/Drawing.String.cpp | 18 +-- src/openrct2/drawing/Drawing.cpp | 2 +- src/openrct2/drawing/Font.cpp | 14 +- src/openrct2/drawing/ImageImporter.cpp | 45 +++---- src/openrct2/drawing/LightFX.cpp | 70 +++++----- src/openrct2/drawing/Rain.cpp | 12 +- src/openrct2/drawing/SSE41Drawing.cpp | 16 +-- src/openrct2/drawing/ScrollingText.cpp | 4 +- src/openrct2/drawing/TTF.cpp | 4 +- src/openrct2/drawing/TTFSDLPort.cpp | 58 ++++---- src/openrct2/drawing/X8DrawingEngine.cpp | 15 ++- src/openrct2/interface/Chat.cpp | 4 +- src/openrct2/interface/InteractiveConsole.cpp | 9 +- src/openrct2/interface/Screenshot.cpp | 4 +- src/openrct2/interface/Viewport.cpp | 14 +- src/openrct2/interface/Window.cpp | 22 ++-- .../localisation/ConversionTables.cpp | 2 +- src/openrct2/localisation/Convert.cpp | 2 +- src/openrct2/localisation/Language.cpp | 10 +- src/openrct2/localisation/Language.h | 2 +- src/openrct2/localisation/LanguagePack.cpp | 24 ++-- .../localisation/Localisation.Date.cpp | 6 +- src/openrct2/localisation/Localisation.cpp | 27 ++-- src/openrct2/localisation/UTF8.cpp | 2 +- src/openrct2/management/Award.cpp | 4 +- src/openrct2/network/Network.cpp | 124 +++++++++--------- src/openrct2/network/NetworkAction.cpp | 4 +- src/openrct2/network/NetworkConnection.cpp | 8 +- src/openrct2/network/NetworkGroup.cpp | 2 +- src/openrct2/network/NetworkKey.cpp | 8 +- src/openrct2/network/NetworkPacket.cpp | 4 +- src/openrct2/network/NetworkPacket.h | 2 +- src/openrct2/network/NetworkPlayer.cpp | 4 +- .../network/NetworkServerAdvertiser.cpp | 4 +- src/openrct2/network/NetworkUser.cpp | 2 +- src/openrct2/network/ServerList.cpp | 11 +- src/openrct2/network/Socket.cpp | 46 ++++--- src/openrct2/network/Twitch.cpp | 6 +- src/openrct2/object/ImageTable.cpp | 8 +- src/openrct2/object/ImageTable.h | 2 +- src/openrct2/object/ObjectFactory.cpp | 2 +- src/openrct2/object/ObjectJsonHelpers.cpp | 20 +-- src/openrct2/object/ObjectList.cpp | 2 +- src/openrct2/object/ObjectManager.cpp | 20 +-- src/openrct2/object/ObjectRepository.cpp | 12 +- src/openrct2/object/ObjectRepository.h | 2 +- src/openrct2/object/RideObject.cpp | 6 +- src/openrct2/object/StringTable.cpp | 6 +- src/openrct2/object/WaterObject.cpp | 4 +- src/openrct2/paint/Paint.cpp | 10 +- src/openrct2/paint/sprite/Paint.Misc.cpp | 4 +- .../paint/tile_element/Paint.Entrance.cpp | 4 +- .../paint/tile_element/Paint.LargeScenery.cpp | 4 +- .../paint/tile_element/Paint.Path.cpp | 9 +- .../paint/tile_element/Paint.Surface.cpp | 18 +-- .../paint/tile_element/Paint.TileElement.cpp | 2 +- .../paint/tile_element/Paint.Wall.cpp | 28 ++-- src/openrct2/peep/Guest.cpp | 30 ++--- src/openrct2/peep/GuestPathfinding.cpp | 22 ++-- src/openrct2/peep/Peep.cpp | 18 +-- src/openrct2/peep/Staff.cpp | 6 +- src/openrct2/platform/Linux.cpp | 6 +- src/openrct2/platform/Platform.macOS.mm | 9 +- src/openrct2/platform/Posix.cpp | 4 +- src/openrct2/platform/Shared.cpp | 2 +- src/openrct2/platform/macos.mm | 20 +-- src/openrct2/rct1/S4Importer.cpp | 2 +- src/openrct2/rct1/T4Importer.cpp | 4 +- src/openrct2/rct12/RCT12.h | 2 +- src/openrct2/readme.md | 1 - src/openrct2/ride/Vehicle.cpp | 9 +- src/openrct2/scenario/ScenarioSources.cpp | 2 +- src/openrct2/windows/_legacy.cpp | 6 +- src/openrct2/world/Banner.h | 2 +- src/openrct2/world/Duck.cpp | 4 +- src/openrct2/world/Footpath.h | 4 +- src/openrct2/world/Map.cpp | 4 +- src/openrct2/world/Sprite.cpp | 4 +- src/openrct2/world/TileElement.h | 2 +- src/openrct2/world/TileInspector.cpp | 4 +- 114 files changed, 604 insertions(+), 560 deletions(-) diff --git a/src/openrct2/actions/ClearAction.hpp b/src/openrct2/actions/ClearAction.hpp index d37b14b6f3..0c8d0b738d 100644 --- a/src/openrct2/actions/ClearAction.hpp +++ b/src/openrct2/actions/ClearAction.hpp @@ -95,8 +95,8 @@ private: auto x0 = std::max(_range.GetLeft(), 32); auto y0 = std::max(_range.GetTop(), 32); - auto x1 = std::min(_range.GetRight(), (int32_t)gMapSizeMaxXY); - auto y1 = std::min(_range.GetBottom(), (int32_t)gMapSizeMaxXY); + auto x1 = std::min(_range.GetRight(), static_cast(gMapSizeMaxXY)); + auto y1 = std::min(_range.GetBottom(), static_cast(gMapSizeMaxXY)); for (int32_t y = y0; y <= y1; y += COORDS_XY_STEP) { diff --git a/src/openrct2/actions/GameAction.cpp b/src/openrct2/actions/GameAction.cpp index 7c85b5979c..7462e05140 100644 --- a/src/openrct2/actions/GameAction.cpp +++ b/src/openrct2/actions/GameAction.cpp @@ -327,7 +327,7 @@ namespace GameActions if (result->Error != GA_ERROR::OK) { - snprintf(temp, sizeof(temp), ") Failed, %u", (uint32_t)result->Error); + snprintf(temp, sizeof(temp), ") Failed, %u", static_cast(result->Error)); } else { @@ -336,7 +336,7 @@ namespace GameActions output.Write(temp, strlen(temp) + 1); - const char* text = (const char*)output.GetData(); + const char* text = static_cast(output.GetData()); log_verbose("%s", text); network_append_server_log(text); diff --git a/src/openrct2/actions/GameActionCompat.cpp b/src/openrct2/actions/GameActionCompat.cpp index 129ef0d68f..d389c7cae5 100644 --- a/src/openrct2/actions/GameActionCompat.cpp +++ b/src/openrct2/actions/GameActionCompat.cpp @@ -45,7 +45,7 @@ money32 park_entrance_place_ghost(const CoordsXYZD& entranceLoc) #pragma region SetParkEntranceFeeAction void park_set_entrance_fee(money32 fee) { - auto gameAction = SetParkEntranceFeeAction((money16)fee); + auto gameAction = SetParkEntranceFeeAction(static_cast(fee)); GameActions::Execute(&gameAction); } #pragma endregion diff --git a/src/openrct2/actions/LandSmoothAction.hpp b/src/openrct2/actions/LandSmoothAction.hpp index 2c9f1a95d8..502bc7b3aa 100644 --- a/src/openrct2/actions/LandSmoothAction.hpp +++ b/src/openrct2/actions/LandSmoothAction.hpp @@ -371,7 +371,7 @@ private: if (surfaceElement != nullptr) { int32_t z = std::clamp( - (uint8_t)tile_element_get_corner_height(surfaceElement, 2), minHeight, maxHeight); + static_cast(tile_element_get_corner_height(surfaceElement, 2)), minHeight, maxHeight); res->Cost += SmoothLandRowByCorner( isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, -32, -32, 0, 2); } @@ -381,7 +381,7 @@ private: if (surfaceElement != nullptr) { int32_t z = std::clamp( - (uint8_t)tile_element_get_corner_height(surfaceElement, 3), minHeight, maxHeight); + static_cast(tile_element_get_corner_height(surfaceElement, 3)), minHeight, maxHeight); res->Cost += SmoothLandRowByCorner( isExecuting, { validRange.GetLeft(), validRange.GetBottom() }, z, -32, 32, 1, 3); } @@ -391,7 +391,7 @@ private: if (surfaceElement != nullptr) { int32_t z = std::clamp( - (uint8_t)tile_element_get_corner_height(surfaceElement, 0), minHeight, maxHeight); + static_cast(tile_element_get_corner_height(surfaceElement, 0)), minHeight, maxHeight); res->Cost += SmoothLandRowByCorner( isExecuting, { validRange.GetRight(), validRange.GetBottom() }, z, 32, 32, 2, 0); } @@ -401,7 +401,7 @@ private: if (surfaceElement != nullptr) { int32_t z = std::clamp( - (uint8_t)tile_element_get_corner_height(surfaceElement, 1), minHeight, maxHeight); + static_cast(tile_element_get_corner_height(surfaceElement, 1)), minHeight, maxHeight); res->Cost += SmoothLandRowByCorner( isExecuting, { validRange.GetRight(), validRange.GetTop() }, z, 32, -32, 3, 1); } @@ -414,16 +414,20 @@ private: auto surfaceElement = map_get_surface_element_at(CoordsXY{ validRange.GetLeft(), y }); if (surfaceElement != nullptr) { - z1 = std::clamp((uint8_t)tile_element_get_corner_height(surfaceElement, 3), minHeight, maxHeight); - z2 = std::clamp((uint8_t)tile_element_get_corner_height(surfaceElement, 2), minHeight, maxHeight); + z1 = std::clamp( + static_cast(tile_element_get_corner_height(surfaceElement, 3)), minHeight, maxHeight); + z2 = std::clamp( + static_cast(tile_element_get_corner_height(surfaceElement, 2)), minHeight, maxHeight); res->Cost += SmoothLandRowByEdge(isExecuting, { validRange.GetLeft(), y }, z1, z2, -32, 0, 0, 1, 3, 2); } surfaceElement = map_get_surface_element_at(CoordsXY{ validRange.GetRight(), y }); if (surfaceElement != nullptr) { - z1 = std::clamp((uint8_t)tile_element_get_corner_height(surfaceElement, 1), minHeight, maxHeight); - z2 = std::clamp((uint8_t)tile_element_get_corner_height(surfaceElement, 0), minHeight, maxHeight); + z1 = std::clamp( + static_cast(tile_element_get_corner_height(surfaceElement, 1)), minHeight, maxHeight); + z2 = std::clamp( + static_cast(tile_element_get_corner_height(surfaceElement, 0)), minHeight, maxHeight); res->Cost += SmoothLandRowByEdge(isExecuting, { validRange.GetRight(), y }, z1, z2, 32, 0, 2, 3, 1, 0); } } @@ -433,16 +437,20 @@ private: auto surfaceElement = map_get_surface_element_at(CoordsXY{ x, validRange.GetTop() }); if (surfaceElement != nullptr) { - z1 = std::clamp((uint8_t)tile_element_get_corner_height(surfaceElement, 1), minHeight, maxHeight); - z2 = std::clamp((uint8_t)tile_element_get_corner_height(surfaceElement, 2), minHeight, maxHeight); + z1 = std::clamp( + static_cast(tile_element_get_corner_height(surfaceElement, 1)), minHeight, maxHeight); + z2 = std::clamp( + static_cast(tile_element_get_corner_height(surfaceElement, 2)), minHeight, maxHeight); res->Cost += SmoothLandRowByEdge(isExecuting, { x, validRange.GetTop() }, z1, z2, 0, -32, 0, 3, 1, 2); } surfaceElement = map_get_surface_element_at(CoordsXY{ x, validRange.GetBottom() }); if (surfaceElement != nullptr) { - z1 = std::clamp((uint8_t)tile_element_get_corner_height(surfaceElement, 0), minHeight, maxHeight); - z2 = std::clamp((uint8_t)tile_element_get_corner_height(surfaceElement, 3), minHeight, maxHeight); + z1 = std::clamp( + static_cast(tile_element_get_corner_height(surfaceElement, 0)), minHeight, maxHeight); + z2 = std::clamp( + static_cast(tile_element_get_corner_height(surfaceElement, 3)), minHeight, maxHeight); res->Cost += SmoothLandRowByEdge(isExecuting, { x, validRange.GetBottom() }, z1, z2, 0, 32, 1, 2, 0, 3); } } diff --git a/src/openrct2/actions/ParkMarketingAction.hpp b/src/openrct2/actions/ParkMarketingAction.hpp index 74321fdd62..60a4f2dd84 100644 --- a/src/openrct2/actions/ParkMarketingAction.hpp +++ b/src/openrct2/actions/ParkMarketingAction.hpp @@ -53,7 +53,7 @@ public: GameActionResult::Ptr Query() const override { - if ((size_t)_type >= std::size(AdvertisingCampaignPricePerWeek) || _numWeeks >= 256) + if (static_cast(_type) >= std::size(AdvertisingCampaignPricePerWeek) || _numWeeks >= 256) { return MakeResult(GA_ERROR::INVALID_PARAMETERS, STR_CANT_START_MARKETING_CAMPAIGN); } diff --git a/src/openrct2/actions/RideCreateAction.hpp b/src/openrct2/actions/RideCreateAction.hpp index 3878b9610a..cb85997acf 100644 --- a/src/openrct2/actions/RideCreateAction.hpp +++ b/src/openrct2/actions/RideCreateAction.hpp @@ -178,7 +178,7 @@ public: ride->lift_hill_speed = RideTypeDescriptors[ride->type].LiftData.minimum_speed; ride->measurement = {}; - ride->excitement = (ride_rating)-1; + ride->excitement = RIDE_RATING_UNDEFINED; ride->cur_num_customers = 0; ride->num_customers_timeout = 0; ride->chairlift_bullwheel_rotation = 0; @@ -218,7 +218,7 @@ public: money32 price = ride_get_common_price(ride); if (price != MONEY32_UNDEFINED) { - ride->price = (money16)price; + ride->price = static_cast(price); } } } @@ -230,7 +230,7 @@ public: money32 price = shop_item_get_common_price(ride, rideEntry->shop_item); if (price != MONEY32_UNDEFINED) { - ride->price = (money16)price; + ride->price = static_cast(price); } } } @@ -242,7 +242,7 @@ public: money32 price = shop_item_get_common_price(ride, rideEntry->shop_item_secondary); if (price != MONEY32_UNDEFINED) { - ride->price_secondary = (money16)price; + ride->price_secondary = static_cast(price); } } } @@ -253,7 +253,7 @@ public: money32 price = shop_item_get_common_price(ride, SHOP_ITEM_PHOTO); if (price != MONEY32_UNDEFINED) { - ride->price_secondary = (money16)price; + ride->price_secondary = static_cast(price); } } } diff --git a/src/openrct2/actions/RideEntranceExitPlaceAction.hpp b/src/openrct2/actions/RideEntranceExitPlaceAction.hpp index 37b5e5271a..5118f61a79 100644 --- a/src/openrct2/actions/RideEntranceExitPlaceAction.hpp +++ b/src/openrct2/actions/RideEntranceExitPlaceAction.hpp @@ -199,13 +199,11 @@ public: if (_isExit) { - ride_set_exit_location( - ride, _stationNum, TileCoordsXYZD(CoordsXYZD{ _loc, z, (uint8_t)tileElement->GetDirection() })); + ride_set_exit_location(ride, _stationNum, TileCoordsXYZD(CoordsXYZD{ _loc, z, tileElement->GetDirection() })); } else { - ride_set_entrance_location( - ride, _stationNum, TileCoordsXYZD(CoordsXYZD{ _loc, z, (uint8_t)tileElement->GetDirection() })); + ride_set_entrance_location(ride, _stationNum, TileCoordsXYZD(CoordsXYZD{ _loc, z, tileElement->GetDirection() })); ride->stations[_stationNum].LastPeepInQueue = SPRITE_INDEX_NULL; ride->stations[_stationNum].QueueLength = 0; diff --git a/src/openrct2/actions/StaffHireNewAction.hpp b/src/openrct2/actions/StaffHireNewAction.hpp index 497af4f4a8..c91d7a763c 100644 --- a/src/openrct2/actions/StaffHireNewAction.hpp +++ b/src/openrct2/actions/StaffHireNewAction.hpp @@ -315,7 +315,7 @@ private: // No walking guests; pick random park entrance if (!gParkEntrances.empty()) { - auto rand = scenario_rand_max((uint32_t)gParkEntrances.size()); + auto rand = scenario_rand_max(static_cast(gParkEntrances.size())); const auto& entrance = gParkEntrances[rand]; auto dir = entrance.direction; x = entrance.x; diff --git a/src/openrct2/actions/SurfaceSetStyleAction.hpp b/src/openrct2/actions/SurfaceSetStyleAction.hpp index c9dd186979..67dfc0a48a 100644 --- a/src/openrct2/actions/SurfaceSetStyleAction.hpp +++ b/src/openrct2/actions/SurfaceSetStyleAction.hpp @@ -55,8 +55,8 @@ public: auto normRange = _range.Normalise(); auto x0 = std::max(normRange.GetLeft(), 32); auto y0 = std::max(normRange.GetTop(), 32); - auto x1 = std::min(normRange.GetRight(), (int32_t)gMapSizeMaxXY); - auto y1 = std::min(normRange.GetBottom(), (int32_t)gMapSizeMaxXY); + auto x1 = std::min(normRange.GetRight(), static_cast(gMapSizeMaxXY)); + auto y1 = std::min(normRange.GetBottom(), static_cast(gMapSizeMaxXY)); MapRange validRange{ x0, y0, x1, y1 }; @@ -171,8 +171,8 @@ public: auto normRange = _range.Normalise(); auto x0 = std::max(normRange.GetLeft(), 32); auto y0 = std::max(normRange.GetTop(), 32); - auto x1 = std::min(normRange.GetRight(), (int32_t)gMapSizeMaxXY); - auto y1 = std::min(normRange.GetBottom(), (int32_t)gMapSizeMaxXY); + auto x1 = std::min(normRange.GetRight(), static_cast(gMapSizeMaxXY)); + auto y1 = std::min(normRange.GetBottom(), static_cast(gMapSizeMaxXY)); MapRange validRange{ x0, y0, x1, y1 }; diff --git a/src/openrct2/audio/Audio.cpp b/src/openrct2/audio/Audio.cpp index 5900822465..c1242f23f6 100644 --- a/src/openrct2/audio/Audio.cpp +++ b/src/openrct2/audio/Audio.cpp @@ -169,7 +169,7 @@ void audio_populate_devices() devices.insert(devices.begin(), defaultDevice); #endif - gAudioDeviceCount = (int32_t)devices.size(); + gAudioDeviceCount = static_cast(devices.size()); gAudioDevices = Memory::AllocateArray(gAudioDeviceCount); for (int32_t i = 0; i < gAudioDeviceCount; i++) { diff --git a/src/openrct2/audio/AudioMixer.cpp b/src/openrct2/audio/AudioMixer.cpp index f19b11c661..3f72b1e4df 100644 --- a/src/openrct2/audio/AudioMixer.cpp +++ b/src/openrct2/audio/AudioMixer.cpp @@ -173,15 +173,15 @@ void Mixer_SetVolume(float volume) int32_t DStoMixerVolume(int32_t volume) { - return (int32_t)(MIXER_VOLUME_MAX * (std::pow(10.0f, (float)volume / 2000))); + return static_cast(MIXER_VOLUME_MAX * (std::pow(10.0f, static_cast(volume) / 2000))); } float DStoMixerPan(int32_t pan) { - return (((float)pan + -DSBPAN_LEFT) / DSBPAN_RIGHT) / 2; + return ((static_cast(pan) + -DSBPAN_LEFT) / DSBPAN_RIGHT) / 2; } double DStoMixerRate(int32_t frequency) { - return (double)frequency / 22050; + return static_cast(frequency) / 22050; } diff --git a/src/openrct2/cmdline/BenchGfxCommmands.cpp b/src/openrct2/cmdline/BenchGfxCommmands.cpp index 343a715c21..76f91f5762 100644 --- a/src/openrct2/cmdline/BenchGfxCommmands.cpp +++ b/src/openrct2/cmdline/BenchGfxCommmands.cpp @@ -19,7 +19,7 @@ const CommandLineCommand CommandLine::BenchGfxCommands[]{ static exitcode_t HandleBenchGfx(CommandLineArgEnumerator* argEnumerator) { - const char** argv = (const char**)argEnumerator->GetArguments() + argEnumerator->GetIndex(); + const char** argv = const_cast(argEnumerator->GetArguments()) + argEnumerator->GetIndex(); int32_t argc = argEnumerator->GetCount() - argEnumerator->GetIndex(); int32_t result = cmdline_for_gfxbench(argv, argc); if (result < 0) diff --git a/src/openrct2/cmdline/BenchSpriteSort.cpp b/src/openrct2/cmdline/BenchSpriteSort.cpp index f1daccfe66..45cdb8b6f2 100644 --- a/src/openrct2/cmdline/BenchSpriteSort.cpp +++ b/src/openrct2/cmdline/BenchSpriteSort.cpp @@ -121,7 +121,7 @@ static std::vector extract_paint_session(const std::string parkFi dpi.width = resolutionWidth; dpi.height = resolutionHeight; dpi.pitch = 0; - dpi.bits = (uint8_t*)malloc(dpi.width * dpi.height); + dpi.bits = static_cast(malloc(dpi.width * dpi.height)); log_info("Obtaining sprite data..."); viewport_render(&dpi, &viewport, 0, 0, viewport.width, viewport.height, &sessions); @@ -190,11 +190,11 @@ static int cmdline_for_bench_sprite_sort(int argc, const char** argv) } else { - argv_for_benchmark.push_back((char*)argv[i]); + argv_for_benchmark.push_back(const_cast(argv[i])); } } // Update argc with all the changes made - argc = (int)argv_for_benchmark.size(); + argc = static_cast(argv_for_benchmark.size()); ::benchmark::Initialize(&argc, &argv_for_benchmark[0]); if (::benchmark::ReportUnrecognizedArguments(argc, &argv_for_benchmark[0])) return -1; @@ -204,7 +204,7 @@ static int cmdline_for_bench_sprite_sort(int argc, const char** argv) static exitcode_t HandleBenchSpriteSort(CommandLineArgEnumerator* argEnumerator) { - const char** argv = (const char**)argEnumerator->GetArguments() + argEnumerator->GetIndex(); + const char** argv = const_cast(argEnumerator->GetArguments()) + argEnumerator->GetIndex(); int32_t argc = argEnumerator->GetCount() - argEnumerator->GetIndex(); int32_t result = cmdline_for_bench_sprite_sort(argc, argv); if (result < 0) diff --git a/src/openrct2/cmdline/CommandLine.cpp b/src/openrct2/cmdline/CommandLine.cpp index 54a71743e2..9575fce863 100644 --- a/src/openrct2/cmdline/CommandLine.cpp +++ b/src/openrct2/cmdline/CommandLine.cpp @@ -62,7 +62,7 @@ bool CommandLineArgEnumerator::TryPopInteger(int32_t* result) char const* arg; if (TryPopString(&arg)) { - *result = (int32_t)atol(arg); + *result = static_cast(atol(arg)); return true; } @@ -74,7 +74,7 @@ bool CommandLineArgEnumerator::TryPopReal(float* result) char const* arg; if (TryPopString(&arg)) { - *result = (float)atof(arg); + *result = static_cast(atof(arg)); return true; } @@ -489,16 +489,16 @@ namespace CommandLine switch (option->Type) { case CMDLINE_TYPE_SWITCH: - *((bool*)option->OutAddress) = true; + *(static_cast(option->OutAddress)) = true; return true; case CMDLINE_TYPE_INTEGER: - *((int32_t*)option->OutAddress) = (int32_t)atol(valueString); + *(static_cast(option->OutAddress)) = static_cast(atol(valueString)); return true; case CMDLINE_TYPE_REAL: - *((float*)option->OutAddress) = (float)atof(valueString); + *(static_cast(option->OutAddress)) = static_cast(atof(valueString)); return true; case CMDLINE_TYPE_STRING: - *((utf8**)option->OutAddress) = String::Duplicate(valueString); + *(static_cast(option->OutAddress)) = String::Duplicate(valueString); return true; default: Console::Error::WriteLine("Unknown CMDLINE_TYPE for: %s", option->LongName); diff --git a/src/openrct2/cmdline/ScreenshotCommands.cpp b/src/openrct2/cmdline/ScreenshotCommands.cpp index dbe126e027..77e9925fb3 100644 --- a/src/openrct2/cmdline/ScreenshotCommands.cpp +++ b/src/openrct2/cmdline/ScreenshotCommands.cpp @@ -41,7 +41,7 @@ const CommandLineCommand CommandLine::ScreenshotCommands[] static exitcode_t HandleScreenshot(CommandLineArgEnumerator* argEnumerator) { - const char** argv = (const char**)argEnumerator->GetArguments() + argEnumerator->GetIndex(); + const char** argv = const_cast(argEnumerator->GetArguments()) + argEnumerator->GetIndex(); int32_t argc = argEnumerator->GetCount() - argEnumerator->GetIndex(); int32_t result = cmdline_for_screenshot(argv, argc, &_options); if (result < 0) diff --git a/src/openrct2/cmdline/SimulateCommands.cpp b/src/openrct2/cmdline/SimulateCommands.cpp index 3848f9ccae..efd89c4b5a 100644 --- a/src/openrct2/cmdline/SimulateCommands.cpp +++ b/src/openrct2/cmdline/SimulateCommands.cpp @@ -30,7 +30,7 @@ const CommandLineCommand CommandLine::SimulateCommands[]{ // Main commands static exitcode_t HandleSimulate(CommandLineArgEnumerator* argEnumerator) { - const char** argv = (const char**)argEnumerator->GetArguments() + argEnumerator->GetIndex(); + const char** argv = const_cast(argEnumerator->GetArguments()) + argEnumerator->GetIndex(); int32_t argc = argEnumerator->GetCount() - argEnumerator->GetIndex(); if (argc < 2) diff --git a/src/openrct2/cmdline/SpriteCommands.cpp b/src/openrct2/cmdline/SpriteCommands.cpp index 900894ffdc..35c5c1c46c 100644 --- a/src/openrct2/cmdline/SpriteCommands.cpp +++ b/src/openrct2/cmdline/SpriteCommands.cpp @@ -50,7 +50,7 @@ static exitcode_t HandleSprite(CommandLineArgEnumerator* argEnumerator) gSpriteMode = 2; Memory::Free(_mode); - const char** argv = (const char**)argEnumerator->GetArguments() + argEnumerator->GetIndex() - 1; + const char** argv = const_cast(argEnumerator->GetArguments()) + argEnumerator->GetIndex() - 1; int32_t argc = argEnumerator->GetCount() - argEnumerator->GetIndex() + 1; int32_t result = cmdline_for_sprite(argv, argc); if (result < 0) diff --git a/src/openrct2/config/IniReader.cpp b/src/openrct2/config/IniReader.cpp index 3bc24b89c8..4c871de0b9 100644 --- a/src/openrct2/config/IniReader.cpp +++ b/src/openrct2/config/IniReader.cpp @@ -201,7 +201,7 @@ private: { return; } - utf8* file = (utf8*)_buffer.data(); + utf8* file = reinterpret_cast(_buffer.data()); utf8* content = String::SkipBOM(file); if (file != content) { @@ -216,7 +216,7 @@ private: bool onNewLineCh = false; for (size_t i = 0; i < _buffer.size(); i++) { - char b = (char)_buffer[i]; + char b = static_cast(_buffer[i]); if (b == 0 || b == '\n' || b == '\r') { if (!onNewLineCh) @@ -363,7 +363,7 @@ private: std::string GetLine(size_t index) { - utf8* szBuffer = (utf8*)_buffer.data(); + utf8* szBuffer = reinterpret_cast(_buffer.data()); auto span = _lines[index]; auto line = std::string(szBuffer + span.Start, span.Length); return line; diff --git a/src/openrct2/core/Crypt.OpenSSL.cpp b/src/openrct2/core/Crypt.OpenSSL.cpp index 7fde32b916..b700a5ad8e 100644 --- a/src/openrct2/core/Crypt.OpenSSL.cpp +++ b/src/openrct2/core/Crypt.OpenSSL.cpp @@ -183,7 +183,7 @@ private: { // Read PEM data via BIO buffer // HACK first parameter is not const on MINGW for some reason - auto bio = BIO_new_mem_buf((void*)pem.data(), (int)pem.size()); + auto bio = BIO_new_mem_buf((void*)pem.data(), static_cast(pem.size())); if (bio == nullptr) { throw std::runtime_error("BIO_new_mem_buf failed"); diff --git a/src/openrct2/core/DataSerialiserTraits.h b/src/openrct2/core/DataSerialiserTraits.h index cf032848af..df11d757b4 100644 --- a/src/openrct2/core/DataSerialiserTraits.h +++ b/src/openrct2/core/DataSerialiserTraits.h @@ -113,7 +113,7 @@ template<> struct DataSerializerTraits { static void encode(IStream* stream, const std::string& str) { - uint16_t len = (uint16_t)str.size(); + uint16_t len = static_cast(str.size()); uint16_t swapped = ByteSwapBE(len); stream->Write(&swapped); stream->WriteArray(str.c_str(), len); diff --git a/src/openrct2/core/Endianness.h b/src/openrct2/core/Endianness.h index 40335745e5..a1a12c2b72 100644 --- a/src/openrct2/core/Endianness.h +++ b/src/openrct2/core/Endianness.h @@ -29,7 +29,7 @@ template<> struct ByteSwapT<2> using UIntType = uint16_t; static uint16_t SwapBE(uint16_t value) { - return (uint16_t)((value << 8) | (value >> 8)); + return static_cast((value << 8) | (value >> 8)); } }; @@ -38,7 +38,8 @@ template<> struct ByteSwapT<4> using UIntType = uint32_t; static uint32_t SwapBE(uint32_t value) { - return (uint32_t)(((value << 24) | ((value << 8) & 0x00FF0000) | ((value >> 8) & 0x0000FF00) | (value >> 24))); + return static_cast( + ((value << 24) | ((value << 8) & 0x00FF0000) | ((value >> 8) & 0x0000FF00) | (value >> 24))); } }; diff --git a/src/openrct2/core/File.cpp b/src/openrct2/core/File.cpp index 5df4e4514d..4f8a8648ba 100644 --- a/src/openrct2/core/File.cpp +++ b/src/openrct2/core/File.cpp @@ -71,7 +71,7 @@ namespace File { result.resize(fsize); fs.seekg(0); - fs.read((char*)result.data(), result.size()); + fs.read(reinterpret_cast(result.data()), result.size()); fs.exceptions(fs.failbit); } return result; @@ -96,7 +96,7 @@ namespace File { std::vector lines; auto data = ReadAllBytes(path); - auto lineStart = (const char*)data.data(); + auto lineStart = reinterpret_cast(data.data()); auto ch = lineStart; char lastC = 0; for (size_t i = 0; i < data.size(); i++) diff --git a/src/openrct2/core/FileIndex.hpp b/src/openrct2/core/FileIndex.hpp index da3e27d4df..07ca60305a 100644 --- a/src/openrct2/core/FileIndex.hpp +++ b/src/openrct2/core/FileIndex.hpp @@ -246,7 +246,7 @@ private: WriteIndexFile(language, scanResult.Stats, allItems); auto endTime = std::chrono::high_resolution_clock::now(); - auto duration = (std::chrono::duration)(endTime - startTime); + auto duration = std::chrono::duration(endTime - startTime); Console::WriteLine("Finished building %s in %.2f seconds.", _name.c_str(), duration.count()); return allItems; diff --git a/src/openrct2/core/FileScanner.cpp b/src/openrct2/core/FileScanner.cpp index 169d62df4f..59ee7e7ae9 100644 --- a/src/openrct2/core/FileScanner.cpp +++ b/src/openrct2/core/FileScanner.cpp @@ -130,7 +130,7 @@ public: { DirectoryState* state = &_directoryStack.top(); state->Index++; - if (state->Index >= (int32_t)state->Listing.size()) + if (state->Index >= static_cast(state->Listing.size())) { _directoryStack.pop(); } @@ -199,7 +199,7 @@ private: c = *ch; if (c == '\0' || c == ';') { - size_t length = (size_t)(ch - start); + size_t length = static_cast(ch - start); if (length > 0) { std::string newPattern = std::string(start, length); @@ -365,8 +365,8 @@ void Path::QueryDirectory(QueryDirectoryResult* result, const std::string& patte result->TotalFiles++; result->TotalFileSize += fileInfo->Size; - result->FileDateModifiedChecksum ^= (uint32_t)(fileInfo->LastModified >> 32) - ^ (uint32_t)(fileInfo->LastModified & 0xFFFFFFFF); + result->FileDateModifiedChecksum ^= static_cast(fileInfo->LastModified >> 32) + ^ static_cast(fileInfo->LastModified & 0xFFFFFFFF); result->FileDateModifiedChecksum = ror32(result->FileDateModifiedChecksum, 5); result->PathChecksum += GetPathChecksum(path); } diff --git a/src/openrct2/core/FileStream.hpp b/src/openrct2/core/FileStream.hpp index 2b395e69ba..31c3359712 100644 --- a/src/openrct2/core/FileStream.hpp +++ b/src/openrct2/core/FileStream.hpp @@ -166,7 +166,7 @@ public: uint64_t remainingBytes = GetLength() - GetPosition(); if (length <= remainingBytes) { - if (fread(buffer, (size_t)length, 1, _file) == 1) + if (fread(buffer, static_cast(length), 1, _file) == 1) { return; } @@ -176,7 +176,7 @@ public: void Write(const void* buffer, uint64_t length) override { - if (fwrite(buffer, (size_t)length, 1, _file) != 1) + if (fwrite(buffer, static_cast(length), 1, _file) != 1) { throw IOException("Unable to write to file."); } @@ -187,7 +187,7 @@ public: uint64_t TryRead(void* buffer, uint64_t length) override { - size_t readBytes = fread(buffer, 1, (size_t)length, _file); + size_t readBytes = fread(buffer, 1, static_cast(length), _file); return readBytes; } diff --git a/src/openrct2/core/Imaging.cpp b/src/openrct2/core/Imaging.cpp index cefc948edb..b8e2e4c4fd 100644 --- a/src/openrct2/core/Imaging.cpp +++ b/src/openrct2/core/Imaging.cpp @@ -32,13 +32,13 @@ namespace Imaging static void PngReadData(png_structp png_ptr, png_bytep data, png_size_t length) { auto istream = static_cast(png_get_io_ptr(png_ptr)); - istream->read((char*)data, length); + istream->read(reinterpret_cast(data), length); } static void PngWriteData(png_structp png_ptr, png_bytep data, png_size_t length) { auto ostream = static_cast(png_get_io_ptr(png_ptr)); - ostream->write((const char*)data, length); + ostream->write(reinterpret_cast(data), length); } static void PngFlush(png_structp png_ptr) @@ -187,7 +187,7 @@ namespace Imaging } // Set the palette - png_palette = (png_colorp)png_malloc(png_ptr, PNG_MAX_PALETTE_LENGTH * sizeof(png_color)); + png_palette = static_cast(png_malloc(png_ptr, PNG_MAX_PALETTE_LENGTH * sizeof(png_color))); if (png_palette == nullptr) { throw std::runtime_error("png_malloc failed."); @@ -227,7 +227,7 @@ namespace Imaging auto pixels = image.Pixels.data(); for (uint32_t y = 0; y < image.Height; y++) { - png_write_row(png_ptr, (png_byte*)pixels); + png_write_row(png_ptr, const_cast(pixels)); pixels += image.Stride; } diff --git a/src/openrct2/core/Json.cpp b/src/openrct2/core/Json.cpp index 07c868630b..b559705024 100644 --- a/src/openrct2/core/Json.cpp +++ b/src/openrct2/core/Json.cpp @@ -20,7 +20,7 @@ namespace Json json_t* json = nullptr; auto fs = FileStream(path, FILE_MODE_OPEN); - size_t fileLength = (size_t)fs.GetLength(); + size_t fileLength = static_cast(fs.GetLength()); if (fileLength > maxSize) { throw IOException("Json file too large."); diff --git a/src/openrct2/core/MemoryStream.cpp b/src/openrct2/core/MemoryStream.cpp index dceec747e5..06808cf2d7 100644 --- a/src/openrct2/core/MemoryStream.cpp +++ b/src/openrct2/core/MemoryStream.cpp @@ -45,7 +45,7 @@ MemoryStream::MemoryStream(void* data, size_t dataSize, uint8_t access) } MemoryStream::MemoryStream(const void* data, size_t dataSize) - : MemoryStream((void*)data, dataSize, MEMORY_ACCESS::READ) + : MemoryStream(const_cast(data), dataSize, MEMORY_ACCESS::READ) { } @@ -115,7 +115,7 @@ uint64_t MemoryStream::GetLength() const uint64_t MemoryStream::GetPosition() const { - return (uint64_t)((uintptr_t)_position - (uintptr_t)_data); + return static_cast((uintptr_t)_position - (uintptr_t)_data); } void MemoryStream::SetPosition(uint64_t position) @@ -144,7 +144,7 @@ void MemoryStream::Seek(int64_t offset, int32_t origin) { throw IOException("New position out of bounds."); } - _position = (void*)((uintptr_t)_data + (uintptr_t)newPosition); + _position = (void*)((uintptr_t)_data + static_cast(newPosition)); } void MemoryStream::Read(void* buffer, uint64_t length) @@ -200,7 +200,7 @@ void MemoryStream::Write(const void* buffer, uint64_t length) { if (_access & MEMORY_ACCESS::OWNER) { - EnsureCapacity((size_t)nextPosition); + EnsureCapacity(static_cast(nextPosition)); } else { @@ -210,7 +210,7 @@ void MemoryStream::Write(const void* buffer, uint64_t length) std::memcpy(_position, buffer, length); _position = (void*)((uintptr_t)_position + length); - _dataSize = std::max(_dataSize, (size_t)nextPosition); + _dataSize = std::max(_dataSize, static_cast(nextPosition)); } void MemoryStream::Write1(const void* buffer) @@ -251,6 +251,6 @@ void MemoryStream::EnsureCapacity(size_t capacity) uint64_t position = GetPosition(); _dataCapacity = newCapacity; _data = Memory::Reallocate(_data, _dataCapacity); - _position = (void*)((uintptr_t)_data + (uintptr_t)position); + _position = (void*)((uintptr_t)_data + static_cast(position)); } } diff --git a/src/openrct2/core/MemoryStream.h b/src/openrct2/core/MemoryStream.h index 0d313654e2..17fb778e78 100644 --- a/src/openrct2/core/MemoryStream.h +++ b/src/openrct2/core/MemoryStream.h @@ -93,7 +93,7 @@ public: { if (_access & MEMORY_ACCESS::OWNER) { - EnsureCapacity((size_t)nextPosition); + EnsureCapacity(static_cast(nextPosition)); } else { @@ -103,7 +103,7 @@ public: std::memcpy(_position, buffer, N); _position = (void*)((uintptr_t)_position + N); - _dataSize = std::max(_dataSize, (size_t)nextPosition); + _dataSize = std::max(_dataSize, static_cast(nextPosition)); } uint64_t TryRead(void* buffer, uint64_t length) override; diff --git a/src/openrct2/core/String.cpp b/src/openrct2/core/String.cpp index caebe49a4e..f764ccb17b 100644 --- a/src/openrct2/core/String.cpp +++ b/src/openrct2/core/String.cpp @@ -82,7 +82,7 @@ namespace String // UTF-32 is the default on most POSIX systems; Windows uses UTF-16. // Unfortunately, we'll have to help the compiler here. # if U_SIZEOF_WCHAR_T == 4 - icu::UnicodeString str = icu::UnicodeString::fromUTF32((const UChar32*)src.data(), src.length()); + icu::UnicodeString str = icu::UnicodeString::fromUTF32(reinterpret_cast(src.data()), src.length()); # elif U_SIZEOF_WCHAR_T == 2 std::wstring wstr = std::wstring(src); icu::UnicodeString str = icu::UnicodeString((const wchar_t*)wstr.c_str()); @@ -112,11 +112,11 @@ namespace String // UTF-32 is the default on most POSIX systems; Windows uses UTF-16. // Unfortunately, we'll have to help the compiler here. # if U_SIZEOF_WCHAR_T == 4 - size_t length = (size_t)str.length(); + size_t length = static_cast(str.length()); std::wstring result(length, '\0'); UErrorCode status = U_ZERO_ERROR; - str.toUTF32((UChar32*)&result[0], str.length(), status); + str.toUTF32(reinterpret_cast(&result[0]), str.length(), status); # elif U_SIZEOF_WCHAR_T == 2 const char16_t* buffer = str.getBuffer(); @@ -228,7 +228,7 @@ namespace String { if (*ch == match) { - return (size_t)(ch - str); + return static_cast(ch - str); } } return SIZE_MAX; @@ -336,7 +336,7 @@ namespace String return nullptr; } - size_t requiredSize = (size_t)len + 1; + size_t requiredSize = static_cast(len) + 1; if (requiredSize > bufferSize) { // Try again with bigger buffer @@ -454,12 +454,13 @@ namespace String utf8* SkipBOM(utf8* buffer) { - return (utf8*)SkipBOM((const utf8*)buffer); + return const_cast(SkipBOM((const utf8*)buffer)); } const utf8* SkipBOM(const utf8* buffer) { - if ((uint8_t)buffer[0] == 0xEF && (uint8_t)buffer[1] == 0xBB && (uint8_t)buffer[2] == 0xBF) + if (static_cast(buffer[0]) == 0xEF && static_cast(buffer[1]) == 0xBB + && static_cast(buffer[2]) == 0xBF) { return buffer + 3; } @@ -489,7 +490,7 @@ namespace String bool IsWhiteSpace(codepoint_t codepoint) { // 0x3000 is the 'ideographic space', a 'fullwidth' character used in CJK languages. - return iswspace((wchar_t)codepoint) || codepoint == 0x3000; + return iswspace(static_cast(codepoint)) || codepoint == 0x3000; } utf8* Trim(utf8* str) @@ -649,7 +650,8 @@ namespace String // Convert the lot. char* buffer_target = &buffer[0]; - ucnv_fromUnicode(conv, &buffer_target, buffer_limit, (const UChar**)&source, source_limit, nullptr, true, &status); + ucnv_fromUnicode( + conv, &buffer_target, buffer_limit, static_cast(&source), source_limit, nullptr, true, &status); if (U_FAILURE(status)) { diff --git a/src/openrct2/core/StringBuilder.hpp b/src/openrct2/core/StringBuilder.hpp index 8b436ba568..71d593e491 100644 --- a/src/openrct2/core/StringBuilder.hpp +++ b/src/openrct2/core/StringBuilder.hpp @@ -36,7 +36,7 @@ public: void Append(int32_t codepoint) { - Append((codepoint_t)codepoint); + Append(static_cast(codepoint)); } /** @@ -178,7 +178,7 @@ private: if (_capacity > capacity) return; - _capacity = std::max((size_t)8, _capacity); + _capacity = std::max(static_cast(8), _capacity); while (_capacity < capacity) { _capacity *= 2; diff --git a/src/openrct2/core/Zip.cpp b/src/openrct2/core/Zip.cpp index 65430095e1..2e77046117 100644 --- a/src/openrct2/core/Zip.cpp +++ b/src/openrct2/core/Zip.cpp @@ -84,7 +84,7 @@ public: auto zipFile = zip_fopen_index(_zip, index, 0); if (zipFile != nullptr) { - result.resize((size_t)dataSize); + result.resize(static_cast(dataSize)); uint64_t readBytes = zip_fread(zipFile, result.data(), dataSize); if (readBytes != dataSize) { diff --git a/src/openrct2/drawing/AVX2Drawing.cpp b/src/openrct2/drawing/AVX2Drawing.cpp index 709af9fa46..d553b422fe 100644 --- a/src/openrct2/drawing/AVX2Drawing.cpp +++ b/src/openrct2/drawing/AVX2Drawing.cpp @@ -27,13 +27,13 @@ void mask_avx2( const __m256i zero = {}; for (int32_t yy = 0; yy < height; yy++) { - const __m256i colour = _mm256_lddqu_si256((const __m256i*)(colourSrc + yy * colourWrapSIMD)); - const __m256i mask = _mm256_lddqu_si256((const __m256i*)(maskSrc + yy * maskWrapSIMD)); - const __m256i dest = _mm256_lddqu_si256((const __m256i*)(dst + yy * dstWrapSIMD)); + const __m256i colour = _mm256_lddqu_si256(reinterpret_cast(colourSrc + yy * colourWrapSIMD)); + const __m256i mask = _mm256_lddqu_si256(reinterpret_cast(maskSrc + yy * maskWrapSIMD)); + const __m256i dest = _mm256_lddqu_si256(reinterpret_cast(dst + yy * dstWrapSIMD)); const __m256i mc = _mm256_and_si256(colour, mask); const __m256i saturate = _mm256_cmpeq_epi8(mc, zero); const __m256i blended = _mm256_blendv_epi8(mc, dest, saturate); - _mm256_storeu_si256((__m256i*)(dst + yy * dstWrapSIMD), blended); + _mm256_storeu_si256(reinterpret_cast<__m256i*>(dst + yy * dstWrapSIMD), blended); } } else diff --git a/src/openrct2/drawing/Drawing.Sprite.cpp b/src/openrct2/drawing/Drawing.Sprite.cpp index b79b99c081..e268ef1b98 100644 --- a/src/openrct2/drawing/Drawing.Sprite.cpp +++ b/src/openrct2/drawing/Drawing.Sprite.cpp @@ -119,7 +119,7 @@ static void read_and_convert_gxdat(IStream* stream, size_t count, bool is_rctc, // Double cast to silence compiler warning about casting to // pointer from integer of mismatched length. - elements[i].offset = (uint8_t*)(uintptr_t)src.offset; + elements[i].offset = (uint8_t*)static_cast(src.offset); elements[i].width = src.width; elements[i].height = src.height; elements[i].x_offset = src.x_offset; @@ -128,7 +128,7 @@ static void read_and_convert_gxdat(IStream* stream, size_t count, bool is_rctc, if (src.flags & G1_FLAG_HAS_ZOOM_SPRITE) { - elements[i].zoomed_offset = (int32_t)(i - rctc_to_rct2_index(rctc - src.zoomed_offset)); + elements[i].zoomed_offset = static_cast(i - rctc_to_rct2_index(rctc - src.zoomed_offset)); } else { @@ -158,7 +158,7 @@ static void read_and_convert_gxdat(IStream* stream, size_t count, bool is_rctc, // Double cast to silence compiler warning about casting to // pointer from integer of mismatched length. - elements[i].offset = (uint8_t*)(uintptr_t)src.offset; + elements[i].offset = (uint8_t*)static_cast(src.offset); elements[i].width = src.width; elements[i].height = src.height; elements[i].x_offset = src.x_offset; @@ -359,8 +359,8 @@ bool gfx_load_csg() size_t fileHeaderSize = fileHeader.GetLength(); size_t fileDataSize = fileData.GetLength(); - _csg.header.num_entries = (uint32_t)(fileHeaderSize / sizeof(rct_g1_element_32bit)); - _csg.header.total_size = (uint32_t)fileDataSize; + _csg.header.num_entries = static_cast(fileHeaderSize / sizeof(rct_g1_element_32bit)); + _csg.header.total_size = static_cast(fileDataSize); if (_csg.header.num_entries < 69917) { @@ -626,7 +626,7 @@ void FASTCALL gfx_draw_sprite_palette_set_software( else if (!(g1->flags & G1_FLAG_1)) { // Move the pointer to the start point of the source - auto source_pointer = g1->offset + (((size_t)g1->width * source_start_y) + source_start_x); + auto source_pointer = g1->offset + ((static_cast(g1->width) * source_start_y) + source_start_x); gfx_bmp_sprite_to_buffer(palette_pointer, source_pointer, dest_pointer, g1, dpi, height, width, imageId); } } @@ -701,7 +701,7 @@ const rct_g1_element* gfx_get_g1_element(int32_t image_id) { openrct2_assert(!gOpenRCT2NoGraphics, "gfx_get_g1_element called on headless instance"); - auto offset = (size_t)image_id; + auto offset = static_cast(image_id); if (offset == 0x7FFFF) { return nullptr; @@ -777,14 +777,14 @@ void gfx_set_g1_element(int32_t imageId, const rct_g1_element* g1) { if (imageId < SPR_RCTC_G1_END) { - if (imageId < (int32_t)_g1.elements.size()) + if (imageId < static_cast(_g1.elements.size())) { _g1.elements[imageId] = *g1; } } else { - size_t idx = (size_t)imageId - SPR_IMAGE_LIST_BEGIN; + size_t idx = static_cast(imageId) - SPR_IMAGE_LIST_BEGIN; // Grow the element buffer if necessary while (idx >= _imageListElements.size()) { diff --git a/src/openrct2/drawing/Drawing.String.cpp b/src/openrct2/drawing/Drawing.String.cpp index f744c0975a..db5197adac 100644 --- a/src/openrct2/drawing/Drawing.String.cpp +++ b/src/openrct2/drawing/Drawing.String.cpp @@ -327,7 +327,7 @@ void draw_string_centred_raw(rct_drawpixelinfo* dpi, int32_t x, int32_t y, int32 { ch = nextCh; } - text = (char*)(ch + 1); + text = const_cast(ch + 1); y += font_get_line_height(gCurrentFontSpriteBase); } @@ -556,7 +556,7 @@ static void ttf_draw_string_raw_ttf(rct_drawpixelinfo* dpi, const utf8* text, te int32_t skipY = drawY - dpi->y; info->x += width; - auto src = (const uint8_t*)surface->pixels; + auto src = static_cast(surface->pixels); uint8_t* dst = dpi->bits; if (skipX < 0) @@ -690,11 +690,11 @@ static const utf8* ttf_process_format_code(rct_drawpixelinfo* dpi, const utf8* t switch (codepoint) { case FORMAT_MOVE_X: - info->x = info->startX + (uint8_t)(*nextCh++); + info->x = info->startX + static_cast(*nextCh++); break; case FORMAT_ADJUST_PALETTE: { - uint16_t eax = palette_to_g1_offset[(uint8_t)*nextCh++]; + uint16_t eax = palette_to_g1_offset[static_cast(*nextCh++)]; const rct_g1_element* g1 = gfx_get_g1_element(eax); if (g1 != nullptr) { @@ -821,7 +821,7 @@ static const utf8* ttf_process_glyph_run(rct_drawpixelinfo* dpi, const utf8* tex } else { - size_t length = (size_t)(ch - text); + size_t length = static_cast(ch - text); std::memcpy(buffer, text, length); buffer[length] = 0; ttf_draw_string_raw(dpi, buffer, info); @@ -866,10 +866,10 @@ static void ttf_process_initial_colour(int32_t colour, text_draw_info* info) if (colour != TEXT_COLOUR_254 && colour != TEXT_COLOUR_255) { info->flags &= ~(TEXT_DRAW_FLAG_INSET | TEXT_DRAW_FLAG_OUTLINE | TEXT_DRAW_FLAG_DARK | TEXT_DRAW_FLAG_EXTRA_DARK); - if ((int16_t)info->font_sprite_base < 0) + if (static_cast(info->font_sprite_base) < 0) { info->flags |= TEXT_DRAW_FLAG_DARK; - if ((int16_t)info->font_sprite_base == FONT_SPRITE_BASE_MEDIUM_EXTRA_DARK) + if (static_cast(info->font_sprite_base) == FONT_SPRITE_BASE_MEDIUM_EXTRA_DARK) { info->flags |= TEXT_DRAW_FLAG_EXTRA_DARK; } @@ -885,7 +885,7 @@ static void ttf_process_initial_colour(int32_t colour, text_draw_info* info) if (!(info->flags & TEXT_DRAW_FLAG_INSET)) { uint16_t flags = info->flags; - colour_char_window(colour, &flags, (uint8_t*)&info->palette); + colour_char_window(colour, &flags, reinterpret_cast(&info->palette)); } } else @@ -1020,7 +1020,7 @@ void shorten_path(utf8* buffer, size_t bufferSize, const utf8* path, int32_t ava size_t length = strlen(path); // Return full string if it fits - if (gfx_get_string_width((char*)path) <= availableWidth) + if (gfx_get_string_width(const_cast(path)) <= availableWidth) { safe_strcpy(buffer, path, bufferSize); return; diff --git a/src/openrct2/drawing/Drawing.cpp b/src/openrct2/drawing/Drawing.cpp index 98402535f6..f9b64fc2b1 100644 --- a/src/openrct2/drawing/Drawing.cpp +++ b/src/openrct2/drawing/Drawing.cpp @@ -565,7 +565,7 @@ void load_palette() return; } - auto water_type = (rct_water_type*)object_entry_get_chunk(OBJECT_TYPE_WATER, 0); + auto water_type = static_cast(object_entry_get_chunk(OBJECT_TYPE_WATER, 0)); uint32_t palette = 0x5FC; diff --git a/src/openrct2/drawing/Font.cpp b/src/openrct2/drawing/Font.cpp index ff09bb2d9d..c9c9f68c11 100644 --- a/src/openrct2/drawing/Font.cpp +++ b/src/openrct2/drawing/Font.cpp @@ -232,7 +232,7 @@ void font_sprite_initialise_characters() } } - _spriteFontCharacterWidths[fontSize][glyphIndex] = (uint8_t)width; + _spriteFontCharacterWidths[fontSize][glyphIndex] = static_cast(width); } } @@ -248,7 +248,7 @@ void font_sprite_initialise_characters() width = g1->width + (2 * g1->x_offset) - 1; } - _additionalSpriteFontCharacterWidth[fontSize][glyphIndex] = (uint8_t)width; + _additionalSpriteFontCharacterWidth[fontSize][glyphIndex] = static_cast(width); } } @@ -274,10 +274,10 @@ int32_t font_sprite_get_codepoint_offset(int32_t codepoint) int32_t font_sprite_get_codepoint_width(uint16_t fontSpriteBase, int32_t codepoint) { - if (fontSpriteBase == (uint16_t)FONT_SPRITE_BASE_MEDIUM_DARK - || fontSpriteBase == (uint16_t)FONT_SPRITE_BASE_MEDIUM_EXTRA_DARK) + if (fontSpriteBase == static_cast(FONT_SPRITE_BASE_MEDIUM_DARK) + || fontSpriteBase == static_cast(FONT_SPRITE_BASE_MEDIUM_EXTRA_DARK)) { - fontSpriteBase = (uint16_t)FONT_SPRITE_BASE_MEDIUM; + fontSpriteBase = static_cast(FONT_SPRITE_BASE_MEDIUM); } int32_t glyphIndex = font_sprite_get_codepoint_offset(codepoint); @@ -286,14 +286,14 @@ int32_t font_sprite_get_codepoint_width(uint16_t fontSpriteBase, int32_t codepoi { glyphIndex = (SPR_CHAR_START + glyphIndex) - SPR_G2_CHAR_BEGIN; - if (glyphIndex >= (int32_t)std::size(_additionalSpriteFontCharacterWidth[baseFontIndex])) + if (glyphIndex >= static_cast(std::size(_additionalSpriteFontCharacterWidth[baseFontIndex]))) { log_warning("Invalid glyph index %u", glyphIndex); glyphIndex = 0; } return _additionalSpriteFontCharacterWidth[baseFontIndex][glyphIndex]; } - else if (glyphIndex < 0 || glyphIndex >= (int32_t)FONT_SPRITE_GLYPH_COUNT) + else if (glyphIndex < 0 || glyphIndex >= static_cast(FONT_SPRITE_GLYPH_COUNT)) { log_warning("Invalid glyph index %u", glyphIndex); glyphIndex = 0; diff --git a/src/openrct2/drawing/ImageImporter.cpp b/src/openrct2/drawing/ImageImporter.cpp index e58377736b..5b9a573aec 100644 --- a/src/openrct2/drawing/ImageImporter.cpp +++ b/src/openrct2/drawing/ImageImporter.cpp @@ -41,7 +41,7 @@ ImportResult ImageImporter::Import( : EncodeRaw(pixels.data(), width, height); rct_g1_element outElement; - outElement.offset = (uint8_t*)buffer; + outElement.offset = static_cast(buffer); outElement.width = width; outElement.height = height; outElement.flags = (flags & IMPORT_FLAGS::RLE ? G1_FLAG_RLE_COMPRESSION : G1_FLAG_BMP); @@ -75,7 +75,7 @@ std::vector ImageImporter::GetPixels( { for (uint32_t x = 0; x < height * width * 4; x++) { - rgbaSrc[x] = (int16_t)pixels[x]; + rgbaSrc[x] = static_cast(pixels[x]); } } @@ -111,11 +111,11 @@ std::vector ImageImporter::GetPixels( std::tuple ImageImporter::EncodeRaw(const int32_t* pixels, uint32_t width, uint32_t height) { auto bufferLength = width * height; - auto buffer = (uint8_t*)std::malloc(bufferLength); + auto buffer = static_cast(std::malloc(bufferLength)); for (size_t i = 0; i < bufferLength; i++) { auto p = pixels[i]; - buffer[i] = (p == PALETTE_TRANSPARENT ? 0 : (uint8_t)p); + buffer[i] = (p == PALETTE_TRANSPARENT ? 0 : static_cast(p)); } return std::make_tuple(buffer, bufferLength); } @@ -129,21 +129,21 @@ std::tuple ImageImporter::EncodeRLE(const int32_t* pixels, uint32 }; auto src = pixels; - auto buffer = (uint8_t*)std::malloc((height * 2) + (width * height * 16)); + auto buffer = static_cast(std::malloc((height * 2) + (width * height * 16))); if (buffer == nullptr) { throw std::bad_alloc(); } std::fill_n(buffer, (height * 2) + (width * height * 16), 0x00); - auto yOffsets = (uint16_t*)buffer; + auto yOffsets = reinterpret_cast(buffer); auto dst = buffer + (height * 2); for (uint32_t y = 0; y < height; y++) { - yOffsets[y] = (uint16_t)(dst - buffer); + yOffsets[y] = static_cast(dst - buffer); auto previousCode = (RLECode*)nullptr; - auto currentCode = (RLECode*)dst; + auto currentCode = reinterpret_cast(dst); dst += 2; auto startX = 0; @@ -169,7 +169,7 @@ std::tuple ImageImporter::EncodeRLE(const int32_t* pixels, uint32 } npixels++; - *dst++ = (uint8_t)paletteIndex; + *dst++ = static_cast(paletteIndex); } if (npixels == 127 || x == width - 1) { @@ -189,7 +189,7 @@ std::tuple ImageImporter::EncodeRLE(const int32_t* pixels, uint32 currentCode->NumPixels |= 0x80; } - currentCode = (RLECode*)dst; + currentCode = reinterpret_cast(dst); dst += 2; } else @@ -213,8 +213,8 @@ std::tuple ImageImporter::EncodeRLE(const int32_t* pixels, uint32 } } - auto bufferLength = (size_t)(dst - buffer); - buffer = (uint8_t*)realloc(buffer, bufferLength); + auto bufferLength = static_cast(dst - buffer); + buffer = static_cast(realloc(buffer, bufferLength)); if (buffer == nullptr) { throw std::bad_alloc(); @@ -238,9 +238,9 @@ int32_t ImageImporter::CalculatePaletteIndex( { if (!IsTransparentPixel(rgbaSrc) && IsChangablePixel(GetPaletteIndex(palette, rgbaSrc))) { - auto dr = rgbaSrc[0] - (int16_t)(palette[paletteIndex].Red); - auto dg = rgbaSrc[1] - (int16_t)(palette[paletteIndex].Green); - auto db = rgbaSrc[2] - (int16_t)(palette[paletteIndex].Blue); + auto dr = rgbaSrc[0] - static_cast(palette[paletteIndex].Red); + auto dg = rgbaSrc[1] - static_cast(palette[paletteIndex].Green); + auto db = rgbaSrc[2] - static_cast(palette[paletteIndex].Blue); if (x + 1 < width) { @@ -298,8 +298,8 @@ int32_t ImageImporter::GetPaletteIndex(const PaletteBGRA* palette, int16_t* colo { for (int32_t i = 0; i < 256; i++) { - if ((int16_t)(palette[i].Red) == colour[0] && (int16_t)(palette[i].Green) == colour[1] - && (int16_t)(palette[i].Blue) == colour[2]) + if (static_cast(palette[i].Red) == colour[0] && static_cast(palette[i].Green) == colour[1] + && static_cast(palette[i].Blue) == colour[2]) { return i; } @@ -335,17 +335,18 @@ bool ImageImporter::IsChangablePixel(int32_t paletteIndex) int32_t ImageImporter::GetClosestPaletteIndex(const PaletteBGRA* palette, const int16_t* colour) { - auto smallestError = (uint32_t)-1; + auto smallestError = static_cast(-1); auto bestMatch = PALETTE_TRANSPARENT; for (int32_t x = 0; x < 256; x++) { if (IsChangablePixel(x)) { - uint32_t error = ((int16_t)(palette[x].Red) - colour[0]) * ((int16_t)(palette[x].Red) - colour[0]) - + ((int16_t)(palette[x].Green) - colour[1]) * ((int16_t)(palette[x].Green) - colour[1]) - + ((int16_t)(palette[x].Blue) - colour[2]) * ((int16_t)(palette[x].Blue) - colour[2]); + uint32_t error = (static_cast(palette[x].Red) - colour[0]) + * (static_cast(palette[x].Red) - colour[0]) + + (static_cast(palette[x].Green) - colour[1]) * (static_cast(palette[x].Green) - colour[1]) + + (static_cast(palette[x].Blue) - colour[2]) * (static_cast(palette[x].Blue) - colour[2]); - if (smallestError == (uint32_t)-1 || smallestError > error) + if (smallestError == static_cast(-1) || smallestError > error) { bestMatch = x; smallestError = error; diff --git a/src/openrct2/drawing/LightFX.cpp b/src/openrct2/drawing/LightFX.cpp index b76465aa50..09561ec1c2 100644 --- a/src/openrct2/drawing/LightFX.cpp +++ b/src/openrct2/drawing/LightFX.cpp @@ -81,24 +81,24 @@ static rct_palette gPalette_light; static uint8_t calc_light_intensity_lantern(int32_t x, int32_t y) { - double distance = (double)(x * x + y * y); + double distance = static_cast(x * x + y * y); double light = 0.03 + std::pow(10.0 / (1.0 + distance / 100.0), 0.55); light *= std::min(1.0, std::max(0.0, 2.0 - std::sqrt(distance) / 64)); light *= 0.1f; - return (uint8_t)(std::min(255.0, light * 255.0)); + return static_cast(std::min(255.0, light * 255.0)); } static uint8_t calc_light_intensity_spot(int32_t x, int32_t y) { - double distance = (double)(x * x + y * y); + double distance = static_cast(x * x + y * y); double light = 0.3 + std::pow(10.0 / (1.0 + distance / 100.0), 0.75); light *= std::min(1.0, std::max(0.0, 2.0 - std::sqrt(distance) / 64)); light *= 0.5f; - return (uint8_t)(std::min(255.0, light * 255.0)) >> 4; + return static_cast(std::min(255.0, light * 255.0)) >> 4; } static void calc_rescale_light_half(uint8_t* target, uint8_t* source, uint32_t targetWidth, uint32_t targetHeight) @@ -425,7 +425,7 @@ void lightfx_swap_buffers() tmp = _LightListBack; _LightListBack = _LightListFront; - _LightListFront = (lightlist_entry*)tmp; + _LightListFront = static_cast(tmp); LightListCurrentCountFront = LightListCurrentCountBack; LightListCurrentCountBack = 0x0; @@ -470,7 +470,7 @@ void lightfx_render_lights_to_frontbuffer() for (uint32_t light = 0; light < LightListCurrentCountFront; light++) { const uint8_t* bufReadBase = nullptr; - uint8_t* bufWriteBase = (uint8_t*)_light_rendered_buffer_front; + uint8_t* bufWriteBase = static_cast(_light_rendered_buffer_front); uint32_t bufReadWidth, bufReadHeight; int32_t bufWriteX, bufWriteY; int32_t bufWriteWidth, bufWriteHeight; @@ -825,7 +825,7 @@ void lightfx_add_lights_magic_vehicle(const Vehicle* vehicle) void lightfx_apply_palette_filter(uint8_t i, uint8_t* r, uint8_t* g, uint8_t* b) { - float night = (float)(pow(gDayNightCycle, 1.5)); + float night = static_cast(pow(gDayNightCycle, 1.5)); float natLightR = 1.0f; float natLightG = 1.0f; @@ -842,9 +842,9 @@ void lightfx_apply_palette_filter(uint8_t i, uint8_t* r, uint8_t* g, uint8_t* b) float sunLight = std::max(0.0f, std::min(1.0f, 2.0f - night * 3.0f)); // Night version - natLightR = flerp(natLightR * 4.0f, 0.635f, (float)(std::pow(night, 0.035f + sunLight * 10.50f))); - natLightG = flerp(natLightG * 4.0f, 0.650f, (float)(std::pow(night, 0.100f + sunLight * 5.50f))); - natLightB = flerp(natLightB * 4.0f, 0.850f, (float)(std::pow(night, 0.200f + sunLight * 1.5f))); + natLightR = flerp(natLightR * 4.0f, 0.635f, (std::pow(night, 0.035f + sunLight * 10.50f))); + natLightG = flerp(natLightG * 4.0f, 0.650f, (std::pow(night, 0.100f + sunLight * 5.50f))); + natLightB = flerp(natLightB * 4.0f, 0.850f, (std::pow(night, 0.200f + sunLight * 1.5f))); float overExpose = 0.0f; float lightAvg = (natLightR + natLightG + natLightB) / 3.0f; @@ -856,7 +856,7 @@ void lightfx_apply_palette_filter(uint8_t i, uint8_t* r, uint8_t* g, uint8_t* b) if (gClimateCurrent.Temperature > 20) { - float offset = ((float)(gClimateCurrent.Temperature - 20)) * 0.04f; + float offset = (static_cast(gClimateCurrent.Temperature - 20)) * 0.04f; offset *= 1.0f - night; lightAvg /= 1.0f + offset; // overExpose += offset * 0.1f; @@ -878,12 +878,12 @@ void lightfx_apply_palette_filter(uint8_t i, uint8_t* r, uint8_t* g, uint8_t* b) natLightB *= 1.0f + overExpose; overExpose *= 255.0f; - float targetFogginess = (float)(gClimateCurrent.RainLevel) / 8.0f; + float targetFogginess = static_cast(gClimateCurrent.RainLevel) / 8.0f; targetFogginess += (night * night) * 0.15f; if (gClimateCurrent.Temperature < 10) { - targetFogginess += ((float)(10 - gClimateCurrent.Temperature)) * 0.01f; + targetFogginess += (static_cast(10 - gClimateCurrent.Temperature)) * 0.01f; } fogginess -= (fogginess - targetFogginess) * 0.00001f; @@ -903,9 +903,10 @@ void lightfx_apply_palette_filter(uint8_t i, uint8_t* r, uint8_t* g, uint8_t* b) float reduceColourNat = 1.0f; float reduceColourLit = 1.0f; - reduceColourLit *= night / (float)std::pow(std::max(1.01f, 0.4f + lightAvg), 2.0); + reduceColourLit *= night / static_cast(std::pow(std::max(1.01f, 0.4f + lightAvg), 2.0)); - float targetLightPollution = reduceColourLit * std::max(0.0f, 0.0f + 0.000001f * (float)lightfx_get_light_polution()); + float targetLightPollution = reduceColourLit + * std::max(0.0f, 0.0f + 0.000001f * static_cast(lightfx_get_light_polution())); lightPolution -= (lightPolution - targetLightPollution) * 0.001f; // lightPollution /= 1.0f + fogginess * 1.0f; @@ -920,7 +921,7 @@ void lightfx_apply_palette_filter(uint8_t i, uint8_t* r, uint8_t* g, uint8_t* b) natLightG /= 1.0f + lightPolution; natLightB /= 1.0f + lightPolution; - reduceColourLit += (float)(gClimateCurrent.RainLevel) / 2.0f; + reduceColourLit += static_cast(gClimateCurrent.RainLevel) / 2.0f; reduceColourNat /= 1.0f + fogginess; reduceColourLit /= 1.0f + fogginess; @@ -950,15 +951,15 @@ void lightfx_apply_palette_filter(uint8_t i, uint8_t* r, uint8_t* g, uint8_t* b) else if ((i % 16) < 7) boost = 1.001f * wetnessBoost; if (i > 230 && i < 232) - boost = ((float)(*b)) / 64.0f; + boost = (static_cast(*b)) / 64.0f; if (false) { // This experiment shifts the colour of pixels as-if they are wet, but it is not a pretty solution at all if ((i % 16)) { - float iVal = ((float)((i + 12) % 16)) / 16.0f; - float eff = (wetness * ((float)std::pow(iVal, 1.5) * 0.85f)); + float iVal = (static_cast((i + 12) % 16)) / 16.0f; + float eff = (wetness * (static_cast(std::pow(iVal, 1.5)) * 0.85f)); reduceColourNat *= 1.0f - eff; addLightNatR += fogR * eff * 3.95f; addLightNatG += fogR * eff * 3.95f; @@ -970,17 +971,26 @@ void lightfx_apply_palette_filter(uint8_t i, uint8_t* r, uint8_t* g, uint8_t* b) addLightNatG *= 1.0f - envFog; addLightNatB *= 1.0f - envFog; - *r = (uint8_t)(std::min( - 255.0f, std::max(0.0f, (-overExpose + (float)(*r) * reduceColourNat * natLightR + envFog * fogR + addLightNatR)))); - *g = (uint8_t)(std::min( - 255.0f, std::max(0.0f, (-overExpose + (float)(*g) * reduceColourNat * natLightG + envFog * fogG + addLightNatG)))); - *b = (uint8_t)(std::min( - 255.0f, std::max(0.0f, (-overExpose + (float)(*b) * reduceColourNat * natLightB + envFog * fogB + addLightNatB)))); + *r = static_cast(std::min( + 255.0f, + std::max( + 0.0f, (-overExpose + static_cast(*r) * reduceColourNat * natLightR + envFog * fogR + addLightNatR)))); + *g = static_cast(std::min( + 255.0f, + std::max( + 0.0f, (-overExpose + static_cast(*g) * reduceColourNat * natLightG + envFog * fogG + addLightNatG)))); + *b = static_cast(std::min( + 255.0f, + std::max( + 0.0f, (-overExpose + static_cast(*b) * reduceColourNat * natLightB + envFog * fogB + addLightNatB)))); rct_palette_entry* dstEntry = &gPalette_light.entries[i]; - dstEntry->red = (uint8_t)(std::min(0xFF, ((float)(*r) * reduceColourLit * boost + lightFog) * elecMultR)); - dstEntry->green = (uint8_t)(std::min(0xFF, ((float)(*g) * reduceColourLit * boost + lightFog) * elecMultG)); - dstEntry->blue = (uint8_t)(std::min(0xFF, ((float)(*b) * reduceColourLit * boost + lightFog) * elecMultB)); + dstEntry->red = static_cast( + std::min(0xFF, (static_cast(*r) * reduceColourLit * boost + lightFog) * elecMultR)); + dstEntry->green = static_cast( + std::min(0xFF, (static_cast(*g) * reduceColourLit * boost + lightFog) * elecMultG)); + dstEntry->blue = static_cast( + std::min(0xFF, (static_cast(*b) * reduceColourLit * boost + lightFog) * elecMultB)); } } @@ -1002,7 +1012,7 @@ void lightfx_render_to_texture( lightfx_prepare_light_list(); lightfx_render_lights_to_frontbuffer(); - uint8_t* lightBits = (uint8_t*)lightfx_get_front_buffer(); + uint8_t* lightBits = static_cast(lightfx_get_front_buffer()); if (lightBits == nullptr) { return; @@ -1010,7 +1020,7 @@ void lightfx_render_to_texture( for (uint32_t y = 0; y < height; y++) { - uintptr_t dstOffset = (uintptr_t)(y * dstPitch); + uintptr_t dstOffset = static_cast(y * dstPitch); uint32_t* dst = (uint32_t*)((uintptr_t)dstPixels + dstOffset); for (uint32_t x = 0; x < width; x++) { diff --git a/src/openrct2/drawing/Rain.cpp b/src/openrct2/drawing/Rain.cpp index 57af305803..50011da10c 100644 --- a/src/openrct2/drawing/Rain.cpp +++ b/src/openrct2/drawing/Rain.cpp @@ -65,14 +65,14 @@ void DrawRain(rct_drawpixelinfo* dpi, IRainDrawer* rainDrawer) */ static void DrawLightRain(IRainDrawer* rainDrawer, int32_t left, int32_t top, int32_t width, int32_t height) { - int32_t x_start = -(int32_t)gScenarioTicks + 8; + int32_t x_start = -static_cast(gScenarioTicks) + 8; int32_t y_start = (gScenarioTicks * 3) + 7; y_start = -y_start; x_start += left; y_start += top; rainDrawer->Draw(left, top, width, height, x_start, y_start); - x_start = -(int32_t)gScenarioTicks + 0x18; + x_start = -static_cast(gScenarioTicks) + 0x18; y_start = (gScenarioTicks * 4) + 0x0D; y_start = -y_start; x_start += left; @@ -86,28 +86,28 @@ static void DrawLightRain(IRainDrawer* rainDrawer, int32_t left, int32_t top, in */ static void DrawHeavyRain(IRainDrawer* rainDrawer, int32_t left, int32_t top, int32_t width, int32_t height) { - int32_t x_start = -(int32_t)gScenarioTicks; + int32_t x_start = -static_cast(gScenarioTicks); int32_t y_start = gScenarioTicks * 5; y_start = -y_start; x_start += left; y_start += top; rainDrawer->Draw(left, top, width, height, x_start, y_start); - x_start = -(int32_t)gScenarioTicks + 0x10; + x_start = -static_cast(gScenarioTicks) + 0x10; y_start = (gScenarioTicks * 6) + 5; y_start = -y_start; x_start += left; y_start += top; rainDrawer->Draw(left, top, width, height, x_start, y_start); - x_start = -(int32_t)gScenarioTicks + 8; + x_start = -static_cast(gScenarioTicks) + 8; y_start = (gScenarioTicks * 3) + 7; y_start = -y_start; x_start += left; y_start += top; rainDrawer->Draw(left, top, width, height, x_start, y_start); - x_start = -(int32_t)gScenarioTicks + 0x18; + x_start = -static_cast(gScenarioTicks) + 0x18; y_start = (gScenarioTicks * 4) + 0x0D; y_start = -y_start; x_start += left; diff --git a/src/openrct2/drawing/SSE41Drawing.cpp b/src/openrct2/drawing/SSE41Drawing.cpp index 45cbe97caf..8d795b14ea 100644 --- a/src/openrct2/drawing/SSE41Drawing.cpp +++ b/src/openrct2/drawing/SSE41Drawing.cpp @@ -29,25 +29,25 @@ void mask_sse4_1( int32_t dstStep = yy * (dstWrap + 32); // first half - const __m128i colour1 = _mm_lddqu_si128((const __m128i*)(colourSrc + colourStep)); - const __m128i mask1 = _mm_lddqu_si128((const __m128i*)(maskSrc + maskStep)); - const __m128i dest1 = _mm_lddqu_si128((const __m128i*)(dst + dstStep)); + const __m128i colour1 = _mm_lddqu_si128(reinterpret_cast(colourSrc + colourStep)); + const __m128i mask1 = _mm_lddqu_si128(reinterpret_cast(maskSrc + maskStep)); + const __m128i dest1 = _mm_lddqu_si128(reinterpret_cast(dst + dstStep)); const __m128i mc1 = _mm_and_si128(colour1, mask1); const __m128i saturate1 = _mm_cmpeq_epi8(mc1, zero128); // _mm_blendv_epi8 is SSE4.1 const __m128i blended1 = _mm_blendv_epi8(mc1, dest1, saturate1); // second half - const __m128i colour2 = _mm_lddqu_si128((const __m128i*)(colourSrc + 16 + colourStep)); - const __m128i mask2 = _mm_lddqu_si128((const __m128i*)(maskSrc + 16 + maskStep)); - const __m128i dest2 = _mm_lddqu_si128((const __m128i*)(dst + 16 + dstStep)); + const __m128i colour2 = _mm_lddqu_si128(reinterpret_cast(colourSrc + 16 + colourStep)); + const __m128i mask2 = _mm_lddqu_si128(reinterpret_cast(maskSrc + 16 + maskStep)); + const __m128i dest2 = _mm_lddqu_si128(reinterpret_cast(dst + 16 + dstStep)); const __m128i mc2 = _mm_and_si128(colour2, mask2); const __m128i saturate2 = _mm_cmpeq_epi8(mc2, zero128); // _mm_blendv_epi8 is SSE4.1 const __m128i blended2 = _mm_blendv_epi8(mc2, dest2, saturate2); - _mm_storeu_si128((__m128i*)(dst + dstStep), blended1); - _mm_storeu_si128((__m128i*)(dst + 16 + dstStep), blended2); + _mm_storeu_si128(reinterpret_cast<__m128i*>(dst + dstStep), blended1); + _mm_storeu_si128(reinterpret_cast<__m128i*>(dst + 16 + dstStep), blended2); } } else diff --git a/src/openrct2/drawing/ScrollingText.cpp b/src/openrct2/drawing/ScrollingText.cpp index b9c8a37c88..efb08e1040 100644 --- a/src/openrct2/drawing/ScrollingText.cpp +++ b/src/openrct2/drawing/ScrollingText.cpp @@ -46,7 +46,7 @@ void scrolling_text_initialise_bitmaps() { uint8_t drawingSurface[64]; rct_drawpixelinfo dpi; - dpi.bits = (uint8_t*)&drawingSurface; + dpi.bits = reinterpret_cast(&drawingSurface); dpi.width = 8; dpi.height = 8; @@ -1596,7 +1596,7 @@ static void scrolling_text_set_bitmap_for_ttf( int32_t pitch = surface->pitch; int32_t width = surface->w; - auto src = (const uint8_t*)surface->pixels; + auto src = static_cast(surface->pixels); // Pitch offset src += 2 * pitch; diff --git a/src/openrct2/drawing/TTF.cpp b/src/openrct2/drawing/TTF.cpp index b7d2a079f0..e20a727ecd 100644 --- a/src/openrct2/drawing/TTF.cpp +++ b/src/openrct2/drawing/TTF.cpp @@ -183,7 +183,7 @@ static void ttf_close_font(TTF_Font* font) static uint32_t ttf_surface_cache_hash(TTF_Font* font, const utf8* text) { - uint32_t hash = (uint32_t)((((uintptr_t)font * 23) ^ 0xAAAAAAAA) & 0xFFFFFFFF); + uint32_t hash = static_cast((((uintptr_t)font * 23) ^ 0xAAAAAAAA) & 0xFFFFFFFF); for (const utf8* ch = text; *ch != 0; ch++) { hash = ror32(hash, 3) ^ (*ch * 13); @@ -376,7 +376,7 @@ static TTFSurface* ttf_render(TTF_Font* font, const utf8* text) void ttf_free_surface(TTFSurface* surface) { - free((void*)surface->pixels); + free(const_cast(surface->pixels)); free(surface); } diff --git a/src/openrct2/drawing/TTFSDLPort.cpp b/src/openrct2/drawing/TTFSDLPort.cpp index 1e56960107..43eaf85e7b 100644 --- a/src/openrct2/drawing/TTFSDLPort.cpp +++ b/src/openrct2/drawing/TTFSDLPort.cpp @@ -323,13 +323,13 @@ static unsigned long RWread(FT_Stream stream, unsigned long offset, unsigned cha { FILE* src; - src = (FILE*)stream->descriptor.pointer; - fseek(src, (int)offset, SEEK_SET); + src = static_cast(stream->descriptor.pointer); + fseek(src, static_cast(offset), SEEK_SET); if (count == 0) { return 0; } - return (unsigned long)fread(buffer, 1, (int)count, src); + return static_cast(fread(buffer, 1, static_cast(count), src)); } static size_t fsize(FILE* file) @@ -337,7 +337,7 @@ static size_t fsize(FILE* file) size_t origPos = ftell(file); fseek(file, 0, SEEK_END); size_t size = ftell(file); - fseek(file, (long)origPos, SEEK_SET); + fseek(file, static_cast(origPos), SEEK_SET); return size; } @@ -380,7 +380,7 @@ static TTF_Font* TTF_OpenFontIndexRW(FILE* src, int freesrc, int ptsize, long in return NULL; } - font = (TTF_Font*)malloc(sizeof *font); + font = static_cast(malloc(sizeof *font)); if (font == NULL) { TTF_SetError("Out of memory"); @@ -390,24 +390,24 @@ static TTF_Font* TTF_OpenFontIndexRW(FILE* src, int freesrc, int ptsize, long in } return NULL; } - std::fill_n((uint8_t*)font, sizeof(*font), 0x00); + std::fill_n(reinterpret_cast(font), sizeof(*font), 0x00); font->src = src; font->freesrc = freesrc; - stream = (FT_Stream)malloc(sizeof(*stream)); + stream = static_cast(malloc(sizeof(*stream))); if (stream == NULL) { TTF_SetError("Out of memory"); TTF_CloseFont(font); return NULL; } - std::fill_n((uint8_t*)stream, sizeof(*stream), 0x00); + std::fill_n(reinterpret_cast(stream), sizeof(*stream), 0x00); stream->read = RWread; stream->descriptor.pointer = src; - stream->pos = (unsigned long)position; - stream->size = (unsigned long)(fsize(src) - position); + stream->pos = static_cast(position); + stream->size = static_cast(fsize(src) - position); font->args.flags = FT_OPEN_STREAM; font->args.stream = stream; @@ -636,7 +636,7 @@ static FT_Error Load_Glyph(TTF_Font* font, uint16_t ch, c_glyph* cached, int wan } if (TTF_HANDLE_STYLE_ITALIC(font)) { - cached->maxx += (int)ceil(font->glyph_italics); + cached->maxx += static_cast(ceil(font->glyph_italics)); } cached->stored |= CACHED_METRICS; } @@ -656,7 +656,7 @@ static FT_Error Load_Glyph(TTF_Font* font, uint16_t ch, c_glyph* cached, int wan FT_Matrix shear; shear.xx = 1 << 16; - shear.xy = (int)(font->glyph_italics * (1 << 16)) / font->height; + shear.xy = static_cast(font->glyph_italics * (1 << 16)) / font->height; shear.yx = 0; shear.yy = 1 << 16; @@ -683,7 +683,7 @@ static FT_Error Load_Glyph(TTF_Font* font, uint16_t ch, c_glyph* cached, int wan FT_Done_Glyph(bitmap_glyph); return error; } - src = &((FT_BitmapGlyph)bitmap_glyph)->bitmap; + src = &(reinterpret_cast(bitmap_glyph))->bitmap; } else { @@ -738,14 +738,14 @@ static FT_Error Load_Glyph(TTF_Font* font, uint16_t ch, c_glyph* cached, int wan } if (TTF_HANDLE_STYLE_ITALIC(font)) { - int bump = (int)ceil(font->glyph_italics); + int bump = static_cast(ceil(font->glyph_italics)); dst->pitch += bump; dst->width += bump; } if (dst->rows != 0) { - dst->buffer = (unsigned char*)malloc(dst->pitch * dst->rows); + dst->buffer = static_cast(malloc(dst->pitch * dst->rows)); if (!dst->buffer) { return FT_Err_Out_Of_Memory; @@ -929,7 +929,7 @@ static FT_Error Load_Glyph(TTF_Font* font, uint16_t ch, c_glyph* cached, int wan { pixel = NUM_GRAYS - 1; } - pixmap[col] = (uint8_t)pixel; + pixmap[col] = static_cast(pixel); } } } @@ -1002,7 +1002,7 @@ void TTF_CloseFont(TTF_Font* font) # define UNKNOWN_UNICODE 0xFFFD static uint32_t UTF8_getch(const char** src, size_t* srclen) { - const uint8_t* p = *(const uint8_t**)src; + const uint8_t* p = *reinterpret_cast(src); size_t left = 0; [[maybe_unused]] bool overlong = false; bool underflow = false; @@ -1020,7 +1020,7 @@ static uint32_t UTF8_getch(const char** src, size_t* srclen) { overlong = true; } - ch = (uint32_t)(p[0] & 0x01); + ch = static_cast(p[0] & 0x01); left = 5; } } @@ -1032,7 +1032,7 @@ static uint32_t UTF8_getch(const char** src, size_t* srclen) { overlong = true; } - ch = (uint32_t)(p[0] & 0x03); + ch = static_cast(p[0] & 0x03); left = 4; } } @@ -1044,7 +1044,7 @@ static uint32_t UTF8_getch(const char** src, size_t* srclen) { overlong = true; } - ch = (uint32_t)(p[0] & 0x07); + ch = static_cast(p[0] & 0x07); left = 3; } } @@ -1056,7 +1056,7 @@ static uint32_t UTF8_getch(const char** src, size_t* srclen) { overlong = true; } - ch = (uint32_t)(p[0] & 0x0F); + ch = static_cast(p[0] & 0x0F); left = 2; } } @@ -1068,7 +1068,7 @@ static uint32_t UTF8_getch(const char** src, size_t* srclen) { overlong = true; } - ch = (uint32_t)(p[0] & 0x1F); + ch = static_cast(p[0] & 0x1F); left = 1; } } @@ -1076,7 +1076,7 @@ static uint32_t UTF8_getch(const char** src, size_t* srclen) { if ((p[0] & 0x80) == 0x00) { - ch = (uint32_t)p[0]; + ch = static_cast(p[0]); } } ++*src; @@ -1284,7 +1284,7 @@ TTFSurface* TTF_RenderUTF8_Solid(TTF_Font* font, const char* text, [[maybe_unuse } /* Create the target surface */ - textbuf = (TTFSurface*)calloc(1, sizeof(TTFSurface)); + textbuf = static_cast(calloc(1, sizeof(TTFSurface))); if (textbuf == NULL) { return NULL; @@ -1347,11 +1347,11 @@ TTFSurface* TTF_RenderUTF8_Solid(TTF_Font* font, const char* text, [[maybe_unuse { /* Make sure we don't go either over, or under the * limit */ - if ((signed)row + glyph->yoffset < 0) + if (static_cast(row) + glyph->yoffset < 0) { continue; } - if ((signed)row + glyph->yoffset >= textbuf->h) + if (static_cast(row) + glyph->yoffset >= textbuf->h) { continue; } @@ -1416,7 +1416,7 @@ TTFSurface* TTF_RenderUTF8_Shaded(TTF_Font* font, const char* text, [[maybe_unus } /* Create the target surface */ - textbuf = (TTFSurface*)calloc(1, sizeof(TTFSurface)); + textbuf = static_cast(calloc(1, sizeof(TTFSurface))); if (textbuf == NULL) { return NULL; @@ -1483,11 +1483,11 @@ TTFSurface* TTF_RenderUTF8_Shaded(TTF_Font* font, const char* text, [[maybe_unus { /* Make sure we don't go either over, or under the * limit */ - if ((signed)row + glyph->yoffset < 0) + if (static_cast(row) + glyph->yoffset < 0) { continue; } - if ((signed)row + glyph->yoffset >= textbuf->h) + if (static_cast(row) + glyph->yoffset >= textbuf->h) { continue; } diff --git a/src/openrct2/drawing/X8DrawingEngine.cpp b/src/openrct2/drawing/X8DrawingEngine.cpp index b6e411cb29..1573486b89 100644 --- a/src/openrct2/drawing/X8DrawingEngine.cpp +++ b/src/openrct2/drawing/X8DrawingEngine.cpp @@ -66,12 +66,12 @@ void X8RainDrawer::Draw(int32_t x, int32_t y, int32_t width, int32_t height, int uint8_t patternX = pattern[patternYPos * 2]; if (patternX != 0xFF) { - if (_rainPixelsCount < (_rainPixelsCapacity - (uint32_t)width)) + if (_rainPixelsCount < (_rainPixelsCapacity - static_cast(width))) { uint32_t finalPixelOffset = width + pixelOffset; uint32_t xPixelOffset = pixelOffset; - xPixelOffset += ((uint8_t)(patternX - patternStartXOffset)) % patternXSpace; + xPixelOffset += (static_cast(patternX - patternStartXOffset)) % patternXSpace; uint8_t patternPixel = pattern[patternYPos * 2 + 1]; for (; xPixelOffset < finalPixelOffset; xPixelOffset += patternXSpace) @@ -158,8 +158,8 @@ void X8DrawingEngine::Invalidate(int32_t left, int32_t top, int32_t right, int32 { left = std::max(left, 0); top = std::max(top, 0); - right = std::min(right, (int32_t)_width); - bottom = std::min(bottom, (int32_t)_height); + right = std::min(right, static_cast(_width)); + bottom = std::min(bottom, static_cast(_height)); if (left >= right) return; @@ -238,9 +238,9 @@ void X8DrawingEngine::CopyRect(int32_t x, int32_t y, int32_t width, int32_t heig // screen; hence the checks. This code should ultimately not be called when // zooming because this function is specific to updating the screen on move int32_t lmargin = std::min(x - dx, 0); - int32_t rmargin = std::min((int32_t)_width - (x - dx + width), 0); + int32_t rmargin = std::min(static_cast(_width) - (x - dx + width), 0); int32_t tmargin = std::min(y - dy, 0); - int32_t bmargin = std::min((int32_t)_height - (y - dy + height), 0); + int32_t bmargin = std::min(static_cast(_height) - (y - dy + height), 0); x -= lmargin; y -= tmargin; width += lmargin + rmargin; @@ -699,7 +699,8 @@ void X8DrawingContext::FilterRect(FILTER_PALETTE_ID palette, int32_t left, int32 // 00678B7E 00678C83 // Location in screen buffer? uint8_t* dst = dpi->bits - + (uint32_t)((startY / dpi->zoom_level) * ((dpi->width / dpi->zoom_level) + dpi->pitch) + (startX / dpi->zoom_level)); + + static_cast( + (startY / dpi->zoom_level) * ((dpi->width / dpi->zoom_level) + dpi->pitch) + (startX / dpi->zoom_level)); // Find colour in colour table? uint16_t g1Index = palette_to_g1_offset[palette]; diff --git a/src/openrct2/interface/Chat.cpp b/src/openrct2/interface/Chat.cpp index 50db2b1a96..7caf627525 100644 --- a/src/openrct2/interface/Chat.cpp +++ b/src/openrct2/interface/Chat.cpp @@ -196,7 +196,7 @@ void chat_draw(rct_drawpixelinfo* dpi, uint8_t chatBackgroundColor) void chat_history_add(const char* src) { size_t bufferSize = strlen(src) + 64; - utf8* buffer = (utf8*)calloc(1, bufferSize); + utf8* buffer = static_cast(calloc(1, bufferSize)); // Find the start of the text (after format codes) const char* ch = src; @@ -213,7 +213,7 @@ void chat_history_add(const char* src) const char* srcText = ch; // Copy format codes to buffer - std::memcpy(buffer, src, std::min(bufferSize, (size_t)(srcText - src))); + std::memcpy(buffer, src, std::min(bufferSize, static_cast(srcText - src))); // Prepend a timestamp time_t timer; diff --git a/src/openrct2/interface/InteractiveConsole.cpp b/src/openrct2/interface/InteractiveConsole.cpp index 5074025b50..164b5b93d2 100644 --- a/src/openrct2/interface/InteractiveConsole.cpp +++ b/src/openrct2/interface/InteractiveConsole.cpp @@ -224,7 +224,7 @@ static int32_t cc_rides(InteractiveConsole& console, const arguments_t& argv) } else { - ride->mode = (uint8_t)(mode & 0xFF); + ride->mode = static_cast(mode & 0xFF); invalidate_test_results(ride); } } @@ -777,7 +777,7 @@ static int32_t cc_set(InteractiveConsole& console, const arguments_t& argv) } else if (argv[0] == "guest_initial_happiness" && invalidArguments(&invalidArgs, int_valid[0])) { - gGuestInitialHappiness = calculate_guest_initial_happiness((uint8_t)int_val[0]); + gGuestInitialHappiness = calculate_guest_initial_happiness(static_cast(int_val[0])); console.Execute("get guest_initial_happiness"); } else if (argv[0] == "guest_initial_hunger" && invalidArguments(&invalidArgs, int_valid[0])) @@ -914,7 +914,7 @@ static int32_t cc_set(InteractiveConsole& console, const arguments_t& argv) } else if (argv[0] == "window_scale" && invalidArguments(&invalidArgs, double_valid[0])) { - float newScale = (float)(0.001 * std::trunc(1000 * double_val[0])); + float newScale = static_cast(0.001 * std::trunc(1000 * double_val[0])); gConfigGeneral.window_scale = std::clamp(newScale, 0.5f, 5.0f); config_save_default(); gfx_invalidate_screen(); @@ -1299,7 +1299,8 @@ static int32_t cc_for_date([[maybe_unused]] InteractiveConsole& console, [[maybe // YYYY OR YYYY MM (no day provided, preserve existing day) if (argv.size() <= 2) { - day = std::clamp(gDateMonthTicks / (0x10000 / days_in_month[month - 1]) + 1, 1, (int)days_in_month[month - 1]); + day = std::clamp( + gDateMonthTicks / (0x10000 / days_in_month[month - 1]) + 1, 1, static_cast(days_in_month[month - 1])); } // YYYY MM DD (year, month, and day provided) diff --git a/src/openrct2/interface/Screenshot.cpp b/src/openrct2/interface/Screenshot.cpp index 5ecd6dba48..af0a291527 100644 --- a/src/openrct2/interface/Screenshot.cpp +++ b/src/openrct2/interface/Screenshot.cpp @@ -198,7 +198,7 @@ std::string screenshot_dump_png_32bpp(int32_t width, int32_t height, const void* return ""; } - const auto pixels8 = (const uint8_t*)pixels; + const auto pixels8 = static_cast(pixels); const auto pixelsLen = width * 4 * height; try @@ -333,7 +333,7 @@ static rct_drawpixelinfo CreateDPI(const rct_viewport& viewport) if (viewport.flags & VIEWPORT_FLAG_TRANSPARENT_BACKGROUND) { - std::memset(dpi.bits, PALETTE_INDEX_0, (size_t)dpi.width * dpi.height); + std::memset(dpi.bits, PALETTE_INDEX_0, static_cast(dpi.width) * dpi.height); } return dpi; diff --git a/src/openrct2/interface/Viewport.cpp b/src/openrct2/interface/Viewport.cpp index c4b7d2bda7..f4940da05c 100644 --- a/src/openrct2/interface/Viewport.cpp +++ b/src/openrct2/interface/Viewport.cpp @@ -903,11 +903,11 @@ void viewport_paint( right = left + width; bottom = top + height; - int16_t x = (int16_t)(left - (int16_t)(viewport->viewPos.x & bitmask)); + int16_t x = static_cast(left - static_cast(viewport->viewPos.x & bitmask)); x = x / viewport->zoom; x += viewport->pos.x; - int16_t y = (int16_t)(top - (int16_t)(viewport->viewPos.y & bitmask)); + int16_t y = static_cast(top - static_cast(viewport->viewPos.y & bitmask)); y = y / viewport->zoom; y += viewport->pos.y; @@ -1252,7 +1252,7 @@ void viewport_set_visibility(uint8_t mode) case 5: // 6CB7D8 // Set underground off, invalidate if it was on invalidate += vp->flags & VIEWPORT_FLAG_UNDERGROUND_INSIDE; - vp->flags &= ~((uint16_t)VIEWPORT_FLAG_UNDERGROUND_INSIDE); + vp->flags &= ~(static_cast(VIEWPORT_FLAG_UNDERGROUND_INSIDE)); break; } if (invalidate != 0) @@ -1425,8 +1425,8 @@ static bool is_sprite_interacted_with_palette_set( // TODO: SAR in dpi done with `>> 1`, in coordinates with `/ 2` rct_drawpixelinfo zoomed_dpi = { /* .bits = */ dpi->bits, - /* .x = */ (int16_t)(dpi->x >> 1), - /* .y = */ (int16_t)(dpi->y >> 1), + /* .x = */ static_cast(dpi->x >> 1), + /* .y = */ static_cast(dpi->y >> 1), /* .height = */ dpi->height, /* .width = */ dpi->width, /* .pitch = */ dpi->pitch, @@ -1645,8 +1645,8 @@ void get_map_coordinates_from_pos_window( { rct_viewport* myviewport = window->viewport; screenCoords -= myviewport->pos; - if (screenCoords.x >= 0 && screenCoords.x < (int32_t)myviewport->width && screenCoords.y >= 0 - && screenCoords.y < (int32_t)myviewport->height) + if (screenCoords.x >= 0 && screenCoords.x < static_cast(myviewport->width) && screenCoords.y >= 0 + && screenCoords.y < static_cast(myviewport->height)) { screenCoords.x = screenCoords.x * myviewport->zoom; screenCoords.y = screenCoords.y * myviewport->zoom; diff --git a/src/openrct2/interface/Window.cpp b/src/openrct2/interface/Window.cpp index 7999d783e9..a1316f2859 100644 --- a/src/openrct2/interface/Window.cpp +++ b/src/openrct2/interface/Window.cpp @@ -162,7 +162,7 @@ void window_update_all() static void window_close_surplus(int32_t cap, int8_t avoid_classification) { // find the amount of windows that are currently open - auto count = (int32_t)g_window_list.size(); + auto count = static_cast(g_window_list.size()); // difference between amount open and cap = amount to close auto diff = count - WINDOW_LIMIT_RESERVED - cap; for (auto i = 0; i < diff; i++) @@ -846,8 +846,8 @@ void window_scroll_to_location(rct_window* w, int32_t x, int32_t y, int32_t z) bool found = false; while (!found) { - int16_t x2 = w->viewport->pos.x + (int16_t)(w->viewport->width * window_scroll_locations[i][0]); - int16_t y2 = w->viewport->pos.y + (int16_t)(w->viewport->height * window_scroll_locations[i][1]); + int16_t x2 = w->viewport->pos.x + static_cast(w->viewport->width * window_scroll_locations[i][0]); + int16_t y2 = w->viewport->pos.y + static_cast(w->viewport->height * window_scroll_locations[i][1]); auto it = window_get_iterator(w); for (; it != g_window_list.end(); it++) @@ -870,7 +870,7 @@ void window_scroll_to_location(rct_window* w, int32_t x, int32_t y, int32_t z) { found = true; } - if (i >= (int32_t)std::size(window_scroll_locations)) + if (i >= static_cast(std::size(window_scroll_locations))) { i = 0; found = true; @@ -883,8 +883,8 @@ void window_scroll_to_location(rct_window* w, int32_t x, int32_t y, int32_t z) if (!(w->flags & WF_NO_SCROLLING)) { w->savedViewPos = screenCoords - - ScreenCoordsXY{ (int16_t)(w->viewport->view_width * window_scroll_locations[i][0]), - (int16_t)(w->viewport->view_height * window_scroll_locations[i][1]) }; + - ScreenCoordsXY{ static_cast(w->viewport->view_width * window_scroll_locations[i][0]), + static_cast(w->viewport->view_height * window_scroll_locations[i][1]) }; w->flags |= WF_SCROLLING_TO_LOCATION; } } @@ -2082,7 +2082,7 @@ void window_follow_sprite(rct_window* w, size_t spriteIndex) { if (spriteIndex < MAX_SPRITES || spriteIndex == SPRITE_INDEX_NULL) { - w->viewport_smart_follow_sprite = (uint16_t)spriteIndex; + w->viewport_smart_follow_sprite = static_cast(spriteIndex); } } @@ -2157,8 +2157,8 @@ void widget_scroll_update_thumbs(rct_window* w, rct_widgetindex widget_index) { double barPosition = (scroll->h_thumb_right * 1.0) / view_size; - scroll->h_thumb_left = (uint16_t)std::lround(scroll->h_thumb_left - (20 * barPosition)); - scroll->h_thumb_right = (uint16_t)std::lround(scroll->h_thumb_right + (20 * (1 - barPosition))); + scroll->h_thumb_left = static_cast(std::lround(scroll->h_thumb_left - (20 * barPosition))); + scroll->h_thumb_right = static_cast(std::lround(scroll->h_thumb_right + (20 * (1 - barPosition)))); } } @@ -2186,8 +2186,8 @@ void widget_scroll_update_thumbs(rct_window* w, rct_widgetindex widget_index) { double barPosition = (scroll->v_thumb_bottom * 1.0) / view_size; - scroll->v_thumb_top = (uint16_t)std::lround(scroll->v_thumb_top - (20 * barPosition)); - scroll->v_thumb_bottom = (uint16_t)std::lround(scroll->v_thumb_bottom + (20 * (1 - barPosition))); + scroll->v_thumb_top = static_cast(std::lround(scroll->v_thumb_top - (20 * barPosition))); + scroll->v_thumb_bottom = static_cast(std::lround(scroll->v_thumb_bottom + (20 * (1 - barPosition)))); } } } diff --git a/src/openrct2/localisation/ConversionTables.cpp b/src/openrct2/localisation/ConversionTables.cpp index 066c737df6..1667546744 100644 --- a/src/openrct2/localisation/ConversionTables.cpp +++ b/src/openrct2/localisation/ConversionTables.cpp @@ -110,7 +110,7 @@ static int32_t encoding_search_compare(const void *pKey, const void *pEntry) static wchar_t encoding_convert_x_to_unicode(wchar_t code, const encoding_convert_entry *table, size_t count) { - encoding_convert_entry * entry = (encoding_convert_entry *)std::bsearch(&code, table, count, sizeof(encoding_convert_entry), encoding_search_compare); + encoding_convert_entry * entry = static_cast(std::bsearch(&code, table, count, sizeof(encoding_convert_entry), encoding_search_compare)); if (entry == nullptr) return code; else return entry->unicode; } diff --git a/src/openrct2/localisation/Convert.cpp b/src/openrct2/localisation/Convert.cpp index 032b23ee3d..345632aba3 100644 --- a/src/openrct2/localisation/Convert.cpp +++ b/src/openrct2/localisation/Convert.cpp @@ -99,7 +99,7 @@ static std::string Encode(const std::string_view& src) } else if (codepoint <= std::numeric_limits::max()) { - dst.push_back((char)(uint8_t)0xFF); + dst.push_back(static_cast(static_cast(0xFF))); dst.push_back((codepoint >> 8) & 0xFF); dst.push_back(codepoint & 0xFF); } diff --git a/src/openrct2/localisation/Language.cpp b/src/openrct2/localisation/Language.cpp index cca9d7428b..f7cc78bea6 100644 --- a/src/openrct2/localisation/Language.cpp +++ b/src/openrct2/localisation/Language.cpp @@ -51,11 +51,11 @@ const language_descriptor LanguagesDescriptors[LANGUAGE_COUNT] = // clang-format on // clang-format off -const utf8 BlackUpArrowString[] = { (utf8)(uint8_t)0xC2, (utf8)(uint8_t)0x8E, (utf8)(uint8_t)0xE2, (utf8)(uint8_t)0x96, (utf8)(uint8_t)0xB2, (utf8)(uint8_t)0x00 }; -const utf8 BlackDownArrowString[] = { (utf8)(uint8_t)0xC2, (utf8)(uint8_t)0x8E, (utf8)(uint8_t)0xE2, (utf8)(uint8_t)0x96, (utf8)(uint8_t)0xBC, (utf8)(uint8_t)0x00 }; -const utf8 BlackLeftArrowString[] = { (utf8)(uint8_t)0xC2, (utf8)(uint8_t)0x8E, (utf8)(uint8_t)0xE2, (utf8)(uint8_t)0x97, (utf8)(uint8_t)0x80, (utf8)(uint8_t)0x00 }; -const utf8 BlackRightArrowString[] = { (utf8)(uint8_t)0xC2, (utf8)(uint8_t)0x8E, (utf8)(uint8_t)0xE2, (utf8)(uint8_t)0x96, (utf8)(uint8_t)0xB6, (utf8)(uint8_t)0x00 }; -const utf8 CheckBoxMarkString[] = { (utf8)(uint8_t)0xE2, (utf8)(uint8_t)0x9C, (utf8)(uint8_t)0x93, (utf8)(uint8_t)0x00 }; +const utf8 BlackUpArrowString[] = { static_cast(static_cast(0xC2)), static_cast(static_cast(0x8E)), static_cast(static_cast(0xE2)), static_cast(static_cast(0x96)), static_cast(static_cast(0xB2)), static_cast(static_cast(0x00)) }; +const utf8 BlackDownArrowString[] = { static_cast(static_cast(0xC2)), static_cast(static_cast(0x8E)), static_cast(static_cast(0xE2)), static_cast(static_cast(0x96)), static_cast(static_cast(0xBC)), static_cast(static_cast(0x00)) }; +const utf8 BlackLeftArrowString[] = { static_cast(static_cast(0xC2)), static_cast(static_cast(0x8E)), static_cast(static_cast(0xE2)), static_cast(static_cast(0x97)), static_cast(static_cast(0x80)), static_cast(static_cast(0x00)) }; +const utf8 BlackRightArrowString[] = { static_cast(static_cast(0xC2)), static_cast(static_cast(0x8E)), static_cast(static_cast(0xE2)), static_cast(static_cast(0x96)), static_cast(static_cast(0xB6)), static_cast(static_cast(0x00)) }; +const utf8 CheckBoxMarkString[] = { static_cast(static_cast(0xE2)), static_cast(static_cast(0x9C)), static_cast(static_cast(0x93)), static_cast(static_cast(0x00)) }; // clang-format on void utf8_remove_format_codes(utf8* text, bool allowcolours) diff --git a/src/openrct2/localisation/Language.h b/src/openrct2/localisation/Language.h index 11ab1e9969..ef10e08e2b 100644 --- a/src/openrct2/localisation/Language.h +++ b/src/openrct2/localisation/Language.h @@ -112,7 +112,7 @@ constexpr utf8* utf8_write_codepoint(utf8* dst, uint32_t codepoint) { if (codepoint <= 0x7F) { - dst[0] = (utf8)codepoint; + dst[0] = static_cast(codepoint); return dst + 1; } else if (codepoint <= 0x7FF) diff --git a/src/openrct2/localisation/LanguagePack.cpp b/src/openrct2/localisation/LanguagePack.cpp index 9d0953ba77..8509ae7aa4 100644 --- a/src/openrct2/localisation/LanguagePack.cpp +++ b/src/openrct2/localisation/LanguagePack.cpp @@ -79,7 +79,7 @@ public: { FileStream fs = FileStream(path, FILE_MODE_OPEN); - size_t fileLength = (size_t)fs.GetLength(); + size_t fileLength = static_cast(fs.GetLength()); if (fileLength > MAX_LANGUAGE_SIZE) { throw IOException("Language file too large."); @@ -132,12 +132,12 @@ public: uint32_t GetCount() const override { - return (uint32_t)_strings.size(); + return static_cast(_strings.size()); } void RemoveString(rct_string_id stringId) override { - if (_strings.size() >= (size_t)stringId) + if (_strings.size() >= static_cast(stringId)) { _strings[stringId] = std::string(); } @@ -145,7 +145,7 @@ public: void SetString(rct_string_id stringId, const std::string& str) override { - if (_strings.size() >= (size_t)stringId) + if (_strings.size() >= static_cast(stringId)) { _strings[stringId] = str; } @@ -159,7 +159,8 @@ public: int32_t ooIndex = offset / ScenarioOverrideMaxStringCount; int32_t ooStringIndex = offset % ScenarioOverrideMaxStringCount; - if (_scenarioOverrides.size() > (size_t)ooIndex && !_scenarioOverrides[ooIndex].strings[ooStringIndex].empty()) + if (_scenarioOverrides.size() > static_cast(ooIndex) + && !_scenarioOverrides[ooIndex].strings[ooStringIndex].empty()) { return _scenarioOverrides[ooIndex].strings[ooStringIndex].c_str(); } @@ -174,7 +175,8 @@ public: int32_t ooIndex = offset / ObjectOverrideMaxStringCount; int32_t ooStringIndex = offset % ObjectOverrideMaxStringCount; - if (_objectOverrides.size() > (size_t)ooIndex && !_objectOverrides[ooIndex].strings[ooStringIndex].empty()) + if (_objectOverrides.size() > static_cast(ooIndex) + && !_objectOverrides[ooIndex].strings[ooStringIndex].empty()) { return _objectOverrides[ooIndex].strings[ooStringIndex].c_str(); } @@ -185,7 +187,7 @@ public: } else { - if ((_strings.size() > (size_t)stringId) && !_strings[stringId].empty()) + if ((_strings.size() > static_cast(stringId)) && !_strings[stringId].empty()) { return _strings[stringId].c_str(); } @@ -553,11 +555,11 @@ private: { if (isByte) { - sb.Append((const utf8*)&token, 1); + sb.Append(reinterpret_cast(&token), 1); } else { - sb.Append((int32_t)token); + sb.Append(static_cast(token)); } } else @@ -587,7 +589,7 @@ private: if (_currentGroup.empty()) { // Make sure the list is big enough to contain this string id - if ((size_t)stringId >= _strings.size()) + if (static_cast(stringId) >= _strings.size()) { _strings.resize(stringId + 1); } @@ -652,7 +654,7 @@ private: #ifdef _WIN32 return input; #else - UErrorCode err = (UErrorCode)0; + UErrorCode err = static_cast(0); // Force a hard left-to-right at the beginning (will mess up mixed strings' word order otherwise) std::string text2 = std::string(u8"\xE2\x80\xAA") + input; diff --git a/src/openrct2/localisation/Localisation.Date.cpp b/src/openrct2/localisation/Localisation.Date.cpp index 6507a9afdd..e1c78968e7 100644 --- a/src/openrct2/localisation/Localisation.Date.cpp +++ b/src/openrct2/localisation/Localisation.Date.cpp @@ -68,8 +68,8 @@ void date_reset() void date_set(int32_t year, int32_t month, int32_t day) { year = std::clamp(year, 1, MAX_YEAR); - month = std::clamp(month, 1, (int)MONTH_COUNT); - day = std::clamp(day, 1, (int)days_in_month[month - 1]); + month = std::clamp(month, 1, static_cast(MONTH_COUNT)); + day = std::clamp(day, 1, static_cast(days_in_month[month - 1])); gDateMonthsElapsed = (year - 1) * MONTH_COUNT + month - 1; gDateMonthTicks = 0x10000 / days_in_month[month - 1] * (day - 1) + 4; } @@ -84,7 +84,7 @@ void date_update() } else { - gDateMonthTicks = floor2((uint16_t)monthTicks, 4); + gDateMonthTicks = floor2(static_cast(monthTicks), 4); } } diff --git a/src/openrct2/localisation/Localisation.cpp b/src/openrct2/localisation/Localisation.cpp index ccfb3950b5..486e0d72fe 100644 --- a/src/openrct2/localisation/Localisation.cpp +++ b/src/openrct2/localisation/Localisation.cpp @@ -879,7 +879,7 @@ static void format_date(char** dest, size_t* size, uint16_t value) { uint16_t args[] = { static_cast(date_get_month(value)), static_cast(date_get_year(value) + 1) }; uint16_t* argsRef = args; - format_string_part(dest, size, STR_DATE_FORMAT_MY, (char**)&argsRef); + format_string_part(dest, size, STR_DATE_FORMAT_MY, reinterpret_cast(&argsRef)); } static void format_length(char** dest, size_t* size, int16_t value) @@ -893,7 +893,7 @@ static void format_length(char** dest, size_t* size, int16_t value) } int16_t* argRef = &value; - format_string_part(dest, size, stringId, (char**)&argRef); + format_string_part(dest, size, stringId, reinterpret_cast(&argRef)); } static void format_velocity(char** dest, size_t* size, uint16_t value) @@ -916,7 +916,7 @@ static void format_velocity(char** dest, size_t* size, uint16_t value) } uint16_t* argRef = &value; - format_string_part(dest, size, stringId, (char**)&argRef); + format_string_part(dest, size, stringId, reinterpret_cast(&argRef)); } static constexpr const rct_string_id DurationFormats[][2] = { @@ -952,7 +952,7 @@ static void format_duration(char** dest, size_t* size, uint16_t value) rct_string_id stringId = DurationFormats[minuteIndex][secondsIndex]; - format_string_part(dest, size, stringId, (char**)&argsRef); + format_string_part(dest, size, stringId, reinterpret_cast(&argsRef)); } static constexpr const rct_string_id RealtimeFormats[][2] = { @@ -988,7 +988,7 @@ static void format_realtime(char** dest, size_t* size, uint16_t value) rct_string_id stringId = RealtimeFormats[hourIndex][minuteIndex]; - format_string_part(dest, size, stringId, (char**)&argsRef); + format_string_part(dest, size, stringId, reinterpret_cast(&argsRef)); } static void format_string_code(uint32_t format_code, char** dest, size_t* size, char** args) @@ -1080,7 +1080,7 @@ static void format_string_code(uint32_t format_code, char** dest, size_t* size, std::memcpy(&value, *args, sizeof(uint16_t)); *args += 2; - format_string_part(dest, size, (rct_string_id)value, args); + format_string_part(dest, size, static_cast(value), args); break; case FORMAT_STRING: // Pop argument @@ -1095,14 +1095,15 @@ static void format_string_code(uint32_t format_code, char** dest, size_t* size, std::memcpy(&value, *args, sizeof(uint16_t)); *args += 2; - format_date(dest, size, (uint16_t)value); + format_date(dest, size, static_cast(value)); break; case FORMAT_MONTH: // Pop argument std::memcpy(&value, *args, sizeof(uint16_t)); *args += 2; - format_append_string(dest, size, language_get_string(DateGameMonthNames[date_get_month((int32_t)value)])); + format_append_string( + dest, size, language_get_string(DateGameMonthNames[date_get_month(static_cast(value))])); break; case FORMAT_VELOCITY: // Pop argument @@ -1110,7 +1111,7 @@ static void format_string_code(uint32_t format_code, char** dest, size_t* size, value = temp16; *args += 2; - format_velocity(dest, size, (uint16_t)value); + format_velocity(dest, size, static_cast(value)); break; case FORMAT_POP16: *args += 2; @@ -1123,14 +1124,14 @@ static void format_string_code(uint32_t format_code, char** dest, size_t* size, std::memcpy(&value, *args, sizeof(uint16_t)); *args += 2; - format_duration(dest, size, (uint16_t)value); + format_duration(dest, size, static_cast(value)); break; case FORMAT_REALTIME: // Pop argument std::memcpy(&value, *args, sizeof(uint16_t)); *args += 2; - format_realtime(dest, size, (uint16_t)value); + format_realtime(dest, size, static_cast(value)); break; case FORMAT_LENGTH: // Pop argument @@ -1138,7 +1139,7 @@ static void format_string_code(uint32_t format_code, char** dest, size_t* size, value = temp16; *args += 2; - format_length(dest, size, (int16_t)value); + format_length(dest, size, static_cast(value)); break; case FORMAT_SPRITE: // Pop argument @@ -1211,7 +1212,7 @@ static void format_string_part_from_raw(utf8** dest, size_t* size, const utf8* s } else { - size_t codepointLength = (size_t)utf8_get_codepoint_length(code); + size_t codepointLength = static_cast(utf8_get_codepoint_length(code)); format_handle_overflow(codepointLength); if (*size > codepointLength) { diff --git a/src/openrct2/localisation/UTF8.cpp b/src/openrct2/localisation/UTF8.cpp index 4049e6a372..6251d313af 100644 --- a/src/openrct2/localisation/UTF8.cpp +++ b/src/openrct2/localisation/UTF8.cpp @@ -120,7 +120,7 @@ utf8* get_string_end(const utf8* text) int32_t argLength = utf8_get_format_code_arg_length(codepoint); ch += argLength; } - return (utf8*)(ch - 1); + return const_cast(ch - 1); } /** diff --git a/src/openrct2/management/Award.cpp b/src/openrct2/management/Award.cpp index 2948a3f810..78a4f796ca 100644 --- a/src/openrct2/management/Award.cpp +++ b/src/openrct2/management/Award.cpp @@ -397,9 +397,9 @@ static bool award_is_deserved_best_restrooms([[maybe_unused]] int32_t activeAwar { // Count open restrooms const auto& rideManager = GetRideManager(); - auto numRestrooms = (size_t)std::count_if(rideManager.begin(), rideManager.end(), [](const Ride& ride) { + auto numRestrooms = static_cast(std::count_if(rideManager.begin(), rideManager.end(), [](const Ride& ride) { return ride.type == RIDE_TYPE_TOILETS && ride.status == RIDE_STATUS_OPEN; - }); + })); // At least 4 open restrooms if (numRestrooms < 4) diff --git a/src/openrct2/network/Network.cpp b/src/openrct2/network/Network.cpp index 505029d4e3..58982dbc35 100644 --- a/src/openrct2/network/Network.cpp +++ b/src/openrct2/network/Network.cpp @@ -901,7 +901,7 @@ const char* Network::FormatChat(NetworkPlayer* fromplayer, const char* text) { lineCh = utf8_write_codepoint(lineCh, FORMAT_OUTLINE); lineCh = utf8_write_codepoint(lineCh, FORMAT_BABYBLUE); - safe_strcpy(lineCh, (const char*)fromplayer->Name.c_str(), sizeof(formatted) - (lineCh - formatted)); + safe_strcpy(lineCh, static_cast(fromplayer->Name.c_str()), sizeof(formatted) - (lineCh - formatted)); safe_strcat(lineCh, ": ", sizeof(formatted) - (lineCh - formatted)); lineCh = strchr(lineCh, '\0'); } @@ -1241,7 +1241,7 @@ void Network::LoadGroups() else { json_t* json_groups = json_object_get(json, "groups"); - size_t groupCount = (size_t)json_array_size(json_groups); + size_t groupCount = json_array_size(json_groups); for (size_t i = 0; i < groupCount; i++) { json_t* jsonGroup = json_array_get(json_groups, i); @@ -1250,7 +1250,7 @@ void Network::LoadGroups() group_list.push_back(std::move(newgroup)); } json_t* jsonDefaultGroup = json_object_get(json, "default_group"); - default_group = (uint8_t)json_integer_value(jsonDefaultGroup); + default_group = static_cast(json_integer_value(jsonDefaultGroup)); if (GetGroupByID(default_group) == nullptr) { default_group = 0; @@ -1400,7 +1400,7 @@ void Network::Client_Send_RequestGameState(uint32_t tick) log_verbose("Requesting gamestate from server for tick %u", tick); std::unique_ptr packet(NetworkPacket::Allocate()); - *packet << (uint32_t)NETWORK_COMMAND_REQUEST_GAMESTATE << tick; + *packet << static_cast(NETWORK_COMMAND_REQUEST_GAMESTATE) << tick; _serverConnection->QueuePacket(std::move(packet)); } @@ -1408,7 +1408,7 @@ void Network::Client_Send_TOKEN() { log_verbose("requesting token"); std::unique_ptr packet(NetworkPacket::Allocate()); - *packet << (uint32_t)NETWORK_COMMAND_TOKEN; + *packet << static_cast(NETWORK_COMMAND_TOKEN); _serverConnection->AuthStatus = NETWORK_AUTH_REQUESTED; _serverConnection->QueuePacket(std::move(packet)); } @@ -1417,13 +1417,13 @@ void Network::Client_Send_AUTH( const std::string& name, const std::string& password, const std::string& pubkey, const std::vector& signature) { std::unique_ptr packet(NetworkPacket::Allocate()); - *packet << (uint32_t)NETWORK_COMMAND_AUTH; + *packet << static_cast(NETWORK_COMMAND_AUTH); packet->WriteString(network_get_version().c_str()); packet->WriteString(name.c_str()); packet->WriteString(password.c_str()); packet->WriteString(pubkey.c_str()); assert(signature.size() <= (size_t)UINT32_MAX); - *packet << (uint32_t)signature.size(); + *packet << static_cast(signature.size()); packet->Write(signature.data(), signature.size()); _serverConnection->AuthStatus = NETWORK_AUTH_REQUESTED; _serverConnection->QueuePacket(std::move(packet)); @@ -1433,11 +1433,11 @@ void Network::Client_Send_OBJECTS(const std::vector& objects) { log_verbose("client requests %u objects", uint32_t(objects.size())); std::unique_ptr packet(NetworkPacket::Allocate()); - *packet << (uint32_t)NETWORK_COMMAND_OBJECTS << (uint32_t)objects.size(); + *packet << static_cast(NETWORK_COMMAND_OBJECTS) << static_cast(objects.size()); for (const auto& object : objects) { log_verbose("client requests object %s", object.c_str()); - packet->Write((const uint8_t*)object.c_str(), 8); + packet->Write(reinterpret_cast(object.c_str()), 8); } _serverConnection->QueuePacket(std::move(packet)); } @@ -1445,7 +1445,7 @@ void Network::Client_Send_OBJECTS(const std::vector& objects) void Network::Server_Send_TOKEN(NetworkConnection& connection) { std::unique_ptr packet(NetworkPacket::Allocate()); - *packet << (uint32_t)NETWORK_COMMAND_TOKEN << (uint32_t)connection.Challenge.size(); + *packet << static_cast(NETWORK_COMMAND_TOKEN) << static_cast(connection.Challenge.size()); packet->Write(connection.Challenge.data(), connection.Challenge.size()); connection.QueuePacket(std::move(packet)); } @@ -1454,11 +1454,11 @@ void Network::Server_Send_OBJECTS(NetworkConnection& connection, const std::vect { log_verbose("Server sends objects list with %u items", objects.size()); std::unique_ptr packet(NetworkPacket::Allocate()); - *packet << (uint32_t)NETWORK_COMMAND_OBJECTS << (uint32_t)objects.size(); + *packet << static_cast(NETWORK_COMMAND_OBJECTS) << static_cast(objects.size()); for (auto object : objects) { log_verbose("Object %.8s (checksum %x)", object->ObjectEntry.name, object->ObjectEntry.checksum); - packet->Write((const uint8_t*)object->ObjectEntry.name, 8); + packet->Write(reinterpret_cast(object->ObjectEntry.name), 8); *packet << object->ObjectEntry.checksum << object->ObjectEntry.flags; } connection.QueuePacket(std::move(packet)); @@ -1493,7 +1493,7 @@ void Network::Server_Send_AUTH(NetworkConnection& connection) new_playerid = connection.Player->Id; } std::unique_ptr packet(NetworkPacket::Allocate()); - *packet << (uint32_t)NETWORK_COMMAND_AUTH << (uint32_t)connection.AuthStatus << new_playerid; + *packet << static_cast(NETWORK_COMMAND_AUTH) << static_cast(connection.AuthStatus) << new_playerid; if (connection.AuthStatus == NETWORK_AUTH_BADVERSION) { packet->WriteString(network_get_version().c_str()); @@ -1537,7 +1537,7 @@ void Network::Server_Send_MAP(NetworkConnection* connection) { size_t datasize = std::min(chunksize, out_size - i); std::unique_ptr packet(NetworkPacket::Allocate()); - *packet << (uint32_t)NETWORK_COMMAND_MAP << (uint32_t)out_size << (uint32_t)i; + *packet << static_cast(NETWORK_COMMAND_MAP) << static_cast(out_size) << static_cast(i); packet->Write(&header[i], datasize); if (connection) { @@ -1569,12 +1569,12 @@ uint8_t* Network::save_for_network(size_t& out_size, const std::vector(data), size, &out_size); if (compressed != nullptr) { - header = (uint8_t*)_strdup("open2_sv6_zlib"); - size_t header_len = strlen((char*)header) + 1; // account for null terminator - header = (uint8_t*)realloc(header, header_len + out_size); + header = reinterpret_cast(_strdup("open2_sv6_zlib")); + size_t header_len = strlen(reinterpret_cast(header)) + 1; // account for null terminator + header = static_cast(realloc(header, header_len + out_size)); if (header == nullptr) { log_error("Failed to allocate %u bytes.", header_len + out_size); @@ -1590,7 +1590,7 @@ uint8_t* Network::save_for_network(size_t& out_size, const std::vector(malloc(size)); if (header == nullptr) { log_error("Failed to allocate %u bytes.", size); @@ -1607,7 +1607,7 @@ uint8_t* Network::save_for_network(size_t& out_size, const std::vector packet(NetworkPacket::Allocate()); - *packet << (uint32_t)NETWORK_COMMAND_CHAT; + *packet << static_cast(NETWORK_COMMAND_CHAT); packet->WriteString(text); _serverConnection->QueuePacket(std::move(packet)); } @@ -1615,7 +1615,7 @@ void Network::Client_Send_CHAT(const char* text) void Network::Server_Send_CHAT(const char* text) { std::unique_ptr packet(NetworkPacket::Allocate()); - *packet << (uint32_t)NETWORK_COMMAND_CHAT; + *packet << static_cast(NETWORK_COMMAND_CHAT); packet->WriteString(text); SendPacketToClients(*packet); } @@ -1637,7 +1637,7 @@ void Network::Client_Send_GAME_ACTION(const GameAction* action) DataSerialiser stream(true); action->Serialise(stream); - *packet << (uint32_t)NETWORK_COMMAND_GAME_ACTION << gCurrentTicks << action->GetType() << stream; + *packet << static_cast(NETWORK_COMMAND_GAME_ACTION) << gCurrentTicks << action->GetType() << stream; _serverConnection->QueuePacket(std::move(packet)); } @@ -1648,7 +1648,7 @@ void Network::Server_Send_GAME_ACTION(const GameAction* action) DataSerialiser stream(true); action->Serialise(stream); - *packet << (uint32_t)NETWORK_COMMAND_GAME_ACTION << gCurrentTicks << action->GetType() << stream; + *packet << static_cast(NETWORK_COMMAND_GAME_ACTION) << gCurrentTicks << action->GetType() << stream; SendPacketToClients(*packet); } @@ -1656,7 +1656,7 @@ void Network::Server_Send_GAME_ACTION(const GameAction* action) void Network::Server_Send_TICK() { std::unique_ptr packet(NetworkPacket::Allocate()); - *packet << (uint32_t)NETWORK_COMMAND_TICK << gCurrentTicks << scenario_rand_state().s0; + *packet << static_cast(NETWORK_COMMAND_TICK) << gCurrentTicks << scenario_rand_state().s0; uint32_t flags = 0; // Simple counter which limits how often a sprite checksum gets sent. // This can get somewhat expensive, so we don't want to push it every tick in release, @@ -1683,7 +1683,7 @@ void Network::Server_Send_TICK() void Network::Server_Send_PLAYERINFO(int32_t playerId) { std::unique_ptr packet(NetworkPacket::Allocate()); - *packet << (uint32_t)NETWORK_COMMAND_PLAYERINFO << gCurrentTicks; + *packet << static_cast(NETWORK_COMMAND_PLAYERINFO) << gCurrentTicks; auto* player = GetPlayerByID(playerId); if (player == nullptr) @@ -1696,7 +1696,7 @@ void Network::Server_Send_PLAYERINFO(int32_t playerId) void Network::Server_Send_PLAYERLIST() { std::unique_ptr packet(NetworkPacket::Allocate()); - *packet << (uint32_t)NETWORK_COMMAND_PLAYERLIST << gCurrentTicks << (uint8_t)player_list.size(); + *packet << static_cast(NETWORK_COMMAND_PLAYERLIST) << gCurrentTicks << static_cast(player_list.size()); for (auto& player : player_list) { player->Write(*packet); @@ -1707,7 +1707,7 @@ void Network::Server_Send_PLAYERLIST() void Network::Client_Send_PING() { std::unique_ptr packet(NetworkPacket::Allocate()); - *packet << (uint32_t)NETWORK_COMMAND_PING; + *packet << static_cast(NETWORK_COMMAND_PING); _serverConnection->QueuePacket(std::move(packet)); } @@ -1715,7 +1715,7 @@ void Network::Server_Send_PING() { last_ping_sent_time = platform_get_ticks(); std::unique_ptr packet(NetworkPacket::Allocate()); - *packet << (uint32_t)NETWORK_COMMAND_PING; + *packet << static_cast(NETWORK_COMMAND_PING); for (auto& client_connection : client_connection_list) { client_connection->PingTime = platform_get_ticks(); @@ -1726,7 +1726,7 @@ void Network::Server_Send_PING() void Network::Server_Send_PINGLIST() { std::unique_ptr packet(NetworkPacket::Allocate()); - *packet << (uint32_t)NETWORK_COMMAND_PINGLIST << (uint8_t)player_list.size(); + *packet << static_cast(NETWORK_COMMAND_PINGLIST) << static_cast(player_list.size()); for (auto& player : player_list) { *packet << player->Id << player->Ping; @@ -1737,7 +1737,7 @@ void Network::Server_Send_PINGLIST() void Network::Server_Send_SETDISCONNECTMSG(NetworkConnection& connection, const char* msg) { std::unique_ptr packet(NetworkPacket::Allocate()); - *packet << (uint32_t)NETWORK_COMMAND_SETDISCONNECTMSG; + *packet << static_cast(NETWORK_COMMAND_SETDISCONNECTMSG); packet->WriteString(msg); connection.QueuePacket(std::move(packet)); } @@ -1759,7 +1759,7 @@ json_t* Network::GetServerInfoAsJson() const void Network::Server_Send_GAMEINFO(NetworkConnection& connection) { std::unique_ptr packet(NetworkPacket::Allocate()); - *packet << (uint32_t)NETWORK_COMMAND_GAMEINFO; + *packet << static_cast(NETWORK_COMMAND_GAMEINFO); # ifndef DISABLE_HTTP json_t* obj = GetServerInfoAsJson(); @@ -1781,14 +1781,14 @@ void Network::Server_Send_GAMEINFO(NetworkConnection& connection) void Network::Server_Send_SHOWERROR(NetworkConnection& connection, rct_string_id title, rct_string_id message) { std::unique_ptr packet(NetworkPacket::Allocate()); - *packet << (uint32_t)NETWORK_COMMAND_SHOWERROR << title << message; + *packet << static_cast(NETWORK_COMMAND_SHOWERROR) << title << message; connection.QueuePacket(std::move(packet)); } void Network::Server_Send_GROUPLIST(NetworkConnection& connection) { std::unique_ptr packet(NetworkPacket::Allocate()); - *packet << (uint32_t)NETWORK_COMMAND_GROUPLIST << (uint8_t)group_list.size() << default_group; + *packet << static_cast(NETWORK_COMMAND_GROUPLIST) << static_cast(group_list.size()) << default_group; for (auto& group : group_list) { group->Write(*packet); @@ -1799,8 +1799,8 @@ void Network::Server_Send_GROUPLIST(NetworkConnection& connection) void Network::Server_Send_EVENT_PLAYER_JOINED(const char* playerName) { std::unique_ptr packet(NetworkPacket::Allocate()); - *packet << (uint32_t)NETWORK_COMMAND_EVENT; - *packet << (uint16_t)SERVER_EVENT_PLAYER_JOINED; + *packet << static_cast(NETWORK_COMMAND_EVENT); + *packet << static_cast(SERVER_EVENT_PLAYER_JOINED); packet->WriteString(playerName); SendPacketToClients(*packet); } @@ -1808,8 +1808,8 @@ void Network::Server_Send_EVENT_PLAYER_JOINED(const char* playerName) void Network::Server_Send_EVENT_PLAYER_DISCONNECTED(const char* playerName, const char* reason) { std::unique_ptr packet(NetworkPacket::Allocate()); - *packet << (uint32_t)NETWORK_COMMAND_EVENT; - *packet << (uint16_t)SERVER_EVENT_PLAYER_DISCONNECTED; + *packet << static_cast(NETWORK_COMMAND_EVENT); + *packet << static_cast(SERVER_EVENT_PLAYER_DISCONNECTED); packet->WriteString(playerName); packet->WriteString(reason); SendPacketToClients(*packet); @@ -2054,7 +2054,7 @@ void Network::ServerClientDisconnected(std::unique_ptr& conne auto res = GameActions::Execute(&pickupAction); } gNetwork.Server_Send_EVENT_PLAYER_DISCONNECTED( - (char*)connection_player->Name.c_str(), connection->GetLastDisconnectReason()); + const_cast(connection_player->Name.c_str()), connection->GetLastDisconnectReason()); // Log player disconnected event AppendServerLog(text); @@ -2212,7 +2212,7 @@ void Network::Client_Handle_TOKEN(NetworkConnection& connection, NetworkPacket& uint32_t challenge_size; packet >> challenge_size; - const char* challenge = (const char*)packet.Read(challenge_size); + const char* challenge = reinterpret_cast(packet.Read(challenge_size)); std::vector signature; const std::string pubkey = _key.PublicKeyString(); @@ -2256,7 +2256,7 @@ void Network::Server_Handle_REQUEST_GAMESTATE(NetworkConnection& connection, Net snapshots->SerialiseSnapshot(const_cast(*snapshot), ds); uint32_t bytesSent = 0; - uint32_t length = (uint32_t)snapshotMemory.GetLength(); + uint32_t length = static_cast(snapshotMemory.GetLength()); while (bytesSent < length) { uint32_t dataSize = CHUNK_SIZE; @@ -2266,8 +2266,8 @@ void Network::Server_Handle_REQUEST_GAMESTATE(NetworkConnection& connection, Net } std::unique_ptr gameStateChunk(NetworkPacket::Allocate()); - *gameStateChunk << (uint32_t)NETWORK_COMMAND_GAMESTATE << tick << length << bytesSent << dataSize; - gameStateChunk->Write((const uint8_t*)snapshotMemory.GetData() + bytesSent, dataSize); + *gameStateChunk << static_cast(NETWORK_COMMAND_GAMESTATE) << tick << length << bytesSent << dataSize; + gameStateChunk->Write(static_cast(snapshotMemory.GetData()) + bytesSent, dataSize); connection.QueuePacket(std::move(gameStateChunk)); @@ -2279,8 +2279,8 @@ void Network::Server_Handle_REQUEST_GAMESTATE(NetworkConnection& connection, Net void Network::Client_Handle_AUTH(NetworkConnection& connection, NetworkPacket& packet) { uint32_t auth_status; - packet >> auth_status >> (uint8_t&)player_id; - connection.AuthStatus = (NETWORK_AUTH)auth_status; + packet >> auth_status >> const_cast(player_id); + connection.AuthStatus = static_cast(auth_status); switch (connection.AuthStatus) { case NETWORK_AUTH_OK: @@ -2330,7 +2330,7 @@ void Network::Server_Client_Joined(const char* name, const std::string& keyhash, if (player) { char text[256]; - const char* player_name = (const char*)player->Name.c_str(); + const char* player_name = static_cast(player->Name.c_str()); format_string(text, 256, STR_MULTIPLAYER_PLAYER_HAS_JOINED_THE_GAME, &player_name); chat_history_add(text); @@ -2341,7 +2341,7 @@ void Network::Server_Client_Joined(const char* name, const std::string& keyhash, // Log player joining event std::string playerNameHash = player->Name + " (" + keyhash + ")"; - player_name = (const char*)playerNameHash.c_str(); + player_name = static_cast(playerNameHash.c_str()); format_string(text, 256, STR_MULTIPLAYER_PLAYER_HAS_JOINED_THE_GAME, &player_name); AppendServerLog(text); } @@ -2353,7 +2353,7 @@ void Network::Server_Handle_TOKEN(NetworkConnection& connection, [[maybe_unused] connection.Challenge.resize(token_size); for (int32_t i = 0; i < token_size; i++) { - connection.Challenge[i] = (uint8_t)(rand() & 0xff); + connection.Challenge[i] = static_cast(rand() & 0xff); } Server_Send_TOKEN(connection); } @@ -2374,7 +2374,7 @@ void Network::Client_Handle_OBJECTS(NetworkConnection& connection, NetworkPacket std::vector requested_objects; for (uint32_t i = 0; i < size; i++) { - const char* name = (const char*)packet.Read(8); + const char* name = reinterpret_cast(packet.Read(8)); // Required, as packet has no null terminators. std::string s(name, name + 8); uint32_t checksum, flags; @@ -2442,7 +2442,7 @@ void Network::Client_Handle_GAMESTATE(NetworkConnection& connection, NetworkPack char uniqueFileName[128] = {}; snprintf( uniqueFileName, sizeof(uniqueFileName), "desync_%llu_%u.txt", - (long long unsigned)platform_get_datetime_now_utc(), tick); + static_cast(platform_get_datetime_now_utc()), tick); std::string outputFile = Path::Combine(outputPath, uniqueFileName); @@ -2486,7 +2486,7 @@ void Network::Server_Handle_OBJECTS(NetworkConnection& connection, NetworkPacket auto& repo = GetContext()->GetObjectRepository(); for (uint32_t i = 0; i < size; i++) { - const char* name = (const char*)packet.Read(8); + const char* name = reinterpret_cast(packet.Read(8)); // This is required, as packet does not have null terminator std::string s(name, name + 8); log_verbose("Client requested object %s", s.c_str()); @@ -2501,7 +2501,7 @@ void Network::Server_Handle_OBJECTS(NetworkConnection& connection, NetworkPacket } } - const char* player_name = (const char*)connection.Player->Name.c_str(); + const char* player_name = static_cast(connection.Player->Name.c_str()); Server_Send_MAP(&connection); Server_Send_EVENT_PLAYER_JOINED(player_name); Server_Send_GROUPLIST(connection); @@ -2528,7 +2528,7 @@ void Network::Server_Handle_AUTH(NetworkConnection& connection, NetworkPacket& p std::vector signature; signature.resize(sigsize); - const uint8_t* signatureData = (const uint8_t*)packet.Read(sigsize); + const uint8_t* signatureData = packet.Read(sigsize); if (signatureData == nullptr) { throw std::runtime_error("Failed to read packet."); @@ -2596,7 +2596,7 @@ void Network::Server_Handle_AUTH(NetworkConnection& connection, NetworkPacket& p } } - if ((size_t)gConfigNetwork.maxplayers <= player_list.size()) + if (static_cast(gConfigNetwork.maxplayers) <= player_list.size()) { connection.AuthStatus = NETWORK_AUTH_FULL; } @@ -2618,7 +2618,7 @@ void Network::Client_Handle_MAP([[maybe_unused]] NetworkConnection& connection, { uint32_t size, offset; packet >> size >> offset; - int32_t chunksize = (int32_t)(packet.Size - packet.BytesRead); + int32_t chunksize = static_cast(packet.Size - packet.BytesRead); if (chunksize <= 0) { return; @@ -2660,7 +2660,7 @@ void Network::Client_Handle_MAP([[maybe_unused]] NetworkConnection& connection, uint8_t* data = &chunk_buffer[0]; size_t data_size = size; // zlib-compressed - if (strcmp("open2_sv6_zlib", (char*)&chunk_buffer[0]) == 0) + if (strcmp("open2_sv6_zlib", reinterpret_cast(&chunk_buffer[0])) == 0) { log_verbose("Received zlib-compressed sv6 map"); has_to_free = true; @@ -3112,7 +3112,7 @@ void Network::Client_Send_GAMEINFO() { log_verbose("requesting gameinfo"); std::unique_ptr packet(NetworkPacket::Allocate()); - *packet << (uint32_t)NETWORK_COMMAND_GAMEINFO; + *packet << static_cast(NETWORK_COMMAND_GAMEINFO); _serverConnection->QueuePacket(std::move(packet)); } @@ -3238,12 +3238,12 @@ uint8_t network_get_current_player_id() int32_t network_get_num_players() { - return (int32_t)gNetwork.player_list.size(); + return static_cast(gNetwork.player_list.size()); } const char* network_get_player_name(uint32_t index) { - return (const char*)gNetwork.player_list[index]->Name.c_str(); + return static_cast(gNetwork.player_list[index]->Name.c_str()); } uint32_t network_get_player_flags(uint32_t index) @@ -3311,7 +3311,7 @@ int32_t network_get_player_index(uint32_t id) { return -1; } - return (int32_t)(gNetwork.GetPlayerIteratorByID(id) - gNetwork.player_list.begin()); + return static_cast(gNetwork.GetPlayerIteratorByID(id) - gNetwork.player_list.begin()); } uint8_t network_get_player_group(uint32_t index) @@ -3331,7 +3331,7 @@ int32_t network_get_group_index(uint8_t id) { return -1; } - return (int32_t)(gNetwork.GetGroupIteratorByID(id) - gNetwork.group_list.begin()); + return static_cast(gNetwork.GetGroupIteratorByID(id) - gNetwork.group_list.begin()); } uint8_t network_get_group_id(uint32_t index) @@ -3341,7 +3341,7 @@ uint8_t network_get_group_id(uint32_t index) int32_t network_get_num_groups() { - return (int32_t)gNetwork.group_list.size(); + return static_cast(gNetwork.group_list.size()); } const char* network_get_group_name(uint32_t index) @@ -3604,7 +3604,7 @@ uint8_t network_get_default_group() int32_t network_get_num_actions() { - return (int32_t)NetworkActions::Actions.size(); + return static_cast(NetworkActions::Actions.size()); } rct_string_id network_get_action_name_string_id(uint32_t index) diff --git a/src/openrct2/network/NetworkAction.cpp b/src/openrct2/network/NetworkAction.cpp index 368b506f96..9ea60e6076 100644 --- a/src/openrct2/network/NetworkAction.cpp +++ b/src/openrct2/network/NetworkAction.cpp @@ -30,7 +30,7 @@ int32_t NetworkActions::FindCommand(int32_t command) }); if (it != Actions.end()) { - return (int32_t)(it - Actions.begin()); + return static_cast(it - Actions.begin()); } return -1; } @@ -42,7 +42,7 @@ int32_t NetworkActions::FindCommandByPermissionName(const std::string& permissio }); if (it != Actions.end()) { - return (int32_t)(it - Actions.begin()); + return static_cast(it - Actions.begin()); } return -1; } diff --git a/src/openrct2/network/NetworkConnection.cpp b/src/openrct2/network/NetworkConnection.cpp index da9ab8d6cd..6e9ebe0652 100644 --- a/src/openrct2/network/NetworkConnection.cpp +++ b/src/openrct2/network/NetworkConnection.cpp @@ -34,7 +34,7 @@ int32_t NetworkConnection::ReadPacket() if (InboundPacket.BytesTransferred < sizeof(InboundPacket.Size)) { // read packet size - void* buffer = &((char*)&InboundPacket.Size)[InboundPacket.BytesTransferred]; + void* buffer = &(reinterpret_cast(&InboundPacket.Size))[InboundPacket.BytesTransferred]; size_t bufferLength = sizeof(InboundPacket.Size) - InboundPacket.BytesTransferred; size_t readBytes; NETWORK_READPACKET status = Socket->ReceiveData(buffer, bufferLength, &readBytes); @@ -87,7 +87,7 @@ bool NetworkConnection::SendPacket(NetworkPacket& packet) uint16_t sizen = Convert::HostToNetwork(packet.Size); std::vector tosend; tosend.reserve(sizeof(sizen) + packet.Size); - tosend.insert(tosend.end(), (uint8_t*)&sizen, (uint8_t*)&sizen + sizeof(sizen)); + tosend.insert(tosend.end(), reinterpret_cast(&sizen), reinterpret_cast(&sizen) + sizeof(sizen)); tosend.insert(tosend.end(), packet.Data->begin(), packet.Data->end()); const void* buffer = &tosend[packet.BytesTransferred]; @@ -110,7 +110,7 @@ void NetworkConnection::QueuePacket(std::unique_ptr packet, bool { if (AuthStatus == NETWORK_AUTH_OK || !packet->CommandRequiresAuth()) { - packet->Size = (uint16_t)packet->Data->size(); + packet->Size = static_cast(packet->Data->size()); if (front) { // If the first packet was already partially sent add new packet to second position @@ -186,7 +186,7 @@ void NetworkConnection::SetLastDisconnectReason(const rct_string_id string_id, v void NetworkConnection::RecordPacketStats(const NetworkPacket& packet, bool sending) { - uint32_t packetSize = (uint32_t)packet.BytesTransferred; + uint32_t packetSize = static_cast(packet.BytesTransferred); uint32_t trafficGroup = NETWORK_STATISTICS_GROUP_BASE; switch (packet.GetCommand()) diff --git a/src/openrct2/network/NetworkGroup.cpp b/src/openrct2/network/NetworkGroup.cpp index 318e6f2482..f4aa0f5ccb 100644 --- a/src/openrct2/network/NetworkGroup.cpp +++ b/src/openrct2/network/NetworkGroup.cpp @@ -26,7 +26,7 @@ NetworkGroup NetworkGroup::FromJson(const json_t* json) throw std::runtime_error("Missing group data"); } - group.Id = (uint8_t)json_integer_value(jsonId); + group.Id = static_cast(json_integer_value(jsonId)); group._name = std::string(json_string_value(jsonName)); std::fill(group.ActionsAllowed.begin(), group.ActionsAllowed.end(), 0); diff --git a/src/openrct2/network/NetworkKey.cpp b/src/openrct2/network/NetworkKey.cpp index 3312dc5284..91b20161a6 100644 --- a/src/openrct2/network/NetworkKey.cpp +++ b/src/openrct2/network/NetworkKey.cpp @@ -48,8 +48,8 @@ bool NetworkKey::LoadPrivate(IStream* stream) { Guard::ArgumentNotNull(stream); - size_t size = (size_t)stream->GetLength(); - if (size == (size_t)-1) + size_t size = static_cast(stream->GetLength()); + if (size == static_cast(-1)) { log_error("unknown size, refusing to load key"); return false; @@ -80,8 +80,8 @@ bool NetworkKey::LoadPublic(IStream* stream) { Guard::ArgumentNotNull(stream); - size_t size = (size_t)stream->GetLength(); - if (size == (size_t)-1) + size_t size = static_cast(stream->GetLength()); + if (size == static_cast(-1)) { log_error("unknown size, refusing to load key"); return false; diff --git a/src/openrct2/network/NetworkPacket.cpp b/src/openrct2/network/NetworkPacket.cpp index f613a699fa..2fc388e0b2 100644 --- a/src/openrct2/network/NetworkPacket.cpp +++ b/src/openrct2/network/NetworkPacket.cpp @@ -34,7 +34,7 @@ int32_t NetworkPacket::GetCommand() const { if (Data->size() >= sizeof(uint32_t)) { - return ByteSwapBE(*(uint32_t*)(&(*Data)[0])); + return ByteSwapBE(*reinterpret_cast(&(*Data)[0])); } else { @@ -90,7 +90,7 @@ const uint8_t* NetworkPacket::Read(size_t size) const utf8* NetworkPacket::ReadString() { - char* str = (char*)&GetData()[BytesRead]; + char* str = reinterpret_cast(&GetData()[BytesRead]); char* strend = str; while (BytesRead < Size && *strend != 0) { diff --git a/src/openrct2/network/NetworkPacket.h b/src/openrct2/network/NetworkPacket.h index 6b9352c899..bd05ea34fa 100644 --- a/src/openrct2/network/NetworkPacket.h +++ b/src/openrct2/network/NetworkPacket.h @@ -65,7 +65,7 @@ public: NetworkPacket& operator<<(DataSerialiser& data) { - Write((const uint8_t*)data.GetStream().GetData(), data.GetStream().GetLength()); + Write(static_cast(data.GetStream().GetData()), data.GetStream().GetLength()); return *this; } }; diff --git a/src/openrct2/network/NetworkPlayer.cpp b/src/openrct2/network/NetworkPlayer.cpp index ccaee8f41c..fe05742f37 100644 --- a/src/openrct2/network/NetworkPlayer.cpp +++ b/src/openrct2/network/NetworkPlayer.cpp @@ -19,7 +19,7 @@ void NetworkPlayer::SetName(const std::string& name) { // 36 == 31 + strlen(" #255"); Name = name.substr(0, 36); - utf8_remove_format_codes((utf8*)Name.data(), false); + utf8_remove_format_codes(static_cast(Name.data()), false); } void NetworkPlayer::Read(NetworkPacket& packet) @@ -32,7 +32,7 @@ void NetworkPlayer::Read(NetworkPacket& packet) void NetworkPlayer::Write(NetworkPacket& packet) { - packet.WriteString((const char*)Name.c_str()); + packet.WriteString(static_cast(Name.c_str())); packet << Id << Flags << Group << LastAction << LastActionCoord.x << LastActionCoord.y << LastActionCoord.z << MoneySpent << CommandsRan; } diff --git a/src/openrct2/network/NetworkServerAdvertiser.cpp b/src/openrct2/network/NetworkServerAdvertiser.cpp index 9086c06196..78773231c9 100644 --- a/src/openrct2/network/NetworkServerAdvertiser.cpp +++ b/src/openrct2/network/NetworkServerAdvertiser.cpp @@ -227,7 +227,7 @@ private: json_t* jsonStatus = json_object_get(jsonRoot, "status"); if (json_is_integer(jsonStatus)) { - int32_t status = (int32_t)json_integer_value(jsonStatus); + int32_t status = static_cast(json_integer_value(jsonStatus)); if (status == MASTER_SERVER_STATUS_OK) { json_t* jsonToken = json_object_get(jsonRoot, "token"); @@ -264,7 +264,7 @@ private: json_t* jsonStatus = json_object_get(jsonRoot, "status"); if (json_is_integer(jsonStatus)) { - int32_t status = (int32_t)json_integer_value(jsonStatus); + int32_t status = static_cast(json_integer_value(jsonStatus)); if (status == MASTER_SERVER_STATUS_OK) { // Master server has successfully updated our server status diff --git a/src/openrct2/network/NetworkUser.cpp b/src/openrct2/network/NetworkUser.cpp index 5540abf698..9e0cb664f6 100644 --- a/src/openrct2/network/NetworkUser.cpp +++ b/src/openrct2/network/NetworkUser.cpp @@ -35,7 +35,7 @@ NetworkUser* NetworkUser::FromJson(json_t* json) user->Name = std::string(name); if (!json_is_null(jsonGroupId)) { - user->GroupId = (uint8_t)json_integer_value(jsonGroupId); + user->GroupId = static_cast(json_integer_value(jsonGroupId)); } user->Remove = false; return user; diff --git a/src/openrct2/network/ServerList.cpp b/src/openrct2/network/ServerList.cpp index f57811fa8f..b24a95f257 100644 --- a/src/openrct2/network/ServerList.cpp +++ b/src/openrct2/network/ServerList.cpp @@ -97,13 +97,14 @@ std::optional ServerListEntry::FromJson(const json_t* server) else { ServerListEntry entry; - entry.address = String::StdFormat("%s:%d", json_string_value(addressIp), (int32_t)json_integer_value(port)); + entry.address = String::StdFormat( + "%s:%d", json_string_value(addressIp), static_cast(json_integer_value(port))); entry.name = (name == nullptr ? "" : json_string_value(name)); entry.description = (description == nullptr ? "" : json_string_value(description)); entry.version = json_string_value(version); entry.requiresPassword = json_is_true(requiresPassword); - entry.players = (uint8_t)json_integer_value(players); - entry.maxplayers = (uint8_t)json_integer_value(maxPlayers); + entry.players = static_cast(json_integer_value(players)); + entry.maxplayers = static_cast(json_integer_value(maxPlayers)); return entry; } } @@ -219,7 +220,7 @@ bool ServerList::WriteFavourites(const std::vector& entries) co try { auto fs = FileStream(path, FILE_MODE_WRITE); - fs.WriteValue((uint32_t)entries.size()); + fs.WriteValue(static_cast(entries.size())); for (const auto& entry : entries) { fs.WriteString(entry.address); @@ -361,7 +362,7 @@ std::future> ServerList::FetchOnlineServerListAsync throw MasterServerException(STR_SERVER_LIST_INVALID_RESPONSE_JSON_NUMBER); } - auto status = (int32_t)json_integer_value(jsonStatus); + auto status = static_cast(json_integer_value(jsonStatus)); if (status != 200) { throw MasterServerException(STR_SERVER_LIST_MASTER_SERVER_FAILED); diff --git a/src/openrct2/network/Socket.cpp b/src/openrct2/network/Socket.cpp index 6ecda08baf..b4a7f0c08d 100644 --- a/src/openrct2/network/Socket.cpp +++ b/src/openrct2/network/Socket.cpp @@ -156,7 +156,7 @@ protected: static bool SetOption(SOCKET socket, int32_t a, int32_t b, bool value) { int32_t ivalue = value ? 1 : 0; - return setsockopt(socket, a, b, (const char*)&ivalue, sizeof(ivalue)) == 0; + return setsockopt(socket, a, b, reinterpret_cast(&ivalue), sizeof(ivalue)) == 0; } private: @@ -187,7 +187,7 @@ private: else { std::memcpy(ss, result->ai_addr, result->ai_addrlen); - *ss_len = (socklen_t)result->ai_addrlen; + *ss_len = static_cast(result->ai_addrlen); freeaddrinfo(result); return true; } @@ -255,13 +255,13 @@ public: // Turn off IPV6_V6ONLY so we can accept both v4 and v6 connections int32_t value = 0; - if (setsockopt(_socket, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&value, sizeof(value)) != 0) + if (setsockopt(_socket, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast(&value), sizeof(value)) != 0) { log_error("IPV6_V6ONLY failed. %d", LAST_SOCKET_ERROR()); } value = 1; - if (setsockopt(_socket, SOL_SOCKET, SO_REUSEADDR, (const char*)&value, sizeof(value)) != 0) + if (setsockopt(_socket, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast(&value), sizeof(value)) != 0) { log_error("SO_REUSEADDR failed. %d", LAST_SOCKET_ERROR()); } @@ -269,7 +269,7 @@ public: try { // Bind to address:port and listen - if (bind(_socket, (sockaddr*)&ss, ss_len) != 0) + if (bind(_socket, reinterpret_cast(&ss), ss_len) != 0) { throw SocketException("Unable to bind to socket."); } @@ -305,7 +305,7 @@ public: socklen_t client_len = sizeof(struct sockaddr_storage); std::unique_ptr tcpSocket; - SOCKET socket = accept(_socket, (struct sockaddr*)&client_addr, &client_len); + SOCKET socket = accept(_socket, reinterpret_cast(&client_addr), &client_len); if (socket == INVALID_SOCKET) { if (LAST_SOCKET_ERROR() != EWOULDBLOCK) @@ -324,7 +324,7 @@ public: { char hostName[NI_MAXHOST]; int32_t rc = getnameinfo( - (struct sockaddr*)&client_addr, client_len, hostName, sizeof(hostName), nullptr, 0, + reinterpret_cast(&client_addr), client_len, hostName, sizeof(hostName), nullptr, 0, NI_NUMERICHOST | NI_NUMERICSERV); SetOption(socket, IPPROTO_TCP, TCP_NODELAY, true); if (rc == 0) @@ -373,7 +373,7 @@ public: } // Connect - int32_t connectResult = connect(_socket, (sockaddr*)&ss, ss_len); + int32_t connectResult = connect(_socket, reinterpret_cast(&ss), ss_len); if (connectResult != SOCKET_ERROR || (LAST_SOCKET_ERROR() != EINPROGRESS && LAST_SOCKET_ERROR() != EWOULDBLOCK)) { throw SocketException("Failed to connect."); @@ -383,7 +383,7 @@ public: int32_t error = 0; socklen_t len = sizeof(error); - if (getsockopt(_socket, SOL_SOCKET, SO_ERROR, (char*)&error, &len) != 0) + if (getsockopt(_socket, SOL_SOCKET, SO_ERROR, reinterpret_cast(&error), &len) != 0) { throw SocketException("getsockopt failed with error: " + std::to_string(LAST_SOCKET_ERROR())); } @@ -406,11 +406,11 @@ public: timeval timeout{}; timeout.tv_sec = 0; timeout.tv_usec = 0; - if (select((int32_t)(_socket + 1), nullptr, &writeFD, nullptr, &timeout) > 0) + if (select(static_cast(_socket + 1), nullptr, &writeFD, nullptr, &timeout) > 0) { error = 0; len = sizeof(error); - if (getsockopt(_socket, SOL_SOCKET, SO_ERROR, (char*)&error, &len) != 0) + if (getsockopt(_socket, SOL_SOCKET, SO_ERROR, reinterpret_cast(&error), &len) != 0) { throw SocketException("getsockopt failed with error: " + std::to_string(LAST_SOCKET_ERROR())); } @@ -476,9 +476,9 @@ public: size_t totalSent = 0; do { - const char* bufferStart = (const char*)buffer + totalSent; + const char* bufferStart = static_cast(buffer) + totalSent; size_t remainingSize = size - totalSent; - int32_t sentBytes = send(_socket, bufferStart, (int32_t)remainingSize, FLAG_NO_PIPE); + int32_t sentBytes = send(_socket, bufferStart, static_cast(remainingSize), FLAG_NO_PIPE); if (sentBytes == SOCKET_ERROR) { return totalSent; @@ -495,7 +495,7 @@ public: throw std::runtime_error("Socket not connected."); } - int32_t readBytes = recv(_socket, (char*)buffer, (int32_t)size, 0); + int32_t readBytes = recv(_socket, static_cast(buffer), static_cast(size), 0); if (readBytes == 0) { *sizeReceived = 0; @@ -618,7 +618,7 @@ public: try { // Bind to address:port and listen - if (bind(_socket, (sockaddr*)&ss, ss_len) != 0) + if (bind(_socket, reinterpret_cast(&ss), ss_len) != 0) { throw SocketException("Unable to bind to socket."); } @@ -641,7 +641,7 @@ public: { throw SocketException("Unable to resolve address."); } - NetworkEndpoint endpoint((const sockaddr*)&ss, ss_len); + NetworkEndpoint endpoint(reinterpret_cast(&ss), ss_len); return SendData(endpoint, buffer, size); } @@ -668,9 +668,11 @@ public: size_t totalSent = 0; do { - const char* bufferStart = (const char*)buffer + totalSent; + const char* bufferStart = static_cast(buffer) + totalSent; size_t remainingSize = size - totalSent; - int32_t sentBytes = sendto(_socket, bufferStart, (int32_t)remainingSize, FLAG_NO_PIPE, (const sockaddr*)ss, ss_len); + int32_t sentBytes = sendto( + _socket, bufferStart, static_cast(remainingSize), FLAG_NO_PIPE, static_cast(ss), + ss_len); if (sentBytes == SOCKET_ERROR) { return totalSent; @@ -690,7 +692,9 @@ public: senderAddrLen = _endpoint.GetAddressLen(); std::memcpy(&senderAddr, &_endpoint.GetAddress(), senderAddrLen); } - auto readBytes = recvfrom(_socket, (char*)buffer, (int32_t)size, 0, (sockaddr*)&senderAddr, &senderAddrLen); + auto readBytes = recvfrom( + _socket, static_cast(buffer), static_cast(size), 0, reinterpret_cast(&senderAddr), + &senderAddrLen); if (readBytes <= 0) { *sizeReceived = 0; @@ -701,7 +705,7 @@ public: *sizeReceived = readBytes; if (sender != nullptr) { - *sender = std::make_unique((sockaddr*)&senderAddr, senderAddrLen); + *sender = std::make_unique(reinterpret_cast(&senderAddr), senderAddrLen); } return NETWORK_READPACKET_SUCCESS; } @@ -886,7 +890,7 @@ std::vector> GetBroadcastAddresses() const char* buf_end = buf + ifconfx.ifc_len; for (const char* p = buf; p < buf_end;) { - auto req = (const ifreq*)p; + auto req = reinterpret_cast(p); if (req->ifr_addr.sa_family == AF_INET) { ifreq r; diff --git a/src/openrct2/network/Twitch.cpp b/src/openrct2/network/Twitch.cpp index 32457a3087..4b71686881 100644 --- a/src/openrct2/network/Twitch.cpp +++ b/src/openrct2/network/Twitch.cpp @@ -492,7 +492,7 @@ namespace Twitch { // Rename peep and add flags auto memLen = std::strlen(member->Name) + 1; - peep->name = (char*)std::malloc(memLen); + peep->name = static_cast(std::malloc(memLen)); if (peep->name != nullptr) { std::memcpy(peep->name, member->Name, memLen); @@ -522,7 +522,7 @@ namespace Twitch { str++; } - return (char*)str; + return const_cast(str); } static void ParseChatMessage(const char* message) @@ -556,7 +556,7 @@ namespace Twitch if (gConfigTwitch.enable_news) { utf8 buffer[256]; - buffer[0] = (utf8)(uint8_t)FORMAT_TOPAZ; + buffer[0] = static_cast(static_cast(FORMAT_TOPAZ)); safe_strcpy(buffer + 1, message, sizeof(buffer) - 1); utf8_remove_formatting(buffer, false); diff --git a/src/openrct2/object/ImageTable.cpp b/src/openrct2/object/ImageTable.cpp index adc9fa62bc..1331325fe9 100644 --- a/src/openrct2/object/ImageTable.cpp +++ b/src/openrct2/object/ImageTable.cpp @@ -45,10 +45,10 @@ void ImageTable::Read(IReadObjectContext* context, IStream* stream) if (remainingBytes > imageDataSize) { context->LogWarning(OBJECT_ERROR_BAD_IMAGE_TABLE, "Image table size longer than expected."); - imageDataSize = (uint32_t)remainingBytes; + imageDataSize = static_cast(remainingBytes); } - auto dataSize = (size_t)imageDataSize; + auto dataSize = static_cast(imageDataSize); auto data = std::make_unique(dataSize); if (data == nullptr) { @@ -63,7 +63,7 @@ void ImageTable::Read(IReadObjectContext* context, IStream* stream) { rct_g1_element g1Element; - uintptr_t imageDataOffset = (uintptr_t)stream->ReadValue(); + uintptr_t imageDataOffset = static_cast(stream->ReadValue()); g1Element.offset = (uint8_t*)(imageDataBase + imageDataOffset); g1Element.width = stream->ReadValue(); @@ -77,7 +77,7 @@ void ImageTable::Read(IReadObjectContext* context, IStream* stream) } // Read g1 element data - size_t readBytes = (size_t)stream->TryRead(data.get(), dataSize); + size_t readBytes = static_cast(stream->TryRead(data.get(), dataSize)); // If data is shorter than expected (some custom objects are unfortunately like that) size_t unreadBytes = dataSize - readBytes; diff --git a/src/openrct2/object/ImageTable.h b/src/openrct2/object/ImageTable.h index 73065f51f0..296b560fc3 100644 --- a/src/openrct2/object/ImageTable.h +++ b/src/openrct2/object/ImageTable.h @@ -37,7 +37,7 @@ public: } uint32_t GetCount() const { - return (uint32_t)_entries.size(); + return static_cast(_entries.size()); } void AddImage(const rct_g1_element* g1); }; diff --git a/src/openrct2/object/ObjectFactory.cpp b/src/openrct2/object/ObjectFactory.cpp index 0b86ba2048..41e591df0d 100644 --- a/src/openrct2/object/ObjectFactory.cpp +++ b/src/openrct2/object/ObjectFactory.cpp @@ -359,7 +359,7 @@ namespace ObjectFactory } json_error_t jsonLoadError; - auto jRoot = json_loadb((const char*)jsonBytes.data(), jsonBytes.size(), 0, &jsonLoadError); + auto jRoot = json_loadb(reinterpret_cast(jsonBytes.data()), jsonBytes.size(), 0, &jsonLoadError); if (jRoot == nullptr) { throw JsonException(&jsonLoadError); diff --git a/src/openrct2/object/ObjectJsonHelpers.cpp b/src/openrct2/object/ObjectJsonHelpers.cpp index cb14ae7a72..6b12cf4a05 100644 --- a/src/openrct2/object/ObjectJsonHelpers.cpp +++ b/src/openrct2/object/ObjectJsonHelpers.cpp @@ -72,7 +72,7 @@ namespace ObjectJsonHelpers if ((g1.flags & G1_FLAG_HAS_ZOOM_SPRITE) && g1.zoomed_offset != 0) { // Fetch image for next zoom level - next_zoom = std::make_unique((uint32_t)(idx - g1.zoomed_offset), getter); + next_zoom = std::make_unique(static_cast(idx - g1.zoomed_offset), getter); if (!next_zoom->HasData()) { next_zoom = nullptr; @@ -317,7 +317,7 @@ namespace ObjectJsonHelpers if (obj != nullptr) { auto& imgTable = static_cast(obj)->GetImageTable(); - auto numImages = (int32_t)imgTable.GetCount(); + auto numImages = static_cast(imgTable.GetCount()); auto images = imgTable.GetImages(); size_t placeHoldersAdded = 0; for (auto i : range) @@ -325,7 +325,7 @@ namespace ObjectJsonHelpers if (i >= 0 && i < numImages) { result.push_back(std::make_unique( - (uint32_t)(i), [images](uint32_t idx) -> const rct_g1_element* { return &images[idx]; })); + static_cast(i), [images](uint32_t idx) -> const rct_g1_element* { return &images[idx]; })); } else { @@ -371,7 +371,7 @@ namespace ObjectJsonHelpers for (auto i : range) { result.push_back(std::make_unique( - (uint32_t)(SPR_CSG_BEGIN + i), + static_cast(SPR_CSG_BEGIN + i), [](uint32_t idx) -> const rct_g1_element* { return gfx_get_g1_element(idx); })); } } @@ -384,8 +384,10 @@ namespace ObjectJsonHelpers { for (auto i : range) { - result.push_back(std::make_unique( - (uint32_t)(i), [](uint32_t idx) -> const rct_g1_element* { return gfx_get_g1_element(idx); })); + result.push_back( + std::make_unique(static_cast(i), [](uint32_t idx) -> const rct_g1_element* { + return gfx_get_g1_element(idx); + })); } } } @@ -437,7 +439,7 @@ namespace ObjectJsonHelpers auto flags = ImageImporter::IMPORT_FLAGS::NONE; if (!raw) { - flags = (ImageImporter::IMPORT_FLAGS)(flags | ImageImporter::IMPORT_FLAGS::RLE); + flags = static_cast(flags | ImageImporter::IMPORT_FLAGS::RLE); } auto imageData = context->GetData(path); auto image = Imaging::ReadFromBuffer(imageData, IMAGE_FORMAT::PNG_32); @@ -543,8 +545,8 @@ namespace ObjectJsonHelpers img = img->next_zoom.get(); // Set old image zoom offset to zoom image which we are about to add - auto g1a = (rct_g1_element*)(&imageTable.GetImages()[tableIndex]); - g1a->zoomed_offset = (int32_t)tableIndex - (int32_t)imageTable.GetCount(); + auto g1a = const_cast(&imageTable.GetImages()[tableIndex]); + g1a->zoomed_offset = static_cast(tableIndex) - static_cast(imageTable.GetCount()); while (img != nullptr) { diff --git a/src/openrct2/object/ObjectList.cpp b/src/openrct2/object/ObjectList.cpp index 451ce98864..157f1ea9b3 100644 --- a/src/openrct2/object/ObjectList.cpp +++ b/src/openrct2/object/ObjectList.cpp @@ -157,7 +157,7 @@ void* get_loaded_object_chunk(size_t index) void object_entry_get_name_fixed(utf8* buffer, size_t bufferSize, const rct_object_entry* entry) { - bufferSize = std::min((size_t)DAT_NAME_LENGTH + 1, bufferSize); + bufferSize = std::min(static_cast(DAT_NAME_LENGTH) + 1, bufferSize); std::memcpy(buffer, entry->name, bufferSize - 1); buffer[bufferSize - 1] = 0; } diff --git a/src/openrct2/object/ObjectManager.cpp b/src/openrct2/object/ObjectManager.cpp index 51dd835f95..0b7548258a 100644 --- a/src/openrct2/object/ObjectManager.cpp +++ b/src/openrct2/object/ObjectManager.cpp @@ -67,7 +67,7 @@ public: Object* GetLoadedObject(int32_t objectType, size_t index) override { - if (index >= (size_t)object_entry_group_counts[objectType]) + if (index >= static_cast(object_entry_group_counts[objectType])) { #ifdef DEBUG log_warning("Object index %u exceeds maximum for type %d.", index, objectType); @@ -117,7 +117,7 @@ public: loadedObject = GetOrLoadObject(ori); if (loadedObject != nullptr) { - if (_loadedObjects.size() <= (size_t)slot) + if (_loadedObjects.size() <= static_cast(slot)) { _loadedObjects.resize(slot + 1); } @@ -320,11 +320,11 @@ private: if (_loadedObjects.size() <= i) { _loadedObjects.resize(i + 1); - return (int32_t)i; + return static_cast(i); } else if (_loadedObjects[i] == nullptr) { - return (int32_t)i; + return static_cast(i); } } return -1; @@ -423,23 +423,23 @@ private: switch (loadedObject->GetObjectType()) { case OBJECT_TYPE_SMALL_SCENERY: - sceneryEntry = (rct_scenery_entry*)loadedObject->GetLegacyData(); + sceneryEntry = static_cast(loadedObject->GetLegacyData()); sceneryEntry->small_scenery.scenery_tab_id = GetPrimarySceneryGroupEntryIndex(loadedObject); break; case OBJECT_TYPE_LARGE_SCENERY: - sceneryEntry = (rct_scenery_entry*)loadedObject->GetLegacyData(); + sceneryEntry = static_cast(loadedObject->GetLegacyData()); sceneryEntry->large_scenery.scenery_tab_id = GetPrimarySceneryGroupEntryIndex(loadedObject); break; case OBJECT_TYPE_WALLS: - sceneryEntry = (rct_scenery_entry*)loadedObject->GetLegacyData(); + sceneryEntry = static_cast(loadedObject->GetLegacyData()); sceneryEntry->wall.scenery_tab_id = GetPrimarySceneryGroupEntryIndex(loadedObject); break; case OBJECT_TYPE_BANNERS: - sceneryEntry = (rct_scenery_entry*)loadedObject->GetLegacyData(); + sceneryEntry = static_cast(loadedObject->GetLegacyData()); sceneryEntry->banner.scenery_tab_id = GetPrimarySceneryGroupEntryIndex(loadedObject); break; case OBJECT_TYPE_PATH_BITS: - sceneryEntry = (rct_scenery_entry*)loadedObject->GetLegacyData(); + sceneryEntry = static_cast(loadedObject->GetLegacyData()); sceneryEntry->path_bit.scenery_tab_id = GetPrimarySceneryGroupEntryIndex(loadedObject); break; case OBJECT_TYPE_SCENERY_GROUP: @@ -708,7 +708,7 @@ private: { result += object_entry_group_counts[i]; } - result += (int32_t)entryIndex; + result += static_cast(entryIndex); return result; } }; diff --git a/src/openrct2/object/ObjectRepository.cpp b/src/openrct2/object/ObjectRepository.cpp index 2d3e77bc5e..808e5cc2c4 100644 --- a/src/openrct2/object/ObjectRepository.cpp +++ b/src/openrct2/object/ObjectRepository.cpp @@ -128,7 +128,7 @@ protected: stream->WriteValue(item.ObjectEntry); stream->WriteString(item.Path); stream->WriteString(item.Name); - uint8_t sourceLength = (uint8_t)item.Sources.size(); + uint8_t sourceLength = static_cast(item.Sources.size()); stream->WriteValue(sourceLength); for (auto source : item.Sources) { @@ -150,7 +150,7 @@ protected: stream->WriteValue(item.RideInfo.RideGroupIndex); break; case OBJECT_TYPE_SCENERY_GROUP: - stream->WriteValue((uint16_t)item.SceneryGroupInfo.Entries.size()); + stream->WriteValue(static_cast(item.SceneryGroupInfo.Entries.size())); for (const auto& entry : item.SceneryGroupInfo.Entries) { stream->WriteValue(entry); @@ -488,8 +488,8 @@ private: size_t newDataSize = dataSize + extraBytesCount; uint8_t* newData = Memory::Allocate(newDataSize); uint8_t* newDataSaltOffset = newData + dataSize; - std::copy_n((const uint8_t*)data, dataSize, newData); - std::copy_n((const uint8_t*)extraBytes, extraBytesCount, newDataSaltOffset); + std::copy_n(static_cast(data), dataSize, newData); + std::copy_n(static_cast(extraBytes), extraBytesCount, newDataSaltOffset); try { @@ -523,7 +523,7 @@ private: uint8_t objectType = entry->GetType(); sawyercoding_chunk_header chunkHeader; chunkHeader.encoding = object_entry_group_encoding[objectType]; - chunkHeader.length = (uint32_t)dataSize; + chunkHeader.length = static_cast(dataSize); uint8_t* encodedDataBuffer = Memory::Allocate(0x600000); size_t encodedDataSize = sawyercoding_write_chunk_buffer(encodedDataBuffer, (uint8_t*)data, chunkHeader); @@ -815,5 +815,5 @@ int32_t object_calculate_checksum(const rct_object_entry* entry, const void* dat checksum = rol32(checksum, 11); } - return (int32_t)checksum; + return static_cast(checksum); } diff --git a/src/openrct2/object/ObjectRepository.h b/src/openrct2/object/ObjectRepository.h index a439a8a8ec..8554ac2ff1 100644 --- a/src/openrct2/object/ObjectRepository.h +++ b/src/openrct2/object/ObjectRepository.h @@ -55,7 +55,7 @@ struct ObjectRepositoryItem if (Sources.empty()) return OBJECT_SOURCE_CUSTOM; else - return (OBJECT_SOURCE_GAME)Sources[0]; + return static_cast(Sources[0]); } }; diff --git a/src/openrct2/object/RideObject.cpp b/src/openrct2/object/RideObject.cpp index 9ed45b9ae4..e450a73ef2 100644 --- a/src/openrct2/object/RideObject.cpp +++ b/src/openrct2/object/RideObject.cpp @@ -1051,7 +1051,7 @@ uint8_t RideObject::ParseRideType(const std::string& s) { "lim_launched_rc", RIDE_TYPE_LIM_LAUNCHED_ROLLER_COASTER }, }; auto result = LookupTable.find(s); - return (result != LookupTable.end()) ? result->second : (uint8_t)RIDE_TYPE_NULL; + return (result != LookupTable.end()) ? result->second : static_cast(RIDE_TYPE_NULL); } uint8_t RideObject::ParseRideCategory(const std::string& s) @@ -1065,7 +1065,7 @@ uint8_t RideObject::ParseRideCategory(const std::string& s) { "stall", RIDE_CATEGORY_SHOP }, }; auto result = LookupTable.find(s); - return (result != LookupTable.end()) ? result->second : (uint8_t)RIDE_CATEGORY_TRANSPORT; + return (result != LookupTable.end()) ? result->second : static_cast(RIDE_CATEGORY_TRANSPORT); } uint8_t RideObject::ParseShopItem(const std::string& s) @@ -1110,5 +1110,5 @@ uint8_t RideObject::ParseShopItem(const std::string& s) { "sunglasses", SHOP_ITEM_SUNGLASSES }, }; auto result = LookupTable.find(s); - return (result != LookupTable.end()) ? result->second : (uint8_t)SHOP_ITEM_NONE; + return (result != LookupTable.end()) ? result->second : static_cast(SHOP_ITEM_NONE); } diff --git a/src/openrct2/object/StringTable.cpp b/src/openrct2/object/StringTable.cpp index 61f89ccc44..e6c2ca6138 100644 --- a/src/openrct2/object/StringTable.cpp +++ b/src/openrct2/object/StringTable.cpp @@ -39,7 +39,7 @@ static bool StringIsBlank(const utf8* str) { for (auto ch = str; *ch != '\0'; ch++) { - if (!isblank((uint8_t)*ch)) + if (!isblank(static_cast(*ch))) { return false; } @@ -52,10 +52,10 @@ void StringTable::Read(IReadObjectContext* context, IStream* stream, uint8_t id) try { RCT2LanguageId rct2LanguageId; - while ((rct2LanguageId = (RCT2LanguageId)stream->ReadValue()) != RCT2_LANGUAGE_ID_END) + while ((rct2LanguageId = static_cast(stream->ReadValue())) != RCT2_LANGUAGE_ID_END) { uint8_t languageId = (rct2LanguageId <= RCT2_LANGUAGE_ID_PORTUGUESE) ? RCT2ToOpenRCT2LanguageId[rct2LanguageId] - : (uint8_t)LANGUAGE_UNDEFINED; + : static_cast(LANGUAGE_UNDEFINED); StringTableEntry entry{}; entry.Id = id; entry.LanguageId = languageId; diff --git a/src/openrct2/object/WaterObject.cpp b/src/openrct2/object/WaterObject.cpp index 4bb59cf701..d9d44323c1 100644 --- a/src/openrct2/object/WaterObject.cpp +++ b/src/openrct2/object/WaterObject.cpp @@ -110,8 +110,8 @@ void WaterObject::ReadJsonPalette(const json_t* jPalette) rct_g1_element g1 = {}; g1.offset = data.get(); - g1.width = (int16_t)numColours; - g1.x_offset = (int16_t)paletteStartIndex; + g1.width = static_cast(numColours); + g1.x_offset = static_cast(paletteStartIndex); g1.flags = G1_FLAG_PALETTE; auto& imageTable = GetImageTable(); diff --git a/src/openrct2/paint/Paint.cpp b/src/openrct2/paint/Paint.cpp index 5ef604af62..30a1f07e48 100644 --- a/src/openrct2/paint/Paint.cpp +++ b/src/openrct2/paint/Paint.cpp @@ -162,7 +162,7 @@ static paint_struct* sub_9819_c( void paint_session_generate(paint_session* session) { rct_drawpixelinfo* dpi = &session->DPI; - LocationXY16 mapTile = { (int16_t)(dpi->x & 0xFFE0), (int16_t)((dpi->y - 16) & 0xFFE0) }; + LocationXY16 mapTile = { static_cast(dpi->x & 0xFFE0), static_cast((dpi->y - 16) & 0xFFE0) }; int16_t half_x = mapTile.x >> 1; uint16_t num_vertical_quadrants = (dpi->height + 2128) >> 5; @@ -880,7 +880,8 @@ paint_struct* sub_98197C( session->LastRootPS = ps; - auto attach = CoordsXY{ (int16_t)ps->bounds.x, (int16_t)ps->bounds.y }.Rotate(session->CurrentRotation); + auto attach = CoordsXY{ static_cast(ps->bounds.x), static_cast(ps->bounds.y) }.Rotate( + session->CurrentRotation); switch (session->CurrentRotation) { case 0: @@ -1094,7 +1095,7 @@ void paint_floating_money_effect( ps->args[1] = y; ps->args[2] = 0; ps->args[3] = 0; - ps->y_offsets = (uint8_t*)y_offsets; + ps->y_offsets = reinterpret_cast(y_offsets); const CoordsXYZ position = { session->SpritePosition.x, @@ -1151,6 +1152,7 @@ void paint_draw_money_structs(rct_drawpixelinfo* dpi, paint_string_struct* ps) forceSpriteFont = true; } - gfx_draw_string_with_y_offsets(&dpi2, buffer, COLOUR_BLACK, ps->x, ps->y, (int8_t*)ps->y_offsets, forceSpriteFont); + gfx_draw_string_with_y_offsets( + &dpi2, buffer, COLOUR_BLACK, ps->x, ps->y, reinterpret_cast(ps->y_offsets), forceSpriteFont); } while ((ps = ps->next) != nullptr); } diff --git a/src/openrct2/paint/sprite/Paint.Misc.cpp b/src/openrct2/paint/sprite/Paint.Misc.cpp index 718cb33235..618c25bced 100644 --- a/src/openrct2/paint/sprite/Paint.Misc.cpp +++ b/src/openrct2/paint/sprite/Paint.Misc.cpp @@ -52,8 +52,8 @@ void misc_paint(paint_session* session, const rct_sprite* misc, int32_t imageDir const MoneyEffect* moneyEffect = &misc->money_effect; auto [stringId, value] = moneyEffect->GetStringId(); paint_floating_money_effect( - session, value, stringId, moneyEffect->y, moneyEffect->z, (int8_t*)&money_wave[moneyEffect->wiggle % 22], - moneyEffect->offset_x, session->CurrentRotation); + session, value, stringId, moneyEffect->y, moneyEffect->z, + const_cast(&money_wave[moneyEffect->wiggle % 22]), moneyEffect->offset_x, session->CurrentRotation); break; } diff --git a/src/openrct2/paint/tile_element/Paint.Entrance.cpp b/src/openrct2/paint/tile_element/Paint.Entrance.cpp index ed704d2b3f..834528b695 100644 --- a/src/openrct2/paint/tile_element/Paint.Entrance.cpp +++ b/src/openrct2/paint/tile_element/Paint.Entrance.cpp @@ -256,7 +256,7 @@ static void park_entrance_paint(paint_session* session, uint8_t direction, int32 sub_98197C(session, image_id, 0, 0, 32, 0x1C, 0, height, 0, 2, height); } - entrance = (rct_entrance_type*)object_entry_get_chunk(OBJECT_TYPE_PARK_ENTRANCE, 0); + entrance = static_cast(object_entry_get_chunk(OBJECT_TYPE_PARK_ENTRANCE, 0)); if (entrance == nullptr) { return; @@ -312,7 +312,7 @@ static void park_entrance_paint(paint_session* session, uint8_t direction, int32 break; case 1: case 2: - entrance = (rct_entrance_type*)object_entry_get_chunk(OBJECT_TYPE_PARK_ENTRANCE, 0); + entrance = static_cast(object_entry_get_chunk(OBJECT_TYPE_PARK_ENTRANCE, 0)); if (entrance == nullptr) { return; diff --git a/src/openrct2/paint/tile_element/Paint.LargeScenery.cpp b/src/openrct2/paint/tile_element/Paint.LargeScenery.cpp index 2200c6b876..b121d882af 100644 --- a/src/openrct2/paint/tile_element/Paint.LargeScenery.cpp +++ b/src/openrct2/paint/tile_element/Paint.LargeScenery.cpp @@ -70,7 +70,7 @@ static rct_large_scenery_text_glyph* large_scenery_sign_get_glyph(rct_large_scen { if (codepoint >= std::size(text->glyphs)) { - return &text->glyphs[(size_t)'?']; + return &text->glyphs[static_cast('?')]; } return &text->glyphs[codepoint]; } @@ -284,7 +284,7 @@ void large_scenery_paint(paint_session* session, uint8_t direction, uint16_t hei } if (entry->large_scenery.flags & LARGE_SCENERY_FLAG_3D_TEXT) { - if (entry->large_scenery.tiles[1].x_offset != (int16_t)(uint16_t)0xFFFF) + if (entry->large_scenery.tiles[1].x_offset != static_cast(static_cast(0xFFFF))) { int32_t sequenceDirection = (tileElement->AsLargeScenery()->GetSequenceIndex() - 1) & 3; if (sequenceDirection != direction) diff --git a/src/openrct2/paint/tile_element/Paint.Path.cpp b/src/openrct2/paint/tile_element/Paint.Path.cpp index b5fe6531ee..6e6bf4752c 100644 --- a/src/openrct2/paint/tile_element/Paint.Path.cpp +++ b/src/openrct2/paint/tile_element/Paint.Path.cpp @@ -720,15 +720,18 @@ static void sub_6A3F61( { case PATH_BIT_DRAW_TYPE_LIGHTS: path_bit_lights_paint( - session, sceneryEntry, tile_element, height, (uint8_t)connectedEdges, sceneryImageFlags); + session, sceneryEntry, tile_element, height, static_cast(connectedEdges), + sceneryImageFlags); break; case PATH_BIT_DRAW_TYPE_BINS: path_bit_bins_paint( - session, sceneryEntry, tile_element, height, (uint8_t)connectedEdges, sceneryImageFlags); + session, sceneryEntry, tile_element, height, static_cast(connectedEdges), + sceneryImageFlags); break; case PATH_BIT_DRAW_TYPE_BENCHES: path_bit_benches_paint( - session, sceneryEntry, tile_element, height, (uint8_t)connectedEdges, sceneryImageFlags); + session, sceneryEntry, tile_element, height, static_cast(connectedEdges), + sceneryImageFlags); break; case PATH_BIT_DRAW_TYPE_JUMPING_FOUNTAINS: path_bit_jumping_fountains_paint(session, sceneryEntry, height, sceneryImageFlags, dpi); diff --git a/src/openrct2/paint/tile_element/Paint.Surface.cpp b/src/openrct2/paint/tile_element/Paint.Surface.cpp index 76b7457659..e155c38358 100644 --- a/src/openrct2/paint/tile_element/Paint.Surface.cpp +++ b/src/openrct2/paint/tile_element/Paint.Surface.cpp @@ -307,7 +307,7 @@ static uint32_t get_surface_image( const paint_session* session, uint8_t index, int32_t offset, uint8_t rotation, int32_t grassLength, bool grid, bool underground) { - auto image = (uint32_t)SPR_NONE; + auto image = static_cast(SPR_NONE); auto obj = get_surface_object(index); if (obj != nullptr) { @@ -323,7 +323,7 @@ static uint32_t get_surface_image( static uint32_t get_surface_pattern(uint8_t index, int32_t offset) { - auto image = (uint32_t)SPR_NONE; + auto image = static_cast(SPR_NONE); auto obj = get_surface_object(index); if (obj != nullptr) { @@ -965,13 +965,13 @@ void surface_paint(paint_session* session, uint8_t direction, uint16_t height, c tile_descriptor selfDescriptor = { TileCoordsXY(base), tileElement, - (uint8_t)terrain_type, + static_cast(terrain_type), surfaceShape, { - (uint8_t)(height / 16 + cornerHeights.top), - (uint8_t)(height / 16 + cornerHeights.right), - (uint8_t)(height / 16 + cornerHeights.bottom), - (uint8_t)(height / 16 + cornerHeights.left), + static_cast(height / 16 + cornerHeights.top), + static_cast(height / 16 + cornerHeights.right), + static_cast(height / 16 + cornerHeights.bottom), + static_cast(height / 16 + cornerHeights.left), }, }; @@ -982,8 +982,8 @@ void surface_paint(paint_session* session, uint8_t direction, uint16_t height, c { const LocationXY16& offset = viewport_surface_paint_data[i][rotation]; const CoordsXY position = { - (int32_t)(base.x + offset.x), - (int32_t)(base.y + offset.y), + static_cast(base.x + offset.x), + static_cast(base.y + offset.y), }; tile_descriptor& descriptor = tileDescriptors[i + 1]; diff --git a/src/openrct2/paint/tile_element/Paint.TileElement.cpp b/src/openrct2/paint/tile_element/Paint.TileElement.cpp index dd3c833f96..be36bcb2e6 100644 --- a/src/openrct2/paint/tile_element/Paint.TileElement.cpp +++ b/src/openrct2/paint/tile_element/Paint.TileElement.cpp @@ -213,7 +213,7 @@ static void sub_68B3FB(paint_session* session, int32_t x, int32_t y) uint16_t max_height = 0; do { - max_height = std::max(max_height, (uint16_t)element->GetClearanceZ()); + max_height = std::max(max_height, static_cast(element->GetClearanceZ())); } while (!(element++)->IsLastForTile()); element--; diff --git a/src/openrct2/paint/tile_element/Paint.Wall.cpp b/src/openrct2/paint/tile_element/Paint.Wall.cpp index b15670faff..a8ea92321f 100644 --- a/src/openrct2/paint/tile_element/Paint.Wall.cpp +++ b/src/openrct2/paint/tile_element/Paint.Wall.cpp @@ -59,16 +59,16 @@ static void fence_paint_door( paint_struct* ps; ps = sub_98197C( - session, imageId, (int8_t)offset.x, (int8_t)offset.y, boundsR1.x, boundsR1.y, (int8_t)boundsR1.z, offset.z, - boundsR1_.x, boundsR1_.y, boundsR1_.z); + session, imageId, static_cast(offset.x), static_cast(offset.y), boundsR1.x, boundsR1.y, + static_cast(boundsR1.z), offset.z, boundsR1_.x, boundsR1_.y, boundsR1_.z); if (ps != nullptr) { ps->tertiary_colour = tertiaryColour; } ps = sub_98197C( - session, imageId + 1, (int8_t)offset.x, (int8_t)offset.y, boundsR2.x, boundsR2.y, (int8_t)boundsR2.z, offset.z, - boundsR2_.x, boundsR2_.y, boundsR2_.z); + session, imageId + 1, static_cast(offset.x), static_cast(offset.y), boundsR2.x, boundsR2.y, + static_cast(boundsR2.z), offset.z, boundsR2_.x, boundsR2_.y, boundsR2_.z); if (ps != nullptr) { ps->tertiary_colour = tertiaryColour; @@ -79,16 +79,16 @@ static void fence_paint_door( paint_struct* ps; ps = sub_98197C( - session, imageId, (int8_t)offset.x, (int8_t)offset.y, boundsL1.x, boundsL1.y, (int8_t)boundsL1.z, offset.z, - boundsL1_.x, boundsL1_.y, boundsL1_.z); + session, imageId, static_cast(offset.x), static_cast(offset.y), boundsL1.x, boundsL1.y, + static_cast(boundsL1.z), offset.z, boundsL1_.x, boundsL1_.y, boundsL1_.z); if (ps != nullptr) { ps->tertiary_colour = tertiaryColour; } ps = sub_98199C( - session, imageId + 1, (int8_t)offset.x, (int8_t)offset.y, boundsL1.x, boundsL1.y, (int8_t)boundsL1.z, offset.z, - boundsL1_.x, boundsL1_.y, boundsL1_.z); + session, imageId + 1, static_cast(offset.x), static_cast(offset.y), boundsL1.x, boundsL1.y, + static_cast(boundsL1.z), offset.z, boundsL1_.x, boundsL1_.y, boundsL1_.z); if (ps != nullptr) { ps->tertiary_colour = tertiaryColour; @@ -117,14 +117,14 @@ static void fence_paint_wall( } sub_98197C( - session, imageId, (int8_t)offset.x, (int8_t)offset.y, bounds.x, bounds.y, (int8_t)bounds.z, offset.z, - boundsOffset.x, boundsOffset.y, boundsOffset.z); + session, imageId, static_cast(offset.x), static_cast(offset.y), bounds.x, bounds.y, + static_cast(bounds.z), offset.z, boundsOffset.x, boundsOffset.y, boundsOffset.z); if (dword_141F710 == 0) { imageId = baseImageId + dword_141F718; sub_98199C( - session, imageId, (int8_t)offset.x, (int8_t)offset.y, bounds.x, bounds.y, (int8_t)bounds.z, offset.z, - boundsOffset.x, boundsOffset.y, boundsOffset.z); + session, imageId, static_cast(offset.x), static_cast(offset.y), bounds.x, bounds.y, + static_cast(bounds.z), offset.z, boundsOffset.x, boundsOffset.y, boundsOffset.z); } } else @@ -140,8 +140,8 @@ static void fence_paint_wall( } paint_struct* paint = sub_98197C( - session, imageId, (int8_t)offset.x, (int8_t)offset.y, bounds.x, bounds.y, (int8_t)bounds.z, offset.z, - boundsOffset.x, boundsOffset.y, boundsOffset.z); + session, imageId, static_cast(offset.x), static_cast(offset.y), bounds.x, bounds.y, + static_cast(bounds.z), offset.z, boundsOffset.x, boundsOffset.y, boundsOffset.z); if (paint != nullptr) { paint->tertiary_colour = tertiaryColour; diff --git a/src/openrct2/peep/Guest.cpp b/src/openrct2/peep/Guest.cpp index 01738e12d6..7e636e3191 100644 --- a/src/openrct2/peep/Guest.cpp +++ b/src/openrct2/peep/Guest.cpp @@ -693,7 +693,7 @@ int32_t Guest::CheckEasterEggName(int32_t index) const void Guest::Tick128UpdateGuest(int32_t index) { - if ((uint32_t)(index & 0x1FF) == (gCurrentTicks & 0x1FF)) + if (static_cast(index & 0x1FF) == (gCurrentTicks & 0x1FF)) { /* Effect of masking with 0x1FF here vs mask 0x7F, * which is the condition for calling this function, is @@ -827,7 +827,7 @@ void Guest::Tick128UpdateGuest(int32_t index) PickRideToGoOn(); } - if ((uint32_t)(index & 0x3FF) == (gCurrentTicks & 0x3FF)) + if (static_cast(index & 0x3FF) == (gCurrentTicks & 0x3FF)) { /* Effect of masking with 0x3FF here vs mask 0x1FF, * which is used in the encompassing conditional, is @@ -1044,7 +1044,7 @@ void Guest::Tick128UpdateGuest(int32_t index) if (state == PEEP_STATE_WALKING && nausea_target >= 128) { - if ((scenario_rand() & 0xFF) <= (uint8_t)((nausea - 128) / 2)) + if ((scenario_rand() & 0xFF) <= static_cast((nausea - 128) / 2)) { if (action >= PEEP_ACTION_NONE_1) { @@ -1586,7 +1586,7 @@ loc_69B119: if (happiness >= 180) itemValue /= 2; - if (itemValue > ((money16)(scenario_rand() & 0x07))) + if (itemValue > (static_cast(scenario_rand() & 0x07))) { // "I'm not paying that much for x" PeepThoughtType thought_type = static_cast( @@ -1603,7 +1603,7 @@ loc_69B119: if (!(gParkFlags & PARK_FLAGS_NO_MONEY)) { - if (itemValue >= (money32)(scenario_rand() & 0x07)) + if (itemValue >= static_cast(scenario_rand() & 0x07)) { // "This x is a really good value" PeepThoughtType thought_item = static_cast( @@ -2204,7 +2204,7 @@ bool Guest::ShouldGoOnRide(Ride* ride, int32_t entranceNum, bool atQueue, bool t // Peeps won't pay more than twice the value of the ride. ridePrice = ride_get_price(ride); - if (ridePrice > (money16)(value * 2)) + if (ridePrice > static_cast(value * 2)) { if (peepAtRide) { @@ -2220,7 +2220,7 @@ bool Guest::ShouldGoOnRide(Ride* ride, int32_t entranceNum, bool atQueue, bool t } // A ride is good value if the price is 50% or less of the ride value and the peep didn't pay to enter the park. - if (ridePrice <= (money16)(value / 2) && peepAtRide) + if (ridePrice <= static_cast(value / 2) && peepAtRide) { if (!(gParkFlags & PARK_FLAGS_NO_MONEY)) { @@ -2345,7 +2345,7 @@ void Guest::SpendMoney(money16& peep_expend_type, money32 amount, ExpenditureTyp cash_in_pocket = std::max(0, cash_in_pocket - amount); cash_spent += amount; - peep_expend_type += (money16)amount; + peep_expend_type += static_cast(amount); window_invalidate_by_number(WC_PEEP, sprite_index); @@ -2462,11 +2462,11 @@ static Vehicle* peep_choose_car_from_ride(Peep* peep, Ride* ride, std::vectortype, RIDE_TYPE_FLAG_HAS_G_FORCES) && ((chosen_car & 0xC) != 0xC)) { - chosen_car = (scenario_rand() & 1) ? 0 : (uint8_t)car_array.size() - 1; + chosen_car = (scenario_rand() & 1) ? 0 : static_cast(car_array.size()) - 1; } else { - chosen_car = (chosen_car * (uint16_t)car_array.size()) >> 8; + chosen_car = (chosen_car * static_cast(car_array.size())) >> 8; } peep->current_car = car_array[chosen_car]; @@ -2862,7 +2862,7 @@ static void peep_update_ride_nausea_growth(Peep* peep, Ride* ride) uint32_t nauseaGrowthRateChange = (ride->nausea * nauseaMultiplier) / 512; nauseaGrowthRateChange *= std::max(static_cast(128), peep->hunger) / 64; nauseaGrowthRateChange >>= (peep->nausea_tolerance & 3); - peep->nausea_target = (uint8_t)std::min(peep->nausea_target + nauseaGrowthRateChange, 255u); + peep->nausea_target = static_cast(std::min(peep->nausea_target + nauseaGrowthRateChange, 255u)); } static bool peep_should_go_on_ride_again(Peep* peep, Ride* ride) @@ -3638,7 +3638,7 @@ static void peep_update_ride_leave_entrance_waypoints(Peep* peep, Ride* ride) waypoint.y = vehicle->y; } - Guard::Assert(vehicle_type->peep_loading_waypoints.size() >= (size_t)(peep->var_37 / 4)); + Guard::Assert(vehicle_type->peep_loading_waypoints.size() >= static_cast(peep->var_37 / 4)); waypoint.x += vehicle_type->peep_loading_waypoints[peep->var_37 / 4][0].x; waypoint.y += vehicle_type->peep_loading_waypoints[peep->var_37 / 4][0].y; @@ -4285,7 +4285,7 @@ void Guest::UpdateRideLeaveVehicle() waypointLoc.y = vehicle->y; } - Guard::Assert(vehicleEntry->peep_loading_waypoints.size() >= (size_t)(var_37 / 4)); + Guard::Assert(vehicleEntry->peep_loading_waypoints.size() >= static_cast(var_37 / 4)); CoordsXYZ exitWaypointLoc = waypointLoc; exitWaypointLoc.x += vehicleEntry->peep_loading_waypoints[var_37 / 4][2].x; @@ -4612,7 +4612,7 @@ void Guest::UpdateRideApproachSpiralSlide() { if (ride->mode == RIDE_MODE_SINGLE_RIDE_PER_ADMISSION) lastRide = true; - if ((uint8_t)(current_car - 1) > (scenario_rand() & 0xF)) + if (static_cast(current_car - 1) > (scenario_rand() & 0xF)) lastRide = true; } @@ -5324,7 +5324,7 @@ void Guest::UpdateWalking() } else if (HasEmptyContainer()) { - if ((!GetNextIsSurface()) && ((uint32_t)(sprite_index & 0x1FF) == (gCurrentTicks & 0x1FF)) + if ((!GetNextIsSurface()) && (static_cast(sprite_index & 0x1FF) == (gCurrentTicks & 0x1FF)) && ((0xFFFF & scenario_rand()) <= 4096)) { uint8_t pos_stnd = 0; diff --git a/src/openrct2/peep/GuestPathfinding.cpp b/src/openrct2/peep/GuestPathfinding.cpp index cf7ecde7d8..cfd6062ae5 100644 --- a/src/openrct2/peep/GuestPathfinding.cpp +++ b/src/openrct2/peep/GuestPathfinding.cpp @@ -613,8 +613,8 @@ static void peep_pathfind_heuristic_search( /* If this is where the search started this is a search loop and the * current search path ends here. * Return without updating the parameters (best result so far). */ - if ((_peepPathFindHistory[0].location.x == (uint8_t)loc.x) && (_peepPathFindHistory[0].location.y == (uint8_t)loc.y) - && (_peepPathFindHistory[0].location.z == loc.z)) + if ((_peepPathFindHistory[0].location.x == static_cast(loc.x)) + && (_peepPathFindHistory[0].location.y == static_cast(loc.y)) && (_peepPathFindHistory[0].location.z == loc.z)) { #if defined(DEBUG_LEVEL_2) && DEBUG_LEVEL_2 if (gPathFindDebug) @@ -1011,8 +1011,8 @@ static void peep_pathfind_heuristic_search( for (int32_t junctionNum = _peepPathFindNumJunctions + 1; junctionNum <= _peepPathFindMaxJunctions; junctionNum++) { - if ((_peepPathFindHistory[junctionNum].location.x == (uint8_t)loc.x) - && (_peepPathFindHistory[junctionNum].location.y == (uint8_t)loc.y) + if ((_peepPathFindHistory[junctionNum].location.x == static_cast(loc.x)) + && (_peepPathFindHistory[junctionNum].location.y == static_cast(loc.y)) && (_peepPathFindHistory[junctionNum].location.z == loc.z)) { pathLoop = true; @@ -1071,8 +1071,8 @@ static void peep_pathfind_heuristic_search( /* This junction was NOT previously visited in the current * search path, so add the junction to the history. */ - _peepPathFindHistory[_peepPathFindNumJunctions].location.x = (uint8_t)loc.x; - _peepPathFindHistory[_peepPathFindNumJunctions].location.y = (uint8_t)loc.y; + _peepPathFindHistory[_peepPathFindNumJunctions].location.x = static_cast(loc.x); + _peepPathFindHistory[_peepPathFindNumJunctions].location.y = static_cast(loc.y); _peepPathFindHistory[_peepPathFindNumJunctions].location.z = loc.z; // .direction take is added below. @@ -1313,7 +1313,7 @@ Direction peep_pathfind_choose_direction(const TileCoordsXYZ& loc, Peep* peep) peep->pathfind_goal.direction = 0; // Clear pathfinding history - std::fill_n((uint8_t*)peep->pathfind_history, sizeof(peep->pathfind_history), 0xFF); + std::fill_n(reinterpret_cast(peep->pathfind_history), sizeof(peep->pathfind_history), 0xFF); #if defined(DEBUG_LEVEL_1) && DEBUG_LEVEL_1 if (gPathFindDebug) { @@ -1374,8 +1374,8 @@ Direction peep_pathfind_choose_direction(const TileCoordsXYZ& loc, Peep* peep) /* The pathfinding will only use elements * 1.._peepPathFindMaxJunctions, so the starting point * is placed in element 0 */ - _peepPathFindHistory[0].location.x = (uint8_t)(loc.x); - _peepPathFindHistory[0].location.y = (uint8_t)(loc.y); + _peepPathFindHistory[0].location.x = static_cast(loc.x); + _peepPathFindHistory[0].location.y = static_cast(loc.y); _peepPathFindHistory[0].location.z = loc.z; _peepPathFindHistory[0].direction = 0xF; @@ -1513,8 +1513,8 @@ Direction peep_pathfind_choose_direction(const TileCoordsXYZ& loc, Peep* peep) * and remember this junction. */ int32_t i = peep->pathfind_goal.direction++; peep->pathfind_goal.direction &= 3; - peep->pathfind_history[i].x = (uint8_t)loc.x; - peep->pathfind_history[i].y = (uint8_t)loc.y; + peep->pathfind_history[i].x = static_cast(loc.x); + peep->pathfind_history[i].y = static_cast(loc.y); peep->pathfind_history[i].z = loc.z; peep->pathfind_history[i].direction = permitted_edges; /* Remove the chosen_edge from those left to try. */ diff --git a/src/openrct2/peep/Peep.cpp b/src/openrct2/peep/Peep.cpp index 0641c32d4d..ff0b29d5aa 100644 --- a/src/openrct2/peep/Peep.cpp +++ b/src/openrct2/peep/Peep.cpp @@ -325,7 +325,7 @@ Peep* rct_sprite::AsPeep() Peep* result = nullptr; if (IsPeep()) { - return (Peep*)this; + return reinterpret_cast(this); } return result; } @@ -418,7 +418,7 @@ void peep_update_all() peep = GET_PEEP(spriteIndex); spriteIndex = peep->next; - if ((uint32_t)(i & 0x7F) != (gCurrentTicks & 0x7F)) + if (static_cast(i & 0x7F) != (gCurrentTicks & 0x7F)) { peep->Update(); } @@ -743,7 +743,7 @@ void Peep::PickupAbort(int32_t old_x) MoveTo(old_x, y, z + 8); - if (x != (int16_t)LOCATION_NULL) + if (x != LOCATION_NULL) { SetState(PEEP_STATE_FALLING); action = PEEP_ACTION_NONE_2; @@ -1791,7 +1791,7 @@ void Peep::FormatActionTo(Formatter& ft) const void Peep::FormatActionTo(void* argsV) const { - Formatter ft((uint8_t*)argsV); + Formatter ft(static_cast(argsV)); switch (state) { case PEEP_STATE_FALLING: @@ -1970,7 +1970,7 @@ void Peep::FormatNameTo(Formatter& ft) const size_t Peep::FormatNameTo(void* argsV) const { - Formatter ft((uint8_t*)argsV); + Formatter ft(static_cast(argsV)); if (name == nullptr) { if (type == PeepType::PEEP_TYPE_STAFF) @@ -2025,7 +2025,7 @@ bool Peep::SetName(const std::string_view& value) } else { - auto newNameMemory = (char*)std::malloc(value.size() + 1); + auto newNameMemory = static_cast(std::malloc(value.size() + 1)); if (newNameMemory != nullptr) { std::memcpy(newNameMemory, value.data(), value.size()); @@ -2682,7 +2682,7 @@ static void peep_footpath_move_forward(Peep* peep, int16_t x, int16_t y, TileEle sprite = get_sprite(sprite_id); if (sprite->generic.sprite_identifier == SPRITE_IDENTIFIER_PEEP) { - Peep* other_peep = (Peep*)sprite; + Peep* other_peep = reinterpret_cast(sprite); if (other_peep->state != PEEP_STATE_WALKING) continue; @@ -2693,7 +2693,7 @@ static void peep_footpath_move_forward(Peep* peep, int16_t x, int16_t y, TileEle } else if (sprite->generic.sprite_identifier == SPRITE_IDENTIFIER_LITTER) { - Litter* litter = (Litter*)sprite; + Litter* litter = reinterpret_cast(sprite); if (abs(litter->z - peep->NextLoc.z) > 16) continue; @@ -3217,7 +3217,7 @@ int32_t Peep::GetZOnSlope(int32_t tile_x, int32_t tile_y) rct_string_id get_real_name_string_id_from_id(uint32_t id) { // Generate a name_string_idx from the peep id using bit twiddling - uint16_t ax = (uint16_t)(id + 0xF0B); + uint16_t ax = static_cast(id + 0xF0B); uint16_t dx = 0; static constexpr uint16_t twiddlingBitOrder[] = { 4, 9, 3, 7, 5, 8, 2, 1, 6, 0, 12, 11, 13, 10 }; for (size_t i = 0; i < std::size(twiddlingBitOrder); i++) diff --git a/src/openrct2/peep/Staff.cpp b/src/openrct2/peep/Staff.cpp index 2b24a1c1f2..41cf7e25cf 100644 --- a/src/openrct2/peep/Staff.cpp +++ b/src/openrct2/peep/Staff.cpp @@ -390,7 +390,7 @@ static bool staff_is_patrol_area_set(int32_t staffIndex, int32_t x, int32_t y) int32_t peepOffset = staffIndex * STAFF_PATROL_AREA_SIZE; int32_t offset = (x | y) >> 5; int32_t bitIndex = (x | y) & 0x1F; - return gStaffPatrolAreas[peepOffset + offset] & (((uint32_t)1) << bitIndex); + return gStaffPatrolAreas[peepOffset + offset] & (1UL << bitIndex); } bool Staff::IsPatrolAreaSet(const CoordsXY& coords) const @@ -441,7 +441,7 @@ void staff_toggle_patrol_area(int32_t staffIndex, int32_t x, int32_t y) */ static uint8_t staff_handyman_direction_to_nearest_litter(Peep* peep) { - uint16_t nearestLitterDist = (uint16_t)-1; + uint16_t nearestLitterDist = 0xFFFF; Litter* nearestLitter = nullptr; Litter* litter = nullptr; @@ -884,7 +884,7 @@ static uint8_t staff_mechanic_direction_path(Peep* peep, uint8_t validDirections return staff_mechanic_direction_path_rand(peep, pathDirections); } - return (uint8_t)pathfindDirection; + return static_cast(pathfindDirection); } return staff_mechanic_direction_path_rand(peep, pathDirections); } diff --git a/src/openrct2/platform/Linux.cpp b/src/openrct2/platform/Linux.cpp index eab3419832..c8a51e49c1 100644 --- a/src/openrct2/platform/Linux.cpp +++ b/src/openrct2/platform/Linux.cpp @@ -204,7 +204,7 @@ bool platform_get_font_path(TTFFontDescriptor* font, utf8* buffer, size_t size) return false; } - FcPattern* pat = FcNameParse((const FcChar8*)font->font_name); + FcPattern* pat = FcNameParse(reinterpret_cast(font->font_name)); FcConfigSubstitute(config, pat, FcMatchPattern); FcDefaultSubstitute(pat); @@ -224,7 +224,7 @@ bool platform_get_font_path(TTFFontDescriptor* font, utf8* buffer, size_t size) // and instead rely on exact matches on the fonts predefined for each font family. FcChar8* matched_font_face = nullptr; if (FcPatternGetString(match, FC_FULLNAME, 0, &matched_font_face) == FcResultMatch - && strcmp(font->font_name, (const char*)matched_font_face) != 0) + && strcmp(font->font_name, reinterpret_cast(matched_font_face)) != 0) { log_verbose("FontConfig provided substitute font %s -- disregarding.", matched_font_face); is_substitute = true; @@ -234,7 +234,7 @@ bool platform_get_font_path(TTFFontDescriptor* font, utf8* buffer, size_t size) if (!is_substitute && FcPatternGetString(match, FC_FILE, 0, &filename) == FcResultMatch) { found = true; - safe_strcpy(buffer, (utf8*)filename, size); + safe_strcpy(buffer, reinterpret_cast(filename), size); log_verbose("FontConfig provided font %s", filename); } diff --git a/src/openrct2/platform/Platform.macOS.mm b/src/openrct2/platform/Platform.macOS.mm index efe493541c..807d080502 100644 --- a/src/openrct2/platform/Platform.macOS.mm +++ b/src/openrct2/platform/Platform.macOS.mm @@ -44,7 +44,8 @@ namespace Platform static std::string GetBundlePath() { - @autoreleasepool { + @autoreleasepool + { NSBundle* bundle = [NSBundle mainBundle]; if (bundle) { @@ -105,14 +106,16 @@ namespace Platform uintptr_t StrDecompToPrecomp(utf8* input) { - @autoreleasepool { + @autoreleasepool + { if (input == NULL) { return 0; } NSString* inputDecomp = [NSString stringWithUTF8String:input]; - return reinterpret_cast(strdup([inputDecomp.precomposedStringWithCanonicalMapping cStringUsingEncoding:NSUTF8StringEncoding])); + return reinterpret_cast( + strdup([inputDecomp.precomposedStringWithCanonicalMapping cStringUsingEncoding:NSUTF8StringEncoding])); } } diff --git a/src/openrct2/platform/Posix.cpp b/src/openrct2/platform/Posix.cpp index 91ff89e596..2596cb55b3 100644 --- a/src/openrct2/platform/Posix.cpp +++ b/src/openrct2/platform/Posix.cpp @@ -373,7 +373,7 @@ bool platform_file_copy(const utf8* srcPath, const utf8* dstPath, bool overwrite size_t file_offset = 0; // Copy file in FILE_BUFFER_SIZE-d chunks - char* buffer = (char*)malloc(FILE_BUFFER_SIZE); + char* buffer = static_cast(malloc(FILE_BUFFER_SIZE)); while ((amount_read = fread(buffer, FILE_BUFFER_SIZE, 1, srcFile))) { fwrite(buffer, amount_read, 1, dstFile); @@ -463,7 +463,7 @@ datetime64 platform_get_datetime_now_utc() // Epoch starts from: 1970-01-01T00:00:00Z // Convert to ticks from 0001-01-01T00:00:00Z - uint64_t utcEpochTicks = (uint64_t)tv.tv_sec * 10000000ULL + tv.tv_usec * 10; + uint64_t utcEpochTicks = static_cast(tv.tv_sec) * 10000000ULL + tv.tv_usec * 10; datetime64 utcNow = epochAsTicks + utcEpochTicks; return utcNow; } diff --git a/src/openrct2/platform/Shared.cpp b/src/openrct2/platform/Shared.cpp index 7672bf71d0..8f5e64ad45 100644 --- a/src/openrct2/platform/Shared.cpp +++ b/src/openrct2/platform/Shared.cpp @@ -168,7 +168,7 @@ uint32_t platform_get_ticks() log_fatal("clock_gettime failed"); exit(-1); } - return (uint32_t)(ts.tv_sec * 1000 + ts.tv_nsec / 1000000); + return static_cast(ts.tv_sec * 1000 + ts.tv_nsec / 1000000); #endif } diff --git a/src/openrct2/platform/macos.mm b/src/openrct2/platform/macos.mm index 67fbede819..b700b393ab 100644 --- a/src/openrct2/platform/macos.mm +++ b/src/openrct2/platform/macos.mm @@ -23,11 +23,11 @@ # include # include - # ifndef NO_TTF bool platform_get_font_path(TTFFontDescriptor* font, utf8* buffer, size_t size) { - @autoreleasepool { + @autoreleasepool + { CTFontDescriptorRef fontRef = CTFontDescriptorCreateWithNameAndSize( (CFStringRef)[NSString stringWithUTF8String:font->font_name], 0.0); CFURLRef url = (CFURLRef)CTFontDescriptorCopyAttribute(fontRef, kCTFontURLAttribute); @@ -47,7 +47,8 @@ bool platform_get_font_path(TTFFontDescriptor* font, utf8* buffer, size_t size) bool platform_has_matching_language(NSString* preferredLocale, uint16_t* languageIdentifier) { - @autoreleasepool { + @autoreleasepool + { if ([preferredLocale isEqualToString:@"en"] || [preferredLocale isEqualToString:@"en-CA"]) { *languageIdentifier = LANGUAGE_ENGLISH_US; @@ -80,8 +81,8 @@ bool platform_has_matching_language(NSString* preferredLocale, uint16_t* languag NSString* languageCode = [[preferredLocale componentsSeparatedByString:@"-"] firstObject]; for (int i = 1; i < LANGUAGE_COUNT; i++) { - NSString* optionLanguageCode = [ - [[NSString stringWithUTF8String:LanguagesDescriptors[i].locale] componentsSeparatedByString:@"-"] firstObject]; + NSString* optionLanguageCode = [[[NSString stringWithUTF8String:LanguagesDescriptors[i].locale] + componentsSeparatedByString:@"-"] firstObject]; if ([languageCode isEqualToString:optionLanguageCode]) { *languageIdentifier = i; @@ -95,7 +96,8 @@ bool platform_has_matching_language(NSString* preferredLocale, uint16_t* languag uint16_t platform_get_locale_language() { - @autoreleasepool { + @autoreleasepool + { NSArray* preferredLanguages = [NSLocale preferredLanguages]; for (NSString* preferredLanguage in preferredLanguages) { @@ -113,7 +115,8 @@ uint16_t platform_get_locale_language() uint8_t platform_get_locale_currency() { - @autoreleasepool { + @autoreleasepool + { NSString* currencyCode = [[NSLocale currentLocale] objectForKey:NSLocaleCurrencyCode]; return platform_get_currency_value(currencyCode.UTF8String); } @@ -121,7 +124,8 @@ uint8_t platform_get_locale_currency() uint8_t platform_get_locale_measurement_format() { - @autoreleasepool { + @autoreleasepool + { NSNumber* metricSystem = [[NSLocale currentLocale] objectForKey:NSLocaleUsesMetricSystem]; if (metricSystem.boolValue) diff --git a/src/openrct2/rct1/S4Importer.cpp b/src/openrct2/rct1/S4Importer.cpp index fe06803ff1..137249a383 100644 --- a/src/openrct2/rct1/S4Importer.cpp +++ b/src/openrct2/rct1/S4Importer.cpp @@ -2481,7 +2481,7 @@ private: void ImportParkName() { std::string parkName = std::string(_s4.scenario_name); - if (is_user_string_id((rct_string_id)_s4.park_name_string_index)) + if (is_user_string_id(static_cast(_s4.park_name_string_index))) { std::string userString = GetUserString(_s4.park_name_string_index); if (!userString.empty()) diff --git a/src/openrct2/rct1/T4Importer.cpp b/src/openrct2/rct1/T4Importer.cpp index 0589307788..5e2154b495 100644 --- a/src/openrct2/rct1/T4Importer.cpp +++ b/src/openrct2/rct1/T4Importer.cpp @@ -151,13 +151,13 @@ private: { const char* vehObjName = RCT1::GetRideTypeObject(td4Base.type); assert(vehObjName != nullptr); - std::memcpy(vehicleObject.name, vehObjName, std::min(String::SizeOf(vehObjName), (size_t)8)); + std::memcpy(vehicleObject.name, vehObjName, std::min(String::SizeOf(vehObjName), static_cast(8))); } else { const char* vehObjName = RCT1::GetVehicleObject(td4Base.vehicle_type); assert(vehObjName != nullptr); - std::memcpy(vehicleObject.name, vehObjName, std::min(String::SizeOf(vehObjName), (size_t)8)); + std::memcpy(vehicleObject.name, vehObjName, std::min(String::SizeOf(vehObjName), static_cast(8))); } std::memcpy(&td->vehicle_object, &vehicleObject, sizeof(rct_object_entry)); td->vehicle_type = td4Base.vehicle_type; diff --git a/src/openrct2/rct12/RCT12.h b/src/openrct2/rct12/RCT12.h index db7760fad0..db97fe8fc8 100644 --- a/src/openrct2/rct12/RCT12.h +++ b/src/openrct2/rct12/RCT12.h @@ -277,7 +277,7 @@ struct RCT12TileElement : public RCT12TileElementBase template TType* as() const { // TODO: CAST-IMPROVEMENT-NEEDED - return (RCT12TileElementType)GetType() == TClass ? (TType*)this : nullptr; + return static_cast(GetType()) == TClass ? (TType*)this : nullptr; } RCT12SurfaceElement* AsSurface() const diff --git a/src/openrct2/readme.md b/src/openrct2/readme.md index eba844d379..82f121ed75 100644 --- a/src/openrct2/readme.md +++ b/src/openrct2/readme.md @@ -91,4 +91,3 @@ - **world** World objects and mechanics such as the climate, landscape, sprites and park. - \ No newline at end of file diff --git a/src/openrct2/ride/Vehicle.cpp b/src/openrct2/ride/Vehicle.cpp index 5127fd2c4f..2741d6c520 100644 --- a/src/openrct2/ride/Vehicle.cpp +++ b/src/openrct2/ride/Vehicle.cpp @@ -8275,7 +8275,7 @@ loc_6DAEB9: if (_vehicleVelocityF64E08 >= 0) { regs.bp = prev_vehicle_on_ride; - if (vehicle_update_motion_collision_detection(this, curX, curY, curZ, (uint16_t*)®s.bp)) + if (vehicle_update_motion_collision_detection(this, curX, curY, curZ, reinterpret_cast(®s.bp))) { goto loc_6DB967; } @@ -8537,7 +8537,8 @@ loc_6DBA33:; { UpdateCrossings(); - if (!vehicle_update_track_motion_backwards_get_new_track(this, trackType, curRide, (uint16_t*)®s.ax)) + if (!vehicle_update_track_motion_backwards_get_new_track( + this, trackType, curRide, reinterpret_cast(®s.ax))) { goto loc_6DBE5E; } @@ -8586,7 +8587,7 @@ loc_6DBA33:; if (_vehicleVelocityF64E08 < 0) { regs.bp = next_vehicle_on_ride; - if (vehicle_update_motion_collision_detection(this, curX, curY, curZ, (uint16_t*)®s.bp)) + if (vehicle_update_motion_collision_detection(this, curX, curY, curZ, reinterpret_cast(®s.bp))) { goto loc_6DBE7F; } @@ -8920,7 +8921,7 @@ loc_6DC743: } } } - vehicle->mini_golf_current_animation = (uint8_t)z; + vehicle->mini_golf_current_animation = static_cast(z); vehicle->animation_frame = 0; vehicle->track_progress++; break; diff --git a/src/openrct2/scenario/ScenarioSources.cpp b/src/openrct2/scenario/ScenarioSources.cpp index 85ddad138e..04bca4c26f 100644 --- a/src/openrct2/scenario/ScenarioSources.cpp +++ b/src/openrct2/scenario/ScenarioSources.cpp @@ -346,7 +346,7 @@ namespace ScenarioSources { outDesc->title = desc->Title; outDesc->id = desc->Id; - outDesc->source = (uint8_t)i; + outDesc->source = static_cast(i); outDesc->index = currentIndex; outDesc->category = desc->Category; return true; diff --git a/src/openrct2/windows/_legacy.cpp b/src/openrct2/windows/_legacy.cpp index 8057474e17..0becb1a2e5 100644 --- a/src/openrct2/windows/_legacy.cpp +++ b/src/openrct2/windows/_legacy.cpp @@ -314,7 +314,7 @@ bool window_ride_construction_update_state( int16_t alternativeType = AlternativeTrackTypes[trackType]; if (alternativeType > -1) { - trackType = (uint8_t)alternativeType; + trackType = static_cast(alternativeType); } liftHillAndInvertedState &= ~CONSTRUCTION_LIFT_HILL_SELECTED; } @@ -341,8 +341,8 @@ bool window_ride_construction_update_state( CoordsXY offsets = { trackCoordinates->x, trackCoordinates->y }; CoordsXY coords = { x, y }; coords += offsets.Rotate(direction_reverse(trackDirection)); - x = (uint16_t)coords.x; - y = (uint16_t)coords.y; + x = static_cast(coords.x); + y = static_cast(coords.y); } else { diff --git a/src/openrct2/world/Banner.h b/src/openrct2/world/Banner.h index 0ec6dba1e0..2daea0670f 100644 --- a/src/openrct2/world/Banner.h +++ b/src/openrct2/world/Banner.h @@ -23,7 +23,7 @@ using BannerIndex = uint16_t; constexpr uint8_t BANNER_NULL = 255; constexpr size_t MAX_BANNERS = 250; -constexpr BannerIndex BANNER_INDEX_NULL = (BannerIndex)-1; +constexpr BannerIndex BANNER_INDEX_NULL = static_cast(-1); constexpr uint8_t SCROLLING_MODE_NONE = 255; diff --git a/src/openrct2/world/Duck.cpp b/src/openrct2/world/Duck.cpp index 9cf0fbcbe1..361ebc4d4d 100644 --- a/src/openrct2/world/Duck.cpp +++ b/src/openrct2/world/Duck.cpp @@ -84,7 +84,7 @@ Duck* rct_sprite::AsDuck() Duck* result = nullptr; if (IsDuck()) { - return (Duck*)this; + return reinterpret_cast(this); } return result; } @@ -351,7 +351,7 @@ void create_duck(const CoordsXY& pos) void duck_update(Duck* duck) { - switch ((DUCK_STATE)duck->state) + switch (static_cast(duck->state)) { case DUCK_STATE::FLY_TO_WATER: duck->UpdateFlyToWater(); diff --git a/src/openrct2/world/Footpath.h b/src/openrct2/world/Footpath.h index 39d4340620..696cfc14d7 100644 --- a/src/openrct2/world/Footpath.h +++ b/src/openrct2/world/Footpath.h @@ -28,10 +28,10 @@ constexpr auto PATH_CLEARANCE = 4 * COORDS_Z_STEP; #define FOOTPATH_ELEMENT_INSERT_QUEUE 0x80 using PathSurfaceIndex = uint16_t; -constexpr PathSurfaceIndex PATH_SURFACE_INDEX_NULL = (PathSurfaceIndex)-1; +constexpr PathSurfaceIndex PATH_SURFACE_INDEX_NULL = static_cast(-1); using PathRailingsIndex = uint8_t; -constexpr PathRailingsIndex PATH_RAILINGS_INDEX_NULL = (PathRailingsIndex)-1; +constexpr PathRailingsIndex PATH_RAILINGS_INDEX_NULL = static_cast(-1); enum class RailingEntrySupportType : uint8_t { diff --git a/src/openrct2/world/Map.cpp b/src/openrct2/world/Map.cpp index d3bc27371d..07519cbc33 100644 --- a/src/openrct2/world/Map.cpp +++ b/src/openrct2/world/Map.cpp @@ -1076,8 +1076,8 @@ void map_reorganise_elements() { context_setcurrentcursor(CURSOR_ZZZ); - TileElement* new_tile_elements = (TileElement*)malloc( - 3 * (MAXIMUM_MAP_SIZE_TECHNICAL * MAXIMUM_MAP_SIZE_TECHNICAL) * sizeof(TileElement)); + TileElement* new_tile_elements = static_cast( + malloc(3 * (MAXIMUM_MAP_SIZE_TECHNICAL * MAXIMUM_MAP_SIZE_TECHNICAL) * sizeof(TileElement))); TileElement* new_elements_pointer = new_tile_elements; if (new_tile_elements == nullptr) diff --git a/src/openrct2/world/Sprite.cpp b/src/openrct2/world/Sprite.cpp index 2543ffda39..3b7b2ba9f0 100644 --- a/src/openrct2/world/Sprite.cpp +++ b/src/openrct2/world/Sprite.cpp @@ -1088,7 +1088,7 @@ int32_t check_for_sprite_list_cycles(bool fix) // Now re-add remainder of the cycle back to list, safely. // Add each sprite to the list until we encounter one that is already part of the list. - while (!index_is_in_list(cycle_next, (SPRITE_LIST)i)) + while (!index_is_in_list(cycle_next, static_cast(i))) { rct_sprite* spr = get_sprite(cycle_next); @@ -1166,7 +1166,7 @@ int32_t check_for_spatial_index_cycles(bool fix) // Now re-add remainder of the cycle back to list, safely. // Add each sprite to the list until we encounter one that is already part of the list. - while (!index_is_in_list(cycle_next, (SPRITE_LIST)i)) + while (!index_is_in_list(cycle_next, static_cast(i))) { rct_sprite* spr = get_sprite(cycle_next); diff --git a/src/openrct2/world/TileElement.h b/src/openrct2/world/TileElement.h index 36c712627c..a200ffaee5 100644 --- a/src/openrct2/world/TileElement.h +++ b/src/openrct2/world/TileElement.h @@ -104,7 +104,7 @@ struct TileElement : public TileElementBase template TType* as() const { // TODO: CAST-IMPROVEMENT-NEEDED - return (TileElementType)GetType() == TClass ? (TType*)this : nullptr; + return static_cast(GetType()) == TClass ? (TType*)this : nullptr; } public: diff --git a/src/openrct2/world/TileInspector.cpp b/src/openrct2/world/TileInspector.cpp index 0ba76cde29..0e309e0768 100644 --- a/src/openrct2/world/TileInspector.cpp +++ b/src/openrct2/world/TileInspector.cpp @@ -761,8 +761,8 @@ GameActionResult::Ptr tile_inspector_wall_animation_frame_offset( map_invalidate_tile_full(loc); rct_window* const tileInspectorWindow = window_find_by_class(WC_TILE_INSPECTOR); - if (tileInspectorWindow != nullptr && (uint32_t)(loc.x / 32) == windowTileInspectorTileX - && (uint32_t)(loc.y / 32) == windowTileInspectorTileY) + if (tileInspectorWindow != nullptr && static_cast(loc.x / 32) == windowTileInspectorTileX + && static_cast(loc.y / 32) == windowTileInspectorTileY) { tileInspectorWindow->Invalidate(); }