diff --git a/src/openrct2-ui/input/Shortcuts.cpp b/src/openrct2-ui/input/Shortcuts.cpp index 5228a9e4f2..1736a5eda6 100644 --- a/src/openrct2-ui/input/Shortcuts.cpp +++ b/src/openrct2-ui/input/Shortcuts.cpp @@ -429,7 +429,7 @@ static void ShortcutLoadGame() { if (!(isInTrackDesignerOrManager())) { - auto loadOrQuitAction = LoadOrQuitAction(LoadOrQuitModes::OpenSavePrompt); + auto loadOrQuitAction = GameActions::LoadOrQuitAction(GameActions::LoadOrQuitModes::OpenSavePrompt); GameActions::Execute(&loadOrQuitAction); } } @@ -522,8 +522,9 @@ static void ShortcutToggleWallSlope() int32_t newSlopeValue = (currSlopeValue + 1) % 3; extern TileCoordsXY windowTileInspectorTile; - auto modifyTile = TileModifyAction( - windowTileInspectorTile.ToCoordsXY(), TileModifyType::WallSetSlope, windowTileInspectorSelectedIndex, newSlopeValue); + auto modifyTile = GameActions::TileModifyAction( + windowTileInspectorTile.ToCoordsXY(), GameActions::TileModifyType::WallSetSlope, windowTileInspectorSelectedIndex, + newSlopeValue); GameActions::Execute(&modifyTile); } @@ -609,7 +610,7 @@ static void ShortcutDecreaseElementHeight() static void ShortcutToggleClearanceChecks() { - auto cheatSetAction = CheatSetAction( + auto cheatSetAction = GameActions::CheatSetAction( CheatType::DisableClearanceChecks, getGameState().cheats.disableClearanceChecks ? 0 : 1); GameActions::Execute(&cheatSetAction); } @@ -782,7 +783,7 @@ void ShortcutManager::RegisterDefaultShortcuts() RegisterShortcut(ShortcutId::kInterfacePause, STR_SHORTCUT_PAUSE_GAME, "PAUSE", []() { if (gLegacyScene != LegacyScene::titleSequence && gLegacyScene != LegacyScene::scenarioEditor && gLegacyScene != LegacyScene::trackDesignsManager) { - auto pauseToggleAction = PauseToggleAction(); + auto pauseToggleAction = GameActions::PauseToggleAction(); GameActions::Execute(&pauseToggleAction); } }); diff --git a/src/openrct2-ui/interface/ViewportInteraction.cpp b/src/openrct2-ui/interface/ViewportInteraction.cpp index 19fee88198..599f043722 100644 --- a/src/openrct2-ui/interface/ViewportInteraction.cpp +++ b/src/openrct2-ui/interface/ViewportInteraction.cpp @@ -222,7 +222,7 @@ namespace OpenRCT2::Ui { if (GameIsNotPaused()) { - auto balloonPress = BalloonPressAction(entity->Id); + auto balloonPress = GameActions::BalloonPressAction(entity->Id); GameActions::Execute(&balloonPress); } } @@ -622,7 +622,7 @@ namespace OpenRCT2::Ui */ static void ViewportInteractionRemoveScenery(const SmallSceneryElement& smallSceneryElement, const CoordsXY& mapCoords) { - auto removeSceneryAction = SmallSceneryRemoveAction( + auto removeSceneryAction = GameActions::SmallSceneryRemoveAction( { mapCoords.x, mapCoords.y, smallSceneryElement.GetBaseZ() }, smallSceneryElement.GetSceneryQuadrant(), smallSceneryElement.GetEntryIndex()); @@ -649,7 +649,7 @@ namespace OpenRCT2::Ui { if (tileElement2->GetType() == TileElementType::Path && tileElement2->GetBaseZ() == z) { - auto action = FootpathRemoveAction({ mapCoords, z }); + auto action = GameActions::FootpathRemoveAction({ mapCoords, z }); GameActions::Execute(&action); break; } @@ -662,7 +662,8 @@ namespace OpenRCT2::Ui */ static void ViewportInteractionRemovePathAddition(const PathElement& pathElement, const CoordsXY& mapCoords) { - auto footpathAdditionRemoveAction = FootpathAdditionRemoveAction({ mapCoords.x, mapCoords.y, pathElement.GetBaseZ() }); + auto footpathAdditionRemoveAction = GameActions::FootpathAdditionRemoveAction( + { mapCoords.x, mapCoords.y, pathElement.GetBaseZ() }); GameActions::Execute(&footpathAdditionRemoveAction); } @@ -682,7 +683,8 @@ namespace OpenRCT2::Ui mapCoords -= CoordsDirectionDelta[rotation]; break; } - auto parkEntranceRemoveAction = ParkEntranceRemoveAction({ mapCoords.x, mapCoords.y, entranceElement.GetBaseZ() }); + auto parkEntranceRemoveAction = GameActions::ParkEntranceRemoveAction( + { mapCoords.x, mapCoords.y, entranceElement.GetBaseZ() }); GameActions::Execute(&parkEntranceRemoveAction); } @@ -700,7 +702,7 @@ namespace OpenRCT2::Ui else { CoordsXYZD wallLocation = { mapCoords.x, mapCoords.y, wallElement.GetBaseZ(), wallElement.GetDirection() }; - auto wallRemoveAction = WallRemoveAction(wallLocation); + auto wallRemoveAction = GameActions::WallRemoveAction(wallLocation); GameActions::Execute(&wallRemoveAction); } } @@ -720,7 +722,7 @@ namespace OpenRCT2::Ui } else { - auto removeSceneryAction = LargeSceneryRemoveAction( + auto removeSceneryAction = GameActions::LargeSceneryRemoveAction( { mapCoords.x, mapCoords.y, largeSceneryElement.GetBaseZ(), largeSceneryElement.GetDirection() }, largeSceneryElement.GetSequenceIndex()); GameActions::Execute(&removeSceneryAction); diff --git a/src/openrct2-ui/ride/Construction.cpp b/src/openrct2-ui/ride/Construction.cpp index 6ffd81805a..9a8c33adf7 100644 --- a/src/openrct2-ui/ride/Construction.cpp +++ b/src/openrct2-ui/ride/Construction.cpp @@ -229,7 +229,7 @@ namespace OpenRCT2 int32_t colour1 = RideGetRandomColourPresetIndex(listItem.Type); int32_t colour2 = RideGetUnusedPresetVehicleColour(rideEntryIndex); - auto gameAction = RideCreateAction( + auto gameAction = GameActions::RideCreateAction( listItem.Type, listItem.EntryIndex, colour1, colour2, getGameState().lastEntranceStyle); gameAction.SetCallback([](const GameAction* ga, const GameActions::Result* result) { diff --git a/src/openrct2-ui/windows/Banner.cpp b/src/openrct2-ui/windows/Banner.cpp index 6c0cef0de6..e89363fda8 100644 --- a/src/openrct2-ui/windows/Banner.cpp +++ b/src/openrct2-ui/windows/Banner.cpp @@ -202,7 +202,7 @@ namespace OpenRCT2::Ui::Windows if (bannerElement == nullptr) break; - auto bannerRemoveAction = BannerRemoveAction( + auto bannerRemoveAction = GameActions::BannerRemoveAction( { banner->position.ToCoordsXY(), bannerElement->GetBaseZ(), bannerElement->GetPosition() }); GameActions::Execute(&bannerRemoveAction); break; @@ -214,8 +214,8 @@ namespace OpenRCT2::Ui::Windows case WIDX_BANNER_NO_ENTRY: { TextinputCancel(); - auto bannerSetStyle = BannerSetStyleAction( - BannerSetStyleType::NoEntry, GetBannerIndex(), !banner->flags.has(BannerFlag::noEntry)); + auto bannerSetStyle = GameActions::BannerSetStyleAction( + GameActions::BannerSetStyleType::NoEntry, GetBannerIndex(), !banner->flags.has(BannerFlag::noEntry)); GameActions::Execute(&bannerSetStyle); break; } @@ -231,8 +231,9 @@ namespace OpenRCT2::Ui::Windows if (dropdownIndex == -1) break; - auto bannerSetStyle = BannerSetStyleAction( - BannerSetStyleType::PrimaryColour, GetBannerIndex(), ColourDropDownIndexToColour(dropdownIndex)); + auto bannerSetStyle = GameActions::BannerSetStyleAction( + GameActions::BannerSetStyleType::PrimaryColour, GetBannerIndex(), + ColourDropDownIndexToColour(dropdownIndex)); GameActions::Execute(&bannerSetStyle); break; } @@ -240,8 +241,8 @@ namespace OpenRCT2::Ui::Windows { if (dropdownIndex == -1) break; - auto bannerSetStyle = BannerSetStyleAction( - BannerSetStyleType::TextColour, GetBannerIndex(), dropdownIndex + 1); + auto bannerSetStyle = GameActions::BannerSetStyleAction( + GameActions::BannerSetStyleType::TextColour, GetBannerIndex(), dropdownIndex + 1); GameActions::Execute(&bannerSetStyle); break; } @@ -252,7 +253,7 @@ namespace OpenRCT2::Ui::Windows { if (widgetIndex == WIDX_BANNER_TEXT) { - auto bannerSetNameAction = BannerSetNameAction(GetBannerIndex(), std::string(text)); + auto bannerSetNameAction = GameActions::BannerSetNameAction(GetBannerIndex(), std::string(text)); GameActions::Execute(&bannerSetNameAction); } } diff --git a/src/openrct2-ui/windows/Cheats.cpp b/src/openrct2-ui/windows/Cheats.cpp index 03d3f1b5fa..fcd4650acf 100644 --- a/src/openrct2-ui/windows/Cheats.cpp +++ b/src/openrct2-ui/windows/Cheats.cpp @@ -916,14 +916,15 @@ static StringId window_cheats_page_titles[] = { break; case WIDX_DATE_SET: { - auto setDateAction = ParkSetDateAction(_yearSpinnerValue - 1, _monthSpinnerValue - 1, _daySpinnerValue - 1); + auto setDateAction = GameActions::ParkSetDateAction( + _yearSpinnerValue - 1, _monthSpinnerValue - 1, _daySpinnerValue - 1); GameActions::Execute(&setDateAction); windowMgr->InvalidateByClass(WindowClass::BottomToolbar); break; } case WIDX_DATE_RESET: { - auto setDateAction = ParkSetDateAction(0, 0, 0); + auto setDateAction = GameActions::ParkSetDateAction(0, 0, 0); GameActions::Execute(&setDateAction); windowMgr->InvalidateByClass(WindowClass::BottomToolbar); InvalidateWidget(WIDX_YEAR_BOX); @@ -965,7 +966,8 @@ static StringId window_cheats_page_titles[] = { InvalidateWidget(WIDX_PARK_RATING_SPINNER); if (Park::GetForcedRating() >= 0) { - auto cheatSetAction = CheatSetAction(CheatType::SetForcedParkRating, _parkRatingSpinnerValue); + auto cheatSetAction = GameActions::CheatSetAction( + CheatType::SetForcedParkRating, _parkRatingSpinnerValue); GameActions::Execute(&cheatSetAction); } break; diff --git a/src/openrct2-ui/windows/DemolishRidePrompt.cpp b/src/openrct2-ui/windows/DemolishRidePrompt.cpp index 20f3c47afb..c7d63832e4 100644 --- a/src/openrct2-ui/windows/DemolishRidePrompt.cpp +++ b/src/openrct2-ui/windows/DemolishRidePrompt.cpp @@ -62,7 +62,7 @@ namespace OpenRCT2::Ui::Windows { case WIDX_DEMOLISH: { - auto gameAction = RideDemolishAction(rideId, RideModifyType::demolish); + auto gameAction = GameActions::RideDemolishAction(rideId, GameActions::RideModifyType::demolish); GameActions::Execute(&gameAction); break; } diff --git a/src/openrct2-ui/windows/EditorParkEntrance.cpp b/src/openrct2-ui/windows/EditorParkEntrance.cpp index f07a362745..907277dbd3 100644 --- a/src/openrct2-ui/windows/EditorParkEntrance.cpp +++ b/src/openrct2-ui/windows/EditorParkEntrance.cpp @@ -194,7 +194,8 @@ namespace OpenRCT2::Ui::Windows ParkEntranceRemoveGhost(); - auto gameAction = ParkEntrancePlaceAction(parkEntrancePosition, gFootpathSelectedId, _selectedEntranceType); + auto gameAction = GameActions::ParkEntrancePlaceAction( + parkEntrancePosition, gFootpathSelectedId, _selectedEntranceType); gameAction.SetFlags(GAME_COMMAND_FLAG_GHOST); auto result = GameActions::Execute(&gameAction); @@ -212,7 +213,8 @@ namespace OpenRCT2::Ui::Windows CoordsXYZD parkEntrancePosition = PlaceParkEntranceGetMapPosition(screenCoords); if (!parkEntrancePosition.IsNull()) { - auto gameAction = ParkEntrancePlaceAction(parkEntrancePosition, gFootpathSelectedId, _selectedEntranceType); + auto gameAction = GameActions::ParkEntrancePlaceAction( + parkEntrancePosition, gFootpathSelectedId, _selectedEntranceType); auto result = GameActions::Execute(&gameAction); if (result.Error == GameActions::Status::Ok) { diff --git a/src/openrct2-ui/windows/EditorScenarioOptions.cpp b/src/openrct2-ui/windows/EditorScenarioOptions.cpp index 64f4f4587c..5269c3b0d9 100644 --- a/src/openrct2-ui/windows/EditorScenarioOptions.cpp +++ b/src/openrct2-ui/windows/EditorScenarioOptions.cpp @@ -1345,7 +1345,7 @@ namespace OpenRCT2::Ui::Windows { case WIDX_PARK_NAME: { - auto action = ParkSetNameAction(std::string(text)); + auto action = GameActions::ParkSetNameAction(std::string(text)); GameActions::Execute(&action); if (scenarioOptions.name.empty()) diff --git a/src/openrct2-ui/windows/Finances.cpp b/src/openrct2-ui/windows/Finances.cpp index bf9ad4fd36..93767afa31 100644 --- a/src/openrct2-ui/windows/Finances.cpp +++ b/src/openrct2-ui/windows/Finances.cpp @@ -14,7 +14,6 @@ #include #include #include -#include #include #include #include @@ -548,7 +547,7 @@ namespace OpenRCT2::Ui::Windows { newLoan = std::min(gameState.park.maxBankLoan, newLoan); } - auto gameAction = ParkSetLoanAction(newLoan); + auto gameAction = GameActions::ParkSetLoanAction(newLoan); GameActions::Execute(&gameAction); break; } @@ -564,7 +563,7 @@ namespace OpenRCT2::Ui::Windows { newLoan = std::max(static_cast(0LL), newLoan); } - auto gameAction = ParkSetLoanAction(newLoan); + auto gameAction = GameActions::ParkSetLoanAction(newLoan); GameActions::Execute(&gameAction); } break; diff --git a/src/openrct2-ui/windows/Footpath.cpp b/src/openrct2-ui/windows/Footpath.cpp index 2b38d50a4f..963c4f2606 100644 --- a/src/openrct2-ui/windows/Footpath.cpp +++ b/src/openrct2-ui/windows/Footpath.cpp @@ -1145,7 +1145,7 @@ namespace OpenRCT2::Ui::Windows auto selectedType = gFootpathSelection.GetSelectedSurface(); PathConstructFlags constructFlags = FootpathCreateConstructFlags(selectedType); - auto footpathPlaceAction = FootpathPlaceAction( + auto footpathPlaceAction = GameActions::FootpathPlaceAction( { *mapPos, baseZ }, slope, selectedType, gFootpathSelection.Railings, kInvalidDirection, constructFlags); footpathPlaceAction.SetCallback([this](const GameAction* ga, const GameActions::Result* result) { if (result->Error == GameActions::Status::Ok) @@ -1237,7 +1237,7 @@ namespace OpenRCT2::Ui::Windows PathConstructFlags constructFlags = FootpathCreateConstructFlags(type); - auto footpathPlaceAction = FootpathPlaceAction( + auto footpathPlaceAction = GameActions::FootpathPlaceAction( footpathLoc, slope, type, gFootpathSelection.Railings, _footpathConstructDirection, constructFlags); footpathPlaceAction.SetCallback([footpathLoc](const GameAction* ga, const GameActions::Result* result) { @@ -1320,7 +1320,7 @@ namespace OpenRCT2::Ui::Windows } gFootpathConstructFromPosition.z = tileElement->GetBaseZ(); - auto action = FootpathRemoveAction(gFootpathConstructFromPosition); + auto action = GameActions::FootpathRemoveAction(gFootpathConstructFromPosition); GameActions::Execute(&action); // Move selection @@ -1756,7 +1756,7 @@ namespace OpenRCT2::Ui::Windows FootpathRemoveProvisional(); - auto footpathPlaceAction = FootpathPlaceAction( + auto footpathPlaceAction = GameActions::FootpathPlaceAction( footpathLoc, slope, type, railingsType, kInvalidDirection, constructFlags); footpathPlaceAction.SetFlags(GAME_COMMAND_FLAG_GHOST | GAME_COMMAND_FLAG_ALLOW_DURING_PAUSED); auto res = GameActions::Execute(&footpathPlaceAction); @@ -1814,7 +1814,7 @@ namespace OpenRCT2::Ui::Windows { _provisionalFootpath.flags.unset(ProvisionalPathFlag::placed); - auto action = FootpathRemoveAction(_provisionalFootpath.position); + auto action = GameActions::FootpathRemoveAction(_provisionalFootpath.position); action.SetFlags(GAME_COMMAND_FLAG_ALLOW_DURING_PAUSED | GAME_COMMAND_FLAG_NO_SPEND | GAME_COMMAND_FLAG_GHOST); GameActions::Execute(&action); } diff --git a/src/openrct2-ui/windows/Guest.cpp b/src/openrct2-ui/windows/Guest.cpp index a849035142..bbf8158560 100644 --- a/src/openrct2-ui/windows/Guest.cpp +++ b/src/openrct2-ui/windows/Guest.cpp @@ -651,8 +651,9 @@ namespace OpenRCT2::Ui::Windows _pickedPeepX = peep->x; CoordsXYZ nullLoc{}; nullLoc.SetNull(); - PeepPickupAction pickupAction{ PeepPickupType::Pickup, EntityId::FromUnderlying(number), nullLoc, - NetworkGetCurrentPlayerId() }; + GameActions::PeepPickupAction pickupAction{ GameActions::PeepPickupType::Pickup, + EntityId::FromUnderlying(number), nullLoc, + NetworkGetCurrentPlayerId() }; pickupAction.SetCallback([peepnum = number](const GameAction* ga, const GameActions::Result* result) { if (result->Error != GameActions::Status::Ok) return; @@ -677,7 +678,7 @@ namespace OpenRCT2::Ui::Windows { uint32_t guestFlags = peep->PeepFlags ^ PEEP_FLAGS_TRACKING; - auto guestSetFlagsAction = GuestSetFlagsAction(EntityId::FromUnderlying(number), guestFlags); + auto guestSetFlagsAction = GameActions::GuestSetFlagsAction(EntityId::FromUnderlying(number), guestFlags); GameActions::Execute(&guestSetFlagsAction); } break; @@ -961,7 +962,7 @@ namespace OpenRCT2::Ui::Windows if (text.empty()) return; std::string sText(text); - auto gameAction = GuestSetNameAction(EntityId::FromUnderlying(number), sText); + auto gameAction = GameActions::GuestSetNameAction(EntityId::FromUnderlying(number), sText); GameActions::Execute(&gameAction); } @@ -1018,10 +1019,10 @@ namespace OpenRCT2::Ui::Windows if (destCoords.IsNull()) return; - PeepPickupAction pickupAction{ PeepPickupType::Place, - EntityId::FromUnderlying(number), - { destCoords, tileElement->GetBaseZ() }, - NetworkGetCurrentPlayerId() }; + GameActions::PeepPickupAction pickupAction{ GameActions::PeepPickupType::Place, + EntityId::FromUnderlying(number), + { destCoords, tileElement->GetBaseZ() }, + NetworkGetCurrentPlayerId() }; pickupAction.SetCallback([](const GameAction* ga, const GameActions::Result* result) { if (result->Error != GameActions::Status::Ok) return; @@ -1036,9 +1037,10 @@ namespace OpenRCT2::Ui::Windows if (widgetIndex != WIDX_PICKUP) return; - PeepPickupAction pickupAction{ - PeepPickupType::Cancel, EntityId::FromUnderlying(number), { _pickedPeepX, 0, 0 }, NetworkGetCurrentPlayerId() - }; + GameActions::PeepPickupAction pickupAction{ GameActions::PeepPickupType::Cancel, + EntityId::FromUnderlying(number), + { _pickedPeepX, 0, 0 }, + NetworkGetCurrentPlayerId() }; GameActions::Execute(&pickupAction); } diff --git a/src/openrct2-ui/windows/Land.cpp b/src/openrct2-ui/windows/Land.cpp index 0f963256e1..7cb5fb0812 100644 --- a/src/openrct2-ui/windows/Land.cpp +++ b/src/openrct2-ui/windows/Land.cpp @@ -339,7 +339,7 @@ namespace OpenRCT2::Ui::Windows if (_landToolMountainMode) { - auto landSmoothAction = LandSmoothAction( + auto landSmoothAction = GameActions::LandSmoothAction( { centreX, centreY }, { gMapSelectPositionA.x, gMapSelectPositionA.y, gMapSelectPositionB.x, gMapSelectPositionB.y }, gMapSelectType, false); @@ -348,7 +348,7 @@ namespace OpenRCT2::Ui::Windows return res.Error == GameActions::Status::Ok ? res.Cost : kMoney64Undefined; } - auto landRaiseAction = LandRaiseAction( + auto landRaiseAction = GameActions::LandRaiseAction( { centreX, centreY }, { gMapSelectPositionA.x, gMapSelectPositionA.y, gMapSelectPositionB.x, gMapSelectPositionB.y }, gMapSelectType); auto res = (flag & GAME_COMMAND_FLAG_APPLY) ? GameActions::Execute(&landRaiseAction) @@ -370,7 +370,7 @@ namespace OpenRCT2::Ui::Windows if (_landToolMountainMode) { - auto landSmoothAction = LandSmoothAction( + auto landSmoothAction = GameActions::LandSmoothAction( { centreX, centreY }, { gMapSelectPositionA.x, gMapSelectPositionA.y, gMapSelectPositionB.x, gMapSelectPositionB.y }, gMapSelectType, true); @@ -379,7 +379,7 @@ namespace OpenRCT2::Ui::Windows return res.Error == GameActions::Status::Ok ? res.Cost : kMoney64Undefined; } - auto landLowerAction = LandLowerAction( + auto landLowerAction = GameActions::LandLowerAction( { centreX, centreY }, { gMapSelectPositionA.x, gMapSelectPositionA.y, gMapSelectPositionB.x, gMapSelectPositionB.y }, gMapSelectType); auto res = (flag & GAME_COMMAND_FLAG_APPLY) ? GameActions::Execute(&landLowerAction) @@ -521,7 +521,7 @@ namespace OpenRCT2::Ui::Windows case WIDX_BACKGROUND: if (gMapSelectFlags & MAP_SELECT_FLAG_ENABLE) { - auto surfaceSetStyleAction = SurfaceSetStyleAction( + auto surfaceSetStyleAction = GameActions::SurfaceSetStyleAction( { gMapSelectPositionA.x, gMapSelectPositionA.y, gMapSelectPositionB.x, gMapSelectPositionB.y }, gLandToolTerrainSurface, gLandToolTerrainEdge); @@ -548,7 +548,7 @@ namespace OpenRCT2::Ui::Windows { if (gMapSelectFlags & MAP_SELECT_FLAG_ENABLE) { - auto surfaceSetStyleAction = SurfaceSetStyleAction( + auto surfaceSetStyleAction = GameActions::SurfaceSetStyleAction( { gMapSelectPositionA.x, gMapSelectPositionA.y, gMapSelectPositionB.x, gMapSelectPositionB.y }, gLandToolTerrainSurface, gLandToolTerrainEdge); diff --git a/src/openrct2-ui/windows/LandRights.cpp b/src/openrct2-ui/windows/LandRights.cpp index 7359cf747d..a82fcc6e9b 100644 --- a/src/openrct2-ui/windows/LandRights.cpp +++ b/src/openrct2-ui/windows/LandRights.cpp @@ -421,12 +421,12 @@ namespace OpenRCT2::Ui::Windows } } - LandBuyRightsAction GetLandBuyAction() + GameActions::LandBuyRightsAction GetLandBuyAction() { - auto mode = (_landRightsMode == LandRightsMode::BuyLand) ? LandBuyRightSetting::BuyLand - : LandBuyRightSetting::BuyConstructionRights; + auto mode = (_landRightsMode == LandRightsMode::BuyLand) ? GameActions::LandBuyRightSetting::BuyLand + : GameActions::LandBuyRightSetting::BuyConstructionRights; - return LandBuyRightsAction( + return GameActions::LandBuyRightsAction( { gMapSelectPositionA.x, gMapSelectPositionA.y, gMapSelectPositionB.x, gMapSelectPositionB.y }, mode); } @@ -448,11 +448,11 @@ namespace OpenRCT2::Ui::Windows } } - LandSetRightsAction GetLandSetAction() + GameActions::LandSetRightsAction GetLandSetAction() { - return LandSetRightsAction( + return GameActions::LandSetRightsAction( { gMapSelectPositionA.x, gMapSelectPositionA.y, gMapSelectPositionB.x, gMapSelectPositionB.y }, - LandSetRightSetting::SetOwnershipWithChecks, GetDesiredOwnership()); + GameActions::LandSetRightSetting::SetOwnershipWithChecks, GetDesiredOwnership()); } void OnToolUpdate(WidgetIndex widgetIndex, const ScreenCoordsXY& screenCoords) override diff --git a/src/openrct2-ui/windows/Map.cpp b/src/openrct2-ui/windows/Map.cpp index 25e0a10a2d..e6fcde4dad 100644 --- a/src/openrct2-ui/windows/Map.cpp +++ b/src/openrct2-ui/windows/Map.cpp @@ -481,7 +481,7 @@ namespace OpenRCT2::Ui::Windows int32_t mapZ = tileElement->GetBaseZ(); - auto gameAction = PeepSpawnPlaceAction({ mapCoords, mapZ, static_cast(direction) }); + auto gameAction = GameActions::PeepSpawnPlaceAction({ mapCoords, mapZ, static_cast(direction) }); auto result = GameActions::Execute(&gameAction); if (result.Error == GameActions::Status::Ok) { @@ -515,7 +515,7 @@ namespace OpenRCT2::Ui::Windows if (_resizeDirection != ResizeDirection::Y) newMapSize.x = size; - auto mapChangeSizeAction = MapChangeSizeAction(newMapSize); + auto mapChangeSizeAction = GameActions::MapChangeSizeAction(newMapSize); GameActions::Execute(&mapChangeSizeAction); Invalidate(); } @@ -763,7 +763,7 @@ namespace OpenRCT2::Ui::Windows if (IsWidgetPressed(WIDX_MAP_SIZE_LINK) || _resizeDirection == ResizeDirection::X) newMapSize.x++; - auto increaseMapSizeAction = MapChangeSizeAction(newMapSize); + auto increaseMapSizeAction = GameActions::MapChangeSizeAction(newMapSize); GameActions::Execute(&increaseMapSizeAction); } @@ -775,7 +775,7 @@ namespace OpenRCT2::Ui::Windows if (IsWidgetPressed(WIDX_MAP_SIZE_LINK) || _resizeDirection == ResizeDirection::X) newMapSize.x--; - auto decreaseMapSizeAction = MapChangeSizeAction(newMapSize); + auto decreaseMapSizeAction = GameActions::MapChangeSizeAction(newMapSize); GameActions::Execute(&decreaseMapSizeAction); } diff --git a/src/openrct2-ui/windows/MazeConstruction.cpp b/src/openrct2-ui/windows/MazeConstruction.cpp index 39800afd1c..eafc703997 100644 --- a/src/openrct2-ui/windows/MazeConstruction.cpp +++ b/src/openrct2-ui/windows/MazeConstruction.cpp @@ -130,7 +130,7 @@ namespace OpenRCT2::Ui::Windows { if (currentRide->overallView.IsNull()) { - auto gameAction = RideDemolishAction(currentRide->id, RideModifyType::demolish); + auto gameAction = GameActions::RideDemolishAction(currentRide->id, GameActions::RideModifyType::demolish); gameAction.SetFlags(GAME_COMMAND_FLAG_ALLOW_DURING_PAUSED); GameActions::Execute(&gameAction); } @@ -355,7 +355,7 @@ namespace OpenRCT2::Ui::Windows RideId rideIndex = gRideEntranceExitPlaceRideIndex; - auto rideEntranceExitPlaceAction = RideEntranceExitPlaceAction( + auto rideEntranceExitPlaceAction = GameActions::RideEntranceExitPlaceAction( entranceOrExitCoords, DirectionReverse(entranceOrExitCoords.direction), rideIndex, gRideEntranceExitPlaceStationIndex, gRideEntranceExitPlaceType == ENTRANCE_TYPE_RIDE_EXIT); @@ -421,7 +421,7 @@ namespace OpenRCT2::Ui::Windows } const auto loc = CoordsXYZD{ x, y, z, static_cast(direction) }; - auto action = MazeSetTrackAction(loc, false, _currentRideIndex, mode); + auto action = GameActions::MazeSetTrackAction(loc, false, _currentRideIndex, mode); action.SetFlags(actionFlags); const auto res = GameActions::Execute(&action); if (res.Error != GameActions::Status::Ok) @@ -433,7 +433,7 @@ namespace OpenRCT2::Ui::Windows _currentTrackBegin.y = y; if (_rideConstructionState != RideConstructionState::MazeMove) { - OpenRCT2::Audio::Play3D(OpenRCT2::Audio::SoundId::PlaceItem, { x, y, z }); + Audio::Play3D(Audio::SoundId::PlaceItem, { x, y, z }); } } }; diff --git a/src/openrct2-ui/windows/Multiplayer.cpp b/src/openrct2-ui/windows/Multiplayer.cpp index c9bca100f3..43188d5727 100644 --- a/src/openrct2-ui/windows/Multiplayer.cpp +++ b/src/openrct2-ui/windows/Multiplayer.cpp @@ -250,13 +250,14 @@ namespace OpenRCT2::Ui::Windows { case WIDX_ADD_GROUP: { - auto networkModifyGroup = NetworkModifyGroupAction(ModifyGroupType::AddGroup); + auto networkModifyGroup = GameActions::NetworkModifyGroupAction(GameActions::ModifyGroupType::AddGroup); GameActions::Execute(&networkModifyGroup); break; } case WIDX_REMOVE_GROUP: { - auto networkModifyGroup = NetworkModifyGroupAction(ModifyGroupType::RemoveGroup, _selectedGroup); + auto networkModifyGroup = GameActions::NetworkModifyGroupAction( + GameActions::ModifyGroupType::RemoveGroup, _selectedGroup); GameActions::Execute(&networkModifyGroup); break; } @@ -480,8 +481,8 @@ namespace OpenRCT2::Ui::Windows { case WIDX_DEFAULT_GROUP_DROPDOWN: { - auto networkModifyGroup = NetworkModifyGroupAction( - ModifyGroupType::SetDefault, NetworkGetGroupID(selectedIndex)); + auto networkModifyGroup = GameActions::NetworkModifyGroupAction( + GameActions::ModifyGroupType::SetDefault, NetworkGetGroupID(selectedIndex)); GameActions::Execute(&networkModifyGroup); break; } @@ -509,7 +510,8 @@ namespace OpenRCT2::Ui::Windows if (text.empty()) return; - auto networkModifyGroup = NetworkModifyGroupAction(ModifyGroupType::SetName, _selectedGroup, std::string(text)); + auto networkModifyGroup = GameActions::NetworkModifyGroupAction( + GameActions::ModifyGroupType::SetName, _selectedGroup, std::string(text)); GameActions::Execute(&networkModifyGroup); break; } @@ -634,8 +636,9 @@ namespace OpenRCT2::Ui::Windows selected_list_item = index; Invalidate(); - auto networkModifyGroup = NetworkModifyGroupAction( - ModifyGroupType::SetPermissions, _selectedGroup, "", index, PermissionState::Toggle); + auto networkModifyGroup = GameActions::NetworkModifyGroupAction( + GameActions::ModifyGroupType::SetPermissions, _selectedGroup, "", index, + GameActions::PermissionState::Toggle); GameActions::Execute(&networkModifyGroup); break; } diff --git a/src/openrct2-ui/windows/NewCampaign.cpp b/src/openrct2-ui/windows/NewCampaign.cpp index 76de65f2f4..70ebcb21e7 100644 --- a/src/openrct2-ui/windows/NewCampaign.cpp +++ b/src/openrct2-ui/windows/NewCampaign.cpp @@ -273,7 +273,7 @@ namespace OpenRCT2::Ui::Windows break; case WIDX_START_BUTTON: { - auto gameAction = ParkMarketingAction( + auto gameAction = GameActions::ParkMarketingAction( Campaign.campaign_type, Campaign.RideId.ToUnderlying(), Campaign.no_weeks); gameAction.SetCallback([](const GameAction* ga, const GameActions::Result* result) { if (result->Error == GameActions::Status::Ok) diff --git a/src/openrct2-ui/windows/Park.cpp b/src/openrct2-ui/windows/Park.cpp index b251a4c3eb..9c962c25be 100644 --- a/src/openrct2-ui/windows/Park.cpp +++ b/src/openrct2-ui/windows/Park.cpp @@ -493,7 +493,7 @@ namespace OpenRCT2::Ui::Windows { if (widgetIndex == WIDX_RENAME && !text.empty()) { - auto action = ParkSetNameAction(std::string(text)); + auto action = GameActions::ParkSetNameAction(std::string(text)); GameActions::Execute(&action); } } @@ -818,14 +818,14 @@ namespace OpenRCT2::Ui::Windows case WIDX_INCREASE_PRICE: { const auto newFee = std::min(kMaxEntranceFee, gameState.park.entranceFee + 1.00_GBP); - auto gameAction = ParkSetEntranceFeeAction(newFee); + auto gameAction = GameActions::ParkSetEntranceFeeAction(newFee); GameActions::Execute(&gameAction); break; } case WIDX_DECREASE_PRICE: { const auto newFee = std::max(0.00_GBP, gameState.park.entranceFee - 1.00_GBP); - auto gameAction = ParkSetEntranceFeeAction(newFee); + auto gameAction = GameActions::ParkSetEntranceFeeAction(newFee); GameActions::Execute(&gameAction); break; } @@ -1040,7 +1040,7 @@ namespace OpenRCT2::Ui::Windows } money = std::clamp(money, 0.00_GBP, kMaxEntranceFee); - auto gameAction = ParkSetEntranceFeeAction(money); + auto gameAction = GameActions::ParkSetEntranceFeeAction(money); GameActions::Execute(&gameAction); } } diff --git a/src/openrct2-ui/windows/PatrolArea.cpp b/src/openrct2-ui/windows/PatrolArea.cpp index 82e842e81b..cfcaa6c851 100644 --- a/src/openrct2-ui/windows/PatrolArea.cpp +++ b/src/openrct2-ui/windows/PatrolArea.cpp @@ -206,7 +206,8 @@ namespace OpenRCT2::Ui::Windows auto staff = GetEntity(_staffId); if (staff != nullptr) { - _mode = staff->IsPatrolAreaSet(*mapTile) ? StaffSetPatrolAreaMode::Unset : StaffSetPatrolAreaMode::Set; + _mode = staff->IsPatrolAreaSet(*mapTile) ? GameActions::StaffSetPatrolAreaMode::Unset + : GameActions::StaffSetPatrolAreaMode::Set; } } @@ -219,7 +220,7 @@ namespace OpenRCT2::Ui::Windows if (staff != nullptr) { MapRange range(gMapSelectPositionA, gMapSelectPositionB); - auto staffSetPatrolAreaAction = StaffSetPatrolAreaAction(_staffId, range, _mode); + auto staffSetPatrolAreaAction = GameActions::StaffSetPatrolAreaAction(_staffId, range, _mode); GameActions::Execute(&staffSetPatrolAreaAction); } } @@ -237,7 +238,7 @@ namespace OpenRCT2::Ui::Windows private: EntityId _staffId; - StaffSetPatrolAreaMode _mode; + GameActions::StaffSetPatrolAreaMode _mode; void EnableTool() { diff --git a/src/openrct2-ui/windows/Player.cpp b/src/openrct2-ui/windows/Player.cpp index dfb8ce969d..13b59476a7 100644 --- a/src/openrct2-ui/windows/Player.cpp +++ b/src/openrct2-ui/windows/Player.cpp @@ -507,7 +507,7 @@ namespace OpenRCT2::Ui::Windows break; case WIDX_KICK: { - auto kickPlayerAction = PlayerKickAction(number); + auto kickPlayerAction = GameActions::PlayerKickAction(number); GameActions::Execute(&kickPlayerAction); } break; @@ -528,7 +528,7 @@ namespace OpenRCT2::Ui::Windows } const auto groupId = NetworkGetGroupID(dropdownIndex); const auto windowHandle = std::make_pair(classification, number); - auto playerSetGroupAction = PlayerSetGroupAction(playerId, groupId); + auto playerSetGroupAction = GameActions::PlayerSetGroupAction(playerId, groupId); playerSetGroupAction.SetCallback([windowHandle](const GameAction* ga, const GameActions::Result* result) { if (result->Error == GameActions::Status::Ok) { diff --git a/src/openrct2-ui/windows/RefurbishRidePrompt.cpp b/src/openrct2-ui/windows/RefurbishRidePrompt.cpp index 19a1b8db20..eb11f009ce 100644 --- a/src/openrct2-ui/windows/RefurbishRidePrompt.cpp +++ b/src/openrct2-ui/windows/RefurbishRidePrompt.cpp @@ -61,7 +61,7 @@ namespace OpenRCT2::Ui::Windows { case WIDX_REFURBISH: { - auto gameAction = RideDemolishAction(rideId, RideModifyType::renew); + auto gameAction = GameActions::RideDemolishAction(rideId, GameActions::RideModifyType::renew); GameActions::Execute(&gameAction); break; } diff --git a/src/openrct2-ui/windows/Research.cpp b/src/openrct2-ui/windows/Research.cpp index 8b1044a9cf..0333072253 100644 --- a/src/openrct2-ui/windows/Research.cpp +++ b/src/openrct2-ui/windows/Research.cpp @@ -506,7 +506,8 @@ namespace OpenRCT2::Ui::Windows { auto activeResearchTypes = gameState.researchPriorities; activeResearchTypes ^= 1uLL << (widgetIndex - (WIDX_TRANSPORT_RIDES + widgetOffset)); - auto gameAction = ParkSetResearchFundingAction(activeResearchTypes, gameState.researchFundingLevel); + auto gameAction = GameActions::ParkSetResearchFundingAction( + activeResearchTypes, gameState.researchFundingLevel); GameActions::Execute(&gameAction); break; } @@ -521,7 +522,7 @@ namespace OpenRCT2::Ui::Windows if (widgetIndex != (WIDX_RESEARCH_FUNDING_DROPDOWN_BUTTON + widgetOffset) || selectedIndex == -1) return; - auto gameAction = ParkSetResearchFundingAction(gameState.researchPriorities, selectedIndex); + auto gameAction = GameActions::ParkSetResearchFundingAction(gameState.researchPriorities, selectedIndex); GameActions::Execute(&gameAction); } diff --git a/src/openrct2-ui/windows/Ride.cpp b/src/openrct2-ui/windows/Ride.cpp index 1cea174705..b833319092 100644 --- a/src/openrct2-ui/windows/Ride.cpp +++ b/src/openrct2-ui/windows/Ride.cpp @@ -1671,7 +1671,7 @@ namespace OpenRCT2::Ui::Windows status = RideStatus::open; break; } - auto gameAction = RideSetStatusAction(ride->id, status); + auto gameAction = GameActions::RideSetStatusAction(ride->id, status); GameActions::Execute(&gameAction); } break; @@ -2220,7 +2220,7 @@ namespace OpenRCT2::Ui::Windows break; } } - auto gameAction = RideSetStatusAction(ride->id, status); + auto gameAction = GameActions::RideSetStatusAction(ride->id, status); GameActions::Execute(&gameAction); } break; @@ -2232,7 +2232,8 @@ namespace OpenRCT2::Ui::Windows auto rideType = _rideDropdownData[rideLabelId].RideTypeId; if (rideType < RIDE_TYPE_COUNT) { - auto rideSetSetting = RideSetSettingAction(rideId, RideSetSetting::RideType, rideType); + auto rideSetSetting = GameActions::RideSetSettingAction( + rideId, GameActions::RideSetSetting::RideType, rideType); rideSetSetting.SetCallback([](const GameAction* ga, const GameActions::Result* result) { // Reset ghost track if ride construction window is open, prevents a crash // Will get set to the correct Alternative variable during set_default_next_piece. @@ -2302,7 +2303,7 @@ namespace OpenRCT2::Ui::Windows if (ride != nullptr) { auto strText = std::string(text); - auto gameAction = RideSetNameAction(ride->id, strText); + auto gameAction = GameActions::RideSetNameAction(ride->id, strText); GameActions::Execute(&gameAction); } } @@ -3070,7 +3071,8 @@ namespace OpenRCT2::Ui::Windows uint8_t increment = ride->mode == RideMode::dodgems ? 10 : 1; SetOperatingSetting( - rideId, RideSetSetting::Operation, std::clamp(ride->operationOption + increment, minValue, maxValue)); + rideId, GameActions::RideSetSetting::Operation, + std::clamp(ride->operationOption + increment, minValue, maxValue)); } void ModeTweakDecrease() @@ -3091,7 +3093,8 @@ namespace OpenRCT2::Ui::Windows uint8_t decrement = ride->mode == RideMode::dodgems ? 10 : 1; SetOperatingSetting( - rideId, RideSetSetting::Operation, std::clamp(ride->operationOption - decrement, minValue, maxValue)); + rideId, GameActions::RideSetSetting::Operation, + std::clamp(ride->operationOption - decrement, minValue, maxValue)); } void ModeDropdown(Widget* widget) @@ -3175,23 +3178,28 @@ namespace OpenRCT2::Ui::Windows SetPage(widgetIndex - WIDX_TAB_1); break; case WIDX_LOAD_CHECKBOX: - SetOperatingSetting(rideId, RideSetSetting::Departure, ride->departFlags ^ RIDE_DEPART_WAIT_FOR_LOAD); + SetOperatingSetting( + rideId, GameActions::RideSetSetting::Departure, ride->departFlags ^ RIDE_DEPART_WAIT_FOR_LOAD); break; case WIDX_LEAVE_WHEN_ANOTHER_ARRIVES_CHECKBOX: SetOperatingSetting( - rideId, RideSetSetting::Departure, ride->departFlags ^ RIDE_DEPART_LEAVE_WHEN_ANOTHER_ARRIVES); + rideId, GameActions::RideSetSetting::Departure, + ride->departFlags ^ RIDE_DEPART_LEAVE_WHEN_ANOTHER_ARRIVES); break; case WIDX_MINIMUM_LENGTH_CHECKBOX: SetOperatingSetting( - rideId, RideSetSetting::Departure, ride->departFlags ^ RIDE_DEPART_WAIT_FOR_MINIMUM_LENGTH); + rideId, GameActions::RideSetSetting::Departure, + ride->departFlags ^ RIDE_DEPART_WAIT_FOR_MINIMUM_LENGTH); break; case WIDX_MAXIMUM_LENGTH_CHECKBOX: SetOperatingSetting( - rideId, RideSetSetting::Departure, ride->departFlags ^ RIDE_DEPART_WAIT_FOR_MAXIMUM_LENGTH); + rideId, GameActions::RideSetSetting::Departure, + ride->departFlags ^ RIDE_DEPART_WAIT_FOR_MAXIMUM_LENGTH); break; case WIDX_SYNCHRONISE_WITH_ADJACENT_STATIONS_CHECKBOX: SetOperatingSetting( - rideId, RideSetSetting::Departure, ride->departFlags ^ RIDE_DEPART_SYNCHRONISE_WITH_ADJACENT_STATIONS); + rideId, GameActions::RideSetSetting::Departure, + ride->departFlags ^ RIDE_DEPART_SYNCHRONISE_WITH_ADJACENT_STATIONS); break; } } @@ -3228,7 +3236,7 @@ namespace OpenRCT2::Ui::Windows ? 0 : ride->getRideTypeDescriptor().LiftData.minimum_speed; SetOperatingSetting( - rideId, RideSetSetting::LiftHillSpeed, + rideId, GameActions::RideSetSetting::LiftHillSpeed, std::clamp(ride->liftHillSpeed + 1, lowerBound, upperBound)); break; case WIDX_LIFT_HILL_SPEED_DECREASE: @@ -3239,7 +3247,7 @@ namespace OpenRCT2::Ui::Windows ? 0 : ride->getRideTypeDescriptor().LiftData.minimum_speed; SetOperatingSetting( - rideId, RideSetSetting::LiftHillSpeed, + rideId, GameActions::RideSetSetting::LiftHillSpeed, std::clamp(ride->liftHillSpeed - 1, lowerBound, upperBound)); break; case WIDX_MINIMUM_LENGTH: @@ -3252,28 +3260,28 @@ namespace OpenRCT2::Ui::Windows upperBound = OpenRCT2::Limits::kMaxWaitingTime; lowerBound = 0; SetOperatingSetting( - rideId, RideSetSetting::MinWaitingTime, + rideId, GameActions::RideSetSetting::MinWaitingTime, std::clamp(ride->minWaitingTime + 1, lowerBound, upperBound)); break; case WIDX_MINIMUM_LENGTH_DECREASE: upperBound = OpenRCT2::Limits::kMaxWaitingTime; lowerBound = 0; SetOperatingSetting( - rideId, RideSetSetting::MinWaitingTime, + rideId, GameActions::RideSetSetting::MinWaitingTime, std::clamp(ride->minWaitingTime - 1, lowerBound, upperBound)); break; case WIDX_MAXIMUM_LENGTH_INCREASE: upperBound = OpenRCT2::Limits::kMaxWaitingTime; lowerBound = 0; SetOperatingSetting( - rideId, RideSetSetting::MaxWaitingTime, + rideId, GameActions::RideSetSetting::MaxWaitingTime, std::clamp(ride->maxWaitingTime + 1, lowerBound, upperBound)); break; case WIDX_MAXIMUM_LENGTH_DECREASE: upperBound = OpenRCT2::Limits::kMaxWaitingTime; lowerBound = 0; SetOperatingSetting( - rideId, RideSetSetting::MaxWaitingTime, + rideId, GameActions::RideSetSetting::MaxWaitingTime, std::clamp(ride->maxWaitingTime - 1, lowerBound, upperBound)); break; case WIDX_MODE_DROPDOWN: @@ -3287,7 +3295,7 @@ namespace OpenRCT2::Ui::Windows : OpenRCT2::Limits::kMaxCircuitsPerRide; lowerBound = 1; SetOperatingSetting( - rideId, RideSetSetting::NumCircuits, + rideId, GameActions::RideSetSetting::NumCircuits, std::clamp(ride->numCircuits + 1, lowerBound, upperBound)); break; case WIDX_OPERATE_NUMBER_OF_CIRCUITS_DECREASE: @@ -3295,7 +3303,7 @@ namespace OpenRCT2::Ui::Windows : OpenRCT2::Limits::kMaxCircuitsPerRide; lowerBound = 1; SetOperatingSetting( - rideId, RideSetSetting::NumCircuits, + rideId, GameActions::RideSetSetting::NumCircuits, std::clamp(ride->numCircuits - 1, lowerBound, upperBound)); break; } @@ -3381,12 +3389,12 @@ namespace OpenRCT2::Ui::Windows } } if (rideMode != RideMode::nullMode) - SetOperatingSetting(rideId, RideSetSetting::Mode, static_cast(rideMode)); + SetOperatingSetting(rideId, GameActions::RideSetSetting::Mode, static_cast(rideMode)); break; } case WIDX_LOAD_DROPDOWN: SetOperatingSetting( - rideId, RideSetSetting::Departure, + rideId, GameActions::RideSetSetting::Departure, (ride->departFlags & ~RIDE_DEPART_WAIT_FOR_LOAD_MASK) | dropdownIndex); break; } @@ -3428,7 +3436,7 @@ namespace OpenRCT2::Ui::Windows { uint32_t origSize = std::stol(std::string(text)) / multiplier; uint8_t size = static_cast(std::clamp(origSize, minValue, maxValue)); - SetOperatingSetting(ride->id, RideSetSetting::Operation, size); + SetOperatingSetting(ride->id, GameActions::RideSetSetting::Operation, size); } catch (const std::logic_error&) { @@ -3439,8 +3447,8 @@ namespace OpenRCT2::Ui::Windows { try { - auto rideSetSetting = widgetIndex == WIDX_MINIMUM_LENGTH ? RideSetSetting::MinWaitingTime - : RideSetSetting::MaxWaitingTime; + auto rideSetSetting = widgetIndex == WIDX_MINIMUM_LENGTH ? GameActions::RideSetSetting::MinWaitingTime + : GameActions::RideSetSetting::MaxWaitingTime; uint16_t upperBound = OpenRCT2::Limits::kMaxWaitingTime; uint16_t lowerBound = 0; @@ -3886,7 +3894,7 @@ namespace OpenRCT2::Ui::Windows switch (widgetIndex) { case WIDX_INSPECTION_INTERVAL_DROPDOWN: - SetOperatingSetting(rideId, RideSetSetting::InspectionInterval, dropdownIndex); + SetOperatingSetting(rideId, GameActions::RideSetSetting::InspectionInterval, dropdownIndex); break; case WIDX_FORCE_BREAKDOWN: @@ -4188,7 +4196,7 @@ namespace OpenRCT2::Ui::Windows auto z = info.Element->GetBaseZ(); auto direction = info.Element->GetDirection(); - auto gameAction = RideSetColourSchemeAction( + auto gameAction = GameActions::RideSetColourSchemeAction( CoordsXYZD{ info.Loc, z, static_cast(direction) }, info.Element->AsTrack()->GetTrackType(), newColourScheme); GameActions::Execute(&gameAction); @@ -4228,8 +4236,8 @@ namespace OpenRCT2::Ui::Windows if (ride != nullptr) { const bool currentlyEnabled = ride->hasLifecycleFlag(RIDE_LIFECYCLE_RANDOM_SHOP_COLOURS); - auto rideSetAppearanceAction = RideSetAppearanceAction( - rideId, RideSetAppearanceType::SellingItemColourIsRandom, currentlyEnabled ? 0 : 1, 0); + auto rideSetAppearanceAction = GameActions::RideSetAppearanceAction( + rideId, GameActions::RideSetAppearanceType::SellingItemColourIsRandom, currentlyEnabled ? 0 : 1, 0); GameActions::Execute(&rideSetAppearanceAction); } break; @@ -4270,24 +4278,24 @@ namespace OpenRCT2::Ui::Windows if (allowChangingBodyColour) { colour_t colour = UtilRand() % kColourNumNormal; - auto vehicleSetBodyColourAction = RideSetAppearanceAction( - rideId, RideSetAppearanceType::VehicleColourBody, colour, i); + auto vehicleSetBodyColourAction = GameActions::RideSetAppearanceAction( + rideId, GameActions::RideSetAppearanceType::VehicleColourBody, colour, i); GameActions::Execute(&vehicleSetBodyColourAction); } if (allowChangingTrimColour) { colour_t colour = UtilRand() % kColourNumNormal; - auto vehicleSetTrimColourAction = RideSetAppearanceAction( - rideId, RideSetAppearanceType::VehicleColourTrim, colour, i); + auto vehicleSetTrimColourAction = GameActions::RideSetAppearanceAction( + rideId, GameActions::RideSetAppearanceType::VehicleColourTrim, colour, i); GameActions::Execute(&vehicleSetTrimColourAction); } if (allowChangingTertiaryColour) { colour_t colour = UtilRand() % kColourNumNormal; - auto vehicleSetTertiaryColourAction = RideSetAppearanceAction( - rideId, RideSetAppearanceType::VehicleColourTertiary, colour, i); + auto vehicleSetTertiaryColourAction = GameActions::RideSetAppearanceAction( + rideId, GameActions::RideSetAppearanceType::VehicleColourTertiary, colour, i); GameActions::Execute(&vehicleSetTertiaryColourAction); } } @@ -4457,32 +4465,32 @@ namespace OpenRCT2::Ui::Windows break; case WIDX_TRACK_MAIN_COLOUR: { - auto rideSetAppearanceAction = RideSetAppearanceAction( - rideId, RideSetAppearanceType::TrackColourMain, ColourDropDownIndexToColour(dropdownIndex), + auto rideSetAppearanceAction = GameActions::RideSetAppearanceAction( + rideId, GameActions::RideSetAppearanceType::TrackColourMain, ColourDropDownIndexToColour(dropdownIndex), _rideColour); GameActions::Execute(&rideSetAppearanceAction); } break; case WIDX_TRACK_ADDITIONAL_COLOUR: { - auto rideSetAppearanceAction = RideSetAppearanceAction( - rideId, RideSetAppearanceType::TrackColourAdditional, ColourDropDownIndexToColour(dropdownIndex), - _rideColour); + auto rideSetAppearanceAction = GameActions::RideSetAppearanceAction( + rideId, GameActions::RideSetAppearanceType::TrackColourAdditional, + ColourDropDownIndexToColour(dropdownIndex), _rideColour); GameActions::Execute(&rideSetAppearanceAction); } break; case WIDX_TRACK_SUPPORT_COLOUR: { - auto rideSetAppearanceAction = RideSetAppearanceAction( - rideId, RideSetAppearanceType::TrackColourSupports, ColourDropDownIndexToColour(dropdownIndex), - _rideColour); + auto rideSetAppearanceAction = GameActions::RideSetAppearanceAction( + rideId, GameActions::RideSetAppearanceType::TrackColourSupports, + ColourDropDownIndexToColour(dropdownIndex), _rideColour); GameActions::Execute(&rideSetAppearanceAction); } break; case WIDX_MAZE_STYLE_DROPDOWN: { - auto rideSetAppearanceAction = RideSetAppearanceAction( - rideId, RideSetAppearanceType::MazeStyle, dropdownIndex, _rideColour); + auto rideSetAppearanceAction = GameActions::RideSetAppearanceAction( + rideId, GameActions::RideSetAppearanceType::MazeStyle, dropdownIndex, _rideColour); GameActions::Execute(&rideSetAppearanceAction); } break; @@ -4493,8 +4501,8 @@ namespace OpenRCT2::Ui::Windows break; } auto objIndex = _entranceDropdownData[dropdownIndex].EntranceTypeId; - auto rideSetAppearanceAction = RideSetAppearanceAction( - rideId, RideSetAppearanceType::EntranceStyle, objIndex, 0); + auto rideSetAppearanceAction = GameActions::RideSetAppearanceAction( + rideId, GameActions::RideSetAppearanceType::EntranceStyle, objIndex, 0); rideSetAppearanceAction.SetCallback([objIndex](const GameAction*, const GameActions::Result* res) { if (res->Error != GameActions::Status::Ok) return; @@ -4505,8 +4513,8 @@ namespace OpenRCT2::Ui::Windows } case WIDX_VEHICLE_COLOUR_SCHEME_DROPDOWN: { - auto rideSetAppearanceAction = RideSetAppearanceAction( - rideId, RideSetAppearanceType::VehicleColourScheme, dropdownIndex, 0); + auto rideSetAppearanceAction = GameActions::RideSetAppearanceAction( + rideId, GameActions::RideSetAppearanceType::VehicleColourScheme, dropdownIndex, 0); rideSetAppearanceAction.SetCallback([this](const GameAction* ga, const GameActions::Result* result) { if (result->Error == GameActions::Status::Ok) { @@ -4522,25 +4530,25 @@ namespace OpenRCT2::Ui::Windows break; case WIDX_VEHICLE_BODY_COLOUR: { - auto rideSetAppearanceAction = RideSetAppearanceAction( - rideId, RideSetAppearanceType::VehicleColourBody, ColourDropDownIndexToColour(dropdownIndex), - _vehicleIndex); + auto rideSetAppearanceAction = GameActions::RideSetAppearanceAction( + rideId, GameActions::RideSetAppearanceType::VehicleColourBody, + ColourDropDownIndexToColour(dropdownIndex), _vehicleIndex); GameActions::Execute(&rideSetAppearanceAction); } break; case WIDX_VEHICLE_TRIM_COLOUR: { - auto rideSetAppearanceAction = RideSetAppearanceAction( - rideId, RideSetAppearanceType::VehicleColourTrim, ColourDropDownIndexToColour(dropdownIndex), - _vehicleIndex); + auto rideSetAppearanceAction = GameActions::RideSetAppearanceAction( + rideId, GameActions::RideSetAppearanceType::VehicleColourTrim, + ColourDropDownIndexToColour(dropdownIndex), _vehicleIndex); GameActions::Execute(&rideSetAppearanceAction); } break; case WIDX_VEHICLE_TERTIARY_COLOUR: { - auto rideSetAppearanceAction = RideSetAppearanceAction( - rideId, RideSetAppearanceType::VehicleColourTertiary, ColourDropDownIndexToColour(dropdownIndex), - _vehicleIndex); + auto rideSetAppearanceAction = GameActions::RideSetAppearanceAction( + rideId, GameActions::RideSetAppearanceType::VehicleColourTertiary, + ColourDropDownIndexToColour(dropdownIndex), _vehicleIndex); GameActions::Execute(&rideSetAppearanceAction); } break; @@ -4969,7 +4977,7 @@ namespace OpenRCT2::Ui::Windows if (ride != nullptr) { int32_t activateMusic = (ride->lifecycleFlags & RIDE_LIFECYCLE_MUSIC) ? 0 : 1; - SetOperatingSetting(rideId, RideSetSetting::Music, activateMusic); + SetOperatingSetting(rideId, GameActions::RideSetSetting::Music, activateMusic); ride->windowInvalidateFlags |= RIDE_INVALIDATE_RIDE_MUSIC; } } @@ -5109,7 +5117,7 @@ namespace OpenRCT2::Ui::Windows && static_cast(dropdownIndex) < window_ride_current_music_style_order.size()) { auto musicStyle = window_ride_current_music_style_order[dropdownIndex]; - SetOperatingSetting(rideId, RideSetSetting::MusicType, musicStyle); + SetOperatingSetting(rideId, GameActions::RideSetSetting::MusicType, musicStyle); } } @@ -6250,7 +6258,7 @@ namespace OpenRCT2::Ui::Windows newFlags ^= EnumToFlag(shop_item); } - auto parkSetParameter = ParkSetParameterAction(ParkParameter::SamePriceInPark, newFlags); + auto parkSetParameter = GameActions::ParkSetParameterAction(GameActions::ParkParameter::SamePriceInPark, newFlags); GameActions::Execute(&parkSetParameter); } @@ -6283,7 +6291,7 @@ namespace OpenRCT2::Ui::Windows UpdateSamePriceThroughoutFlags(shopItem); - auto rideSetPriceAction = RideSetPriceAction(rideId, ride->price[0], true); + auto rideSetPriceAction = GameActions::RideSetPriceAction(rideId, ride->price[0], true); GameActions::Execute(&rideSetPriceAction); } @@ -6303,13 +6311,13 @@ namespace OpenRCT2::Ui::Windows UpdateSamePriceThroughoutFlags(shop_item); - auto rideSetPriceAction = RideSetPriceAction(rideId, ride->price[1], false); + auto rideSetPriceAction = GameActions::RideSetPriceAction(rideId, ride->price[1], false); GameActions::Execute(&rideSetPriceAction); } void IncomeSetPrimaryPrice(money64 price) { - auto rideSetPriceAction = RideSetPriceAction(rideId, price, true); + auto rideSetPriceAction = GameActions::RideSetPriceAction(rideId, price, true); GameActions::Execute(&rideSetPriceAction); } @@ -6356,7 +6364,7 @@ namespace OpenRCT2::Ui::Windows void IncomeSetSecondaryPrice(money64 price) { - auto rideSetPriceAction = RideSetPriceAction(rideId, price, false); + auto rideSetPriceAction = GameActions::RideSetPriceAction(rideId, price, false); GameActions::Execute(&rideSetPriceAction); } diff --git a/src/openrct2-ui/windows/RideConstruction.cpp b/src/openrct2-ui/windows/RideConstruction.cpp index ef9e2f75dc..bdbc770190 100644 --- a/src/openrct2-ui/windows/RideConstruction.cpp +++ b/src/openrct2-ui/windows/RideConstruction.cpp @@ -312,7 +312,7 @@ namespace OpenRCT2::Ui::Windows if (!_autoOpeningShop) { _autoOpeningShop = true; - auto gameAction = RideSetStatusAction(currentRide->id, RideStatus::open); + auto gameAction = GameActions::RideSetStatusAction(currentRide->id, RideStatus::open); GameActions::Execute(&gameAction); _autoOpeningShop = false; } @@ -325,7 +325,7 @@ namespace OpenRCT2::Ui::Windows } else { - auto gameAction = RideDemolishAction(currentRide->id, RideModifyType::demolish); + auto gameAction = GameActions::RideDemolishAction(currentRide->id, GameActions::RideModifyType::demolish); gameAction.SetFlags(GAME_COMMAND_FLAG_ALLOW_DURING_PAUSED); GameActions::Execute(&gameAction); } @@ -1099,7 +1099,7 @@ namespace OpenRCT2::Ui::Windows { auto status = currentRide->status == RideStatus::simulating ? RideStatus::closed : RideStatus::simulating; - auto gameAction = RideSetStatusAction(currentRide->id, status); + auto gameAction = GameActions::RideSetStatusAction(currentRide->id, status); GameActions::Execute(&gameAction); } break; @@ -2318,7 +2318,7 @@ namespace OpenRCT2::Ui::Windows return; } - auto trackPlaceAction = TrackPlaceAction( + auto trackPlaceAction = GameActions::TrackPlaceAction( rideIndex, trackType, currentRide->type, { trackPos, static_cast(trackDirection) }, properties & 0xFF, (properties >> 8) & 0x0F, (properties >> 12) & 0x0F, liftHillAndAlternativeState, false); if (_rideConstructionState == RideConstructionState::Back) @@ -2353,7 +2353,7 @@ namespace OpenRCT2::Ui::Windows _currentTrackSelectionFlags.set(TrackSelectionFlag::trackPlaceActionQueued); } - const auto resultData = res.GetData(); + const auto resultData = res.GetData(); if (resultData.GroundFlags & ELEMENT_IS_UNDERGROUND) { ViewportSetVisibility(ViewportVisibility::UndergroundViewOn); @@ -2448,7 +2448,7 @@ namespace OpenRCT2::Ui::Windows _gotoStartPlacementMode = true; } - auto trackRemoveAction = TrackRemoveAction( + auto trackRemoveAction = GameActions::TrackRemoveAction( _currentTrackPieceType, 0, { _currentTrackBegin.x, _currentTrackBegin.y, _currentTrackBegin.z, currentDirection }); @@ -2567,7 +2567,7 @@ namespace OpenRCT2::Ui::Windows &tileElement, {}) != std::nullopt) { - auto trackSetBrakeSpeed = TrackSetBrakeSpeedAction( + auto trackSetBrakeSpeed = GameActions::TrackSetBrakeSpeedAction( _currentTrackBegin, tileElement->AsTrack()->GetTrackType(), brakesSpeed); trackSetBrakeSpeed.SetCallback([](const GameAction* ga, const GameActions::Result* result) { WindowRideConstructionUpdateActiveElements(); @@ -2653,7 +2653,7 @@ namespace OpenRCT2::Ui::Windows if (gRideEntranceExitPlaceDirection == kInvalidDirection) return; - auto rideEntranceExitPlaceAction = RideEntranceExitPlaceAction( + auto rideEntranceExitPlaceAction = GameActions::RideEntranceExitPlaceAction( entranceOrExitCoords, DirectionReverse(gRideEntranceExitPlaceDirection), gRideEntranceExitPlaceRideIndex, gRideEntranceExitPlaceStationIndex, gRideEntranceExitPlaceType == ENTRANCE_TYPE_RIDE_EXIT); @@ -3700,7 +3700,7 @@ namespace OpenRCT2::Ui::Windows gDisableErrorWindowSound = true; - auto gameAction = MazeSetTrackAction( + auto gameAction = GameActions::MazeSetTrackAction( CoordsXYZD{ _currentTrackBegin, 0 }, true, _currentRideIndex, GC_SET_MAZE_TRACK_BUILD); auto mazeSetTrackResult = GameActions::Execute(&gameAction); if (mazeSetTrackResult.Error == GameActions::Status::Ok) @@ -4760,7 +4760,8 @@ namespace OpenRCT2::Ui::Windows if (rtd.specialType == RtdSpecialType::maze) { int32_t flags = GAME_COMMAND_FLAG_ALLOW_DURING_PAUSED | GAME_COMMAND_FLAG_NO_SPEND | GAME_COMMAND_FLAG_GHOST; - auto gameAction = MazeSetTrackAction(CoordsXYZD{ trackPos, 0 }, true, rideIndex, GC_SET_MAZE_TRACK_BUILD); + auto gameAction = GameActions::MazeSetTrackAction( + CoordsXYZD{ trackPos, 0 }, true, rideIndex, GC_SET_MAZE_TRACK_BUILD); gameAction.SetFlags(flags); auto result = GameActions::Execute(&gameAction); @@ -4776,7 +4777,7 @@ namespace OpenRCT2::Ui::Windows return result.Cost; } - auto trackPlaceAction = TrackPlaceAction( + auto trackPlaceAction = GameActions::TrackPlaceAction( rideIndex, trackType, ride->type, { trackPos, static_cast(trackDirection) }, 0, 0, 0, liftHillAndAlternativeState, false); trackPlaceAction.SetFlags(GAME_COMMAND_FLAG_ALLOW_DURING_PAUSED | GAME_COMMAND_FLAG_NO_SPEND | GAME_COMMAND_FLAG_GHOST); @@ -4801,7 +4802,7 @@ namespace OpenRCT2::Ui::Windows _unkF440C5 = { trackPos.x, trackPos.y, trackPos.z + zBegin, static_cast(trackDirection) }; _currentTrackSelectionFlags.set(TrackSelectionFlag::track); - const auto resultData = res.GetData(); + const auto resultData = res.GetData(); const auto visiblity = (resultData.GroundFlags & ELEMENT_IS_UNDERGROUND) ? ViewportVisibility::UndergroundViewOn : ViewportVisibility::UndergroundViewOff; ViewportSetVisibility(visiblity); @@ -5148,7 +5149,7 @@ namespace OpenRCT2::Ui::Windows }; for (const auto& quadrant : quadrants) { - auto gameAction = MazeSetTrackAction(quadrant, false, rideIndex, GC_SET_MAZE_TRACK_FILL); + auto gameAction = GameActions::MazeSetTrackAction(quadrant, false, rideIndex, GC_SET_MAZE_TRACK_FILL); gameAction.SetFlags(flags); auto res = GameActions::Execute(&gameAction); } @@ -5166,7 +5167,7 @@ namespace OpenRCT2::Ui::Windows { auto trackType = next_track.element->AsTrack()->GetTrackType(); int32_t trackSequence = next_track.element->AsTrack()->GetSequenceIndex(); - auto trackRemoveAction = TrackRemoveAction{ + auto trackRemoveAction = GameActions::TrackRemoveAction{ trackType, trackSequence, { next_track.x, next_track.y, z, static_cast(direction) } }; trackRemoveAction.SetFlags( diff --git a/src/openrct2-ui/windows/RideList.cpp b/src/openrct2-ui/windows/RideList.cpp index 2cfd4c158c..868557c532 100644 --- a/src/openrct2-ui/windows/RideList.cpp +++ b/src/openrct2-ui/windows/RideList.cpp @@ -473,7 +473,7 @@ namespace OpenRCT2::Ui::Windows const auto selectedRideId = _rideList[index].Id; if (_quickDemolishMode && NetworkGetMode() != NETWORK_MODE_CLIENT) { - auto gameAction = RideDemolishAction(selectedRideId, RideModifyType::demolish); + auto gameAction = GameActions::RideDemolishAction(selectedRideId, GameActions::RideModifyType::demolish); GameActions::Execute(&gameAction); RefreshList(); } @@ -1110,7 +1110,7 @@ namespace OpenRCT2::Ui::Windows if (rideRef.status != RideStatus::closed && rideRef.getClassification() == static_cast(page)) { - auto gameAction = RideSetStatusAction(rideRef.id, RideStatus::closed); + auto gameAction = GameActions::RideSetStatusAction(rideRef.id, RideStatus::closed); GameActions::Execute(&gameAction); } } @@ -1123,7 +1123,7 @@ namespace OpenRCT2::Ui::Windows { if (rideRef.status != RideStatus::open && rideRef.getClassification() == static_cast(page)) { - auto gameAction = RideSetStatusAction(rideRef.id, RideStatus::open); + auto gameAction = GameActions::RideSetStatusAction(rideRef.id, RideStatus::open); GameActions::Execute(&gameAction); } } diff --git a/src/openrct2-ui/windows/Scenery.cpp b/src/openrct2-ui/windows/Scenery.cpp index 47e03b4edf..ac4fe463ac 100644 --- a/src/openrct2-ui/windows/Scenery.cpp +++ b/src/openrct2-ui/windows/Scenery.cpp @@ -62,7 +62,7 @@ #include #include -using namespace OpenRCT2::Numerics; +using namespace Numerics; namespace OpenRCT2::Ui::Windows { @@ -199,7 +199,7 @@ namespace OpenRCT2::Ui::Windows const SceneryGroupEntry* GetSceneryGroupEntry() const { - return OpenRCT2::ObjectManager::GetObjectEntry(SceneryGroupIndex); + return ObjectManager::GetObjectEntry(SceneryGroupIndex); } }; @@ -329,7 +329,8 @@ namespace OpenRCT2::Ui::Windows { const auto newStatus = !IsSceneryItemRestricted(tabSelectedScenery); const auto objectType = GetObjectTypeFromSceneryType(tabSelectedScenery.SceneryType); - auto action = ScenerySetRestrictedAction(objectType, tabSelectedScenery.EntryIndex, newStatus); + auto action = GameActions::ScenerySetRestrictedAction( + objectType, tabSelectedScenery.EntryIndex, newStatus); GameActions::Execute(&action); } break; @@ -554,22 +555,22 @@ namespace OpenRCT2::Ui::Windows else if (tabSelectedScenery.SceneryType == SCENERY_TYPE_LARGE) { gCurrentToolId = static_cast( - OpenRCT2::ObjectManager::GetObjectEntry(tabSelectedScenery.EntryIndex)->tool_id); + ObjectManager::GetObjectEntry(tabSelectedScenery.EntryIndex)->tool_id); } else if (tabSelectedScenery.SceneryType == SCENERY_TYPE_WALL) { gCurrentToolId = static_cast( - OpenRCT2::ObjectManager::GetObjectEntry(tabSelectedScenery.EntryIndex)->tool_id); + ObjectManager::GetObjectEntry(tabSelectedScenery.EntryIndex)->tool_id); } else if (tabSelectedScenery.SceneryType == SCENERY_TYPE_PATH_ITEM) { gCurrentToolId = static_cast( - OpenRCT2::ObjectManager::GetObjectEntry(tabSelectedScenery.EntryIndex)->tool_id); + ObjectManager::GetObjectEntry(tabSelectedScenery.EntryIndex)->tool_id); } else { // small scenery gCurrentToolId = static_cast( - OpenRCT2::ObjectManager::GetObjectEntry(tabSelectedScenery.EntryIndex)->tool_id); + ObjectManager::GetObjectEntry(tabSelectedScenery.EntryIndex)->tool_id); } } else @@ -699,8 +700,7 @@ namespace OpenRCT2::Ui::Windows { widgets[WIDX_SCENERY_BUILD_CLUSTER_BUTTON].type = WidgetType::flatBtn; - auto* sceneryEntry = OpenRCT2::ObjectManager::GetObjectEntry( - tabSelectedScenery.EntryIndex); + auto* sceneryEntry = ObjectManager::GetObjectEntry(tabSelectedScenery.EntryIndex); if (sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_ROTATABLE)) { widgets[WIDX_SCENERY_ROTATE_OBJECTS_BUTTON].type = WidgetType::flatBtn; @@ -739,8 +739,7 @@ namespace OpenRCT2::Ui::Windows { if (tabSelectedScenery.SceneryType == SCENERY_TYPE_BANNER) { - auto* bannerEntry = OpenRCT2::ObjectManager::GetObjectEntry( - tabSelectedScenery.EntryIndex); + auto* bannerEntry = ObjectManager::GetObjectEntry(tabSelectedScenery.EntryIndex); if (bannerEntry->flags & BANNER_ENTRY_FLAG_HAS_PRIMARY_COLOUR) { widgets[WIDX_SCENERY_PRIMARY_COLOUR_BUTTON].type = WidgetType::colourBtn; @@ -748,8 +747,7 @@ namespace OpenRCT2::Ui::Windows } else if (tabSelectedScenery.SceneryType == SCENERY_TYPE_LARGE) { - auto* sceneryEntry = OpenRCT2::ObjectManager::GetObjectEntry( - tabSelectedScenery.EntryIndex); + auto* sceneryEntry = ObjectManager::GetObjectEntry(tabSelectedScenery.EntryIndex); if (sceneryEntry->flags & LARGE_SCENERY_FLAG_HAS_PRIMARY_COLOUR && !(sceneryEntry->flags & LARGE_SCENERY_FLAG_HIDE_PRIMARY_REMAP_BUTTON)) @@ -762,7 +760,7 @@ namespace OpenRCT2::Ui::Windows } else if (tabSelectedScenery.SceneryType == SCENERY_TYPE_WALL) { - auto* wallEntry = OpenRCT2::ObjectManager::GetObjectEntry(tabSelectedScenery.EntryIndex); + auto* wallEntry = ObjectManager::GetObjectEntry(tabSelectedScenery.EntryIndex); if (wallEntry->flags & (WALL_SCENERY_HAS_PRIMARY_COLOUR | WALL_SCENERY_HAS_GLASS)) { widgets[WIDX_SCENERY_PRIMARY_COLOUR_BUTTON].type = WidgetType::colourBtn; @@ -780,8 +778,7 @@ namespace OpenRCT2::Ui::Windows } else if (tabSelectedScenery.SceneryType == SCENERY_TYPE_SMALL) { - auto* sceneryEntry = OpenRCT2::ObjectManager::GetObjectEntry( - tabSelectedScenery.EntryIndex); + auto* sceneryEntry = ObjectManager::GetObjectEntry(tabSelectedScenery.EntryIndex); if (sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_HAS_PRIMARY_COLOUR | SMALL_SCENERY_FLAG_HAS_GLASS)) { @@ -978,7 +975,7 @@ namespace OpenRCT2::Ui::Windows gWindowSceneryRotation = rotation.value(); } gWindowSceneryEyedropperEnabled = false; - OpenRCT2::Audio::Play(OpenRCT2::Audio::SoundId::Click1, 0, ContextGetWidth() / 2); + Audio::Play(Audio::SoundId::Click1, 0, ContextGetWidth() / 2); _hoverCounter = -16; gSceneryPlaceCost = kMoney64Undefined; Invalidate(); @@ -1007,7 +1004,7 @@ namespace OpenRCT2::Ui::Windows for (ObjectEntryIndex scenerySetIndex = 0; scenerySetIndex < kMaxTabs - kReservedTabCount; scenerySetIndex++) { - const auto* sceneryGroupEntry = OpenRCT2::ObjectManager::GetObjectEntry(scenerySetIndex); + const auto* sceneryGroupEntry = ObjectManager::GetObjectEntry(scenerySetIndex); if (sceneryGroupEntry != nullptr && SceneryGroupIsInvented(scenerySetIndex)) { SceneryTabInfo tabInfo; @@ -1036,7 +1033,7 @@ namespace OpenRCT2::Ui::Windows // small scenery for (ObjectEntryIndex sceneryId = 0; sceneryId < kMaxSmallSceneryObjects; sceneryId++) { - const auto* sceneryEntry = OpenRCT2::ObjectManager::GetObjectEntry(sceneryId); + const auto* sceneryEntry = ObjectManager::GetObjectEntry(sceneryId); if (sceneryEntry != nullptr) { InitSceneryEntry({ SCENERY_TYPE_SMALL, sceneryId }, sceneryEntry->scenery_tab_id); @@ -1046,7 +1043,7 @@ namespace OpenRCT2::Ui::Windows // large scenery for (ObjectEntryIndex sceneryId = 0; sceneryId < kMaxLargeSceneryObjects; sceneryId++) { - const auto* sceneryEntry = OpenRCT2::ObjectManager::GetObjectEntry(sceneryId); + const auto* sceneryEntry = ObjectManager::GetObjectEntry(sceneryId); if (sceneryEntry != nullptr) { InitSceneryEntry({ SCENERY_TYPE_LARGE, sceneryId }, sceneryEntry->scenery_tab_id); @@ -1056,7 +1053,7 @@ namespace OpenRCT2::Ui::Windows // walls for (ObjectEntryIndex sceneryId = 0; sceneryId < kMaxWallSceneryObjects; sceneryId++) { - const auto* sceneryEntry = OpenRCT2::ObjectManager::GetObjectEntry(sceneryId); + const auto* sceneryEntry = ObjectManager::GetObjectEntry(sceneryId); if (sceneryEntry != nullptr) { InitSceneryEntry({ SCENERY_TYPE_WALL, sceneryId }, sceneryEntry->scenery_tab_id); @@ -1066,7 +1063,7 @@ namespace OpenRCT2::Ui::Windows // banners for (ObjectEntryIndex sceneryId = 0; sceneryId < kMaxBannerObjects; sceneryId++) { - const auto* sceneryEntry = OpenRCT2::ObjectManager::GetObjectEntry(sceneryId); + const auto* sceneryEntry = ObjectManager::GetObjectEntry(sceneryId); if (sceneryEntry != nullptr) { InitSceneryEntry({ SCENERY_TYPE_BANNER, sceneryId }, sceneryEntry->scenery_tab_id); @@ -1075,7 +1072,7 @@ namespace OpenRCT2::Ui::Windows for (ObjectEntryIndex sceneryId = 0; sceneryId < kMaxPathAdditionObjects; sceneryId++) { - const auto* sceneryEntry = OpenRCT2::ObjectManager::GetObjectEntry(sceneryId); + const auto* sceneryEntry = ObjectManager::GetObjectEntry(sceneryId); if (sceneryEntry != nullptr) { InitSceneryEntry({ SCENERY_TYPE_PATH_ITEM, sceneryId }, sceneryEntry->scenery_tab_id); @@ -1514,7 +1511,7 @@ namespace OpenRCT2::Ui::Windows _sceneryPaintEnabled = false; gWindowSceneryEyedropperEnabled = false; - OpenRCT2::Audio::Play(OpenRCT2::Audio::SoundId::Click1, 0, windowPos.x + (width / 2)); + Audio::Play(Audio::SoundId::Click1, 0, windowPos.x + (width / 2)); _hoverCounter = -16; gSceneryPlaceCost = kMoney64Undefined; Invalidate(); @@ -1544,8 +1541,7 @@ namespace OpenRCT2::Ui::Windows { case SCENERY_TYPE_SMALL: { - auto* sceneryEntry = OpenRCT2::ObjectManager::GetObjectEntry( - selectedScenery.EntryIndex); + auto* sceneryEntry = ObjectManager::GetObjectEntry(selectedScenery.EntryIndex); if (sceneryEntry != nullptr) { price = sceneryEntry->price; @@ -1555,8 +1551,7 @@ namespace OpenRCT2::Ui::Windows } case SCENERY_TYPE_PATH_ITEM: { - auto* sceneryEntry = OpenRCT2::ObjectManager::GetObjectEntry( - selectedScenery.EntryIndex); + auto* sceneryEntry = ObjectManager::GetObjectEntry(selectedScenery.EntryIndex); if (sceneryEntry != nullptr) { price = sceneryEntry->price; @@ -1566,8 +1561,7 @@ namespace OpenRCT2::Ui::Windows } case SCENERY_TYPE_WALL: { - auto* sceneryEntry = OpenRCT2::ObjectManager::GetObjectEntry( - selectedScenery.EntryIndex); + auto* sceneryEntry = ObjectManager::GetObjectEntry(selectedScenery.EntryIndex); if (sceneryEntry != nullptr) { price = sceneryEntry->price; @@ -1577,8 +1571,7 @@ namespace OpenRCT2::Ui::Windows } case SCENERY_TYPE_LARGE: { - auto* sceneryEntry = OpenRCT2::ObjectManager::GetObjectEntry( - selectedScenery.EntryIndex); + auto* sceneryEntry = ObjectManager::GetObjectEntry(selectedScenery.EntryIndex); if (sceneryEntry != nullptr) { price = sceneryEntry->price; @@ -1588,8 +1581,7 @@ namespace OpenRCT2::Ui::Windows } case SCENERY_TYPE_BANNER: { - auto* sceneryEntry = OpenRCT2::ObjectManager::GetObjectEntry( - selectedScenery.EntryIndex); + auto* sceneryEntry = ObjectManager::GetObjectEntry(selectedScenery.EntryIndex); if (sceneryEntry != nullptr) { price = sceneryEntry->price; @@ -1621,14 +1613,14 @@ namespace OpenRCT2::Ui::Windows { if (scenerySelection.SceneryType == SCENERY_TYPE_BANNER) { - auto bannerEntry = OpenRCT2::ObjectManager::GetObjectEntry(scenerySelection.EntryIndex); + auto bannerEntry = ObjectManager::GetObjectEntry(scenerySelection.EntryIndex); auto imageId = ImageId(bannerEntry->image + gWindowSceneryRotation * 2, _sceneryPrimaryColour); GfxDrawSprite(rt, imageId, { 33, 40 }); GfxDrawSprite(rt, imageId.WithIndexOffset(1), { 33, 40 }); } else if (scenerySelection.SceneryType == SCENERY_TYPE_LARGE) { - auto sceneryEntry = OpenRCT2::ObjectManager::GetObjectEntry(scenerySelection.EntryIndex); + auto sceneryEntry = ObjectManager::GetObjectEntry(scenerySelection.EntryIndex); auto imageId = ImageId(sceneryEntry->image + gWindowSceneryRotation); if (sceneryEntry->flags & LARGE_SCENERY_FLAG_HAS_PRIMARY_COLOUR) imageId = imageId.WithPrimary(_sceneryPrimaryColour); @@ -1640,7 +1632,7 @@ namespace OpenRCT2::Ui::Windows } else if (scenerySelection.SceneryType == SCENERY_TYPE_WALL) { - auto wallEntry = OpenRCT2::ObjectManager::GetObjectEntry(scenerySelection.EntryIndex); + auto wallEntry = ObjectManager::GetObjectEntry(scenerySelection.EntryIndex); auto imageId = ImageId(wallEntry->image); auto spriteTop = (wallEntry->height * 2) + 0x32; if (wallEntry->flags & WALL_SCENERY_HAS_GLASS) @@ -1676,14 +1668,13 @@ namespace OpenRCT2::Ui::Windows } else if (scenerySelection.SceneryType == SCENERY_TYPE_PATH_ITEM) { - auto* pathAdditionEntry = OpenRCT2::ObjectManager::GetObjectEntry( - scenerySelection.EntryIndex); + auto* pathAdditionEntry = ObjectManager::GetObjectEntry(scenerySelection.EntryIndex); auto imageId = ImageId(pathAdditionEntry->image); GfxDrawSprite(rt, imageId, { 11, 16 }); } else { - auto sceneryEntry = OpenRCT2::ObjectManager::GetObjectEntry(scenerySelection.EntryIndex); + auto sceneryEntry = ObjectManager::GetObjectEntry(scenerySelection.EntryIndex); auto imageId = ImageId(sceneryEntry->image + gWindowSceneryRotation); if (sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_HAS_PRIMARY_COLOUR)) { @@ -1844,7 +1835,7 @@ namespace OpenRCT2::Ui::Windows gMapSelectPositionB.y = mapTile.y; } - auto* sceneryEntry = OpenRCT2::ObjectManager::GetObjectEntry(selection.EntryIndex); + auto* sceneryEntry = ObjectManager::GetObjectEntry(selection.EntryIndex); gMapSelectType = MAP_SELECT_TYPE_FULL; if (!sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_FULL_TILE) && !gWindowSceneryScatterEnabled) @@ -1991,7 +1982,7 @@ namespace OpenRCT2::Ui::Windows return; } - auto* sceneryEntry = OpenRCT2::ObjectManager::GetObjectEntry(selection.EntryIndex); + auto* sceneryEntry = ObjectManager::GetObjectEntry(selection.EntryIndex); gMapSelectionTiles.clear(); for (auto& tile : sceneryEntry->tiles) @@ -2096,14 +2087,14 @@ namespace OpenRCT2::Ui::Windows SceneryRemoveGhostToolPlacement(); // 6e252b - auto smallSceneryPlaceAction = SmallSceneryPlaceAction( + auto smallSceneryPlaceAction = GameActions::SmallSceneryPlaceAction( loc, quadrant, entryIndex, primaryColour, secondaryColour, tertiaryColour); smallSceneryPlaceAction.SetFlags(GAME_COMMAND_FLAG_GHOST | GAME_COMMAND_FLAG_ALLOW_DURING_PAUSED); auto res = GameActions::Execute(&smallSceneryPlaceAction); if (res.Error != GameActions::Status::Ok) return kMoney64Undefined; - const auto placementData = res.GetData(); + const auto placementData = res.GetData(); gSceneryPlaceRotation = loc.direction; gSceneryPlaceObject.SceneryType = SCENERY_TYPE_SMALL; @@ -2131,7 +2122,7 @@ namespace OpenRCT2::Ui::Windows SceneryRemoveGhostToolPlacement(); // 6e265b - auto footpathAdditionPlaceAction = FootpathAdditionPlaceAction(loc, entryIndex); + auto footpathAdditionPlaceAction = GameActions::FootpathAdditionPlaceAction(loc, entryIndex); footpathAdditionPlaceAction.SetFlags(GAME_COMMAND_FLAG_GHOST | GAME_COMMAND_FLAG_ALLOW_DURING_PAUSED); footpathAdditionPlaceAction.SetCallback([=](const GameAction* ga, const GameActions::Result* result) { if (result->Error != GameActions::Status::Ok) @@ -2155,14 +2146,15 @@ namespace OpenRCT2::Ui::Windows SceneryRemoveGhostToolPlacement(); // 6e26b0 - auto wallPlaceAction = WallPlaceAction(entryIndex, loc, edge, primaryColour, secondaryColour, tertiaryColour); + auto wallPlaceAction = GameActions::WallPlaceAction( + entryIndex, loc, edge, primaryColour, secondaryColour, tertiaryColour); wallPlaceAction.SetFlags( GAME_COMMAND_FLAG_GHOST | GAME_COMMAND_FLAG_ALLOW_DURING_PAUSED | GAME_COMMAND_FLAG_NO_SPEND); wallPlaceAction.SetCallback([=](const GameAction* ga, const GameActions::Result* result) { if (result->Error != GameActions::Status::Ok) return; - const auto placementData = result->GetData(); + const auto placementData = result->GetData(); gSceneryGhostPosition = { loc, placementData.BaseHeight }; gSceneryGhostWallRotation = edge; @@ -2183,14 +2175,15 @@ namespace OpenRCT2::Ui::Windows SceneryRemoveGhostToolPlacement(); // 6e25a7 - auto sceneryPlaceAction = LargeSceneryPlaceAction(loc, entryIndex, primaryColour, secondaryColour, tertiaryColour); + auto sceneryPlaceAction = GameActions::LargeSceneryPlaceAction( + loc, entryIndex, primaryColour, secondaryColour, tertiaryColour); sceneryPlaceAction.SetFlags( GAME_COMMAND_FLAG_GHOST | GAME_COMMAND_FLAG_ALLOW_DURING_PAUSED | GAME_COMMAND_FLAG_NO_SPEND); auto res = GameActions::Execute(&sceneryPlaceAction); if (res.Error != GameActions::Status::Ok) return kMoney64Undefined; - const auto placementData = res.GetData(); + const auto placementData = res.GetData(); gSceneryPlaceRotation = loc.direction; @@ -2216,7 +2209,7 @@ namespace OpenRCT2::Ui::Windows // 6e2612 auto primaryColour = _sceneryPrimaryColour; - auto bannerPlaceAction = BannerPlaceAction(loc, entryIndex, primaryColour); + auto bannerPlaceAction = GameActions::BannerPlaceAction(loc, entryIndex, primaryColour); bannerPlaceAction.SetFlags( GAME_COMMAND_FLAG_GHOST | GAME_COMMAND_FLAG_ALLOW_DURING_PAUSED | GAME_COMMAND_FLAG_NO_SPEND); auto res = GameActions::Execute(&bannerPlaceAction); @@ -2251,7 +2244,7 @@ namespace OpenRCT2::Ui::Windows return; uint8_t quadrant = info.Element->AsSmallScenery()->GetSceneryQuadrant(); - auto repaintScenery = SmallScenerySetColourAction( + auto repaintScenery = GameActions::SmallScenerySetColourAction( { info.Loc, info.Element->GetBaseZ() }, quadrant, info.Element->AsSmallScenery()->GetEntryIndex(), _sceneryPrimaryColour, _scenerySecondaryColour, _sceneryTertiaryColour); @@ -2266,7 +2259,7 @@ namespace OpenRCT2::Ui::Windows if (!(scenery_entry->flags & (WALL_SCENERY_HAS_PRIMARY_COLOUR | WALL_SCENERY_HAS_GLASS))) return; - auto repaintScenery = WallSetColourAction( + auto repaintScenery = GameActions::WallSetColourAction( { info.Loc, info.Element->GetBaseZ(), info.Element->GetDirection() }, _sceneryPrimaryColour, _scenerySecondaryColour, _sceneryTertiaryColour); @@ -2281,7 +2274,7 @@ namespace OpenRCT2::Ui::Windows if (!(sceneryEntry->flags & LARGE_SCENERY_FLAG_HAS_PRIMARY_COLOUR)) return; - auto repaintScenery = LargeScenerySetColourAction( + auto repaintScenery = GameActions::LargeScenerySetColourAction( { info.Loc, info.Element->GetBaseZ(), info.Element->GetDirection() }, info.Element->AsLargeScenery()->GetSequenceIndex(), _sceneryPrimaryColour, _scenerySecondaryColour, _sceneryTertiaryColour); @@ -2294,10 +2287,10 @@ namespace OpenRCT2::Ui::Windows auto banner = info.Element->AsBanner()->GetBanner(); if (banner != nullptr) { - auto* bannerEntry = OpenRCT2::ObjectManager::GetObjectEntry(banner->type); + auto* bannerEntry = ObjectManager::GetObjectEntry(banner->type); if (bannerEntry->flags & BANNER_ENTRY_FLAG_HAS_PRIMARY_COLOUR) { - auto repaintScenery = BannerSetColourAction( + auto repaintScenery = GameActions::BannerSetColourAction( { info.Loc, info.Element->GetBaseZ(), info.Element->AsBanner()->GetPosition() }, _sceneryPrimaryColour); @@ -2323,7 +2316,7 @@ namespace OpenRCT2::Ui::Windows { SmallSceneryElement* sceneryElement = info.Element->AsSmallScenery(); auto entryIndex = sceneryElement->GetEntryIndex(); - auto* sceneryEntry = OpenRCT2::ObjectManager::GetObjectEntry(entryIndex); + auto* sceneryEntry = ObjectManager::GetObjectEntry(entryIndex); if (sceneryEntry != nullptr) { WindowScenerySetSelectedItem( @@ -2336,7 +2329,7 @@ namespace OpenRCT2::Ui::Windows case ViewportInteractionItem::Wall: { auto entryIndex = info.Element->AsWall()->GetEntryIndex(); - auto* sceneryEntry = OpenRCT2::ObjectManager::GetObjectEntry(entryIndex); + auto* sceneryEntry = ObjectManager::GetObjectEntry(entryIndex); if (sceneryEntry != nullptr) { WindowScenerySetSelectedItem( @@ -2349,7 +2342,7 @@ namespace OpenRCT2::Ui::Windows case ViewportInteractionItem::LargeScenery: { auto entryIndex = info.Element->AsLargeScenery()->GetEntryIndex(); - auto* sceneryEntry = OpenRCT2::ObjectManager::GetObjectEntry(entryIndex); + auto* sceneryEntry = ObjectManager::GetObjectEntry(entryIndex); if (sceneryEntry != nullptr) { WindowScenerySetSelectedItem( @@ -2364,7 +2357,7 @@ namespace OpenRCT2::Ui::Windows auto banner = info.Element->AsBanner()->GetBanner(); if (banner != nullptr) { - auto sceneryEntry = OpenRCT2::ObjectManager::GetObjectEntry(banner->type); + auto sceneryEntry = ObjectManager::GetObjectEntry(banner->type); if (sceneryEntry != nullptr) { WindowScenerySetSelectedItem( @@ -2376,7 +2369,7 @@ namespace OpenRCT2::Ui::Windows case ViewportInteractionItem::PathAddition: { auto entryIndex = info.Element->AsPath()->GetAdditionEntryIndex(); - auto* pathAdditionEntry = OpenRCT2::ObjectManager::GetObjectEntry(entryIndex); + auto* pathAdditionEntry = ObjectManager::GetObjectEntry(entryIndex); if (pathAdditionEntry != nullptr) { WindowScenerySetSelectedItem( @@ -2481,7 +2474,7 @@ namespace OpenRCT2::Ui::Windows std::numeric_limits::max() - 32); bool can_raise_item = false; - const auto* sceneryEntry = OpenRCT2::ObjectManager::GetObjectEntry(sceneryIndex); + const auto* sceneryEntry = ObjectManager::GetObjectEntry(sceneryIndex); if (sceneryEntry == nullptr) { gridPos.SetNull(); @@ -2712,7 +2705,7 @@ namespace OpenRCT2::Ui::Windows uint16_t maxPossibleHeight = ZoomLevel::max().ApplyTo( std::numeric_limits::max() - 32); - auto* wallEntry = OpenRCT2::ObjectManager::GetObjectEntry(sceneryIndex); + auto* wallEntry = ObjectManager::GetObjectEntry(sceneryIndex); if (wallEntry != nullptr) { maxPossibleHeight -= wallEntry->height; @@ -2803,7 +2796,7 @@ namespace OpenRCT2::Ui::Windows uint16_t maxPossibleHeight = ZoomLevel::max().ApplyTo( std::numeric_limits::max() - 32); - auto* sceneryEntry = OpenRCT2::ObjectManager::GetObjectEntry(sceneryIndex); + auto* sceneryEntry = ObjectManager::GetObjectEntry(sceneryIndex); if (sceneryEntry) { int16_t maxClearZ = 0; @@ -3000,7 +2993,7 @@ namespace OpenRCT2::Ui::Windows for (int32_t q = 0; q < quantity; q++) { int32_t zCoordinate = gSceneryPlaceZ; - auto* sceneryEntry = OpenRCT2::ObjectManager::GetObjectEntry(selectedScenery); + auto* sceneryEntry = ObjectManager::GetObjectEntry(selectedScenery); int16_t cur_grid_x = gridPos.x; int16_t cur_grid_y = gridPos.y; @@ -3038,7 +3031,7 @@ namespace OpenRCT2::Ui::Windows // Try find a valid z coordinate for (; zAttemptRange != 0; zAttemptRange--) { - auto smallSceneryPlaceAction = SmallSceneryPlaceAction( + auto smallSceneryPlaceAction = GameActions::SmallSceneryPlaceAction( { cur_grid_x, cur_grid_y, gSceneryPlaceZ, gSceneryPlaceRotation }, quadrant, selectedScenery, _sceneryPrimaryColour, _scenerySecondaryColour, _sceneryTertiaryColour); auto res = GameActions::Query(&smallSceneryPlaceAction); @@ -3061,14 +3054,14 @@ namespace OpenRCT2::Ui::Windows // Actually place if (success == GameActions::Status::Ok || ((q + 1 == quantity) && forceError)) { - auto smallSceneryPlaceAction = SmallSceneryPlaceAction( + auto smallSceneryPlaceAction = GameActions::SmallSceneryPlaceAction( { cur_grid_x, cur_grid_y, gSceneryPlaceZ, gSceneryPlaceRotation }, quadrant, selectedScenery, _sceneryPrimaryColour, _scenerySecondaryColour, _sceneryTertiaryColour); smallSceneryPlaceAction.SetCallback([=](const GameAction* ga, const GameActions::Result* result) { if (result->Error == GameActions::Status::Ok) { - OpenRCT2::Audio::Play3D(OpenRCT2::Audio::SoundId::PlaceItem, result->Position); + Audio::Play3D(Audio::SoundId::PlaceItem, result->Position); } }); auto res = GameActions::Execute(&smallSceneryPlaceAction); @@ -3093,14 +3086,15 @@ namespace OpenRCT2::Ui::Windows if (gridPos.IsNull()) return; - auto footpathAdditionPlaceAction = FootpathAdditionPlaceAction({ gridPos, z }, selectedScenery); + auto footpathAdditionPlaceAction = GameActions::FootpathAdditionPlaceAction( + { gridPos, z }, selectedScenery); footpathAdditionPlaceAction.SetCallback([](const GameAction* ga, const GameActions::Result* result) { if (result->Error != GameActions::Status::Ok) { return; } - OpenRCT2::Audio::Play3D(OpenRCT2::Audio::SoundId::PlaceItem, result->Position); + Audio::Play3D(Audio::SoundId::PlaceItem, result->Position); }); auto res = GameActions::Execute(&footpathAdditionPlaceAction); break; @@ -3120,7 +3114,7 @@ namespace OpenRCT2::Ui::Windows for (; zAttemptRange != 0; zAttemptRange--) { - auto wallPlaceAction = WallPlaceAction( + auto wallPlaceAction = GameActions::WallPlaceAction( selectedScenery, { gridPos, gSceneryPlaceZ }, edges, _sceneryPrimaryColour, _scenerySecondaryColour, _sceneryTertiaryColour); @@ -3144,14 +3138,14 @@ namespace OpenRCT2::Ui::Windows } } - auto wallPlaceAction = WallPlaceAction( + auto wallPlaceAction = GameActions::WallPlaceAction( selectedScenery, { gridPos, gSceneryPlaceZ }, edges, _sceneryPrimaryColour, _scenerySecondaryColour, _sceneryTertiaryColour); wallPlaceAction.SetCallback([](const GameAction* ga, const GameActions::Result* result) { if (result->Error == GameActions::Status::Ok) { - OpenRCT2::Audio::Play3D(OpenRCT2::Audio::SoundId::PlaceItem, result->Position); + Audio::Play3D(Audio::SoundId::PlaceItem, result->Position); } }); auto res = GameActions::Execute(&wallPlaceAction); @@ -3174,7 +3168,7 @@ namespace OpenRCT2::Ui::Windows { CoordsXYZD loc = { gridPos, gSceneryPlaceZ, direction }; - auto sceneryPlaceAction = LargeSceneryPlaceAction( + auto sceneryPlaceAction = GameActions::LargeSceneryPlaceAction( loc, selectedScenery, _sceneryPrimaryColour, _scenerySecondaryColour, _sceneryTertiaryColour); auto res = GameActions::Query(&sceneryPlaceAction); @@ -3199,16 +3193,16 @@ namespace OpenRCT2::Ui::Windows CoordsXYZD loc = { gridPos, gSceneryPlaceZ, direction }; - auto sceneryPlaceAction = LargeSceneryPlaceAction( + auto sceneryPlaceAction = GameActions::LargeSceneryPlaceAction( loc, selectedScenery, _sceneryPrimaryColour, _scenerySecondaryColour, _sceneryTertiaryColour); sceneryPlaceAction.SetCallback([=](const GameAction* ga, const GameActions::Result* result) { if (result->Error == GameActions::Status::Ok) { - OpenRCT2::Audio::Play3D(OpenRCT2::Audio::SoundId::PlaceItem, result->Position); + Audio::Play3D(Audio::SoundId::PlaceItem, result->Position); } else { - OpenRCT2::Audio::Play3D(OpenRCT2::Audio::SoundId::Error, { loc.x, loc.y, gSceneryPlaceZ }); + Audio::Play3D(Audio::SoundId::Error, { loc.x, loc.y, gSceneryPlaceZ }); } }); auto res = GameActions::Execute(&sceneryPlaceAction); @@ -3224,12 +3218,12 @@ namespace OpenRCT2::Ui::Windows CoordsXYZD loc{ gridPos, z, direction }; auto primaryColour = _sceneryPrimaryColour; - auto bannerPlaceAction = BannerPlaceAction(loc, selectedScenery, primaryColour); + auto bannerPlaceAction = GameActions::BannerPlaceAction(loc, selectedScenery, primaryColour); bannerPlaceAction.SetCallback([=](const GameAction* ga, const GameActions::Result* result) { if (result->Error == GameActions::Status::Ok) { - auto data = result->GetData(); - OpenRCT2::Audio::Play3D(OpenRCT2::Audio::SoundId::PlaceItem, result->Position); + auto data = result->GetData(); + Audio::Play3D(Audio::SoundId::PlaceItem, result->Position); ContextOpenDetailWindow(WD_BANNER, data.bannerId.ToUnderlying()); } }); diff --git a/src/openrct2-ui/windows/Sign.cpp b/src/openrct2-ui/windows/Sign.cpp index 55aed77149..6902554722 100644 --- a/src/openrct2-ui/windows/Sign.cpp +++ b/src/openrct2-ui/windows/Sign.cpp @@ -172,12 +172,12 @@ namespace OpenRCT2::Ui::Windows if (_isSmall) { CoordsXYZD wallLocation = { bannerCoords, tileElement->GetBaseZ(), tileElement->GetDirection() }; - auto wallRemoveAction = WallRemoveAction(wallLocation); + auto wallRemoveAction = GameActions::WallRemoveAction(wallLocation); GameActions::Execute(&wallRemoveAction); } else { - auto sceneryRemoveAction = LargeSceneryRemoveAction( + auto sceneryRemoveAction = GameActions::LargeSceneryRemoveAction( { bannerCoords, tileElement->GetBaseZ(), tileElement->GetDirection() }, tileElement->AsLargeScenery()->GetSequenceIndex()); GameActions::Execute(&sceneryRemoveAction); @@ -213,7 +213,8 @@ namespace OpenRCT2::Ui::Windows if (dropdownIndex == -1) return; _mainColour = ColourDropDownIndexToColour(dropdownIndex); - auto signSetStyleAction = SignSetStyleAction(GetBannerIndex(), _mainColour, _textColour, !_isSmall); + auto signSetStyleAction = GameActions::SignSetStyleAction( + GetBannerIndex(), _mainColour, _textColour, !_isSmall); GameActions::Execute(&signSetStyleAction); break; } @@ -222,7 +223,8 @@ namespace OpenRCT2::Ui::Windows if (dropdownIndex == -1) return; _textColour = ColourDropDownIndexToColour(dropdownIndex); - auto signSetStyleAction = SignSetStyleAction(GetBannerIndex(), _mainColour, _textColour, !_isSmall); + auto signSetStyleAction = GameActions::SignSetStyleAction( + GetBannerIndex(), _mainColour, _textColour, !_isSmall); GameActions::Execute(&signSetStyleAction); break; } @@ -237,7 +239,7 @@ namespace OpenRCT2::Ui::Windows { if (widgetIndex == WIDX_SIGN_TEXT && !text.empty()) { - auto signSetNameAction = SignSetNameAction(GetBannerIndex(), std::string(text)); + auto signSetNameAction = GameActions::SignSetNameAction(GetBannerIndex(), std::string(text)); GameActions::Execute(&signSetNameAction); } } diff --git a/src/openrct2-ui/windows/Staff.cpp b/src/openrct2-ui/windows/Staff.cpp index 62f920b03c..094c7cae0a 100644 --- a/src/openrct2-ui/windows/Staff.cpp +++ b/src/openrct2-ui/windows/Staff.cpp @@ -381,8 +381,9 @@ namespace OpenRCT2::Ui::Windows _pickedPeepOldX = staff->x; CoordsXYZ nullLoc{}; nullLoc.SetNull(); - PeepPickupAction pickupAction{ PeepPickupType::Pickup, EntityId::FromUnderlying(number), nullLoc, - NetworkGetCurrentPlayerId() }; + GameActions::PeepPickupAction pickupAction{ GameActions::PeepPickupType::Pickup, + EntityId::FromUnderlying(number), nullLoc, + NetworkGetCurrentPlayerId() }; pickupAction.SetCallback([peepnum = number](const GameAction* ga, const GameActions::Result* result) { if (result->Error != GameActions::Status::Ok) return; @@ -480,8 +481,8 @@ namespace OpenRCT2::Ui::Windows auto* windowMgr = Ui::GetWindowManager(); windowMgr->CloseByClass(WindowClass::PatrolArea); - auto staffSetPatrolAreaAction = StaffSetPatrolAreaAction( - staff->Id, {}, StaffSetPatrolAreaMode::ClearAll); + auto staffSetPatrolAreaAction = GameActions::StaffSetPatrolAreaAction( + staff->Id, {}, GameActions::StaffSetPatrolAreaMode::ClearAll); GameActions::Execute(&staffSetPatrolAreaAction); } else @@ -706,9 +707,10 @@ namespace OpenRCT2::Ui::Windows if (destCoords.IsNull()) return; - PeepPickupAction pickupAction{ - PeepPickupType::Place, staffEntityId, { destCoords, tileElement->GetBaseZ() }, NetworkGetCurrentPlayerId() - }; + GameActions::PeepPickupAction pickupAction{ GameActions::PeepPickupType::Place, + staffEntityId, + { destCoords, tileElement->GetBaseZ() }, + NetworkGetCurrentPlayerId() }; pickupAction.SetCallback([](const GameAction* ga, const GameActions::Result* result) { if (result->Error != GameActions::Status::Ok) return; @@ -723,9 +725,10 @@ namespace OpenRCT2::Ui::Windows if (widgetIndex != WIDX_PICKUP) return; - PeepPickupAction pickupAction{ - PeepPickupType::Cancel, EntityId::FromUnderlying(number), { _pickedPeepOldX, 0, 0 }, NetworkGetCurrentPlayerId() - }; + GameActions::PeepPickupAction pickupAction{ GameActions::PeepPickupType::Cancel, + EntityId::FromUnderlying(number), + { _pickedPeepOldX, 0, 0 }, + NetworkGetCurrentPlayerId() }; GameActions::Execute(&pickupAction); } @@ -742,7 +745,7 @@ namespace OpenRCT2::Ui::Windows if (text.empty()) return; - auto gameAction = StaffSetNameAction(EntityId::FromUnderlying(number), std::string{ text }); + auto gameAction = GameActions::StaffSetNameAction(EntityId::FromUnderlying(number), std::string{ text }); GameActions::Execute(&gameAction); } #pragma endregion @@ -812,7 +815,7 @@ namespace OpenRCT2::Ui::Windows return; ObjectEntryIndex costume = _availableCostumes[dropdownIndex].index; - auto staffSetCostumeAction = StaffSetCostumeAction(EntityId::FromUnderlying(number), costume); + auto staffSetCostumeAction = GameActions::StaffSetCostumeAction(EntityId::FromUnderlying(number), costume); GameActions::Execute(&staffSetCostumeAction); } @@ -1099,7 +1102,7 @@ namespace OpenRCT2::Ui::Windows } uint8_t newOrders = staff->StaffOrders ^ (1 << orderId); - auto staffSetOrdersAction = StaffSetOrdersAction(EntityId::FromUnderlying(number), newOrders); + auto staffSetOrdersAction = GameActions::StaffSetOrdersAction(EntityId::FromUnderlying(number), newOrders); GameActions::Execute(&staffSetOrdersAction); } diff --git a/src/openrct2-ui/windows/StaffFirePrompt.cpp b/src/openrct2-ui/windows/StaffFirePrompt.cpp index d281112fc4..192f779d37 100644 --- a/src/openrct2-ui/windows/StaffFirePrompt.cpp +++ b/src/openrct2-ui/windows/StaffFirePrompt.cpp @@ -61,7 +61,7 @@ namespace OpenRCT2::Ui::Windows { case WIDX_YES: { - auto staffFireAction = StaffFireAction(EntityId::FromUnderlying(number)); + auto staffFireAction = GameActions::StaffFireAction(EntityId::FromUnderlying(number)); GameActions::Execute(&staffFireAction); break; } diff --git a/src/openrct2-ui/windows/StaffList.cpp b/src/openrct2-ui/windows/StaffList.cpp index 4feb486dd7..66ead3e95e 100644 --- a/src/openrct2-ui/windows/StaffList.cpp +++ b/src/openrct2-ui/windows/StaffList.cpp @@ -232,7 +232,8 @@ namespace OpenRCT2::Ui::Windows } if (widgetIndex == WIDX_STAFF_LIST_UNIFORM_COLOUR_PICKER) { - auto action = StaffSetColourAction(GetSelectedStaffType(), ColourDropDownIndexToColour(dropdownIndex)); + auto action = GameActions::StaffSetColourAction( + GetSelectedStaffType(), ColourDropDownIndexToColour(dropdownIndex)); GameActions::Execute(&action); } } @@ -341,7 +342,7 @@ namespace OpenRCT2::Ui::Windows { if (_quickFireMode) { - auto staffFireAction = StaffFireAction(entry.Id); + auto staffFireAction = GameActions::StaffFireAction(entry.Id); GameActions::Execute(&staffFireAction); } else @@ -536,12 +537,12 @@ namespace OpenRCT2::Ui::Windows else costume = findPeepAnimationsIndexForType(animPeepType); - auto hireStaffAction = StaffHireNewAction(autoPosition, staffType, costume, staffOrders); + auto hireStaffAction = GameActions::StaffHireNewAction(autoPosition, staffType, costume, staffOrders); hireStaffAction.SetCallback([=](const GameAction*, const GameActions::Result* res) -> void { if (res->Error != GameActions::Status::Ok) return; - auto actionResult = res->GetData(); + auto actionResult = res->GetData(); auto* staff = GetEntity(actionResult.StaffEntityId); if (staff == nullptr) return; @@ -552,7 +553,8 @@ namespace OpenRCT2::Ui::Windows CoordsXYZ nullLoc{}; nullLoc.SetNull(); - PeepPickupAction pickupAction{ PeepPickupType::Pickup, staff->Id, nullLoc, NetworkGetCurrentPlayerId() }; + GameActions::PeepPickupAction pickupAction{ GameActions::PeepPickupType::Pickup, staff->Id, nullLoc, + NetworkGetCurrentPlayerId() }; pickupAction.SetCallback([staffId = staff->Id](const GameAction* ga, const GameActions::Result* result) { if (result->Error != GameActions::Status::Ok) return; diff --git a/src/openrct2-ui/windows/TileInspector.cpp b/src/openrct2-ui/windows/TileInspector.cpp index 0e0330d144..8aad520b0e 100644 --- a/src/openrct2-ui/windows/TileInspector.cpp +++ b/src/openrct2-ui/windows/TileInspector.cpp @@ -1866,14 +1866,14 @@ static uint64_t PageDisabledWidgets[] = { void RemoveElement(int32_t elementIndex) { Guard::Assert(elementIndex >= 0 && elementIndex < windowTileInspectorElementCount, "elementIndex out of range"); - auto modifyTile = TileModifyAction(_toolMap, TileModifyType::AnyRemove, elementIndex); + auto modifyTile = GameActions::TileModifyAction(_toolMap, GameActions::TileModifyType::AnyRemove, elementIndex); GameActions::Execute(&modifyTile); } void RotateElement(int32_t elementIndex) { Guard::Assert(elementIndex >= 0 && elementIndex < windowTileInspectorElementCount, "elementIndex out of range"); - auto modifyTile = TileModifyAction(_toolMap, TileModifyType::AnyRotate, elementIndex); + auto modifyTile = GameActions::TileModifyAction(_toolMap, GameActions::TileModifyType::AnyRotate, elementIndex); GameActions::Execute(&modifyTile); } @@ -1885,14 +1885,14 @@ static uint64_t PageDisabledWidgets[] = { // This might happen if two people are modifying the same tile. if (!firstInRange || !secondInRange) return; - auto modifyTile = TileModifyAction(_toolMap, TileModifyType::AnySwap, first, second); + auto modifyTile = GameActions::TileModifyAction(_toolMap, GameActions::TileModifyType::AnySwap, first, second); GameActions::Execute(&modifyTile); } void SortElements() { Guard::Assert(_tileSelected, "No tile selected"); - auto modifyTile = TileModifyAction(_toolMap, TileModifyType::AnySort); + auto modifyTile = GameActions::TileModifyAction(_toolMap, GameActions::TileModifyType::AnySort); GameActions::Execute(&modifyTile); } @@ -1916,50 +1916,56 @@ static uint64_t PageDisabledWidgets[] = { void PasteElement() { - auto modifyTile = TileModifyAction(_toolMap, TileModifyType::AnyPaste, 0, 0, _copiedElement, _copiedBanner); + auto modifyTile = GameActions::TileModifyAction( + _toolMap, GameActions::TileModifyType::AnyPaste, 0, 0, _copiedElement, _copiedBanner); GameActions::Execute(&modifyTile); } void BaseHeightOffset(int16_t elementIndex, int8_t heightOffset) { - auto modifyTile = TileModifyAction(_toolMap, TileModifyType::AnyBaseHeightOffset, elementIndex, heightOffset); + auto modifyTile = GameActions::TileModifyAction( + _toolMap, GameActions::TileModifyType::AnyBaseHeightOffset, elementIndex, heightOffset); GameActions::Execute(&modifyTile); } void SurfaceShowParkFences(bool showFences) { - auto modifyTile = TileModifyAction(_toolMap, TileModifyType::SurfaceShowParkFences, showFences); + auto modifyTile = GameActions::TileModifyAction( + _toolMap, GameActions::TileModifyType::SurfaceShowParkFences, showFences); GameActions::Execute(&modifyTile); } void SurfaceToggleCorner(int32_t cornerIndex) { - auto modifyTile = TileModifyAction(_toolMap, TileModifyType::SurfaceToggleCorner, cornerIndex); + auto modifyTile = GameActions::TileModifyAction( + _toolMap, GameActions::TileModifyType::SurfaceToggleCorner, cornerIndex); GameActions::Execute(&modifyTile); } void SurfaceToggleDiagonal() { - auto modifyTile = TileModifyAction(_toolMap, TileModifyType::SurfaceToggleDiagonal); + auto modifyTile = GameActions::TileModifyAction(_toolMap, GameActions::TileModifyType::SurfaceToggleDiagonal); GameActions::Execute(&modifyTile); } void PathSetSloped(int32_t elementIndex, bool sloped) { - auto modifyTile = TileModifyAction(_toolMap, TileModifyType::PathSetSlope, elementIndex, sloped); + auto modifyTile = GameActions::TileModifyAction( + _toolMap, GameActions::TileModifyType::PathSetSlope, elementIndex, sloped); GameActions::Execute(&modifyTile); } void PathSetJunctionRailings(int32_t elementIndex, bool hasJunctionRailings) { - auto modifyTile = TileModifyAction( - _toolMap, TileModifyType::PathSetJunctionRailings, elementIndex, hasJunctionRailings); + auto modifyTile = GameActions::TileModifyAction( + _toolMap, GameActions::TileModifyType::PathSetJunctionRailings, elementIndex, hasJunctionRailings); GameActions::Execute(&modifyTile); } void PathSetBroken(int32_t elementIndex, bool broken) { - auto modifyTile = TileModifyAction(_toolMap, TileModifyType::PathSetBroken, elementIndex, broken); + auto modifyTile = GameActions::TileModifyAction( + _toolMap, GameActions::TileModifyType::PathSetBroken, elementIndex, broken); GameActions::Execute(&modifyTile); } @@ -1967,14 +1973,16 @@ static uint64_t PageDisabledWidgets[] = { { Guard::Assert(elementIndex >= 0 && elementIndex < windowTileInspectorElementCount, "elementIndex out of range"); Guard::Assert(cornerIndex >= 0 && cornerIndex < 8, "cornerIndex out of range"); - auto modifyTile = TileModifyAction(_toolMap, TileModifyType::PathToggleEdge, elementIndex, cornerIndex); + auto modifyTile = GameActions::TileModifyAction( + _toolMap, GameActions::TileModifyType::PathToggleEdge, elementIndex, cornerIndex); GameActions::Execute(&modifyTile); } void EntranceMakeUsable(int32_t elementIndex) { Guard::ArgumentInRange(elementIndex, 0, windowTileInspectorElementCount - 1); - auto modifyTile = TileModifyAction(_toolMap, TileModifyType::EntranceMakeUsable, elementIndex); + auto modifyTile = GameActions::TileModifyAction( + _toolMap, GameActions::TileModifyType::EntranceMakeUsable, elementIndex); GameActions::Execute(&modifyTile); } @@ -1982,41 +1990,45 @@ static uint64_t PageDisabledWidgets[] = { { // Make sure only the correct bits are set Guard::Assert((slopeValue & 3) == slopeValue, "slopeValue doesn't match its mask"); - auto modifyTile = TileModifyAction(_toolMap, TileModifyType::WallSetSlope, elementIndex, slopeValue); + auto modifyTile = GameActions::TileModifyAction( + _toolMap, GameActions::TileModifyType::WallSetSlope, elementIndex, slopeValue); GameActions::Execute(&modifyTile); } void WallAnimationFrameOffset(int16_t elementIndex, int8_t animationFrameOffset) { - auto modifyTile = TileModifyAction( - _toolMap, TileModifyType::WallSetAnimationFrame, elementIndex, animationFrameOffset); + auto modifyTile = GameActions::TileModifyAction( + _toolMap, GameActions::TileModifyType::WallSetAnimationFrame, elementIndex, animationFrameOffset); GameActions::Execute(&modifyTile); } void TrackBlockHeightOffset(int32_t elementIndex, int8_t heightOffset) { - auto modifyTile = TileModifyAction(_toolMap, TileModifyType::TrackBaseHeightOffset, elementIndex, heightOffset); + auto modifyTile = GameActions::TileModifyAction( + _toolMap, GameActions::TileModifyType::TrackBaseHeightOffset, elementIndex, heightOffset); GameActions::Execute(&modifyTile); } void TrackBlockSetLift(int32_t elementIndex, bool entireTrackBlock, bool chain) { - auto modifyTile = TileModifyAction( - _toolMap, entireTrackBlock ? TileModifyType::TrackSetChainBlock : TileModifyType::TrackSetChain, elementIndex, - chain); + auto modifyTile = GameActions::TileModifyAction( + _toolMap, + entireTrackBlock ? GameActions::TileModifyType::TrackSetChainBlock : GameActions::TileModifyType::TrackSetChain, + elementIndex, chain); GameActions::Execute(&modifyTile); } void TrackSetBrakeClosed(int32_t elementIndex, bool isClosed) { - auto modifyTile = TileModifyAction(_toolMap, TileModifyType::TrackSetBrake, elementIndex, isClosed); + auto modifyTile = GameActions::TileModifyAction( + _toolMap, GameActions::TileModifyType::TrackSetBrake, elementIndex, isClosed); GameActions::Execute(&modifyTile); } void TrackSetIndestructible(int32_t elementIndex, bool isIndestructible) { - auto modifyTile = TileModifyAction( - _toolMap, TileModifyType::TrackSetIndestructible, elementIndex, isIndestructible); + auto modifyTile = GameActions::TileModifyAction( + _toolMap, GameActions::TileModifyType::TrackSetIndestructible, elementIndex, isIndestructible); GameActions::Execute(&modifyTile); } @@ -2024,16 +2036,17 @@ static uint64_t PageDisabledWidgets[] = { { // quarterIndex is widget index relative to WIDX_SCENERY_CHECK_QUARTER_N, so a value from 0-3 Guard::Assert(quarterIndex >= 0 && quarterIndex < 4, "quarterIndex out of range"); - auto modifyTile = TileModifyAction( - _toolMap, TileModifyType::ScenerySetQuarterLocation, elementIndex, (quarterIndex - GetCurrentRotation()) & 3); + auto modifyTile = GameActions::TileModifyAction( + _toolMap, GameActions::TileModifyType::ScenerySetQuarterLocation, elementIndex, + (quarterIndex - GetCurrentRotation()) & 3); GameActions::Execute(&modifyTile); } // ToggleQuadrantCollision? void ToggleQuadrantCollosion(int32_t elementIndex, const int32_t quadrantIndex) { - auto modifyTile = TileModifyAction( - _toolMap, TileModifyType::ScenerySetQuarterCollision, elementIndex, + auto modifyTile = GameActions::TileModifyAction( + _toolMap, GameActions::TileModifyType::ScenerySetQuarterCollision, elementIndex, (quadrantIndex + 2 - GetCurrentRotation()) & 3); GameActions::Execute(&modifyTile); } @@ -2043,20 +2056,23 @@ static uint64_t PageDisabledWidgets[] = { Guard::Assert(edgeIndex >= 0 && edgeIndex < 4, "edgeIndex out of range"); // Make edgeIndex = 0 edgeIndex = (edgeIndex - GetCurrentRotation()) & 3; - auto modifyTile = TileModifyAction(_toolMap, TileModifyType::BannerToggleBlockingEdge, elementIndex, edgeIndex); + auto modifyTile = GameActions::TileModifyAction( + _toolMap, GameActions::TileModifyType::BannerToggleBlockingEdge, elementIndex, edgeIndex); GameActions::Execute(&modifyTile); } void ToggleInvisibility(int32_t elementIndex) { Guard::Assert(elementIndex >= 0 && elementIndex < windowTileInspectorElementCount, "elementIndex out of range"); - auto modifyTile = TileModifyAction(_toolMap, TileModifyType::AnyToggleInvisilibity, elementIndex); + auto modifyTile = GameActions::TileModifyAction( + _toolMap, GameActions::TileModifyType::AnyToggleInvisilibity, elementIndex); GameActions::Execute(&modifyTile); } void WallSetAnimationIsBackwards(int32_t elementIndex, bool backwards) { - auto modifyTile = TileModifyAction(_toolMap, TileModifyType::WallSetAnimationIsBackwards, elementIndex, backwards); + auto modifyTile = GameActions::TileModifyAction( + _toolMap, GameActions::TileModifyType::WallSetAnimationIsBackwards, elementIndex, backwards); GameActions::Execute(&modifyTile); } diff --git a/src/openrct2-ui/windows/TitleMenu.cpp b/src/openrct2-ui/windows/TitleMenu.cpp index fdb613b1e6..4335f535c9 100644 --- a/src/openrct2-ui/windows/TitleMenu.cpp +++ b/src/openrct2-ui/windows/TitleMenu.cpp @@ -147,7 +147,7 @@ namespace OpenRCT2::Ui::Windows { windowMgr->CloseByClass(WindowClass::ScenarioSelect); windowMgr->CloseByClass(WindowClass::ServerList); - auto loadOrQuitAction = LoadOrQuitAction(LoadOrQuitModes::OpenSavePrompt); + auto loadOrQuitAction = GameActions::LoadOrQuitAction(GameActions::LoadOrQuitModes::OpenSavePrompt); GameActions::Execute(&loadOrQuitAction); } break; diff --git a/src/openrct2-ui/windows/TopToolbar.cpp b/src/openrct2-ui/windows/TopToolbar.cpp index f8ab85d4b8..bdecaf0dae 100644 --- a/src/openrct2-ui/windows/TopToolbar.cpp +++ b/src/openrct2-ui/windows/TopToolbar.cpp @@ -308,7 +308,7 @@ namespace OpenRCT2::Ui::Windows case WIDX_PAUSE: if (NetworkGetMode() != NETWORK_MODE_CLIENT) { - auto pauseToggleAction = PauseToggleAction(); + auto pauseToggleAction = GameActions::PauseToggleAction(); GameActions::Execute(&pauseToggleAction); _waitingForPause = true; } @@ -444,14 +444,14 @@ namespace OpenRCT2::Ui::Windows { case DDIDX_NEW_GAME: { - auto loadOrQuitAction = LoadOrQuitAction( - LoadOrQuitModes::OpenSavePrompt, PromptMode::saveBeforeNewGame); + auto loadOrQuitAction = GameActions::LoadOrQuitAction( + GameActions::LoadOrQuitModes::OpenSavePrompt, PromptMode::saveBeforeNewGame); GameActions::Execute(&loadOrQuitAction); break; } case DDIDX_LOAD_GAME: { - auto loadOrQuitAction = LoadOrQuitAction(LoadOrQuitModes::OpenSavePrompt); + auto loadOrQuitAction = GameActions::LoadOrQuitAction(GameActions::LoadOrQuitModes::OpenSavePrompt); GameActions::Execute(&loadOrQuitAction); break; } @@ -504,8 +504,8 @@ namespace OpenRCT2::Ui::Windows auto* windowMgr = Ui::GetWindowManager(); windowMgr->CloseByClass(WindowClass::ManageTrackDesign); windowMgr->CloseByClass(WindowClass::TrackDeletePrompt); - auto loadOrQuitAction = LoadOrQuitAction( - LoadOrQuitModes::OpenSavePrompt, PromptMode::saveBeforeQuit); + auto loadOrQuitAction = GameActions::LoadOrQuitAction( + GameActions::LoadOrQuitModes::OpenSavePrompt, PromptMode::saveBeforeQuit); GameActions::Execute(&loadOrQuitAction); break; } @@ -1299,7 +1299,7 @@ namespace OpenRCT2::Ui::Windows if (newSpeed >= 5) newSpeed = 8; - auto setSpeedAction = GameSetSpeedAction(newSpeed); + auto setSpeedAction = GameActions::GameSetSpeedAction(newSpeed); GameActions::Execute(&setSpeedAction); } } diff --git a/src/openrct2-ui/windows/TrackDesignPlace.cpp b/src/openrct2-ui/windows/TrackDesignPlace.cpp index a3d16248c7..06940dc3a0 100644 --- a/src/openrct2-ui/windows/TrackDesignPlace.cpp +++ b/src/openrct2-ui/windows/TrackDesignPlace.cpp @@ -213,7 +213,7 @@ namespace OpenRCT2::Ui::Windows if (res.Error == GameActions::Status::Ok) { // Valid location found. Place the ghost at the location. - auto tdAction = TrackDesignAction(trackLoc, *_trackDesign); + auto tdAction = GameActions::TrackDesignAction(trackLoc, *_trackDesign); tdAction.SetFlags(GAME_COMMAND_FLAG_NO_SPEND | GAME_COMMAND_FLAG_GHOST); tdAction.SetCallback([&](const GameAction*, const GameActions::Result* result) { if (result->Error == GameActions::Status::Ok) @@ -282,7 +282,7 @@ namespace OpenRCT2::Ui::Windows return; } - auto tdAction = TrackDesignAction({ trackLoc, _currentTrackPieceDirection }, *_trackDesign); + auto tdAction = GameActions::TrackDesignAction({ trackLoc, _currentTrackPieceDirection }, *_trackDesign); tdAction.SetCallback([&](const GameAction*, const GameActions::Result* result) { if (result->Error != GameActions::Status::Ok) { @@ -378,7 +378,7 @@ namespace OpenRCT2::Ui::Windows { if (_hasPlacementGhost) { - auto tdAction = TrackDesignAction({ _placementGhostLoc }, *_trackDesign); + auto tdAction = GameActions::TrackDesignAction({ _placementGhostLoc }, *_trackDesign); tdAction.SetFlags(GAME_COMMAND_FLAG_NO_SPEND | GAME_COMMAND_FLAG_GHOST); auto res = GameActions::Execute(&tdAction); if (res.Error != GameActions::Status::Ok) @@ -703,7 +703,7 @@ namespace OpenRCT2::Ui::Windows GameActions::Result res; for (int32_t i = 0; i < 7; i++, loc.z += kCoordsZStep) { - auto tdAction = TrackDesignAction( + auto tdAction = GameActions::TrackDesignAction( CoordsXYZD{ loc.x, loc.y, loc.z, _currentTrackPieceDirection }, *_trackDesign); tdAction.SetFlags(newFlags); res = GameActions::Query(&tdAction); diff --git a/src/openrct2-ui/windows/Water.cpp b/src/openrct2-ui/windows/Water.cpp index 281db038b8..753d1df52b 100644 --- a/src/openrct2-ui/windows/Water.cpp +++ b/src/openrct2-ui/windows/Water.cpp @@ -260,7 +260,7 @@ namespace OpenRCT2::Ui::Windows { gInputDragLast.y += dx; - auto waterRaiseAction = WaterRaiseAction( + auto waterRaiseAction = GameActions::WaterRaiseAction( { gMapSelectPositionA.x, gMapSelectPositionA.y, gMapSelectPositionB.x, gMapSelectPositionB.y }); GameActions::Execute(&waterRaiseAction); @@ -276,7 +276,7 @@ namespace OpenRCT2::Ui::Windows { gInputDragLast.y += dx; - auto waterLowerAction = WaterLowerAction( + auto waterLowerAction = GameActions::WaterLowerAction( { gMapSelectPositionA.x, gMapSelectPositionA.y, gMapSelectPositionB.x, gMapSelectPositionB.y }); GameActions::Execute(&waterLowerAction); _waterToolRaiseCost = kMoney64Undefined; @@ -301,9 +301,9 @@ namespace OpenRCT2::Ui::Windows if (!(gMapSelectFlags & MAP_SELECT_FLAG_ENABLE)) return; - auto waterLowerAction = WaterLowerAction( + auto waterLowerAction = GameActions::WaterLowerAction( { gMapSelectPositionA.x, gMapSelectPositionA.y, gMapSelectPositionB.x, gMapSelectPositionB.y }); - auto waterRaiseAction = WaterRaiseAction( + auto waterRaiseAction = GameActions::WaterRaiseAction( { gMapSelectPositionA.x, gMapSelectPositionA.y, gMapSelectPositionB.x, gMapSelectPositionB.y }); auto res = GameActions::Query(&waterLowerAction); @@ -392,9 +392,9 @@ namespace OpenRCT2::Ui::Windows if (!state_changed) return; - auto waterLowerAction = WaterLowerAction( + auto waterLowerAction = GameActions::WaterLowerAction( { gMapSelectPositionA.x, gMapSelectPositionA.y, gMapSelectPositionB.x, gMapSelectPositionB.y }); - auto waterRaiseAction = WaterRaiseAction( + auto waterRaiseAction = GameActions::WaterRaiseAction( { gMapSelectPositionA.x, gMapSelectPositionA.y, gMapSelectPositionB.x, gMapSelectPositionB.y }); auto res = GameActions::Query(&waterLowerAction); diff --git a/src/openrct2/Cheats.cpp b/src/openrct2/Cheats.cpp index a3a6f1865a..9321ac5333 100644 --- a/src/openrct2/Cheats.cpp +++ b/src/openrct2/Cheats.cpp @@ -61,7 +61,7 @@ void CheatsReset() void CheatsSet(CheatType cheatType, int64_t param1 /* = 0*/, int64_t param2 /* = 0*/) { - auto cheatSetAction = CheatSetAction(cheatType, param1, param2); + auto cheatSetAction = GameActions::CheatSetAction(cheatType, param1, param2); GameActions::Execute(&cheatSetAction); } diff --git a/src/openrct2/Editor.cpp b/src/openrct2/Editor.cpp index 108550d788..2ef606e736 100644 --- a/src/openrct2/Editor.cpp +++ b/src/openrct2/Editor.cpp @@ -238,11 +238,12 @@ namespace OpenRCT2::Editor auto& gameState = getGameState(); MapRange range = { 2 * kCoordsXYStep, 2 * kCoordsXYStep, (gameState.mapSize.x - 3) * kCoordsXYStep, (gameState.mapSize.y - 3) * kCoordsXYStep }; - auto landSetRightsAction = LandSetRightsAction(range, LandSetRightSetting::SetForSale); + + auto landSetRightsAction = GameActions::LandSetRightsAction(range, GameActions::LandSetRightSetting::SetForSale); landSetRightsAction.SetFlags(GAME_COMMAND_FLAG_NO_SPEND); GameActions::Execute(&landSetRightsAction); - auto landBuyRightsAction = LandBuyRightsAction(range, LandBuyRightSetting::BuyLand); + auto landBuyRightsAction = GameActions::LandBuyRightsAction(range, GameActions::LandBuyRightSetting::BuyLand); landBuyRightsAction.SetFlags(GAME_COMMAND_FLAG_NO_SPEND); GameActions::Execute(&landBuyRightsAction); } diff --git a/src/openrct2/Game.cpp b/src/openrct2/Game.cpp index b1f7156051..1966249527 100644 --- a/src/openrct2/Game.cpp +++ b/src/openrct2/Game.cpp @@ -102,7 +102,7 @@ using namespace OpenRCT2; void GameResetSpeed() { - auto setSpeedAction = GameSetSpeedAction(1); + auto setSpeedAction = GameActions::GameSetSpeedAction(1); GameActions::Execute(&setSpeedAction); } @@ -112,7 +112,7 @@ void GameIncreaseGameSpeed() if (newSpeed == 5) newSpeed = 8; - auto setSpeedAction = GameSetSpeedAction(newSpeed); + auto setSpeedAction = GameActions::GameSetSpeedAction(newSpeed); GameActions::Execute(&setSpeedAction); } @@ -122,7 +122,7 @@ void GameReduceGameSpeed() if (newSpeed == 7) newSpeed = 4; - auto setSpeedAction = GameSetSpeedAction(newSpeed); + auto setSpeedAction = GameActions::GameSetSpeedAction(newSpeed); GameActions::Execute(&setSpeedAction); } @@ -655,7 +655,7 @@ void GameLoadOrQuitNoSavePrompt() { case PromptMode::saveBeforeLoad: { - auto loadOrQuitAction = LoadOrQuitAction(LoadOrQuitModes::CloseSavePrompt); + auto loadOrQuitAction = GameActions::LoadOrQuitAction(GameActions::LoadOrQuitModes::CloseSavePrompt); GameActions::Execute(&loadOrQuitAction); ToolCancel(); if (gLegacyScene == LegacyScene::scenarioEditor) @@ -674,7 +674,7 @@ void GameLoadOrQuitNoSavePrompt() } case PromptMode::saveBeforeQuit: { - auto loadOrQuitAction = LoadOrQuitAction(LoadOrQuitModes::CloseSavePrompt); + auto loadOrQuitAction = GameActions::LoadOrQuitAction(GameActions::LoadOrQuitModes::CloseSavePrompt); GameActions::Execute(&loadOrQuitAction); ToolCancel(); if (gInputFlags.has(InputFlag::unk5)) @@ -692,7 +692,7 @@ void GameLoadOrQuitNoSavePrompt() } case PromptMode::saveBeforeNewGame: { - auto loadOrQuitAction = LoadOrQuitAction(LoadOrQuitModes::CloseSavePrompt); + auto loadOrQuitAction = GameActions::LoadOrQuitAction(GameActions::LoadOrQuitModes::CloseSavePrompt); GameActions::Execute(&loadOrQuitAction); ToolCancel(); auto intent = Intent(WindowClass::ScenarioSelect); diff --git a/src/openrct2/ReplayManager.cpp b/src/openrct2/ReplayManager.cpp index 54adf13e6d..e3e4bc45eb 100644 --- a/src/openrct2/ReplayManager.cpp +++ b/src/openrct2/ReplayManager.cpp @@ -21,7 +21,7 @@ #include "actions/FootpathPlaceAction.h" #include "actions/GameAction.h" #include "actions/RideEntranceExitPlaceAction.h" -#include "actions/RideSetSettingAction.h" +// #include "actions/RideSetSettingAction.h" #include "actions/TileModifyAction.h" #include "actions/TrackPlaceAction.h" #include "config/Config.h" diff --git a/src/openrct2/actions/BalloonPressAction.cpp b/src/openrct2/actions/BalloonPressAction.cpp index 331be6ab82..c8a30f8b9d 100644 --- a/src/openrct2/actions/BalloonPressAction.cpp +++ b/src/openrct2/actions/BalloonPressAction.cpp @@ -14,52 +14,51 @@ #include "../entity/EntityRegistry.h" #include "GameAction.h" -using namespace OpenRCT2; - -BalloonPressAction::BalloonPressAction(EntityId spriteIndex) - : _spriteIndex(spriteIndex) +namespace OpenRCT2::GameActions { -} - -void BalloonPressAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit("id", _spriteIndex); -} - -uint16_t BalloonPressAction::GetActionFlags() const -{ - return GameAction::GetActionFlags(); -} - -void BalloonPressAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - stream << DS_TAG(_spriteIndex); -} - -GameActions::Result BalloonPressAction::Query() const -{ - auto balloon = TryGetEntity(_spriteIndex); - if (balloon == nullptr) + BalloonPressAction::BalloonPressAction(EntityId spriteIndex) + : _spriteIndex(spriteIndex) { - LOG_ERROR("Balloon not found for spriteIndex %u", _spriteIndex); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_BALLOON_NOT_FOUND); - } - return GameActions::Result(); -} - -GameActions::Result BalloonPressAction::Execute() const -{ - auto balloon = TryGetEntity(_spriteIndex); - if (balloon == nullptr) - { - LOG_ERROR("Balloon not found for spriteIndex %u", _spriteIndex); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_BALLOON_NOT_FOUND); } - balloon->Press(); + void BalloonPressAction::AcceptParameters(GameActionParameterVisitor& visitor) + { + visitor.Visit("id", _spriteIndex); + } - return GameActions::Result(); -} + uint16_t BalloonPressAction::GetActionFlags() const + { + return GameAction::GetActionFlags(); + } + + void BalloonPressAction::Serialise(DataSerialiser& stream) + { + GameAction::Serialise(stream); + stream << DS_TAG(_spriteIndex); + } + + Result BalloonPressAction::Query() const + { + auto balloon = TryGetEntity(_spriteIndex); + if (balloon == nullptr) + { + LOG_ERROR("Balloon not found for spriteIndex %u", _spriteIndex); + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_BALLOON_NOT_FOUND); + } + return Result(); + } + + Result BalloonPressAction::Execute() const + { + auto balloon = TryGetEntity(_spriteIndex); + if (balloon == nullptr) + { + LOG_ERROR("Balloon not found for spriteIndex %u", _spriteIndex); + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_BALLOON_NOT_FOUND); + } + + balloon->Press(); + + return Result(); + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/BalloonPressAction.h b/src/openrct2/actions/BalloonPressAction.h index 6520ae1cfe..f5c0f6279b 100644 --- a/src/openrct2/actions/BalloonPressAction.h +++ b/src/openrct2/actions/BalloonPressAction.h @@ -12,19 +12,22 @@ #include "../Identifiers.h" #include "GameAction.h" -class BalloonPressAction final : public GameActionBase +namespace OpenRCT2::GameActions { - EntityId _spriteIndex{ EntityId::GetNull() }; + class BalloonPressAction final : public GameActionBase + { + EntityId _spriteIndex{ EntityId::GetNull() }; -public: - BalloonPressAction() = default; - BalloonPressAction(EntityId spriteIndex); + public: + BalloonPressAction() = default; + BalloonPressAction(EntityId spriteIndex); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; -}; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/BannerPlaceAction.cpp b/src/openrct2/actions/BannerPlaceAction.cpp index dad84d99d8..0cf7886df6 100644 --- a/src/openrct2/actions/BannerPlaceAction.cpp +++ b/src/openrct2/actions/BannerPlaceAction.cpp @@ -22,166 +22,159 @@ #include "../world/tile_element/PathElement.h" #include "GameAction.h" -using namespace OpenRCT2; - -BannerPlaceAction::BannerPlaceAction(const CoordsXYZD& loc, ObjectEntryIndex bannerType, colour_t primaryColour) - : _loc(loc) - , _bannerType(bannerType) - , _primaryColour(primaryColour) +namespace OpenRCT2::GameActions { -} - -void BannerPlaceAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit(_loc); - visitor.Visit("object", _bannerType); - visitor.Visit("primaryColour", _primaryColour); -} - -uint16_t BannerPlaceAction::GetActionFlags() const -{ - return GameAction::GetActionFlags(); -} - -void BannerPlaceAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_loc) << DS_TAG(_bannerType) << DS_TAG(_primaryColour); -} - -GameActions::Result BannerPlaceAction::Query() const -{ - auto res = GameActions::Result(); - res.Position.x = _loc.x + 16; - res.Position.y = _loc.y + 16; - res.Position.z = _loc.z; - res.Expenditure = ExpenditureType::landscaping; - res.ErrorTitle = STR_CANT_POSITION_THIS_HERE; - - if (!LocationValid(_loc)) + BannerPlaceAction::BannerPlaceAction(const CoordsXYZD& loc, ObjectEntryIndex bannerType, colour_t primaryColour) + : _loc(loc) + , _bannerType(bannerType) + , _primaryColour(primaryColour) { - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_OFF_EDGE_OF_MAP); } - if (!MapCheckCapacityAndReorganise(_loc)) + void BannerPlaceAction::AcceptParameters(GameActionParameterVisitor& visitor) { - LOG_ERROR("No free map elements."); - return GameActions::Result( - GameActions::Status::NoFreeElements, STR_CANT_POSITION_THIS_HERE, STR_TILE_ELEMENT_LIMIT_REACHED); + visitor.Visit(_loc); + visitor.Visit("object", _bannerType); + visitor.Visit("primaryColour", _primaryColour); } - auto pathElement = GetValidPathElement(); - - if (pathElement == nullptr) + uint16_t BannerPlaceAction::GetActionFlags() const { - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_CAN_ONLY_BE_BUILT_ACROSS_PATHS); + return GameAction::GetActionFlags(); } - if (!MapCanBuildAt(_loc)) + void BannerPlaceAction::Serialise(DataSerialiser& stream) { - return GameActions::Result(GameActions::Status::NotOwned, STR_CANT_POSITION_THIS_HERE, STR_LAND_NOT_OWNED_BY_PARK); + GameAction::Serialise(stream); + + stream << DS_TAG(_loc) << DS_TAG(_bannerType) << DS_TAG(_primaryColour); } - auto baseHeight = _loc.z + kPathHeightStep; - BannerElement* existingBannerElement = MapGetBannerElementAt({ _loc.x, _loc.y, baseHeight }, _loc.direction); - if (existingBannerElement != nullptr) + Result BannerPlaceAction::Query() const { - return GameActions::Result( - GameActions::Status::ItemAlreadyPlaced, STR_CANT_POSITION_THIS_HERE, STR_BANNER_SIGN_IN_THE_WAY); + auto res = Result(); + res.Position.x = _loc.x + 16; + res.Position.y = _loc.y + 16; + res.Position.z = _loc.z; + res.Expenditure = ExpenditureType::landscaping; + res.ErrorTitle = STR_CANT_POSITION_THIS_HERE; + + if (!LocationValid(_loc)) + { + return Result(Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_OFF_EDGE_OF_MAP); + } + + if (!MapCheckCapacityAndReorganise(_loc)) + { + LOG_ERROR("No free map elements."); + return Result(Status::NoFreeElements, STR_CANT_POSITION_THIS_HERE, STR_TILE_ELEMENT_LIMIT_REACHED); + } + + auto pathElement = GetValidPathElement(); + + if (pathElement == nullptr) + { + return Result(Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_CAN_ONLY_BE_BUILT_ACROSS_PATHS); + } + + if (!MapCanBuildAt(_loc)) + { + return Result(Status::NotOwned, STR_CANT_POSITION_THIS_HERE, STR_LAND_NOT_OWNED_BY_PARK); + } + + auto baseHeight = _loc.z + kPathHeightStep; + BannerElement* existingBannerElement = MapGetBannerElementAt({ _loc.x, _loc.y, baseHeight }, _loc.direction); + if (existingBannerElement != nullptr) + { + return Result(Status::ItemAlreadyPlaced, STR_CANT_POSITION_THIS_HERE, STR_BANNER_SIGN_IN_THE_WAY); + } + + if (HasReachedBannerLimit()) + { + LOG_ERROR("No free banners available"); + return Result(Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_TOO_MANY_BANNERS_IN_GAME); + } + + auto* bannerEntry = OpenRCT2::ObjectManager::GetObjectEntry(_bannerType); + if (bannerEntry == nullptr) + { + LOG_ERROR("Banner entry not found for bannerType %u", _bannerType); + return Result(Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_ERR_BANNER_ELEMENT_NOT_FOUND); + } + res.Cost = bannerEntry->price; + res.SetData(BannerPlaceActionResult{}); + + return res; } - if (HasReachedBannerLimit()) + Result BannerPlaceAction::Execute() const { - LOG_ERROR("No free banners available"); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_TOO_MANY_BANNERS_IN_GAME); + auto res = Result(); + res.Position.x = _loc.x + 16; + res.Position.y = _loc.y + 16; + res.Position.z = _loc.z; + res.Expenditure = ExpenditureType::landscaping; + res.ErrorTitle = STR_CANT_POSITION_THIS_HERE; + + if (!MapCheckCapacityAndReorganise(_loc)) + { + LOG_ERROR("No free map elements."); + return Result(Status::NoFreeElements, STR_CANT_POSITION_THIS_HERE, STR_TILE_ELEMENT_LIMIT_REACHED); + } + + auto* bannerEntry = OpenRCT2::ObjectManager::GetObjectEntry(_bannerType); + if (bannerEntry == nullptr) + { + LOG_ERROR("Banner entry not found for bannerType %u", _bannerType); + return Result(Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_ERR_BANNER_ELEMENT_NOT_FOUND); + } + + auto banner = CreateBanner(); + if (banner == nullptr) + { + LOG_ERROR("No free banners available"); + return Result(Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_TOO_MANY_BANNERS_IN_GAME); + } + banner->flags = {}; + banner->text = {}; + banner->textColour = TextColour::white; + banner->type = _bannerType; // Banner must be deleted after this point in an early return + banner->colour = _primaryColour; + banner->position = TileCoordsXY(_loc); + + res.SetData(BannerPlaceActionResult{ banner->id }); + auto* bannerElement = TileElementInsert({ _loc, _loc.z + (2 * kCoordsZStep) }, 0b0000); + Guard::Assert(bannerElement != nullptr); + + bannerElement->SetClearanceZ(_loc.z + kPathClearance); + bannerElement->SetPosition(_loc.direction); + bannerElement->ResetAllowedEdges(); + bannerElement->SetIndex(banner->id); + bannerElement->SetGhost(GetFlags() & GAME_COMMAND_FLAG_GHOST); + + MapInvalidateTileFull(_loc); + MapAnimations::MarkTileForInvalidation(TileCoordsXY(_loc)); + + res.Cost = bannerEntry->price; + return res; } - auto* bannerEntry = OpenRCT2::ObjectManager::GetObjectEntry(_bannerType); - if (bannerEntry == nullptr) + PathElement* BannerPlaceAction::GetValidPathElement() const { - LOG_ERROR("Banner entry not found for bannerType %u", _bannerType); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_ERR_BANNER_ELEMENT_NOT_FOUND); + for (auto* pathElement : TileElementsView(_loc)) + { + if (pathElement->GetBaseZ() != _loc.z && pathElement->GetBaseZ() != _loc.z - kPathHeightStep) + continue; + + if (!(pathElement->GetEdges() & (1 << _loc.direction))) + continue; + + if (pathElement->IsGhost() && !(GetFlags() & GAME_COMMAND_FLAG_GHOST)) + continue; + + return pathElement; + } + + return nullptr; } - res.Cost = bannerEntry->price; - res.SetData(BannerPlaceActionResult{}); - - return res; -} - -GameActions::Result BannerPlaceAction::Execute() const -{ - auto res = GameActions::Result(); - res.Position.x = _loc.x + 16; - res.Position.y = _loc.y + 16; - res.Position.z = _loc.z; - res.Expenditure = ExpenditureType::landscaping; - res.ErrorTitle = STR_CANT_POSITION_THIS_HERE; - - if (!MapCheckCapacityAndReorganise(_loc)) - { - LOG_ERROR("No free map elements."); - return GameActions::Result( - GameActions::Status::NoFreeElements, STR_CANT_POSITION_THIS_HERE, STR_TILE_ELEMENT_LIMIT_REACHED); - } - - auto* bannerEntry = OpenRCT2::ObjectManager::GetObjectEntry(_bannerType); - if (bannerEntry == nullptr) - { - LOG_ERROR("Banner entry not found for bannerType %u", _bannerType); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_ERR_BANNER_ELEMENT_NOT_FOUND); - } - - auto banner = CreateBanner(); - if (banner == nullptr) - { - LOG_ERROR("No free banners available"); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_TOO_MANY_BANNERS_IN_GAME); - } - banner->flags = {}; - banner->text = {}; - banner->textColour = TextColour::white; - banner->type = _bannerType; // Banner must be deleted after this point in an early return - banner->colour = _primaryColour; - banner->position = TileCoordsXY(_loc); - - res.SetData(BannerPlaceActionResult{ banner->id }); - auto* bannerElement = TileElementInsert({ _loc, _loc.z + (2 * kCoordsZStep) }, 0b0000); - Guard::Assert(bannerElement != nullptr); - - bannerElement->SetClearanceZ(_loc.z + kPathClearance); - bannerElement->SetPosition(_loc.direction); - bannerElement->ResetAllowedEdges(); - bannerElement->SetIndex(banner->id); - bannerElement->SetGhost(GetFlags() & GAME_COMMAND_FLAG_GHOST); - - MapInvalidateTileFull(_loc); - MapAnimations::MarkTileForInvalidation(TileCoordsXY(_loc)); - - res.Cost = bannerEntry->price; - return res; -} - -PathElement* BannerPlaceAction::GetValidPathElement() const -{ - for (auto* pathElement : TileElementsView(_loc)) - { - if (pathElement->GetBaseZ() != _loc.z && pathElement->GetBaseZ() != _loc.z - kPathHeightStep) - continue; - - if (!(pathElement->GetEdges() & (1 << _loc.direction))) - continue; - - if (pathElement->IsGhost() && !(GetFlags() & GAME_COMMAND_FLAG_GHOST)) - continue; - - return pathElement; - } - - return nullptr; -} +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/BannerPlaceAction.h b/src/openrct2/actions/BannerPlaceAction.h index 8fcde8a294..9c75a204ba 100644 --- a/src/openrct2/actions/BannerPlaceAction.h +++ b/src/openrct2/actions/BannerPlaceAction.h @@ -11,30 +11,33 @@ #include "GameAction.h" -struct BannerPlaceActionResult +namespace OpenRCT2::GameActions { - BannerIndex bannerId = BannerIndex::GetNull(); -}; + struct BannerPlaceActionResult + { + BannerIndex bannerId = BannerIndex::GetNull(); + }; -class BannerPlaceAction final : public GameActionBase -{ -private: - CoordsXYZD _loc; - OpenRCT2::ObjectEntryIndex _bannerType{ kBannerNull }; - uint8_t _primaryColour{}; + class BannerPlaceAction final : public GameActionBase + { + private: + CoordsXYZD _loc; + ObjectEntryIndex _bannerType{ kBannerNull }; + uint8_t _primaryColour{}; -public: - BannerPlaceAction() = default; - BannerPlaceAction(const CoordsXYZD& loc, OpenRCT2::ObjectEntryIndex bannerType, colour_t primaryColour); + public: + BannerPlaceAction() = default; + BannerPlaceAction(const CoordsXYZD& loc, ObjectEntryIndex bannerType, colour_t primaryColour); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; -private: - OpenRCT2::PathElement* GetValidPathElement() const; -}; + private: + PathElement* GetValidPathElement() const; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/BannerRemoveAction.cpp b/src/openrct2/actions/BannerRemoveAction.cpp index 1320a4fbfa..201677beed 100644 --- a/src/openrct2/actions/BannerRemoveAction.cpp +++ b/src/openrct2/actions/BannerRemoveAction.cpp @@ -19,135 +19,138 @@ #include "../world/tile_element/BannerElement.h" #include "GameAction.h" -using namespace OpenRCT2; - -BannerRemoveAction::BannerRemoveAction(const CoordsXYZD& loc) - : _loc(loc) +namespace OpenRCT2::GameActions { -} - -void BannerRemoveAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit(_loc); -} - -uint16_t BannerRemoveAction::GetActionFlags() const -{ - return GameAction::GetActionFlags(); -} - -void BannerRemoveAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_loc); -} - -GameActions::Result BannerRemoveAction::Query() const -{ - auto res = GameActions::Result(); - res.Expenditure = ExpenditureType::landscaping; - res.Position.x = _loc.x + 16; - res.Position.y = _loc.y + 16; - res.Position.z = _loc.z; - res.ErrorTitle = STR_CANT_REMOVE_THIS; - - if (!LocationValid(_loc)) + BannerRemoveAction::BannerRemoveAction(const CoordsXYZD& loc) + : _loc(loc) { - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_REMOVE_THIS, STR_OFF_EDGE_OF_MAP); - } - if (!MapCanBuildAt({ _loc.x, _loc.y, _loc.z - 16 })) - { - return GameActions::Result(GameActions::Status::NotOwned, STR_CANT_REMOVE_THIS, STR_LAND_NOT_OWNED_BY_PARK); } - BannerElement* bannerElement = GetBannerElementAt(); - if (bannerElement == nullptr) + void BannerRemoveAction::AcceptParameters(GameActionParameterVisitor& visitor) { - LOG_ERROR("Invalid banner location, x = %d, y = %d, z = %d, direction = %d", _loc.x, _loc.y, _loc.z, _loc.direction); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_REMOVE_THIS, kStringIdNone); + visitor.Visit(_loc); } - auto bannerIndex = bannerElement->GetIndex(); - if (bannerIndex == BannerIndex::GetNull()) + uint16_t BannerRemoveAction::GetActionFlags() const { - LOG_ERROR("Invalid banner index %u", bannerIndex); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_REMOVE_THIS, kStringIdNone); + return GameAction::GetActionFlags(); } - auto banner = bannerElement->GetBanner(); - if (banner == nullptr) + void BannerRemoveAction::Serialise(DataSerialiser& stream) { - LOG_ERROR("Invalid banner index %u", bannerIndex); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_REMOVE_THIS, kStringIdNone); + GameAction::Serialise(stream); + + stream << DS_TAG(_loc); } - auto* bannerEntry = OpenRCT2::ObjectManager::GetObjectEntry(banner->type); - if (bannerEntry != nullptr) + Result BannerRemoveAction::Query() const { - res.Cost = -((bannerEntry->price * 3) / 4); + auto res = Result(); + res.Expenditure = ExpenditureType::landscaping; + res.Position.x = _loc.x + 16; + res.Position.y = _loc.y + 16; + res.Position.z = _loc.z; + res.ErrorTitle = STR_CANT_REMOVE_THIS; + + if (!LocationValid(_loc)) + { + return Result(Status::InvalidParameters, STR_CANT_REMOVE_THIS, STR_OFF_EDGE_OF_MAP); + } + if (!MapCanBuildAt({ _loc.x, _loc.y, _loc.z - 16 })) + { + return Result(Status::NotOwned, STR_CANT_REMOVE_THIS, STR_LAND_NOT_OWNED_BY_PARK); + } + + BannerElement* bannerElement = GetBannerElementAt(); + if (bannerElement == nullptr) + { + LOG_ERROR( + "Invalid banner location, x = %d, y = %d, z = %d, direction = %d", _loc.x, _loc.y, _loc.z, _loc.direction); + return Result(Status::InvalidParameters, STR_CANT_REMOVE_THIS, kStringIdNone); + } + + auto bannerIndex = bannerElement->GetIndex(); + if (bannerIndex == BannerIndex::GetNull()) + { + LOG_ERROR("Invalid banner index %u", bannerIndex); + return Result(Status::InvalidParameters, STR_CANT_REMOVE_THIS, kStringIdNone); + } + + auto banner = bannerElement->GetBanner(); + if (banner == nullptr) + { + LOG_ERROR("Invalid banner index %u", bannerIndex); + return Result(Status::InvalidParameters, STR_CANT_REMOVE_THIS, kStringIdNone); + } + + auto* bannerEntry = ObjectManager::GetObjectEntry(banner->type); + if (bannerEntry != nullptr) + { + res.Cost = -((bannerEntry->price * 3) / 4); + } + + return res; } - return res; -} - -GameActions::Result BannerRemoveAction::Execute() const -{ - auto res = GameActions::Result(); - res.Expenditure = ExpenditureType::landscaping; - res.Position.x = _loc.x + 16; - res.Position.y = _loc.y + 16; - res.Position.z = _loc.z; - res.ErrorTitle = STR_CANT_REMOVE_THIS; - - BannerElement* bannerElement = GetBannerElementAt(); - if (bannerElement == nullptr) + Result BannerRemoveAction::Execute() const { - LOG_ERROR("Invalid banner location, x = %d, y = %d, z = %d, direction = %d", _loc.x, _loc.y, _loc.z, _loc.direction); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_REMOVE_THIS, kStringIdNone); + auto res = Result(); + res.Expenditure = ExpenditureType::landscaping; + res.Position.x = _loc.x + 16; + res.Position.y = _loc.y + 16; + res.Position.z = _loc.z; + res.ErrorTitle = STR_CANT_REMOVE_THIS; + + BannerElement* bannerElement = GetBannerElementAt(); + if (bannerElement == nullptr) + { + LOG_ERROR( + "Invalid banner location, x = %d, y = %d, z = %d, direction = %d", _loc.x, _loc.y, _loc.z, _loc.direction); + return Result(Status::InvalidParameters, STR_CANT_REMOVE_THIS, kStringIdNone); + } + + auto bannerIndex = bannerElement->GetIndex(); + if (bannerIndex == BannerIndex::GetNull()) + { + LOG_ERROR("Invalid banner index %u", bannerIndex); + return Result(Status::InvalidParameters, STR_CANT_REMOVE_THIS, kStringIdNone); + } + + auto banner = bannerElement->GetBanner(); + if (banner == nullptr) + { + LOG_ERROR("Invalid banner index %u", bannerIndex); + return Result(Status::InvalidParameters, STR_CANT_REMOVE_THIS, kStringIdNone); + } + + auto* bannerEntry = ObjectManager::GetObjectEntry(banner->type); + if (bannerEntry != nullptr) + { + res.Cost = -((bannerEntry->price * 3) / 4); + } + + reinterpret_cast(bannerElement)->RemoveBannerEntry(); + MapInvalidateTileZoom1({ _loc, _loc.z, _loc.z + 32 }); + bannerElement->Remove(); + + return res; } - auto bannerIndex = bannerElement->GetIndex(); - if (bannerIndex == BannerIndex::GetNull()) + BannerElement* BannerRemoveAction::GetBannerElementAt() const { - LOG_ERROR("Invalid banner index %u", bannerIndex); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_REMOVE_THIS, kStringIdNone); + // Find the banner element at known z and position + for (auto* bannerElement : TileElementsView(_loc)) + { + if (bannerElement->GetBaseZ() != _loc.z) + continue; + if (bannerElement->IsGhost() && !(GetFlags() & GAME_COMMAND_FLAG_GHOST)) + continue; + if (bannerElement->GetPosition() != _loc.direction) + continue; + + return bannerElement; + } + + return nullptr; } - - auto banner = bannerElement->GetBanner(); - if (banner == nullptr) - { - LOG_ERROR("Invalid banner index %u", bannerIndex); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_REMOVE_THIS, kStringIdNone); - } - - auto* bannerEntry = OpenRCT2::ObjectManager::GetObjectEntry(banner->type); - if (bannerEntry != nullptr) - { - res.Cost = -((bannerEntry->price * 3) / 4); - } - - reinterpret_cast(bannerElement)->RemoveBannerEntry(); - MapInvalidateTileZoom1({ _loc, _loc.z, _loc.z + 32 }); - bannerElement->Remove(); - - return res; -} - -BannerElement* BannerRemoveAction::GetBannerElementAt() const -{ - // Find the banner element at known z and position - for (auto* bannerElement : TileElementsView(_loc)) - { - if (bannerElement->GetBaseZ() != _loc.z) - continue; - if (bannerElement->IsGhost() && !(GetFlags() & GAME_COMMAND_FLAG_GHOST)) - continue; - if (bannerElement->GetPosition() != _loc.direction) - continue; - - return bannerElement; - } - - return nullptr; -} +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/BannerRemoveAction.h b/src/openrct2/actions/BannerRemoveAction.h index 67100f9109..6108212809 100644 --- a/src/openrct2/actions/BannerRemoveAction.h +++ b/src/openrct2/actions/BannerRemoveAction.h @@ -11,23 +11,26 @@ #include "GameAction.h" -class BannerRemoveAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - CoordsXYZD _loc; + class BannerRemoveAction final : public GameActionBase + { + private: + CoordsXYZD _loc; -public: - BannerRemoveAction() = default; - BannerRemoveAction(const CoordsXYZD& loc); + public: + BannerRemoveAction() = default; + BannerRemoveAction(const CoordsXYZD& loc); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; -private: - OpenRCT2::BannerElement* GetBannerElementAt() const; -}; + private: + BannerElement* GetBannerElementAt() const; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/BannerSetColourAction.cpp b/src/openrct2/actions/BannerSetColourAction.cpp index 8a3d7c4125..579e22c661 100644 --- a/src/openrct2/actions/BannerSetColourAction.cpp +++ b/src/openrct2/actions/BannerSetColourAction.cpp @@ -17,93 +17,94 @@ #include "../world/tile_element/BannerElement.h" #include "GameAction.h" -using namespace OpenRCT2; - -BannerSetColourAction::BannerSetColourAction(const CoordsXYZD& loc, uint8_t primaryColour) - : _loc(loc) - , _primaryColour(primaryColour) +namespace OpenRCT2::GameActions { -} - -void BannerSetColourAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit(_loc); - visitor.Visit("primaryColour", _primaryColour); -} - -uint16_t BannerSetColourAction::GetActionFlags() const -{ - return GameAction::GetActionFlags() | GameActions::Flags::AllowWhilePaused; -} - -void BannerSetColourAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_loc) << DS_TAG(_primaryColour); -} - -GameActions::Result BannerSetColourAction::Query() const -{ - return QueryExecute(false); -} - -GameActions::Result BannerSetColourAction::Execute() const -{ - return QueryExecute(true); -} - -GameActions::Result BannerSetColourAction::QueryExecute(bool isExecuting) const -{ - auto res = GameActions::Result(); - res.Expenditure = ExpenditureType::landscaping; - res.Position.x = _loc.x + 16; - res.Position.y = _loc.y + 16; - res.Position.z = _loc.z; - res.ErrorTitle = STR_CANT_REPAINT_THIS; - - if (!LocationValid(_loc)) + BannerSetColourAction::BannerSetColourAction(const CoordsXYZD& loc, uint8_t primaryColour) + : _loc(loc) + , _primaryColour(primaryColour) { - LOG_ERROR("Invalid x / y coordinates: x = %d, y = %d", _loc.x, _loc.y); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_REPAINT_THIS, STR_OFF_EDGE_OF_MAP); } - if (_primaryColour > 31) + void BannerSetColourAction::AcceptParameters(GameActionParameterVisitor& visitor) { - LOG_ERROR("Invalid primary colour %u", _primaryColour); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_REPAINT_THIS, STR_ERR_INVALID_COLOUR); + visitor.Visit(_loc); + visitor.Visit("primaryColour", _primaryColour); } - if (!MapCanBuildAt({ _loc.x, _loc.y, _loc.z - 16 })) + uint16_t BannerSetColourAction::GetActionFlags() const { - return GameActions::Result(GameActions::Status::NotOwned, STR_CANT_REPAINT_THIS, STR_LAND_NOT_OWNED_BY_PARK); + return GameAction::GetActionFlags() | Flags::AllowWhilePaused; } - auto bannerElement = MapGetBannerElementAt(_loc, _loc.direction); - - if (bannerElement == nullptr) + void BannerSetColourAction::Serialise(DataSerialiser& stream) { - LOG_ERROR("No banner at x = %d, y = %d, z = %d, direction = %u", _loc.x, _loc.y, _loc.z, _loc.direction); - return GameActions::Result(GameActions::Status::Unknown, STR_CANT_REPAINT_THIS, STR_ERR_BANNER_ELEMENT_NOT_FOUND); + GameAction::Serialise(stream); + + stream << DS_TAG(_loc) << DS_TAG(_primaryColour); } - auto index = bannerElement->GetIndex(); - auto banner = GetBanner(index); - if (banner == nullptr) + Result BannerSetColourAction::Query() const { - LOG_ERROR("Invalid banner index %u", index); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_REPAINT_THIS, kStringIdNone); + return QueryExecute(false); } - if (isExecuting) + Result BannerSetColourAction::Execute() const { - auto intent = Intent(INTENT_ACTION_UPDATE_BANNER); - intent.PutExtra(INTENT_EXTRA_BANNER_INDEX, index); - ContextBroadcastIntent(&intent); - - banner->colour = _primaryColour; - MapInvalidateTileZoom1({ _loc, _loc.z, _loc.z + 32 }); + return QueryExecute(true); } - return res; -} + Result BannerSetColourAction::QueryExecute(bool isExecuting) const + { + auto res = Result(); + res.Expenditure = ExpenditureType::landscaping; + res.Position.x = _loc.x + 16; + res.Position.y = _loc.y + 16; + res.Position.z = _loc.z; + res.ErrorTitle = STR_CANT_REPAINT_THIS; + + if (!LocationValid(_loc)) + { + LOG_ERROR("Invalid x / y coordinates: x = %d, y = %d", _loc.x, _loc.y); + return Result(Status::InvalidParameters, STR_CANT_REPAINT_THIS, STR_OFF_EDGE_OF_MAP); + } + + if (_primaryColour > 31) + { + LOG_ERROR("Invalid primary colour %u", _primaryColour); + return Result(Status::InvalidParameters, STR_CANT_REPAINT_THIS, STR_ERR_INVALID_COLOUR); + } + + if (!MapCanBuildAt({ _loc.x, _loc.y, _loc.z - 16 })) + { + return Result(Status::NotOwned, STR_CANT_REPAINT_THIS, STR_LAND_NOT_OWNED_BY_PARK); + } + + auto bannerElement = MapGetBannerElementAt(_loc, _loc.direction); + + if (bannerElement == nullptr) + { + LOG_ERROR("No banner at x = %d, y = %d, z = %d, direction = %u", _loc.x, _loc.y, _loc.z, _loc.direction); + return Result(Status::Unknown, STR_CANT_REPAINT_THIS, STR_ERR_BANNER_ELEMENT_NOT_FOUND); + } + + auto index = bannerElement->GetIndex(); + auto banner = GetBanner(index); + if (banner == nullptr) + { + LOG_ERROR("Invalid banner index %u", index); + return Result(Status::InvalidParameters, STR_CANT_REPAINT_THIS, kStringIdNone); + } + + if (isExecuting) + { + auto intent = Intent(INTENT_ACTION_UPDATE_BANNER); + intent.PutExtra(INTENT_EXTRA_BANNER_INDEX, index); + ContextBroadcastIntent(&intent); + + banner->colour = _primaryColour; + MapInvalidateTileZoom1({ _loc, _loc.z, _loc.z + 32 }); + } + + return res; + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/BannerSetColourAction.h b/src/openrct2/actions/BannerSetColourAction.h index 5a1a663476..546c1dd68a 100644 --- a/src/openrct2/actions/BannerSetColourAction.h +++ b/src/openrct2/actions/BannerSetColourAction.h @@ -11,24 +11,27 @@ #include "GameAction.h" -class BannerSetColourAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - CoordsXYZD _loc; - uint8_t _primaryColour{}; + class BannerSetColourAction final : public GameActionBase + { + private: + CoordsXYZD _loc; + uint8_t _primaryColour{}; -public: - BannerSetColourAction() = default; - BannerSetColourAction(const CoordsXYZD& loc, uint8_t primaryColour); + public: + BannerSetColourAction() = default; + BannerSetColourAction(const CoordsXYZD& loc, uint8_t primaryColour); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; -private: - OpenRCT2::GameActions::Result QueryExecute(bool isExecuting) const; -}; + private: + Result QueryExecute(bool isExecuting) const; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/BannerSetNameAction.cpp b/src/openrct2/actions/BannerSetNameAction.cpp index 1b069ee941..7cd2caf795 100644 --- a/src/openrct2/actions/BannerSetNameAction.cpp +++ b/src/openrct2/actions/BannerSetNameAction.cpp @@ -19,83 +19,81 @@ #include "../world/tile_element/BannerElement.h" #include "GameAction.h" -using namespace OpenRCT2; - -BannerSetNameAction::BannerSetNameAction(BannerIndex bannerIndex, const std::string& name) - : _bannerIndex(bannerIndex) - , _name(name) +namespace OpenRCT2::GameActions { -} - -void BannerSetNameAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit("id", _bannerIndex); - visitor.Visit("name", _name); -} - -uint16_t BannerSetNameAction::GetActionFlags() const -{ - return GameAction::GetActionFlags() | GameActions::Flags::AllowWhilePaused; -} - -void BannerSetNameAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - stream << DS_TAG(_bannerIndex) << DS_TAG(_name); -} - -GameActions::Result BannerSetNameAction::Query() const -{ - auto banner = GetBanner(_bannerIndex); - if (banner == nullptr) + BannerSetNameAction::BannerSetNameAction(BannerIndex bannerIndex, const std::string& name) + : _bannerIndex(bannerIndex) + , _name(name) { - LOG_ERROR("Banner not found for bannerIndex %d", _bannerIndex); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_RENAME_BANNER, STR_ERR_BANNER_ELEMENT_NOT_FOUND); } - TileElement* tileElement = BannerGetTileElement(_bannerIndex); - - if (tileElement == nullptr) + void BannerSetNameAction::AcceptParameters(GameActionParameterVisitor& visitor) { - LOG_ERROR("Banner tile element not found for bannerIndex %d", _bannerIndex); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_RENAME_BANNER, STR_ERR_BANNER_ELEMENT_NOT_FOUND); + visitor.Visit("id", _bannerIndex); + visitor.Visit("name", _name); } - BannerElement* bannerElement = tileElement->AsBanner(); - CoordsXYZD loc = { banner->position.ToCoordsXY(), bannerElement->GetBaseZ(), bannerElement->GetPosition() }; - - if (!LocationValid(loc)) + uint16_t BannerSetNameAction::GetActionFlags() const { - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_RENAME_BANNER, STR_OFF_EDGE_OF_MAP); - } - if (!MapCanBuildAt({ loc.x, loc.y, loc.z - 16 })) - { - return GameActions::Result(GameActions::Status::NotOwned, STR_CANT_RENAME_BANNER, STR_LAND_NOT_OWNED_BY_PARK); + return GameAction::GetActionFlags() | Flags::AllowWhilePaused; } - return GameActions::Result(); -} - -GameActions::Result BannerSetNameAction::Execute() const -{ - auto banner = GetBanner(_bannerIndex); - if (banner == nullptr) + void BannerSetNameAction::Serialise(DataSerialiser& stream) { - LOG_ERROR("Banner not found for bannerIndex %d", _bannerIndex); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_RENAME_BANNER, STR_ERR_BANNER_ELEMENT_NOT_FOUND); + GameAction::Serialise(stream); + stream << DS_TAG(_bannerIndex) << DS_TAG(_name); } - banner->text = _name; + Result BannerSetNameAction::Query() const + { + auto banner = GetBanner(_bannerIndex); + if (banner == nullptr) + { + LOG_ERROR("Banner not found for bannerIndex %d", _bannerIndex); + return Result(Status::InvalidParameters, STR_CANT_RENAME_BANNER, STR_ERR_BANNER_ELEMENT_NOT_FOUND); + } - auto intent = Intent(INTENT_ACTION_UPDATE_BANNER); - intent.PutExtra(INTENT_EXTRA_BANNER_INDEX, _bannerIndex); - ContextBroadcastIntent(&intent); + TileElement* tileElement = BannerGetTileElement(_bannerIndex); - ScrollingTextInvalidate(); - GfxInvalidateScreen(); + if (tileElement == nullptr) + { + LOG_ERROR("Banner tile element not found for bannerIndex %d", _bannerIndex); + return Result(Status::InvalidParameters, STR_CANT_RENAME_BANNER, STR_ERR_BANNER_ELEMENT_NOT_FOUND); + } - return GameActions::Result(); -} + BannerElement* bannerElement = tileElement->AsBanner(); + CoordsXYZD loc = { banner->position.ToCoordsXY(), bannerElement->GetBaseZ(), bannerElement->GetPosition() }; + + if (!LocationValid(loc)) + { + return Result(Status::InvalidParameters, STR_CANT_RENAME_BANNER, STR_OFF_EDGE_OF_MAP); + } + if (!MapCanBuildAt({ loc.x, loc.y, loc.z - 16 })) + { + return Result(Status::NotOwned, STR_CANT_RENAME_BANNER, STR_LAND_NOT_OWNED_BY_PARK); + } + + return Result(); + } + + Result BannerSetNameAction::Execute() const + { + auto banner = GetBanner(_bannerIndex); + if (banner == nullptr) + { + LOG_ERROR("Banner not found for bannerIndex %d", _bannerIndex); + return Result(Status::InvalidParameters, STR_CANT_RENAME_BANNER, STR_ERR_BANNER_ELEMENT_NOT_FOUND); + } + + banner->text = _name; + + auto intent = Intent(INTENT_ACTION_UPDATE_BANNER); + intent.PutExtra(INTENT_EXTRA_BANNER_INDEX, _bannerIndex); + ContextBroadcastIntent(&intent); + + ScrollingTextInvalidate(); + GfxInvalidateScreen(); + + return Result(); + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/BannerSetNameAction.h b/src/openrct2/actions/BannerSetNameAction.h index 01e09fd8dc..212feea9c4 100644 --- a/src/openrct2/actions/BannerSetNameAction.h +++ b/src/openrct2/actions/BannerSetNameAction.h @@ -11,21 +11,24 @@ #include "GameAction.h" -class BannerSetNameAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - BannerIndex _bannerIndex{ BannerIndex::GetNull() }; - std::string _name; + class BannerSetNameAction final : public GameActionBase + { + private: + BannerIndex _bannerIndex{ BannerIndex::GetNull() }; + std::string _name; -public: - BannerSetNameAction() = default; - BannerSetNameAction(BannerIndex bannerIndex, const std::string& name); + public: + BannerSetNameAction() = default; + BannerSetNameAction(BannerIndex bannerIndex, const std::string& name); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; -}; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/BannerSetStyleAction.cpp b/src/openrct2/actions/BannerSetStyleAction.cpp index e6d3e00319..13755265b2 100644 --- a/src/openrct2/actions/BannerSetStyleAction.cpp +++ b/src/openrct2/actions/BannerSetStyleAction.cpp @@ -18,172 +18,167 @@ #include "../world/tile_element/BannerElement.h" #include "GameAction.h" -using namespace OpenRCT2; - -BannerSetStyleAction::BannerSetStyleAction(BannerSetStyleType type, BannerIndex bannerIndex, uint8_t parameter) - : _type(type) - , _bannerIndex(bannerIndex) - , _parameter(parameter) +namespace OpenRCT2::GameActions { -} - -void BannerSetStyleAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit("id", _bannerIndex); - visitor.Visit("type", _type); - visitor.Visit("parameter", _parameter); -} - -uint16_t BannerSetStyleAction::GetActionFlags() const -{ - return GameAction::GetActionFlags() | GameActions::Flags::AllowWhilePaused; -} - -void BannerSetStyleAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_type) << DS_TAG(_bannerIndex) << DS_TAG(_parameter); -} - -GameActions::Result BannerSetStyleAction::Query() const -{ - StringId errorTitle = STR_CANT_REPAINT_THIS; - if (_type == BannerSetStyleType::NoEntry) + BannerSetStyleAction::BannerSetStyleAction(BannerSetStyleType type, BannerIndex bannerIndex, uint8_t parameter) + : _type(type) + , _bannerIndex(bannerIndex) + , _parameter(parameter) { - errorTitle = STR_CANT_RENAME_BANNER; } - auto res = GameActions::Result(); - - auto banner = GetBanner(_bannerIndex); - if (banner == nullptr) + void BannerSetStyleAction::AcceptParameters(GameActionParameterVisitor& visitor) { - LOG_ERROR("Banner not found for bannerIndex %d", _bannerIndex); - return GameActions::Result(GameActions::Status::InvalidParameters, errorTitle, STR_ERR_BANNER_ELEMENT_NOT_FOUND); + visitor.Visit("id", _bannerIndex); + visitor.Visit("type", _type); + visitor.Visit("parameter", _parameter); } - res.Expenditure = ExpenditureType::landscaping; - auto location = banner->position.ToCoordsXY().ToTileCentre(); - res.Position = { location, TileElementHeight(location) }; - - TileElement* tileElement = BannerGetTileElement(_bannerIndex); - - if (tileElement == nullptr) + uint16_t BannerSetStyleAction::GetActionFlags() const { - LOG_ERROR("Banner tile element not found for bannerIndex %d", _bannerIndex); - return GameActions::Result(GameActions::Status::InvalidParameters, errorTitle, STR_ERR_BANNER_ELEMENT_NOT_FOUND); + return GameAction::GetActionFlags() | Flags::AllowWhilePaused; } - BannerElement* bannerElement = tileElement->AsBanner(); - CoordsXYZ loc = { banner->position.ToCoordsXY(), bannerElement->GetBaseZ() }; + void BannerSetStyleAction::Serialise(DataSerialiser& stream) + { + GameAction::Serialise(stream); - if (!LocationValid(loc)) - { - return GameActions::Result(GameActions::Status::InvalidParameters, errorTitle, STR_OFF_EDGE_OF_MAP); - } - if (!MapCanBuildAt({ loc.x, loc.y, loc.z - 16 })) - { - return GameActions::Result(GameActions::Status::NotOwned, errorTitle, STR_LAND_NOT_OWNED_BY_PARK); + stream << DS_TAG(_type) << DS_TAG(_bannerIndex) << DS_TAG(_parameter); } - switch (_type) + Result BannerSetStyleAction::Query() const { - case BannerSetStyleType::PrimaryColour: - if (_parameter > COLOUR_COUNT) - { - LOG_ERROR("Invalid primary colour %u", _parameter); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_REPAINT_THIS, STR_ERR_INVALID_COLOUR); - } - break; - - case BannerSetStyleType::TextColour: - if (_parameter > 13) - { - LOG_ERROR("Invalid text colour %u", _parameter); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_REPAINT_THIS, STR_ERR_INVALID_COLOUR); - } - break; - case BannerSetStyleType::NoEntry: - if (tileElement->AsBanner() == nullptr) - { - LOG_ERROR("Tile element was not a banner."); - return GameActions::Result(GameActions::Status::Unknown, STR_CANT_RENAME_BANNER, kStringIdNone); - } - break; - default: - LOG_ERROR("Invalid banner style type %u", _type); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_REPAINT_THIS, STR_ERR_VALUE_OUT_OF_RANGE); - } - return res; -} - -GameActions::Result BannerSetStyleAction::Execute() const -{ - auto res = GameActions::Result(); - - auto banner = GetBanner(_bannerIndex); - if (banner == nullptr) - { - LOG_ERROR("Banner not found for bannerIndex %d", _bannerIndex); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_REPAINT_THIS, STR_ERR_BANNER_ELEMENT_NOT_FOUND); - } - - res.Expenditure = ExpenditureType::landscaping; - auto location = banner->position.ToCoordsXY().ToTileCentre(); - res.Position = { location, TileElementHeight(location) }; - - TileElement* tileElement = BannerGetTileElement(_bannerIndex); - - if (tileElement == nullptr) - { - LOG_ERROR("Banner tile element not found for bannerIndex &u", _bannerIndex); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_REPAINT_THIS, kStringIdNone); - } - - switch (_type) - { - case BannerSetStyleType::PrimaryColour: - banner->colour = _parameter; - break; - case BannerSetStyleType::TextColour: - banner->textColour = static_cast(_parameter); - break; - case BannerSetStyleType::NoEntry: + StringId errorTitle = STR_CANT_REPAINT_THIS; + if (_type == BannerSetStyleType::NoEntry) { - BannerElement* bannerElement = tileElement->AsBanner(); - if (bannerElement == nullptr) - { - LOG_ERROR("Tile element was not a banner."); - return GameActions::Result( - GameActions::Status::Unknown, STR_CANT_REPAINT_THIS, STR_ERR_BANNER_ELEMENT_NOT_FOUND); - } - - banner->flags.set(BannerFlag::noEntry, (_parameter != 0)); - uint8_t allowedEdges = 0xF; - if (banner->flags.has(BannerFlag::noEntry)) - { - allowedEdges &= ~(1 << bannerElement->GetPosition()); - } - bannerElement->SetAllowedEdges(allowedEdges); - break; + errorTitle = STR_CANT_RENAME_BANNER; } - default: - LOG_ERROR("Invalid banner style type %u", _type); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_REPAINT_THIS, STR_ERR_VALUE_OUT_OF_RANGE); + + auto res = Result(); + + auto banner = GetBanner(_bannerIndex); + if (banner == nullptr) + { + LOG_ERROR("Banner not found for bannerIndex %d", _bannerIndex); + return Result(Status::InvalidParameters, errorTitle, STR_ERR_BANNER_ELEMENT_NOT_FOUND); + } + + res.Expenditure = ExpenditureType::landscaping; + auto location = banner->position.ToCoordsXY().ToTileCentre(); + res.Position = { location, TileElementHeight(location) }; + + TileElement* tileElement = BannerGetTileElement(_bannerIndex); + + if (tileElement == nullptr) + { + LOG_ERROR("Banner tile element not found for bannerIndex %d", _bannerIndex); + return Result(Status::InvalidParameters, errorTitle, STR_ERR_BANNER_ELEMENT_NOT_FOUND); + } + + BannerElement* bannerElement = tileElement->AsBanner(); + CoordsXYZ loc = { banner->position.ToCoordsXY(), bannerElement->GetBaseZ() }; + + if (!LocationValid(loc)) + { + return Result(Status::InvalidParameters, errorTitle, STR_OFF_EDGE_OF_MAP); + } + if (!MapCanBuildAt({ loc.x, loc.y, loc.z - 16 })) + { + return Result(Status::NotOwned, errorTitle, STR_LAND_NOT_OWNED_BY_PARK); + } + + switch (_type) + { + case BannerSetStyleType::PrimaryColour: + if (_parameter > COLOUR_COUNT) + { + LOG_ERROR("Invalid primary colour %u", _parameter); + return Result(Status::InvalidParameters, STR_CANT_REPAINT_THIS, STR_ERR_INVALID_COLOUR); + } + break; + + case BannerSetStyleType::TextColour: + if (_parameter > 13) + { + LOG_ERROR("Invalid text colour %u", _parameter); + return Result(Status::InvalidParameters, STR_CANT_REPAINT_THIS, STR_ERR_INVALID_COLOUR); + } + break; + case BannerSetStyleType::NoEntry: + if (tileElement->AsBanner() == nullptr) + { + LOG_ERROR("Tile element was not a banner."); + return Result(Status::Unknown, STR_CANT_RENAME_BANNER, kStringIdNone); + } + break; + default: + LOG_ERROR("Invalid banner style type %u", _type); + return Result(Status::InvalidParameters, STR_CANT_REPAINT_THIS, STR_ERR_VALUE_OUT_OF_RANGE); + } + return res; } - auto intent = Intent(INTENT_ACTION_UPDATE_BANNER); - intent.PutExtra(INTENT_EXTRA_BANNER_INDEX, _bannerIndex); - ContextBroadcastIntent(&intent); + Result BannerSetStyleAction::Execute() const + { + auto res = Result(); - ScrollingTextInvalidate(); - GfxInvalidateScreen(); + auto banner = GetBanner(_bannerIndex); + if (banner == nullptr) + { + LOG_ERROR("Banner not found for bannerIndex %d", _bannerIndex); + return Result(Status::InvalidParameters, STR_CANT_REPAINT_THIS, STR_ERR_BANNER_ELEMENT_NOT_FOUND); + } - return res; -} + res.Expenditure = ExpenditureType::landscaping; + auto location = banner->position.ToCoordsXY().ToTileCentre(); + res.Position = { location, TileElementHeight(location) }; + + TileElement* tileElement = BannerGetTileElement(_bannerIndex); + + if (tileElement == nullptr) + { + LOG_ERROR("Banner tile element not found for bannerIndex &u", _bannerIndex); + return Result(Status::InvalidParameters, STR_CANT_REPAINT_THIS, kStringIdNone); + } + + switch (_type) + { + case BannerSetStyleType::PrimaryColour: + banner->colour = _parameter; + break; + case BannerSetStyleType::TextColour: + banner->textColour = static_cast(_parameter); + break; + case BannerSetStyleType::NoEntry: + { + BannerElement* bannerElement = tileElement->AsBanner(); + if (bannerElement == nullptr) + { + LOG_ERROR("Tile element was not a banner."); + return Result(Status::Unknown, STR_CANT_REPAINT_THIS, STR_ERR_BANNER_ELEMENT_NOT_FOUND); + } + + banner->flags.set(BannerFlag::noEntry, (_parameter != 0)); + uint8_t allowedEdges = 0xF; + if (banner->flags.has(BannerFlag::noEntry)) + { + allowedEdges &= ~(1 << bannerElement->GetPosition()); + } + bannerElement->SetAllowedEdges(allowedEdges); + break; + } + default: + LOG_ERROR("Invalid banner style type %u", _type); + return Result(Status::InvalidParameters, STR_CANT_REPAINT_THIS, STR_ERR_VALUE_OUT_OF_RANGE); + } + + auto intent = Intent(INTENT_ACTION_UPDATE_BANNER); + intent.PutExtra(INTENT_EXTRA_BANNER_INDEX, _bannerIndex); + ContextBroadcastIntent(&intent); + + ScrollingTextInvalidate(); + GfxInvalidateScreen(); + + return res; + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/BannerSetStyleAction.h b/src/openrct2/actions/BannerSetStyleAction.h index 20de773ba6..bca3226911 100644 --- a/src/openrct2/actions/BannerSetStyleAction.h +++ b/src/openrct2/actions/BannerSetStyleAction.h @@ -11,32 +11,35 @@ #include "GameAction.h" -// There is also the BannerSetColourAction that sets primary colour but this action takes banner index rather than x, y, z, -// direction -enum class BannerSetStyleType : uint8_t +namespace OpenRCT2::GameActions { - PrimaryColour, - TextColour, - NoEntry, - Count -}; + // There is also the BannerSetColourAction that sets primary colour but this action takes banner index rather than x, y, z, + // direction + enum class BannerSetStyleType : uint8_t + { + PrimaryColour, + TextColour, + NoEntry, + Count + }; -class BannerSetStyleAction final : public GameActionBase -{ -private: - BannerSetStyleType _type{ BannerSetStyleType::Count }; - BannerIndex _bannerIndex{ BannerIndex::GetNull() }; - uint8_t _parameter{}; + class BannerSetStyleAction final : public GameActionBase + { + private: + BannerSetStyleType _type{ BannerSetStyleType::Count }; + BannerIndex _bannerIndex{ BannerIndex::GetNull() }; + uint8_t _parameter{}; -public: - BannerSetStyleAction() = default; - BannerSetStyleAction(BannerSetStyleType type, BannerIndex bannerIndex, uint8_t parameter); + public: + BannerSetStyleAction() = default; + BannerSetStyleAction(BannerSetStyleType type, BannerIndex bannerIndex, uint8_t parameter); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; -}; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/CheatSetAction.cpp b/src/openrct2/actions/CheatSetAction.cpp index 068bebf66b..3147d11d64 100644 --- a/src/openrct2/actions/CheatSetAction.cpp +++ b/src/openrct2/actions/CheatSetAction.cpp @@ -45,823 +45,826 @@ #include "ParkSetLoanAction.h" #include "ParkSetParameterAction.h" -using namespace OpenRCT2; - -using ParametersRange = std::pair, std::pair>; - -CheatSetAction::CheatSetAction(CheatType cheatType, int64_t param1, int64_t param2) - : _cheatType(static_cast(cheatType)) - , _param1(param1) - , _param2(param2) +namespace OpenRCT2::GameActions { -} + using ParametersRange = std::pair, std::pair>; -void CheatSetAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit("type", _cheatType); - visitor.Visit("param1", _param1); - visitor.Visit("param2", _param2); -} - -uint16_t CheatSetAction::GetActionFlags() const -{ - return GameAction::GetActionFlags() | GameActions::Flags::AllowWhilePaused; -} - -void CheatSetAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - stream << DS_TAG(_cheatType) << DS_TAG(_param1) << DS_TAG(_param2); -} - -GameActions::Result CheatSetAction::Query() const -{ - if (static_cast(_cheatType) >= static_cast(CheatType::Count)) + CheatSetAction::CheatSetAction(CheatType cheatType, int64_t param1, int64_t param2) + : _cheatType(static_cast(cheatType)) + , _param1(param1) + , _param2(param2) { - LOG_ERROR("Invalid cheat type %u", _cheatType); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_VALUE_OUT_OF_RANGE); } - ParametersRange validRange = GetParameterRange(static_cast(_cheatType.id)); - - if (_param1 < validRange.first.first || _param1 > validRange.first.second) + void CheatSetAction::AcceptParameters(GameActionParameterVisitor& visitor) { - LOG_ERROR( - "The first cheat parameter is out of range. Value = %d, min = %d, max = %d", _param1, validRange.first.first, - validRange.first.second); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_VALUE_OUT_OF_RANGE); - } - if (_param2 < validRange.second.first || _param2 > validRange.second.second) - { - LOG_ERROR( - "The second cheat parameter is out of range. Value = %d, min = %d, max = %d", _param2, validRange.second.first, - validRange.second.second); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_VALUE_OUT_OF_RANGE); + visitor.Visit("type", _cheatType); + visitor.Visit("param1", _param1); + visitor.Visit("param2", _param2); } - return GameActions::Result(); -} - -GameActions::Result CheatSetAction::Execute() const -{ - auto& gameState = getGameState(); - auto* windowMgr = Ui::GetWindowManager(); - - switch (static_cast(_cheatType.id)) + uint16_t CheatSetAction::GetActionFlags() const { - case CheatType::SandboxMode: - gameState.cheats.sandboxMode = _param1 != 0; - windowMgr->InvalidateByClass(WindowClass::Map); - windowMgr->InvalidateByClass(WindowClass::Footpath); - break; - case CheatType::DisableClearanceChecks: - gameState.cheats.disableClearanceChecks = _param1 != 0; - // Required to update the clearance checks overlay on the Cheats button. - windowMgr->InvalidateByClass(WindowClass::TopToolbar); - break; - case CheatType::DisableSupportLimits: - gameState.cheats.disableSupportLimits = _param1 != 0; - break; - case CheatType::ShowAllOperatingModes: - gameState.cheats.showAllOperatingModes = _param1 != 0; - break; - case CheatType::ShowVehiclesFromOtherTrackTypes: - gameState.cheats.showVehiclesFromOtherTrackTypes = _param1 != 0; - break; - case CheatType::FastLiftHill: - gameState.cheats.unlockOperatingLimits = _param1 != 0; - break; - case CheatType::DisableBrakesFailure: - gameState.cheats.disableBrakesFailure = _param1 != 0; - break; - case CheatType::DisableAllBreakdowns: - gameState.cheats.disableAllBreakdowns = _param1 != 0; - break; - case CheatType::DisableTrainLengthLimit: - gameState.cheats.disableTrainLengthLimit = _param1 != 0; - break; - case CheatType::EnableChainLiftOnAllTrack: - gameState.cheats.enableChainLiftOnAllTrack = _param1 != 0; - break; - case CheatType::BuildInPauseMode: - gameState.cheats.buildInPauseMode = _param1 != 0; - break; - case CheatType::IgnoreRideIntensity: - gameState.cheats.ignoreRideIntensity = _param1 != 0; - break; - case CheatType::IgnorePrice: - gameState.cheats.ignorePrice = _param1 != 0; - break; - case CheatType::DisableVandalism: - gameState.cheats.disableVandalism = _param1 != 0; - break; - case CheatType::DisableLittering: - gameState.cheats.disableLittering = _param1 != 0; - break; - case CheatType::NoMoney: - SetScenarioNoMoney(_param1 != 0); - break; - case CheatType::AddMoney: - AddMoney(_param1); - break; - case CheatType::SetMoney: - SetMoney(_param1); - break; - case CheatType::ClearLoan: - ClearLoan(); - break; - case CheatType::SetGuestParameter: - SetGuestParameter(_param1, _param2); - break; - case CheatType::GenerateGuests: - GenerateGuests(_param1); - break; - case CheatType::RemoveAllGuests: - RemoveAllGuests(); - break; - case CheatType::GiveAllGuests: - GiveObjectToGuests(_param1); - break; - case CheatType::SetGrassLength: - SetGrassLength(_param1); - break; - case CheatType::WaterPlants: - WaterPlants(); - break; - case CheatType::FixVandalism: - FixVandalism(); - break; - case CheatType::RemoveLitter: - RemoveLitter(); - break; - case CheatType::DisablePlantAging: - gameState.cheats.disablePlantAging = _param1 != 0; - break; - case CheatType::SetStaffSpeed: - SetStaffSpeed(_param1); - break; - case CheatType::RenewRides: - RenewRides(); - break; - case CheatType::MakeDestructible: - gameState.cheats.makeAllDestructible = _param1 != 0; - windowMgr->InvalidateByClass(WindowClass::Ride); - break; - case CheatType::FixRides: - FixBrokenRides(); - break; - case CheatType::ResetCrashStatus: - ResetRideCrashStatus(); - break; - case CheatType::TenMinuteInspections: - Set10MinuteInspection(); - break; - case CheatType::WinScenario: - ScenarioSuccess(gameState); - break; - case CheatType::ForceWeather: - // Todo - make sure this is safe - ClimateForceWeather(WeatherType{ static_cast(_param1) }); - break; - case CheatType::FreezeWeather: - gameState.cheats.freezeWeather = _param1 != 0; - break; - case CheatType::NeverendingMarketing: - gameState.cheats.neverendingMarketing = _param1 != 0; - break; - case CheatType::OpenClosePark: - ParkSetOpen(!Park::IsOpen(gameState.park)); - break; - case CheatType::HaveFun: - gameState.scenarioOptions.objective.Type = Scenario::ObjectiveType::haveFun; - break; - case CheatType::SetForcedParkRating: - Park::SetForcedRating(_param1); - break; - case CheatType::AllowArbitraryRideTypeChanges: - gameState.cheats.allowArbitraryRideTypeChanges = _param1 != 0; - windowMgr->InvalidateByClass(WindowClass::Ride); - break; - case CheatType::OwnAllLand: - OwnAllLand(); - break; - case CheatType::DisableRideValueAging: - gameState.cheats.disableRideValueAging = _param1 != 0; - break; - case CheatType::IgnoreResearchStatus: - gameState.cheats.ignoreResearchStatus = _param1 != 0; - break; - case CheatType::EnableAllDrawableTrackPieces: - gameState.cheats.enableAllDrawableTrackPieces = _param1 != 0; - break; - case CheatType::CreateDucks: - CreateDucks(_param1); - break; - case CheatType::RemoveDucks: - Duck::RemoveAll(); - break; - case CheatType::AllowTrackPlaceInvalidHeights: - gameState.cheats.allowTrackPlaceInvalidHeights = _param1 != 0; - break; - case CheatType::AllowRegularPathAsQueue: - gameState.cheats.allowRegularPathAsQueue = _param1 != 0; - break; - case CheatType::AllowSpecialColourSchemes: - gameState.cheats.allowSpecialColourSchemes = static_cast(_param1); - break; - case CheatType::RemoveParkFences: - RemoveParkFences(); - break; - default: + return GameAction::GetActionFlags() | Flags::AllowWhilePaused; + } + + void CheatSetAction::Serialise(DataSerialiser& stream) + { + GameAction::Serialise(stream); + stream << DS_TAG(_cheatType) << DS_TAG(_param1) << DS_TAG(_param2); + } + + Result CheatSetAction::Query() const + { + if (static_cast(_cheatType) >= static_cast(CheatType::Count)) { - LOG_ERROR("Invalid cheat type %d", _cheatType.id); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_VALUE_OUT_OF_RANGE); + LOG_ERROR("Invalid cheat type %u", _cheatType); + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_VALUE_OUT_OF_RANGE); + } + + ParametersRange validRange = GetParameterRange(static_cast(_cheatType.id)); + + if (_param1 < validRange.first.first || _param1 > validRange.first.second) + { + LOG_ERROR( + "The first cheat parameter is out of range. Value = %d, min = %d, max = %d", _param1, validRange.first.first, + validRange.first.second); + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_VALUE_OUT_OF_RANGE); + } + if (_param2 < validRange.second.first || _param2 > validRange.second.second) + { + LOG_ERROR( + "The second cheat parameter is out of range. Value = %d, min = %d, max = %d", _param2, validRange.second.first, + validRange.second.second); + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_VALUE_OUT_OF_RANGE); + } + + return Result(); + } + + Result CheatSetAction::Execute() const + { + auto& gameState = getGameState(); + auto* windowMgr = Ui::GetWindowManager(); + + switch (static_cast(_cheatType.id)) + { + case CheatType::SandboxMode: + gameState.cheats.sandboxMode = _param1 != 0; + windowMgr->InvalidateByClass(WindowClass::Map); + windowMgr->InvalidateByClass(WindowClass::Footpath); + break; + case CheatType::DisableClearanceChecks: + gameState.cheats.disableClearanceChecks = _param1 != 0; + // Required to update the clearance checks overlay on the Cheats button. + windowMgr->InvalidateByClass(WindowClass::TopToolbar); + break; + case CheatType::DisableSupportLimits: + gameState.cheats.disableSupportLimits = _param1 != 0; + break; + case CheatType::ShowAllOperatingModes: + gameState.cheats.showAllOperatingModes = _param1 != 0; + break; + case CheatType::ShowVehiclesFromOtherTrackTypes: + gameState.cheats.showVehiclesFromOtherTrackTypes = _param1 != 0; + break; + case CheatType::FastLiftHill: + gameState.cheats.unlockOperatingLimits = _param1 != 0; + break; + case CheatType::DisableBrakesFailure: + gameState.cheats.disableBrakesFailure = _param1 != 0; + break; + case CheatType::DisableAllBreakdowns: + gameState.cheats.disableAllBreakdowns = _param1 != 0; + break; + case CheatType::DisableTrainLengthLimit: + gameState.cheats.disableTrainLengthLimit = _param1 != 0; + break; + case CheatType::EnableChainLiftOnAllTrack: + gameState.cheats.enableChainLiftOnAllTrack = _param1 != 0; + break; + case CheatType::BuildInPauseMode: + gameState.cheats.buildInPauseMode = _param1 != 0; + break; + case CheatType::IgnoreRideIntensity: + gameState.cheats.ignoreRideIntensity = _param1 != 0; + break; + case CheatType::IgnorePrice: + gameState.cheats.ignorePrice = _param1 != 0; + break; + case CheatType::DisableVandalism: + gameState.cheats.disableVandalism = _param1 != 0; + break; + case CheatType::DisableLittering: + gameState.cheats.disableLittering = _param1 != 0; + break; + case CheatType::NoMoney: + SetScenarioNoMoney(_param1 != 0); + break; + case CheatType::AddMoney: + AddMoney(_param1); + break; + case CheatType::SetMoney: + SetMoney(_param1); + break; + case CheatType::ClearLoan: + ClearLoan(); + break; + case CheatType::SetGuestParameter: + SetGuestParameter(_param1, _param2); + break; + case CheatType::GenerateGuests: + GenerateGuests(_param1); + break; + case CheatType::RemoveAllGuests: + RemoveAllGuests(); + break; + case CheatType::GiveAllGuests: + GiveObjectToGuests(_param1); + break; + case CheatType::SetGrassLength: + SetGrassLength(_param1); + break; + case CheatType::WaterPlants: + WaterPlants(); + break; + case CheatType::FixVandalism: + FixVandalism(); + break; + case CheatType::RemoveLitter: + RemoveLitter(); + break; + case CheatType::DisablePlantAging: + gameState.cheats.disablePlantAging = _param1 != 0; + break; + case CheatType::SetStaffSpeed: + SetStaffSpeed(_param1); + break; + case CheatType::RenewRides: + RenewRides(); + break; + case CheatType::MakeDestructible: + gameState.cheats.makeAllDestructible = _param1 != 0; + windowMgr->InvalidateByClass(WindowClass::Ride); + break; + case CheatType::FixRides: + FixBrokenRides(); + break; + case CheatType::ResetCrashStatus: + ResetRideCrashStatus(); + break; + case CheatType::TenMinuteInspections: + Set10MinuteInspection(); + break; + case CheatType::WinScenario: + ScenarioSuccess(gameState); + break; + case CheatType::ForceWeather: + // Todo - make sure this is safe + ClimateForceWeather(WeatherType{ static_cast(_param1) }); + break; + case CheatType::FreezeWeather: + gameState.cheats.freezeWeather = _param1 != 0; + break; + case CheatType::NeverendingMarketing: + gameState.cheats.neverendingMarketing = _param1 != 0; + break; + case CheatType::OpenClosePark: + ParkSetOpen(!Park::IsOpen(gameState.park)); + break; + case CheatType::HaveFun: + gameState.scenarioOptions.objective.Type = Scenario::ObjectiveType::haveFun; + break; + case CheatType::SetForcedParkRating: + Park::SetForcedRating(_param1); + break; + case CheatType::AllowArbitraryRideTypeChanges: + gameState.cheats.allowArbitraryRideTypeChanges = _param1 != 0; + windowMgr->InvalidateByClass(WindowClass::Ride); + break; + case CheatType::OwnAllLand: + OwnAllLand(); + break; + case CheatType::DisableRideValueAging: + gameState.cheats.disableRideValueAging = _param1 != 0; + break; + case CheatType::IgnoreResearchStatus: + gameState.cheats.ignoreResearchStatus = _param1 != 0; + break; + case CheatType::EnableAllDrawableTrackPieces: + gameState.cheats.enableAllDrawableTrackPieces = _param1 != 0; + break; + case CheatType::CreateDucks: + CreateDucks(_param1); + break; + case CheatType::RemoveDucks: + Duck::RemoveAll(); + break; + case CheatType::AllowTrackPlaceInvalidHeights: + gameState.cheats.allowTrackPlaceInvalidHeights = _param1 != 0; + break; + case CheatType::AllowRegularPathAsQueue: + gameState.cheats.allowRegularPathAsQueue = _param1 != 0; + break; + case CheatType::AllowSpecialColourSchemes: + gameState.cheats.allowSpecialColourSchemes = static_cast(_param1); + break; + case CheatType::RemoveParkFences: + RemoveParkFences(); + break; + default: + { + LOG_ERROR("Invalid cheat type %d", _cheatType.id); + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_VALUE_OUT_OF_RANGE); + } + } + + if (NetworkGetMode() == NETWORK_MODE_NONE) + { + Config::Save(); + } + + windowMgr->InvalidateByClass(WindowClass::Cheats); + return Result(); + } + + ParametersRange CheatSetAction::GetParameterRange(CheatType cheatType) const + { + switch (static_cast(_cheatType.id)) + { + case CheatType::SandboxMode: + [[fallthrough]]; + case CheatType::DisableClearanceChecks: + [[fallthrough]]; + case CheatType::DisableSupportLimits: + [[fallthrough]]; + case CheatType::ShowAllOperatingModes: + [[fallthrough]]; + case CheatType::ShowVehiclesFromOtherTrackTypes: + [[fallthrough]]; + case CheatType::FastLiftHill: + [[fallthrough]]; + case CheatType::DisableBrakesFailure: + [[fallthrough]]; + case CheatType::DisableAllBreakdowns: + [[fallthrough]]; + case CheatType::DisableTrainLengthLimit: + [[fallthrough]]; + case CheatType::EnableChainLiftOnAllTrack: + [[fallthrough]]; + case CheatType::BuildInPauseMode: + [[fallthrough]]; + case CheatType::IgnoreRideIntensity: + [[fallthrough]]; + case CheatType::IgnorePrice: + [[fallthrough]]; + case CheatType::DisableVandalism: + [[fallthrough]]; + case CheatType::DisableLittering: + [[fallthrough]]; + case CheatType::NoMoney: + [[fallthrough]]; + case CheatType::DisablePlantAging: + [[fallthrough]]; + case CheatType::FreezeWeather: + [[fallthrough]]; + case CheatType::NeverendingMarketing: + [[fallthrough]]; + case CheatType::AllowArbitraryRideTypeChanges: + [[fallthrough]]; + case CheatType::DisableRideValueAging: + [[fallthrough]]; + case CheatType::IgnoreResearchStatus: + [[fallthrough]]; + case CheatType::EnableAllDrawableTrackPieces: + [[fallthrough]]; + case CheatType::AllowRegularPathAsQueue: + [[fallthrough]]; + case CheatType::UnlockAllPrices: + [[fallthrough]]; + case CheatType::MakeDestructible: + [[fallthrough]]; + case CheatType::AllowSpecialColourSchemes: + [[fallthrough]]; + case CheatType::AllowTrackPlaceInvalidHeights: + [[fallthrough]]; + case CheatType::OpenClosePark: + return { { 0, 1 }, { 0, 0 } }; + case CheatType::AddMoney: + [[fallthrough]]; + case CheatType::SetMoney: + return { { std::numeric_limits::min(), std::numeric_limits::max() }, { 0, 0 } }; + case CheatType::SetGuestParameter: + switch (_param1) + { + case GUEST_PARAMETER_HAPPINESS: + return { { GUEST_PARAMETER_HAPPINESS, GUEST_PARAMETER_PREFERRED_RIDE_INTENSITY }, + { 0, kPeepMaxHappiness } }; + case GUEST_PARAMETER_ENERGY: + return { { GUEST_PARAMETER_HAPPINESS, GUEST_PARAMETER_PREFERRED_RIDE_INTENSITY }, + { kPeepMinEnergy, kPeepMaxEnergy } }; + case GUEST_PARAMETER_HUNGER: + return { { GUEST_PARAMETER_HAPPINESS, GUEST_PARAMETER_PREFERRED_RIDE_INTENSITY }, + { 0, kPeepMaxHunger } }; + case GUEST_PARAMETER_THIRST: + return { { GUEST_PARAMETER_HAPPINESS, GUEST_PARAMETER_PREFERRED_RIDE_INTENSITY }, + { 0, kPeepMaxThirst } }; + case GUEST_PARAMETER_NAUSEA: + return { { GUEST_PARAMETER_HAPPINESS, GUEST_PARAMETER_PREFERRED_RIDE_INTENSITY }, + { 0, kPeepMaxNausea } }; + case GUEST_PARAMETER_NAUSEA_TOLERANCE: + return { { GUEST_PARAMETER_HAPPINESS, GUEST_PARAMETER_PREFERRED_RIDE_INTENSITY }, + { EnumValue(PeepNauseaTolerance::None), EnumValue(PeepNauseaTolerance::High) } }; + case GUEST_PARAMETER_TOILET: + return { { GUEST_PARAMETER_HAPPINESS, GUEST_PARAMETER_PREFERRED_RIDE_INTENSITY }, + { 0, kPeepMaxToilet } }; + case GUEST_PARAMETER_PREFERRED_RIDE_INTENSITY: + return { { GUEST_PARAMETER_HAPPINESS, GUEST_PARAMETER_PREFERRED_RIDE_INTENSITY }, { 0, 255 } }; + default: + return { { 0, 0 }, { 0, 0 } }; + } + case CheatType::GenerateGuests: + return { { 1, 10000 }, { 0, 0 } }; + case CheatType::GiveAllGuests: + return { { OBJECT_MONEY, OBJECT_UMBRELLA }, { 0, 0 } }; + case CheatType::SetGrassLength: + return { { 0, 7 }, { 0, 0 } }; + case CheatType::SetStaffSpeed: + return { { 0, 255 }, { 0, 0 } }; + case CheatType::ForceWeather: + return { { 0, EnumValue(WeatherType::Count) - 1 }, { 0, 0 } }; + case CheatType::SetForcedParkRating: + return { { -1, 999 }, { 0, 0 } }; + case CheatType::CreateDucks: + return { { 0, 100 }, { 0, 0 } }; + case CheatType::RemoveDucks: + [[fallthrough]]; + case CheatType::ClearLoan: + [[fallthrough]]; + case CheatType::RemoveAllGuests: + [[fallthrough]]; + case CheatType::OwnAllLand: + [[fallthrough]]; + case CheatType::WinScenario: + [[fallthrough]]; + case CheatType::HaveFun: + [[fallthrough]]; + case CheatType::FixVandalism: + [[fallthrough]]; + case CheatType::WaterPlants: + [[fallthrough]]; + case CheatType::FixRides: + [[fallthrough]]; + case CheatType::RenewRides: + [[fallthrough]]; + case CheatType::TenMinuteInspections: + [[fallthrough]]; + case CheatType::ResetCrashStatus: + [[fallthrough]]; + case CheatType::NoCapOnQueueLengthDummy: + [[fallthrough]]; + case CheatType::RemoveLitter: + [[fallthrough]]; + case CheatType::RemoveParkFences: + return { { 0, 0 }, { 0, 0 } }; + case CheatType::Count: + break; + } + + // Should be unreachable unless new cheats are added, still have to return something + // to avoid compiler warnings. + Guard::Assert(false, "Missing validation parameter for cheat: %d", _cheatType.id); + return { { 0, 0 }, { 0, 0 } }; + } + + void CheatSetAction::SetGrassLength(int32_t length) const + { + auto& gameState = getGameState(); + for (int32_t y = 0; y < gameState.mapSize.y; y++) + { + for (int32_t x = 0; x < gameState.mapSize.x; x++) + { + auto surfaceElement = MapGetSurfaceElementAt(TileCoordsXY{ x, y }); + if (surfaceElement == nullptr) + continue; + + if (surfaceElement != nullptr && (surfaceElement->GetOwnership() & OWNERSHIP_OWNED) + && surfaceElement->GetWaterHeight() == 0 && surfaceElement->CanGrassGrow()) + { + surfaceElement->SetGrassLength(length); + } + } + } + + GfxInvalidateScreen(); + } + + void CheatSetAction::WaterPlants() const + { + TileElementIterator it; + + TileElementIteratorBegin(&it); + do + { + if (it.element->GetType() == TileElementType::SmallScenery) + { + it.element->AsSmallScenery()->SetAge(0); + } + } while (TileElementIteratorNext(&it)); + + GfxInvalidateScreen(); + } + + void CheatSetAction::FixVandalism() const + { + TileElementIterator it; + + TileElementIteratorBegin(&it); + do + { + if (it.element->GetType() != TileElementType::Path) + continue; + + if (!(it.element)->AsPath()->HasAddition()) + continue; + + it.element->AsPath()->SetIsBroken(false); + } while (TileElementIteratorNext(&it)); + + GfxInvalidateScreen(); + } + + void CheatSetAction::RemoveLitter() const + { + for (auto litter : EntityList()) + { + EntityRemove(litter); + } + + TileElementIterator it{}; + TileElementIteratorBegin(&it); + do + { + if (it.element->GetType() != TileElementType::Path) + continue; + + auto* path = it.element->AsPath(); + if (!path->HasAddition()) + continue; + + auto* pathAdditionEntry = path->GetAdditionEntry(); + if (pathAdditionEntry != nullptr && pathAdditionEntry->flags & PATH_ADDITION_FLAG_IS_BIN) + path->SetAdditionStatus(0xFF); + + } while (TileElementIteratorNext(&it)); + + GfxInvalidateScreen(); + } + + void CheatSetAction::FixBrokenRides() const + { + for (auto& ride : GetRideManager()) + { + if (ride.lifecycleFlags & (RIDE_LIFECYCLE_BREAKDOWN_PENDING | RIDE_LIFECYCLE_BROKEN_DOWN)) + { + auto mechanic = RideGetAssignedMechanic(ride); + + if (mechanic != nullptr) + { + if (ride.mechanicStatus == RIDE_MECHANIC_STATUS_FIXING) + { + mechanic->RideSubState = PeepRideSubState::ApproachExit; + } + else if ( + ride.mechanicStatus == RIDE_MECHANIC_STATUS_CALLING + || ride.mechanicStatus == RIDE_MECHANIC_STATUS_HEADING) + { + mechanic->RemoveFromRide(); + } + } + + RideFixBreakdown(ride, 0); + ride.windowInvalidateFlags |= RIDE_INVALIDATE_RIDE_MAIN | RIDE_INVALIDATE_RIDE_LIST; + } } } - if (NetworkGetMode() == NETWORK_MODE_NONE) + void CheatSetAction::RenewRides() const { - Config::Save(); + for (auto& ride : GetRideManager()) + { + ride.renew(); + } + auto* windowMgr = Ui::GetWindowManager(); + windowMgr->InvalidateByClass(WindowClass::Ride); } - windowMgr->InvalidateByClass(WindowClass::Cheats); - return GameActions::Result(); -} - -ParametersRange CheatSetAction::GetParameterRange(CheatType cheatType) const -{ - switch (static_cast(_cheatType.id)) + void CheatSetAction::ResetRideCrashStatus() const { - case CheatType::SandboxMode: - [[fallthrough]]; - case CheatType::DisableClearanceChecks: - [[fallthrough]]; - case CheatType::DisableSupportLimits: - [[fallthrough]]; - case CheatType::ShowAllOperatingModes: - [[fallthrough]]; - case CheatType::ShowVehiclesFromOtherTrackTypes: - [[fallthrough]]; - case CheatType::FastLiftHill: - [[fallthrough]]; - case CheatType::DisableBrakesFailure: - [[fallthrough]]; - case CheatType::DisableAllBreakdowns: - [[fallthrough]]; - case CheatType::DisableTrainLengthLimit: - [[fallthrough]]; - case CheatType::EnableChainLiftOnAllTrack: - [[fallthrough]]; - case CheatType::BuildInPauseMode: - [[fallthrough]]; - case CheatType::IgnoreRideIntensity: - [[fallthrough]]; - case CheatType::IgnorePrice: - [[fallthrough]]; - case CheatType::DisableVandalism: - [[fallthrough]]; - case CheatType::DisableLittering: - [[fallthrough]]; - case CheatType::NoMoney: - [[fallthrough]]; - case CheatType::DisablePlantAging: - [[fallthrough]]; - case CheatType::FreezeWeather: - [[fallthrough]]; - case CheatType::NeverendingMarketing: - [[fallthrough]]; - case CheatType::AllowArbitraryRideTypeChanges: - [[fallthrough]]; - case CheatType::DisableRideValueAging: - [[fallthrough]]; - case CheatType::IgnoreResearchStatus: - [[fallthrough]]; - case CheatType::EnableAllDrawableTrackPieces: - [[fallthrough]]; - case CheatType::AllowRegularPathAsQueue: - [[fallthrough]]; - case CheatType::UnlockAllPrices: - [[fallthrough]]; - case CheatType::MakeDestructible: - [[fallthrough]]; - case CheatType::AllowSpecialColourSchemes: - [[fallthrough]]; - case CheatType::AllowTrackPlaceInvalidHeights: - [[fallthrough]]; - case CheatType::OpenClosePark: - return { { 0, 1 }, { 0, 0 } }; - case CheatType::AddMoney: - [[fallthrough]]; - case CheatType::SetMoney: - return { { std::numeric_limits::min(), std::numeric_limits::max() }, { 0, 0 } }; - case CheatType::SetGuestParameter: - switch (_param1) + for (auto& ride : GetRideManager()) + { + // Reset crash status and history + ride.lifecycleFlags &= ~RIDE_LIFECYCLE_CRASHED; + ride.lastCrashType = RIDE_CRASH_TYPE_NONE; + } + auto* windowMgr = Ui::GetWindowManager(); + windowMgr->InvalidateByClass(WindowClass::Ride); + } + + void CheatSetAction::Set10MinuteInspection() const + { + for (auto& ride : GetRideManager()) + { + // Set inspection interval to 10 minutes + ride.inspectionInterval = RIDE_INSPECTION_EVERY_10_MINUTES; + } + auto* windowMgr = Ui::GetWindowManager(); + windowMgr->InvalidateByClass(WindowClass::Ride); + } + + void CheatSetAction::SetScenarioNoMoney(bool enabled) const + { + auto& park = getGameState().park; + if (enabled) + { + park.flags |= PARK_FLAGS_NO_MONEY; + } + else + { + park.flags &= ~PARK_FLAGS_NO_MONEY; + } + + // Invalidate all windows that have anything to do with finance + auto* windowMgr = Ui::GetWindowManager(); + windowMgr->InvalidateByClass(WindowClass::Ride); + windowMgr->InvalidateByClass(WindowClass::Peep); + windowMgr->InvalidateByClass(WindowClass::ParkInformation); + windowMgr->InvalidateByClass(WindowClass::Finances); + windowMgr->InvalidateByClass(WindowClass::BottomToolbar); + windowMgr->InvalidateByClass(WindowClass::TopToolbar); + windowMgr->InvalidateByClass(WindowClass::Cheats); + } + + void CheatSetAction::SetMoney(money64 amount) const + { + getGameState().park.cash = amount; + + auto* windowMgr = Ui::GetWindowManager(); + windowMgr->InvalidateByClass(WindowClass::Finances); + windowMgr->InvalidateByClass(WindowClass::BottomToolbar); + } + + void CheatSetAction::AddMoney(money64 amount) const + { + auto& park = getGameState().park; + park.cash = AddClamp(park.cash, amount); + + auto* windowMgr = Ui::GetWindowManager(); + windowMgr->InvalidateByClass(WindowClass::Finances); + windowMgr->InvalidateByClass(WindowClass::BottomToolbar); + } + + void CheatSetAction::ClearLoan() const + { + // First give money + AddMoney(getGameState().park.bankLoan); + + // Then pay the loan + auto gameAction = ParkSetLoanAction(0.00_GBP); + ExecuteNested(&gameAction); + } + + void CheatSetAction::GenerateGuests(int32_t count) const + { + for (int32_t i = 0; i < count; i++) + { + Park::GenerateGuest(); + } + + auto* windowMgr = Ui::GetWindowManager(); + windowMgr->InvalidateByClass(WindowClass::BottomToolbar); + } + + void CheatSetAction::SetGuestParameter(int32_t parameter, int32_t value) const + { + for (auto peep : EntityList()) + { + switch (parameter) { case GUEST_PARAMETER_HAPPINESS: - return { { GUEST_PARAMETER_HAPPINESS, GUEST_PARAMETER_PREFERRED_RIDE_INTENSITY }, - { 0, kPeepMaxHappiness } }; - case GUEST_PARAMETER_ENERGY: - return { { GUEST_PARAMETER_HAPPINESS, GUEST_PARAMETER_PREFERRED_RIDE_INTENSITY }, - { kPeepMinEnergy, kPeepMaxEnergy } }; - case GUEST_PARAMETER_HUNGER: - return { { GUEST_PARAMETER_HAPPINESS, GUEST_PARAMETER_PREFERRED_RIDE_INTENSITY }, { 0, kPeepMaxHunger } }; - case GUEST_PARAMETER_THIRST: - return { { GUEST_PARAMETER_HAPPINESS, GUEST_PARAMETER_PREFERRED_RIDE_INTENSITY }, { 0, kPeepMaxThirst } }; - case GUEST_PARAMETER_NAUSEA: - return { { GUEST_PARAMETER_HAPPINESS, GUEST_PARAMETER_PREFERRED_RIDE_INTENSITY }, { 0, kPeepMaxNausea } }; - case GUEST_PARAMETER_NAUSEA_TOLERANCE: - return { { GUEST_PARAMETER_HAPPINESS, GUEST_PARAMETER_PREFERRED_RIDE_INTENSITY }, - { EnumValue(PeepNauseaTolerance::None), EnumValue(PeepNauseaTolerance::High) } }; - case GUEST_PARAMETER_TOILET: - return { { GUEST_PARAMETER_HAPPINESS, GUEST_PARAMETER_PREFERRED_RIDE_INTENSITY }, { 0, kPeepMaxToilet } }; - case GUEST_PARAMETER_PREFERRED_RIDE_INTENSITY: - return { { GUEST_PARAMETER_HAPPINESS, GUEST_PARAMETER_PREFERRED_RIDE_INTENSITY }, { 0, 255 } }; - default: - return { { 0, 0 }, { 0, 0 } }; - } - case CheatType::GenerateGuests: - return { { 1, 10000 }, { 0, 0 } }; - case CheatType::GiveAllGuests: - return { { OBJECT_MONEY, OBJECT_UMBRELLA }, { 0, 0 } }; - case CheatType::SetGrassLength: - return { { 0, 7 }, { 0, 0 } }; - case CheatType::SetStaffSpeed: - return { { 0, 255 }, { 0, 0 } }; - case CheatType::ForceWeather: - return { { 0, EnumValue(WeatherType::Count) - 1 }, { 0, 0 } }; - case CheatType::SetForcedParkRating: - return { { -1, 999 }, { 0, 0 } }; - case CheatType::CreateDucks: - return { { 0, 100 }, { 0, 0 } }; - case CheatType::RemoveDucks: - [[fallthrough]]; - case CheatType::ClearLoan: - [[fallthrough]]; - case CheatType::RemoveAllGuests: - [[fallthrough]]; - case CheatType::OwnAllLand: - [[fallthrough]]; - case CheatType::WinScenario: - [[fallthrough]]; - case CheatType::HaveFun: - [[fallthrough]]; - case CheatType::FixVandalism: - [[fallthrough]]; - case CheatType::WaterPlants: - [[fallthrough]]; - case CheatType::FixRides: - [[fallthrough]]; - case CheatType::RenewRides: - [[fallthrough]]; - case CheatType::TenMinuteInspections: - [[fallthrough]]; - case CheatType::ResetCrashStatus: - [[fallthrough]]; - case CheatType::NoCapOnQueueLengthDummy: - [[fallthrough]]; - case CheatType::RemoveLitter: - [[fallthrough]]; - case CheatType::RemoveParkFences: - return { { 0, 0 }, { 0, 0 } }; - case CheatType::Count: - break; - } - - // Should be unreachable unless new cheats are added, still have to return something - // to avoid compiler warnings. - Guard::Assert(false, "Missing validation parameter for cheat: %d", _cheatType.id); - return { { 0, 0 }, { 0, 0 } }; -} - -void CheatSetAction::SetGrassLength(int32_t length) const -{ - auto& gameState = getGameState(); - for (int32_t y = 0; y < gameState.mapSize.y; y++) - { - for (int32_t x = 0; x < gameState.mapSize.x; x++) - { - auto surfaceElement = MapGetSurfaceElementAt(TileCoordsXY{ x, y }); - if (surfaceElement == nullptr) - continue; - - if (surfaceElement != nullptr && (surfaceElement->GetOwnership() & OWNERSHIP_OWNED) - && surfaceElement->GetWaterHeight() == 0 && surfaceElement->CanGrassGrow()) - { - surfaceElement->SetGrassLength(length); - } - } - } - - GfxInvalidateScreen(); -} - -void CheatSetAction::WaterPlants() const -{ - TileElementIterator it; - - TileElementIteratorBegin(&it); - do - { - if (it.element->GetType() == TileElementType::SmallScenery) - { - it.element->AsSmallScenery()->SetAge(0); - } - } while (TileElementIteratorNext(&it)); - - GfxInvalidateScreen(); -} - -void CheatSetAction::FixVandalism() const -{ - TileElementIterator it; - - TileElementIteratorBegin(&it); - do - { - if (it.element->GetType() != TileElementType::Path) - continue; - - if (!(it.element)->AsPath()->HasAddition()) - continue; - - it.element->AsPath()->SetIsBroken(false); - } while (TileElementIteratorNext(&it)); - - GfxInvalidateScreen(); -} - -void CheatSetAction::RemoveLitter() const -{ - for (auto litter : EntityList()) - { - EntityRemove(litter); - } - - TileElementIterator it{}; - TileElementIteratorBegin(&it); - do - { - if (it.element->GetType() != TileElementType::Path) - continue; - - auto* path = it.element->AsPath(); - if (!path->HasAddition()) - continue; - - auto* pathAdditionEntry = path->GetAdditionEntry(); - if (pathAdditionEntry != nullptr && pathAdditionEntry->flags & PATH_ADDITION_FLAG_IS_BIN) - path->SetAdditionStatus(0xFF); - - } while (TileElementIteratorNext(&it)); - - GfxInvalidateScreen(); -} - -void CheatSetAction::FixBrokenRides() const -{ - for (auto& ride : GetRideManager()) - { - if (ride.lifecycleFlags & (RIDE_LIFECYCLE_BREAKDOWN_PENDING | RIDE_LIFECYCLE_BROKEN_DOWN)) - { - auto mechanic = RideGetAssignedMechanic(ride); - - if (mechanic != nullptr) - { - if (ride.mechanicStatus == RIDE_MECHANIC_STATUS_FIXING) - { - mechanic->RideSubState = PeepRideSubState::ApproachExit; - } - else if ( - ride.mechanicStatus == RIDE_MECHANIC_STATUS_CALLING || ride.mechanicStatus == RIDE_MECHANIC_STATUS_HEADING) - { - mechanic->RemoveFromRide(); - } - } - - RideFixBreakdown(ride, 0); - ride.windowInvalidateFlags |= RIDE_INVALIDATE_RIDE_MAIN | RIDE_INVALIDATE_RIDE_LIST; - } - } -} - -void CheatSetAction::RenewRides() const -{ - for (auto& ride : GetRideManager()) - { - ride.renew(); - } - auto* windowMgr = Ui::GetWindowManager(); - windowMgr->InvalidateByClass(WindowClass::Ride); -} - -void CheatSetAction::ResetRideCrashStatus() const -{ - for (auto& ride : GetRideManager()) - { - // Reset crash status and history - ride.lifecycleFlags &= ~RIDE_LIFECYCLE_CRASHED; - ride.lastCrashType = RIDE_CRASH_TYPE_NONE; - } - auto* windowMgr = Ui::GetWindowManager(); - windowMgr->InvalidateByClass(WindowClass::Ride); -} - -void CheatSetAction::Set10MinuteInspection() const -{ - for (auto& ride : GetRideManager()) - { - // Set inspection interval to 10 minutes - ride.inspectionInterval = RIDE_INSPECTION_EVERY_10_MINUTES; - } - auto* windowMgr = Ui::GetWindowManager(); - windowMgr->InvalidateByClass(WindowClass::Ride); -} - -void CheatSetAction::SetScenarioNoMoney(bool enabled) const -{ - auto& park = getGameState().park; - if (enabled) - { - park.flags |= PARK_FLAGS_NO_MONEY; - } - else - { - park.flags &= ~PARK_FLAGS_NO_MONEY; - } - - // Invalidate all windows that have anything to do with finance - auto* windowMgr = Ui::GetWindowManager(); - windowMgr->InvalidateByClass(WindowClass::Ride); - windowMgr->InvalidateByClass(WindowClass::Peep); - windowMgr->InvalidateByClass(WindowClass::ParkInformation); - windowMgr->InvalidateByClass(WindowClass::Finances); - windowMgr->InvalidateByClass(WindowClass::BottomToolbar); - windowMgr->InvalidateByClass(WindowClass::TopToolbar); - windowMgr->InvalidateByClass(WindowClass::Cheats); -} - -void CheatSetAction::SetMoney(money64 amount) const -{ - getGameState().park.cash = amount; - - auto* windowMgr = Ui::GetWindowManager(); - windowMgr->InvalidateByClass(WindowClass::Finances); - windowMgr->InvalidateByClass(WindowClass::BottomToolbar); -} - -void CheatSetAction::AddMoney(money64 amount) const -{ - auto& park = getGameState().park; - park.cash = AddClamp(park.cash, amount); - - auto* windowMgr = Ui::GetWindowManager(); - windowMgr->InvalidateByClass(WindowClass::Finances); - windowMgr->InvalidateByClass(WindowClass::BottomToolbar); -} - -void CheatSetAction::ClearLoan() const -{ - // First give money - AddMoney(getGameState().park.bankLoan); - - // Then pay the loan - auto gameAction = ParkSetLoanAction(0.00_GBP); - GameActions::ExecuteNested(&gameAction); -} - -void CheatSetAction::GenerateGuests(int32_t count) const -{ - for (int32_t i = 0; i < count; i++) - { - Park::GenerateGuest(); - } - - auto* windowMgr = Ui::GetWindowManager(); - windowMgr->InvalidateByClass(WindowClass::BottomToolbar); -} - -void CheatSetAction::SetGuestParameter(int32_t parameter, int32_t value) const -{ - for (auto peep : EntityList()) - { - switch (parameter) - { - case GUEST_PARAMETER_HAPPINESS: - peep->Happiness = value; - peep->HappinessTarget = value; - // Clear the 'red-faced with anger' status if we're making the guest happy - if (value > 0) - { - peep->PeepFlags &= ~PEEP_FLAGS_ANGRY; - peep->Angriness = 0; - } - break; - case GUEST_PARAMETER_ENERGY: - peep->Energy = value; - peep->EnergyTarget = value; - break; - case GUEST_PARAMETER_HUNGER: - peep->Hunger = value; - break; - case GUEST_PARAMETER_THIRST: - peep->Thirst = value; - break; - case GUEST_PARAMETER_NAUSEA: - peep->Nausea = value; - peep->NauseaTarget = value; - break; - case GUEST_PARAMETER_NAUSEA_TOLERANCE: - peep->NauseaTolerance = static_cast(value); - break; - case GUEST_PARAMETER_TOILET: - peep->Toilet = value; - break; - case GUEST_PARAMETER_PREFERRED_RIDE_INTENSITY: - peep->Intensity = IntensityRange(value, 15); - break; - } - peep->UpdateAnimationGroup(); - } -} - -void CheatSetAction::GiveObjectToGuests(int32_t object) const -{ - for (auto peep : EntityList()) - { - switch (object) - { - case OBJECT_MONEY: - peep->CashInPocket = 1000.00_GBP; - break; - case OBJECT_PARK_MAP: - peep->GiveItem(ShopItem::Map); - break; - case OBJECT_BALLOON: - peep->GiveItem(ShopItem::Balloon); - peep->BalloonColour = ScenarioRandMax(kColourNumNormal); - peep->UpdateAnimationGroup(); - break; - case OBJECT_UMBRELLA: - peep->GiveItem(ShopItem::Umbrella); - peep->UmbrellaColour = ScenarioRandMax(kColourNumOriginal); - peep->UpdateAnimationGroup(); - break; - } - } - - auto* windowMgr = Ui::GetWindowManager(); - windowMgr->InvalidateByClass(WindowClass::Peep); -} - -void CheatSetAction::RemoveAllGuests() const -{ - for (auto& ride : GetRideManager()) - { - ride.numRiders = 0; - - for (auto& station : ride.getStations()) - { - station.QueueLength = 0; - station.LastPeepInQueue = EntityId::GetNull(); - } - - for (auto trainIndex : ride.vehicles) - { - for (Vehicle* vehicle = TryGetEntity(trainIndex); vehicle != nullptr; - vehicle = TryGetEntity(vehicle->next_vehicle_on_train)) - { - auto i = 0; - for (auto& peepInTrainIndex : vehicle->peep) - { - if (i >= vehicle->num_peeps) - break; - - auto peep = TryGetEntity(peepInTrainIndex); - if (peep != nullptr && peep->CurrentRide == ride.id) + peep->Happiness = value; + peep->HappinessTarget = value; + // Clear the 'red-faced with anger' status if we're making the guest happy + if (value > 0) { - if ((peep->State == PeepState::OnRide && peep->RideSubState == PeepRideSubState::OnRide) - || (peep->State == PeepState::LeavingRide && peep->RideSubState == PeepRideSubState::LeaveVehicle)) - { - vehicle->ApplyMass(-peep->Mass); - } + peep->PeepFlags &= ~PEEP_FLAGS_ANGRY; + peep->Angriness = 0; } - peepInTrainIndex = EntityId::GetNull(); - i++; - } - - vehicle->num_peeps = 0; - vehicle->next_free_seat = 0; + break; + case GUEST_PARAMETER_ENERGY: + peep->Energy = value; + peep->EnergyTarget = value; + break; + case GUEST_PARAMETER_HUNGER: + peep->Hunger = value; + break; + case GUEST_PARAMETER_THIRST: + peep->Thirst = value; + break; + case GUEST_PARAMETER_NAUSEA: + peep->Nausea = value; + peep->NauseaTarget = value; + break; + case GUEST_PARAMETER_NAUSEA_TOLERANCE: + peep->NauseaTolerance = static_cast(value); + break; + case GUEST_PARAMETER_TOILET: + peep->Toilet = value; + break; + case GUEST_PARAMETER_PREFERRED_RIDE_INTENSITY: + peep->Intensity = IntensityRange(value, 15); + break; } + peep->UpdateAnimationGroup(); } } - // Do not use the FOR_ALL_PEEPS macro for this as next sprite index - // will be fetched on a deleted guest. - for (auto guest : EntityList()) + void CheatSetAction::GiveObjectToGuests(int32_t object) const { - // Frozen peeps are usually placed and tweaked for artistic purposes, - // so exempt them from being removed. - if (guest->PeepFlags & PEEP_FLAGS_POSITION_FROZEN) - continue; - - guest->Remove(); - } - - auto* windowMgr = Ui::GetWindowManager(); - windowMgr->InvalidateByClass(WindowClass::Ride); - GfxInvalidateScreen(); -} - -void CheatSetAction::SetStaffSpeed(uint8_t value) const -{ - for (auto peep : EntityList()) - { - peep->Energy = value; - peep->EnergyTarget = value; - } -} - -void CheatSetAction::OwnAllLand() const -{ - const auto min = CoordsXY{ kCoordsXYStep, kCoordsXYStep }; - const auto max = GetMapSizeUnits() - CoordsXY{ kCoordsXYStep, kCoordsXYStep }; - - for (CoordsXY coords = min; coords.y <= max.y; coords.y += kCoordsXYStep) - { - for (coords.x = min.x; coords.x <= max.x; coords.x += kCoordsXYStep) + for (auto peep : EntityList()) { - auto* surfaceElement = MapGetSurfaceElementAt(coords); - if (surfaceElement == nullptr) - continue; - - // Ignore already owned tiles. - if (surfaceElement->GetOwnership() & OWNERSHIP_OWNED) - continue; - - int32_t baseZ = surfaceElement->GetBaseZ(); - int32_t destOwnership = CheckMaxAllowableLandRightsForTile({ coords, baseZ }); - - // only own tiles that were not set to 0 - if (destOwnership != OWNERSHIP_UNOWNED) + switch (object) { - surfaceElement->SetOwnership(destOwnership); - Park::UpdateFencesAroundTile(coords); - MapInvalidateTile({ coords, baseZ, baseZ + 16 }); + case OBJECT_MONEY: + peep->CashInPocket = 1000.00_GBP; + break; + case OBJECT_PARK_MAP: + peep->GiveItem(ShopItem::Map); + break; + case OBJECT_BALLOON: + peep->GiveItem(ShopItem::Balloon); + peep->BalloonColour = ScenarioRandMax(kColourNumNormal); + peep->UpdateAnimationGroup(); + break; + case OBJECT_UMBRELLA: + peep->GiveItem(ShopItem::Umbrella); + peep->UmbrellaColour = ScenarioRandMax(kColourNumOriginal); + peep->UpdateAnimationGroup(); + break; + } + } + + auto* windowMgr = Ui::GetWindowManager(); + windowMgr->InvalidateByClass(WindowClass::Peep); + } + + void CheatSetAction::RemoveAllGuests() const + { + for (auto& ride : GetRideManager()) + { + ride.numRiders = 0; + + for (auto& station : ride.getStations()) + { + station.QueueLength = 0; + station.LastPeepInQueue = EntityId::GetNull(); + } + + for (auto trainIndex : ride.vehicles) + { + for (Vehicle* vehicle = TryGetEntity(trainIndex); vehicle != nullptr; + vehicle = TryGetEntity(vehicle->next_vehicle_on_train)) + { + auto i = 0; + for (auto& peepInTrainIndex : vehicle->peep) + { + if (i >= vehicle->num_peeps) + break; + + auto peep = TryGetEntity(peepInTrainIndex); + if (peep != nullptr && peep->CurrentRide == ride.id) + { + if ((peep->State == PeepState::OnRide && peep->RideSubState == PeepRideSubState::OnRide) + || (peep->State == PeepState::LeavingRide + && peep->RideSubState == PeepRideSubState::LeaveVehicle)) + { + vehicle->ApplyMass(-peep->Mass); + } + } + peepInTrainIndex = EntityId::GetNull(); + i++; + } + + vehicle->num_peeps = 0; + vehicle->next_free_seat = 0; + } + } + } + + // Do not use the FOR_ALL_PEEPS macro for this as next sprite index + // will be fetched on a deleted guest. + for (auto guest : EntityList()) + { + // Frozen peeps are usually placed and tweaked for artistic purposes, + // so exempt them from being removed. + if (guest->PeepFlags & PEEP_FLAGS_POSITION_FROZEN) + continue; + + guest->Remove(); + } + + auto* windowMgr = Ui::GetWindowManager(); + windowMgr->InvalidateByClass(WindowClass::Ride); + GfxInvalidateScreen(); + } + + void CheatSetAction::SetStaffSpeed(uint8_t value) const + { + for (auto peep : EntityList()) + { + peep->Energy = value; + peep->EnergyTarget = value; + } + } + + void CheatSetAction::OwnAllLand() const + { + const auto min = CoordsXY{ kCoordsXYStep, kCoordsXYStep }; + const auto max = GetMapSizeUnits() - CoordsXY{ kCoordsXYStep, kCoordsXYStep }; + + for (CoordsXY coords = min; coords.y <= max.y; coords.y += kCoordsXYStep) + { + for (coords.x = min.x; coords.x <= max.x; coords.x += kCoordsXYStep) + { + auto* surfaceElement = MapGetSurfaceElementAt(coords); + if (surfaceElement == nullptr) + continue; + + // Ignore already owned tiles. + if (surfaceElement->GetOwnership() & OWNERSHIP_OWNED) + continue; + + int32_t baseZ = surfaceElement->GetBaseZ(); + int32_t destOwnership = CheckMaxAllowableLandRightsForTile({ coords, baseZ }); + + // only own tiles that were not set to 0 + if (destOwnership != OWNERSHIP_UNOWNED) + { + surfaceElement->SetOwnership(destOwnership); + Park::UpdateFencesAroundTile(coords); + MapInvalidateTile({ coords, baseZ, baseZ + 16 }); + } + } + } + + // Completely unown peep spawn points + for (const auto& spawn : getGameState().peepSpawns) + { + auto* surfaceElement = MapGetSurfaceElementAt(spawn); + if (surfaceElement != nullptr) + { + surfaceElement->SetOwnership(OWNERSHIP_UNOWNED); + Park::UpdateFencesAroundTile(spawn); + uint16_t baseZ = surfaceElement->GetBaseZ(); + MapInvalidateTile({ spawn, baseZ, baseZ + 16 }); + } + } + + MapCountRemainingLandRights(); + } + + void CheatSetAction::ParkSetOpen(bool isOpen) const + { + auto parkSetParameter = ParkSetParameterAction(isOpen ? ParkParameter::Open : ParkParameter::Close); + ExecuteNested(&parkSetParameter); + } + + void CheatSetAction::CreateDucks(int count) const + { + for (int i = 0; i < count; i++) + { + // 100 attempts at finding some water to create a few ducks at + for (int32_t attempts = 0; attempts < 100; attempts++) + { + if (ScenarioCreateDucks()) + break; } } } - // Completely unown peep spawn points - for (const auto& spawn : getGameState().peepSpawns) + void CheatSetAction::RemoveParkFences() const { - auto* surfaceElement = MapGetSurfaceElementAt(spawn); - if (surfaceElement != nullptr) + TileElementIterator it; + TileElementIteratorBegin(&it); + do { - surfaceElement->SetOwnership(OWNERSHIP_UNOWNED); - Park::UpdateFencesAroundTile(spawn); - uint16_t baseZ = surfaceElement->GetBaseZ(); - MapInvalidateTile({ spawn, baseZ, baseZ + 16 }); - } + if (it.element->GetType() == TileElementType::Surface) + { + // Remove all park fence flags + it.element->AsSurface()->SetParkFences(0); + } + } while (TileElementIteratorNext(&it)); + + GfxInvalidateScreen(); } - - MapCountRemainingLandRights(); -} - -void CheatSetAction::ParkSetOpen(bool isOpen) const -{ - auto parkSetParameter = ParkSetParameterAction(isOpen ? ParkParameter::Open : ParkParameter::Close); - GameActions::ExecuteNested(&parkSetParameter); -} - -void CheatSetAction::CreateDucks(int count) const -{ - for (int i = 0; i < count; i++) - { - // 100 attempts at finding some water to create a few ducks at - for (int32_t attempts = 0; attempts < 100; attempts++) - { - if (ScenarioCreateDucks()) - break; - } - } -} - -void CheatSetAction::RemoveParkFences() const -{ - TileElementIterator it; - TileElementIteratorBegin(&it); - do - { - if (it.element->GetType() == TileElementType::Surface) - { - // Remove all park fence flags - it.element->AsSurface()->SetParkFences(0); - } - } while (TileElementIteratorNext(&it)); - - GfxInvalidateScreen(); -} +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/CheatSetAction.h b/src/openrct2/actions/CheatSetAction.h index fe387771b6..89f7947ff3 100644 --- a/src/openrct2/actions/CheatSetAction.h +++ b/src/openrct2/actions/CheatSetAction.h @@ -11,48 +11,51 @@ #include "GameAction.h" -class CheatSetAction final : public GameActionBase +namespace OpenRCT2::GameActions { - using ParametersRange = std::pair, std::pair>; + class CheatSetAction final : public GameActionBase + { + using ParametersRange = std::pair, std::pair>; -private: - NetworkCheatType_t _cheatType{ EnumValue(CheatType::Count) }; - int64_t _param1{}; - int64_t _param2{}; + private: + NetworkCheatType_t _cheatType{ EnumValue(CheatType::Count) }; + int64_t _param1{}; + int64_t _param2{}; -public: - CheatSetAction() = default; - CheatSetAction(CheatType cheatType, int64_t param1 = 0, int64_t param2 = 0); + public: + CheatSetAction() = default; + CheatSetAction(CheatType cheatType, int64_t param1 = 0, int64_t param2 = 0); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; -private: - ParametersRange GetParameterRange(CheatType cheatType) const; - void SetGrassLength(int32_t length) const; - void WaterPlants() const; - void FixVandalism() const; - void RemoveLitter() const; - void FixBrokenRides() const; - void RenewRides() const; - void ResetRideCrashStatus() const; - void Set10MinuteInspection() const; - void SetScenarioNoMoney(bool enabled) const; - void SetMoney(money64 amount) const; - void AddMoney(money64 amount) const; - void ClearLoan() const; - void GenerateGuests(int32_t count) const; - void SetGuestParameter(int32_t parameter, int32_t value) const; - void GiveObjectToGuests(int32_t object) const; - void RemoveAllGuests() const; - void SetStaffSpeed(uint8_t value) const; - void OwnAllLand() const; - void ParkSetOpen(bool isOpen) const; - void CreateDucks(int count) const; - void RemoveParkFences() const; -}; + private: + ParametersRange GetParameterRange(CheatType cheatType) const; + void SetGrassLength(int32_t length) const; + void WaterPlants() const; + void FixVandalism() const; + void RemoveLitter() const; + void FixBrokenRides() const; + void RenewRides() const; + void ResetRideCrashStatus() const; + void Set10MinuteInspection() const; + void SetScenarioNoMoney(bool enabled) const; + void SetMoney(money64 amount) const; + void AddMoney(money64 amount) const; + void ClearLoan() const; + void GenerateGuests(int32_t count) const; + void SetGuestParameter(int32_t parameter, int32_t value) const; + void GiveObjectToGuests(int32_t object) const; + void RemoveAllGuests() const; + void SetStaffSpeed(uint8_t value) const; + void OwnAllLand() const; + void ParkSetOpen(bool isOpen) const; + void CreateDucks(int count) const; + void RemoveParkFences() const; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/ClearAction.cpp b/src/openrct2/actions/ClearAction.cpp index d1a19d3e64..c49bd3c490 100644 --- a/src/openrct2/actions/ClearAction.cpp +++ b/src/openrct2/actions/ClearAction.cpp @@ -143,7 +143,7 @@ money64 ClearAction::ClearSceneryFromTile(const CoordsXY& tilePos, bool executin case TileElementType::Path: if (_itemsToClear & CLEARABLE_ITEMS::kSceneryFootpath) { - auto footpathRemoveAction = FootpathRemoveAction({ tilePos, tileElement->GetBaseZ() }); + auto footpathRemoveAction = GameActions::FootpathRemoveAction({ tilePos, tileElement->GetBaseZ() }); footpathRemoveAction.SetFlags(GetFlags()); auto res = executing ? GameActions::ExecuteNested(&footpathRemoveAction) @@ -159,7 +159,7 @@ money64 ClearAction::ClearSceneryFromTile(const CoordsXY& tilePos, bool executin case TileElementType::SmallScenery: if (_itemsToClear & CLEARABLE_ITEMS::kScenerySmall) { - auto removeSceneryAction = SmallSceneryRemoveAction( + auto removeSceneryAction = GameActions::SmallSceneryRemoveAction( { tilePos, tileElement->GetBaseZ() }, tileElement->AsSmallScenery()->GetSceneryQuadrant(), tileElement->AsSmallScenery()->GetEntryIndex()); removeSceneryAction.SetFlags(GetFlags()); @@ -178,7 +178,7 @@ money64 ClearAction::ClearSceneryFromTile(const CoordsXY& tilePos, bool executin if (_itemsToClear & CLEARABLE_ITEMS::kScenerySmall) { CoordsXYZD wallLocation = { tilePos, tileElement->GetBaseZ(), tileElement->GetDirection() }; - auto wallRemoveAction = WallRemoveAction(wallLocation); + auto wallRemoveAction = GameActions::WallRemoveAction(wallLocation); wallRemoveAction.SetFlags(GetFlags()); auto res = executing ? GameActions::ExecuteNested(&wallRemoveAction) @@ -194,7 +194,7 @@ money64 ClearAction::ClearSceneryFromTile(const CoordsXY& tilePos, bool executin case TileElementType::LargeScenery: if (_itemsToClear & CLEARABLE_ITEMS::kSceneryLarge) { - auto removeSceneryAction = LargeSceneryRemoveAction( + auto removeSceneryAction = GameActions::LargeSceneryRemoveAction( { tilePos, tileElement->GetBaseZ(), tileElement->GetDirection() }, tileElement->AsLargeScenery()->GetSequenceIndex()); removeSceneryAction.SetFlags(GetFlags() | GAME_COMMAND_FLAG_TRACK_DESIGN); diff --git a/src/openrct2/actions/CustomAction.cpp b/src/openrct2/actions/CustomAction.cpp index a474abce63..11fae91d5f 100644 --- a/src/openrct2/actions/CustomAction.cpp +++ b/src/openrct2/actions/CustomAction.cpp @@ -13,51 +13,52 @@ #include "../Context.h" #include "../scripting/ScriptEngine.h" -using namespace OpenRCT2; - -CustomAction::CustomAction(const std::string& id, const std::string& json, const std::string& pluginName) - : _id(id) - , _json(json) - , _pluginName(pluginName) +namespace OpenRCT2::GameActions { -} + CustomAction::CustomAction(const std::string& id, const std::string& json, const std::string& pluginName) + : _id(id) + , _json(json) + , _pluginName(pluginName) + { + } -std::string CustomAction::GetId() const -{ - return _id; -} + std::string CustomAction::GetId() const + { + return _id; + } -std::string CustomAction::GetJson() const -{ - return _json; -} + std::string CustomAction::GetJson() const + { + return _json; + } -std::string CustomAction::GetPluginName() const -{ - return _pluginName; -} + std::string CustomAction::GetPluginName() const + { + return _pluginName; + } -uint16_t CustomAction::GetActionFlags() const -{ - return GameAction::GetActionFlags() | GameActions::Flags::AllowWhilePaused; -} + uint16_t CustomAction::GetActionFlags() const + { + return GameAction::GetActionFlags() | Flags::AllowWhilePaused; + } -void CustomAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - stream << DS_TAG(_id) << DS_TAG(_json); -} + void CustomAction::Serialise(DataSerialiser& stream) + { + GameAction::Serialise(stream); + stream << DS_TAG(_id) << DS_TAG(_json); + } -GameActions::Result CustomAction::Query() const -{ - auto& scriptingEngine = OpenRCT2::GetContext()->GetScriptEngine(); - return scriptingEngine.QueryOrExecuteCustomGameAction(*this, false); -} + Result CustomAction::Query() const + { + auto& scriptingEngine = GetContext()->GetScriptEngine(); + return scriptingEngine.QueryOrExecuteCustomGameAction(*this, false); + } -GameActions::Result CustomAction::Execute() const -{ - auto& scriptingEngine = OpenRCT2::GetContext()->GetScriptEngine(); - return scriptingEngine.QueryOrExecuteCustomGameAction(*this, true); -} + Result CustomAction::Execute() const + { + auto& scriptingEngine = GetContext()->GetScriptEngine(); + return scriptingEngine.QueryOrExecuteCustomGameAction(*this, true); + } +} // namespace OpenRCT2::GameActions #endif diff --git a/src/openrct2/actions/CustomAction.h b/src/openrct2/actions/CustomAction.h index 9e8253f36a..c7b41ec9bb 100644 --- a/src/openrct2/actions/CustomAction.h +++ b/src/openrct2/actions/CustomAction.h @@ -13,26 +13,29 @@ #include "GameAction.h" -class CustomAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - std::string _id; - std::string _json; - std::string _pluginName; + class CustomAction final : public GameActionBase + { + private: + std::string _id; + std::string _json; + std::string _pluginName; -public: - CustomAction() = default; - CustomAction(const std::string& id, const std::string& json, const std::string& pluginName); + public: + CustomAction() = default; + CustomAction(const std::string& id, const std::string& json, const std::string& pluginName); - std::string GetId() const; - std::string GetJson() const; - std::string GetPluginName() const; + std::string GetId() const; + std::string GetJson() const; + std::string GetPluginName() const; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; -}; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; + }; +} // namespace OpenRCT2::GameActions #endif diff --git a/src/openrct2/actions/FootpathAdditionPlaceAction.cpp b/src/openrct2/actions/FootpathAdditionPlaceAction.cpp index c1811d996c..2421678859 100644 --- a/src/openrct2/actions/FootpathAdditionPlaceAction.cpp +++ b/src/openrct2/actions/FootpathAdditionPlaceAction.cpp @@ -24,177 +24,169 @@ #include "../world/Scenery.h" #include "../world/tile_element/PathElement.h" -using namespace OpenRCT2; - -FootpathAdditionPlaceAction::FootpathAdditionPlaceAction(const CoordsXYZ& loc, ObjectEntryIndex pathItemType) - : _loc(loc) - , _entryIndex(pathItemType) +namespace OpenRCT2::GameActions { -} - -void FootpathAdditionPlaceAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit(_loc); - visitor.Visit("object", _entryIndex); -} - -uint16_t FootpathAdditionPlaceAction::GetActionFlags() const -{ - return GameAction::GetActionFlags(); -} - -void FootpathAdditionPlaceAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_loc) << DS_TAG(_entryIndex); -} - -GameActions::Result FootpathAdditionPlaceAction::Query() const -{ - auto res = GameActions::Result(); - res.Expenditure = ExpenditureType::landscaping; - res.Position = _loc; - if (!LocationValid(_loc)) + FootpathAdditionPlaceAction::FootpathAdditionPlaceAction(const CoordsXYZ& loc, ObjectEntryIndex pathItemType) + : _loc(loc) + , _entryIndex(pathItemType) { - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_OFF_EDGE_OF_MAP); } - if (!(gLegacyScene == LegacyScene::scenarioEditor || getGameState().cheats.sandboxMode) && !MapIsLocationOwned(_loc)) + void FootpathAdditionPlaceAction::AcceptParameters(GameActionParameterVisitor& visitor) { - return GameActions::Result(GameActions::Status::Disallowed, STR_CANT_POSITION_THIS_HERE, STR_LAND_NOT_OWNED_BY_PARK); + visitor.Visit(_loc); + visitor.Visit("object", _entryIndex); } - if (_loc.z < kFootpathMinHeight) + uint16_t FootpathAdditionPlaceAction::GetActionFlags() const { - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_TOO_LOW); + return GameAction::GetActionFlags(); } - if (_loc.z > kFootpathMaxHeight) + void FootpathAdditionPlaceAction::Serialise(DataSerialiser& stream) { - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_TOO_HIGH); + GameAction::Serialise(stream); + + stream << DS_TAG(_loc) << DS_TAG(_entryIndex); } - auto tileElement = MapGetFootpathElement(_loc); - if (tileElement == nullptr) + Result FootpathAdditionPlaceAction::Query() const { - LOG_ERROR("No path element at x = %d, y = %d, z = %d", _loc.x, _loc.y, _loc.z); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_ERR_PATH_ELEMENT_NOT_FOUND); - } - - auto pathElement = tileElement->AsPath(); - if (pathElement->IsLevelCrossing(_loc)) - { - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, - STR_CANNOT_BUILD_PATH_ADDITIONS_ON_LEVEL_CROSSINGS); - } - - // No change - if (!(GetFlags() & GAME_COMMAND_FLAG_GHOST) && pathElement->GetAdditionEntryIndex() == _entryIndex - && !(pathElement->IsBroken())) - { - return res; - } - - auto* pathAdditionEntry = ObjectManager::GetObjectEntry(_entryIndex); - if (pathAdditionEntry == nullptr) - { - LOG_ERROR("Unknown footpath addition entry for entryIndex %d", _entryIndex); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_UNKNOWN_OBJECT_TYPE); - } - uint16_t sceneryFlags = pathAdditionEntry->flags; - - if ((sceneryFlags & PATH_ADDITION_FLAG_DONT_ALLOW_ON_SLOPE) && pathElement->IsSloped()) - { - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_CANT_BUILD_THIS_ON_SLOPED_FOOTPATH); - } - - if ((sceneryFlags & PATH_ADDITION_FLAG_DONT_ALLOW_ON_QUEUE) && pathElement->IsQueue()) - { - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_CANNOT_PLACE_THESE_ON_QUEUE_LINE_AREA); - } - - if (!(sceneryFlags & (PATH_ADDITION_FLAG_JUMPING_FOUNTAIN_WATER | PATH_ADDITION_FLAG_JUMPING_FOUNTAIN_SNOW)) - && (pathElement->GetEdges()) == 0x0F) - { - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_CAN_ONLY_BE_PLACED_ON_PATH_EDGES); - } - - if ((sceneryFlags & PATH_ADDITION_FLAG_IS_QUEUE_SCREEN) && !pathElement->IsQueue()) - { - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_CAN_ONLY_PLACE_THESE_ON_QUEUE_AREA); - } - - res.Cost = pathAdditionEntry->price; - - // Should place a ghost? - if (GetFlags() & GAME_COMMAND_FLAG_GHOST) - { - // Check if there is something on the path already - if (pathElement->HasAddition()) + auto res = Result(); + res.Expenditure = ExpenditureType::landscaping; + res.Position = _loc; + if (!LocationValid(_loc)) { - return GameActions::Result(GameActions::Status::ItemAlreadyPlaced, STR_CANT_POSITION_THIS_HERE, kStringIdNone); + return Result(Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_OFF_EDGE_OF_MAP); } - } - return res; -} -GameActions::Result FootpathAdditionPlaceAction::Execute() const -{ - auto res = GameActions::Result(); - res.Position = _loc; - res.Expenditure = ExpenditureType::landscaping; + if (!(gLegacyScene == LegacyScene::scenarioEditor || getGameState().cheats.sandboxMode) && !MapIsLocationOwned(_loc)) + { + return Result(Status::Disallowed, STR_CANT_POSITION_THIS_HERE, STR_LAND_NOT_OWNED_BY_PARK); + } - auto tileElement = MapGetFootpathElement(_loc); - auto pathElement = tileElement->AsPath(); + if (_loc.z < kFootpathMinHeight) + { + return Result(Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_TOO_LOW); + } - if (pathElement == nullptr) - { - LOG_ERROR("No path element at x = %d, y = %d, z = %d", _loc.x, _loc.y, _loc.z); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_ERR_PATH_ELEMENT_NOT_FOUND); - } + if (_loc.z > kFootpathMaxHeight) + { + return Result(Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_TOO_HIGH); + } - // No change - if (!(GetFlags() & GAME_COMMAND_FLAG_GHOST) && pathElement->GetAdditionEntryIndex() == _entryIndex - && !(pathElement->IsBroken()) && !pathElement->AdditionIsGhost()) - { + auto tileElement = MapGetFootpathElement(_loc); + if (tileElement == nullptr) + { + LOG_ERROR("No path element at x = %d, y = %d, z = %d", _loc.x, _loc.y, _loc.z); + return Result(Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_ERR_PATH_ELEMENT_NOT_FOUND); + } + + auto pathElement = tileElement->AsPath(); + if (pathElement->IsLevelCrossing(_loc)) + { + return Result( + Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_CANNOT_BUILD_PATH_ADDITIONS_ON_LEVEL_CROSSINGS); + } + + // No change + if (!(GetFlags() & GAME_COMMAND_FLAG_GHOST) && pathElement->GetAdditionEntryIndex() == _entryIndex + && !(pathElement->IsBroken())) + { + return res; + } + + auto* pathAdditionEntry = ObjectManager::GetObjectEntry(_entryIndex); + if (pathAdditionEntry == nullptr) + { + LOG_ERROR("Unknown footpath addition entry for entryIndex %d", _entryIndex); + return Result(Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_UNKNOWN_OBJECT_TYPE); + } + uint16_t sceneryFlags = pathAdditionEntry->flags; + + if ((sceneryFlags & PATH_ADDITION_FLAG_DONT_ALLOW_ON_SLOPE) && pathElement->IsSloped()) + { + return Result(Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_CANT_BUILD_THIS_ON_SLOPED_FOOTPATH); + } + + if ((sceneryFlags & PATH_ADDITION_FLAG_DONT_ALLOW_ON_QUEUE) && pathElement->IsQueue()) + { + return Result(Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_CANNOT_PLACE_THESE_ON_QUEUE_LINE_AREA); + } + + if (!(sceneryFlags & (PATH_ADDITION_FLAG_JUMPING_FOUNTAIN_WATER | PATH_ADDITION_FLAG_JUMPING_FOUNTAIN_SNOW)) + && (pathElement->GetEdges()) == 0x0F) + { + return Result(Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_CAN_ONLY_BE_PLACED_ON_PATH_EDGES); + } + + if ((sceneryFlags & PATH_ADDITION_FLAG_IS_QUEUE_SCREEN) && !pathElement->IsQueue()) + { + return Result(Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_CAN_ONLY_PLACE_THESE_ON_QUEUE_AREA); + } + + res.Cost = pathAdditionEntry->price; + + // Should place a ghost? + if (GetFlags() & GAME_COMMAND_FLAG_GHOST) + { + // Check if there is something on the path already + if (pathElement->HasAddition()) + { + return Result(Status::ItemAlreadyPlaced, STR_CANT_POSITION_THIS_HERE, kStringIdNone); + } + } return res; } - auto* pathAdditionEntry = OpenRCT2::ObjectManager::GetObjectEntry(_entryIndex); - if (pathAdditionEntry == nullptr) + Result FootpathAdditionPlaceAction::Execute() const { - LOG_ERROR("Unknown footpath addition entry for entryIndex %d", _entryIndex); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_UNKNOWN_OBJECT_TYPE); - } + auto res = Result(); + res.Position = _loc; + res.Expenditure = ExpenditureType::landscaping; - res.Cost = pathAdditionEntry->price; + auto tileElement = MapGetFootpathElement(_loc); + auto pathElement = tileElement->AsPath(); - if (GetFlags() & GAME_COMMAND_FLAG_GHOST) - { - pathElement->SetAdditionIsGhost(true); - } - else - { - FootpathInterruptPeeps(_loc); - pathElement->SetAdditionIsGhost(false); - } + if (pathElement == nullptr) + { + LOG_ERROR("No path element at x = %d, y = %d, z = %d", _loc.x, _loc.y, _loc.z); + return Result(Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_ERR_PATH_ELEMENT_NOT_FOUND); + } - pathElement->SetAdditionEntryIndex(_entryIndex); - pathElement->SetIsBroken(false); - if (pathAdditionEntry->flags & PATH_ADDITION_FLAG_IS_BIN) - { - pathElement->SetAdditionStatus(255); + // No change + if (!(GetFlags() & GAME_COMMAND_FLAG_GHOST) && pathElement->GetAdditionEntryIndex() == _entryIndex + && !(pathElement->IsBroken()) && !pathElement->AdditionIsGhost()) + { + return res; + } + + auto* pathAdditionEntry = OpenRCT2::ObjectManager::GetObjectEntry(_entryIndex); + if (pathAdditionEntry == nullptr) + { + LOG_ERROR("Unknown footpath addition entry for entryIndex %d", _entryIndex); + return Result(Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_UNKNOWN_OBJECT_TYPE); + } + + res.Cost = pathAdditionEntry->price; + + if (GetFlags() & GAME_COMMAND_FLAG_GHOST) + { + pathElement->SetAdditionIsGhost(true); + } + else + { + FootpathInterruptPeeps(_loc); + pathElement->SetAdditionIsGhost(false); + } + + pathElement->SetAdditionEntryIndex(_entryIndex); + pathElement->SetIsBroken(false); + if (pathAdditionEntry->flags & PATH_ADDITION_FLAG_IS_BIN) + { + pathElement->SetAdditionStatus(255); + } + MapInvalidateTileFull(_loc); + return res; } - MapInvalidateTileFull(_loc); - return res; -} +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/FootpathAdditionPlaceAction.h b/src/openrct2/actions/FootpathAdditionPlaceAction.h index 14fe4fa4ed..8e81475ab1 100644 --- a/src/openrct2/actions/FootpathAdditionPlaceAction.h +++ b/src/openrct2/actions/FootpathAdditionPlaceAction.h @@ -11,21 +11,24 @@ #include "GameAction.h" -class FootpathAdditionPlaceAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - CoordsXYZ _loc; - OpenRCT2::ObjectEntryIndex _entryIndex{}; + class FootpathAdditionPlaceAction final : public GameActionBase + { + private: + CoordsXYZ _loc; + ObjectEntryIndex _entryIndex{}; -public: - FootpathAdditionPlaceAction() = default; - FootpathAdditionPlaceAction(const CoordsXYZ& loc, OpenRCT2::ObjectEntryIndex pathItemType); + public: + FootpathAdditionPlaceAction() = default; + FootpathAdditionPlaceAction(const CoordsXYZ& loc, ObjectEntryIndex pathItemType); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; -}; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/FootpathAdditionRemoveAction.cpp b/src/openrct2/actions/FootpathAdditionRemoveAction.cpp index f506cfdf3c..d1645283d4 100644 --- a/src/openrct2/actions/FootpathAdditionRemoveAction.cpp +++ b/src/openrct2/actions/FootpathAdditionRemoveAction.cpp @@ -21,99 +21,97 @@ #include "../world/Park.h" #include "../world/tile_element/PathElement.h" -using namespace OpenRCT2; - -FootpathAdditionRemoveAction::FootpathAdditionRemoveAction(const CoordsXYZ& loc) - : _loc(loc) +namespace OpenRCT2::GameActions { -} - -void FootpathAdditionRemoveAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit(_loc); -} - -uint16_t FootpathAdditionRemoveAction::GetActionFlags() const -{ - return GameAction::GetActionFlags(); -} - -void FootpathAdditionRemoveAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_loc); -} - -GameActions::Result FootpathAdditionRemoveAction::Query() const -{ - if (!LocationValid(_loc)) + FootpathAdditionRemoveAction::FootpathAdditionRemoveAction(const CoordsXYZ& loc) + : _loc(loc) { - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_REMOVE_THIS, STR_OFF_EDGE_OF_MAP); } - if (!(gLegacyScene == LegacyScene::scenarioEditor || getGameState().cheats.sandboxMode) && !MapIsLocationOwned(_loc)) + void FootpathAdditionRemoveAction::AcceptParameters(GameActionParameterVisitor& visitor) { - return GameActions::Result(GameActions::Status::Disallowed, STR_CANT_REMOVE_THIS, STR_LAND_NOT_OWNED_BY_PARK); + visitor.Visit(_loc); } - if (_loc.z < kFootpathMinHeight) + uint16_t FootpathAdditionRemoveAction::GetActionFlags() const { - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_REMOVE_THIS, STR_TOO_LOW); + return GameAction::GetActionFlags(); } - if (_loc.z > kFootpathMaxHeight) + void FootpathAdditionRemoveAction::Serialise(DataSerialiser& stream) { - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_REMOVE_THIS, STR_TOO_HIGH); + GameAction::Serialise(stream); + + stream << DS_TAG(_loc); } - auto tileElement = MapGetFootpathElement(_loc); - if (tileElement == nullptr) + Result FootpathAdditionRemoveAction::Query() const { - LOG_ERROR("No path element at x = %d, y = %d, z = %d", _loc.x, _loc.y, _loc.z); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_REMOVE_THIS, STR_ERR_PATH_ELEMENT_NOT_FOUND); + if (!LocationValid(_loc)) + { + return Result(Status::InvalidParameters, STR_CANT_REMOVE_THIS, STR_OFF_EDGE_OF_MAP); + } + + if (!(gLegacyScene == LegacyScene::scenarioEditor || getGameState().cheats.sandboxMode) && !MapIsLocationOwned(_loc)) + { + return Result(Status::Disallowed, STR_CANT_REMOVE_THIS, STR_LAND_NOT_OWNED_BY_PARK); + } + + if (_loc.z < kFootpathMinHeight) + { + return Result(Status::InvalidParameters, STR_CANT_REMOVE_THIS, STR_TOO_LOW); + } + + if (_loc.z > kFootpathMaxHeight) + { + return Result(Status::InvalidParameters, STR_CANT_REMOVE_THIS, STR_TOO_HIGH); + } + + auto tileElement = MapGetFootpathElement(_loc); + if (tileElement == nullptr) + { + LOG_ERROR("No path element at x = %d, y = %d, z = %d", _loc.x, _loc.y, _loc.z); + return Result(Status::InvalidParameters, STR_CANT_REMOVE_THIS, STR_ERR_PATH_ELEMENT_NOT_FOUND); + } + + auto pathElement = tileElement->AsPath(); + if (pathElement == nullptr) + { + LOG_ERROR("No path element at x = %d, y = %d, z = %d", _loc.x, _loc.y, _loc.z); + return Result(Status::InvalidParameters, STR_CANT_REMOVE_THIS, STR_ERR_PATH_ELEMENT_NOT_FOUND); + } + + if (!pathElement->AdditionIsGhost() && (GetFlags() & GAME_COMMAND_FLAG_GHOST)) + { + LOG_WARNING("Tried to remove non ghost during ghost removal."); + return Result(Status::Disallowed, STR_CANT_REMOVE_THIS, kStringIdNone); + } + auto res = Result(); + res.Position = _loc; + res.Cost = 0.00_GBP; + return res; } - auto pathElement = tileElement->AsPath(); - if (pathElement == nullptr) + Result FootpathAdditionRemoveAction::Execute() const { - LOG_ERROR("No path element at x = %d, y = %d, z = %d", _loc.x, _loc.y, _loc.z); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_REMOVE_THIS, STR_ERR_PATH_ELEMENT_NOT_FOUND); + auto* pathElement = MapGetFootpathElement(_loc); + if (!(GetFlags() & GAME_COMMAND_FLAG_GHOST)) + { + FootpathInterruptPeeps(_loc); + } + + if (pathElement == nullptr) + { + LOG_ERROR("No path element at x = %d, y = %d, z = %d", _loc.x, _loc.y, _loc.z); + return Result(Status::InvalidParameters, STR_CANT_REMOVE_THIS, STR_ERR_PATH_ELEMENT_NOT_FOUND); + } + + pathElement->SetAddition(0); + MapInvalidateTileFull(_loc); + + auto res = Result(); + res.Position = _loc; + res.Cost = 0.00_GBP; + return res; } - - if (!pathElement->AdditionIsGhost() && (GetFlags() & GAME_COMMAND_FLAG_GHOST)) - { - LOG_WARNING("Tried to remove non ghost during ghost removal."); - return GameActions::Result(GameActions::Status::Disallowed, STR_CANT_REMOVE_THIS, kStringIdNone); - } - auto res = GameActions::Result(); - res.Position = _loc; - res.Cost = 0.00_GBP; - return res; -} - -GameActions::Result FootpathAdditionRemoveAction::Execute() const -{ - auto* pathElement = MapGetFootpathElement(_loc); - if (!(GetFlags() & GAME_COMMAND_FLAG_GHOST)) - { - FootpathInterruptPeeps(_loc); - } - - if (pathElement == nullptr) - { - LOG_ERROR("No path element at x = %d, y = %d, z = %d", _loc.x, _loc.y, _loc.z); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_REMOVE_THIS, STR_ERR_PATH_ELEMENT_NOT_FOUND); - } - - pathElement->SetAddition(0); - MapInvalidateTileFull(_loc); - - auto res = GameActions::Result(); - res.Position = _loc; - res.Cost = 0.00_GBP; - return res; -} +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/FootpathAdditionRemoveAction.h b/src/openrct2/actions/FootpathAdditionRemoveAction.h index 761ebe03d5..e43166f8ed 100644 --- a/src/openrct2/actions/FootpathAdditionRemoveAction.h +++ b/src/openrct2/actions/FootpathAdditionRemoveAction.h @@ -11,20 +11,23 @@ #include "GameAction.h" -class FootpathAdditionRemoveAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - CoordsXYZ _loc; + class FootpathAdditionRemoveAction final : public GameActionBase + { + private: + CoordsXYZ _loc; -public: - FootpathAdditionRemoveAction() = default; - FootpathAdditionRemoveAction(const CoordsXYZ& loc); + public: + FootpathAdditionRemoveAction() = default; + FootpathAdditionRemoveAction(const CoordsXYZ& loc); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; -}; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/FootpathLayoutPlaceAction.cpp b/src/openrct2/actions/FootpathLayoutPlaceAction.cpp index 6eb5371e60..7a189db203 100644 --- a/src/openrct2/actions/FootpathLayoutPlaceAction.cpp +++ b/src/openrct2/actions/FootpathLayoutPlaceAction.cpp @@ -26,295 +26,291 @@ #include "../world/tile_element/Slope.h" #include "../world/tile_element/SurfaceElement.h" -using namespace OpenRCT2; - -FootpathLayoutPlaceAction::FootpathLayoutPlaceAction( - const CoordsXYZ& loc, uint8_t slope, ObjectEntryIndex type, ObjectEntryIndex railingsType, uint8_t edges, - PathConstructFlags constructFlags) - : _loc(loc) - , _slope(slope) - , _type(type) - , _railingsType(railingsType) - , _edges(edges) - , _constructFlags(constructFlags) +namespace OpenRCT2::GameActions { -} - -void FootpathLayoutPlaceAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_loc) << DS_TAG(_slope) << DS_TAG(_type) << DS_TAG(_railingsType) << DS_TAG(_edges) - << DS_TAG(_constructFlags); -} - -void FootpathLayoutPlaceAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit(_loc); - visitor.Visit("slope", _slope); - visitor.Visit("object", _type); - visitor.Visit("railingsObject", _railingsType); - visitor.Visit("edges", _edges); - visitor.Visit("constructFlags", _constructFlags); -} - -uint16_t FootpathLayoutPlaceAction::GetActionFlags() const -{ - return GameAction::GetActionFlags(); -} - -GameActions::Result FootpathLayoutPlaceAction::Query() const -{ - auto res = GameActions::Result(); - res.Cost = 0; - res.Expenditure = ExpenditureType::landscaping; - res.Position = _loc.ToTileCentre(); - - gFootpathGroundFlags = 0; - - if (!LocationValid(_loc) || MapIsEdge(_loc)) + FootpathLayoutPlaceAction::FootpathLayoutPlaceAction( + const CoordsXYZ& loc, uint8_t slope, ObjectEntryIndex type, ObjectEntryIndex railingsType, uint8_t edges, + PathConstructFlags constructFlags) + : _loc(loc) + , _slope(slope) + , _type(type) + , _railingsType(railingsType) + , _edges(edges) + , _constructFlags(constructFlags) { - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_OFF_EDGE_OF_MAP); } - if (!(gLegacyScene == LegacyScene::scenarioEditor || getGameState().cheats.sandboxMode) && !MapIsLocationOwned(_loc)) + void FootpathLayoutPlaceAction::Serialise(DataSerialiser& stream) { - return GameActions::Result( - GameActions::Status::Disallowed, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_LAND_NOT_OWNED_BY_PARK); + GameAction::Serialise(stream); + + stream << DS_TAG(_loc) << DS_TAG(_slope) << DS_TAG(_type) << DS_TAG(_railingsType) << DS_TAG(_edges) + << DS_TAG(_constructFlags); } - if (_loc.z < kFootpathMinHeight) + void FootpathLayoutPlaceAction::AcceptParameters(GameActionParameterVisitor& visitor) { - return GameActions::Result( - GameActions::Status::Disallowed, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_TOO_LOW); + visitor.Visit(_loc); + visitor.Visit("slope", _slope); + visitor.Visit("object", _type); + visitor.Visit("railingsObject", _railingsType); + visitor.Visit("edges", _edges); + visitor.Visit("constructFlags", _constructFlags); } - if (_loc.z > kFootpathMaxHeight) + uint16_t FootpathLayoutPlaceAction::GetActionFlags() const { - return GameActions::Result( - GameActions::Status::Disallowed, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_TOO_HIGH); + return GameAction::GetActionFlags(); } - return ElementInsertQuery(std::move(res)); -} - -GameActions::Result FootpathLayoutPlaceAction::Execute() const -{ - auto res = GameActions::Result(); - res.Cost = 0; - res.Expenditure = ExpenditureType::landscaping; - res.Position = _loc.ToTileCentre(); - - if (!(GetFlags() & GAME_COMMAND_FLAG_GHOST)) + Result FootpathLayoutPlaceAction::Query() const { - FootpathInterruptPeeps(_loc); - } - - gFootpathGroundFlags = 0; - - // Force ride construction to recheck area - _currentTrackSelectionFlags.set(TrackSelectionFlag::recheck); - - return ElementInsertExecute(std::move(res)); -} - -GameActions::Result FootpathLayoutPlaceAction::ElementInsertQuery(GameActions::Result res) const -{ - bool entrancePath = false, entranceIsSamePath = false; - - if (!MapCheckCapacityAndReorganise(_loc)) - { - return GameActions::Result( - GameActions::Status::NoFreeElements, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, - STR_TILE_ELEMENT_LIMIT_REACHED); - } - - res.Cost = 12.00_GBP; - - QuarterTile quarterTile{ 0b1111, 0 }; - auto zLow = _loc.z; - auto zHigh = zLow + kPathClearance; - if (_slope & FOOTPATH_PROPERTIES_FLAG_IS_SLOPED) - { - quarterTile = QuarterTile{ 0b1111, 0b1100 }.Rotate(_slope & kTileElementDirectionMask); - zHigh += kPathHeightStep; - } - - auto entranceElement = MapGetParkEntranceElementAt(_loc, false); - // Make sure the entrance part is the middle - if (entranceElement != nullptr && (entranceElement->GetSequenceIndex()) == 0) - { - entrancePath = true; - // Make the price the same as replacing a path - if (IsSameAsEntranceElement(*entranceElement)) - entranceIsSamePath = true; - else - res.Cost -= 6.00_GBP; - } - - // Do not attempt to build a crossing with a queue or a sloped path. - auto isQueue = _constructFlags & PathConstructFlag::IsQueue; - auto crossingMode = isQueue || (_slope != kTileSlopeFlat) ? CreateCrossingMode::none : CreateCrossingMode::pathOverTrack; - auto canBuild = MapCanConstructWithClearAt( - { _loc, zLow, zHigh }, &MapPlaceNonSceneryClearFunc, quarterTile, GetFlags(), crossingMode); - if (!entrancePath && canBuild.Error != GameActions::Status::Ok) - { - canBuild.ErrorTitle = STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE; - return canBuild; - } - res.Cost += canBuild.Cost; - - const auto clearanceData = canBuild.GetData(); - gFootpathGroundFlags = clearanceData.GroundFlags; - - if (!getGameState().cheats.disableClearanceChecks && (clearanceData.GroundFlags & ELEMENT_IS_UNDERWATER)) - { - return GameActions::Result( - GameActions::Status::Disallowed, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_CANT_BUILD_THIS_UNDERWATER); - } - - auto surfaceElement = MapGetSurfaceElementAt(_loc); - if (surfaceElement == nullptr) - { - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, - STR_ERR_SURFACE_ELEMENT_NOT_FOUND); - } - int32_t supportHeight = zLow - surfaceElement->GetBaseZ(); - res.Cost += supportHeight < 0 ? 20.00_GBP : (supportHeight / kPathHeightStep) * 5.00_GBP; - - // Prevent the place sound from being spammed - if (entranceIsSamePath) + auto res = Result(); res.Cost = 0; + res.Expenditure = ExpenditureType::landscaping; + res.Position = _loc.ToTileCentre(); - return res; -} + gFootpathGroundFlags = 0; -GameActions::Result FootpathLayoutPlaceAction::ElementInsertExecute(GameActions::Result res) const -{ - bool entrancePath = false, entranceIsSamePath = false; - - if (!(GetFlags() & (GAME_COMMAND_FLAG_ALLOW_DURING_PAUSED | GAME_COMMAND_FLAG_GHOST))) - { - FootpathRemoveLitter(_loc); - } - - res.Cost = 12.00_GBP; - - QuarterTile quarterTile{ 0b1111, 0 }; - auto zLow = _loc.z; - auto zHigh = zLow + kPathClearance; - if (_slope & FOOTPATH_PROPERTIES_FLAG_IS_SLOPED) - { - quarterTile = QuarterTile{ 0b1111, 0b1100 }.Rotate(_slope & kTileElementDirectionMask); - zHigh += kPathHeightStep; - } - - auto entranceElement = MapGetParkEntranceElementAt(_loc, false); - // Make sure the entrance part is the middle - if (entranceElement != nullptr && (entranceElement->GetSequenceIndex()) == 0) - { - entrancePath = true; - // Make the price the same as replacing a path - if (IsSameAsEntranceElement(*entranceElement)) - entranceIsSamePath = true; - else - res.Cost -= 6.00_GBP; - } - - // Do not attempt to build a crossing with a queue or a sloped path. - auto isQueue = _constructFlags & PathConstructFlag::IsQueue; - auto crossingMode = isQueue || (_slope != kTileSlopeFlat) ? CreateCrossingMode::none : CreateCrossingMode::pathOverTrack; - auto canBuild = MapCanConstructWithClearAt( - { _loc, zLow, zHigh }, &MapPlaceNonSceneryClearFunc, quarterTile, GAME_COMMAND_FLAG_APPLY | GetFlags(), crossingMode); - if (!entrancePath && canBuild.Error != GameActions::Status::Ok) - { - canBuild.ErrorTitle = STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE; - return canBuild; - } - res.Cost += canBuild.Cost; - - const auto clearanceData = canBuild.GetData(); - gFootpathGroundFlags = clearanceData.GroundFlags; - - auto surfaceElement = MapGetSurfaceElementAt(_loc); - if (surfaceElement == nullptr) - { - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, - STR_ERR_SURFACE_ELEMENT_NOT_FOUND); - } - int32_t supportHeight = zLow - surfaceElement->GetBaseZ(); - res.Cost += supportHeight < 0 ? 20.00_GBP : (supportHeight / kPathHeightStep) * 5.00_GBP; - - if (entrancePath) - { - if (!(GetFlags() & GAME_COMMAND_FLAG_GHOST) && !entranceIsSamePath) + if (!LocationValid(_loc) || MapIsEdge(_loc)) { + return Result(Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_OFF_EDGE_OF_MAP); + } + + if (!(gLegacyScene == LegacyScene::scenarioEditor || getGameState().cheats.sandboxMode) && !MapIsLocationOwned(_loc)) + { + return Result(Status::Disallowed, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_LAND_NOT_OWNED_BY_PARK); + } + + if (_loc.z < kFootpathMinHeight) + { + return Result(Status::Disallowed, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_TOO_LOW); + } + + if (_loc.z > kFootpathMaxHeight) + { + return Result(Status::Disallowed, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_TOO_HIGH); + } + + return ElementInsertQuery(std::move(res)); + } + + Result FootpathLayoutPlaceAction::Execute() const + { + auto res = Result(); + res.Cost = 0; + res.Expenditure = ExpenditureType::landscaping; + res.Position = _loc.ToTileCentre(); + + if (!(GetFlags() & GAME_COMMAND_FLAG_GHOST)) + { + FootpathInterruptPeeps(_loc); + } + + gFootpathGroundFlags = 0; + + // Force ride construction to recheck area + _currentTrackSelectionFlags.set(TrackSelectionFlag::recheck); + + return ElementInsertExecute(std::move(res)); + } + + Result FootpathLayoutPlaceAction::ElementInsertQuery(Result res) const + { + bool entrancePath = false, entranceIsSamePath = false; + + if (!MapCheckCapacityAndReorganise(_loc)) + { + return Result( + Status::NoFreeElements, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_TILE_ELEMENT_LIMIT_REACHED); + } + + res.Cost = 12.00_GBP; + + QuarterTile quarterTile{ 0b1111, 0 }; + auto zLow = _loc.z; + auto zHigh = zLow + kPathClearance; + if (_slope & FOOTPATH_PROPERTIES_FLAG_IS_SLOPED) + { + quarterTile = QuarterTile{ 0b1111, 0b1100 }.Rotate(_slope & kTileElementDirectionMask); + zHigh += kPathHeightStep; + } + + auto entranceElement = MapGetParkEntranceElementAt(_loc, false); + // Make sure the entrance part is the middle + if (entranceElement != nullptr && (entranceElement->GetSequenceIndex()) == 0) + { + entrancePath = true; + // Make the price the same as replacing a path + if (IsSameAsEntranceElement(*entranceElement)) + entranceIsSamePath = true; + else + res.Cost -= 6.00_GBP; + } + + // Do not attempt to build a crossing with a queue or a sloped path. + auto isQueue = _constructFlags & PathConstructFlag::IsQueue; + auto crossingMode = isQueue || (_slope != kTileSlopeFlat) ? CreateCrossingMode::none + : CreateCrossingMode::pathOverTrack; + auto canBuild = MapCanConstructWithClearAt( + { _loc, zLow, zHigh }, &MapPlaceNonSceneryClearFunc, quarterTile, GetFlags(), crossingMode); + if (!entrancePath && canBuild.Error != Status::Ok) + { + canBuild.ErrorTitle = STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE; + return canBuild; + } + res.Cost += canBuild.Cost; + + const auto clearanceData = canBuild.GetData(); + gFootpathGroundFlags = clearanceData.GroundFlags; + + if (!getGameState().cheats.disableClearanceChecks && (clearanceData.GroundFlags & ELEMENT_IS_UNDERWATER)) + { + return Result(Status::Disallowed, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_CANT_BUILD_THIS_UNDERWATER); + } + + auto surfaceElement = MapGetSurfaceElementAt(_loc); + if (surfaceElement == nullptr) + { + return Result( + Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_ERR_SURFACE_ELEMENT_NOT_FOUND); + } + int32_t supportHeight = zLow - surfaceElement->GetBaseZ(); + res.Cost += supportHeight < 0 ? 20.00_GBP : (supportHeight / kPathHeightStep) * 5.00_GBP; + + // Prevent the place sound from being spammed + if (entranceIsSamePath) + res.Cost = 0; + + return res; + } + + Result FootpathLayoutPlaceAction::ElementInsertExecute(Result res) const + { + bool entrancePath = false, entranceIsSamePath = false; + + if (!(GetFlags() & (GAME_COMMAND_FLAG_ALLOW_DURING_PAUSED | GAME_COMMAND_FLAG_GHOST))) + { + FootpathRemoveLitter(_loc); + } + + res.Cost = 12.00_GBP; + + QuarterTile quarterTile{ 0b1111, 0 }; + auto zLow = _loc.z; + auto zHigh = zLow + kPathClearance; + if (_slope & FOOTPATH_PROPERTIES_FLAG_IS_SLOPED) + { + quarterTile = QuarterTile{ 0b1111, 0b1100 }.Rotate(_slope & kTileElementDirectionMask); + zHigh += kPathHeightStep; + } + + auto entranceElement = MapGetParkEntranceElementAt(_loc, false); + // Make sure the entrance part is the middle + if (entranceElement != nullptr && (entranceElement->GetSequenceIndex()) == 0) + { + entrancePath = true; + // Make the price the same as replacing a path + if (IsSameAsEntranceElement(*entranceElement)) + entranceIsSamePath = true; + else + res.Cost -= 6.00_GBP; + } + + // Do not attempt to build a crossing with a queue or a sloped path. + auto isQueue = _constructFlags & PathConstructFlag::IsQueue; + auto crossingMode = isQueue || (_slope != kTileSlopeFlat) ? CreateCrossingMode::none + : CreateCrossingMode::pathOverTrack; + auto canBuild = MapCanConstructWithClearAt( + { _loc, zLow, zHigh }, &MapPlaceNonSceneryClearFunc, quarterTile, GAME_COMMAND_FLAG_APPLY | GetFlags(), + crossingMode); + if (!entrancePath && canBuild.Error != Status::Ok) + { + canBuild.ErrorTitle = STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE; + return canBuild; + } + res.Cost += canBuild.Cost; + + const auto clearanceData = canBuild.GetData(); + gFootpathGroundFlags = clearanceData.GroundFlags; + + auto surfaceElement = MapGetSurfaceElementAt(_loc); + if (surfaceElement == nullptr) + { + return Result( + Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_ERR_SURFACE_ELEMENT_NOT_FOUND); + } + int32_t supportHeight = zLow - surfaceElement->GetBaseZ(); + res.Cost += supportHeight < 0 ? 20.00_GBP : (supportHeight / kPathHeightStep) * 5.00_GBP; + + if (entrancePath) + { + if (!(GetFlags() & GAME_COMMAND_FLAG_GHOST) && !entranceIsSamePath) + { + if (_constructFlags & PathConstructFlag::IsLegacyPathObject) + { + entranceElement->SetLegacyPathEntryIndex(_type); + } + else + { + entranceElement->SetSurfaceEntryIndex(_type); + } + MapInvalidateTileFull(_loc); + } + } + else + { + auto* pathElement = TileElementInsert(_loc, 0b1111); + Guard::Assert(pathElement != nullptr); + + pathElement->SetClearanceZ(zHigh); if (_constructFlags & PathConstructFlag::IsLegacyPathObject) { - entranceElement->SetLegacyPathEntryIndex(_type); + pathElement->SetLegacyPathEntryIndex(_type); } else { - entranceElement->SetSurfaceEntryIndex(_type); + pathElement->SetSurfaceEntryIndex(_type); + pathElement->SetRailingsEntryIndex(_railingsType); } + pathElement->SetSlopeDirection(_slope & FOOTPATH_PROPERTIES_SLOPE_DIRECTION_MASK); + pathElement->SetSloped(_slope & FOOTPATH_PROPERTIES_FLAG_IS_SLOPED); + pathElement->SetIsQueue(isQueue); + pathElement->SetAddition(0); + pathElement->SetRideIndex(RideId::GetNull()); + pathElement->SetAdditionStatus(255); + pathElement->SetIsBroken(false); + pathElement->SetEdges(_edges); + pathElement->SetCorners(0); + pathElement->SetGhost(GetFlags() & GAME_COMMAND_FLAG_GHOST); + MapInvalidateTileFull(_loc); } - } - else - { - auto* pathElement = TileElementInsert(_loc, 0b1111); - Guard::Assert(pathElement != nullptr); - pathElement->SetClearanceZ(zHigh); + // Prevent the place sound from being spammed + if (entranceIsSamePath) + res.Cost = 0; + + return res; + } + + bool FootpathLayoutPlaceAction::IsSameAsEntranceElement(const EntranceElement& entranceElement) const + { + if (entranceElement.HasLegacyPathEntry()) + { + if (_constructFlags & PathConstructFlag::IsLegacyPathObject) + { + return entranceElement.GetLegacyPathEntryIndex() == _type; + } + + return false; + } + if (_constructFlags & PathConstructFlag::IsLegacyPathObject) { - pathElement->SetLegacyPathEntryIndex(_type); - } - else - { - pathElement->SetSurfaceEntryIndex(_type); - pathElement->SetRailingsEntryIndex(_railingsType); - } - pathElement->SetSlopeDirection(_slope & FOOTPATH_PROPERTIES_SLOPE_DIRECTION_MASK); - pathElement->SetSloped(_slope & FOOTPATH_PROPERTIES_FLAG_IS_SLOPED); - pathElement->SetIsQueue(isQueue); - pathElement->SetAddition(0); - pathElement->SetRideIndex(RideId::GetNull()); - pathElement->SetAdditionStatus(255); - pathElement->SetIsBroken(false); - pathElement->SetEdges(_edges); - pathElement->SetCorners(0); - pathElement->SetGhost(GetFlags() & GAME_COMMAND_FLAG_GHOST); - - MapInvalidateTileFull(_loc); - } - - // Prevent the place sound from being spammed - if (entranceIsSamePath) - res.Cost = 0; - - return res; -} - -bool FootpathLayoutPlaceAction::IsSameAsEntranceElement(const EntranceElement& entranceElement) const -{ - if (entranceElement.HasLegacyPathEntry()) - { - if (_constructFlags & PathConstructFlag::IsLegacyPathObject) - { - return entranceElement.GetLegacyPathEntryIndex() == _type; + return false; } - return false; + return entranceElement.GetSurfaceEntryIndex() == _type; } - - if (_constructFlags & PathConstructFlag::IsLegacyPathObject) - { - return false; - } - - return entranceElement.GetSurfaceEntryIndex() == _type; -} +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/FootpathLayoutPlaceAction.h b/src/openrct2/actions/FootpathLayoutPlaceAction.h index 4434007df0..576baf8465 100644 --- a/src/openrct2/actions/FootpathLayoutPlaceAction.h +++ b/src/openrct2/actions/FootpathLayoutPlaceAction.h @@ -12,32 +12,35 @@ #include "../world/Footpath.h" #include "GameAction.h" -class FootpathLayoutPlaceAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - CoordsXYZ _loc; - uint8_t _slope{}; - OpenRCT2::ObjectEntryIndex _type{}; - OpenRCT2::ObjectEntryIndex _railingsType{}; - uint8_t _edges{}; - PathConstructFlags _constructFlags{}; + class FootpathLayoutPlaceAction final : public GameActionBase + { + private: + CoordsXYZ _loc; + uint8_t _slope{}; + ObjectEntryIndex _type{}; + ObjectEntryIndex _railingsType{}; + uint8_t _edges{}; + PathConstructFlags _constructFlags{}; -public: - FootpathLayoutPlaceAction() = default; - FootpathLayoutPlaceAction( - const CoordsXYZ& loc, uint8_t slope, OpenRCT2::ObjectEntryIndex type, OpenRCT2::ObjectEntryIndex railingsType, - uint8_t edges, PathConstructFlags constructFlags = 0); + public: + FootpathLayoutPlaceAction() = default; + FootpathLayoutPlaceAction( + const CoordsXYZ& loc, uint8_t slope, ObjectEntryIndex type, ObjectEntryIndex railingsType, uint8_t edges, + PathConstructFlags constructFlags = 0); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; -private: - OpenRCT2::GameActions::Result ElementInsertQuery(OpenRCT2::GameActions::Result res) const; - OpenRCT2::GameActions::Result ElementInsertExecute(OpenRCT2::GameActions::Result res) const; - bool IsSameAsEntranceElement(const OpenRCT2::EntranceElement& entranceElement) const; -}; + private: + Result ElementInsertQuery(Result res) const; + Result ElementInsertExecute(Result res) const; + bool IsSameAsEntranceElement(const EntranceElement& entranceElement) const; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/FootpathPlaceAction.cpp b/src/openrct2/actions/FootpathPlaceAction.cpp index 5f19db237e..047e4376e6 100644 --- a/src/openrct2/actions/FootpathPlaceAction.cpp +++ b/src/openrct2/actions/FootpathPlaceAction.cpp @@ -35,399 +35,212 @@ #include -using namespace OpenRCT2; - -FootpathPlaceAction::FootpathPlaceAction( - const CoordsXYZ& loc, uint8_t slope, ObjectEntryIndex type, ObjectEntryIndex railingsType, Direction direction, - PathConstructFlags constructFlags) - : _loc(loc) - , _slope(slope) - , _type(type) - , _railingsType(railingsType) - , _direction(direction) - , _constructFlags(constructFlags) +namespace OpenRCT2::GameActions { -} - -void FootpathPlaceAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit(_loc); - visitor.Visit("object", _type); - visitor.Visit("railingsObject", _railingsType); - visitor.Visit("direction", _direction); - visitor.Visit("slope", _slope); - visitor.Visit("constructFlags", _constructFlags); -} - -uint16_t FootpathPlaceAction::GetActionFlags() const -{ - return GameAction::GetActionFlags(); -} - -void FootpathPlaceAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_loc) << DS_TAG(_slope) << DS_TAG(_type) << DS_TAG(_railingsType) << DS_TAG(_direction) - << DS_TAG(_constructFlags); -} - -GameActions::Result FootpathPlaceAction::Query() const -{ - auto res = GameActions::Result(); - res.Cost = 0; - res.Expenditure = ExpenditureType::landscaping; - res.Position = _loc.ToTileCentre(); - - gFootpathGroundFlags = 0; - - if (!LocationValid(_loc) || MapIsEdge(_loc)) + FootpathPlaceAction::FootpathPlaceAction( + const CoordsXYZ& loc, uint8_t slope, ObjectEntryIndex type, ObjectEntryIndex railingsType, Direction direction, + PathConstructFlags constructFlags) + : _loc(loc) + , _slope(slope) + , _type(type) + , _railingsType(railingsType) + , _direction(direction) + , _constructFlags(constructFlags) { - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_BUILD_FOOTPATH_HERE, STR_OFF_EDGE_OF_MAP); } - if (!(gLegacyScene == LegacyScene::scenarioEditor || getGameState().cheats.sandboxMode) && !MapIsLocationOwned(_loc)) + void FootpathPlaceAction::AcceptParameters(GameActionParameterVisitor& visitor) { - return GameActions::Result(GameActions::Status::Disallowed, STR_CANT_BUILD_FOOTPATH_HERE, STR_LAND_NOT_OWNED_BY_PARK); + visitor.Visit(_loc); + visitor.Visit("object", _type); + visitor.Visit("railingsObject", _railingsType); + visitor.Visit("direction", _direction); + visitor.Visit("slope", _slope); + visitor.Visit("constructFlags", _constructFlags); } - if (_slope & SLOPE_IS_IRREGULAR_FLAG) + uint16_t FootpathPlaceAction::GetActionFlags() const { - return GameActions::Result(GameActions::Status::Disallowed, STR_CANT_BUILD_FOOTPATH_HERE, STR_LAND_SLOPE_UNSUITABLE); + return GameAction::GetActionFlags(); } - if (_loc.z < kFootpathMinHeight) + void FootpathPlaceAction::Serialise(DataSerialiser& stream) { - return GameActions::Result(GameActions::Status::Disallowed, STR_CANT_BUILD_FOOTPATH_HERE, STR_TOO_LOW); + GameAction::Serialise(stream); + + stream << DS_TAG(_loc) << DS_TAG(_slope) << DS_TAG(_type) << DS_TAG(_railingsType) << DS_TAG(_direction) + << DS_TAG(_constructFlags); } - if (_loc.z > kFootpathMaxHeight) + Result FootpathPlaceAction::Query() const { - return GameActions::Result(GameActions::Status::Disallowed, STR_CANT_BUILD_FOOTPATH_HERE, STR_TOO_HIGH); - } + auto res = Result(); + res.Cost = 0; + res.Expenditure = ExpenditureType::landscaping; + res.Position = _loc.ToTileCentre(); - if (_direction != kInvalidDirection && !DirectionValid(_direction)) - { - LOG_ERROR("Direction invalid. direction = %u", _direction); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_BUILD_FOOTPATH_HERE, STR_ERR_VALUE_OUT_OF_RANGE); - } + gFootpathGroundFlags = 0; - auto intent = Intent(INTENT_ACTION_REMOVE_PROVISIONAL_FOOTPATH); - ContextBroadcastIntent(&intent); - - auto tileElement = MapGetFootpathElementSlope(_loc, _slope); - if (tileElement == nullptr) - { - return ElementInsertQuery(std::move(res)); - } - return ElementUpdateQuery(tileElement, std::move(res)); -} - -GameActions::Result FootpathPlaceAction::Execute() const -{ - auto res = GameActions::Result(); - res.Cost = 0; - res.Expenditure = ExpenditureType::landscaping; - res.Position = _loc.ToTileCentre(); - - if (!(GetFlags() & GAME_COMMAND_FLAG_GHOST)) - { - FootpathInterruptPeeps(_loc); - } - - gFootpathGroundFlags = 0; - - // Force ride construction to recheck area - _currentTrackSelectionFlags.set(TrackSelectionFlag::recheck); - - if (!(GetFlags() & GAME_COMMAND_FLAG_GHOST)) - { - if (_direction != kInvalidDirection && !getGameState().cheats.disableClearanceChecks) + if (!LocationValid(_loc) || MapIsEdge(_loc)) { - // It is possible, let's remove walls between the old and new piece of path - auto zLow = _loc.z; - auto zHigh = zLow + kPathClearance; - WallRemoveIntersectingWalls( - { _loc, zLow, zHigh + ((_slope & kTileSlopeRaisedCornersMask) ? 16 : 0) }, DirectionReverse(_direction)); - WallRemoveIntersectingWalls( - { _loc.x - CoordsDirectionDelta[_direction].x, _loc.y - CoordsDirectionDelta[_direction].y, zLow, zHigh }, - _direction); + return Result(Status::InvalidParameters, STR_CANT_BUILD_FOOTPATH_HERE, STR_OFF_EDGE_OF_MAP); } + + if (!(gLegacyScene == LegacyScene::scenarioEditor || getGameState().cheats.sandboxMode) && !MapIsLocationOwned(_loc)) + { + return Result(Status::Disallowed, STR_CANT_BUILD_FOOTPATH_HERE, STR_LAND_NOT_OWNED_BY_PARK); + } + + if (_slope & SLOPE_IS_IRREGULAR_FLAG) + { + return Result(Status::Disallowed, STR_CANT_BUILD_FOOTPATH_HERE, STR_LAND_SLOPE_UNSUITABLE); + } + + if (_loc.z < kFootpathMinHeight) + { + return Result(Status::Disallowed, STR_CANT_BUILD_FOOTPATH_HERE, STR_TOO_LOW); + } + + if (_loc.z > kFootpathMaxHeight) + { + return Result(Status::Disallowed, STR_CANT_BUILD_FOOTPATH_HERE, STR_TOO_HIGH); + } + + if (_direction != kInvalidDirection && !DirectionValid(_direction)) + { + LOG_ERROR("Direction invalid. direction = %u", _direction); + return Result(Status::InvalidParameters, STR_CANT_BUILD_FOOTPATH_HERE, STR_ERR_VALUE_OUT_OF_RANGE); + } + + auto intent = Intent(INTENT_ACTION_REMOVE_PROVISIONAL_FOOTPATH); + ContextBroadcastIntent(&intent); + + auto tileElement = MapGetFootpathElementSlope(_loc, _slope); + if (tileElement == nullptr) + { + return ElementInsertQuery(std::move(res)); + } + return ElementUpdateQuery(tileElement, std::move(res)); } - auto tileElement = MapGetFootpathElementSlope(_loc, _slope); - if (tileElement == nullptr) + Result FootpathPlaceAction::Execute() const { - return ElementInsertExecute(std::move(res)); + auto res = Result(); + res.Cost = 0; + res.Expenditure = ExpenditureType::landscaping; + res.Position = _loc.ToTileCentre(); + + if (!(GetFlags() & GAME_COMMAND_FLAG_GHOST)) + { + FootpathInterruptPeeps(_loc); + } + + gFootpathGroundFlags = 0; + + // Force ride construction to recheck area + _currentTrackSelectionFlags.set(TrackSelectionFlag::recheck); + + if (!(GetFlags() & GAME_COMMAND_FLAG_GHOST)) + { + if (_direction != kInvalidDirection && !getGameState().cheats.disableClearanceChecks) + { + // It is possible, let's remove walls between the old and new piece of path + auto zLow = _loc.z; + auto zHigh = zLow + kPathClearance; + WallRemoveIntersectingWalls( + { _loc, zLow, zHigh + ((_slope & kTileSlopeRaisedCornersMask) ? 16 : 0) }, DirectionReverse(_direction)); + WallRemoveIntersectingWalls( + { _loc.x - CoordsDirectionDelta[_direction].x, _loc.y - CoordsDirectionDelta[_direction].y, zLow, zHigh }, + _direction); + } + } + + auto tileElement = MapGetFootpathElementSlope(_loc, _slope); + if (tileElement == nullptr) + { + return ElementInsertExecute(std::move(res)); + } + return ElementUpdateExecute(tileElement, std::move(res)); } - return ElementUpdateExecute(tileElement, std::move(res)); -} + + bool FootpathPlaceAction::IsSameAsPathElement(const PathElement* pathElement) const + { + // Check if both this action and the element is queue + if (pathElement->IsQueue() != ((_constructFlags & PathConstructFlag::IsQueue) != 0)) + return false; + + auto footpathObj = pathElement->GetLegacyPathEntry(); + if (footpathObj == nullptr) + { + if (_constructFlags & PathConstructFlag::IsLegacyPathObject) + { + return false; + } + + return pathElement->GetSurfaceEntryIndex() == _type && pathElement->GetRailingsEntryIndex() == _railingsType; + } + + if (_constructFlags & PathConstructFlag::IsLegacyPathObject) + { + return pathElement->GetLegacyPathEntryIndex() == _type; + } -bool FootpathPlaceAction::IsSameAsPathElement(const PathElement* pathElement) const -{ - // Check if both this action and the element is queue - if (pathElement->IsQueue() != ((_constructFlags & PathConstructFlag::IsQueue) != 0)) return false; + } - auto footpathObj = pathElement->GetLegacyPathEntry(); - if (footpathObj == nullptr) + bool FootpathPlaceAction::IsSameAsEntranceElement(const EntranceElement& entranceElement) const { + if (entranceElement.HasLegacyPathEntry()) + { + if (_constructFlags & PathConstructFlag::IsLegacyPathObject) + { + return entranceElement.GetLegacyPathEntryIndex() == _type; + } + + return false; + } + if (_constructFlags & PathConstructFlag::IsLegacyPathObject) { return false; } - return pathElement->GetSurfaceEntryIndex() == _type && pathElement->GetRailingsEntryIndex() == _railingsType; + return entranceElement.GetSurfaceEntryIndex() == _type; } - if (_constructFlags & PathConstructFlag::IsLegacyPathObject) + Result FootpathPlaceAction::ElementUpdateQuery(PathElement* pathElement, Result res) const { - return pathElement->GetLegacyPathEntryIndex() == _type; - } - - return false; -} - -bool FootpathPlaceAction::IsSameAsEntranceElement(const EntranceElement& entranceElement) const -{ - if (entranceElement.HasLegacyPathEntry()) - { - if (_constructFlags & PathConstructFlag::IsLegacyPathObject) + if (_constructFlags & PathConstructFlag::IsQueue && pathElement->IsLevelCrossing(_loc)) { - return entranceElement.GetLegacyPathEntryIndex() == _type; + return Result(Status::Disallowed, STR_CANT_BUILD_FOOTPATH_HERE, STR_QUEUE_PATHS_CANNOT_BE_USED_FOR_LEVEL_CROSSINGS); } - return false; - } - - if (_constructFlags & PathConstructFlag::IsLegacyPathObject) - { - return false; - } - - return entranceElement.GetSurfaceEntryIndex() == _type; -} - -GameActions::Result FootpathPlaceAction::ElementUpdateQuery(PathElement* pathElement, GameActions::Result res) const -{ - if (_constructFlags & PathConstructFlag::IsQueue && pathElement->IsLevelCrossing(_loc)) - { - return GameActions::Result( - GameActions::Status::Disallowed, STR_CANT_BUILD_FOOTPATH_HERE, STR_QUEUE_PATHS_CANNOT_BE_USED_FOR_LEVEL_CROSSINGS); - } - - if (!IsSameAsPathElement(pathElement)) - { - res.Cost += 6.00_GBP; - } - - if (GetFlags() & GAME_COMMAND_FLAG_GHOST && !pathElement->IsGhost()) - { - return GameActions::Result(GameActions::Status::Unknown, STR_CANT_BUILD_FOOTPATH_HERE, kStringIdNone); - } - return res; -} - -GameActions::Result FootpathPlaceAction::ElementUpdateExecute(PathElement* pathElement, GameActions::Result res) const -{ - if (!IsSameAsPathElement(pathElement)) - { - res.Cost += 6.00_GBP; - } - - FootpathQueueChainReset(); - - if (!(GetFlags() & GAME_COMMAND_FLAG_TRACK_DESIGN)) - { - FootpathRemoveEdgesAt(_loc, reinterpret_cast(pathElement)); - } - - if (_constructFlags & PathConstructFlag::IsLegacyPathObject) - { - pathElement->SetLegacyPathEntryIndex(_type); - } - else - { - pathElement->SetSurfaceEntryIndex(_type); - pathElement->SetRailingsEntryIndex(_railingsType); - } - - pathElement->SetIsQueue((_constructFlags & PathConstructFlag::IsQueue) != 0); - - auto* elem = pathElement->GetAdditionEntry(); - if (elem != nullptr) - { - if (_constructFlags & PathConstructFlag::IsQueue) + if (!IsSameAsPathElement(pathElement)) { - // remove any addition that isn't a TV or a lamp - if ((elem->flags & PATH_ADDITION_FLAG_IS_QUEUE_SCREEN) == 0 && (elem->flags & PATH_ADDITION_FLAG_LAMP) == 0) - { - pathElement->SetIsBroken(false); - pathElement->SetAddition(0); - } + res.Cost += 6.00_GBP; } - else + + if (GetFlags() & GAME_COMMAND_FLAG_GHOST && !pathElement->IsGhost()) { - // remove all TVs - if ((elem->flags & PATH_ADDITION_FLAG_IS_QUEUE_SCREEN) != 0) - { - pathElement->SetIsBroken(false); - pathElement->SetAddition(0); - } + return Result(Status::Unknown, STR_CANT_BUILD_FOOTPATH_HERE, kStringIdNone); } + return res; } - RemoveIntersectingWalls(pathElement); - return res; -} - -GameActions::Result FootpathPlaceAction::ElementInsertQuery(GameActions::Result res) const -{ - bool entrancePath = false, entranceIsSamePath = false; - - if (!MapCheckCapacityAndReorganise(_loc)) + Result FootpathPlaceAction::ElementUpdateExecute(PathElement* pathElement, Result res) const { - return GameActions::Result(GameActions::Status::NoFreeElements, STR_CANT_BUILD_FOOTPATH_HERE, kStringIdNone); - } - - res.Cost = 12.00_GBP; - - QuarterTile quarterTile{ 0b1111, 0 }; - auto zLow = _loc.z; - auto zHigh = zLow + kPathClearance; - if (_slope & FOOTPATH_PROPERTIES_FLAG_IS_SLOPED) - { - quarterTile = QuarterTile{ 0b1111, 0b1100 }.Rotate(_slope & kTileElementDirectionMask); - zHigh += kPathHeightStep; - } - - auto entranceElement = MapGetParkEntranceElementAt(_loc, false); - // Make sure the entrance part is the middle - if (entranceElement != nullptr && (entranceElement->GetSequenceIndex()) == 0) - { - entrancePath = true; - // Make the price the same as replacing a path - if (IsSameAsEntranceElement(*entranceElement)) - entranceIsSamePath = true; - else - res.Cost -= 6.00_GBP; - } - - // Do not attempt to build a crossing with a queue or a sloped path. - auto isQueue = _constructFlags & PathConstructFlag::IsQueue; - auto crossingMode = isQueue || (_slope != kTileSlopeFlat) ? CreateCrossingMode::none : CreateCrossingMode::pathOverTrack; - auto canBuild = MapCanConstructWithClearAt( - { _loc, zLow, zHigh }, &MapPlaceNonSceneryClearFunc, quarterTile, GetFlags(), crossingMode); - if (!entrancePath && canBuild.Error != GameActions::Status::Ok) - { - canBuild.ErrorTitle = STR_CANT_BUILD_FOOTPATH_HERE; - return canBuild; - } - res.Cost += canBuild.Cost; - - const auto clearanceData = canBuild.GetData(); - - gFootpathGroundFlags = clearanceData.GroundFlags; - if (!getGameState().cheats.disableClearanceChecks && (clearanceData.GroundFlags & ELEMENT_IS_UNDERWATER)) - { - return GameActions::Result( - GameActions::Status::Disallowed, STR_CANT_BUILD_FOOTPATH_HERE, STR_CANT_BUILD_THIS_UNDERWATER); - } - - auto surfaceElement = MapGetSurfaceElementAt(_loc); - if (surfaceElement == nullptr) - { - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_BUILD_FOOTPATH_HERE, STR_ERR_SURFACE_ELEMENT_NOT_FOUND); - } - int32_t supportHeight = zLow - surfaceElement->GetBaseZ(); - res.Cost += supportHeight < 0 ? 20.00_GBP : (supportHeight / kPathHeightStep) * 5.00_GBP; - - // Prevent the place sound from being spammed - if (entranceIsSamePath) - res.Cost = 0; - - return res; -} - -GameActions::Result FootpathPlaceAction::ElementInsertExecute(GameActions::Result res) const -{ - bool entrancePath = false, entranceIsSamePath = false; - - if (!(GetFlags() & (GAME_COMMAND_FLAG_ALLOW_DURING_PAUSED | GAME_COMMAND_FLAG_GHOST))) - { - FootpathRemoveLitter(_loc); - } - - res.Cost = 12.00_GBP; - - QuarterTile quarterTile{ 0b1111, 0 }; - auto zLow = _loc.z; - auto zHigh = zLow + kPathClearance; - if (_slope & FOOTPATH_PROPERTIES_FLAG_IS_SLOPED) - { - quarterTile = QuarterTile{ 0b1111, 0b1100 }.Rotate(_slope & kTileElementDirectionMask); - zHigh += kPathHeightStep; - } - - auto entranceElement = MapGetParkEntranceElementAt(_loc, false); - // Make sure the entrance part is the middle - if (entranceElement != nullptr && (entranceElement->GetSequenceIndex()) == 0) - { - entrancePath = true; - // Make the price the same as replacing a path - if (IsSameAsEntranceElement(*entranceElement)) - entranceIsSamePath = true; - else - res.Cost -= 6.00_GBP; - } - - // Do not attempt to build a crossing with a queue or a sloped. - auto isQueue = _constructFlags & PathConstructFlag::IsQueue; - auto crossingMode = isQueue || (_slope != kTileSlopeFlat) ? CreateCrossingMode::none : CreateCrossingMode::pathOverTrack; - auto canBuild = MapCanConstructWithClearAt( - { _loc, zLow, zHigh }, &MapPlaceNonSceneryClearFunc, quarterTile, GAME_COMMAND_FLAG_APPLY | GetFlags(), crossingMode); - if (!entrancePath && canBuild.Error != GameActions::Status::Ok) - { - canBuild.ErrorTitle = STR_CANT_BUILD_FOOTPATH_HERE; - return canBuild; - } - res.Cost += canBuild.Cost; - - const auto clearanceData = canBuild.GetData(); - gFootpathGroundFlags = clearanceData.GroundFlags; - - auto surfaceElement = MapGetSurfaceElementAt(_loc); - if (surfaceElement == nullptr) - { - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_BUILD_FOOTPATH_HERE, STR_ERR_SURFACE_ELEMENT_NOT_FOUND); - } - int32_t supportHeight = zLow - surfaceElement->GetBaseZ(); - res.Cost += supportHeight < 0 ? 20.00_GBP : (supportHeight / kPathHeightStep) * 5.00_GBP; - - if (entrancePath) - { - if (!(GetFlags() & GAME_COMMAND_FLAG_GHOST) && !entranceIsSamePath) + if (!IsSameAsPathElement(pathElement)) { - if (_constructFlags & PathConstructFlag::IsLegacyPathObject) - { - entranceElement->SetLegacyPathEntryIndex(_type); - } - else - { - entranceElement->SetSurfaceEntryIndex(_type); - } - MapInvalidateTileFull(_loc); + res.Cost += 6.00_GBP; + } + + FootpathQueueChainReset(); + + if (!(GetFlags() & GAME_COMMAND_FLAG_TRACK_DESIGN)) + { + FootpathRemoveEdgesAt(_loc, reinterpret_cast(pathElement)); } - } - else - { - auto* pathElement = TileElementInsert(_loc, 0b1111); - Guard::Assert(pathElement != nullptr); - pathElement->SetClearanceZ(zHigh); if (_constructFlags & PathConstructFlag::IsLegacyPathObject) { pathElement->SetLegacyPathEntryIndex(_type); @@ -437,110 +250,296 @@ GameActions::Result FootpathPlaceAction::ElementInsertExecute(GameActions::Resul pathElement->SetSurfaceEntryIndex(_type); pathElement->SetRailingsEntryIndex(_railingsType); } - pathElement->SetSlopeDirection(_slope & FOOTPATH_PROPERTIES_SLOPE_DIRECTION_MASK); - pathElement->SetSloped(_slope & FOOTPATH_PROPERTIES_FLAG_IS_SLOPED); - pathElement->SetIsQueue(isQueue); - pathElement->SetAddition(0); - pathElement->SetRideIndex(RideId::GetNull()); - pathElement->SetAdditionStatus(255); - pathElement->SetIsBroken(false); - pathElement->SetGhost(GetFlags() & GAME_COMMAND_FLAG_GHOST); - FootpathQueueChainReset(); + pathElement->SetIsQueue((_constructFlags & PathConstructFlag::IsQueue) != 0); - if (!(GetFlags() & GAME_COMMAND_FLAG_TRACK_DESIGN)) + auto* elem = pathElement->GetAdditionEntry(); + if (elem != nullptr) { - FootpathRemoveEdgesAt(_loc, pathElement->as()); - } - if (gLegacyScene == LegacyScene::scenarioEditor && !(GetFlags() & GAME_COMMAND_FLAG_GHOST)) - { - AutomaticallySetPeepSpawn(); + if (_constructFlags & PathConstructFlag::IsQueue) + { + // remove any addition that isn't a TV or a lamp + if ((elem->flags & PATH_ADDITION_FLAG_IS_QUEUE_SCREEN) == 0 && (elem->flags & PATH_ADDITION_FLAG_LAMP) == 0) + { + pathElement->SetIsBroken(false); + pathElement->SetAddition(0); + } + } + else + { + // remove all TVs + if ((elem->flags & PATH_ADDITION_FLAG_IS_QUEUE_SCREEN) != 0) + { + pathElement->SetIsBroken(false); + pathElement->SetAddition(0); + } + } } RemoveIntersectingWalls(pathElement); + return res; } - // Prevent the place sound from being spammed - if (entranceIsSamePath) - res.Cost = 0; - - return res; -} - -/** - * - * rct2: 0x006A65AD - */ -void FootpathPlaceAction::AutomaticallySetPeepSpawn() const -{ - auto mapSizeUnits = GetMapSizeUnits(); - uint8_t direction = 0; - if (_loc.x != kCoordsXYStep) + Result FootpathPlaceAction::ElementInsertQuery(Result res) const { - direction++; - if (_loc.y != mapSizeUnits.y - kCoordsXYStep) + bool entrancePath = false, entranceIsSamePath = false; + + if (!MapCheckCapacityAndReorganise(_loc)) { - direction++; - if (_loc.x != mapSizeUnits.x - kCoordsXYStep) + return Result(Status::NoFreeElements, STR_CANT_BUILD_FOOTPATH_HERE, kStringIdNone); + } + + res.Cost = 12.00_GBP; + + QuarterTile quarterTile{ 0b1111, 0 }; + auto zLow = _loc.z; + auto zHigh = zLow + kPathClearance; + if (_slope & FOOTPATH_PROPERTIES_FLAG_IS_SLOPED) + { + quarterTile = QuarterTile{ 0b1111, 0b1100 }.Rotate(_slope & kTileElementDirectionMask); + zHigh += kPathHeightStep; + } + + auto entranceElement = MapGetParkEntranceElementAt(_loc, false); + // Make sure the entrance part is the middle + if (entranceElement != nullptr && (entranceElement->GetSequenceIndex()) == 0) + { + entrancePath = true; + // Make the price the same as replacing a path + if (IsSameAsEntranceElement(*entranceElement)) + entranceIsSamePath = true; + else + res.Cost -= 6.00_GBP; + } + + // Do not attempt to build a crossing with a queue or a sloped path. + auto isQueue = _constructFlags & PathConstructFlag::IsQueue; + auto crossingMode = isQueue || (_slope != kTileSlopeFlat) ? CreateCrossingMode::none + : CreateCrossingMode::pathOverTrack; + auto canBuild = MapCanConstructWithClearAt( + { _loc, zLow, zHigh }, &MapPlaceNonSceneryClearFunc, quarterTile, GetFlags(), crossingMode); + if (!entrancePath && canBuild.Error != Status::Ok) + { + canBuild.ErrorTitle = STR_CANT_BUILD_FOOTPATH_HERE; + return canBuild; + } + res.Cost += canBuild.Cost; + + const auto clearanceData = canBuild.GetData(); + + gFootpathGroundFlags = clearanceData.GroundFlags; + if (!getGameState().cheats.disableClearanceChecks && (clearanceData.GroundFlags & ELEMENT_IS_UNDERWATER)) + { + return Result(Status::Disallowed, STR_CANT_BUILD_FOOTPATH_HERE, STR_CANT_BUILD_THIS_UNDERWATER); + } + + auto surfaceElement = MapGetSurfaceElementAt(_loc); + if (surfaceElement == nullptr) + { + return Result(Status::InvalidParameters, STR_CANT_BUILD_FOOTPATH_HERE, STR_ERR_SURFACE_ELEMENT_NOT_FOUND); + } + int32_t supportHeight = zLow - surfaceElement->GetBaseZ(); + res.Cost += supportHeight < 0 ? 20.00_GBP : (supportHeight / kPathHeightStep) * 5.00_GBP; + + // Prevent the place sound from being spammed + if (entranceIsSamePath) + res.Cost = 0; + + return res; + } + + Result FootpathPlaceAction::ElementInsertExecute(Result res) const + { + bool entrancePath = false, entranceIsSamePath = false; + + if (!(GetFlags() & (GAME_COMMAND_FLAG_ALLOW_DURING_PAUSED | GAME_COMMAND_FLAG_GHOST))) + { + FootpathRemoveLitter(_loc); + } + + res.Cost = 12.00_GBP; + + QuarterTile quarterTile{ 0b1111, 0 }; + auto zLow = _loc.z; + auto zHigh = zLow + kPathClearance; + if (_slope & FOOTPATH_PROPERTIES_FLAG_IS_SLOPED) + { + quarterTile = QuarterTile{ 0b1111, 0b1100 }.Rotate(_slope & kTileElementDirectionMask); + zHigh += kPathHeightStep; + } + + auto entranceElement = MapGetParkEntranceElementAt(_loc, false); + // Make sure the entrance part is the middle + if (entranceElement != nullptr && (entranceElement->GetSequenceIndex()) == 0) + { + entrancePath = true; + // Make the price the same as replacing a path + if (IsSameAsEntranceElement(*entranceElement)) + entranceIsSamePath = true; + else + res.Cost -= 6.00_GBP; + } + + // Do not attempt to build a crossing with a queue or a sloped. + auto isQueue = _constructFlags & PathConstructFlag::IsQueue; + auto crossingMode = isQueue || (_slope != kTileSlopeFlat) ? CreateCrossingMode::none + : CreateCrossingMode::pathOverTrack; + auto canBuild = MapCanConstructWithClearAt( + { _loc, zLow, zHigh }, &MapPlaceNonSceneryClearFunc, quarterTile, GAME_COMMAND_FLAG_APPLY | GetFlags(), + crossingMode); + if (!entrancePath && canBuild.Error != Status::Ok) + { + canBuild.ErrorTitle = STR_CANT_BUILD_FOOTPATH_HERE; + return canBuild; + } + res.Cost += canBuild.Cost; + + const auto clearanceData = canBuild.GetData(); + gFootpathGroundFlags = clearanceData.GroundFlags; + + auto surfaceElement = MapGetSurfaceElementAt(_loc); + if (surfaceElement == nullptr) + { + return Result(Status::InvalidParameters, STR_CANT_BUILD_FOOTPATH_HERE, STR_ERR_SURFACE_ELEMENT_NOT_FOUND); + } + int32_t supportHeight = zLow - surfaceElement->GetBaseZ(); + res.Cost += supportHeight < 0 ? 20.00_GBP : (supportHeight / kPathHeightStep) * 5.00_GBP; + + if (entrancePath) + { + if (!(GetFlags() & GAME_COMMAND_FLAG_GHOST) && !entranceIsSamePath) { - direction++; - if (_loc.y != kCoordsXYStep) - return; + if (_constructFlags & PathConstructFlag::IsLegacyPathObject) + { + entranceElement->SetLegacyPathEntryIndex(_type); + } + else + { + entranceElement->SetSurfaceEntryIndex(_type); + } + MapInvalidateTileFull(_loc); } } - } - - auto& gameState = getGameState(); - if (gameState.peepSpawns.empty()) - { - gameState.peepSpawns.emplace_back(); - } - PeepSpawn* peepSpawn = &gameState.peepSpawns[0]; - peepSpawn->x = _loc.x + (DirectionOffsets[direction].x * 15) + 16; - peepSpawn->y = _loc.y + (DirectionOffsets[direction].y * 15) + 16; - peepSpawn->direction = direction; - peepSpawn->z = _loc.z; -} - -void FootpathPlaceAction::RemoveIntersectingWalls(PathElement* pathElement) const -{ - if (pathElement->IsSloped() && !(GetFlags() & GAME_COMMAND_FLAG_GHOST)) - { - auto direction = pathElement->GetSlopeDirection(); - int32_t z = pathElement->GetBaseZ(); - WallRemoveIntersectingWalls({ _loc, z, z + (6 * kCoordsZStep) }, DirectionReverse(direction)); - WallRemoveIntersectingWalls({ _loc, z, z + (6 * kCoordsZStep) }, direction); - // Removing walls may have made the pointer invalid, so find it again - pathElement = MapGetFootpathElement(CoordsXYZ(_loc, z)); - if (pathElement == nullptr) + else { - LOG_ERROR("Something went wrong. Could not refind footpath."); - return; + auto* pathElement = TileElementInsert(_loc, 0b1111); + Guard::Assert(pathElement != nullptr); + + pathElement->SetClearanceZ(zHigh); + if (_constructFlags & PathConstructFlag::IsLegacyPathObject) + { + pathElement->SetLegacyPathEntryIndex(_type); + } + else + { + pathElement->SetSurfaceEntryIndex(_type); + pathElement->SetRailingsEntryIndex(_railingsType); + } + pathElement->SetSlopeDirection(_slope & FOOTPATH_PROPERTIES_SLOPE_DIRECTION_MASK); + pathElement->SetSloped(_slope & FOOTPATH_PROPERTIES_FLAG_IS_SLOPED); + pathElement->SetIsQueue(isQueue); + pathElement->SetAddition(0); + pathElement->SetRideIndex(RideId::GetNull()); + pathElement->SetAdditionStatus(255); + pathElement->SetIsBroken(false); + pathElement->SetGhost(GetFlags() & GAME_COMMAND_FLAG_GHOST); + + FootpathQueueChainReset(); + + if (!(GetFlags() & GAME_COMMAND_FLAG_TRACK_DESIGN)) + { + FootpathRemoveEdgesAt(_loc, pathElement->as()); + } + if (gLegacyScene == LegacyScene::scenarioEditor && !(GetFlags() & GAME_COMMAND_FLAG_GHOST)) + { + AutomaticallySetPeepSpawn(); + } + + RemoveIntersectingWalls(pathElement); } + + // Prevent the place sound from being spammed + if (entranceIsSamePath) + res.Cost = 0; + + return res; } - if (!(GetFlags() & GAME_COMMAND_FLAG_TRACK_DESIGN)) - FootpathConnectEdges(_loc, reinterpret_cast(pathElement), GetFlags()); - - FootpathUpdateQueueChains(); - MapInvalidateTileFull(_loc); -} - -PathElement* FootpathPlaceAction::MapGetFootpathElementSlope(const CoordsXYZ& footpathPos, int32_t slope) const -{ - const bool isSloped = slope & FOOTPATH_PROPERTIES_FLAG_IS_SLOPED; - const auto slopeDirection = slope & FOOTPATH_PROPERTIES_SLOPE_DIRECTION_MASK; - - for (auto* pathElement : TileElementsView(footpathPos)) + /** + * + * rct2: 0x006A65AD + */ + void FootpathPlaceAction::AutomaticallySetPeepSpawn() const { - if (pathElement->GetBaseZ() != footpathPos.z) - continue; - if (pathElement->IsSloped() != isSloped) - continue; - if (pathElement->GetSlopeDirection() != slopeDirection) - continue; - return pathElement; + auto mapSizeUnits = GetMapSizeUnits(); + uint8_t direction = 0; + if (_loc.x != kCoordsXYStep) + { + direction++; + if (_loc.y != mapSizeUnits.y - kCoordsXYStep) + { + direction++; + if (_loc.x != mapSizeUnits.x - kCoordsXYStep) + { + direction++; + if (_loc.y != kCoordsXYStep) + return; + } + } + } + + auto& gameState = getGameState(); + if (gameState.peepSpawns.empty()) + { + gameState.peepSpawns.emplace_back(); + } + PeepSpawn* peepSpawn = &gameState.peepSpawns[0]; + peepSpawn->x = _loc.x + (DirectionOffsets[direction].x * 15) + 16; + peepSpawn->y = _loc.y + (DirectionOffsets[direction].y * 15) + 16; + peepSpawn->direction = direction; + peepSpawn->z = _loc.z; } - return nullptr; -} + void FootpathPlaceAction::RemoveIntersectingWalls(PathElement* pathElement) const + { + if (pathElement->IsSloped() && !(GetFlags() & GAME_COMMAND_FLAG_GHOST)) + { + auto direction = pathElement->GetSlopeDirection(); + int32_t z = pathElement->GetBaseZ(); + WallRemoveIntersectingWalls({ _loc, z, z + (6 * kCoordsZStep) }, DirectionReverse(direction)); + WallRemoveIntersectingWalls({ _loc, z, z + (6 * kCoordsZStep) }, direction); + // Removing walls may have made the pointer invalid, so find it again + pathElement = MapGetFootpathElement(CoordsXYZ(_loc, z)); + if (pathElement == nullptr) + { + LOG_ERROR("Something went wrong. Could not refind footpath."); + return; + } + } + + if (!(GetFlags() & GAME_COMMAND_FLAG_TRACK_DESIGN)) + FootpathConnectEdges(_loc, reinterpret_cast(pathElement), GetFlags()); + + FootpathUpdateQueueChains(); + MapInvalidateTileFull(_loc); + } + + PathElement* FootpathPlaceAction::MapGetFootpathElementSlope(const CoordsXYZ& footpathPos, int32_t slope) const + { + const bool isSloped = slope & FOOTPATH_PROPERTIES_FLAG_IS_SLOPED; + const auto slopeDirection = slope & FOOTPATH_PROPERTIES_SLOPE_DIRECTION_MASK; + + for (auto* pathElement : TileElementsView(footpathPos)) + { + if (pathElement->GetBaseZ() != footpathPos.z) + continue; + if (pathElement->IsSloped() != isSloped) + continue; + if (pathElement->GetSlopeDirection() != slopeDirection) + continue; + return pathElement; + } + + return nullptr; + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/FootpathPlaceAction.h b/src/openrct2/actions/FootpathPlaceAction.h index dcd3fb2bd5..d4b6abe423 100644 --- a/src/openrct2/actions/FootpathPlaceAction.h +++ b/src/openrct2/actions/FootpathPlaceAction.h @@ -12,39 +12,40 @@ #include "../world/Footpath.h" #include "GameAction.h" -class FootpathPlaceAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - CoordsXYZ _loc; - uint8_t _slope{}; - OpenRCT2::ObjectEntryIndex _type{}; - OpenRCT2::ObjectEntryIndex _railingsType{}; - Direction _direction{ kInvalidDirection }; - PathConstructFlags _constructFlags{}; + class FootpathPlaceAction final : public GameActionBase + { + private: + CoordsXYZ _loc; + uint8_t _slope{}; + ObjectEntryIndex _type{}; + ObjectEntryIndex _railingsType{}; + Direction _direction{ kInvalidDirection }; + PathConstructFlags _constructFlags{}; -public: - FootpathPlaceAction() = default; - FootpathPlaceAction( - const CoordsXYZ& loc, uint8_t slope, OpenRCT2::ObjectEntryIndex type, OpenRCT2::ObjectEntryIndex railingsType, - Direction direction = kInvalidDirection, PathConstructFlags constructFlags = 0); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + public: + FootpathPlaceAction() = default; + FootpathPlaceAction( + const CoordsXYZ& loc, uint8_t slope, ObjectEntryIndex type, ObjectEntryIndex railingsType, + Direction direction = kInvalidDirection, PathConstructFlags constructFlags = 0); + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; -private: - OpenRCT2::GameActions::Result ElementUpdateQuery( - OpenRCT2::PathElement* pathElement, OpenRCT2::GameActions::Result res) const; - OpenRCT2::GameActions::Result ElementUpdateExecute( - OpenRCT2::PathElement* pathElement, OpenRCT2::GameActions::Result res) const; - OpenRCT2::GameActions::Result ElementInsertQuery(OpenRCT2::GameActions::Result res) const; - OpenRCT2::GameActions::Result ElementInsertExecute(OpenRCT2::GameActions::Result res) const; - void AutomaticallySetPeepSpawn() const; - void RemoveIntersectingWalls(OpenRCT2::PathElement* pathElement) const; - OpenRCT2::PathElement* MapGetFootpathElementSlope(const CoordsXYZ& footpathPos, int32_t slope) const; - bool IsSameAsPathElement(const OpenRCT2::PathElement* pathElement) const; - bool IsSameAsEntranceElement(const OpenRCT2::EntranceElement& entranceElement) const; -}; + private: + Result ElementUpdateQuery(PathElement* pathElement, Result res) const; + Result ElementUpdateExecute(PathElement* pathElement, Result res) const; + Result ElementInsertQuery(Result res) const; + Result ElementInsertExecute(Result res) const; + void AutomaticallySetPeepSpawn() const; + void RemoveIntersectingWalls(PathElement* pathElement) const; + PathElement* MapGetFootpathElementSlope(const CoordsXYZ& footpathPos, int32_t slope) const; + bool IsSameAsPathElement(const PathElement* pathElement) const; + bool IsSameAsEntranceElement(const EntranceElement& entranceElement) const; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/FootpathRemoveAction.cpp b/src/openrct2/actions/FootpathRemoveAction.cpp index b8f633833c..7e644f6777 100644 --- a/src/openrct2/actions/FootpathRemoveAction.cpp +++ b/src/openrct2/actions/FootpathRemoveAction.cpp @@ -22,172 +22,171 @@ #include "../world/tile_element/PathElement.h" #include "BannerRemoveAction.h" -using namespace OpenRCT2; - -FootpathRemoveAction::FootpathRemoveAction(const CoordsXYZ& location) - : _loc(location) +namespace OpenRCT2::GameActions { -} - -void FootpathRemoveAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit(_loc); -} - -uint16_t FootpathRemoveAction::GetActionFlags() const -{ - return GameAction::GetActionFlags(); -} - -void FootpathRemoveAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_loc); -} - -GameActions::Result FootpathRemoveAction::Query() const -{ - auto res = GameActions::Result(); - res.Cost = 0; - res.Expenditure = ExpenditureType::landscaping; - res.Position = { _loc.x + 16, _loc.y + 16, _loc.z }; - - if (!LocationValid(_loc)) + FootpathRemoveAction::FootpathRemoveAction(const CoordsXYZ& location) + : _loc(location) { - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_REMOVE_FOOTPATH_FROM_HERE, STR_OFF_EDGE_OF_MAP); } - if (!(gLegacyScene == LegacyScene::scenarioEditor || getGameState().cheats.sandboxMode) && !MapIsLocationOwned(_loc)) + void FootpathRemoveAction::AcceptParameters(GameActionParameterVisitor& visitor) { - return GameActions::Result( - GameActions::Status::NotOwned, STR_CANT_REMOVE_FOOTPATH_FROM_HERE, STR_LAND_NOT_OWNED_BY_PARK); + visitor.Visit(_loc); } - TileElement* footpathElement = GetFootpathElement(); - if (footpathElement == nullptr) + uint16_t FootpathRemoveAction::GetActionFlags() const { - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_REMOVE_FOOTPATH_FROM_HERE, STR_ERR_PATH_ELEMENT_NOT_FOUND); + return GameAction::GetActionFlags(); } - res.Cost = GetRefundPrice(footpathElement); - - return res; -} - -GameActions::Result FootpathRemoveAction::Execute() const -{ - auto res = GameActions::Result(); - res.Cost = 0; - res.Expenditure = ExpenditureType::landscaping; - res.Position = { _loc.x + 16, _loc.y + 16, _loc.z }; - - if (!(GetFlags() & GAME_COMMAND_FLAG_GHOST)) + void FootpathRemoveAction::Serialise(DataSerialiser& stream) { - FootpathInterruptPeeps(_loc); - FootpathRemoveLitter(_loc); + GameAction::Serialise(stream); + + stream << DS_TAG(_loc); } - TileElement* footpathElement = GetFootpathElement(); - if (footpathElement != nullptr) + Result FootpathRemoveAction::Query() const { - FootpathQueueChainReset(); - auto bannerRes = RemoveBannersAtElement(_loc, footpathElement); - if (bannerRes.Error == GameActions::Status::Ok) + auto res = Result(); + res.Cost = 0; + res.Expenditure = ExpenditureType::landscaping; + res.Position = { _loc.x + 16, _loc.y + 16, _loc.z }; + + if (!LocationValid(_loc)) { - res.Cost += bannerRes.Cost; + return Result(Status::InvalidParameters, STR_CANT_REMOVE_FOOTPATH_FROM_HERE, STR_OFF_EDGE_OF_MAP); } - FootpathRemoveEdgesAt(_loc, footpathElement); - MapInvalidateTileFull(_loc); - TileElementRemove(footpathElement); - FootpathUpdateQueueChains(); - auto& gameState = getGameState(); - // Remove the spawn point (if there is one in the current tile) - gameState.peepSpawns.erase( - std::remove_if( - gameState.peepSpawns.begin(), gameState.peepSpawns.end(), - [this](const CoordsXYZ& spawn) { - { - return spawn.ToTileStart() == _loc.ToTileStart(); - } - }), - gameState.peepSpawns.end()); - } - else - { - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_REMOVE_FOOTPATH_FROM_HERE, kStringIdNone); - } - - res.Cost += GetRefundPrice(footpathElement); - - return res; -} - -TileElement* FootpathRemoveAction::GetFootpathElement() const -{ - bool getGhostPath = GetFlags() & GAME_COMMAND_FLAG_GHOST; - - // FIXME: This is a hack to get the footpath element. It should be done in a better way. - TileElement* tileElement = MapGetFootpathElement(_loc)->as(); - TileElement* footpathElement = nullptr; - if (tileElement != nullptr) - { - if (getGhostPath && !tileElement->IsGhost()) + if (!(gLegacyScene == LegacyScene::scenarioEditor || getGameState().cheats.sandboxMode) && !MapIsLocationOwned(_loc)) { - while (!(tileElement++)->IsLastForTile()) + return Result(Status::NotOwned, STR_CANT_REMOVE_FOOTPATH_FROM_HERE, STR_LAND_NOT_OWNED_BY_PARK); + } + + TileElement* footpathElement = GetFootpathElement(); + if (footpathElement == nullptr) + { + return Result(Status::InvalidParameters, STR_CANT_REMOVE_FOOTPATH_FROM_HERE, STR_ERR_PATH_ELEMENT_NOT_FOUND); + } + + res.Cost = GetRefundPrice(footpathElement); + + return res; + } + + Result FootpathRemoveAction::Execute() const + { + auto res = Result(); + res.Cost = 0; + res.Expenditure = ExpenditureType::landscaping; + res.Position = { _loc.x + 16, _loc.y + 16, _loc.z }; + + if (!(GetFlags() & GAME_COMMAND_FLAG_GHOST)) + { + FootpathInterruptPeeps(_loc); + FootpathRemoveLitter(_loc); + } + + TileElement* footpathElement = GetFootpathElement(); + if (footpathElement != nullptr) + { + FootpathQueueChainReset(); + auto bannerRes = RemoveBannersAtElement(_loc, footpathElement); + if (bannerRes.Error == Status::Ok) { - if (tileElement->GetType() != TileElementType::Path && !tileElement->IsGhost()) - { - continue; - } - footpathElement = tileElement; - break; + res.Cost += bannerRes.Cost; } + FootpathRemoveEdgesAt(_loc, footpathElement); + MapInvalidateTileFull(_loc); + TileElementRemove(footpathElement); + FootpathUpdateQueueChains(); + + auto& gameState = getGameState(); + // Remove the spawn point (if there is one in the current tile) + gameState.peepSpawns.erase( + std::remove_if( + gameState.peepSpawns.begin(), gameState.peepSpawns.end(), + [this](const CoordsXYZ& spawn) { + { + return spawn.ToTileStart() == _loc.ToTileStart(); + } + }), + gameState.peepSpawns.end()); } else { - footpathElement = tileElement; + return Result(Status::InvalidParameters, STR_CANT_REMOVE_FOOTPATH_FROM_HERE, kStringIdNone); } + + res.Cost += GetRefundPrice(footpathElement); + + return res; } - return footpathElement; -} - -money64 FootpathRemoveAction::GetRefundPrice(TileElement* footpathElement) const -{ - money64 cost = -10.00_GBP; - return cost; -} - -/** - * - * rct2: 0x006BA23E - */ -GameActions::Result FootpathRemoveAction::RemoveBannersAtElement(const CoordsXY& loc, TileElement* tileElement) const -{ - auto result = GameActions::Result(); - while (!(tileElement++)->IsLastForTile()) + TileElement* FootpathRemoveAction::GetFootpathElement() const { - if (tileElement->GetType() == TileElementType::Path) - return result; + bool getGhostPath = GetFlags() & GAME_COMMAND_FLAG_GHOST; - if (tileElement->GetType() != TileElementType::Banner) - continue; - - auto bannerRemoveAction = BannerRemoveAction({ loc, tileElement->GetBaseZ(), tileElement->AsBanner()->GetPosition() }); - bool isGhost = tileElement->IsGhost(); - auto bannerFlags = GetFlags() | (isGhost ? static_cast(GAME_COMMAND_FLAG_GHOST) : 0); - bannerRemoveAction.SetFlags(bannerFlags); - auto res = GameActions::ExecuteNested(&bannerRemoveAction); - // Ghost removal is free - if (res.Error == GameActions::Status::Ok && !isGhost) + // FIXME: This is a hack to get the footpath element. It should be done in a better way. + TileElement* tileElement = MapGetFootpathElement(_loc)->as(); + TileElement* footpathElement = nullptr; + if (tileElement != nullptr) { - result.Cost += res.Cost; + if (getGhostPath && !tileElement->IsGhost()) + { + while (!(tileElement++)->IsLastForTile()) + { + if (tileElement->GetType() != TileElementType::Path && !tileElement->IsGhost()) + { + continue; + } + footpathElement = tileElement; + break; + } + } + else + { + footpathElement = tileElement; + } } - tileElement--; + + return footpathElement; } - return result; -} + + money64 FootpathRemoveAction::GetRefundPrice(TileElement* footpathElement) const + { + money64 cost = -10.00_GBP; + return cost; + } + + /** + * + * rct2: 0x006BA23E + */ + Result FootpathRemoveAction::RemoveBannersAtElement(const CoordsXY& loc, TileElement* tileElement) const + { + auto result = Result(); + while (!(tileElement++)->IsLastForTile()) + { + if (tileElement->GetType() == TileElementType::Path) + return result; + + if (tileElement->GetType() != TileElementType::Banner) + continue; + + auto bannerRemoveAction = BannerRemoveAction( + { loc, tileElement->GetBaseZ(), tileElement->AsBanner()->GetPosition() }); + bool isGhost = tileElement->IsGhost(); + auto bannerFlags = GetFlags() | (isGhost ? static_cast(GAME_COMMAND_FLAG_GHOST) : 0); + bannerRemoveAction.SetFlags(bannerFlags); + auto res = ExecuteNested(&bannerRemoveAction); + // Ghost removal is free + if (res.Error == Status::Ok && !isGhost) + { + result.Cost += res.Cost; + } + tileElement--; + } + return result; + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/FootpathRemoveAction.h b/src/openrct2/actions/FootpathRemoveAction.h index ab2c83f00e..2398de32dc 100644 --- a/src/openrct2/actions/FootpathRemoveAction.h +++ b/src/openrct2/actions/FootpathRemoveAction.h @@ -12,25 +12,28 @@ #include "../management/Finance.h" #include "GameAction.h" -class FootpathRemoveAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - CoordsXYZ _loc; + class FootpathRemoveAction final : public GameActionBase + { + private: + CoordsXYZ _loc; -public: - FootpathRemoveAction() = default; - FootpathRemoveAction(const CoordsXYZ& location); + public: + FootpathRemoveAction() = default; + FootpathRemoveAction(const CoordsXYZ& location); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; -private: - OpenRCT2::TileElement* GetFootpathElement() const; - money64 GetRefundPrice(OpenRCT2::TileElement* footpathElement) const; - OpenRCT2::GameActions::Result RemoveBannersAtElement(const CoordsXY& loc, OpenRCT2::TileElement* tileElement) const; -}; + private: + TileElement* GetFootpathElement() const; + money64 GetRefundPrice(TileElement* footpathElement) const; + Result RemoveBannersAtElement(const CoordsXY& loc, TileElement* tileElement) const; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/GameAction.cpp b/src/openrct2/actions/GameAction.cpp index 6ac0b5355d..361b2ebb97 100644 --- a/src/openrct2/actions/GameAction.cpp +++ b/src/openrct2/actions/GameAction.cpp @@ -31,8 +31,6 @@ #include -using namespace OpenRCT2; - namespace OpenRCT2::GameActions { struct QueuedGameAction @@ -143,8 +141,8 @@ namespace OpenRCT2::GameActions Guard::Assert(action != nullptr); - GameActions::Result result = Execute(action); - if (result.Error == GameActions::Status::Ok && NetworkGetMode() == NETWORK_MODE_SERVER) + Result result = Execute(action); + if (result.Error == Status::Ok && NetworkGetMode() == NETWORK_MODE_SERVER) { // Relay this action to all other clients. NetworkSendGameAction(action); @@ -161,7 +159,7 @@ namespace OpenRCT2::GameActions GameAction::Ptr Clone(const GameAction* action) { - std::unique_ptr ga = GameActions::Create(action->GetType()); + std::unique_ptr ga = Create(action->GetType()); ga->SetCallback(action->GetCallback()); // Serialise action data into stream. @@ -184,21 +182,21 @@ namespace OpenRCT2::GameActions return true; if (getGameState().cheats.buildInPauseMode) return true; - if (actionFlags & GameActions::Flags::AllowWhilePaused) + if (actionFlags & Flags::AllowWhilePaused) return true; return false; } - static GameActions::Result QueryInternal(const GameAction* action, bool topLevel) + static Result QueryInternal(const GameAction* action, bool topLevel) { Guard::ArgumentNotNull(action); uint16_t actionFlags = action->GetActionFlags(); if (topLevel && !CheckActionInPausedMode(actionFlags)) { - GameActions::Result result = GameActions::Result(); + Result result = Result(); - result.Error = GameActions::Status::GamePaused; + result.Error = Status::GamePaused; result.ErrorTitle = STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE; result.ErrorMessage = STR_CONSTRUCTION_NOT_POSSIBLE_WHILE_GAME_IS_PAUSED; @@ -207,11 +205,11 @@ namespace OpenRCT2::GameActions auto result = action->Query(); - if (result.Error == GameActions::Status::Ok) + if (result.Error == Status::Ok) { if (!FinanceCheckAffordability(result.Cost, action->GetFlags())) { - result.Error = GameActions::Status::InsufficientFunds; + result.Error = Status::InsufficientFunds; result.ErrorTitle = STR_CANT_DO_THIS; result.ErrorMessage = STR_NOT_ENOUGH_CASH_REQUIRES; Formatter(result.ErrorMessageArgs.data()).Add(result.Cost); @@ -220,12 +218,12 @@ namespace OpenRCT2::GameActions return result; } - GameActions::Result Query(const GameAction* action) + Result Query(const GameAction* action) { return QueryInternal(action, true); } - GameActions::Result QueryNested(const GameAction* action) + Result QueryNested(const GameAction* action) { return QueryInternal(action, false); } @@ -261,13 +259,13 @@ namespace OpenRCT2::GameActions action->Serialise(ds); } - static void LogActionFinish(ActionLogContext& ctx, const GameAction* action, const GameActions::Result& result) + static void LogActionFinish(ActionLogContext& ctx, const GameAction* action, const Result& result) { MemoryStream& output = ctx.output; char temp[128] = {}; - if (result.Error != GameActions::Status::Ok) + if (result.Error != Status::Ok) { snprintf(temp, sizeof(temp), ") Failed, %u", static_cast(result.Error)); } @@ -284,7 +282,7 @@ namespace OpenRCT2::GameActions NetworkAppendServerLog(text); } - static GameActions::Result ExecuteInternal(const GameAction* action, bool topLevel) + static Result ExecuteInternal(const GameAction* action, bool topLevel) { Guard::ArgumentNotNull(action); @@ -292,7 +290,7 @@ namespace OpenRCT2::GameActions uint32_t flags = action->GetFlags(); // Some actions are not recorded in the replay. - const auto ignoreForReplays = (actionFlags & GameActions::Flags::IgnoreForReplays) != 0; + const auto ignoreForReplays = (actionFlags & Flags::IgnoreForReplays) != 0; auto* replayManager = OpenRCT2::GetContext()->GetReplayManager(); if (replayManager != nullptr && (replayManager->IsReplaying() || replayManager->IsNormalising())) @@ -301,8 +299,8 @@ namespace OpenRCT2::GameActions if ((flags & GAME_COMMAND_FLAG_REPLAY) == 0 && !ignoreForReplays) { // TODO: Introduce proper error. - auto result = GameActions::Result(); - result.Error = GameActions::Status::GamePaused; + auto result = Result(); + result.Error = Status::GamePaused; result.ErrorTitle = STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE; result.ErrorMessage = STR_CONSTRUCTION_NOT_POSSIBLE_WHILE_GAME_IS_PAUSED; @@ -310,17 +308,16 @@ namespace OpenRCT2::GameActions } } - GameActions::Result result = QueryInternal(action, topLevel); + Result result = QueryInternal(action, topLevel); #ifdef ENABLE_SCRIPTING - if (result.Error == GameActions::Status::Ok - && ((NetworkGetMode() == NETWORK_MODE_NONE) || (flags & GAME_COMMAND_FLAG_NETWORKED))) + if (result.Error == Status::Ok && ((NetworkGetMode() == NETWORK_MODE_NONE) || (flags & GAME_COMMAND_FLAG_NETWORKED))) { auto& scriptEngine = GetContext()->GetScriptEngine(); scriptEngine.RunGameActionHooks(*action, result, false); // Script hooks may now have changed the game action result... } #endif - if (result.Error == GameActions::Status::Ok) + if (result.Error == Status::Ok) { if (topLevel) { @@ -328,7 +325,7 @@ namespace OpenRCT2::GameActions if (NetworkGetMode() == NETWORK_MODE_CLIENT) { // As a client we have to wait or send it first. - if (!(actionFlags & GameActions::Flags::ClientOnly) && !(flags & GAME_COMMAND_FLAG_NETWORKED)) + if (!(actionFlags & Flags::ClientOnly) && !(flags & GAME_COMMAND_FLAG_NETWORKED)) { LOG_VERBOSE("[%s] GameAction::Execute %s (Out)", GetRealm(), action->GetName()); NetworkSendGameAction(action); @@ -341,7 +338,7 @@ namespace OpenRCT2::GameActions // If player is the server it would execute right away as where clients execute the commands // at the beginning of the frame, so we have to put them into the queue. // This is also the case when its executed from the UI update. - if (!(actionFlags & GameActions::Flags::ClientOnly) && !(flags & GAME_COMMAND_FLAG_NETWORKED)) + if (!(actionFlags & Flags::ClientOnly) && !(flags & GAME_COMMAND_FLAG_NETWORKED)) { LOG_VERBOSE("[%s] GameAction::Execute %s (Queue)", GetRealm(), action->GetName()); Enqueue(action, getGameState().currentTicks); @@ -357,7 +354,7 @@ namespace OpenRCT2::GameActions // Execute the action, changing the game state result = action->Execute(); #ifdef ENABLE_SCRIPTING - if (result.Error == GameActions::Status::Ok) + if (result.Error == Status::Ok) { auto& scriptEngine = GetContext()->GetScriptEngine(); scriptEngine.RunGameActionHooks(*action, result, true); @@ -372,13 +369,13 @@ namespace OpenRCT2::GameActions return result; // Update money balance - if (result.Error == GameActions::Status::Ok && FinanceCheckMoneyRequired(flags) && result.Cost != 0) + if (result.Error == Status::Ok && FinanceCheckMoneyRequired(flags) && result.Cost != 0) { FinancePayment(result.Cost, result.Expenditure); MoneyEffect::Create(result.Cost, result.Position); } - if (!(actionFlags & GameActions::Flags::ClientOnly) && result.Error == GameActions::Status::Ok) + if (!(actionFlags & Flags::ClientOnly) && result.Error == Status::Ok) { if (NetworkGetMode() != NETWORK_MODE_NONE) { @@ -448,7 +445,7 @@ namespace OpenRCT2::GameActions } } - if (result.Error != GameActions::Status::Ok && shouldShowError) + if (result.Error != Status::Ok && shouldShowError) { auto windowManager = Ui::GetWindowManager(); windowManager->ShowError(result.GetErrorTitle(), result.GetErrorMessage()); @@ -457,12 +454,12 @@ namespace OpenRCT2::GameActions return result; } - GameActions::Result Execute(const GameAction* action) + Result Execute(const GameAction* action) { return ExecuteInternal(action, true); } - GameActions::Result ExecuteNested(const GameAction* action) + Result ExecuteNested(const GameAction* action) { return ExecuteInternal(action, false); } @@ -470,7 +467,7 @@ namespace OpenRCT2::GameActions const char* GameAction::GetName() const { - return GameActions::GetName(_type); + return OpenRCT2::GameActions::GetName(_type); } bool GameAction::LocationValid(const CoordsXY& coords) const @@ -479,10 +476,10 @@ bool GameAction::LocationValid(const CoordsXY& coords) const if (!result) return false; #ifdef ENABLE_SCRIPTING - auto& hookEngine = GetContext()->GetScriptEngine().GetHookEngine(); + auto& hookEngine = OpenRCT2::GetContext()->GetScriptEngine().GetHookEngine(); if (hookEngine.HasSubscriptions(OpenRCT2::Scripting::HookType::actionLocation)) { - auto ctx = GetContext()->GetScriptEngine().GetContext(); + auto ctx = OpenRCT2::GetContext()->GetScriptEngine().GetContext(); // Create event args object auto obj = OpenRCT2::Scripting::DukObject(ctx); @@ -492,7 +489,7 @@ bool GameAction::LocationValid(const CoordsXY& coords) const obj.Set("type", EnumValue(_type)); auto flags = GetActionFlags(); - obj.Set("isClientOnly", (flags & GameActions::Flags::ClientOnly) != 0); + obj.Set("isClientOnly", (flags & OpenRCT2::GameActions::Flags::ClientOnly) != 0); obj.Set("result", true); // Call the subscriptions diff --git a/src/openrct2/actions/GameAction.h b/src/openrct2/actions/GameAction.h index 124972bef4..0e200d3143 100644 --- a/src/openrct2/actions/GameAction.h +++ b/src/openrct2/actions/GameAction.h @@ -288,11 +288,11 @@ namespace OpenRCT2::GameActions GameAction::Ptr Clone(const GameAction* action); // This should be used if a round trip is to be expected. - OpenRCT2::GameActions::Result Query(const GameAction* action); - OpenRCT2::GameActions::Result Execute(const GameAction* action); + Result Query(const GameAction* action); + Result Execute(const GameAction* action); // This should be used from within game actions. - OpenRCT2::GameActions::Result QueryNested(const GameAction* action); - OpenRCT2::GameActions::Result ExecuteNested(const GameAction* action); + Result QueryNested(const GameAction* action); + Result ExecuteNested(const GameAction* action); } // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/GameActionRegistry.cpp b/src/openrct2/actions/GameActionRegistry.cpp index 8a566732df..de3bb35168 100644 --- a/src/openrct2/actions/GameActionRegistry.cpp +++ b/src/openrct2/actions/GameActionRegistry.cpp @@ -94,8 +94,6 @@ #include -using namespace OpenRCT2; - namespace OpenRCT2::GameActions { struct GameActionEntry diff --git a/src/openrct2/actions/GameActionResult.cpp b/src/openrct2/actions/GameActionResult.cpp index cf1b4cb3af..bb53ea1010 100644 --- a/src/openrct2/actions/GameActionResult.cpp +++ b/src/openrct2/actions/GameActionResult.cpp @@ -8,7 +8,7 @@ using namespace OpenRCT2; namespace OpenRCT2::GameActions { - Result::Result(GameActions::Status error, StringId title, StringId message, uint8_t* args /*= nullptr*/) + Result::Result(Status error, StringId title, StringId message, uint8_t* args /*= nullptr*/) : Error(error) , ErrorTitle(title) , ErrorMessage(message) @@ -33,12 +33,12 @@ namespace OpenRCT2::GameActions } }; - std::string GameActions::Result::GetErrorTitle() const + std::string Result::GetErrorTitle() const { return std::visit(StringVariantVisitor{ ErrorMessageArgs.data() }, ErrorTitle); } - std::string GameActions::Result::GetErrorMessage() const + std::string Result::GetErrorMessage() const { return std::visit(StringVariantVisitor{ ErrorMessageArgs.data() }, ErrorMessage); } diff --git a/src/openrct2/actions/GameActionResult.h b/src/openrct2/actions/GameActionResult.h index 3fbabc2c16..f40d2b311f 100644 --- a/src/openrct2/actions/GameActionResult.h +++ b/src/openrct2/actions/GameActionResult.h @@ -6,6 +6,7 @@ * * OpenRCT2 is licensed under the GNU General Public License version 3. *****************************************************************************/ + #pragma once #include "../management/Finance.h" @@ -56,7 +57,7 @@ namespace OpenRCT2::GameActions public: using StringVariant = std::variant; - OpenRCT2::GameActions::Status Error = OpenRCT2::GameActions::Status::Ok; + Status Error = Status::Ok; StringVariant ErrorTitle = kStringIdNone; StringVariant ErrorMessage = kStringIdNone; std::array ErrorMessageArgs{}; @@ -74,7 +75,7 @@ namespace OpenRCT2::GameActions #endif Result() = default; - Result(OpenRCT2::GameActions::Status error, StringId title, StringId message, uint8_t* args = nullptr); + Result(Status error, StringId title, StringId message, uint8_t* args = nullptr); std::string GetErrorTitle() const; std::string GetErrorMessage() const; diff --git a/src/openrct2/actions/GameSetSpeedAction.cpp b/src/openrct2/actions/GameSetSpeedAction.cpp index aaa7cf81bd..af791f6bc6 100644 --- a/src/openrct2/actions/GameSetSpeedAction.cpp +++ b/src/openrct2/actions/GameSetSpeedAction.cpp @@ -13,64 +13,63 @@ #include "../config/Config.h" #include "../ui/WindowManager.h" -using namespace OpenRCT2; - -GameSetSpeedAction::GameSetSpeedAction(uint8_t speed) - : _speed(speed) +namespace OpenRCT2::GameActions { -} - -void GameSetSpeedAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit("speed", _speed); -} - -uint16_t GameSetSpeedAction::GetActionFlags() const -{ - return GameAction::GetActionFlags() | GameActions::Flags::AllowWhilePaused | GameActions::Flags::IgnoreForReplays; -} - -void GameSetSpeedAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_speed); -} - -GameActions::Result GameSetSpeedAction::Query() const -{ - GameActions::Result res = GameActions::Result(); - - if (!IsValidSpeed(_speed)) + GameSetSpeedAction::GameSetSpeedAction(uint8_t speed) + : _speed(speed) { - LOG_ERROR("Invalid speed %u", _speed); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_VALUE_OUT_OF_RANGE); } - return res; -} - -GameActions::Result GameSetSpeedAction::Execute() const -{ - GameActions::Result res = GameActions::Result(); - - if (!IsValidSpeed(_speed)) + void GameSetSpeedAction::AcceptParameters(GameActionParameterVisitor& visitor) { - LOG_ERROR("Invalid speed %u", _speed); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_VALUE_OUT_OF_RANGE); + visitor.Visit("speed", _speed); } - gGameSpeed = _speed; + uint16_t GameSetSpeedAction::GetActionFlags() const + { + return GameAction::GetActionFlags() | Flags::AllowWhilePaused | Flags::IgnoreForReplays; + } - auto* windowMgr = Ui::GetWindowManager(); - windowMgr->InvalidateByClass(WindowClass::TopToolbar); + void GameSetSpeedAction::Serialise(DataSerialiser& stream) + { + GameAction::Serialise(stream); - return res; -} + stream << DS_TAG(_speed); + } -bool GameSetSpeedAction::IsValidSpeed(uint8_t speed) const -{ - return speed >= 1 && (speed <= 4 || (Config::Get().general.DebuggingTools && speed <= 8)); -} + Result GameSetSpeedAction::Query() const + { + Result res = Result(); + + if (!IsValidSpeed(_speed)) + { + LOG_ERROR("Invalid speed %u", _speed); + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_VALUE_OUT_OF_RANGE); + } + + return res; + } + + Result GameSetSpeedAction::Execute() const + { + Result res = Result(); + + if (!IsValidSpeed(_speed)) + { + LOG_ERROR("Invalid speed %u", _speed); + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_VALUE_OUT_OF_RANGE); + } + + gGameSpeed = _speed; + + auto* windowMgr = Ui::GetWindowManager(); + windowMgr->InvalidateByClass(WindowClass::TopToolbar); + + return res; + } + + bool GameSetSpeedAction::IsValidSpeed(uint8_t speed) const + { + return speed >= 1 && (speed <= 4 || (Config::Get().general.DebuggingTools && speed <= 8)); + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/GameSetSpeedAction.h b/src/openrct2/actions/GameSetSpeedAction.h index 25e5d1fd98..89c84b0db2 100644 --- a/src/openrct2/actions/GameSetSpeedAction.h +++ b/src/openrct2/actions/GameSetSpeedAction.h @@ -11,23 +11,26 @@ #include "GameAction.h" -class GameSetSpeedAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - uint8_t _speed{ 1 }; + class GameSetSpeedAction final : public GameActionBase + { + private: + uint8_t _speed{ 1 }; -public: - GameSetSpeedAction() = default; - GameSetSpeedAction(uint8_t speed); + public: + GameSetSpeedAction() = default; + GameSetSpeedAction(uint8_t speed); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; -private: - bool IsValidSpeed(uint8_t speed) const; -}; + private: + bool IsValidSpeed(uint8_t speed) const; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/GuestSetFlagsAction.cpp b/src/openrct2/actions/GuestSetFlagsAction.cpp index 6333df89f4..1a9069bafc 100644 --- a/src/openrct2/actions/GuestSetFlagsAction.cpp +++ b/src/openrct2/actions/GuestSetFlagsAction.cpp @@ -14,53 +14,54 @@ #include "../OpenRCT2.h" #include "../entity/EntityRegistry.h" -using namespace OpenRCT2; - -GuestSetFlagsAction::GuestSetFlagsAction(EntityId peepId, uint32_t flags) - : _peepId(peepId) - , _newFlags(flags) +namespace OpenRCT2::GameActions { -} - -void GuestSetFlagsAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit("peep", _peepId); - visitor.Visit("guestFlags", _newFlags); -} - -uint16_t GuestSetFlagsAction::GetActionFlags() const -{ - return GameAction::GetActionFlags() | GameActions::Flags::AllowWhilePaused; -} - -void GuestSetFlagsAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_peepId) << DS_TAG(_newFlags); -} - -GameActions::Result GuestSetFlagsAction::Query() const -{ - auto* peep = TryGetEntity(_peepId); - if (peep == nullptr) + GuestSetFlagsAction::GuestSetFlagsAction(EntityId peepId, uint32_t flags) + : _peepId(peepId) + , _newFlags(flags) { - LOG_ERROR("Guest entity not found for peepID %u", _peepId.ToUnderlying()); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_CHANGE_THIS, kStringIdNone); - } - return GameActions::Result(); -} - -GameActions::Result GuestSetFlagsAction::Execute() const -{ - auto* peep = TryGetEntity(_peepId); - if (peep == nullptr) - { - LOG_ERROR("Guest entity not found for peepID %u", _peepId.ToUnderlying()); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_CHANGE_THIS, kStringIdNone); } - peep->PeepFlags = _newFlags; + void GuestSetFlagsAction::AcceptParameters(GameActionParameterVisitor& visitor) + { + visitor.Visit("peep", _peepId); + visitor.Visit("guestFlags", _newFlags); + } - return GameActions::Result(); -} + uint16_t GuestSetFlagsAction::GetActionFlags() const + { + return GameAction::GetActionFlags() | Flags::AllowWhilePaused; + } + + void GuestSetFlagsAction::Serialise(DataSerialiser& stream) + { + GameAction::Serialise(stream); + + stream << DS_TAG(_peepId) << DS_TAG(_newFlags); + } + + Result GuestSetFlagsAction::Query() const + { + auto* peep = TryGetEntity(_peepId); + if (peep == nullptr) + { + LOG_ERROR("Guest entity not found for peepID %u", _peepId.ToUnderlying()); + return Result(Status::InvalidParameters, STR_CANT_CHANGE_THIS, kStringIdNone); + } + return Result(); + } + + Result GuestSetFlagsAction::Execute() const + { + auto* peep = TryGetEntity(_peepId); + if (peep == nullptr) + { + LOG_ERROR("Guest entity not found for peepID %u", _peepId.ToUnderlying()); + return Result(Status::InvalidParameters, STR_CANT_CHANGE_THIS, kStringIdNone); + } + + peep->PeepFlags = _newFlags; + + return Result(); + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/GuestSetFlagsAction.h b/src/openrct2/actions/GuestSetFlagsAction.h index c048f89a02..ac9ddac1e0 100644 --- a/src/openrct2/actions/GuestSetFlagsAction.h +++ b/src/openrct2/actions/GuestSetFlagsAction.h @@ -11,21 +11,24 @@ #include "GameAction.h" -class GuestSetFlagsAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - EntityId _peepId{ EntityId::GetNull() }; - uint32_t _newFlags{}; + class GuestSetFlagsAction final : public GameActionBase + { + private: + EntityId _peepId{ EntityId::GetNull() }; + uint32_t _newFlags{}; -public: - GuestSetFlagsAction() = default; - GuestSetFlagsAction(EntityId peepId, uint32_t flags); + public: + GuestSetFlagsAction() = default; + GuestSetFlagsAction(EntityId peepId, uint32_t flags); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; -}; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/GuestSetNameAction.cpp b/src/openrct2/actions/GuestSetNameAction.cpp index 2d08cdffed..eeace67360 100644 --- a/src/openrct2/actions/GuestSetNameAction.cpp +++ b/src/openrct2/actions/GuestSetNameAction.cpp @@ -19,89 +19,90 @@ #include "../windows/Intent.h" #include "../world/Park.h" -using namespace OpenRCT2; - -GuestSetNameAction::GuestSetNameAction(EntityId spriteIndex, const std::string& name) - : _spriteIndex(spriteIndex) - , _name(name) +namespace OpenRCT2::GameActions { -} - -EntityId GuestSetNameAction::GetSpriteIndex() const -{ - return _spriteIndex; -} - -std::string GuestSetNameAction::GetGuestName() const -{ - return _name; -} - -void GuestSetNameAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit("peep", _spriteIndex); - visitor.Visit("name", _name); -} - -uint16_t GuestSetNameAction::GetActionFlags() const -{ - return GameAction::GetActionFlags() | GameActions::Flags::AllowWhilePaused; -} - -void GuestSetNameAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_spriteIndex) << DS_TAG(_name); -} - -GameActions::Result GuestSetNameAction::Query() const -{ - if (_spriteIndex.ToUnderlying() >= kMaxEntities || _spriteIndex.IsNull()) + GuestSetNameAction::GuestSetNameAction(EntityId spriteIndex, const std::string& name) + : _spriteIndex(spriteIndex) + , _name(name) { - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_NAME_GUEST, STR_ERR_VALUE_OUT_OF_RANGE); } - auto guest = TryGetEntity(_spriteIndex); - if (guest == nullptr) + EntityId GuestSetNameAction::GetSpriteIndex() const { - LOG_ERROR("Guest entity not found for spriteIndex %u", _spriteIndex); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_NAME_GUEST, kStringIdNone); + return _spriteIndex; } - return GameActions::Result(); -} - -GameActions::Result GuestSetNameAction::Execute() const -{ - auto guest = TryGetEntity(_spriteIndex); - if (guest == nullptr) + std::string GuestSetNameAction::GetGuestName() const { - LOG_ERROR("Guest entity not found for spriteIndex %u", _spriteIndex); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_NAME_GUEST, kStringIdNone); + return _name; } - auto curName = guest->GetName(); - if (curName == _name) + void GuestSetNameAction::AcceptParameters(GameActionParameterVisitor& visitor) { - return GameActions::Result(); + visitor.Visit("peep", _spriteIndex); + visitor.Visit("name", _name); } - if (!guest->SetName(_name)) + uint16_t GuestSetNameAction::GetActionFlags() const { - return GameActions::Result(GameActions::Status::Unknown, STR_CANT_NAME_GUEST, kStringIdNone); + return GameAction::GetActionFlags() | Flags::AllowWhilePaused; } - // Easter egg functions are for guests only - guest->HandleEasterEggName(); + void GuestSetNameAction::Serialise(DataSerialiser& stream) + { + GameAction::Serialise(stream); - GfxInvalidateScreen(); + stream << DS_TAG(_spriteIndex) << DS_TAG(_name); + } - auto intent = Intent(INTENT_ACTION_REFRESH_GUEST_LIST); - ContextBroadcastIntent(&intent); + Result GuestSetNameAction::Query() const + { + if (_spriteIndex.ToUnderlying() >= kMaxEntities || _spriteIndex.IsNull()) + { + return Result(Status::InvalidParameters, STR_CANT_NAME_GUEST, STR_ERR_VALUE_OUT_OF_RANGE); + } - auto res = GameActions::Result(); - res.Position = guest->GetLocation(); + auto guest = TryGetEntity(_spriteIndex); + if (guest == nullptr) + { + LOG_ERROR("Guest entity not found for spriteIndex %u", _spriteIndex); + return Result(Status::InvalidParameters, STR_CANT_NAME_GUEST, kStringIdNone); + } - return res; -} + return Result(); + } + + Result GuestSetNameAction::Execute() const + { + auto guest = TryGetEntity(_spriteIndex); + if (guest == nullptr) + { + LOG_ERROR("Guest entity not found for spriteIndex %u", _spriteIndex); + return Result(Status::InvalidParameters, STR_CANT_NAME_GUEST, kStringIdNone); + } + + auto curName = guest->GetName(); + if (curName == _name) + { + return Result(); + } + + if (!guest->SetName(_name)) + { + return Result(Status::Unknown, STR_CANT_NAME_GUEST, kStringIdNone); + } + + // Easter egg functions are for guests only + guest->HandleEasterEggName(); + + GfxInvalidateScreen(); + + auto intent = Intent(INTENT_ACTION_REFRESH_GUEST_LIST); + ContextBroadcastIntent(&intent); + + auto res = Result(); + res.Position = guest->GetLocation(); + + return res; + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/GuestSetNameAction.h b/src/openrct2/actions/GuestSetNameAction.h index a1266f0c7b..292f792a3f 100644 --- a/src/openrct2/actions/GuestSetNameAction.h +++ b/src/openrct2/actions/GuestSetNameAction.h @@ -11,24 +11,27 @@ #include "GameAction.h" -class GuestSetNameAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - EntityId _spriteIndex{ EntityId::GetNull() }; - std::string _name; + class GuestSetNameAction final : public GameActionBase + { + private: + EntityId _spriteIndex{ EntityId::GetNull() }; + std::string _name; -public: - GuestSetNameAction() = default; - GuestSetNameAction(EntityId spriteIndex, const std::string& name); + public: + GuestSetNameAction() = default; + GuestSetNameAction(EntityId spriteIndex, const std::string& name); - EntityId GetSpriteIndex() const; - std::string GetGuestName() const; + EntityId GetSpriteIndex() const; + std::string GetGuestName() const; - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; -}; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/LandBuyRightsAction.cpp b/src/openrct2/actions/LandBuyRightsAction.cpp index eb503e6201..bdaf4bcfc1 100644 --- a/src/openrct2/actions/LandBuyRightsAction.cpp +++ b/src/openrct2/actions/LandBuyRightsAction.cpp @@ -24,152 +24,150 @@ #include "../world/Scenery.h" #include "../world/tile_element/SurfaceElement.h" -using namespace OpenRCT2; - -LandBuyRightsAction::LandBuyRightsAction(const MapRange& range, LandBuyRightSetting setting) - : _range(range) - , _setting(setting) +namespace OpenRCT2::GameActions { -} - -LandBuyRightsAction::LandBuyRightsAction(const CoordsXY& coord, LandBuyRightSetting setting) - : _range(coord.x, coord.y, coord.x, coord.y) - , _setting(setting) -{ -} - -void LandBuyRightsAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit(_range); - visitor.Visit("setting", _setting); -} - -uint16_t LandBuyRightsAction::GetActionFlags() const -{ - return GameAction::GetActionFlags(); -} - -void LandBuyRightsAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_range) << DS_TAG(_setting); -} - -GameActions::Result LandBuyRightsAction::Query() const -{ - return QueryExecute(false); -} - -GameActions::Result LandBuyRightsAction::Execute() const -{ - return QueryExecute(true); -} - -GameActions::Result LandBuyRightsAction::QueryExecute(bool isExecuting) const -{ - auto res = GameActions::Result(); - - MapRange normRange = _range.Normalise(); - // Keep big coordinates within map boundaries - auto mapSizeMaxXY = GetMapSizeMaxXY(); - auto aX = std::max(32, normRange.GetLeft()); - auto bX = std::min(mapSizeMaxXY.x, normRange.GetRight()); - auto aY = std::max(32, normRange.GetTop()); - auto bY = std::min(mapSizeMaxXY.y, normRange.GetBottom()); - - MapRange validRange = MapRange{ aX, aY, bX, bY }; - - CoordsXYZ centre{ (validRange.GetLeft() + validRange.GetRight()) / 2 + 16, - (validRange.GetTop() + validRange.GetBottom()) / 2 + 16, 0 }; - centre.z = TileElementHeight(centre); - - res.Position = centre; - res.Expenditure = ExpenditureType::landPurchase; - - // Game command modified to accept selection size - for (auto y = validRange.GetTop(); y <= validRange.GetBottom(); y += kCoordsXYStep) + LandBuyRightsAction::LandBuyRightsAction(const MapRange& range, LandBuyRightSetting setting) + : _range(range) + , _setting(setting) { - for (auto x = validRange.GetLeft(); x <= validRange.GetRight(); x += kCoordsXYStep) + } + + LandBuyRightsAction::LandBuyRightsAction(const CoordsXY& coord, LandBuyRightSetting setting) + : _range(coord.x, coord.y, coord.x, coord.y) + , _setting(setting) + { + } + + void LandBuyRightsAction::AcceptParameters(GameActionParameterVisitor& visitor) + { + visitor.Visit(_range); + visitor.Visit("setting", _setting); + } + + uint16_t LandBuyRightsAction::GetActionFlags() const + { + return GameAction::GetActionFlags(); + } + + void LandBuyRightsAction::Serialise(DataSerialiser& stream) + { + GameAction::Serialise(stream); + + stream << DS_TAG(_range) << DS_TAG(_setting); + } + + Result LandBuyRightsAction::Query() const + { + return QueryExecute(false); + } + + Result LandBuyRightsAction::Execute() const + { + return QueryExecute(true); + } + + Result LandBuyRightsAction::QueryExecute(bool isExecuting) const + { + auto res = Result(); + + MapRange normRange = _range.Normalise(); + // Keep big coordinates within map boundaries + auto mapSizeMaxXY = GetMapSizeMaxXY(); + auto aX = std::max(32, normRange.GetLeft()); + auto bX = std::min(mapSizeMaxXY.x, normRange.GetRight()); + auto aY = std::max(32, normRange.GetTop()); + auto bY = std::min(mapSizeMaxXY.y, normRange.GetBottom()); + + MapRange validRange = MapRange{ aX, aY, bX, bY }; + + CoordsXYZ centre{ (validRange.GetLeft() + validRange.GetRight()) / 2 + 16, + (validRange.GetTop() + validRange.GetBottom()) / 2 + 16, 0 }; + centre.z = TileElementHeight(centre); + + res.Position = centre; + res.Expenditure = ExpenditureType::landPurchase; + + // Game command modified to accept selection size + for (auto y = validRange.GetTop(); y <= validRange.GetBottom(); y += kCoordsXYStep) { - if (!LocationValid({ x, y })) - continue; - auto result = MapBuyLandRightsForTile({ x, y }, isExecuting); - if (result.Error == GameActions::Status::Ok) + for (auto x = validRange.GetLeft(); x <= validRange.GetRight(); x += kCoordsXYStep) { - res.Cost += result.Cost; + if (!LocationValid({ x, y })) + continue; + auto result = MapBuyLandRightsForTile({ x, y }, isExecuting); + if (result.Error == Status::Ok) + { + res.Cost += result.Cost; + } } } - } - if (isExecuting) - { - MapCountRemainingLandRights(); - } - return res; -} - -GameActions::Result LandBuyRightsAction::MapBuyLandRightsForTile(const CoordsXY& loc, bool isExecuting) const -{ - if (_setting >= LandBuyRightSetting::Count) - { - LOG_ERROR("Invalid land buying setting %u", _setting); - return GameActions::Result(GameActions::Status::InvalidParameters, kErrorTitles[0], STR_ERR_VALUE_OUT_OF_RANGE); + if (isExecuting) + { + MapCountRemainingLandRights(); + } + return res; } - SurfaceElement* surfaceElement = MapGetSurfaceElementAt(loc); - if (surfaceElement == nullptr) + Result LandBuyRightsAction::MapBuyLandRightsForTile(const CoordsXY& loc, bool isExecuting) const { - LOG_ERROR("No surface at x = %d, y = %d", loc.x, loc.y); - return GameActions::Result( - GameActions::Status::InvalidParameters, kErrorTitles[EnumValue(_setting)], STR_ERR_SURFACE_ELEMENT_NOT_FOUND); - } - - auto res = GameActions::Result(); - switch (_setting) - { - case LandBuyRightSetting::BuyLand: // 0 - if ((surfaceElement->GetOwnership() & OWNERSHIP_OWNED) != 0) - { // If the land is already owned - return res; - } - - if (gLegacyScene == LegacyScene::scenarioEditor || (surfaceElement->GetOwnership() & OWNERSHIP_AVAILABLE) == 0) - { - return GameActions::Result( - GameActions::Status::NotOwned, kErrorTitles[EnumValue(_setting)], STR_LAND_NOT_FOR_SALE); - } - if (isExecuting) - { - surfaceElement->SetOwnership(OWNERSHIP_OWNED); - Park::UpdateFencesAroundTile(loc); - } - res.Cost = getGameState().scenarioOptions.landPrice; - return res; - - case LandBuyRightSetting::BuyConstructionRights: // 2 - if ((surfaceElement->GetOwnership() & (OWNERSHIP_OWNED | OWNERSHIP_CONSTRUCTION_RIGHTS_OWNED)) != 0) - { // If the land or construction rights are already owned - return res; - } - - if (gLegacyScene == LegacyScene::scenarioEditor - || (surfaceElement->GetOwnership() & OWNERSHIP_CONSTRUCTION_RIGHTS_AVAILABLE) == 0) - { - return GameActions::Result( - GameActions::Status::NotOwned, kErrorTitles[EnumValue(_setting)], STR_CONSTRUCTION_RIGHTS_NOT_FOR_SALE); - } - - if (isExecuting) - { - surfaceElement->SetOwnership(surfaceElement->GetOwnership() | OWNERSHIP_CONSTRUCTION_RIGHTS_OWNED); - uint16_t baseZ = surfaceElement->GetBaseZ(); - MapInvalidateTile({ loc, baseZ, baseZ + 16 }); - } - res.Cost = getGameState().scenarioOptions.constructionRightsPrice; - return res; - - default: + if (_setting >= LandBuyRightSetting::Count) + { LOG_ERROR("Invalid land buying setting %u", _setting); - return GameActions::Result(GameActions::Status::InvalidParameters, kErrorTitles[0], STR_ERR_VALUE_OUT_OF_RANGE); + return Result(Status::InvalidParameters, kErrorTitles[0], STR_ERR_VALUE_OUT_OF_RANGE); + } + + SurfaceElement* surfaceElement = MapGetSurfaceElementAt(loc); + if (surfaceElement == nullptr) + { + LOG_ERROR("No surface at x = %d, y = %d", loc.x, loc.y); + return Result(Status::InvalidParameters, kErrorTitles[EnumValue(_setting)], STR_ERR_SURFACE_ELEMENT_NOT_FOUND); + } + + auto res = Result(); + switch (_setting) + { + case LandBuyRightSetting::BuyLand: // 0 + if ((surfaceElement->GetOwnership() & OWNERSHIP_OWNED) != 0) + { // If the land is already owned + return res; + } + + if (gLegacyScene == LegacyScene::scenarioEditor || (surfaceElement->GetOwnership() & OWNERSHIP_AVAILABLE) == 0) + { + return Result(Status::NotOwned, kErrorTitles[EnumValue(_setting)], STR_LAND_NOT_FOR_SALE); + } + if (isExecuting) + { + surfaceElement->SetOwnership(OWNERSHIP_OWNED); + Park::UpdateFencesAroundTile(loc); + } + res.Cost = getGameState().scenarioOptions.landPrice; + return res; + + case LandBuyRightSetting::BuyConstructionRights: // 2 + if ((surfaceElement->GetOwnership() & (OWNERSHIP_OWNED | OWNERSHIP_CONSTRUCTION_RIGHTS_OWNED)) != 0) + { // If the land or construction rights are already owned + return res; + } + + if (gLegacyScene == LegacyScene::scenarioEditor + || (surfaceElement->GetOwnership() & OWNERSHIP_CONSTRUCTION_RIGHTS_AVAILABLE) == 0) + { + return Result(Status::NotOwned, kErrorTitles[EnumValue(_setting)], STR_CONSTRUCTION_RIGHTS_NOT_FOR_SALE); + } + + if (isExecuting) + { + surfaceElement->SetOwnership(surfaceElement->GetOwnership() | OWNERSHIP_CONSTRUCTION_RIGHTS_OWNED); + uint16_t baseZ = surfaceElement->GetBaseZ(); + MapInvalidateTile({ loc, baseZ, baseZ + 16 }); + } + res.Cost = getGameState().scenarioOptions.constructionRightsPrice; + return res; + + default: + LOG_ERROR("Invalid land buying setting %u", _setting); + return Result(Status::InvalidParameters, kErrorTitles[0], STR_ERR_VALUE_OUT_OF_RANGE); + } } -} +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/LandBuyRightsAction.h b/src/openrct2/actions/LandBuyRightsAction.h index 7f2cf7a918..577f5617e2 100644 --- a/src/openrct2/actions/LandBuyRightsAction.h +++ b/src/openrct2/actions/LandBuyRightsAction.h @@ -11,38 +11,41 @@ #include "GameAction.h" -enum class LandBuyRightSetting : uint8_t +namespace OpenRCT2::GameActions { - BuyLand, - BuyConstructionRights, - Count -}; - -class LandBuyRightsAction final : public GameActionBase -{ -private: - MapRange _range; - LandBuyRightSetting _setting{ LandBuyRightSetting::Count }; - - constexpr static StringId kErrorTitles[] = { - STR_CANT_BUY_LAND, - STR_CANT_BUY_CONSTRUCTION_RIGHTS_HERE, + enum class LandBuyRightSetting : uint8_t + { + BuyLand, + BuyConstructionRights, + Count }; -public: - LandBuyRightsAction() = default; - LandBuyRightsAction(const MapRange& range, LandBuyRightSetting setting); - LandBuyRightsAction(const CoordsXY& coord, LandBuyRightSetting setting); + class LandBuyRightsAction final : public GameActionBase + { + private: + MapRange _range; + LandBuyRightSetting _setting{ LandBuyRightSetting::Count }; - void AcceptParameters(GameActionParameterVisitor& visitor) override; + constexpr static StringId kErrorTitles[] = { + STR_CANT_BUY_LAND, + STR_CANT_BUY_CONSTRUCTION_RIGHTS_HERE, + }; - uint16_t GetActionFlags() const override; + public: + LandBuyRightsAction() = default; + LandBuyRightsAction(const MapRange& range, LandBuyRightSetting setting); + LandBuyRightsAction(const CoordsXY& coord, LandBuyRightSetting setting); - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; -private: - OpenRCT2::GameActions::Result QueryExecute(bool isExecuting) const; - OpenRCT2::GameActions::Result MapBuyLandRightsForTile(const CoordsXY& loc, bool isExecuting) const; -}; + uint16_t GetActionFlags() const override; + + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; + + private: + Result QueryExecute(bool isExecuting) const; + Result MapBuyLandRightsForTile(const CoordsXY& loc, bool isExecuting) const; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/LandLowerAction.cpp b/src/openrct2/actions/LandLowerAction.cpp index dfbc21ef21..2e29f81172 100644 --- a/src/openrct2/actions/LandLowerAction.cpp +++ b/src/openrct2/actions/LandLowerAction.cpp @@ -25,125 +25,125 @@ #include "../world/tile_element/Slope.h" #include "../world/tile_element/SurfaceElement.h" -using namespace OpenRCT2; - -LandLowerAction::LandLowerAction(const CoordsXY& coords, MapRange range, uint8_t selectionType) - : _coords(coords) - , _range(range) - , _selectionType(selectionType) +namespace OpenRCT2::GameActions { -} - -void LandLowerAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit(_coords); - visitor.Visit(_range); - visitor.Visit("selectionType", _selectionType); -} - -uint16_t LandLowerAction::GetActionFlags() const -{ - return GameAction::GetActionFlags(); -} - -void LandLowerAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_coords) << DS_TAG(_range) << DS_TAG(_selectionType); -} - -GameActions::Result LandLowerAction::Query() const -{ - return QueryExecute(false); -} - -GameActions::Result LandLowerAction::Execute() const -{ - return QueryExecute(true); -} - -GameActions::Result LandLowerAction::QueryExecute(bool isExecuting) const -{ - auto res = GameActions::Result(); - size_t tableRow = _selectionType; - - // The selections between MAP_SELECT_TYPE_FULL and MAP_SELECT_TYPE_EDGE_0 are not included in the tables - if (_selectionType >= MAP_SELECT_TYPE_EDGE_0 && _selectionType <= MAP_SELECT_TYPE_EDGE_3) - tableRow -= MAP_SELECT_TYPE_EDGE_0 - MAP_SELECT_TYPE_FULL - 1; - - auto validRange = ClampRangeWithinMap(_range); - - res.Position = { _coords.x, _coords.y, TileElementHeight(_coords) }; - res.Expenditure = ExpenditureType::landscaping; - - if (isExecuting) + LandLowerAction::LandLowerAction(const CoordsXY& coords, MapRange range, uint8_t selectionType) + : _coords(coords) + , _range(range) + , _selectionType(selectionType) { - OpenRCT2::Audio::Play3D(OpenRCT2::Audio::SoundId::PlaceItem, { _coords.x, _coords.y, TileElementHeight(_coords) }); } - uint8_t maxHeight = MapGetHighestLandHeight(validRange); - bool withinOwnership = false; - - for (int32_t y = validRange.GetTop(); y <= validRange.GetBottom(); y += kCoordsXYStep) + void LandLowerAction::AcceptParameters(GameActionParameterVisitor& visitor) { - for (int32_t x = validRange.GetLeft(); x <= validRange.GetRight(); x += kCoordsXYStep) - { - if (!LocationValid({ x, y })) - continue; - auto* surfaceElement = MapGetSurfaceElementAt(CoordsXY{ x, y }); - if (surfaceElement == nullptr) - continue; + visitor.Visit(_coords); + visitor.Visit(_range); + visitor.Visit("selectionType", _selectionType); + } - if (gLegacyScene != LegacyScene::scenarioEditor && !getGameState().cheats.sandboxMode) + uint16_t LandLowerAction::GetActionFlags() const + { + return GameAction::GetActionFlags(); + } + + void LandLowerAction::Serialise(DataSerialiser& stream) + { + GameAction::Serialise(stream); + + stream << DS_TAG(_coords) << DS_TAG(_range) << DS_TAG(_selectionType); + } + + Result LandLowerAction::Query() const + { + return QueryExecute(false); + } + + Result LandLowerAction::Execute() const + { + return QueryExecute(true); + } + + Result LandLowerAction::QueryExecute(bool isExecuting) const + { + auto res = Result(); + size_t tableRow = _selectionType; + + // The selections between MAP_SELECT_TYPE_FULL and MAP_SELECT_TYPE_EDGE_0 are not included in the tables + if (_selectionType >= MAP_SELECT_TYPE_EDGE_0 && _selectionType <= MAP_SELECT_TYPE_EDGE_3) + tableRow -= MAP_SELECT_TYPE_EDGE_0 - MAP_SELECT_TYPE_FULL - 1; + + auto validRange = ClampRangeWithinMap(_range); + + res.Position = { _coords.x, _coords.y, TileElementHeight(_coords) }; + res.Expenditure = ExpenditureType::landscaping; + + if (isExecuting) + { + OpenRCT2::Audio::Play3D(OpenRCT2::Audio::SoundId::PlaceItem, { _coords.x, _coords.y, TileElementHeight(_coords) }); + } + + uint8_t maxHeight = MapGetHighestLandHeight(validRange); + bool withinOwnership = false; + + for (int32_t y = validRange.GetTop(); y <= validRange.GetBottom(); y += kCoordsXYStep) + { + for (int32_t x = validRange.GetLeft(); x <= validRange.GetRight(); x += kCoordsXYStep) { - if (!MapIsLocationInPark(CoordsXY{ x, y })) - { + if (!LocationValid({ x, y })) continue; + auto* surfaceElement = MapGetSurfaceElementAt(CoordsXY{ x, y }); + if (surfaceElement == nullptr) + continue; + + if (gLegacyScene != LegacyScene::scenarioEditor && !getGameState().cheats.sandboxMode) + { + if (!MapIsLocationInPark(CoordsXY{ x, y })) + { + continue; + } + } + withinOwnership = true; + + uint8_t height = surfaceElement->BaseHeight; + if (surfaceElement->GetSlope() & kTileSlopeRaisedCornersMask) + height += 2; + if (surfaceElement->GetSlope() & kTileSlopeDiagonalFlag) + height += 2; + + if (height < maxHeight) + continue; + + height = surfaceElement->BaseHeight; + uint8_t currentSlope = surfaceElement->GetSlope(); + uint8_t newSlope = LowerSurfaceCornerFlags(tableRow, currentSlope); + if (newSlope & kTileSlopeRaiseOrLowerBaseHeight) + height -= 2; + + newSlope &= kTileSlopeMask; + + auto landSetHeightAction = LandSetHeightAction({ x, y }, height, newSlope); + landSetHeightAction.SetFlags(GetFlags()); + auto result = isExecuting ? ExecuteNested(&landSetHeightAction) : QueryNested(&landSetHeightAction); + if (result.Error == Status::Ok) + { + res.Cost += result.Cost; + } + else + { + result.ErrorTitle = STR_CANT_LOWER_LAND_HERE; + return result; } } - withinOwnership = true; - - uint8_t height = surfaceElement->BaseHeight; - if (surfaceElement->GetSlope() & kTileSlopeRaisedCornersMask) - height += 2; - if (surfaceElement->GetSlope() & kTileSlopeDiagonalFlag) - height += 2; - - if (height < maxHeight) - continue; - - height = surfaceElement->BaseHeight; - uint8_t currentSlope = surfaceElement->GetSlope(); - uint8_t newSlope = LowerSurfaceCornerFlags(tableRow, currentSlope); - if (newSlope & kTileSlopeRaiseOrLowerBaseHeight) - height -= 2; - - newSlope &= kTileSlopeMask; - - auto landSetHeightAction = LandSetHeightAction({ x, y }, height, newSlope); - landSetHeightAction.SetFlags(GetFlags()); - auto result = isExecuting ? GameActions::ExecuteNested(&landSetHeightAction) - : GameActions::QueryNested(&landSetHeightAction); - if (result.Error == GameActions::Status::Ok) - { - res.Cost += result.Cost; - } - else - { - result.ErrorTitle = STR_CANT_LOWER_LAND_HERE; - return result; - } } + + if (!withinOwnership) + { + return Result(Status::Disallowed, STR_CANT_LOWER_LAND_HERE, STR_LAND_NOT_OWNED_BY_PARK); + } + + // Force ride construction to recheck area + _currentTrackSelectionFlags.set(TrackSelectionFlag::recheck); + + return res; } - - if (!withinOwnership) - { - return GameActions::Result(GameActions::Status::Disallowed, STR_CANT_LOWER_LAND_HERE, STR_LAND_NOT_OWNED_BY_PARK); - } - - // Force ride construction to recheck area - _currentTrackSelectionFlags.set(TrackSelectionFlag::recheck); - - return res; -} +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/LandLowerAction.h b/src/openrct2/actions/LandLowerAction.h index 98a0e8688d..a9eed1fc4a 100644 --- a/src/openrct2/actions/LandLowerAction.h +++ b/src/openrct2/actions/LandLowerAction.h @@ -11,25 +11,28 @@ #include "GameAction.h" -class LandLowerAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - CoordsXY _coords; - MapRange _range; - uint8_t _selectionType{}; + class LandLowerAction final : public GameActionBase + { + private: + CoordsXY _coords; + MapRange _range; + uint8_t _selectionType{}; -public: - LandLowerAction() = default; - LandLowerAction(const CoordsXY& coords, MapRange range, uint8_t selectionType); + public: + LandLowerAction() = default; + LandLowerAction(const CoordsXY& coords, MapRange range, uint8_t selectionType); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; -private: - OpenRCT2::GameActions::Result QueryExecute(bool isExecuting) const; -}; + private: + Result QueryExecute(bool isExecuting) const; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/LandRaiseAction.cpp b/src/openrct2/actions/LandRaiseAction.cpp index c6fb849907..045aea296c 100644 --- a/src/openrct2/actions/LandRaiseAction.cpp +++ b/src/openrct2/actions/LandRaiseAction.cpp @@ -26,128 +26,128 @@ #include "../world/tile_element/Slope.h" #include "../world/tile_element/SurfaceElement.h" -using namespace OpenRCT2; - -LandRaiseAction::LandRaiseAction(const CoordsXY& coords, MapRange range, uint8_t selectionType) - : _coords(coords) - , _range(range) - , _selectionType(selectionType) +namespace OpenRCT2::GameActions { -} - -void LandRaiseAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit(_coords); - visitor.Visit(_range); - visitor.Visit("selectionType", _selectionType); -} - -uint16_t LandRaiseAction::GetActionFlags() const -{ - return GameAction::GetActionFlags(); -} - -void LandRaiseAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_coords) << DS_TAG(_range) << DS_TAG(_selectionType); -} - -GameActions::Result LandRaiseAction::Query() const -{ - return QueryExecute(false); -} - -GameActions::Result LandRaiseAction::Execute() const -{ - return QueryExecute(true); -} - -GameActions::Result LandRaiseAction::QueryExecute(bool isExecuting) const -{ - auto res = GameActions::Result(); - size_t tableRow = _selectionType; - - // The selections between MAP_SELECT_TYPE_FULL and MAP_SELECT_TYPE_EDGE_0 are not included in the tables - if (_selectionType >= MAP_SELECT_TYPE_EDGE_0 && _selectionType <= MAP_SELECT_TYPE_EDGE_3) - tableRow -= MAP_SELECT_TYPE_EDGE_0 - MAP_SELECT_TYPE_FULL - 1; - - auto validRange = ClampRangeWithinMap(_range); - - res.Position = { _coords.x, _coords.y, TileElementHeight(_coords) }; - res.Expenditure = ExpenditureType::landscaping; - - if (isExecuting) + LandRaiseAction::LandRaiseAction(const CoordsXY& coords, MapRange range, uint8_t selectionType) + : _coords(coords) + , _range(range) + , _selectionType(selectionType) { - OpenRCT2::Audio::Play3D(OpenRCT2::Audio::SoundId::PlaceItem, { _coords.x, _coords.y, TileElementHeight(_coords) }); } - uint8_t minHeight = MapGetLowestLandHeight(validRange); - bool withinOwnership = false; - - for (int32_t y = validRange.GetTop(); y <= validRange.GetBottom(); y += kCoordsXYStep) + void LandRaiseAction::AcceptParameters(GameActionParameterVisitor& visitor) { - for (int32_t x = validRange.GetLeft(); x <= validRange.GetRight(); x += kCoordsXYStep) + visitor.Visit(_coords); + visitor.Visit(_range); + visitor.Visit("selectionType", _selectionType); + } + + uint16_t LandRaiseAction::GetActionFlags() const + { + return GameAction::GetActionFlags(); + } + + void LandRaiseAction::Serialise(DataSerialiser& stream) + { + GameAction::Serialise(stream); + + stream << DS_TAG(_coords) << DS_TAG(_range) << DS_TAG(_selectionType); + } + + Result LandRaiseAction::Query() const + { + return QueryExecute(false); + } + + Result LandRaiseAction::Execute() const + { + return QueryExecute(true); + } + + Result LandRaiseAction::QueryExecute(bool isExecuting) const + { + auto res = Result(); + size_t tableRow = _selectionType; + + // The selections between MAP_SELECT_TYPE_FULL and MAP_SELECT_TYPE_EDGE_0 are not included in the tables + if (_selectionType >= MAP_SELECT_TYPE_EDGE_0 && _selectionType <= MAP_SELECT_TYPE_EDGE_3) + tableRow -= MAP_SELECT_TYPE_EDGE_0 - MAP_SELECT_TYPE_FULL - 1; + + auto validRange = ClampRangeWithinMap(_range); + + res.Position = { _coords.x, _coords.y, TileElementHeight(_coords) }; + res.Expenditure = ExpenditureType::landscaping; + + if (isExecuting) { - if (!LocationValid({ x, y })) - continue; - auto* surfaceElement = MapGetSurfaceElementAt(CoordsXY{ x, y }); - if (surfaceElement == nullptr) - continue; + OpenRCT2::Audio::Play3D(OpenRCT2::Audio::SoundId::PlaceItem, { _coords.x, _coords.y, TileElementHeight(_coords) }); + } - if (gLegacyScene != LegacyScene::scenarioEditor && !getGameState().cheats.sandboxMode) + uint8_t minHeight = MapGetLowestLandHeight(validRange); + bool withinOwnership = false; + + for (int32_t y = validRange.GetTop(); y <= validRange.GetBottom(); y += kCoordsXYStep) + { + for (int32_t x = validRange.GetLeft(); x <= validRange.GetRight(); x += kCoordsXYStep) { - if (!MapIsLocationInPark(CoordsXY{ x, y })) - { + if (!LocationValid({ x, y })) + continue; + auto* surfaceElement = MapGetSurfaceElementAt(CoordsXY{ x, y }); + if (surfaceElement == nullptr) continue; - } - } - withinOwnership = true; - uint8_t height = surfaceElement->BaseHeight; - - if (height > minHeight) - continue; - - uint8_t currentSlope = surfaceElement->GetSlope(); - uint8_t newSlope = RaiseSurfaceCornerFlags(tableRow, currentSlope); - if (newSlope & kTileSlopeRaiseOrLowerBaseHeight) - { - if (height + 2 > UINT8_MAX) + if (gLegacyScene != LegacyScene::scenarioEditor && !getGameState().cheats.sandboxMode) { - height = UINT8_MAX; + if (!MapIsLocationInPark(CoordsXY{ x, y })) + { + continue; + } + } + withinOwnership = true; + + uint8_t height = surfaceElement->BaseHeight; + + if (height > minHeight) + continue; + + uint8_t currentSlope = surfaceElement->GetSlope(); + uint8_t newSlope = RaiseSurfaceCornerFlags(tableRow, currentSlope); + if (newSlope & kTileSlopeRaiseOrLowerBaseHeight) + { + if (height + 2 > UINT8_MAX) + { + height = UINT8_MAX; + } + else + { + height += 2; + } + } + newSlope &= kTileSlopeMask; + + auto landSetHeightAction = LandSetHeightAction({ x, y }, height, newSlope); + landSetHeightAction.SetFlags(GetFlags()); + auto result = isExecuting ? ExecuteNested(&landSetHeightAction) : QueryNested(&landSetHeightAction); + if (result.Error == Status::Ok) + { + res.Cost += result.Cost; } else { - height += 2; + result.ErrorTitle = STR_CANT_RAISE_LAND_HERE; + return result; } } - newSlope &= kTileSlopeMask; - - auto landSetHeightAction = LandSetHeightAction({ x, y }, height, newSlope); - landSetHeightAction.SetFlags(GetFlags()); - auto result = isExecuting ? GameActions::ExecuteNested(&landSetHeightAction) - : GameActions::QueryNested(&landSetHeightAction); - if (result.Error == GameActions::Status::Ok) - { - res.Cost += result.Cost; - } - else - { - result.ErrorTitle = STR_CANT_RAISE_LAND_HERE; - return result; - } } + + if (!withinOwnership) + { + return Result(Status::Disallowed, STR_CANT_RAISE_LAND_HERE, STR_LAND_NOT_OWNED_BY_PARK); + } + + // Force ride construction to recheck area + _currentTrackSelectionFlags.set(TrackSelectionFlag::recheck); + + return res; } - - if (!withinOwnership) - { - return GameActions::Result(GameActions::Status::Disallowed, STR_CANT_RAISE_LAND_HERE, STR_LAND_NOT_OWNED_BY_PARK); - } - - // Force ride construction to recheck area - _currentTrackSelectionFlags.set(TrackSelectionFlag::recheck); - - return res; -} +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/LandRaiseAction.h b/src/openrct2/actions/LandRaiseAction.h index 8542824039..0ea3f92372 100644 --- a/src/openrct2/actions/LandRaiseAction.h +++ b/src/openrct2/actions/LandRaiseAction.h @@ -11,25 +11,28 @@ #include "GameAction.h" -class LandRaiseAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - CoordsXY _coords; - MapRange _range; - uint8_t _selectionType{}; + class LandRaiseAction final : public GameActionBase + { + private: + CoordsXY _coords; + MapRange _range; + uint8_t _selectionType{}; -public: - LandRaiseAction() = default; - LandRaiseAction(const CoordsXY& coords, MapRange range, uint8_t selectionType); + public: + LandRaiseAction() = default; + LandRaiseAction(const CoordsXY& coords, MapRange range, uint8_t selectionType); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; -private: - OpenRCT2::GameActions::Result QueryExecute(bool isExecuting) const; -}; + private: + Result QueryExecute(bool isExecuting) const; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/LandSetHeightAction.cpp b/src/openrct2/actions/LandSetHeightAction.cpp index fcbe2075d8..bc02e6625d 100644 --- a/src/openrct2/actions/LandSetHeightAction.cpp +++ b/src/openrct2/actions/LandSetHeightAction.cpp @@ -29,284 +29,108 @@ #include "../world/tile_element/SurfaceElement.h" #include "../world/tile_element/TrackElement.h" -using namespace OpenRCT2; - -LandSetHeightAction::LandSetHeightAction(const CoordsXY& coords, uint8_t height, uint8_t style) - : _coords(coords) - , _height(height) - , _style(style) +namespace OpenRCT2::GameActions { -} - -void LandSetHeightAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit(_coords); - visitor.Visit("height", _height); - visitor.Visit("style", _style); -} - -uint16_t LandSetHeightAction::GetActionFlags() const -{ - return GameAction::GetActionFlags() | GameActions::Flags::EditorOnly; -} - -void LandSetHeightAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_coords) << DS_TAG(_height) << DS_TAG(_style); -} - -GameActions::Result LandSetHeightAction::Query() const -{ - auto& gameState = getGameState(); - if (gameState.park.flags & PARK_FLAGS_FORBID_LANDSCAPE_CHANGES) + LandSetHeightAction::LandSetHeightAction(const CoordsXY& coords, uint8_t height, uint8_t style) + : _coords(coords) + , _height(height) + , _style(style) { - return GameActions::Result(GameActions::Status::Disallowed, STR_FORBIDDEN_BY_THE_LOCAL_AUTHORITY, kStringIdNone); } - StringId errorMessage = CheckParameters(); - if (errorMessage != kStringIdNone) + void LandSetHeightAction::AcceptParameters(GameActionParameterVisitor& visitor) { - return GameActions::Result(GameActions::Status::Disallowed, kStringIdNone, errorMessage); + visitor.Visit(_coords); + visitor.Visit("height", _height); + visitor.Visit("style", _style); } - if (gLegacyScene != LegacyScene::scenarioEditor && !gameState.cheats.sandboxMode) + uint16_t LandSetHeightAction::GetActionFlags() const { - if (!MapIsLocationInPark(_coords)) + return GameAction::GetActionFlags() | Flags::EditorOnly; + } + + void LandSetHeightAction::Serialise(DataSerialiser& stream) + { + GameAction::Serialise(stream); + + stream << DS_TAG(_coords) << DS_TAG(_height) << DS_TAG(_style); + } + + Result LandSetHeightAction::Query() const + { + auto& gameState = getGameState(); + if (gameState.park.flags & PARK_FLAGS_FORBID_LANDSCAPE_CHANGES) { - return GameActions::Result(GameActions::Status::Disallowed, STR_LAND_NOT_OWNED_BY_PARK, kStringIdNone); + return Result(Status::Disallowed, STR_FORBIDDEN_BY_THE_LOCAL_AUTHORITY, kStringIdNone); } - } - money64 sceneryRemovalCost = 0; - if (!gameState.cheats.disableClearanceChecks) - { - if (gameState.park.flags & PARK_FLAGS_FORBID_TREE_REMOVAL) - { - // Check for obstructing large trees - TileElement* tileElement = CheckTreeObstructions(); - if (tileElement != nullptr) - { - auto res = GameActions::Result(GameActions::Status::Disallowed, kStringIdNone, kStringIdNone); - MapGetObstructionErrorText(tileElement, res); - return res; - } - } - sceneryRemovalCost = GetSmallSceneryRemovalCost(); - } - - // Check for ride support limits - if (!gameState.cheats.disableSupportLimits) - { - errorMessage = CheckRideSupports(); + StringId errorMessage = CheckParameters(); if (errorMessage != kStringIdNone) { - return GameActions::Result(GameActions::Status::Disallowed, kStringIdNone, errorMessage); + return Result(Status::Disallowed, kStringIdNone, errorMessage); } - } - auto* surfaceElement = MapGetSurfaceElementAt(_coords); - if (surfaceElement == nullptr) - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_SURFACE_ELEMENT_NOT_FOUND); - - // We need to check if there is _currently_ a level crossing on the tile. - // For that, we need the old height, so we can't use the _height variable. - auto oldCoords = CoordsXYZ{ _coords, surfaceElement->GetBaseZ() }; - auto* pathElement = MapGetFootpathElement(oldCoords); - if (pathElement != nullptr && pathElement->AsPath()->IsLevelCrossing(oldCoords)) - { - return GameActions::Result(GameActions::Status::Disallowed, STR_REMOVE_LEVEL_CROSSING_FIRST, kStringIdNone); - } - - TileElement* tileElement = CheckFloatingStructures(reinterpret_cast(surfaceElement), _height); - if (tileElement != nullptr) - { - auto res = GameActions::Result(GameActions::Status::Disallowed, kStringIdNone, kStringIdNone); - MapGetObstructionErrorText(tileElement, res); - return res; - } - - if (!gameState.cheats.disableClearanceChecks) - { - uint8_t zCorner = _height; - if (_style & kTileSlopeRaisedCornersMask) + if (gLegacyScene != LegacyScene::scenarioEditor && !gameState.cheats.sandboxMode) { - zCorner += 2; - if (_style & kTileSlopeDiagonalFlag) + if (!MapIsLocationInPark(_coords)) { - zCorner += 2; + return Result(Status::Disallowed, STR_LAND_NOT_OWNED_BY_PARK, kStringIdNone); } } - auto clearResult = MapCanConstructWithClearAt( - { _coords, _height * kCoordsZStep, zCorner * kCoordsZStep }, &MapSetLandHeightClearFunc, { 0b1111, 0 }, 0, - CreateCrossingMode::none); - if (clearResult.Error != GameActions::Status::Ok) + money64 sceneryRemovalCost = 0; + if (!gameState.cheats.disableClearanceChecks) { - clearResult.Error = GameActions::Status::Disallowed; - return clearResult; - } - } - auto res = GameActions::Result(); - res.Cost = sceneryRemovalCost + GetSurfaceHeightChangeCost(surfaceElement); - res.Expenditure = ExpenditureType::landscaping; - return res; -} - -GameActions::Result LandSetHeightAction::Execute() const -{ - money64 cost = 0.00_GBP; - auto surfaceHeight = TileElementHeight(_coords); - FootpathRemoveLitter({ _coords, surfaceHeight }); - - if (!getGameState().cheats.disableClearanceChecks) - { - WallRemoveAt({ _coords, _height * 8 - 16, _height * 8 + 32 }); - cost += GetSmallSceneryRemovalCost(); - SmallSceneryRemoval(); - } - - auto* surfaceElement = MapGetSurfaceElementAt(_coords); - if (surfaceElement == nullptr) - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_SURFACE_ELEMENT_NOT_FOUND); - - cost += GetSurfaceHeightChangeCost(surfaceElement); - SetSurfaceHeight(reinterpret_cast(surfaceElement)); - - auto res = GameActions::Result(); - res.Position = { _coords.x + 16, _coords.y + 16, surfaceHeight }; - res.Cost = cost; - res.Expenditure = ExpenditureType::landscaping; - return res; -} - -StringId LandSetHeightAction::CheckParameters() const -{ - if (!LocationValid(_coords) || MapIsEdge(_coords)) - { - return STR_OFF_EDGE_OF_MAP; - } - - if (_height < kMinimumLandHeight) - { - return STR_TOO_LOW; - } - - // Divide by 2 and subtract 7 to get the in-game units. - if (_height > kMaximumLandHeight) - { - return STR_TOO_HIGH; - } - - if (_height > kMaximumLandHeight - 2 && (_style & kTileSlopeMask) != 0) - { - return STR_TOO_HIGH; - } - - if (_height == kMaximumLandHeight - 2 && (_style & kTileSlopeDiagonalFlag)) - { - return STR_TOO_HIGH; - } - - return kStringIdNone; -} - -TileElement* LandSetHeightAction::CheckTreeObstructions() const -{ - for (auto* sceneryElement : TileElementsView(_coords)) - { - if (_height > sceneryElement->ClearanceHeight) - continue; - if (_height + 4 < sceneryElement->BaseHeight) - continue; - - auto* sceneryEntry = sceneryElement->GetEntry(); - if (!sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_IS_TREE)) - continue; - - return sceneryElement->as(); - } - return nullptr; -} - -money64 LandSetHeightAction::GetSmallSceneryRemovalCost() const -{ - money64 cost{ 0 }; - - for (auto* sceneryElement : TileElementsView(_coords)) - { - if (_height > sceneryElement->ClearanceHeight) - continue; - if (_height + 4 < sceneryElement->BaseHeight) - continue; - - auto* sceneryEntry = sceneryElement->GetEntry(); - if (sceneryEntry == nullptr) - continue; - - cost += sceneryEntry->removal_price; - } - - return cost; -} - -void LandSetHeightAction::SmallSceneryRemoval() const -{ - TileElement* tileElement = MapGetFirstElementAt(_coords); - do - { - if (tileElement == nullptr) - break; - if (tileElement->GetType() != TileElementType::SmallScenery) - continue; - if (_height > tileElement->ClearanceHeight) - continue; - if (_height + 4 < tileElement->BaseHeight) - continue; - TileElementRemove(tileElement--); - } while (!(tileElement++)->IsLastForTile()); -} - -StringId LandSetHeightAction::CheckRideSupports() const -{ - for (auto* trackElement : TileElementsView(_coords)) - { - RideId rideIndex = trackElement->GetRideIndex(); - - auto ride = GetRide(rideIndex); - if (ride == nullptr) - continue; - - const auto* rideEntry = ride->getRideEntry(); - if (rideEntry == nullptr) - continue; - - int32_t maxHeight = rideEntry->max_height; - if (maxHeight == 0) - { - maxHeight = ride->getRideTypeDescriptor().Heights.MaxHeight; + if (gameState.park.flags & PARK_FLAGS_FORBID_TREE_REMOVAL) + { + // Check for obstructing large trees + TileElement* tileElement = CheckTreeObstructions(); + if (tileElement != nullptr) + { + auto res = Result(Status::Disallowed, kStringIdNone, kStringIdNone); + MapGetObstructionErrorText(tileElement, res); + return res; + } + } + sceneryRemovalCost = GetSmallSceneryRemovalCost(); } - int32_t zDelta = trackElement->ClearanceHeight - _height; - if (zDelta >= 0 && zDelta / 2 > maxHeight) + // Check for ride support limits + if (!gameState.cheats.disableSupportLimits) { - return STR_SUPPORTS_CANT_BE_EXTENDED; + errorMessage = CheckRideSupports(); + if (errorMessage != kStringIdNone) + { + return Result(Status::Disallowed, kStringIdNone, errorMessage); + } } - } - return kStringIdNone; -} -TileElement* LandSetHeightAction::CheckFloatingStructures(TileElement* surfaceElement, uint8_t zCorner) const -{ - if (surfaceElement->AsSurface()->HasTrackThatNeedsWater()) - { - uint32_t waterHeight = surfaceElement->AsSurface()->GetWaterHeight(); - if (waterHeight != 0) + auto* surfaceElement = MapGetSurfaceElementAt(_coords); + if (surfaceElement == nullptr) + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_SURFACE_ELEMENT_NOT_FOUND); + + // We need to check if there is _currently_ a level crossing on the tile. + // For that, we need the old height, so we can't use the _height variable. + auto oldCoords = CoordsXYZ{ _coords, surfaceElement->GetBaseZ() }; + auto* pathElement = MapGetFootpathElement(oldCoords); + if (pathElement != nullptr && pathElement->AsPath()->IsLevelCrossing(oldCoords)) { - if (_style & kTileSlopeMask) + return Result(Status::Disallowed, STR_REMOVE_LEVEL_CROSSING_FIRST, kStringIdNone); + } + + TileElement* tileElement = CheckFloatingStructures(reinterpret_cast(surfaceElement), _height); + if (tileElement != nullptr) + { + auto res = Result(Status::Disallowed, kStringIdNone, kStringIdNone); + MapGetObstructionErrorText(tileElement, res); + return res; + } + + if (!gameState.cheats.disableClearanceChecks) + { + uint8_t zCorner = _height; + if (_style & kTileSlopeRaisedCornersMask) { zCorner += 2; if (_style & kTileSlopeDiagonalFlag) @@ -314,50 +138,225 @@ TileElement* LandSetHeightAction::CheckFloatingStructures(TileElement* surfaceEl zCorner += 2; } } - if (zCorner > (waterHeight / kCoordsZStep) - 2) + + auto clearResult = MapCanConstructWithClearAt( + { _coords, _height * kCoordsZStep, zCorner * kCoordsZStep }, &MapSetLandHeightClearFunc, { 0b1111, 0 }, 0, + CreateCrossingMode::none); + if (clearResult.Error != Status::Ok) { - return ++surfaceElement; + clearResult.Error = Status::Disallowed; + return clearResult; } } + auto res = Result(); + res.Cost = sceneryRemovalCost + GetSurfaceHeightChangeCost(surfaceElement); + res.Expenditure = ExpenditureType::landscaping; + return res; } - return nullptr; -} -money64 LandSetHeightAction::GetSurfaceHeightChangeCost(SurfaceElement* surfaceElement) const -{ - money64 cost{ 0 }; - for (Direction i : kAllDirections) + Result LandSetHeightAction::Execute() const { - int32_t cornerHeight = TileElementGetCornerHeight(surfaceElement, i); - cornerHeight -= MapGetCornerHeight(_height, _style & kTileSlopeMask, i); - cost += 2.50_GBP * abs(cornerHeight); - } - return cost; -} + money64 cost = 0.00_GBP; + auto surfaceHeight = TileElementHeight(_coords); + FootpathRemoveLitter({ _coords, surfaceHeight }); -void LandSetHeightAction::SetSurfaceHeight(TileElement* surfaceElement) const -{ - surfaceElement->BaseHeight = _height; - surfaceElement->ClearanceHeight = _height; - surfaceElement->AsSurface()->SetSlope(_style); - int32_t waterHeight = surfaceElement->AsSurface()->GetWaterHeight() / kCoordsZStep; - if (waterHeight != 0 && waterHeight <= _height) + if (!getGameState().cheats.disableClearanceChecks) + { + WallRemoveAt({ _coords, _height * 8 - 16, _height * 8 + 32 }); + cost += GetSmallSceneryRemovalCost(); + SmallSceneryRemoval(); + } + + auto* surfaceElement = MapGetSurfaceElementAt(_coords); + if (surfaceElement == nullptr) + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_SURFACE_ELEMENT_NOT_FOUND); + + cost += GetSurfaceHeightChangeCost(surfaceElement); + SetSurfaceHeight(reinterpret_cast(surfaceElement)); + + auto res = Result(); + res.Position = { _coords.x + 16, _coords.y + 16, surfaceHeight }; + res.Cost = cost; + res.Expenditure = ExpenditureType::landscaping; + return res; + } + + StringId LandSetHeightAction::CheckParameters() const { - surfaceElement->AsSurface()->SetWaterHeight(0); + if (!LocationValid(_coords) || MapIsEdge(_coords)) + { + return STR_OFF_EDGE_OF_MAP; + } + + if (_height < kMinimumLandHeight) + { + return STR_TOO_LOW; + } + + // Divide by 2 and subtract 7 to get the in-game units. + if (_height > kMaximumLandHeight) + { + return STR_TOO_HIGH; + } + + if (_height > kMaximumLandHeight - 2 && (_style & kTileSlopeMask) != 0) + { + return STR_TOO_HIGH; + } + + if (_height == kMaximumLandHeight - 2 && (_style & kTileSlopeDiagonalFlag)) + { + return STR_TOO_HIGH; + } + + return kStringIdNone; } - MapInvalidateTileFull(_coords); -} + TileElement* LandSetHeightAction::CheckTreeObstructions() const + { + for (auto* sceneryElement : TileElementsView(_coords)) + { + if (_height > sceneryElement->ClearanceHeight) + continue; + if (_height + 4 < sceneryElement->BaseHeight) + continue; -int32_t LandSetHeightAction::MapSetLandHeightClearFunc( - TileElement** tile_element, [[maybe_unused]] const CoordsXY& coords, [[maybe_unused]] uint8_t flags, - [[maybe_unused]] money64* price) -{ - if ((*tile_element)->GetType() == TileElementType::Surface) - return 0; + auto* sceneryEntry = sceneryElement->GetEntry(); + if (!sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_IS_TREE)) + continue; - if ((*tile_element)->GetType() == TileElementType::SmallScenery) - return 0; + return sceneryElement->as(); + } + return nullptr; + } - return 1; -} + money64 LandSetHeightAction::GetSmallSceneryRemovalCost() const + { + money64 cost{ 0 }; + + for (auto* sceneryElement : TileElementsView(_coords)) + { + if (_height > sceneryElement->ClearanceHeight) + continue; + if (_height + 4 < sceneryElement->BaseHeight) + continue; + + auto* sceneryEntry = sceneryElement->GetEntry(); + if (sceneryEntry == nullptr) + continue; + + cost += sceneryEntry->removal_price; + } + + return cost; + } + + void LandSetHeightAction::SmallSceneryRemoval() const + { + TileElement* tileElement = MapGetFirstElementAt(_coords); + do + { + if (tileElement == nullptr) + break; + if (tileElement->GetType() != TileElementType::SmallScenery) + continue; + if (_height > tileElement->ClearanceHeight) + continue; + if (_height + 4 < tileElement->BaseHeight) + continue; + TileElementRemove(tileElement--); + } while (!(tileElement++)->IsLastForTile()); + } + + StringId LandSetHeightAction::CheckRideSupports() const + { + for (auto* trackElement : TileElementsView(_coords)) + { + RideId rideIndex = trackElement->GetRideIndex(); + + auto ride = GetRide(rideIndex); + if (ride == nullptr) + continue; + + const auto* rideEntry = ride->getRideEntry(); + if (rideEntry == nullptr) + continue; + + int32_t maxHeight = rideEntry->max_height; + if (maxHeight == 0) + { + maxHeight = ride->getRideTypeDescriptor().Heights.MaxHeight; + } + + int32_t zDelta = trackElement->ClearanceHeight - _height; + if (zDelta >= 0 && zDelta / 2 > maxHeight) + { + return STR_SUPPORTS_CANT_BE_EXTENDED; + } + } + return kStringIdNone; + } + + TileElement* LandSetHeightAction::CheckFloatingStructures(TileElement* surfaceElement, uint8_t zCorner) const + { + if (surfaceElement->AsSurface()->HasTrackThatNeedsWater()) + { + uint32_t waterHeight = surfaceElement->AsSurface()->GetWaterHeight(); + if (waterHeight != 0) + { + if (_style & kTileSlopeMask) + { + zCorner += 2; + if (_style & kTileSlopeDiagonalFlag) + { + zCorner += 2; + } + } + if (zCorner > (waterHeight / kCoordsZStep) - 2) + { + return ++surfaceElement; + } + } + } + return nullptr; + } + + money64 LandSetHeightAction::GetSurfaceHeightChangeCost(SurfaceElement* surfaceElement) const + { + money64 cost{ 0 }; + for (Direction i : kAllDirections) + { + int32_t cornerHeight = TileElementGetCornerHeight(surfaceElement, i); + cornerHeight -= MapGetCornerHeight(_height, _style & kTileSlopeMask, i); + cost += 2.50_GBP * abs(cornerHeight); + } + return cost; + } + + void LandSetHeightAction::SetSurfaceHeight(TileElement* surfaceElement) const + { + surfaceElement->BaseHeight = _height; + surfaceElement->ClearanceHeight = _height; + surfaceElement->AsSurface()->SetSlope(_style); + int32_t waterHeight = surfaceElement->AsSurface()->GetWaterHeight() / kCoordsZStep; + if (waterHeight != 0 && waterHeight <= _height) + { + surfaceElement->AsSurface()->SetWaterHeight(0); + } + + MapInvalidateTileFull(_coords); + } + + int32_t LandSetHeightAction::MapSetLandHeightClearFunc( + TileElement** tile_element, [[maybe_unused]] const CoordsXY& coords, [[maybe_unused]] uint8_t flags, + [[maybe_unused]] money64* price) + { + if ((*tile_element)->GetType() == TileElementType::Surface) + return 0; + + if ((*tile_element)->GetType() == TileElementType::SmallScenery) + return 0; + + return 1; + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/LandSetHeightAction.h b/src/openrct2/actions/LandSetHeightAction.h index 540a096382..eab40d6b79 100644 --- a/src/openrct2/actions/LandSetHeightAction.h +++ b/src/openrct2/actions/LandSetHeightAction.h @@ -11,40 +11,43 @@ #include "GameAction.h" -class LandSetHeightAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - CoordsXY _coords; - uint8_t _height{}; - uint8_t _style{}; + class LandSetHeightAction final : public GameActionBase + { + private: + CoordsXY _coords; + uint8_t _height{}; + uint8_t _style{}; -public: - LandSetHeightAction() = default; - LandSetHeightAction(const CoordsXY& coords, uint8_t height, uint8_t style); + public: + LandSetHeightAction() = default; + LandSetHeightAction(const CoordsXY& coords, uint8_t height, uint8_t style); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; -private: - StringId CheckParameters() const; - OpenRCT2::TileElement* CheckTreeObstructions() const; - money64 GetSmallSceneryRemovalCost() const; - void SmallSceneryRemoval() const; - StringId CheckRideSupports() const; - OpenRCT2::TileElement* CheckFloatingStructures(OpenRCT2::TileElement* surfaceElement, uint8_t zCorner) const; - money64 GetSurfaceHeightChangeCost(OpenRCT2::SurfaceElement* surfaceElement) const; - void SetSurfaceHeight(OpenRCT2::TileElement* surfaceElement) const; + private: + StringId CheckParameters() const; + TileElement* CheckTreeObstructions() const; + money64 GetSmallSceneryRemovalCost() const; + void SmallSceneryRemoval() const; + StringId CheckRideSupports() const; + TileElement* CheckFloatingStructures(TileElement* surfaceElement, uint8_t zCorner) const; + money64 GetSurfaceHeightChangeCost(SurfaceElement* surfaceElement) const; + void SetSurfaceHeight(TileElement* surfaceElement) const; - /** - * - * rct2: 0x00663CB9 - */ - static int32_t MapSetLandHeightClearFunc( - OpenRCT2::TileElement** tile_element, [[maybe_unused]] const CoordsXY& coords, [[maybe_unused]] uint8_t flags, - [[maybe_unused]] money64* price); -}; + /** + * + * rct2: 0x00663CB9 + */ + static int32_t MapSetLandHeightClearFunc( + TileElement** tile_element, [[maybe_unused]] const CoordsXY& coords, [[maybe_unused]] uint8_t flags, + [[maybe_unused]] money64* price); + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/LandSetRightsAction.cpp b/src/openrct2/actions/LandSetRightsAction.cpp index 0b7bc0861f..27d1b74774 100644 --- a/src/openrct2/actions/LandSetRightsAction.cpp +++ b/src/openrct2/actions/LandSetRightsAction.cpp @@ -26,213 +26,214 @@ #include "../world/tile_element/EntranceElement.h" #include "../world/tile_element/SurfaceElement.h" -using namespace OpenRCT2; -using namespace OpenRCT2::Numerics; - -LandSetRightsAction::LandSetRightsAction(const MapRange& range, LandSetRightSetting setting, uint8_t ownership) - : _range(range) - , _setting(setting) - , _ownership(ownership) +namespace OpenRCT2::GameActions { -} + using namespace OpenRCT2::Numerics; -LandSetRightsAction::LandSetRightsAction(const CoordsXY& coord, LandSetRightSetting setting, uint8_t ownership) - : _range(coord.x, coord.y, coord.x, coord.y) - , _setting(setting) - , _ownership(ownership) -{ -} - -void LandSetRightsAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit(_range); - visitor.Visit("setting", _setting); - visitor.Visit("ownership", _ownership); -} - -uint16_t LandSetRightsAction::GetActionFlags() const -{ - return GameAction::GetActionFlags() | GameActions::Flags::EditorOnly; -} - -void LandSetRightsAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_range) << DS_TAG(_setting) << DS_TAG(_ownership); -} - -GameActions::Result LandSetRightsAction::Query() const -{ - return QueryExecute(false); -} - -GameActions::Result LandSetRightsAction::Execute() const -{ - return QueryExecute(true); -} - -GameActions::Result LandSetRightsAction::QueryExecute(bool isExecuting) const -{ - auto res = GameActions::Result(); - - auto validRange = ClampRangeWithinMap(_range.Normalise()); - CoordsXYZ centre{ (validRange.GetLeft() + validRange.GetRight()) / 2 + 16, - (validRange.GetTop() + validRange.GetBottom()) / 2 + 16, 0 }; - centre.z = TileElementHeight(centre); - - res.Position = centre; - res.Expenditure = ExpenditureType::landPurchase; - - if (!isInEditorMode() && !getGameState().cheats.sandboxMode) + LandSetRightsAction::LandSetRightsAction(const MapRange& range, LandSetRightSetting setting, uint8_t ownership) + : _range(range) + , _setting(setting) + , _ownership(ownership) { - return GameActions::Result(GameActions::Status::NotInEditorMode, kStringIdNone, STR_LAND_NOT_FOR_SALE); } - // Game command modified to accept selection size - for (auto y = validRange.GetTop(); y <= validRange.GetBottom(); y += kCoordsXYStep) + LandSetRightsAction::LandSetRightsAction(const CoordsXY& coord, LandSetRightSetting setting, uint8_t ownership) + : _range(coord.x, coord.y, coord.x, coord.y) + , _setting(setting) + , _ownership(ownership) { - for (auto x = validRange.GetLeft(); x <= validRange.GetRight(); x += kCoordsXYStep) + } + + void LandSetRightsAction::AcceptParameters(GameActionParameterVisitor& visitor) + { + visitor.Visit(_range); + visitor.Visit("setting", _setting); + visitor.Visit("ownership", _ownership); + } + + uint16_t LandSetRightsAction::GetActionFlags() const + { + return GameAction::GetActionFlags() | Flags::EditorOnly; + } + + void LandSetRightsAction::Serialise(DataSerialiser& stream) + { + GameAction::Serialise(stream); + + stream << DS_TAG(_range) << DS_TAG(_setting) << DS_TAG(_ownership); + } + + Result LandSetRightsAction::Query() const + { + return QueryExecute(false); + } + + Result LandSetRightsAction::Execute() const + { + return QueryExecute(true); + } + + Result LandSetRightsAction::QueryExecute(bool isExecuting) const + { + auto res = Result(); + + auto validRange = ClampRangeWithinMap(_range.Normalise()); + CoordsXYZ centre{ (validRange.GetLeft() + validRange.GetRight()) / 2 + 16, + (validRange.GetTop() + validRange.GetBottom()) / 2 + 16, 0 }; + centre.z = TileElementHeight(centre); + + res.Position = centre; + res.Expenditure = ExpenditureType::landPurchase; + + if (!isInEditorMode() && !getGameState().cheats.sandboxMode) { - if (!LocationValid({ x, y })) - continue; - auto result = MapBuyLandRightsForTile({ x, y }, isExecuting); - if (result.Error == GameActions::Status::Ok) + return Result(Status::NotInEditorMode, kStringIdNone, STR_LAND_NOT_FOR_SALE); + } + + // Game command modified to accept selection size + for (auto y = validRange.GetTop(); y <= validRange.GetBottom(); y += kCoordsXYStep) + { + for (auto x = validRange.GetLeft(); x <= validRange.GetRight(); x += kCoordsXYStep) { - res.Cost += result.Cost; + if (!LocationValid({ x, y })) + continue; + auto result = MapBuyLandRightsForTile({ x, y }, isExecuting); + if (result.Error == Status::Ok) + { + res.Cost += result.Cost; + } } } - } - if (isExecuting) - { - MapCountRemainingLandRights(); - OpenRCT2::Audio::Play3D(OpenRCT2::Audio::SoundId::PlaceItem, centre); - } - return res; -} - -GameActions::Result LandSetRightsAction::MapBuyLandRightsForTile(const CoordsXY& loc, bool isExecuting) const -{ - SurfaceElement* surfaceElement = MapGetSurfaceElementAt(loc); - if (surfaceElement == nullptr) - { - LOG_ERROR("No surface at x = %d, y = %d", loc.x, loc.y); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_SURFACE_ELEMENT_NOT_FOUND); - } - - auto res = GameActions::Result(); - switch (_setting) - { - case LandSetRightSetting::UnownLand: - if (isExecuting) - { - surfaceElement->SetOwnership( - surfaceElement->GetOwnership() & ~(OWNERSHIP_OWNED | OWNERSHIP_CONSTRUCTION_RIGHTS_OWNED)); - Park::UpdateFencesAroundTile(loc); - } - return res; - case LandSetRightSetting::UnownConstructionRights: - if (isExecuting) - { - surfaceElement->SetOwnership(surfaceElement->GetOwnership() & ~OWNERSHIP_CONSTRUCTION_RIGHTS_OWNED); - uint16_t baseZ = surfaceElement->GetBaseZ(); - MapInvalidateTile({ loc, baseZ, baseZ + 16 }); - } - return res; - case LandSetRightSetting::SetForSale: - if (isExecuting) - { - surfaceElement->SetOwnership(surfaceElement->GetOwnership() | OWNERSHIP_AVAILABLE); - uint16_t baseZ = surfaceElement->GetBaseZ(); - MapInvalidateTile({ loc, baseZ, baseZ + 16 }); - } - return res; - case LandSetRightSetting::SetConstructionRightsForSale: - if (isExecuting) - { - surfaceElement->SetOwnership(surfaceElement->GetOwnership() | OWNERSHIP_CONSTRUCTION_RIGHTS_AVAILABLE); - uint16_t baseZ = surfaceElement->GetBaseZ(); - MapInvalidateTile({ loc, baseZ, baseZ + 16 }); - } - return res; - case LandSetRightSetting::SetOwnershipWithChecks: + if (isExecuting) { - if (_ownership == surfaceElement->GetOwnership()) - { - return res; - } + MapCountRemainingLandRights(); + OpenRCT2::Audio::Play3D(OpenRCT2::Audio::SoundId::PlaceItem, centre); + } + return res; + } - for (auto* entranceElement : TileElementsView(loc)) - { - if (entranceElement->GetEntranceType() != ENTRANCE_TYPE_PARK_ENTRANCE) - continue; + Result LandSetRightsAction::MapBuyLandRightsForTile(const CoordsXY& loc, bool isExecuting) const + { + SurfaceElement* surfaceElement = MapGetSurfaceElementAt(loc); + if (surfaceElement == nullptr) + { + LOG_ERROR("No surface at x = %d, y = %d", loc.x, loc.y); + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_SURFACE_ELEMENT_NOT_FOUND); + } - // Do not allow ownership of park entrance. - if (_ownership == OWNERSHIP_OWNED || _ownership == OWNERSHIP_AVAILABLE) - return res; - - // Allow construction rights available / for sale on park entrances on surface. - // There is no need to check the height if _ownership is 0 (unowned and no rights available). - if (_ownership == OWNERSHIP_CONSTRUCTION_RIGHTS_OWNED || _ownership == OWNERSHIP_CONSTRUCTION_RIGHTS_AVAILABLE) + auto res = Result(); + switch (_setting) + { + case LandSetRightSetting::UnownLand: + if (isExecuting) { - if (entranceElement->BaseHeight - 3 > surfaceElement->BaseHeight - || entranceElement->BaseHeight < surfaceElement->BaseHeight) - { + surfaceElement->SetOwnership( + surfaceElement->GetOwnership() & ~(OWNERSHIP_OWNED | OWNERSHIP_CONSTRUCTION_RIGHTS_OWNED)); + Park::UpdateFencesAroundTile(loc); + } + return res; + case LandSetRightSetting::UnownConstructionRights: + if (isExecuting) + { + surfaceElement->SetOwnership(surfaceElement->GetOwnership() & ~OWNERSHIP_CONSTRUCTION_RIGHTS_OWNED); + uint16_t baseZ = surfaceElement->GetBaseZ(); + MapInvalidateTile({ loc, baseZ, baseZ + 16 }); + } + return res; + case LandSetRightSetting::SetForSale: + if (isExecuting) + { + surfaceElement->SetOwnership(surfaceElement->GetOwnership() | OWNERSHIP_AVAILABLE); + uint16_t baseZ = surfaceElement->GetBaseZ(); + MapInvalidateTile({ loc, baseZ, baseZ + 16 }); + } + return res; + case LandSetRightSetting::SetConstructionRightsForSale: + if (isExecuting) + { + surfaceElement->SetOwnership(surfaceElement->GetOwnership() | OWNERSHIP_CONSTRUCTION_RIGHTS_AVAILABLE); + uint16_t baseZ = surfaceElement->GetBaseZ(); + MapInvalidateTile({ loc, baseZ, baseZ + 16 }); + } + return res; + case LandSetRightSetting::SetOwnershipWithChecks: + { + if (_ownership == surfaceElement->GetOwnership()) + { + return res; + } + + for (auto* entranceElement : TileElementsView(loc)) + { + if (entranceElement->GetEntranceType() != ENTRANCE_TYPE_PARK_ENTRANCE) + continue; + + // Do not allow ownership of park entrance. + if (_ownership == OWNERSHIP_OWNED || _ownership == OWNERSHIP_AVAILABLE) return res; + + // Allow construction rights available / for sale on park entrances on surface. + // There is no need to check the height if _ownership is 0 (unowned and no rights available). + if (_ownership == OWNERSHIP_CONSTRUCTION_RIGHTS_OWNED + || _ownership == OWNERSHIP_CONSTRUCTION_RIGHTS_AVAILABLE) + { + if (entranceElement->BaseHeight - 3 > surfaceElement->BaseHeight + || entranceElement->BaseHeight < surfaceElement->BaseHeight) + { + return res; + } } } - } - auto& gameState = getGameState(); - const uint8_t currentOwnership = surfaceElement->GetOwnership(); + auto& gameState = getGameState(); + const uint8_t currentOwnership = surfaceElement->GetOwnership(); - // Are land rights or construction rights currently owned? - if (!(currentOwnership & (OWNERSHIP_OWNED | OWNERSHIP_CONSTRUCTION_RIGHTS_OWNED))) - { - // Buying land - if (!(currentOwnership & OWNERSHIP_OWNED) && (_ownership & OWNERSHIP_OWNED)) - res.Cost = gameState.scenarioOptions.landPrice; - - // Buying construction rights - if (!(currentOwnership & OWNERSHIP_CONSTRUCTION_RIGHTS_OWNED) - && (_ownership & OWNERSHIP_CONSTRUCTION_RIGHTS_OWNED)) - res.Cost = gameState.scenarioOptions.constructionRightsPrice; - } - else - { - // Selling land - if ((currentOwnership & OWNERSHIP_OWNED) && !(_ownership & OWNERSHIP_OWNED)) - res.Cost = -gameState.scenarioOptions.landPrice; - - // Selling construction rights - if ((currentOwnership & OWNERSHIP_CONSTRUCTION_RIGHTS_OWNED) - && !(_ownership & OWNERSHIP_CONSTRUCTION_RIGHTS_OWNED)) - res.Cost = -gameState.scenarioOptions.constructionRightsPrice; - } - - if (isExecuting) - { - if (_ownership != OWNERSHIP_UNOWNED) + // Are land rights or construction rights currently owned? + if (!(currentOwnership & (OWNERSHIP_OWNED | OWNERSHIP_CONSTRUCTION_RIGHTS_OWNED))) { - gameState.peepSpawns.erase( - std::remove_if( - gameState.peepSpawns.begin(), gameState.peepSpawns.end(), - [x = loc.x, y = loc.y](const auto& spawn) { - return floor2(spawn.x, 32) == x && floor2(spawn.y, 32) == y; - }), - gameState.peepSpawns.end()); + // Buying land + if (!(currentOwnership & OWNERSHIP_OWNED) && (_ownership & OWNERSHIP_OWNED)) + res.Cost = gameState.scenarioOptions.landPrice; + + // Buying construction rights + if (!(currentOwnership & OWNERSHIP_CONSTRUCTION_RIGHTS_OWNED) + && (_ownership & OWNERSHIP_CONSTRUCTION_RIGHTS_OWNED)) + res.Cost = gameState.scenarioOptions.constructionRightsPrice; } - surfaceElement->SetOwnership(_ownership); - Park::UpdateFencesAroundTile(loc); - gMapLandRightsUpdateSuccess = true; + else + { + // Selling land + if ((currentOwnership & OWNERSHIP_OWNED) && !(_ownership & OWNERSHIP_OWNED)) + res.Cost = -gameState.scenarioOptions.landPrice; + + // Selling construction rights + if ((currentOwnership & OWNERSHIP_CONSTRUCTION_RIGHTS_OWNED) + && !(_ownership & OWNERSHIP_CONSTRUCTION_RIGHTS_OWNED)) + res.Cost = -gameState.scenarioOptions.constructionRightsPrice; + } + + if (isExecuting) + { + if (_ownership != OWNERSHIP_UNOWNED) + { + gameState.peepSpawns.erase( + std::remove_if( + gameState.peepSpawns.begin(), gameState.peepSpawns.end(), + [x = loc.x, y = loc.y](const auto& spawn) { + return floor2(spawn.x, 32) == x && floor2(spawn.y, 32) == y; + }), + gameState.peepSpawns.end()); + } + surfaceElement->SetOwnership(_ownership); + Park::UpdateFencesAroundTile(loc); + gMapLandRightsUpdateSuccess = true; + } + return res; } - return res; + default: + LOG_ERROR("Invalid setting %u to set land rights", _setting); + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_VALUE_OUT_OF_RANGE); } - default: - LOG_ERROR("Invalid setting %u to set land rights", _setting); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_VALUE_OUT_OF_RANGE); } -} +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/LandSetRightsAction.h b/src/openrct2/actions/LandSetRightsAction.h index 63fc9ebb49..bf804da984 100644 --- a/src/openrct2/actions/LandSetRightsAction.h +++ b/src/openrct2/actions/LandSetRightsAction.h @@ -11,37 +11,40 @@ #include "GameAction.h" -enum class LandSetRightSetting : uint8_t +namespace OpenRCT2::GameActions { - UnownLand, - UnownConstructionRights, - SetForSale, - SetConstructionRightsForSale, - SetOwnershipWithChecks, - Count -}; + enum class LandSetRightSetting : uint8_t + { + UnownLand, + UnownConstructionRights, + SetForSale, + SetConstructionRightsForSale, + SetOwnershipWithChecks, + Count + }; -class LandSetRightsAction final : public GameActionBase -{ -private: - MapRange _range; - LandSetRightSetting _setting{ LandSetRightSetting::Count }; - uint8_t _ownership{}; + class LandSetRightsAction final : public GameActionBase + { + private: + MapRange _range; + LandSetRightSetting _setting{ LandSetRightSetting::Count }; + uint8_t _ownership{}; -public: - LandSetRightsAction() = default; - LandSetRightsAction(const MapRange& range, LandSetRightSetting setting, uint8_t ownership = 0); - LandSetRightsAction(const CoordsXY& coord, LandSetRightSetting setting, uint8_t ownership = 0); + public: + LandSetRightsAction() = default; + LandSetRightsAction(const MapRange& range, LandSetRightSetting setting, uint8_t ownership = 0); + LandSetRightsAction(const CoordsXY& coord, LandSetRightSetting setting, uint8_t ownership = 0); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; -private: - OpenRCT2::GameActions::Result QueryExecute(bool isExecuting) const; - OpenRCT2::GameActions::Result MapBuyLandRightsForTile(const CoordsXY& loc, bool isExecuting) const; -}; + private: + Result QueryExecute(bool isExecuting) const; + Result MapBuyLandRightsForTile(const CoordsXY& loc, bool isExecuting) const; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/LandSmoothAction.cpp b/src/openrct2/actions/LandSmoothAction.cpp index 6a1701e8d6..af078b5dc6 100644 --- a/src/openrct2/actions/LandSmoothAction.cpp +++ b/src/openrct2/actions/LandSmoothAction.cpp @@ -28,617 +28,629 @@ #include -using namespace OpenRCT2; - -LandSmoothAction::LandSmoothAction(const CoordsXY& coords, MapRange range, uint8_t selectionType, bool isLowering) - : _coords(coords) - , _range(range) - , _selectionType(selectionType) - , _isLowering(isLowering) +namespace OpenRCT2::GameActions { -} - -void LandSmoothAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit(_coords); - visitor.Visit(_range); - visitor.Visit("selectionType", _selectionType); - visitor.Visit("isLowering", _isLowering); -} - -uint16_t LandSmoothAction::GetActionFlags() const -{ - return GameAction::GetActionFlags(); -} - -void LandSmoothAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_coords) << DS_TAG(_range) << DS_TAG(_selectionType) << DS_TAG(_isLowering); -} - -GameActions::Result LandSmoothAction::Query() const -{ - return SmoothLand(false); -} - -GameActions::Result LandSmoothAction::Execute() const -{ - return SmoothLand(true); -} - -GameActions::Result LandSmoothAction::SmoothLandTile( - int32_t direction, bool isExecuting, const CoordsXY& loc, SurfaceElement* surfaceElement) const -{ - int32_t targetBaseZ = surfaceElement->BaseHeight; - int32_t slope = surfaceElement->GetSlope(); - if (_isLowering) + LandSmoothAction::LandSmoothAction(const CoordsXY& coords, MapRange range, uint8_t selectionType, bool isLowering) + : _coords(coords) + , _range(range) + , _selectionType(selectionType) + , _isLowering(isLowering) { - slope = LowerSurfaceCornerFlags(direction, slope); - if (slope & kTileSlopeRaiseOrLowerBaseHeight) + } + + void LandSmoothAction::AcceptParameters(GameActionParameterVisitor& visitor) + { + visitor.Visit(_coords); + visitor.Visit(_range); + visitor.Visit("selectionType", _selectionType); + visitor.Visit("isLowering", _isLowering); + } + + uint16_t LandSmoothAction::GetActionFlags() const + { + return GameAction::GetActionFlags(); + } + + void LandSmoothAction::Serialise(DataSerialiser& stream) + { + GameAction::Serialise(stream); + + stream << DS_TAG(_coords) << DS_TAG(_range) << DS_TAG(_selectionType) << DS_TAG(_isLowering); + } + + Result LandSmoothAction::Query() const + { + return SmoothLand(false); + } + + Result LandSmoothAction::Execute() const + { + return SmoothLand(true); + } + + Result LandSmoothAction::SmoothLandTile( + int32_t direction, bool isExecuting, const CoordsXY& loc, SurfaceElement* surfaceElement) const + { + int32_t targetBaseZ = surfaceElement->BaseHeight; + int32_t slope = surfaceElement->GetSlope(); + if (_isLowering) { - targetBaseZ -= 2; - slope &= ~kTileSlopeRaiseOrLowerBaseHeight; - } - } - else - { - slope = RaiseSurfaceCornerFlags(direction, slope); - if (slope & kTileSlopeRaiseOrLowerBaseHeight) - { - targetBaseZ += 2; - slope &= ~kTileSlopeRaiseOrLowerBaseHeight; - } - } - - auto landSetHeightAction = LandSetHeightAction(loc, targetBaseZ, slope); - landSetHeightAction.SetFlags(GetFlags()); - auto res = isExecuting ? GameActions::ExecuteNested(&landSetHeightAction) : GameActions::QueryNested(&landSetHeightAction); - - return res; -} - -money64 LandSmoothAction::SmoothLandRowByEdge( - bool isExecuting, const CoordsXY& loc, int32_t expectedLandHeight1, int32_t expectedLandHeight2, int32_t stepX, - int32_t stepY, int32_t direction1, int32_t direction2, int32_t checkDirection1, int32_t checkDirection2) const -{ - uint8_t shouldContinue = 0xF; - int32_t landChangePerTile = _isLowering ? 2 : -2; - money64 totalCost = 0; - - // check if we need to start at all - if (!LocationValid(loc) || !LocationValid({ loc.x + stepX, loc.y + stepY })) - { - return 0; - } - auto surfaceElement = MapGetSurfaceElementAt(loc); - auto nextSurfaceElement = MapGetSurfaceElementAt(CoordsXY{ loc.x + stepX, loc.y + stepY }); - if (surfaceElement == nullptr || nextSurfaceElement == nullptr) - { - return 0; - } - if (TileElementGetCornerHeight(surfaceElement, checkDirection1) != expectedLandHeight1 + landChangePerTile) - { - shouldContinue &= ~0x1; - } - if (TileElementGetCornerHeight(surfaceElement, checkDirection2) != expectedLandHeight2 + landChangePerTile) - { - shouldContinue &= ~0x2; - } - if (TileElementGetCornerHeight(surfaceElement, checkDirection1) - != TileElementGetCornerHeight(nextSurfaceElement, direction1)) - { - shouldContinue &= ~0x1; - } - if (TileElementGetCornerHeight(surfaceElement, checkDirection2) - != TileElementGetCornerHeight(nextSurfaceElement, direction2)) - { - shouldContinue &= ~0x2; - } - auto nextLoc = loc; - while ((shouldContinue & 0x3) != 0) - { - shouldContinue = ((shouldContinue << 2) | 0x3) & shouldContinue; - nextLoc.x += stepX; - nextLoc.y += stepY; - // check if we need to continue after raising the current tile - // this needs to be checked before the tile is changed - if (!LocationValid({ nextLoc.x + stepX, nextLoc.y + stepY })) - { - shouldContinue &= ~0x3; + slope = LowerSurfaceCornerFlags(direction, slope); + if (slope & kTileSlopeRaiseOrLowerBaseHeight) + { + targetBaseZ -= 2; + slope &= ~kTileSlopeRaiseOrLowerBaseHeight; + } } else { - surfaceElement = nextSurfaceElement; - nextSurfaceElement = MapGetSurfaceElementAt(CoordsXY{ nextLoc.x + stepX, nextLoc.y + stepY }); - if (nextSurfaceElement == nullptr) + slope = RaiseSurfaceCornerFlags(direction, slope); + if (slope & kTileSlopeRaiseOrLowerBaseHeight) + { + targetBaseZ += 2; + slope &= ~kTileSlopeRaiseOrLowerBaseHeight; + } + } + + auto landSetHeightAction = LandSetHeightAction(loc, targetBaseZ, slope); + landSetHeightAction.SetFlags(GetFlags()); + auto res = isExecuting ? ExecuteNested(&landSetHeightAction) : QueryNested(&landSetHeightAction); + + return res; + } + + money64 LandSmoothAction::SmoothLandRowByEdge( + bool isExecuting, const CoordsXY& loc, int32_t expectedLandHeight1, int32_t expectedLandHeight2, int32_t stepX, + int32_t stepY, int32_t direction1, int32_t direction2, int32_t checkDirection1, int32_t checkDirection2) const + { + uint8_t shouldContinue = 0xF; + int32_t landChangePerTile = _isLowering ? 2 : -2; + money64 totalCost = 0; + + // check if we need to start at all + if (!LocationValid(loc) || !LocationValid({ loc.x + stepX, loc.y + stepY })) + { + return 0; + } + auto surfaceElement = MapGetSurfaceElementAt(loc); + auto nextSurfaceElement = MapGetSurfaceElementAt(CoordsXY{ loc.x + stepX, loc.y + stepY }); + if (surfaceElement == nullptr || nextSurfaceElement == nullptr) + { + return 0; + } + if (TileElementGetCornerHeight(surfaceElement, checkDirection1) != expectedLandHeight1 + landChangePerTile) + { + shouldContinue &= ~0x1; + } + if (TileElementGetCornerHeight(surfaceElement, checkDirection2) != expectedLandHeight2 + landChangePerTile) + { + shouldContinue &= ~0x2; + } + if (TileElementGetCornerHeight(surfaceElement, checkDirection1) + != TileElementGetCornerHeight(nextSurfaceElement, direction1)) + { + shouldContinue &= ~0x1; + } + if (TileElementGetCornerHeight(surfaceElement, checkDirection2) + != TileElementGetCornerHeight(nextSurfaceElement, direction2)) + { + shouldContinue &= ~0x2; + } + auto nextLoc = loc; + while ((shouldContinue & 0x3) != 0) + { + shouldContinue = ((shouldContinue << 2) | 0x3) & shouldContinue; + nextLoc.x += stepX; + nextLoc.y += stepY; + // check if we need to continue after raising the current tile + // this needs to be checked before the tile is changed + if (!LocationValid({ nextLoc.x + stepX, nextLoc.y + stepY })) { shouldContinue &= ~0x3; } - if (TileElementGetCornerHeight(surfaceElement, direction1) + landChangePerTile - != TileElementGetCornerHeight(surfaceElement, checkDirection1)) + else { - shouldContinue &= ~0x1; - } - if (TileElementGetCornerHeight(surfaceElement, direction2) + landChangePerTile - != TileElementGetCornerHeight(surfaceElement, checkDirection2)) - { - shouldContinue &= ~0x2; - } - if ((shouldContinue & 0x1) - && TileElementGetCornerHeight(surfaceElement, checkDirection1) - != TileElementGetCornerHeight(nextSurfaceElement, direction1)) - { - shouldContinue &= ~0x1; - } - if ((shouldContinue & 0x2) - && TileElementGetCornerHeight(surfaceElement, checkDirection2) - != TileElementGetCornerHeight(nextSurfaceElement, direction2)) - { - shouldContinue &= ~0x2; - } - } - expectedLandHeight1 += landChangePerTile; - - // change land of current tile - int32_t targetBaseZ = surfaceElement->BaseHeight; - int32_t slope = surfaceElement->GetSlope(); - int32_t oldSlope = slope; - if (_isLowering) - { - if (shouldContinue & 0x4) - { - slope = LowerSurfaceCornerFlags(direction1, slope); - if (slope & kTileSlopeRaiseOrLowerBaseHeight) + surfaceElement = nextSurfaceElement; + nextSurfaceElement = MapGetSurfaceElementAt(CoordsXY{ nextLoc.x + stepX, nextLoc.y + stepY }); + if (nextSurfaceElement == nullptr) { - targetBaseZ -= 2; - slope &= ~kTileSlopeRaiseOrLowerBaseHeight; + shouldContinue &= ~0x3; + } + if (TileElementGetCornerHeight(surfaceElement, direction1) + landChangePerTile + != TileElementGetCornerHeight(surfaceElement, checkDirection1)) + { + shouldContinue &= ~0x1; + } + if (TileElementGetCornerHeight(surfaceElement, direction2) + landChangePerTile + != TileElementGetCornerHeight(surfaceElement, checkDirection2)) + { + shouldContinue &= ~0x2; + } + if ((shouldContinue & 0x1) + && TileElementGetCornerHeight(surfaceElement, checkDirection1) + != TileElementGetCornerHeight(nextSurfaceElement, direction1)) + { + shouldContinue &= ~0x1; + } + if ((shouldContinue & 0x2) + && TileElementGetCornerHeight(surfaceElement, checkDirection2) + != TileElementGetCornerHeight(nextSurfaceElement, direction2)) + { + shouldContinue &= ~0x2; } } - if ((shouldContinue & 0x8) - && MapGetCornerHeight(surfaceElement->BaseHeight, oldSlope, direction2) - == MapGetCornerHeight(targetBaseZ, slope, direction2)) + expectedLandHeight1 += landChangePerTile; + + // change land of current tile + int32_t targetBaseZ = surfaceElement->BaseHeight; + int32_t slope = surfaceElement->GetSlope(); + int32_t oldSlope = slope; + if (_isLowering) { - slope = LowerSurfaceCornerFlags(direction2, slope); - if (slope & kTileSlopeRaiseOrLowerBaseHeight) + if (shouldContinue & 0x4) { - targetBaseZ -= 2; - slope &= ~kTileSlopeRaiseOrLowerBaseHeight; + slope = LowerSurfaceCornerFlags(direction1, slope); + if (slope & kTileSlopeRaiseOrLowerBaseHeight) + { + targetBaseZ -= 2; + slope &= ~kTileSlopeRaiseOrLowerBaseHeight; + } } - } - } - else - { - if (shouldContinue & 0x4) - { - slope = RaiseSurfaceCornerFlags(direction1, slope); - if (slope & kTileSlopeRaiseOrLowerBaseHeight) + if ((shouldContinue & 0x8) + && MapGetCornerHeight(surfaceElement->BaseHeight, oldSlope, direction2) + == MapGetCornerHeight(targetBaseZ, slope, direction2)) { - targetBaseZ += 2; - slope &= ~kTileSlopeRaiseOrLowerBaseHeight; + slope = LowerSurfaceCornerFlags(direction2, slope); + if (slope & kTileSlopeRaiseOrLowerBaseHeight) + { + targetBaseZ -= 2; + slope &= ~kTileSlopeRaiseOrLowerBaseHeight; + } } } - if ((shouldContinue & 0x8) - && MapGetCornerHeight(surfaceElement->BaseHeight, oldSlope, direction2) - == MapGetCornerHeight(targetBaseZ, slope, direction2)) - { - slope = RaiseSurfaceCornerFlags(direction2, slope); - if (slope & kTileSlopeRaiseOrLowerBaseHeight) - { - targetBaseZ += 2; - slope &= ~kTileSlopeRaiseOrLowerBaseHeight; - } - } - } - auto landSetHeightAction = LandSetHeightAction(nextLoc, targetBaseZ, slope); - landSetHeightAction.SetFlags(GetFlags()); - auto res = isExecuting ? GameActions::ExecuteNested(&landSetHeightAction) - : GameActions::QueryNested(&landSetHeightAction); - if (res.Error == GameActions::Status::Ok) - { - totalCost += res.Cost; - } - } - return totalCost; -} - -money64 LandSmoothAction::SmoothLandRowByCorner( - bool isExecuting, const CoordsXY& loc, int32_t expectedLandHeight, int32_t stepX, int32_t stepY, int32_t direction, - int32_t checkDirection) const -{ - bool shouldContinue = true; - money64 totalCost = 0; - int32_t landChangePerTile; - if (stepX == 0 || stepY == 0) - { - landChangePerTile = _isLowering ? 2 : -2; - } - else - { - landChangePerTile = _isLowering ? 4 : -4; - } - - // check if we need to start at all - if (!LocationValid(loc) || !LocationValid({ loc.x + stepX, loc.y + stepY })) - { - return 0; - } - auto surfaceElement = MapGetSurfaceElementAt(loc); - auto nextSurfaceElement = MapGetSurfaceElementAt(CoordsXY{ loc.x + stepX, loc.y + stepY }); - if (surfaceElement == nullptr || nextSurfaceElement == nullptr) - { - return 0; - } - if (TileElementGetCornerHeight(surfaceElement, checkDirection) != expectedLandHeight + (_isLowering ? 2 : -2)) - { - return 0; - } - if (TileElementGetCornerHeight(surfaceElement, checkDirection) != TileElementGetCornerHeight(nextSurfaceElement, direction)) - { - return 0; - } - - auto nextLoc = loc; - while (shouldContinue) - { - nextLoc.x += stepX; - nextLoc.y += stepY; - // check if we need to continue after raising the current tile - // this needs to be checked before the tile is changed - if (!LocationValid({ nextLoc.x + stepX, nextLoc.y + stepY })) - { - shouldContinue = false; - } - else - { - surfaceElement = nextSurfaceElement; - nextSurfaceElement = MapGetSurfaceElementAt(CoordsXY{ nextLoc.x + stepX, nextLoc.y + stepY }); - if (nextSurfaceElement == nullptr) - { - shouldContinue = false; - } - if (TileElementGetCornerHeight(surfaceElement, direction) + landChangePerTile - != TileElementGetCornerHeight(surfaceElement, checkDirection)) - { - shouldContinue = false; - } - if (shouldContinue - && TileElementGetCornerHeight(surfaceElement, checkDirection) - != TileElementGetCornerHeight(nextSurfaceElement, direction)) - { - shouldContinue = false; - } - } - if (stepX * stepY != 0) - { - totalCost += SmoothLandRowByCorner( - isExecuting, nextLoc, expectedLandHeight + (landChangePerTile / 2), 0, stepY, direction, checkDirection ^ 3); - totalCost += SmoothLandRowByCorner( - isExecuting, nextLoc, expectedLandHeight + (landChangePerTile / 2), stepX, 0, direction, checkDirection ^ 1); - } - expectedLandHeight += landChangePerTile; - // change land of current tile - auto result = SmoothLandTile(direction, isExecuting, nextLoc, surfaceElement); - if (result.Error == GameActions::Status::Ok) - { - totalCost += result.Cost; - } - } - return totalCost; -} - -GameActions::Result LandSmoothAction::SmoothLand(bool isExecuting) const -{ - const bool raiseLand = !_isLowering; - const int32_t selectionType = _selectionType; - const int32_t heightOffset = raiseLand ? 2 : -2; - - auto normRange = _range.Normalise(); - // Cap bounds to map - auto l = std::max(normRange.GetLeft(), 32); - auto t = std::max(normRange.GetTop(), 32); - auto r = std::clamp(normRange.GetRight(), 0, kMaximumTileStartXY); - auto b = std::clamp(normRange.GetBottom(), 0, kMaximumTileStartXY); - auto validRange = MapRange{ l, t, r, b }; - - int32_t centreZ = TileElementHeight(_coords); - - auto res = GameActions::Result(); - res.ErrorTitle = kErrorTitles[_isLowering ? 0 : 1]; - res.Expenditure = ExpenditureType::landscaping; - res.Position = { _coords.x, _coords.y, centreZ }; - - // Do the smoothing - switch (selectionType) - { - case MAP_SELECT_TYPE_FULL: - { - uint8_t minHeight = heightOffset + MapGetLowestLandHeight(validRange); - uint8_t maxHeight = heightOffset + MapGetHighestLandHeight(validRange); - - // Smooth the 4 corners - { // top-left - auto surfaceElement = MapGetSurfaceElementAt(CoordsXY{ validRange.GetLeft(), validRange.GetTop() }); - if (surfaceElement != nullptr) - { - int32_t z = std::clamp( - static_cast(TileElementGetCornerHeight(surfaceElement, 2)), minHeight, maxHeight); - res.Cost += SmoothLandRowByCorner( - isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, -32, -32, 0, 2); - } - } - { // bottom-left - auto surfaceElement = MapGetSurfaceElementAt(CoordsXY{ validRange.GetLeft(), validRange.GetBottom() }); - if (surfaceElement != nullptr) - { - int32_t z = std::clamp( - static_cast(TileElementGetCornerHeight(surfaceElement, 3)), minHeight, maxHeight); - res.Cost += SmoothLandRowByCorner( - isExecuting, { validRange.GetLeft(), validRange.GetBottom() }, z, -32, 32, 1, 3); - } - } - { // bottom-right - auto surfaceElement = MapGetSurfaceElementAt(CoordsXY{ validRange.GetRight(), validRange.GetBottom() }); - if (surfaceElement != nullptr) - { - int32_t z = std::clamp( - static_cast(TileElementGetCornerHeight(surfaceElement, 0)), minHeight, maxHeight); - res.Cost += SmoothLandRowByCorner( - isExecuting, { validRange.GetRight(), validRange.GetBottom() }, z, 32, 32, 2, 0); - } - } - { // top-right - auto surfaceElement = MapGetSurfaceElementAt(CoordsXY{ validRange.GetRight(), validRange.GetTop() }); - if (surfaceElement != nullptr) - { - int32_t z = std::clamp( - static_cast(TileElementGetCornerHeight(surfaceElement, 1)), minHeight, maxHeight); - res.Cost += SmoothLandRowByCorner( - isExecuting, { validRange.GetRight(), validRange.GetTop() }, z, 32, -32, 3, 1); - } - } - - // Smooth the edges - int32_t z1, z2; - for (int32_t y = validRange.GetTop(); y <= validRange.GetBottom(); y += kCoordsXYStep) - { - auto surfaceElement = MapGetSurfaceElementAt(CoordsXY{ validRange.GetLeft(), y }); - if (surfaceElement != nullptr) - { - z1 = std::clamp(static_cast(TileElementGetCornerHeight(surfaceElement, 3)), minHeight, maxHeight); - z2 = std::clamp(static_cast(TileElementGetCornerHeight(surfaceElement, 2)), minHeight, maxHeight); - res.Cost += SmoothLandRowByEdge(isExecuting, { validRange.GetLeft(), y }, z1, z2, -32, 0, 0, 1, 3, 2); - } - - surfaceElement = MapGetSurfaceElementAt(CoordsXY{ validRange.GetRight(), y }); - if (surfaceElement != nullptr) - { - z1 = std::clamp(static_cast(TileElementGetCornerHeight(surfaceElement, 1)), minHeight, maxHeight); - z2 = std::clamp(static_cast(TileElementGetCornerHeight(surfaceElement, 0)), minHeight, maxHeight); - res.Cost += SmoothLandRowByEdge(isExecuting, { validRange.GetRight(), y }, z1, z2, 32, 0, 2, 3, 1, 0); - } - } - - for (int32_t x = validRange.GetLeft(); x <= validRange.GetRight(); x += kCoordsXYStep) - { - auto surfaceElement = MapGetSurfaceElementAt(CoordsXY{ x, validRange.GetTop() }); - if (surfaceElement != nullptr) - { - z1 = std::clamp(static_cast(TileElementGetCornerHeight(surfaceElement, 1)), minHeight, maxHeight); - z2 = std::clamp(static_cast(TileElementGetCornerHeight(surfaceElement, 2)), minHeight, maxHeight); - res.Cost += SmoothLandRowByEdge(isExecuting, { x, validRange.GetTop() }, z1, z2, 0, -32, 0, 3, 1, 2); - } - - surfaceElement = MapGetSurfaceElementAt(CoordsXY{ x, validRange.GetBottom() }); - if (surfaceElement != nullptr) - { - z1 = std::clamp(static_cast(TileElementGetCornerHeight(surfaceElement, 0)), minHeight, maxHeight); - z2 = std::clamp(static_cast(TileElementGetCornerHeight(surfaceElement, 3)), minHeight, maxHeight); - res.Cost += SmoothLandRowByEdge(isExecuting, { x, validRange.GetBottom() }, z1, z2, 0, 32, 1, 2, 0, 3); - } - } - break; - } - case MAP_SELECT_TYPE_CORNER_0: - case MAP_SELECT_TYPE_CORNER_1: - case MAP_SELECT_TYPE_CORNER_2: - case MAP_SELECT_TYPE_CORNER_3: - { - auto surfaceElement = MapGetSurfaceElementAt(CoordsXY{ validRange.GetLeft(), validRange.GetTop() }); - if (surfaceElement == nullptr) - break; - uint8_t newBaseZ = surfaceElement->BaseHeight; - uint8_t newSlope = surfaceElement->GetSlope(); - - if (raiseLand) - { - newSlope = RaiseSurfaceCornerFlags(selectionType, newSlope); - } else { - newSlope = LowerSurfaceCornerFlags(selectionType, newSlope); + if (shouldContinue & 0x4) + { + slope = RaiseSurfaceCornerFlags(direction1, slope); + if (slope & kTileSlopeRaiseOrLowerBaseHeight) + { + targetBaseZ += 2; + slope &= ~kTileSlopeRaiseOrLowerBaseHeight; + } + } + if ((shouldContinue & 0x8) + && MapGetCornerHeight(surfaceElement->BaseHeight, oldSlope, direction2) + == MapGetCornerHeight(targetBaseZ, slope, direction2)) + { + slope = RaiseSurfaceCornerFlags(direction2, slope); + if (slope & kTileSlopeRaiseOrLowerBaseHeight) + { + targetBaseZ += 2; + slope &= ~kTileSlopeRaiseOrLowerBaseHeight; + } + } } - - if (newSlope & kTileSlopeRaiseOrLowerBaseHeight) + auto landSetHeightAction = LandSetHeightAction(nextLoc, targetBaseZ, slope); + landSetHeightAction.SetFlags(GetFlags()); + auto res = isExecuting ? ExecuteNested(&landSetHeightAction) : QueryNested(&landSetHeightAction); + if (res.Error == Status::Ok) { - newBaseZ += heightOffset; - newSlope &= ~kTileSlopeRaiseOrLowerBaseHeight; + totalCost += res.Cost; } - - // Smooth the corners - int32_t z = MapGetCornerHeight(newBaseZ, newSlope, 2); - res.Cost += SmoothLandRowByCorner(isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, -32, -32, 0, 2); - z = MapGetCornerHeight(newBaseZ, newSlope, 0); - res.Cost += SmoothLandRowByCorner(isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, 32, 32, 2, 0); - z = MapGetCornerHeight(newBaseZ, newSlope, 3); - res.Cost += SmoothLandRowByCorner(isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, -32, 32, 1, 3); - z = MapGetCornerHeight(newBaseZ, newSlope, 1); - res.Cost += SmoothLandRowByCorner(isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, 32, -32, 3, 1); - - // Smooth the edges - switch (selectionType) - { - case MAP_SELECT_TYPE_CORNER_0: - z = MapGetCornerHeight(newBaseZ, newSlope, 0); - res.Cost += SmoothLandRowByCorner( - isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, 32, 0, 3, 0); - res.Cost += SmoothLandRowByCorner( - isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, 0, 32, 1, 0); - z = MapGetCornerHeight(newBaseZ, newSlope, 3); - res.Cost += SmoothLandRowByCorner( - isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, -32, 0, 0, 3); - z = MapGetCornerHeight(newBaseZ, newSlope, 1); - res.Cost += SmoothLandRowByCorner( - isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, 0, -32, 0, 1); - break; - case MAP_SELECT_TYPE_CORNER_1: - z = MapGetCornerHeight(newBaseZ, newSlope, 1); - res.Cost += SmoothLandRowByCorner( - isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, 32, 0, 2, 1); - res.Cost += SmoothLandRowByCorner( - isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, 0, -32, 0, 1); - z = MapGetCornerHeight(newBaseZ, newSlope, 2); - res.Cost += SmoothLandRowByCorner( - isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, -32, 0, 1, 2); - z = MapGetCornerHeight(newBaseZ, newSlope, 0); - res.Cost += SmoothLandRowByCorner( - isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, 0, 32, 1, 0); - break; - case MAP_SELECT_TYPE_CORNER_2: - z = MapGetCornerHeight(newBaseZ, newSlope, 2); - res.Cost += SmoothLandRowByCorner( - isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, -32, 0, 1, 2); - res.Cost += SmoothLandRowByCorner( - isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, 0, -32, 3, 2); - z = MapGetCornerHeight(newBaseZ, newSlope, 1); - res.Cost += SmoothLandRowByCorner( - isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, 32, 0, 2, 1); - z = MapGetCornerHeight(newBaseZ, newSlope, 3); - res.Cost += SmoothLandRowByCorner( - isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, 0, 32, 2, 3); - break; - case MAP_SELECT_TYPE_CORNER_3: - z = MapGetCornerHeight(newBaseZ, newSlope, 3); - res.Cost += SmoothLandRowByCorner( - isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, -32, 0, 0, 3); - res.Cost += SmoothLandRowByCorner( - isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, 0, 32, 2, 3); - z = MapGetCornerHeight(newBaseZ, newSlope, 0); - res.Cost += SmoothLandRowByCorner( - isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, 32, 0, 3, 0); - z = MapGetCornerHeight(newBaseZ, newSlope, 2); - res.Cost += SmoothLandRowByCorner( - isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, 0, -32, 3, 2); - break; - } - break; } - case MAP_SELECT_TYPE_EDGE_0: - case MAP_SELECT_TYPE_EDGE_1: - case MAP_SELECT_TYPE_EDGE_2: - case MAP_SELECT_TYPE_EDGE_3: + return totalCost; + } + + money64 LandSmoothAction::SmoothLandRowByCorner( + bool isExecuting, const CoordsXY& loc, int32_t expectedLandHeight, int32_t stepX, int32_t stepY, int32_t direction, + int32_t checkDirection) const + { + bool shouldContinue = true; + money64 totalCost = 0; + int32_t landChangePerTile; + if (stepX == 0 || stepY == 0) { - // TODO: Handle smoothing by edge - // Get the two corners to raise - auto surfaceElement = MapGetSurfaceElementAt(CoordsXY{ validRange.GetLeft(), validRange.GetTop() }); - if (surfaceElement == nullptr) - break; - uint8_t newBaseZ = surfaceElement->BaseHeight; - uint8_t oldSlope = surfaceElement->GetSlope(); - int32_t rowIndex = selectionType - (MAP_SELECT_TYPE_EDGE_0 - MAP_SELECT_TYPE_FULL - 1); - uint8_t newSlope = raiseLand ? RaiseSurfaceCornerFlags(rowIndex, oldSlope) - : LowerSurfaceCornerFlags(rowIndex, oldSlope); - - const bool changeBaseHeight = newSlope & kTileSlopeRaiseOrLowerBaseHeight; - if (changeBaseHeight) - { - newBaseZ += heightOffset; - newSlope &= ~kTileSlopeRaiseOrLowerBaseHeight; - } - - const uint8_t edge = selectionType - MAP_SELECT_TYPE_EDGE_0; - - // Table with corners for each edge selection. The first two are the selected corners, the latter - // two are the opposites - static constexpr uint8_t cornerIndices[][4] = { - { 2, 3, 1, 0 }, // MAP_SELECT_TYPE_EDGE_0 - { 3, 0, 2, 1 }, // MAP_SELECT_TYPE_EDGE_1 - { 0, 1, 3, 2 }, // MAP_SELECT_TYPE_EDGE_2 - { 1, 2, 0, 3 }, // MAP_SELECT_TYPE_EDGE_3 - }; - // Big coordinate offsets for the neighbouring tile for the given edge selection - static constexpr CoordsXY stepOffsets[] = { - { -32, 0 }, - { 0, 32 }, - { 32, 0 }, - { 0, -32 }, - }; - - // Smooth higher and lower edges - uint8_t c1 = cornerIndices[edge][0]; - uint8_t c2 = cornerIndices[edge][1]; - uint8_t c3 = cornerIndices[edge][2]; - uint8_t c4 = cornerIndices[edge][3]; - uint8_t z1 = MapGetCornerHeight(newBaseZ, newSlope, c1); - uint8_t z2 = MapGetCornerHeight(newBaseZ, newSlope, c2); - uint8_t z3 = MapGetCornerHeight(newBaseZ, newSlope, c3); - uint8_t z4 = MapGetCornerHeight(newBaseZ, newSlope, c4); - // Smooth the edge at the top of the new slope - res.Cost += SmoothLandRowByEdge( - isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z1, z2, stepOffsets[edge].x, stepOffsets[edge].y, - c3, c4, c1, c2); - // Smooth the edge at the bottom of the new slope - res.Cost += SmoothLandRowByEdge( - isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z3, z4, -stepOffsets[edge].x, -stepOffsets[edge].y, - c1, c2, c3, c4); - - // Smooth corners - res.Cost += SmoothLandRowByCorner( - isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z1, -stepOffsets[edge].y, stepOffsets[edge].x, c2, - c1); - res.Cost += SmoothLandRowByCorner( - isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z2, stepOffsets[edge].y, -stepOffsets[edge].x, c1, - c2); - int32_t z = MapGetCornerHeight(newBaseZ, newSlope, 2); - res.Cost += SmoothLandRowByCorner(isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, -32, -32, 0, 2); - z = MapGetCornerHeight(newBaseZ, newSlope, 0); - res.Cost += SmoothLandRowByCorner(isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, 32, 32, 2, 0); - z = MapGetCornerHeight(newBaseZ, newSlope, 3); - res.Cost += SmoothLandRowByCorner(isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, -32, 32, 1, 3); - z = MapGetCornerHeight(newBaseZ, newSlope, 1); - res.Cost += SmoothLandRowByCorner(isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, 32, -32, 3, 1); - break; + landChangePerTile = _isLowering ? 2 : -2; + } + else + { + landChangePerTile = _isLowering ? 4 : -4; } - default: - LOG_ERROR("Invalid map selection type %u", _selectionType); - return GameActions::Result( - GameActions::Status::InvalidParameters, std::get(res.ErrorTitle), STR_ERR_VALUE_OUT_OF_RANGE); - } // switch selectionType - // Raise / lower the land tool selection area - GameActions::Result result; - if (raiseLand) - { - auto raiseLandAction = LandRaiseAction({ _coords.x, _coords.y }, validRange, selectionType); - raiseLandAction.SetFlags(GetFlags()); - result = isExecuting ? GameActions::ExecuteNested(&raiseLandAction) : GameActions::QueryNested(&raiseLandAction); - } - else - { - auto lowerLandAction = LandLowerAction({ _coords.x, _coords.y }, validRange, selectionType); - lowerLandAction.SetFlags(GetFlags()); - result = isExecuting ? GameActions::ExecuteNested(&lowerLandAction) : GameActions::QueryNested(&lowerLandAction); - } - if (result.Error != GameActions::Status::Ok) - { - return result; + // check if we need to start at all + if (!LocationValid(loc) || !LocationValid({ loc.x + stepX, loc.y + stepY })) + { + return 0; + } + auto surfaceElement = MapGetSurfaceElementAt(loc); + auto nextSurfaceElement = MapGetSurfaceElementAt(CoordsXY{ loc.x + stepX, loc.y + stepY }); + if (surfaceElement == nullptr || nextSurfaceElement == nullptr) + { + return 0; + } + if (TileElementGetCornerHeight(surfaceElement, checkDirection) != expectedLandHeight + (_isLowering ? 2 : -2)) + { + return 0; + } + if (TileElementGetCornerHeight(surfaceElement, checkDirection) + != TileElementGetCornerHeight(nextSurfaceElement, direction)) + { + return 0; + } + + auto nextLoc = loc; + while (shouldContinue) + { + nextLoc.x += stepX; + nextLoc.y += stepY; + // check if we need to continue after raising the current tile + // this needs to be checked before the tile is changed + if (!LocationValid({ nextLoc.x + stepX, nextLoc.y + stepY })) + { + shouldContinue = false; + } + else + { + surfaceElement = nextSurfaceElement; + nextSurfaceElement = MapGetSurfaceElementAt(CoordsXY{ nextLoc.x + stepX, nextLoc.y + stepY }); + if (nextSurfaceElement == nullptr) + { + shouldContinue = false; + } + if (TileElementGetCornerHeight(surfaceElement, direction) + landChangePerTile + != TileElementGetCornerHeight(surfaceElement, checkDirection)) + { + shouldContinue = false; + } + if (shouldContinue + && TileElementGetCornerHeight(surfaceElement, checkDirection) + != TileElementGetCornerHeight(nextSurfaceElement, direction)) + { + shouldContinue = false; + } + } + if (stepX * stepY != 0) + { + totalCost += SmoothLandRowByCorner( + isExecuting, nextLoc, expectedLandHeight + (landChangePerTile / 2), 0, stepY, direction, + checkDirection ^ 3); + totalCost += SmoothLandRowByCorner( + isExecuting, nextLoc, expectedLandHeight + (landChangePerTile / 2), stepX, 0, direction, + checkDirection ^ 1); + } + expectedLandHeight += landChangePerTile; + // change land of current tile + auto result = SmoothLandTile(direction, isExecuting, nextLoc, surfaceElement); + if (result.Error == Status::Ok) + { + totalCost += result.Cost; + } + } + return totalCost; } - if (isExecuting) + Result LandSmoothAction::SmoothLand(bool isExecuting) const { - OpenRCT2::Audio::Play3D(OpenRCT2::Audio::SoundId::PlaceItem, { _coords.x, _coords.y, centreZ }); + const bool raiseLand = !_isLowering; + const int32_t selectionType = _selectionType; + const int32_t heightOffset = raiseLand ? 2 : -2; + + auto normRange = _range.Normalise(); + // Cap bounds to map + auto l = std::max(normRange.GetLeft(), 32); + auto t = std::max(normRange.GetTop(), 32); + auto r = std::clamp(normRange.GetRight(), 0, kMaximumTileStartXY); + auto b = std::clamp(normRange.GetBottom(), 0, kMaximumTileStartXY); + auto validRange = MapRange{ l, t, r, b }; + + int32_t centreZ = TileElementHeight(_coords); + + auto res = Result(); + res.ErrorTitle = kErrorTitles[_isLowering ? 0 : 1]; + res.Expenditure = ExpenditureType::landscaping; + res.Position = { _coords.x, _coords.y, centreZ }; + + // Do the smoothing + switch (selectionType) + { + case MAP_SELECT_TYPE_FULL: + { + uint8_t minHeight = heightOffset + MapGetLowestLandHeight(validRange); + uint8_t maxHeight = heightOffset + MapGetHighestLandHeight(validRange); + + // Smooth the 4 corners + { // top-left + auto surfaceElement = MapGetSurfaceElementAt(CoordsXY{ validRange.GetLeft(), validRange.GetTop() }); + if (surfaceElement != nullptr) + { + int32_t z = std::clamp( + static_cast(TileElementGetCornerHeight(surfaceElement, 2)), minHeight, maxHeight); + res.Cost += SmoothLandRowByCorner( + isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, -32, -32, 0, 2); + } + } + { // bottom-left + auto surfaceElement = MapGetSurfaceElementAt(CoordsXY{ validRange.GetLeft(), validRange.GetBottom() }); + if (surfaceElement != nullptr) + { + int32_t z = std::clamp( + static_cast(TileElementGetCornerHeight(surfaceElement, 3)), minHeight, maxHeight); + res.Cost += SmoothLandRowByCorner( + isExecuting, { validRange.GetLeft(), validRange.GetBottom() }, z, -32, 32, 1, 3); + } + } + { // bottom-right + auto surfaceElement = MapGetSurfaceElementAt(CoordsXY{ validRange.GetRight(), validRange.GetBottom() }); + if (surfaceElement != nullptr) + { + int32_t z = std::clamp( + static_cast(TileElementGetCornerHeight(surfaceElement, 0)), minHeight, maxHeight); + res.Cost += SmoothLandRowByCorner( + isExecuting, { validRange.GetRight(), validRange.GetBottom() }, z, 32, 32, 2, 0); + } + } + { // top-right + auto surfaceElement = MapGetSurfaceElementAt(CoordsXY{ validRange.GetRight(), validRange.GetTop() }); + if (surfaceElement != nullptr) + { + int32_t z = std::clamp( + static_cast(TileElementGetCornerHeight(surfaceElement, 1)), minHeight, maxHeight); + res.Cost += SmoothLandRowByCorner( + isExecuting, { validRange.GetRight(), validRange.GetTop() }, z, 32, -32, 3, 1); + } + } + + // Smooth the edges + int32_t z1, z2; + for (int32_t y = validRange.GetTop(); y <= validRange.GetBottom(); y += kCoordsXYStep) + { + auto surfaceElement = MapGetSurfaceElementAt(CoordsXY{ validRange.GetLeft(), y }); + if (surfaceElement != nullptr) + { + z1 = std::clamp( + static_cast(TileElementGetCornerHeight(surfaceElement, 3)), minHeight, maxHeight); + z2 = std::clamp( + static_cast(TileElementGetCornerHeight(surfaceElement, 2)), minHeight, maxHeight); + res.Cost += SmoothLandRowByEdge(isExecuting, { validRange.GetLeft(), y }, z1, z2, -32, 0, 0, 1, 3, 2); + } + + surfaceElement = MapGetSurfaceElementAt(CoordsXY{ validRange.GetRight(), y }); + if (surfaceElement != nullptr) + { + z1 = std::clamp( + static_cast(TileElementGetCornerHeight(surfaceElement, 1)), minHeight, maxHeight); + z2 = std::clamp( + static_cast(TileElementGetCornerHeight(surfaceElement, 0)), minHeight, maxHeight); + res.Cost += SmoothLandRowByEdge(isExecuting, { validRange.GetRight(), y }, z1, z2, 32, 0, 2, 3, 1, 0); + } + } + + for (int32_t x = validRange.GetLeft(); x <= validRange.GetRight(); x += kCoordsXYStep) + { + auto surfaceElement = MapGetSurfaceElementAt(CoordsXY{ x, validRange.GetTop() }); + if (surfaceElement != nullptr) + { + z1 = std::clamp( + static_cast(TileElementGetCornerHeight(surfaceElement, 1)), minHeight, maxHeight); + z2 = std::clamp( + static_cast(TileElementGetCornerHeight(surfaceElement, 2)), minHeight, maxHeight); + res.Cost += SmoothLandRowByEdge(isExecuting, { x, validRange.GetTop() }, z1, z2, 0, -32, 0, 3, 1, 2); + } + + surfaceElement = MapGetSurfaceElementAt(CoordsXY{ x, validRange.GetBottom() }); + if (surfaceElement != nullptr) + { + z1 = std::clamp( + static_cast(TileElementGetCornerHeight(surfaceElement, 0)), minHeight, maxHeight); + z2 = std::clamp( + static_cast(TileElementGetCornerHeight(surfaceElement, 3)), minHeight, maxHeight); + res.Cost += SmoothLandRowByEdge(isExecuting, { x, validRange.GetBottom() }, z1, z2, 0, 32, 1, 2, 0, 3); + } + } + break; + } + case MAP_SELECT_TYPE_CORNER_0: + case MAP_SELECT_TYPE_CORNER_1: + case MAP_SELECT_TYPE_CORNER_2: + case MAP_SELECT_TYPE_CORNER_3: + { + auto surfaceElement = MapGetSurfaceElementAt(CoordsXY{ validRange.GetLeft(), validRange.GetTop() }); + if (surfaceElement == nullptr) + break; + uint8_t newBaseZ = surfaceElement->BaseHeight; + uint8_t newSlope = surfaceElement->GetSlope(); + + if (raiseLand) + { + newSlope = RaiseSurfaceCornerFlags(selectionType, newSlope); + } + else + { + newSlope = LowerSurfaceCornerFlags(selectionType, newSlope); + } + + if (newSlope & kTileSlopeRaiseOrLowerBaseHeight) + { + newBaseZ += heightOffset; + newSlope &= ~kTileSlopeRaiseOrLowerBaseHeight; + } + + // Smooth the corners + int32_t z = MapGetCornerHeight(newBaseZ, newSlope, 2); + res.Cost += SmoothLandRowByCorner( + isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, -32, -32, 0, 2); + z = MapGetCornerHeight(newBaseZ, newSlope, 0); + res.Cost += SmoothLandRowByCorner(isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, 32, 32, 2, 0); + z = MapGetCornerHeight(newBaseZ, newSlope, 3); + res.Cost += SmoothLandRowByCorner(isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, -32, 32, 1, 3); + z = MapGetCornerHeight(newBaseZ, newSlope, 1); + res.Cost += SmoothLandRowByCorner(isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, 32, -32, 3, 1); + + // Smooth the edges + switch (selectionType) + { + case MAP_SELECT_TYPE_CORNER_0: + z = MapGetCornerHeight(newBaseZ, newSlope, 0); + res.Cost += SmoothLandRowByCorner( + isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, 32, 0, 3, 0); + res.Cost += SmoothLandRowByCorner( + isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, 0, 32, 1, 0); + z = MapGetCornerHeight(newBaseZ, newSlope, 3); + res.Cost += SmoothLandRowByCorner( + isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, -32, 0, 0, 3); + z = MapGetCornerHeight(newBaseZ, newSlope, 1); + res.Cost += SmoothLandRowByCorner( + isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, 0, -32, 0, 1); + break; + case MAP_SELECT_TYPE_CORNER_1: + z = MapGetCornerHeight(newBaseZ, newSlope, 1); + res.Cost += SmoothLandRowByCorner( + isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, 32, 0, 2, 1); + res.Cost += SmoothLandRowByCorner( + isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, 0, -32, 0, 1); + z = MapGetCornerHeight(newBaseZ, newSlope, 2); + res.Cost += SmoothLandRowByCorner( + isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, -32, 0, 1, 2); + z = MapGetCornerHeight(newBaseZ, newSlope, 0); + res.Cost += SmoothLandRowByCorner( + isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, 0, 32, 1, 0); + break; + case MAP_SELECT_TYPE_CORNER_2: + z = MapGetCornerHeight(newBaseZ, newSlope, 2); + res.Cost += SmoothLandRowByCorner( + isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, -32, 0, 1, 2); + res.Cost += SmoothLandRowByCorner( + isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, 0, -32, 3, 2); + z = MapGetCornerHeight(newBaseZ, newSlope, 1); + res.Cost += SmoothLandRowByCorner( + isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, 32, 0, 2, 1); + z = MapGetCornerHeight(newBaseZ, newSlope, 3); + res.Cost += SmoothLandRowByCorner( + isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, 0, 32, 2, 3); + break; + case MAP_SELECT_TYPE_CORNER_3: + z = MapGetCornerHeight(newBaseZ, newSlope, 3); + res.Cost += SmoothLandRowByCorner( + isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, -32, 0, 0, 3); + res.Cost += SmoothLandRowByCorner( + isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, 0, 32, 2, 3); + z = MapGetCornerHeight(newBaseZ, newSlope, 0); + res.Cost += SmoothLandRowByCorner( + isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, 32, 0, 3, 0); + z = MapGetCornerHeight(newBaseZ, newSlope, 2); + res.Cost += SmoothLandRowByCorner( + isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, 0, -32, 3, 2); + break; + } + break; + } + case MAP_SELECT_TYPE_EDGE_0: + case MAP_SELECT_TYPE_EDGE_1: + case MAP_SELECT_TYPE_EDGE_2: + case MAP_SELECT_TYPE_EDGE_3: + { + // TODO: Handle smoothing by edge + // Get the two corners to raise + auto surfaceElement = MapGetSurfaceElementAt(CoordsXY{ validRange.GetLeft(), validRange.GetTop() }); + if (surfaceElement == nullptr) + break; + uint8_t newBaseZ = surfaceElement->BaseHeight; + uint8_t oldSlope = surfaceElement->GetSlope(); + int32_t rowIndex = selectionType - (MAP_SELECT_TYPE_EDGE_0 - MAP_SELECT_TYPE_FULL - 1); + uint8_t newSlope = raiseLand ? RaiseSurfaceCornerFlags(rowIndex, oldSlope) + : LowerSurfaceCornerFlags(rowIndex, oldSlope); + + const bool changeBaseHeight = newSlope & kTileSlopeRaiseOrLowerBaseHeight; + if (changeBaseHeight) + { + newBaseZ += heightOffset; + newSlope &= ~kTileSlopeRaiseOrLowerBaseHeight; + } + + const uint8_t edge = selectionType - MAP_SELECT_TYPE_EDGE_0; + + // Table with corners for each edge selection. The first two are the selected corners, the latter + // two are the opposites + static constexpr uint8_t cornerIndices[][4] = { + { 2, 3, 1, 0 }, // MAP_SELECT_TYPE_EDGE_0 + { 3, 0, 2, 1 }, // MAP_SELECT_TYPE_EDGE_1 + { 0, 1, 3, 2 }, // MAP_SELECT_TYPE_EDGE_2 + { 1, 2, 0, 3 }, // MAP_SELECT_TYPE_EDGE_3 + }; + // Big coordinate offsets for the neighbouring tile for the given edge selection + static constexpr CoordsXY stepOffsets[] = { + { -32, 0 }, + { 0, 32 }, + { 32, 0 }, + { 0, -32 }, + }; + + // Smooth higher and lower edges + uint8_t c1 = cornerIndices[edge][0]; + uint8_t c2 = cornerIndices[edge][1]; + uint8_t c3 = cornerIndices[edge][2]; + uint8_t c4 = cornerIndices[edge][3]; + uint8_t z1 = MapGetCornerHeight(newBaseZ, newSlope, c1); + uint8_t z2 = MapGetCornerHeight(newBaseZ, newSlope, c2); + uint8_t z3 = MapGetCornerHeight(newBaseZ, newSlope, c3); + uint8_t z4 = MapGetCornerHeight(newBaseZ, newSlope, c4); + // Smooth the edge at the top of the new slope + res.Cost += SmoothLandRowByEdge( + isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z1, z2, stepOffsets[edge].x, + stepOffsets[edge].y, c3, c4, c1, c2); + // Smooth the edge at the bottom of the new slope + res.Cost += SmoothLandRowByEdge( + isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z3, z4, -stepOffsets[edge].x, + -stepOffsets[edge].y, c1, c2, c3, c4); + + // Smooth corners + res.Cost += SmoothLandRowByCorner( + isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z1, -stepOffsets[edge].y, stepOffsets[edge].x, + c2, c1); + res.Cost += SmoothLandRowByCorner( + isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z2, stepOffsets[edge].y, -stepOffsets[edge].x, + c1, c2); + int32_t z = MapGetCornerHeight(newBaseZ, newSlope, 2); + res.Cost += SmoothLandRowByCorner( + isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, -32, -32, 0, 2); + z = MapGetCornerHeight(newBaseZ, newSlope, 0); + res.Cost += SmoothLandRowByCorner(isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, 32, 32, 2, 0); + z = MapGetCornerHeight(newBaseZ, newSlope, 3); + res.Cost += SmoothLandRowByCorner(isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, -32, 32, 1, 3); + z = MapGetCornerHeight(newBaseZ, newSlope, 1); + res.Cost += SmoothLandRowByCorner(isExecuting, { validRange.GetLeft(), validRange.GetTop() }, z, 32, -32, 3, 1); + break; + } + default: + LOG_ERROR("Invalid map selection type %u", _selectionType); + return Result(Status::InvalidParameters, std::get(res.ErrorTitle), STR_ERR_VALUE_OUT_OF_RANGE); + } // switch selectionType + + // Raise / lower the land tool selection area + Result result; + if (raiseLand) + { + auto raiseLandAction = LandRaiseAction({ _coords.x, _coords.y }, validRange, selectionType); + raiseLandAction.SetFlags(GetFlags()); + result = isExecuting ? ExecuteNested(&raiseLandAction) : QueryNested(&raiseLandAction); + } + else + { + auto lowerLandAction = LandLowerAction({ _coords.x, _coords.y }, validRange, selectionType); + lowerLandAction.SetFlags(GetFlags()); + result = isExecuting ? ExecuteNested(&lowerLandAction) : QueryNested(&lowerLandAction); + } + if (result.Error != Status::Ok) + { + return result; + } + + if (isExecuting) + { + Audio::Play3D(Audio::SoundId::PlaceItem, { _coords.x, _coords.y, centreZ }); + } + res.Cost += result.Cost; + return res; } - res.Cost += result.Cost; - return res; -} +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/LandSmoothAction.h b/src/openrct2/actions/LandSmoothAction.h index 2af68946cf..9889a63f41 100644 --- a/src/openrct2/actions/LandSmoothAction.h +++ b/src/openrct2/actions/LandSmoothAction.h @@ -11,39 +11,41 @@ #include "GameAction.h" -class LandSmoothAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - CoordsXY _coords; - MapRange _range; - uint8_t _selectionType{}; - bool _isLowering{}; + class LandSmoothAction final : public GameActionBase + { + private: + CoordsXY _coords; + MapRange _range; + uint8_t _selectionType{}; + bool _isLowering{}; - constexpr static StringId kErrorTitles[] = { - STR_CANT_LOWER_LAND_HERE, - STR_CANT_RAISE_LAND_HERE, + constexpr static StringId kErrorTitles[] = { + STR_CANT_LOWER_LAND_HERE, + STR_CANT_RAISE_LAND_HERE, + }; + + public: + LandSmoothAction() = default; + LandSmoothAction(const CoordsXY& coords, MapRange range, uint8_t selectionType, bool isLowering); + + void AcceptParameters(GameActionParameterVisitor& visitor) override; + + uint16_t GetActionFlags() const override; + + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; + + private: + Result SmoothLandTile(int32_t direction, bool isExecuting, const CoordsXY& loc, SurfaceElement* surfaceElement) const; + money64 SmoothLandRowByEdge( + bool isExecuting, const CoordsXY& loc, int32_t expectedLandHeight1, int32_t expectedLandHeight2, int32_t stepX, + int32_t stepY, int32_t direction1, int32_t direction2, int32_t checkDirection1, int32_t checkDirection2) const; + money64 SmoothLandRowByCorner( + bool isExecuting, const CoordsXY& loc, int32_t expectedLandHeight, int32_t stepX, int32_t stepY, int32_t direction, + int32_t checkDirection) const; + Result SmoothLand(bool isExecuting) const; }; - -public: - LandSmoothAction() = default; - LandSmoothAction(const CoordsXY& coords, MapRange range, uint8_t selectionType, bool isLowering); - - void AcceptParameters(GameActionParameterVisitor& visitor) override; - - uint16_t GetActionFlags() const override; - - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; - -private: - OpenRCT2::GameActions::Result SmoothLandTile( - int32_t direction, bool isExecuting, const CoordsXY& loc, OpenRCT2::SurfaceElement* surfaceElement) const; - money64 SmoothLandRowByEdge( - bool isExecuting, const CoordsXY& loc, int32_t expectedLandHeight1, int32_t expectedLandHeight2, int32_t stepX, - int32_t stepY, int32_t direction1, int32_t direction2, int32_t checkDirection1, int32_t checkDirection2) const; - money64 SmoothLandRowByCorner( - bool isExecuting, const CoordsXY& loc, int32_t expectedLandHeight, int32_t stepX, int32_t stepY, int32_t direction, - int32_t checkDirection) const; - OpenRCT2::GameActions::Result SmoothLand(bool isExecuting) const; -}; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/LargeSceneryPlaceAction.cpp b/src/openrct2/actions/LargeSceneryPlaceAction.cpp index 9b93bdf47d..273bad98c0 100644 --- a/src/openrct2/actions/LargeSceneryPlaceAction.cpp +++ b/src/openrct2/actions/LargeSceneryPlaceAction.cpp @@ -28,376 +28,369 @@ #include "../world/tile_element/Slope.h" #include "../world/tile_element/SurfaceElement.h" -using namespace OpenRCT2; - -LargeSceneryPlaceAction::LargeSceneryPlaceAction( - const CoordsXYZD& loc, ObjectEntryIndex sceneryType, uint8_t primaryColour, uint8_t secondaryColour, uint8_t tertiaryColour) - : _loc(loc) - , _sceneryType(sceneryType) - , _primaryColour(primaryColour) - , _secondaryColour(secondaryColour) - , _tertiaryColour(tertiaryColour) +namespace OpenRCT2::GameActions { -} - -void LargeSceneryPlaceAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit(_loc); - visitor.Visit("object", _sceneryType); - visitor.Visit("primaryColour", _primaryColour); - visitor.Visit("secondaryColour", _secondaryColour); - visitor.Visit("tertiaryColour", _tertiaryColour); -} - -uint16_t LargeSceneryPlaceAction::GetActionFlags() const -{ - return GameAction::GetActionFlags(); -} - -void LargeSceneryPlaceAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_loc) << DS_TAG(_sceneryType) << DS_TAG(_primaryColour) << DS_TAG(_secondaryColour) - << DS_TAG(_tertiaryColour); -} - -GameActions::Result LargeSceneryPlaceAction::Query() const -{ - auto res = GameActions::Result(); - res.ErrorTitle = STR_CANT_POSITION_THIS_HERE; - res.Expenditure = ExpenditureType::landscaping; - int16_t surfaceHeight = TileElementHeight(_loc); - res.Position.x = _loc.x + 16; - res.Position.y = _loc.y + 16; - res.Position.z = surfaceHeight; - - auto resultData = LargeSceneryPlaceActionResult{}; - - auto& gameState = getGameState(); - - money64 supportsCost = 0; - - if (_primaryColour >= COLOUR_COUNT) + LargeSceneryPlaceAction::LargeSceneryPlaceAction( + const CoordsXYZD& loc, ObjectEntryIndex sceneryType, uint8_t primaryColour, uint8_t secondaryColour, + uint8_t tertiaryColour) + : _loc(loc) + , _sceneryType(sceneryType) + , _primaryColour(primaryColour) + , _secondaryColour(secondaryColour) + , _tertiaryColour(tertiaryColour) { - LOG_ERROR("Invalid primary colour %u", _primaryColour); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_ERR_INVALID_COLOUR); - } - else if (_secondaryColour >= COLOUR_COUNT) - { - LOG_ERROR("Invalid secondary colour %u", _secondaryColour); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_ERR_INVALID_COLOUR); - } - else if (_tertiaryColour >= COLOUR_COUNT) - { - LOG_ERROR("Invalid tertiary colour %u", _tertiaryColour); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_ERR_INVALID_COLOUR); - } - else if (_sceneryType >= kMaxLargeSceneryObjects) - { - LOG_ERROR("Invalid sceneryType %u", _sceneryType); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_ERR_VALUE_OUT_OF_RANGE); } - auto* sceneryEntry = ObjectManager::GetObjectEntry(_sceneryType); - if (sceneryEntry == nullptr) + void LargeSceneryPlaceAction::AcceptParameters(GameActionParameterVisitor& visitor) { - LOG_ERROR("Large scenery entry not found for sceneryType %u", _sceneryType); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_UNKNOWN_OBJECT_TYPE); + visitor.Visit(_loc); + visitor.Visit("object", _sceneryType); + visitor.Visit("primaryColour", _primaryColour); + visitor.Visit("secondaryColour", _secondaryColour); + visitor.Visit("tertiaryColour", _tertiaryColour); } - const auto totalNumTiles = sceneryEntry->tiles.size(); - int16_t maxHeight = GetMaxSurfaceHeight(sceneryEntry->tiles); - - if (_loc.z != 0) + uint16_t LargeSceneryPlaceAction::GetActionFlags() const { - maxHeight = _loc.z; + return GameAction::GetActionFlags(); } - res.Position.z = maxHeight; - - if (sceneryEntry->scrolling_mode != kScrollingModeNone) + void LargeSceneryPlaceAction::Serialise(DataSerialiser& stream) { - if (HasReachedBannerLimit()) + GameAction::Serialise(stream); + + stream << DS_TAG(_loc) << DS_TAG(_sceneryType) << DS_TAG(_primaryColour) << DS_TAG(_secondaryColour) + << DS_TAG(_tertiaryColour); + } + + Result LargeSceneryPlaceAction::Query() const + { + auto res = Result(); + res.ErrorTitle = STR_CANT_POSITION_THIS_HERE; + res.Expenditure = ExpenditureType::landscaping; + int16_t surfaceHeight = TileElementHeight(_loc); + res.Position.x = _loc.x + 16; + res.Position.y = _loc.y + 16; + res.Position.z = surfaceHeight; + + auto resultData = LargeSceneryPlaceActionResult{}; + + auto& gameState = getGameState(); + + money64 supportsCost = 0; + + if (_primaryColour >= COLOUR_COUNT) { - LOG_ERROR("No free banners available"); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_TOO_MANY_BANNERS_IN_GAME); + LOG_ERROR("Invalid primary colour %u", _primaryColour); + return Result(Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_ERR_INVALID_COLOUR); } - } - - for (auto& tile : sceneryEntry->tiles) - { - auto curTile = CoordsXY{ tile.offset }.Rotate(_loc.direction); - - curTile.x += _loc.x; - curTile.y += _loc.y; - - int32_t zLow = tile.offset.z + maxHeight; - int32_t zHigh = tile.zClearance + zLow; - - QuarterTile quarterTile = QuarterTile{ tile.corners, 0 }.Rotate(_loc.direction); - const auto isTree = (sceneryEntry->flags & LARGE_SCENERY_FLAG_IS_TREE) != 0; - auto canBuild = MapCanConstructWithClearAt( - { curTile, zLow, zHigh }, &MapPlaceSceneryClearFunc, quarterTile, GetFlags(), CreateCrossingMode::none, isTree); - if (canBuild.Error != GameActions::Status::Ok) + else if (_secondaryColour >= COLOUR_COUNT) { - canBuild.ErrorTitle = STR_CANT_POSITION_THIS_HERE; - return canBuild; + LOG_ERROR("Invalid secondary colour %u", _secondaryColour); + return Result(Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_ERR_INVALID_COLOUR); + } + else if (_tertiaryColour >= COLOUR_COUNT) + { + LOG_ERROR("Invalid tertiary colour %u", _tertiaryColour); + return Result(Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_ERR_INVALID_COLOUR); + } + else if (_sceneryType >= kMaxLargeSceneryObjects) + { + LOG_ERROR("Invalid sceneryType %u", _sceneryType); + return Result(Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_ERR_VALUE_OUT_OF_RANGE); } - supportsCost += canBuild.Cost; - - const auto clearanceData = canBuild.GetData(); - int32_t tempSceneryGroundFlags = clearanceData.GroundFlags & (ELEMENT_IS_ABOVE_GROUND | ELEMENT_IS_UNDERGROUND); - if (!gameState.cheats.disableClearanceChecks) + auto* sceneryEntry = ObjectManager::GetObjectEntry(_sceneryType); + if (sceneryEntry == nullptr) { - if ((clearanceData.GroundFlags & ELEMENT_IS_UNDERWATER) || (clearanceData.GroundFlags & ELEMENT_IS_UNDERGROUND)) + LOG_ERROR("Large scenery entry not found for sceneryType %u", _sceneryType); + return Result(Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_UNKNOWN_OBJECT_TYPE); + } + + const auto totalNumTiles = sceneryEntry->tiles.size(); + int16_t maxHeight = GetMaxSurfaceHeight(sceneryEntry->tiles); + + if (_loc.z != 0) + { + maxHeight = _loc.z; + } + + res.Position.z = maxHeight; + + if (sceneryEntry->scrolling_mode != kScrollingModeNone) + { + if (HasReachedBannerLimit()) { - return GameActions::Result( - GameActions::Status::Disallowed, STR_CANT_POSITION_THIS_HERE, STR_CANT_BUILD_THIS_UNDERWATER); - } - if (resultData.GroundFlags && !(resultData.GroundFlags & tempSceneryGroundFlags)) - { - return GameActions::Result( - GameActions::Status::Disallowed, STR_CANT_POSITION_THIS_HERE, - STR_CANT_BUILD_PARTLY_ABOVE_AND_PARTLY_BELOW_GROUND); + LOG_ERROR("No free banners available"); + return Result(Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_TOO_MANY_BANNERS_IN_GAME); } } - resultData.GroundFlags = tempSceneryGroundFlags; - - if (!LocationValid(curTile) || MapIsEdge(curTile)) + for (auto& tile : sceneryEntry->tiles) { - return GameActions::Result(GameActions::Status::Disallowed, STR_CANT_POSITION_THIS_HERE, STR_OFF_EDGE_OF_MAP); + auto curTile = CoordsXY{ tile.offset }.Rotate(_loc.direction); + + curTile.x += _loc.x; + curTile.y += _loc.y; + + int32_t zLow = tile.offset.z + maxHeight; + int32_t zHigh = tile.zClearance + zLow; + + QuarterTile quarterTile = QuarterTile{ tile.corners, 0 }.Rotate(_loc.direction); + const auto isTree = (sceneryEntry->flags & LARGE_SCENERY_FLAG_IS_TREE) != 0; + auto canBuild = MapCanConstructWithClearAt( + { curTile, zLow, zHigh }, &MapPlaceSceneryClearFunc, quarterTile, GetFlags(), CreateCrossingMode::none, isTree); + if (canBuild.Error != Status::Ok) + { + canBuild.ErrorTitle = STR_CANT_POSITION_THIS_HERE; + return canBuild; + } + + supportsCost += canBuild.Cost; + + const auto clearanceData = canBuild.GetData(); + int32_t tempSceneryGroundFlags = clearanceData.GroundFlags & (ELEMENT_IS_ABOVE_GROUND | ELEMENT_IS_UNDERGROUND); + if (!gameState.cheats.disableClearanceChecks) + { + if ((clearanceData.GroundFlags & ELEMENT_IS_UNDERWATER) || (clearanceData.GroundFlags & ELEMENT_IS_UNDERGROUND)) + { + return Result(Status::Disallowed, STR_CANT_POSITION_THIS_HERE, STR_CANT_BUILD_THIS_UNDERWATER); + } + if (resultData.GroundFlags && !(resultData.GroundFlags & tempSceneryGroundFlags)) + { + return Result( + Status::Disallowed, STR_CANT_POSITION_THIS_HERE, STR_CANT_BUILD_PARTLY_ABOVE_AND_PARTLY_BELOW_GROUND); + } + } + + resultData.GroundFlags = tempSceneryGroundFlags; + + if (!LocationValid(curTile) || MapIsEdge(curTile)) + { + return Result(Status::Disallowed, STR_CANT_POSITION_THIS_HERE, STR_OFF_EDGE_OF_MAP); + } + + if (gLegacyScene != LegacyScene::scenarioEditor && !MapIsLocationOwned({ curTile, zLow }) + && !gameState.cheats.sandboxMode) + { + return Result(Status::Disallowed, STR_CANT_POSITION_THIS_HERE, STR_LAND_NOT_OWNED_BY_PARK); + } } - if (gLegacyScene != LegacyScene::scenarioEditor && !MapIsLocationOwned({ curTile, zLow }) - && !gameState.cheats.sandboxMode) + if (!CheckMapCapacity(sceneryEntry->tiles, totalNumTiles)) { - return GameActions::Result( - GameActions::Status::Disallowed, STR_CANT_POSITION_THIS_HERE, STR_LAND_NOT_OWNED_BY_PARK); - } - } - - if (!CheckMapCapacity(sceneryEntry->tiles, totalNumTiles)) - { - LOG_ERROR("No free map elements available"); - return GameActions::Result( - GameActions::Status::NoFreeElements, STR_CANT_POSITION_THIS_HERE, STR_TILE_ELEMENT_LIMIT_REACHED); - } - - // Force ride construction to recheck area - _currentTrackSelectionFlags.set(TrackSelectionFlag::recheck); - - res.Cost = sceneryEntry->price + supportsCost; - res.SetData(std::move(resultData)); - - return res; -} - -GameActions::Result LargeSceneryPlaceAction::Execute() const -{ - auto res = GameActions::Result(); - res.ErrorTitle = STR_CANT_POSITION_THIS_HERE; - res.Expenditure = ExpenditureType::landscaping; - - int16_t surfaceHeight = TileElementHeight(_loc); - res.Position.x = _loc.x + 16; - res.Position.y = _loc.y + 16; - res.Position.z = surfaceHeight; - - auto resultData = LargeSceneryPlaceActionResult{}; - - money64 supportsCost = 0; - - auto* sceneryEntry = ObjectManager::GetObjectEntry(_sceneryType); - if (sceneryEntry == nullptr) - { - LOG_ERROR("Large scenery entry not found for sceneryType = %u", _sceneryType); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_UNKNOWN_OBJECT_TYPE); - } - - if (sceneryEntry->tiles.empty()) - { - LOG_ERROR("Invalid large scenery object, sceneryType = %u", _sceneryType); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, kStringIdNone); - } - - int16_t maxHeight = GetMaxSurfaceHeight(sceneryEntry->tiles); - - if (_loc.z != 0) - { - maxHeight = _loc.z; - } - - res.Position.z = maxHeight; - - // Allocate banner - Banner* banner = nullptr; - if (sceneryEntry->scrolling_mode != kScrollingModeNone) - { - banner = CreateBanner(); - if (banner == nullptr) - { - LOG_ERROR("No free banners available"); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_TOO_MANY_BANNERS_IN_GAME); + LOG_ERROR("No free map elements available"); + return Result(Status::NoFreeElements, STR_CANT_POSITION_THIS_HERE, STR_TILE_ELEMENT_LIMIT_REACHED); } - banner->text = {}; - banner->colour = 2; - banner->textColour = TextColour::white; - banner->flags = { BannerFlag::isLargeScenery }; - banner->type = 0; - banner->position = TileCoordsXY(_loc); + // Force ride construction to recheck area + _currentTrackSelectionFlags.set(TrackSelectionFlag::recheck); - RideId rideIndex = BannerGetClosestRideIndex({ _loc, maxHeight }); - if (!rideIndex.IsNull()) - { - banner->rideIndex = rideIndex; - banner->flags.set(BannerFlag::linkedToRide); - } + res.Cost = sceneryEntry->price + supportsCost; + res.SetData(std::move(resultData)); - resultData.bannerId = banner->id; + return res; } - for (auto& tile : sceneryEntry->tiles) + Result LargeSceneryPlaceAction::Execute() const { - auto curTile = CoordsXY{ tile.offset }.Rotate(_loc.direction); + auto res = Result(); + res.ErrorTitle = STR_CANT_POSITION_THIS_HERE; + res.Expenditure = ExpenditureType::landscaping; - curTile.x += _loc.x; - curTile.y += _loc.y; + int16_t surfaceHeight = TileElementHeight(_loc); + res.Position.x = _loc.x + 16; + res.Position.y = _loc.y + 16; + res.Position.z = surfaceHeight; - int32_t zLow = tile.offset.z + maxHeight; - int32_t zHigh = tile.zClearance + zLow; + auto resultData = LargeSceneryPlaceActionResult{}; - QuarterTile quarterTile = QuarterTile{ tile.corners, 0 }.Rotate(_loc.direction); - const auto isTree = (sceneryEntry->flags & LARGE_SCENERY_FLAG_IS_TREE) != 0; - auto canBuild = MapCanConstructWithClearAt( - { curTile, zLow, zHigh }, &MapPlaceSceneryClearFunc, quarterTile, GetFlags(), CreateCrossingMode::none, isTree); - if (canBuild.Error != GameActions::Status::Ok) + money64 supportsCost = 0; + + auto* sceneryEntry = ObjectManager::GetObjectEntry(_sceneryType); + if (sceneryEntry == nullptr) { + LOG_ERROR("Large scenery entry not found for sceneryType = %u", _sceneryType); + return Result(Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_UNKNOWN_OBJECT_TYPE); + } + + if (sceneryEntry->tiles.empty()) + { + LOG_ERROR("Invalid large scenery object, sceneryType = %u", _sceneryType); + return Result(Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, kStringIdNone); + } + + int16_t maxHeight = GetMaxSurfaceHeight(sceneryEntry->tiles); + + if (_loc.z != 0) + { + maxHeight = _loc.z; + } + + res.Position.z = maxHeight; + + // Allocate banner + Banner* banner = nullptr; + if (sceneryEntry->scrolling_mode != kScrollingModeNone) + { + banner = CreateBanner(); + if (banner == nullptr) + { + LOG_ERROR("No free banners available"); + return Result(Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_TOO_MANY_BANNERS_IN_GAME); + } + + banner->text = {}; + banner->colour = 2; + banner->textColour = TextColour::white; + banner->flags = { BannerFlag::isLargeScenery }; + banner->type = 0; + banner->position = TileCoordsXY(_loc); + + RideId rideIndex = BannerGetClosestRideIndex({ _loc, maxHeight }); + if (!rideIndex.IsNull()) + { + banner->rideIndex = rideIndex; + banner->flags.set(BannerFlag::linkedToRide); + } + + resultData.bannerId = banner->id; + } + + for (auto& tile : sceneryEntry->tiles) + { + auto curTile = CoordsXY{ tile.offset }.Rotate(_loc.direction); + + curTile.x += _loc.x; + curTile.y += _loc.y; + + int32_t zLow = tile.offset.z + maxHeight; + int32_t zHigh = tile.zClearance + zLow; + + QuarterTile quarterTile = QuarterTile{ tile.corners, 0 }.Rotate(_loc.direction); + const auto isTree = (sceneryEntry->flags & LARGE_SCENERY_FLAG_IS_TREE) != 0; + auto canBuild = MapCanConstructWithClearAt( + { curTile, zLow, zHigh }, &MapPlaceSceneryClearFunc, quarterTile, GetFlags(), CreateCrossingMode::none, isTree); + if (canBuild.Error != Status::Ok) + { + if (banner != nullptr) + { + DeleteBanner(banner->id); + } + canBuild.ErrorTitle = STR_CANT_POSITION_THIS_HERE; + return canBuild; + } + + supportsCost += canBuild.Cost; + + const auto clearanceData = canBuild.GetData(); + resultData.GroundFlags = clearanceData.GroundFlags & (ELEMENT_IS_ABOVE_GROUND | ELEMENT_IS_UNDERGROUND); + + if (!(GetFlags() & GAME_COMMAND_FLAG_GHOST)) + { + FootpathRemoveLitter({ curTile, zLow }); + if (!getGameState().cheats.disableClearanceChecks) + { + WallRemoveAt({ curTile, zLow, zHigh }); + } + } + + auto* newSceneryElement = TileElementInsert( + CoordsXYZ{ curTile.x, curTile.y, zLow }, quarterTile.GetBaseQuarterOccupied()); + Guard::Assert(newSceneryElement != nullptr); + newSceneryElement->SetClearanceZ(zHigh); + + SetNewLargeSceneryElement(*newSceneryElement, tile.index); if (banner != nullptr) { - DeleteBanner(banner->id); + newSceneryElement->SetBannerIndex(banner->id); } - canBuild.ErrorTitle = STR_CANT_POSITION_THIS_HERE; - return canBuild; - } - supportsCost += canBuild.Cost; + MapAnimations::MarkTileForInvalidation(TileCoordsXY(curTile)); + MapInvalidateTileFull(curTile); - const auto clearanceData = canBuild.GetData(); - resultData.GroundFlags = clearanceData.GroundFlags & (ELEMENT_IS_ABOVE_GROUND | ELEMENT_IS_UNDERGROUND); - - if (!(GetFlags() & GAME_COMMAND_FLAG_GHOST)) - { - FootpathRemoveLitter({ curTile, zLow }); - if (!getGameState().cheats.disableClearanceChecks) + if (tile.index == 0) { - WallRemoveAt({ curTile, zLow, zHigh }); + resultData.firstTileHeight = zLow; } } - auto* newSceneryElement = TileElementInsert( - CoordsXYZ{ curTile.x, curTile.y, zLow }, quarterTile.GetBaseQuarterOccupied()); - Guard::Assert(newSceneryElement != nullptr); - newSceneryElement->SetClearanceZ(zHigh); + // Force ride construction to recheck area + _currentTrackSelectionFlags.set(TrackSelectionFlag::recheck); - SetNewLargeSceneryElement(*newSceneryElement, tile.index); - if (banner != nullptr) - { - newSceneryElement->SetBannerIndex(banner->id); - } + res.Cost = sceneryEntry->price + supportsCost; + res.SetData(std::move(resultData)); - MapAnimations::MarkTileForInvalidation(TileCoordsXY(curTile)); - MapInvalidateTileFull(curTile); - - if (tile.index == 0) - { - resultData.firstTileHeight = zLow; - } + return res; } - // Force ride construction to recheck area - _currentTrackSelectionFlags.set(TrackSelectionFlag::recheck); - - res.Cost = sceneryEntry->price + supportsCost; - res.SetData(std::move(resultData)); - - return res; -} - -bool LargeSceneryPlaceAction::CheckMapCapacity(std::span tiles, size_t numTiles) const -{ - for (auto& tile : tiles) + bool LargeSceneryPlaceAction::CheckMapCapacity(std::span tiles, size_t numTiles) const { - auto curTile = CoordsXY{ tile.offset }.Rotate(_loc.direction); - - curTile.x += _loc.x; - curTile.y += _loc.y; - if (!MapCheckCapacityAndReorganise(curTile, numTiles)) + for (auto& tile : tiles) { - return false; + auto curTile = CoordsXY{ tile.offset }.Rotate(_loc.direction); + + curTile.x += _loc.x; + curTile.y += _loc.y; + if (!MapCheckCapacityAndReorganise(curTile, numTiles)) + { + return false; + } } + return true; } - return true; -} -int16_t LargeSceneryPlaceAction::GetMaxSurfaceHeight(std::span tiles) const -{ - int16_t maxHeight = -1; - for (auto& tile : tiles) + int16_t LargeSceneryPlaceAction::GetMaxSurfaceHeight(std::span tiles) const { - auto curTile = CoordsXY{ tile.offset }.Rotate(_loc.direction); - - curTile.x += _loc.x; - curTile.y += _loc.y; - - if (!MapIsLocationValid(curTile)) + int16_t maxHeight = -1; + for (auto& tile : tiles) { - continue; - } + auto curTile = CoordsXY{ tile.offset }.Rotate(_loc.direction); - auto* surfaceElement = MapGetSurfaceElementAt(curTile); - if (surfaceElement == nullptr) - continue; + curTile.x += _loc.x; + curTile.y += _loc.y; - int32_t baseZ = surfaceElement->GetBaseZ(); - int32_t slope = surfaceElement->GetSlope(); + if (!MapIsLocationValid(curTile)) + { + continue; + } - if ((slope & kTileSlopeRaisedCornersMask) != kTileSlopeFlat) - { - baseZ += kLandHeightStep; - if (slope & kTileSlopeDiagonalFlag) + auto* surfaceElement = MapGetSurfaceElementAt(curTile); + if (surfaceElement == nullptr) + continue; + + int32_t baseZ = surfaceElement->GetBaseZ(); + int32_t slope = surfaceElement->GetSlope(); + + if ((slope & kTileSlopeRaisedCornersMask) != kTileSlopeFlat) { baseZ += kLandHeightStep; + if (slope & kTileSlopeDiagonalFlag) + { + baseZ += kLandHeightStep; + } + } + + if (baseZ > maxHeight) + { + maxHeight = baseZ; } } + return maxHeight; + } - if (baseZ > maxHeight) + void LargeSceneryPlaceAction::SetNewLargeSceneryElement(LargeSceneryElement& sceneryElement, uint8_t tileNum) const + { + sceneryElement.SetDirection(_loc.direction); + sceneryElement.SetEntryIndex(_sceneryType); + sceneryElement.SetSequenceIndex(tileNum); + sceneryElement.SetPrimaryColour(_primaryColour); + sceneryElement.SetSecondaryColour(_secondaryColour); + sceneryElement.SetTertiaryColour(_tertiaryColour); + + if (GetFlags() & GAME_COMMAND_FLAG_GHOST) { - maxHeight = baseZ; + sceneryElement.SetGhost(true); } } - return maxHeight; -} - -void LargeSceneryPlaceAction::SetNewLargeSceneryElement(LargeSceneryElement& sceneryElement, uint8_t tileNum) const -{ - sceneryElement.SetDirection(_loc.direction); - sceneryElement.SetEntryIndex(_sceneryType); - sceneryElement.SetSequenceIndex(tileNum); - sceneryElement.SetPrimaryColour(_primaryColour); - sceneryElement.SetSecondaryColour(_secondaryColour); - sceneryElement.SetTertiaryColour(_tertiaryColour); - - if (GetFlags() & GAME_COMMAND_FLAG_GHOST) - { - sceneryElement.SetGhost(true); - } -} +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/LargeSceneryPlaceAction.h b/src/openrct2/actions/LargeSceneryPlaceAction.h index ed6f494fdb..730061f82f 100644 --- a/src/openrct2/actions/LargeSceneryPlaceAction.h +++ b/src/openrct2/actions/LargeSceneryPlaceAction.h @@ -11,45 +11,48 @@ #include "GameAction.h" -struct LargeSceneryPlaceActionResult -{ - uint8_t GroundFlags{ 0 }; - int32_t firstTileHeight{ 0 }; - BannerIndex bannerId = BannerIndex::GetNull(); -}; - namespace OpenRCT2 { struct LargeSceneryTile; struct LargeSceneryElement; } // namespace OpenRCT2 -class LargeSceneryPlaceAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - CoordsXYZD _loc; - OpenRCT2::ObjectEntryIndex _sceneryType{ OpenRCT2::kObjectEntryIndexNull }; - uint8_t _primaryColour{}; - uint8_t _secondaryColour{}; - uint8_t _tertiaryColour{}; + struct LargeSceneryPlaceActionResult + { + uint8_t GroundFlags{ 0 }; + int32_t firstTileHeight{ 0 }; + BannerIndex bannerId = BannerIndex::GetNull(); + }; -public: - LargeSceneryPlaceAction() = default; + class LargeSceneryPlaceAction final : public GameActionBase + { + private: + CoordsXYZD _loc; + ObjectEntryIndex _sceneryType{ kObjectEntryIndexNull }; + uint8_t _primaryColour{}; + uint8_t _secondaryColour{}; + uint8_t _tertiaryColour{}; - LargeSceneryPlaceAction( - const CoordsXYZD& loc, OpenRCT2::ObjectEntryIndex sceneryType, uint8_t primaryColour, uint8_t secondaryColour, - uint8_t tertiaryColour); + public: + LargeSceneryPlaceAction() = default; - void AcceptParameters(GameActionParameterVisitor& visitor) override; + LargeSceneryPlaceAction( + const CoordsXYZD& loc, ObjectEntryIndex sceneryType, uint8_t primaryColour, uint8_t secondaryColour, + uint8_t tertiaryColour); - uint16_t GetActionFlags() const override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; + uint16_t GetActionFlags() const override; -private: - bool CheckMapCapacity(std::span tiles, size_t numTiles) const; - int16_t GetMaxSurfaceHeight(std::span tiles) const; - void SetNewLargeSceneryElement(OpenRCT2::LargeSceneryElement& sceneryElement, uint8_t tileNum) const; -}; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; + + private: + bool CheckMapCapacity(std::span tiles, size_t numTiles) const; + int16_t GetMaxSurfaceHeight(std::span tiles) const; + void SetNewLargeSceneryElement(LargeSceneryElement& sceneryElement, uint8_t tileNum) const; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/LargeSceneryRemoveAction.cpp b/src/openrct2/actions/LargeSceneryRemoveAction.cpp index aa33d6d92a..6244b7e71d 100644 --- a/src/openrct2/actions/LargeSceneryRemoveAction.cpp +++ b/src/openrct2/actions/LargeSceneryRemoveAction.cpp @@ -22,197 +22,196 @@ #include "../world/TileElementsView.h" #include "../world/tile_element/LargeSceneryElement.h" -using namespace OpenRCT2; - -LargeSceneryRemoveAction::LargeSceneryRemoveAction(const CoordsXYZD& location, uint16_t tileIndex) - : _loc(location) - , _tileIndex(tileIndex) +namespace OpenRCT2::GameActions { -} - -void LargeSceneryRemoveAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit(_loc); - visitor.Visit("tileIndex", _tileIndex); -} - -uint16_t LargeSceneryRemoveAction::GetActionFlags() const -{ - return GameAction::GetActionFlags(); -} - -void LargeSceneryRemoveAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_loc) << DS_TAG(_tileIndex); -} - -GameActions::Result LargeSceneryRemoveAction::Query() const -{ - auto res = GameActions::Result(); - - const uint32_t flags = GetFlags(); - - res.Position.x = _loc.x + 16; - res.Position.y = _loc.y + 16; - res.Position.z = _loc.z; - res.Expenditure = ExpenditureType::landscaping; - res.Cost = 0; - - TileElement* tileElement = FindLargeSceneryElement(_loc, _tileIndex); - if (tileElement == nullptr) + LargeSceneryRemoveAction::LargeSceneryRemoveAction(const CoordsXYZD& location, uint16_t tileIndex) + : _loc(location) + , _tileIndex(tileIndex) { - LOG_ERROR("No large scenery element to remove at x = %d, y = %d", _loc.x, _loc.y); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_REMOVE_THIS, STR_INVALID_SELECTION_OF_OBJECTS); } - auto* sceneryEntry = tileElement->AsLargeScenery()->GetEntry(); - // If we have a bugged scenery entry, do not touch the tile element. - if (sceneryEntry == nullptr) + void LargeSceneryRemoveAction::AcceptParameters(GameActionParameterVisitor& visitor) { - LOG_WARNING("Scenery entry at x = %d, y = %d not removed because it is an unknown object type", _loc.x, _loc.y); - return GameActions::Result(GameActions::Status::Unknown, STR_CANT_REMOVE_THIS, STR_UNKNOWN_OBJECT_TYPE); + visitor.Visit(_loc); + visitor.Visit("tileIndex", _tileIndex); } - auto rotatedOffsets = CoordsXYZ{ CoordsXY{ sceneryEntry->tiles[_tileIndex].offset }.Rotate(_loc.direction), - sceneryEntry->tiles[_tileIndex].offset.z }; - - auto firstTile = CoordsXYZ{ _loc.x, _loc.y, _loc.z } - rotatedOffsets; - - bool calculate_cost = true; - for (auto& tile : sceneryEntry->tiles) + uint16_t LargeSceneryRemoveAction::GetActionFlags() const { - auto currentTileRotatedOffset = CoordsXYZ{ CoordsXY{ tile.offset }.Rotate(_loc.direction), tile.offset.z }; + return GameAction::GetActionFlags(); + } - auto currentTile = CoordsXYZ{ firstTile.x, firstTile.y, firstTile.z } + currentTileRotatedOffset; + void LargeSceneryRemoveAction::Serialise(DataSerialiser& stream) + { + GameAction::Serialise(stream); - if (gLegacyScene != LegacyScene::scenarioEditor && !getGameState().cheats.sandboxMode) + stream << DS_TAG(_loc) << DS_TAG(_tileIndex); + } + + Result LargeSceneryRemoveAction::Query() const + { + auto res = Result(); + + const uint32_t flags = GetFlags(); + + res.Position.x = _loc.x + 16; + res.Position.y = _loc.y + 16; + res.Position.z = _loc.z; + res.Expenditure = ExpenditureType::landscaping; + res.Cost = 0; + + TileElement* tileElement = FindLargeSceneryElement(_loc, _tileIndex); + if (tileElement == nullptr) { - if (getGameState().park.flags & PARK_FLAGS_FORBID_TREE_REMOVAL) + LOG_ERROR("No large scenery element to remove at x = %d, y = %d", _loc.x, _loc.y); + return Result(Status::InvalidParameters, STR_CANT_REMOVE_THIS, STR_INVALID_SELECTION_OF_OBJECTS); + } + + auto* sceneryEntry = tileElement->AsLargeScenery()->GetEntry(); + // If we have a bugged scenery entry, do not touch the tile element. + if (sceneryEntry == nullptr) + { + LOG_WARNING("Scenery entry at x = %d, y = %d not removed because it is an unknown object type", _loc.x, _loc.y); + return Result(Status::Unknown, STR_CANT_REMOVE_THIS, STR_UNKNOWN_OBJECT_TYPE); + } + + auto rotatedOffsets = CoordsXYZ{ CoordsXY{ sceneryEntry->tiles[_tileIndex].offset }.Rotate(_loc.direction), + sceneryEntry->tiles[_tileIndex].offset.z }; + + auto firstTile = CoordsXYZ{ _loc.x, _loc.y, _loc.z } - rotatedOffsets; + + bool calculate_cost = true; + for (auto& tile : sceneryEntry->tiles) + { + auto currentTileRotatedOffset = CoordsXYZ{ CoordsXY{ tile.offset }.Rotate(_loc.direction), tile.offset.z }; + + auto currentTile = CoordsXYZ{ firstTile.x, firstTile.y, firstTile.z } + currentTileRotatedOffset; + + if (gLegacyScene != LegacyScene::scenarioEditor && !getGameState().cheats.sandboxMode) { - if (sceneryEntry->HasFlag(LARGE_SCENERY_FLAG_IS_TREE)) + if (getGameState().park.flags & PARK_FLAGS_FORBID_TREE_REMOVAL) { - res.Error = GameActions::Status::NoClearance; - res.ErrorTitle = STR_CANT_REMOVE_THIS; - res.ErrorMessage = STR_FORBIDDEN_BY_THE_LOCAL_AUTHORITY; - return res; + if (sceneryEntry->HasFlag(LARGE_SCENERY_FLAG_IS_TREE)) + { + res.Error = Status::NoClearance; + res.ErrorTitle = STR_CANT_REMOVE_THIS; + res.ErrorMessage = STR_FORBIDDEN_BY_THE_LOCAL_AUTHORITY; + return res; + } + } + + if (!MapIsLocationOwned({ currentTile.x, currentTile.y, currentTile.z })) + { + return Result(Status::NoClearance, STR_CANT_REMOVE_THIS, STR_LAND_NOT_OWNED_BY_PARK); } } - if (!MapIsLocationOwned({ currentTile.x, currentTile.y, currentTile.z })) + if (!LocationValid(currentTile)) { - return GameActions::Result(GameActions::Status::NoClearance, STR_CANT_REMOVE_THIS, STR_LAND_NOT_OWNED_BY_PARK); + return Result(Status::InvalidParameters, STR_CANT_REMOVE_THIS, STR_OFF_EDGE_OF_MAP); + } + // Prevent duplicate costs when using the clear scenery tool that overlaps multiple large + // scenery tile elements. + if (flags & GAME_COMMAND_FLAG_TRACK_DESIGN) + { + if (tileElement->AsLargeScenery()->IsAccounted()) + calculate_cost = false; + + // Sets the flag to prevent this being counted in additional calls + tileElement->AsLargeScenery()->SetIsAccounted(true); } } - if (!LocationValid(currentTile)) - { - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_REMOVE_THIS, STR_OFF_EDGE_OF_MAP); - } - // Prevent duplicate costs when using the clear scenery tool that overlaps multiple large - // scenery tile elements. - if (flags & GAME_COMMAND_FLAG_TRACK_DESIGN) - { - if (tileElement->AsLargeScenery()->IsAccounted()) - calculate_cost = false; + if (calculate_cost) + res.Cost = sceneryEntry->removal_price; - // Sets the flag to prevent this being counted in additional calls - tileElement->AsLargeScenery()->SetIsAccounted(true); - } + return res; } - if (calculate_cost) + Result LargeSceneryRemoveAction::Execute() const + { + auto res = Result(); + + res.Position.x = _loc.x + 16; + res.Position.y = _loc.y + 16; + res.Position.z = _loc.z; + res.Expenditure = ExpenditureType::landscaping; + res.Cost = 0; + + TileElement* tileElement = FindLargeSceneryElement(_loc, _tileIndex); + if (tileElement == nullptr) + { + LOG_ERROR("No large scenery element to remove at %d, y = %d", _loc.x, _loc.y); + return Result(Status::InvalidParameters, STR_CANT_REMOVE_THIS, STR_INVALID_SELECTION_OF_OBJECTS); + } + + auto* sceneryEntry = tileElement->AsLargeScenery()->GetEntry(); + // If we have a bugged scenery entry, do not touch the tile element. + if (sceneryEntry == nullptr) + { + LOG_WARNING("Scenery entry at x = %d, y = %d not removed because it is an unknown object type", _loc.x, _loc.y); + return Result(Status::Unknown, STR_CANT_REMOVE_THIS, kStringIdNone); + } + + tileElement->RemoveBannerEntry(); + + auto rotatedFirstTile = CoordsXYZ{ CoordsXY{ sceneryEntry->tiles[_tileIndex].offset }.Rotate(_loc.direction), + sceneryEntry->tiles[_tileIndex].offset.z }; + + auto firstTile = CoordsXYZ{ _loc.x, _loc.y, _loc.z } - rotatedFirstTile; + + for (auto& tile : sceneryEntry->tiles) + { + auto rotatedCurrentTile = CoordsXYZ{ CoordsXY{ tile.offset }.Rotate(_loc.direction), tile.offset.z }; + + auto currentTile = CoordsXYZ{ firstTile.x, firstTile.y, firstTile.z } + rotatedCurrentTile; + + if (gLegacyScene != LegacyScene::scenarioEditor && !getGameState().cheats.sandboxMode) + { + if (!MapIsLocationOwned({ currentTile.x, currentTile.y, currentTile.z })) + { + return Result(Status::NoClearance, STR_CANT_REMOVE_THIS, STR_LAND_NOT_OWNED_BY_PARK); + } + } + + auto* sceneryElement = FindLargeSceneryElement(currentTile, tile.index); + if (sceneryElement == nullptr) + { + LOG_ERROR("Tile not found when trying to remove element!"); + } + else + { + MapInvalidateTileFull(currentTile); + TileElementRemove(sceneryElement); + } + } + res.Cost = sceneryEntry->removal_price; - return res; -} - -GameActions::Result LargeSceneryRemoveAction::Execute() const -{ - auto res = GameActions::Result(); - - res.Position.x = _loc.x + 16; - res.Position.y = _loc.y + 16; - res.Position.z = _loc.z; - res.Expenditure = ExpenditureType::landscaping; - res.Cost = 0; - - TileElement* tileElement = FindLargeSceneryElement(_loc, _tileIndex); - if (tileElement == nullptr) - { - LOG_ERROR("No large scenery element to remove at %d, y = %d", _loc.x, _loc.y); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_REMOVE_THIS, STR_INVALID_SELECTION_OF_OBJECTS); + return res; } - auto* sceneryEntry = tileElement->AsLargeScenery()->GetEntry(); - // If we have a bugged scenery entry, do not touch the tile element. - if (sceneryEntry == nullptr) + TileElement* LargeSceneryRemoveAction::FindLargeSceneryElement(const CoordsXYZ& pos, int32_t sequenceIndex) const { - LOG_WARNING("Scenery entry at x = %d, y = %d not removed because it is an unknown object type", _loc.x, _loc.y); - return GameActions::Result(GameActions::Status::Unknown, STR_CANT_REMOVE_THIS, kStringIdNone); - } - - tileElement->RemoveBannerEntry(); - - auto rotatedFirstTile = CoordsXYZ{ CoordsXY{ sceneryEntry->tiles[_tileIndex].offset }.Rotate(_loc.direction), - sceneryEntry->tiles[_tileIndex].offset.z }; - - auto firstTile = CoordsXYZ{ _loc.x, _loc.y, _loc.z } - rotatedFirstTile; - - for (auto& tile : sceneryEntry->tiles) - { - auto rotatedCurrentTile = CoordsXYZ{ CoordsXY{ tile.offset }.Rotate(_loc.direction), tile.offset.z }; - - auto currentTile = CoordsXYZ{ firstTile.x, firstTile.y, firstTile.z } + rotatedCurrentTile; - - if (gLegacyScene != LegacyScene::scenarioEditor && !getGameState().cheats.sandboxMode) + const bool isGhost = GetFlags() & GAME_COMMAND_FLAG_GHOST; + for (auto* sceneryElement : TileElementsView(pos)) { - if (!MapIsLocationOwned({ currentTile.x, currentTile.y, currentTile.z })) - { - return GameActions::Result(GameActions::Status::NoClearance, STR_CANT_REMOVE_THIS, STR_LAND_NOT_OWNED_BY_PARK); - } + // If we are removing ghost elements + if (isGhost && sceneryElement->IsGhost() == false) + continue; + + if (sceneryElement->GetDirection() != _loc.direction) + continue; + + if (sceneryElement->GetSequenceIndex() != sequenceIndex) + continue; + + if (sceneryElement->GetBaseZ() != pos.z) + continue; + + return sceneryElement->as(); } - auto* sceneryElement = FindLargeSceneryElement(currentTile, tile.index); - if (sceneryElement == nullptr) - { - LOG_ERROR("Tile not found when trying to remove element!"); - } - else - { - MapInvalidateTileFull(currentTile); - TileElementRemove(sceneryElement); - } + return nullptr; } - - res.Cost = sceneryEntry->removal_price; - - return res; -} - -TileElement* LargeSceneryRemoveAction::FindLargeSceneryElement(const CoordsXYZ& pos, int32_t sequenceIndex) const -{ - const bool isGhost = GetFlags() & GAME_COMMAND_FLAG_GHOST; - for (auto* sceneryElement : TileElementsView(pos)) - { - // If we are removing ghost elements - if (isGhost && sceneryElement->IsGhost() == false) - continue; - - if (sceneryElement->GetDirection() != _loc.direction) - continue; - - if (sceneryElement->GetSequenceIndex() != sequenceIndex) - continue; - - if (sceneryElement->GetBaseZ() != pos.z) - continue; - - return sceneryElement->as(); - } - - return nullptr; -} +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/LargeSceneryRemoveAction.h b/src/openrct2/actions/LargeSceneryRemoveAction.h index ac68c1a2f4..6b6e5e0b79 100644 --- a/src/openrct2/actions/LargeSceneryRemoveAction.h +++ b/src/openrct2/actions/LargeSceneryRemoveAction.h @@ -11,24 +11,27 @@ #include "GameAction.h" -class LargeSceneryRemoveAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - CoordsXYZD _loc; - uint16_t _tileIndex{}; + class LargeSceneryRemoveAction final : public GameActionBase + { + private: + CoordsXYZD _loc; + uint16_t _tileIndex{}; -public: - LargeSceneryRemoveAction() = default; - LargeSceneryRemoveAction(const CoordsXYZD& location, uint16_t tileIndex); + public: + LargeSceneryRemoveAction() = default; + LargeSceneryRemoveAction(const CoordsXYZD& location, uint16_t tileIndex); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; -private: - OpenRCT2::TileElement* FindLargeSceneryElement(const CoordsXYZ& pos, int32_t sequenceIndex) const; -}; + private: + TileElement* FindLargeSceneryElement(const CoordsXYZ& pos, int32_t sequenceIndex) const; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/LargeScenerySetColourAction.cpp b/src/openrct2/actions/LargeScenerySetColourAction.cpp index 4664aa7cc2..03fad8e6ef 100644 --- a/src/openrct2/actions/LargeScenerySetColourAction.cpp +++ b/src/openrct2/actions/LargeScenerySetColourAction.cpp @@ -17,146 +17,147 @@ #include "../world/Scenery.h" #include "../world/tile_element/LargeSceneryElement.h" -using namespace OpenRCT2; - -LargeScenerySetColourAction::LargeScenerySetColourAction( - const CoordsXYZD& loc, uint8_t tileIndex, uint8_t primaryColour, uint8_t secondaryColour, uint8_t tertiaryColour) - : _loc(loc) - , _tileIndex(tileIndex) - , _primaryColour(primaryColour) - , _secondaryColour(secondaryColour) - , _tertiaryColour(tertiaryColour) +namespace OpenRCT2::GameActions { -} - -void LargeScenerySetColourAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit(_loc); - visitor.Visit("tileIndex", _tileIndex); - visitor.Visit("primaryColour", _primaryColour); - visitor.Visit("secondaryColour", _secondaryColour); - visitor.Visit("tertiaryColour", _tertiaryColour); -} - -uint16_t LargeScenerySetColourAction::GetActionFlags() const -{ - return GameAction::GetActionFlags() | GameActions::Flags::AllowWhilePaused; -} - -void LargeScenerySetColourAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_loc) << DS_TAG(_tileIndex) << DS_TAG(_primaryColour) << DS_TAG(_secondaryColour) - << DS_TAG(_tertiaryColour); -} - -GameActions::Result LargeScenerySetColourAction::Query() const -{ - return QueryExecute(false); -} - -GameActions::Result LargeScenerySetColourAction::Execute() const -{ - return QueryExecute(true); -} - -GameActions::Result LargeScenerySetColourAction::QueryExecute(bool isExecuting) const -{ - auto res = GameActions::Result(); - res.Expenditure = ExpenditureType::landscaping; - res.Position.x = _loc.x + 16; - res.Position.y = _loc.y + 16; - res.Position.z = TileElementHeight(_loc); - res.ErrorTitle = STR_CANT_REPAINT_THIS; - - auto mapSizeMax = GetMapSizeMaxXY(); - if (_loc.x < 0 || _loc.y < 0 || _loc.x > mapSizeMax.x || _loc.y > mapSizeMax.y) + LargeScenerySetColourAction::LargeScenerySetColourAction( + const CoordsXYZD& loc, uint8_t tileIndex, uint8_t primaryColour, uint8_t secondaryColour, uint8_t tertiaryColour) + : _loc(loc) + , _tileIndex(tileIndex) + , _primaryColour(primaryColour) + , _secondaryColour(secondaryColour) + , _tertiaryColour(tertiaryColour) { - LOG_ERROR("Invalid x / y coordinates: x = %d, y = %d", _loc.x, _loc.y); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_REPAINT_THIS, STR_ERR_VALUE_OUT_OF_RANGE); } - if (_primaryColour >= COLOUR_COUNT) + void LargeScenerySetColourAction::AcceptParameters(GameActionParameterVisitor& visitor) { - LOG_ERROR("Invalid primary colour %u", _primaryColour); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_REPAINT_THIS, STR_ERR_INVALID_COLOUR); - } - else if (_secondaryColour >= COLOUR_COUNT) - { - LOG_ERROR("Invalid secondary colour %u", _secondaryColour); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_REPAINT_THIS, STR_ERR_INVALID_COLOUR); - } - else if (_tertiaryColour >= COLOUR_COUNT) - { - LOG_ERROR("Invalid tertiary colour %u", _tertiaryColour); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_REPAINT_THIS, STR_ERR_INVALID_COLOUR); + visitor.Visit(_loc); + visitor.Visit("tileIndex", _tileIndex); + visitor.Visit("primaryColour", _primaryColour); + visitor.Visit("secondaryColour", _secondaryColour); + visitor.Visit("tertiaryColour", _tertiaryColour); } - auto largeElement = MapGetLargeScenerySegment(_loc, _tileIndex); - - if (largeElement == nullptr) + uint16_t LargeScenerySetColourAction::GetActionFlags() const { - LOG_ERROR( - "Could not find large scenery at: x = %d, y = %d, z = %d, direction = %d, tileIndex = %u", _loc.x, _loc.y, _loc.z, - _loc.direction, _tileIndex); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_REPAINT_THIS, kStringIdNone); + return GameAction::GetActionFlags() | Flags::AllowWhilePaused; } - if ((GetFlags() & GAME_COMMAND_FLAG_GHOST) && !(largeElement->IsGhost())) + void LargeScenerySetColourAction::Serialise(DataSerialiser& stream) { - return res; + GameAction::Serialise(stream); + + stream << DS_TAG(_loc) << DS_TAG(_tileIndex) << DS_TAG(_primaryColour) << DS_TAG(_secondaryColour) + << DS_TAG(_tertiaryColour); } - auto* sceneryEntry = largeElement->GetEntry(); - - if (sceneryEntry == nullptr) + Result LargeScenerySetColourAction::Query() const { - LOG_ERROR("Scenery element doesn't have scenery entry"); - return GameActions::Result(GameActions::Status::Unknown, STR_CANT_REPAINT_THIS, kStringIdNone); + return QueryExecute(false); } - // Work out the base tile coordinates (Tile with index 0) - auto rotatedBaseCoordsOffset = CoordsXYZ{ CoordsXY{ sceneryEntry->tiles[_tileIndex].offset }.Rotate(_loc.direction), - sceneryEntry->tiles[_tileIndex].offset.z }; - auto baseTile = CoordsXYZ{ _loc.x, _loc.y, _loc.z } - rotatedBaseCoordsOffset; - - for (auto& tile : sceneryEntry->tiles) + Result LargeScenerySetColourAction::Execute() const { - // Work out the current tile coordinates - auto rotatedTileCoords = CoordsXYZ{ CoordsXY{ tile.offset }.Rotate(_loc.direction), tile.offset.z }; - auto currentTile = CoordsXYZ{ baseTile.x, baseTile.y, baseTile.z } + rotatedTileCoords; + return QueryExecute(true); + } - if (gLegacyScene != LegacyScene::scenarioEditor && !getGameState().cheats.sandboxMode) + Result LargeScenerySetColourAction::QueryExecute(bool isExecuting) const + { + auto res = Result(); + res.Expenditure = ExpenditureType::landscaping; + res.Position.x = _loc.x + 16; + res.Position.y = _loc.y + 16; + res.Position.z = TileElementHeight(_loc); + res.ErrorTitle = STR_CANT_REPAINT_THIS; + + auto mapSizeMax = GetMapSizeMaxXY(); + if (_loc.x < 0 || _loc.y < 0 || _loc.x > mapSizeMax.x || _loc.y > mapSizeMax.y) { - if (!MapIsLocationOwned(currentTile)) - { - return GameActions::Result(GameActions::Status::NotOwned, STR_CANT_REPAINT_THIS, STR_LAND_NOT_OWNED_BY_PARK); - } + LOG_ERROR("Invalid x / y coordinates: x = %d, y = %d", _loc.x, _loc.y); + return Result(Status::InvalidParameters, STR_CANT_REPAINT_THIS, STR_ERR_VALUE_OUT_OF_RANGE); } - if (!LocationValid(currentTile)) + if (_primaryColour >= COLOUR_COUNT) { - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_REPAINT_THIS, STR_OFF_EDGE_OF_MAP); + LOG_ERROR("Invalid primary colour %u", _primaryColour); + return Result(Status::InvalidParameters, STR_CANT_REPAINT_THIS, STR_ERR_INVALID_COLOUR); + } + else if (_secondaryColour >= COLOUR_COUNT) + { + LOG_ERROR("Invalid secondary colour %u", _secondaryColour); + return Result(Status::InvalidParameters, STR_CANT_REPAINT_THIS, STR_ERR_INVALID_COLOUR); + } + else if (_tertiaryColour >= COLOUR_COUNT) + { + LOG_ERROR("Invalid tertiary colour %u", _tertiaryColour); + return Result(Status::InvalidParameters, STR_CANT_REPAINT_THIS, STR_ERR_INVALID_COLOUR); } - auto tileElement = MapGetLargeScenerySegment({ currentTile.x, currentTile.y, _loc.z, _loc.direction }, tile.index); + auto largeElement = MapGetLargeScenerySegment(_loc, _tileIndex); - if (tileElement == nullptr) + if (largeElement == nullptr) { LOG_ERROR( - "Large scenery element not found at: x = %d, y = %d, z = %d, direction = %d", _loc.x, _loc.y, _loc.z, - _loc.direction); - return GameActions::Result(GameActions::Status::Unknown, STR_CANT_REPAINT_THIS, kStringIdNone); + "Could not find large scenery at: x = %d, y = %d, z = %d, direction = %d, tileIndex = %u", _loc.x, _loc.y, + _loc.z, _loc.direction, _tileIndex); + return Result(Status::InvalidParameters, STR_CANT_REPAINT_THIS, kStringIdNone); } - if (isExecuting) - { - tileElement->SetPrimaryColour(_primaryColour); - tileElement->SetSecondaryColour(_secondaryColour); - tileElement->SetTertiaryColour(_tertiaryColour); - MapInvalidateTileFull(currentTile); + if ((GetFlags() & GAME_COMMAND_FLAG_GHOST) && !(largeElement->IsGhost())) + { + return res; } + + auto* sceneryEntry = largeElement->GetEntry(); + + if (sceneryEntry == nullptr) + { + LOG_ERROR("Scenery element doesn't have scenery entry"); + return Result(Status::Unknown, STR_CANT_REPAINT_THIS, kStringIdNone); + } + // Work out the base tile coordinates (Tile with index 0) + auto rotatedBaseCoordsOffset = CoordsXYZ{ CoordsXY{ sceneryEntry->tiles[_tileIndex].offset }.Rotate(_loc.direction), + sceneryEntry->tiles[_tileIndex].offset.z }; + + auto baseTile = CoordsXYZ{ _loc.x, _loc.y, _loc.z } - rotatedBaseCoordsOffset; + + for (auto& tile : sceneryEntry->tiles) + { + // Work out the current tile coordinates + auto rotatedTileCoords = CoordsXYZ{ CoordsXY{ tile.offset }.Rotate(_loc.direction), tile.offset.z }; + auto currentTile = CoordsXYZ{ baseTile.x, baseTile.y, baseTile.z } + rotatedTileCoords; + + if (gLegacyScene != LegacyScene::scenarioEditor && !getGameState().cheats.sandboxMode) + { + if (!MapIsLocationOwned(currentTile)) + { + return Result(Status::NotOwned, STR_CANT_REPAINT_THIS, STR_LAND_NOT_OWNED_BY_PARK); + } + } + + if (!LocationValid(currentTile)) + { + return Result(Status::InvalidParameters, STR_CANT_REPAINT_THIS, STR_OFF_EDGE_OF_MAP); + } + + auto tileElement = MapGetLargeScenerySegment({ currentTile.x, currentTile.y, _loc.z, _loc.direction }, tile.index); + + if (tileElement == nullptr) + { + LOG_ERROR( + "Large scenery element not found at: x = %d, y = %d, z = %d, direction = %d", _loc.x, _loc.y, _loc.z, + _loc.direction); + return Result(Status::Unknown, STR_CANT_REPAINT_THIS, kStringIdNone); + } + if (isExecuting) + { + tileElement->SetPrimaryColour(_primaryColour); + tileElement->SetSecondaryColour(_secondaryColour); + tileElement->SetTertiaryColour(_tertiaryColour); + + MapInvalidateTileFull(currentTile); + } + } + return res; } - return res; -} +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/LargeScenerySetColourAction.h b/src/openrct2/actions/LargeScenerySetColourAction.h index 2889f2cf48..f0a56d7dcb 100644 --- a/src/openrct2/actions/LargeScenerySetColourAction.h +++ b/src/openrct2/actions/LargeScenerySetColourAction.h @@ -11,28 +11,31 @@ #include "GameAction.h" -class LargeScenerySetColourAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - CoordsXYZD _loc; - uint8_t _tileIndex{}; - uint8_t _primaryColour{}; - uint8_t _secondaryColour{}; - uint8_t _tertiaryColour{}; + class LargeScenerySetColourAction final : public GameActionBase + { + private: + CoordsXYZD _loc; + uint8_t _tileIndex{}; + uint8_t _primaryColour{}; + uint8_t _secondaryColour{}; + uint8_t _tertiaryColour{}; -public: - LargeScenerySetColourAction() = default; - LargeScenerySetColourAction( - const CoordsXYZD& loc, uint8_t tileIndex, uint8_t primaryColour, uint8_t secondaryColour, uint8_t tertiaryColour); + public: + LargeScenerySetColourAction() = default; + LargeScenerySetColourAction( + const CoordsXYZD& loc, uint8_t tileIndex, uint8_t primaryColour, uint8_t secondaryColour, uint8_t tertiaryColour); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; -private: - OpenRCT2::GameActions::Result QueryExecute(bool isExecuting) const; -}; + private: + Result QueryExecute(bool isExecuting) const; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/LoadOrQuitAction.cpp b/src/openrct2/actions/LoadOrQuitAction.cpp index e45fbdd81c..fe5ce0ac44 100644 --- a/src/openrct2/actions/LoadOrQuitAction.cpp +++ b/src/openrct2/actions/LoadOrQuitAction.cpp @@ -13,55 +13,56 @@ #include "../OpenRCT2.h" #include "../ui/WindowManager.h" -using namespace OpenRCT2; - -LoadOrQuitAction::LoadOrQuitAction(LoadOrQuitModes mode, PromptMode savePromptMode) - : _mode(mode) - , _savePromptMode(savePromptMode) +namespace OpenRCT2::GameActions { -} - -void LoadOrQuitAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit("mode", _mode); - visitor.Visit("savePromptMode", _savePromptMode); -} - -uint16_t LoadOrQuitAction::GetActionFlags() const -{ - return GameAction::GetActionFlags() | GameActions::Flags::ClientOnly | GameActions::Flags::AllowWhilePaused; -} - -void LoadOrQuitAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_mode) << DS_TAG(_savePromptMode); -} - -GameActions::Result LoadOrQuitAction::Query() const -{ - return GameActions::Result(); -} - -GameActions::Result LoadOrQuitAction::Execute() const -{ - auto mode = static_cast(_mode); - switch (mode) + LoadOrQuitAction::LoadOrQuitAction(LoadOrQuitModes mode, PromptMode savePromptMode) + : _mode(mode) + , _savePromptMode(savePromptMode) { - case LoadOrQuitModes::OpenSavePrompt: - gSavePromptMode = _savePromptMode; - ContextOpenWindow(WindowClass::SavePrompt); - break; - case LoadOrQuitModes::CloseSavePrompt: - { - auto* windowMgr = Ui::GetWindowManager(); - windowMgr->CloseByClass(WindowClass::SavePrompt); - break; - } - default: - GameLoadOrQuitNoSavePrompt(); - break; } - return GameActions::Result(); -} + + void LoadOrQuitAction::AcceptParameters(GameActionParameterVisitor& visitor) + { + visitor.Visit("mode", _mode); + visitor.Visit("savePromptMode", _savePromptMode); + } + + uint16_t LoadOrQuitAction::GetActionFlags() const + { + return GameAction::GetActionFlags() | Flags::ClientOnly | Flags::AllowWhilePaused; + } + + void LoadOrQuitAction::Serialise(DataSerialiser& stream) + { + GameAction::Serialise(stream); + + stream << DS_TAG(_mode) << DS_TAG(_savePromptMode); + } + + Result LoadOrQuitAction::Query() const + { + return Result(); + } + + Result LoadOrQuitAction::Execute() const + { + auto mode = static_cast(_mode); + switch (mode) + { + case LoadOrQuitModes::OpenSavePrompt: + gSavePromptMode = _savePromptMode; + ContextOpenWindow(WindowClass::SavePrompt); + break; + case LoadOrQuitModes::CloseSavePrompt: + { + auto* windowMgr = Ui::GetWindowManager(); + windowMgr->CloseByClass(WindowClass::SavePrompt); + break; + } + default: + GameLoadOrQuitNoSavePrompt(); + break; + } + return Result(); + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/LoadOrQuitAction.h b/src/openrct2/actions/LoadOrQuitAction.h index 90bf913ff1..611cd9261e 100644 --- a/src/openrct2/actions/LoadOrQuitAction.h +++ b/src/openrct2/actions/LoadOrQuitAction.h @@ -12,27 +12,30 @@ #include "../interface/Window.h" #include "GameAction.h" -enum class LoadOrQuitModes : uint8_t +namespace OpenRCT2::GameActions { - OpenSavePrompt, - CloseSavePrompt -}; + enum class LoadOrQuitModes : uint8_t + { + OpenSavePrompt, + CloseSavePrompt + }; -class LoadOrQuitAction final : public GameActionBase -{ -private: - LoadOrQuitModes _mode{}; - PromptMode _savePromptMode{ PromptMode::saveBeforeLoad }; + class LoadOrQuitAction final : public GameActionBase + { + private: + LoadOrQuitModes _mode{}; + PromptMode _savePromptMode{ PromptMode::saveBeforeLoad }; -public: - LoadOrQuitAction() = default; - LoadOrQuitAction(LoadOrQuitModes mode, PromptMode savePromptMode = PromptMode::saveBeforeLoad); + public: + LoadOrQuitAction() = default; + LoadOrQuitAction(LoadOrQuitModes mode, PromptMode savePromptMode = PromptMode::saveBeforeLoad); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; -}; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/MapChangeSizeAction.cpp b/src/openrct2/actions/MapChangeSizeAction.cpp index ed60cbf00a..8f26677725 100644 --- a/src/openrct2/actions/MapChangeSizeAction.cpp +++ b/src/openrct2/actions/MapChangeSizeAction.cpp @@ -17,85 +17,84 @@ #include "../windows/Intent.h" #include "../world/Park.h" -using namespace OpenRCT2; - -MapChangeSizeAction::MapChangeSizeAction(const TileCoordsXY& targetSize) - : MapChangeSizeAction(targetSize, TileCoordsXY()) +namespace OpenRCT2::GameActions { -} - -MapChangeSizeAction::MapChangeSizeAction(const TileCoordsXY& targetSize, const TileCoordsXY& shift) - : _targetSize(targetSize) - , _shift(shift) -{ -} - -uint16_t MapChangeSizeAction::GetActionFlags() const -{ - return GameAction::GetActionFlags() | GameActions::Flags::AllowWhilePaused; -} - -void MapChangeSizeAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - stream << DS_TAG(_targetSize); - stream << DS_TAG(_shift); -} - -GameActions::Result MapChangeSizeAction::Query() const -{ - if (_targetSize.x > kMaximumMapSizeTechnical || _targetSize.y > kMaximumMapSizeTechnical) + MapChangeSizeAction::MapChangeSizeAction(const TileCoordsXY& targetSize) + : MapChangeSizeAction(targetSize, TileCoordsXY()) { - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_INCREASE_MAP_SIZE_ANY_FURTHER, STR_ERR_VALUE_OUT_OF_RANGE); - } - if (_targetSize.x < kMinimumMapSizeTechnical || _targetSize.y < kMinimumMapSizeTechnical) - { - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_DECREASE_MAP_SIZE_ANY_FURTHER, STR_ERR_VALUE_OUT_OF_RANGE); - } - return GameActions::Result(); -} - -GameActions::Result MapChangeSizeAction::Execute() const -{ - auto& gameState = getGameState(); - // Expand map - while (_targetSize.x > gameState.mapSize.x) - { - gameState.mapSize.x++; - MapExtendBoundarySurfaceX(); - } - while (_targetSize.y > gameState.mapSize.y) - { - gameState.mapSize.y++; - MapExtendBoundarySurfaceY(); } - // Shift the map (allows increasing the map at the 0,0 position - ShiftMap(_shift); - - // Shrink map - if (_targetSize.x < gameState.mapSize.x || _targetSize.y < gameState.mapSize.y) + MapChangeSizeAction::MapChangeSizeAction(const TileCoordsXY& targetSize, const TileCoordsXY& shift) + : _targetSize(targetSize) + , _shift(shift) { - gameState.mapSize = _targetSize; - MapRemoveOutOfRangeElements(); } - auto* ctx = OpenRCT2::GetContext(); - auto& uiContext = ctx->GetUiContext(); - auto* windowManager = uiContext.GetWindowManager(); - OpenRCT2::Park::UpdateSize(gameState); + uint16_t MapChangeSizeAction::GetActionFlags() const + { + return GameAction::GetActionFlags() | Flags::AllowWhilePaused; + } - windowManager->BroadcastIntent(Intent(INTENT_ACTION_MAP)); - GfxInvalidateScreen(); - return GameActions::Result(); -} + void MapChangeSizeAction::Serialise(DataSerialiser& stream) + { + GameAction::Serialise(stream); + stream << DS_TAG(_targetSize); + stream << DS_TAG(_shift); + } -void MapChangeSizeAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit("targetSizeX", _targetSize.x); - visitor.Visit("targetSizeY", _targetSize.y); - visitor.Visit("shiftX", _shift.x); - visitor.Visit("shiftY", _shift.y); -} + Result MapChangeSizeAction::Query() const + { + if (_targetSize.x > kMaximumMapSizeTechnical || _targetSize.y > kMaximumMapSizeTechnical) + { + return Result(Status::InvalidParameters, STR_CANT_INCREASE_MAP_SIZE_ANY_FURTHER, STR_ERR_VALUE_OUT_OF_RANGE); + } + if (_targetSize.x < kMinimumMapSizeTechnical || _targetSize.y < kMinimumMapSizeTechnical) + { + return Result(Status::InvalidParameters, STR_CANT_DECREASE_MAP_SIZE_ANY_FURTHER, STR_ERR_VALUE_OUT_OF_RANGE); + } + return Result(); + } + + Result MapChangeSizeAction::Execute() const + { + auto& gameState = getGameState(); + // Expand map + while (_targetSize.x > gameState.mapSize.x) + { + gameState.mapSize.x++; + MapExtendBoundarySurfaceX(); + } + while (_targetSize.y > gameState.mapSize.y) + { + gameState.mapSize.y++; + MapExtendBoundarySurfaceY(); + } + + // Shift the map (allows increasing the map at the 0,0 position + ShiftMap(_shift); + + // Shrink map + if (_targetSize.x < gameState.mapSize.x || _targetSize.y < gameState.mapSize.y) + { + gameState.mapSize = _targetSize; + MapRemoveOutOfRangeElements(); + } + + auto* ctx = OpenRCT2::GetContext(); + auto& uiContext = ctx->GetUiContext(); + auto* windowManager = uiContext.GetWindowManager(); + Park::UpdateSize(gameState); + + windowManager->BroadcastIntent(Intent(INTENT_ACTION_MAP)); + GfxInvalidateScreen(); + return Result(); + } + + void MapChangeSizeAction::AcceptParameters(GameActionParameterVisitor& visitor) + { + visitor.Visit("targetSizeX", _targetSize.x); + visitor.Visit("targetSizeY", _targetSize.y); + visitor.Visit("shiftX", _shift.x); + visitor.Visit("shiftY", _shift.y); + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/MapChangeSizeAction.h b/src/openrct2/actions/MapChangeSizeAction.h index 8c8d6a9944..5c8520c145 100644 --- a/src/openrct2/actions/MapChangeSizeAction.h +++ b/src/openrct2/actions/MapChangeSizeAction.h @@ -12,21 +12,24 @@ #include "../world/Map.h" #include "GameAction.h" -class MapChangeSizeAction final : public GameActionBase +namespace OpenRCT2::GameActions { -public: - MapChangeSizeAction() = default; - MapChangeSizeAction(const TileCoordsXY& targetSize); - MapChangeSizeAction(const TileCoordsXY& targetSize, const TileCoordsXY& shift); + class MapChangeSizeAction final : public GameActionBase + { + public: + MapChangeSizeAction() = default; + MapChangeSizeAction(const TileCoordsXY& targetSize); + MapChangeSizeAction(const TileCoordsXY& targetSize, const TileCoordsXY& shift); - void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; -private: - TileCoordsXY _targetSize; - TileCoordsXY _shift; -}; + private: + TileCoordsXY _targetSize; + TileCoordsXY _shift; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/MazePlaceTrackAction.cpp b/src/openrct2/actions/MazePlaceTrackAction.cpp index 3ee2f4638f..84d42a1a67 100644 --- a/src/openrct2/actions/MazePlaceTrackAction.cpp +++ b/src/openrct2/actions/MazePlaceTrackAction.cpp @@ -20,187 +20,188 @@ #include "../world/tile_element/SurfaceElement.h" #include "../world/tile_element/TrackElement.h" -using namespace OpenRCT2; - -using namespace OpenRCT2::TrackMetaData; - -MazePlaceTrackAction::MazePlaceTrackAction(const CoordsXYZ& location, RideId rideIndex, uint16_t mazeEntry) - : _loc(location) - , _rideIndex(rideIndex) - , _mazeEntry(mazeEntry) +namespace OpenRCT2::GameActions { -} + using namespace OpenRCT2::TrackMetaData; -void MazePlaceTrackAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit(_loc); - visitor.Visit("ride", _rideIndex); - visitor.Visit("mazeEntry", _mazeEntry); -} - -void MazePlaceTrackAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - stream << DS_TAG(_loc) << DS_TAG(_rideIndex) << DS_TAG(_mazeEntry); -} - -GameActions::Result MazePlaceTrackAction::Query() const -{ - auto res = GameActions::Result(); - - res.Position = _loc + CoordsXYZ{ 8, 8, 0 }; - res.Expenditure = ExpenditureType::rideConstruction; - res.ErrorTitle = STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE; - if ((_loc.z & 0xF) != 0) + MazePlaceTrackAction::MazePlaceTrackAction(const CoordsXYZ& location, RideId rideIndex, uint16_t mazeEntry) + : _loc(location) + , _rideIndex(rideIndex) + , _mazeEntry(mazeEntry) { - res.Error = GameActions::Status::Unknown; - res.ErrorMessage = STR_INVALID_HEIGHT; - return res; } - if (!LocationValid(_loc)) + void MazePlaceTrackAction::AcceptParameters(GameActionParameterVisitor& visitor) { - res.Error = GameActions::Status::InvalidParameters; - res.ErrorMessage = STR_OFF_EDGE_OF_MAP; - return res; - } - auto& gameState = getGameState(); - if (!MapIsLocationOwned(_loc) && !gameState.cheats.sandboxMode) - { - res.Error = GameActions::Status::NotOwned; - res.ErrorMessage = STR_LAND_NOT_OWNED_BY_PARK; - return res; + visitor.Visit(_loc); + visitor.Visit("ride", _rideIndex); + visitor.Visit("mazeEntry", _mazeEntry); } - if (!MapCheckCapacityAndReorganise(_loc)) + void MazePlaceTrackAction::Serialise(DataSerialiser& stream) { - res.Error = GameActions::Status::NoFreeElements; - res.ErrorMessage = STR_TILE_ELEMENT_LIMIT_REACHED; - return res; - } - auto surfaceElement = MapGetSurfaceElementAt(_loc); - if (surfaceElement == nullptr) - { - res.Error = GameActions::Status::Unknown; - res.ErrorMessage = STR_INVALID_SELECTION_OF_OBJECTS; - return res; + GameAction::Serialise(stream); + stream << DS_TAG(_loc) << DS_TAG(_rideIndex) << DS_TAG(_mazeEntry); } - auto baseHeight = _loc.z; - auto clearanceHeight = _loc.z + kMazeClearanceHeight; - - auto heightDifference = baseHeight - surfaceElement->GetBaseZ(); - if (heightDifference >= 0 && !gameState.cheats.disableSupportLimits) + Result MazePlaceTrackAction::Query() const { - heightDifference /= kCoordsZPerTinyZ; + auto res = Result(); - auto* ride = GetRide(_rideIndex); - const auto& rtd = ride->getRideTypeDescriptor(); - if (heightDifference > rtd.Heights.MaxHeight) + res.Position = _loc + CoordsXYZ{ 8, 8, 0 }; + res.Expenditure = ExpenditureType::rideConstruction; + res.ErrorTitle = STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE; + if ((_loc.z & 0xF) != 0) { - res.Error = GameActions::Status::TooHigh; - res.ErrorMessage = STR_TOO_HIGH_FOR_SUPPORTS; + res.Error = Status::Unknown; + res.ErrorMessage = STR_INVALID_HEIGHT; return res; } - } - auto canBuild = MapCanConstructWithClearAt( - { _loc.ToTileStart(), baseHeight, clearanceHeight }, &MapPlaceNonSceneryClearFunc, { 0b1111, 0 }, GetFlags()); - if (canBuild.Error != GameActions::Status::Ok) - { - canBuild.ErrorTitle = STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE; - return canBuild; - } + if (!LocationValid(_loc)) + { + res.Error = Status::InvalidParameters; + res.ErrorMessage = STR_OFF_EDGE_OF_MAP; + return res; + } + auto& gameState = getGameState(); + if (!MapIsLocationOwned(_loc) && !gameState.cheats.sandboxMode) + { + res.Error = Status::NotOwned; + res.ErrorMessage = STR_LAND_NOT_OWNED_BY_PARK; + return res; + } + + if (!MapCheckCapacityAndReorganise(_loc)) + { + res.Error = Status::NoFreeElements; + res.ErrorMessage = STR_TILE_ELEMENT_LIMIT_REACHED; + return res; + } + auto surfaceElement = MapGetSurfaceElementAt(_loc); + if (surfaceElement == nullptr) + { + res.Error = Status::Unknown; + res.ErrorMessage = STR_INVALID_SELECTION_OF_OBJECTS; + return res; + } + + auto baseHeight = _loc.z; + auto clearanceHeight = _loc.z + kMazeClearanceHeight; + + auto heightDifference = baseHeight - surfaceElement->GetBaseZ(); + if (heightDifference >= 0 && !gameState.cheats.disableSupportLimits) + { + heightDifference /= kCoordsZPerTinyZ; + + auto* ride = GetRide(_rideIndex); + const auto& rtd = ride->getRideTypeDescriptor(); + if (heightDifference > rtd.Heights.MaxHeight) + { + res.Error = Status::TooHigh; + res.ErrorMessage = STR_TOO_HIGH_FOR_SUPPORTS; + return res; + } + } + + auto canBuild = MapCanConstructWithClearAt( + { _loc.ToTileStart(), baseHeight, clearanceHeight }, &MapPlaceNonSceneryClearFunc, { 0b1111, 0 }, GetFlags()); + if (canBuild.Error != Status::Ok) + { + canBuild.ErrorTitle = STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE; + return canBuild; + } + + const auto clearanceData = canBuild.GetData(); + if (clearanceData.GroundFlags & ELEMENT_IS_UNDERWATER) + { + res.Error = Status::NoClearance; + res.ErrorMessage = STR_RIDE_CANT_BUILD_THIS_UNDERWATER; + return res; + } + + if (clearanceData.GroundFlags & ELEMENT_IS_UNDERGROUND) + { + res.Error = Status::NoClearance; + res.ErrorMessage = STR_CAN_ONLY_BUILD_THIS_ABOVE_GROUND; + return res; + } + + auto ride = GetRide(_rideIndex); + if (ride == nullptr || ride->type == kRideTypeNull) + { + LOG_ERROR("Ride not found for rideIndex %u", _rideIndex); + res.Error = Status::InvalidParameters; + res.ErrorMessage = STR_ERR_RIDE_NOT_FOUND; + return res; + } + + res.Cost = MazeCalculateCost(canBuild.Cost, *ride, _loc); - const auto clearanceData = canBuild.GetData(); - if (clearanceData.GroundFlags & ELEMENT_IS_UNDERWATER) - { - res.Error = GameActions::Status::NoClearance; - res.ErrorMessage = STR_RIDE_CANT_BUILD_THIS_UNDERWATER; return res; } - if (clearanceData.GroundFlags & ELEMENT_IS_UNDERGROUND) + Result MazePlaceTrackAction::Execute() const { - res.Error = GameActions::Status::NoClearance; - res.ErrorMessage = STR_CAN_ONLY_BUILD_THIS_ABOVE_GROUND; + auto res = Result(); + + res.Position = _loc + CoordsXYZ{ 8, 8, 0 }; + res.Expenditure = ExpenditureType::rideConstruction; + res.ErrorTitle = STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE; + + auto ride = GetRide(_rideIndex); + if (ride == nullptr) + { + LOG_ERROR("Ride not found for rideIndex %u", _rideIndex); + res.Error = Status::InvalidParameters; + res.ErrorMessage = STR_ERR_RIDE_NOT_FOUND; + return res; + } + + uint32_t flags = GetFlags(); + if (!(flags & GAME_COMMAND_FLAG_GHOST)) + { + FootpathRemoveLitter(_loc); + WallRemoveAt({ _loc.ToTileStart(), _loc.z, _loc.z + 32 }); + } + + auto baseHeight = _loc.z; + auto clearanceHeight = _loc.z + kMazeClearanceHeight; + + auto canBuild = MapCanConstructWithClearAt( + { _loc.ToTileStart(), baseHeight, clearanceHeight }, &MapPlaceNonSceneryClearFunc, { 0b1111, 0 }, + GetFlags() | GAME_COMMAND_FLAG_APPLY); + if (canBuild.Error != Status::Ok) + { + canBuild.ErrorTitle = STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE; + return canBuild; + } + + res.Cost = MazeCalculateCost(canBuild.Cost, *ride, _loc); + + auto startLoc = _loc.ToTileStart(); + + auto* trackElement = TileElementInsert(_loc, 0b1111); + Guard::Assert(trackElement != nullptr); + + trackElement->SetClearanceZ(clearanceHeight); + trackElement->SetTrackType(TrackElemType::Maze); + trackElement->SetRideType(ride->type); + trackElement->SetRideIndex(_rideIndex); + trackElement->SetMazeEntry(_mazeEntry); + trackElement->SetGhost(flags & GAME_COMMAND_FLAG_GHOST); + + MapInvalidateTileFull(startLoc); + + ride->mazeTiles++; + ride->getStation().SetBaseZ(trackElement->GetBaseZ()); + ride->getStation().Start = { 0, 0 }; + + if (ride->mazeTiles == 1) + { + ride->overallView = startLoc; + } + return res; } - - auto ride = GetRide(_rideIndex); - if (ride == nullptr || ride->type == kRideTypeNull) - { - LOG_ERROR("Ride not found for rideIndex %u", _rideIndex); - res.Error = GameActions::Status::InvalidParameters; - res.ErrorMessage = STR_ERR_RIDE_NOT_FOUND; - return res; - } - - res.Cost = MazeCalculateCost(canBuild.Cost, *ride, _loc); - - return res; -} - -GameActions::Result MazePlaceTrackAction::Execute() const -{ - auto res = GameActions::Result(); - - res.Position = _loc + CoordsXYZ{ 8, 8, 0 }; - res.Expenditure = ExpenditureType::rideConstruction; - res.ErrorTitle = STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE; - - auto ride = GetRide(_rideIndex); - if (ride == nullptr) - { - LOG_ERROR("Ride not found for rideIndex %u", _rideIndex); - res.Error = GameActions::Status::InvalidParameters; - res.ErrorMessage = STR_ERR_RIDE_NOT_FOUND; - return res; - } - - uint32_t flags = GetFlags(); - if (!(flags & GAME_COMMAND_FLAG_GHOST)) - { - FootpathRemoveLitter(_loc); - WallRemoveAt({ _loc.ToTileStart(), _loc.z, _loc.z + 32 }); - } - - auto baseHeight = _loc.z; - auto clearanceHeight = _loc.z + kMazeClearanceHeight; - - auto canBuild = MapCanConstructWithClearAt( - { _loc.ToTileStart(), baseHeight, clearanceHeight }, &MapPlaceNonSceneryClearFunc, { 0b1111, 0 }, - GetFlags() | GAME_COMMAND_FLAG_APPLY); - if (canBuild.Error != GameActions::Status::Ok) - { - canBuild.ErrorTitle = STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE; - return canBuild; - } - - res.Cost = MazeCalculateCost(canBuild.Cost, *ride, _loc); - - auto startLoc = _loc.ToTileStart(); - - auto* trackElement = TileElementInsert(_loc, 0b1111); - Guard::Assert(trackElement != nullptr); - - trackElement->SetClearanceZ(clearanceHeight); - trackElement->SetTrackType(TrackElemType::Maze); - trackElement->SetRideType(ride->type); - trackElement->SetRideIndex(_rideIndex); - trackElement->SetMazeEntry(_mazeEntry); - trackElement->SetGhost(flags & GAME_COMMAND_FLAG_GHOST); - - MapInvalidateTileFull(startLoc); - - ride->mazeTiles++; - ride->getStation().SetBaseZ(trackElement->GetBaseZ()); - ride->getStation().Start = { 0, 0 }; - - if (ride->mazeTiles == 1) - { - ride->overallView = startLoc; - } - - return res; -} +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/MazePlaceTrackAction.h b/src/openrct2/actions/MazePlaceTrackAction.h index 0efbc3e634..b2bb6086c5 100644 --- a/src/openrct2/actions/MazePlaceTrackAction.h +++ b/src/openrct2/actions/MazePlaceTrackAction.h @@ -6,23 +6,27 @@ * * OpenRCT2 is licensed under the GNU General Public License version 3. *****************************************************************************/ + #pragma once #include "GameAction.h" -class MazePlaceTrackAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - CoordsXYZ _loc; - RideId _rideIndex{ RideId::GetNull() }; - uint16_t _mazeEntry{}; + class MazePlaceTrackAction final : public GameActionBase + { + private: + CoordsXYZ _loc; + RideId _rideIndex{ RideId::GetNull() }; + uint16_t _mazeEntry{}; -public: - MazePlaceTrackAction() = default; - MazePlaceTrackAction(const CoordsXYZ& location, RideId rideIndex, uint16_t mazeEntry); + public: + MazePlaceTrackAction() = default; + MazePlaceTrackAction(const CoordsXYZ& location, RideId rideIndex, uint16_t mazeEntry); - void AcceptParameters(GameActionParameterVisitor& visitor) override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; -}; + void AcceptParameters(GameActionParameterVisitor& visitor) override; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/MazeSetTrackAction.cpp b/src/openrct2/actions/MazeSetTrackAction.cpp index 0b82b3df99..ee29f25876 100644 --- a/src/openrct2/actions/MazeSetTrackAction.cpp +++ b/src/openrct2/actions/MazeSetTrackAction.cpp @@ -26,339 +26,341 @@ #include "../world/tile_element/SurfaceElement.h" #include "../world/tile_element/TrackElement.h" -using namespace OpenRCT2; - -using namespace OpenRCT2::TrackMetaData; - -// clang-format off -/** rct2: 0x00993CE9 */ -static constexpr uint8_t kByte993CE9[] = { - 0xFF, 0xE0, 0xFF, - 14, 0, 1, 2, - 6, 2, 4, 5, - 9, 10, 6, 8, - 12, 13, 14, 10, -}; - -/** rct2: 0x00993CFC */ -static constexpr uint8_t kByte993CFC[] = { - 5, 12, 0xFF, 0xFF, - 9, 0, 0xFF, 0xFF, - 13, 4, 0xFF, 0xFF, - 1, 8, 0xFF, 0xFF, -}; - -/** rct2: 0x00993D0C */ -static constexpr uint8_t kByte993D0C[] = { - 3, 0, 0xFF, 0xFF, - 0, 1, 0xFF, 0xFF, - 1, 2, 0xFF, 0xFF, - 2, 3, 0xFF, 0xFF, -}; -// clang-format on - -MazeSetTrackAction::MazeSetTrackAction(const CoordsXYZD& location, bool initialPlacement, RideId rideIndex, uint8_t mode) - : _loc(location) - , _initialPlacement(initialPlacement) - , _rideIndex(rideIndex) - , _mode(mode) +namespace OpenRCT2::GameActions { -} + using namespace OpenRCT2::TrackMetaData; -void MazeSetTrackAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit(_loc); - visitor.Visit("ride", _rideIndex); - visitor.Visit("mode", _mode); - visitor.Visit("isInitialPlacement", _initialPlacement); -} + // clang-format off + /** rct2: 0x00993CE9 */ + static constexpr uint8_t kByte993CE9[] = { + 0xFF, 0xE0, 0xFF, + 14, 0, 1, 2, + 6, 2, 4, 5, + 9, 10, 6, 8, + 12, 13, 14, 10, + }; -void MazeSetTrackAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - stream << DS_TAG(_loc) << DS_TAG(_loc.direction) << DS_TAG(_initialPlacement) << DS_TAG(_rideIndex) << DS_TAG(_mode); -} + /** rct2: 0x00993CFC */ + static constexpr uint8_t kByte993CFC[] = { + 5, 12, 0xFF, 0xFF, + 9, 0, 0xFF, 0xFF, + 13, 4, 0xFF, 0xFF, + 1, 8, 0xFF, 0xFF, + }; -GameActions::Result MazeSetTrackAction::Query() const -{ - auto res = GameActions::Result(); + /** rct2: 0x00993D0C */ + static constexpr uint8_t kByte993D0C[] = { + 3, 0, 0xFF, 0xFF, + 0, 1, 0xFF, 0xFF, + 1, 2, 0xFF, 0xFF, + 2, 3, 0xFF, 0xFF, + }; + // clang-format on - res.Position = _loc + CoordsXYZ{ 8, 8, 0 }; - res.Expenditure = ExpenditureType::rideConstruction; - res.ErrorTitle = STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE; - if ((_loc.z & 0xF) != 0 && _mode == GC_SET_MAZE_TRACK_BUILD) + MazeSetTrackAction::MazeSetTrackAction(const CoordsXYZD& location, bool initialPlacement, RideId rideIndex, uint8_t mode) + : _loc(location) + , _initialPlacement(initialPlacement) + , _rideIndex(rideIndex) + , _mode(mode) { - res.Error = GameActions::Status::Unknown; - res.ErrorMessage = STR_INVALID_HEIGHT; - return res; } - if (!LocationValid(_loc)) + void MazeSetTrackAction::AcceptParameters(GameActionParameterVisitor& visitor) { - res.Error = GameActions::Status::InvalidParameters; - res.ErrorMessage = STR_OFF_EDGE_OF_MAP; - return res; - } - auto& gameState = getGameState(); - if (!MapIsLocationOwned(_loc) && !gameState.cheats.sandboxMode) - { - res.Error = GameActions::Status::NotOwned; - res.ErrorMessage = STR_LAND_NOT_OWNED_BY_PARK; - return res; + visitor.Visit(_loc); + visitor.Visit("ride", _rideIndex); + visitor.Visit("mode", _mode); + visitor.Visit("isInitialPlacement", _initialPlacement); } - if (!MapCheckCapacityAndReorganise(_loc)) + void MazeSetTrackAction::Serialise(DataSerialiser& stream) { - res.Error = GameActions::Status::NoFreeElements; - res.ErrorMessage = STR_TILE_ELEMENT_LIMIT_REACHED; - return res; - } - auto surfaceElement = MapGetSurfaceElementAt(_loc); - if (surfaceElement == nullptr) - { - res.Error = GameActions::Status::Unknown; - res.ErrorMessage = STR_INVALID_SELECTION_OF_OBJECTS; - return res; + GameAction::Serialise(stream); + stream << DS_TAG(_loc) << DS_TAG(_loc.direction) << DS_TAG(_initialPlacement) << DS_TAG(_rideIndex) << DS_TAG(_mode); } - auto baseHeight = _loc.z; - auto clearanceHeight = _loc.z + 32; - - auto heightDifference = baseHeight - surfaceElement->GetBaseZ(); - if (heightDifference >= 0 && !gameState.cheats.disableSupportLimits) + Result MazeSetTrackAction::Query() const { - heightDifference /= kCoordsZPerTinyZ; + auto res = Result(); - auto* ride = GetRide(_rideIndex); - const auto& rtd = ride->getRideTypeDescriptor(); - if (heightDifference > rtd.Heights.MaxHeight) + res.Position = _loc + CoordsXYZ{ 8, 8, 0 }; + res.Expenditure = ExpenditureType::rideConstruction; + res.ErrorTitle = STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE; + if ((_loc.z & 0xF) != 0 && _mode == GC_SET_MAZE_TRACK_BUILD) { - res.Error = GameActions::Status::TooHigh; - res.ErrorMessage = STR_TOO_HIGH_FOR_SUPPORTS; + res.Error = Status::Unknown; + res.ErrorMessage = STR_INVALID_HEIGHT; return res; } - } - TileElement* tileElement = MapGetTrackElementAtOfTypeFromRide(_loc, TrackElemType::Maze, _rideIndex); - if (tileElement == nullptr) - { - if (_mode != GC_SET_MAZE_TRACK_BUILD) + if (!LocationValid(_loc)) { - res.Error = GameActions::Status::Unknown; + res.Error = Status::InvalidParameters; + res.ErrorMessage = STR_OFF_EDGE_OF_MAP; + return res; + } + auto& gameState = getGameState(); + if (!MapIsLocationOwned(_loc) && !gameState.cheats.sandboxMode) + { + res.Error = Status::NotOwned; + res.ErrorMessage = STR_LAND_NOT_OWNED_BY_PARK; + return res; + } + + if (!MapCheckCapacityAndReorganise(_loc)) + { + res.Error = Status::NoFreeElements; + res.ErrorMessage = STR_TILE_ELEMENT_LIMIT_REACHED; + return res; + } + auto surfaceElement = MapGetSurfaceElementAt(_loc); + if (surfaceElement == nullptr) + { + res.Error = Status::Unknown; res.ErrorMessage = STR_INVALID_SELECTION_OF_OBJECTS; return res; } - auto constructResult = MapCanConstructAt({ _loc.ToTileStart(), baseHeight, clearanceHeight }, { 0b1111, 0 }); - if (constructResult.Error != GameActions::Status::Ok) + + auto baseHeight = _loc.z; + auto clearanceHeight = _loc.z + 32; + + auto heightDifference = baseHeight - surfaceElement->GetBaseZ(); + if (heightDifference >= 0 && !gameState.cheats.disableSupportLimits) { - constructResult.ErrorTitle = STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE; - return constructResult; + heightDifference /= kCoordsZPerTinyZ; + + auto* ride = GetRide(_rideIndex); + const auto& rtd = ride->getRideTypeDescriptor(); + if (heightDifference > rtd.Heights.MaxHeight) + { + res.Error = Status::TooHigh; + res.ErrorMessage = STR_TOO_HIGH_FOR_SUPPORTS; + return res; + } } - const auto clearanceData = constructResult.GetData(); - if (clearanceData.GroundFlags & ELEMENT_IS_UNDERWATER) + TileElement* tileElement = MapGetTrackElementAtOfTypeFromRide(_loc, TrackElemType::Maze, _rideIndex); + if (tileElement == nullptr) { - res.Error = GameActions::Status::NoClearance; - res.ErrorMessage = STR_RIDE_CANT_BUILD_THIS_UNDERWATER; + if (_mode != GC_SET_MAZE_TRACK_BUILD) + { + res.Error = Status::Unknown; + res.ErrorMessage = STR_INVALID_SELECTION_OF_OBJECTS; + return res; + } + auto constructResult = MapCanConstructAt({ _loc.ToTileStart(), baseHeight, clearanceHeight }, { 0b1111, 0 }); + if (constructResult.Error != Status::Ok) + { + constructResult.ErrorTitle = STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE; + return constructResult; + } + + const auto clearanceData = constructResult.GetData(); + if (clearanceData.GroundFlags & ELEMENT_IS_UNDERWATER) + { + res.Error = Status::NoClearance; + res.ErrorMessage = STR_RIDE_CANT_BUILD_THIS_UNDERWATER; + return res; + } + + if (clearanceData.GroundFlags & ELEMENT_IS_UNDERGROUND) + { + res.Error = Status::NoClearance; + res.ErrorMessage = STR_CAN_ONLY_BUILD_THIS_ABOVE_GROUND; + return res; + } + + auto ride = GetRide(_rideIndex); + if (ride == nullptr || !RideTypeIsValid(ride->type)) + { + LOG_ERROR("Ride not found for rideIndex %u", _rideIndex); + res.Error = Status::NoClearance; + res.ErrorMessage = STR_ERR_RIDE_NOT_FOUND; + return res; + } + + res.Cost = MazeCalculateCost(constructResult.Cost, *ride, _loc); + return res; } - if (clearanceData.GroundFlags & ELEMENT_IS_UNDERGROUND) - { - res.Error = GameActions::Status::NoClearance; - res.ErrorMessage = STR_CAN_ONLY_BUILD_THIS_ABOVE_GROUND; - return res; - } + return Result(); + } + + Result MazeSetTrackAction::Execute() const + { + auto res = Result(); + + res.Position = _loc + CoordsXYZ{ 8, 8, 0 }; + res.Expenditure = ExpenditureType::rideConstruction; + res.ErrorTitle = STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE; auto ride = GetRide(_rideIndex); - if (ride == nullptr || !RideTypeIsValid(ride->type)) + if (ride == nullptr) { LOG_ERROR("Ride not found for rideIndex %u", _rideIndex); - res.Error = GameActions::Status::NoClearance; + res.Error = Status::InvalidParameters; res.ErrorMessage = STR_ERR_RIDE_NOT_FOUND; return res; } - res.Cost = MazeCalculateCost(constructResult.Cost, *ride, _loc); - - return res; - } - - return GameActions::Result(); -} - -GameActions::Result MazeSetTrackAction::Execute() const -{ - auto res = GameActions::Result(); - - res.Position = _loc + CoordsXYZ{ 8, 8, 0 }; - res.Expenditure = ExpenditureType::rideConstruction; - res.ErrorTitle = STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE; - - auto ride = GetRide(_rideIndex); - if (ride == nullptr) - { - LOG_ERROR("Ride not found for rideIndex %u", _rideIndex); - res.Error = GameActions::Status::InvalidParameters; - res.ErrorMessage = STR_ERR_RIDE_NOT_FOUND; - return res; - } - - uint32_t flags = GetFlags(); - if (!(flags & GAME_COMMAND_FLAG_GHOST)) - { - FootpathRemoveLitter(_loc); - WallRemoveAt({ _loc.ToTileStart(), _loc.z, _loc.z + 32 }); - } - - auto tileElement = MapGetTrackElementAtOfTypeFromRide(_loc, TrackElemType::Maze, _rideIndex); - if (tileElement == nullptr) - { - res.Cost = MazeCalculateCost(0, *ride, _loc); - - auto startLoc = _loc.ToTileStart(); - - auto* trackElement = TileElementInsert(_loc, 0b1111); - Guard::Assert(trackElement != nullptr); - - trackElement->SetClearanceZ(_loc.z + kMazeClearanceHeight); - trackElement->SetTrackType(TrackElemType::Maze); - trackElement->SetRideType(ride->type); - trackElement->SetRideIndex(_rideIndex); - trackElement->SetMazeEntry(0xFFFF); - trackElement->SetGhost(flags & GAME_COMMAND_FLAG_GHOST); - - tileElement = trackElement->as(); - - MapInvalidateTileFull(startLoc); - - ride->mazeTiles++; - ride->getStation().SetBaseZ(tileElement->GetBaseZ()); - ride->getStation().Start = { 0, 0 }; - - if (_initialPlacement && !(flags & GAME_COMMAND_FLAG_GHOST)) + uint32_t flags = GetFlags(); + if (!(flags & GAME_COMMAND_FLAG_GHOST)) { - ride->overallView = startLoc; + FootpathRemoveLitter(_loc); + WallRemoveAt({ _loc.ToTileStart(), _loc.z, _loc.z + 32 }); } - } - switch (_mode) - { - case GC_SET_MAZE_TRACK_BUILD: + auto tileElement = MapGetTrackElementAtOfTypeFromRide(_loc, TrackElemType::Maze, _rideIndex); + if (tileElement == nullptr) { - uint8_t segmentOffset = MazeGetSegmentBit(_loc); + res.Cost = MazeCalculateCost(0, *ride, _loc); - tileElement->AsTrack()->MazeEntrySubtract(1 << segmentOffset); + auto startLoc = _loc.ToTileStart(); - if (!_initialPlacement) + auto* trackElement = TileElementInsert(_loc, 0b1111); + Guard::Assert(trackElement != nullptr); + + trackElement->SetClearanceZ(_loc.z + kMazeClearanceHeight); + trackElement->SetTrackType(TrackElemType::Maze); + trackElement->SetRideType(ride->type); + trackElement->SetRideIndex(_rideIndex); + trackElement->SetMazeEntry(0xFFFF); + trackElement->SetGhost(flags & GAME_COMMAND_FLAG_GHOST); + + tileElement = trackElement->as(); + + MapInvalidateTileFull(startLoc); + + ride->mazeTiles++; + ride->getStation().SetBaseZ(tileElement->GetBaseZ()); + ride->getStation().Start = { 0, 0 }; + + if (_initialPlacement && !(flags & GAME_COMMAND_FLAG_GHOST)) { - segmentOffset = kByte993CE9[(_loc.direction + segmentOffset)]; + ride->overallView = startLoc; + } + } + + switch (_mode) + { + case GC_SET_MAZE_TRACK_BUILD: + { + uint8_t segmentOffset = MazeGetSegmentBit(_loc); + tileElement->AsTrack()->MazeEntrySubtract(1 << segmentOffset); - uint8_t temp_edx = kByte993CFC[segmentOffset]; - if (temp_edx != 0xFF) + if (!_initialPlacement) { - auto previousElementLoc = CoordsXY{ _loc }.ToTileStart() - CoordsDirectionDelta[_loc.direction]; + segmentOffset = kByte993CE9[(_loc.direction + segmentOffset)]; + tileElement->AsTrack()->MazeEntrySubtract(1 << segmentOffset); - TileElement* previousTileElement = MapGetTrackElementAtOfTypeFromRide( - { previousElementLoc, _loc.z }, TrackElemType::Maze, _rideIndex); + uint8_t temp_edx = kByte993CFC[segmentOffset]; + if (temp_edx != 0xFF) + { + auto previousElementLoc = CoordsXY{ _loc }.ToTileStart() - CoordsDirectionDelta[_loc.direction]; - if (previousTileElement != nullptr) - { - previousTileElement->AsTrack()->MazeEntrySubtract(1 << temp_edx); - } - else - { - tileElement->AsTrack()->MazeEntryAdd(1 << segmentOffset); + TileElement* previousTileElement = MapGetTrackElementAtOfTypeFromRide( + { previousElementLoc, _loc.z }, TrackElemType::Maze, _rideIndex); + + if (previousTileElement != nullptr) + { + previousTileElement->AsTrack()->MazeEntrySubtract(1 << temp_edx); + } + else + { + tileElement->AsTrack()->MazeEntryAdd(1 << segmentOffset); + } } } + + break; } - break; + case GC_SET_MAZE_TRACK_MOVE: + break; + + case GC_SET_MAZE_TRACK_FILL: + if (!_initialPlacement) + { + auto previousSegment = CoordsXY{ _loc.x - CoordsDirectionDelta[_loc.direction].x / 2, + _loc.y - CoordsDirectionDelta[_loc.direction].y / 2 }; + + tileElement = MapGetTrackElementAtOfTypeFromRide( + { previousSegment, _loc.z }, TrackElemType::Maze, _rideIndex); + + MapInvalidateTileFull(previousSegment.ToTileStart()); + if (tileElement == nullptr) + { + LOG_ERROR("No surface found"); + res.Error = Status::Unknown; + res.ErrorMessage = STR_ERR_SURFACE_ELEMENT_NOT_FOUND; + return res; + } + + uint32_t segmentBit = MazeGetSegmentBit(previousSegment); + + tileElement->AsTrack()->MazeEntryAdd(1 << segmentBit); + segmentBit--; + tileElement->AsTrack()->MazeEntryAdd(1 << segmentBit); + segmentBit = (segmentBit - 4) & 0x0F; + tileElement->AsTrack()->MazeEntryAdd(1 << segmentBit); + segmentBit = (segmentBit + 3) & 0x0F; + + do + { + tileElement->AsTrack()->MazeEntryAdd(1 << segmentBit); + + uint32_t direction1 = kByte993D0C[segmentBit]; + auto nextElementLoc = previousSegment.ToTileStart() + CoordsDirectionDelta[direction1]; + + TileElement* tmp_tileElement = MapGetTrackElementAtOfTypeFromRide( + { nextElementLoc, _loc.z }, TrackElemType::Maze, _rideIndex); + + if (tmp_tileElement != nullptr) + { + uint8_t edx11 = kByte993CFC[segmentBit]; + tmp_tileElement->AsTrack()->MazeEntryAdd(1 << (edx11)); + } + + segmentBit--; + } while ((segmentBit & 0x3) != 0x3); + } + break; } - case GC_SET_MAZE_TRACK_MOVE: - break; + MapInvalidateTile({ _loc.ToTileStart(), tileElement->GetBaseZ(), tileElement->GetClearanceZ() }); - case GC_SET_MAZE_TRACK_FILL: - if (!_initialPlacement) - { - auto previousSegment = CoordsXY{ _loc.x - CoordsDirectionDelta[_loc.direction].x / 2, - _loc.y - CoordsDirectionDelta[_loc.direction].y / 2 }; + if ((tileElement->AsTrack()->GetMazeEntry() & 0x8888) == 0x8888) + { + TileElementRemove(tileElement); + ride->validateStations(); + ride->mazeTiles--; + } - tileElement = MapGetTrackElementAtOfTypeFromRide({ previousSegment, _loc.z }, TrackElemType::Maze, _rideIndex); - - MapInvalidateTileFull(previousSegment.ToTileStart()); - if (tileElement == nullptr) - { - LOG_ERROR("No surface found"); - res.Error = GameActions::Status::Unknown; - res.ErrorMessage = STR_ERR_SURFACE_ELEMENT_NOT_FOUND; - return res; - } - - uint32_t segmentBit = MazeGetSegmentBit(previousSegment); - - tileElement->AsTrack()->MazeEntryAdd(1 << segmentBit); - segmentBit--; - tileElement->AsTrack()->MazeEntryAdd(1 << segmentBit); - segmentBit = (segmentBit - 4) & 0x0F; - tileElement->AsTrack()->MazeEntryAdd(1 << segmentBit); - segmentBit = (segmentBit + 3) & 0x0F; - - do - { - tileElement->AsTrack()->MazeEntryAdd(1 << segmentBit); - - uint32_t direction1 = kByte993D0C[segmentBit]; - auto nextElementLoc = previousSegment.ToTileStart() + CoordsDirectionDelta[direction1]; - - TileElement* tmp_tileElement = MapGetTrackElementAtOfTypeFromRide( - { nextElementLoc, _loc.z }, TrackElemType::Maze, _rideIndex); - - if (tmp_tileElement != nullptr) - { - uint8_t edx11 = kByte993CFC[segmentBit]; - tmp_tileElement->AsTrack()->MazeEntryAdd(1 << (edx11)); - } - - segmentBit--; - } while ((segmentBit & 0x3) != 0x3); - } - break; + return res; } - MapInvalidateTile({ _loc.ToTileStart(), tileElement->GetBaseZ(), tileElement->GetClearanceZ() }); - - if ((tileElement->AsTrack()->GetMazeEntry() & 0x8888) == 0x8888) + uint8_t MazeSetTrackAction::MazeGetSegmentBit(const CoordsXY& coords) const { - TileElementRemove(tileElement); - ride->validateStations(); - ride->mazeTiles--; + uint8_t minorX = coords.x & 0x1F; + uint8_t minorY = coords.y & 0x1F; + + if (minorX == 0 && minorY == 0) + { + return 3; + } + + if (minorY == 16 && minorX == 16) + { + return 11; + } + + if (minorY == 0) + { + return 15; + } + + return 7; } - - return res; -} - -uint8_t MazeSetTrackAction::MazeGetSegmentBit(const CoordsXY& coords) const -{ - uint8_t minorX = coords.x & 0x1F; - uint8_t minorY = coords.y & 0x1F; - - if (minorX == 0 && minorY == 0) - { - return 3; - } - - if (minorY == 16 && minorX == 16) - { - return 11; - } - - if (minorY == 0) - { - return 15; - } - - return 7; -} +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/MazeSetTrackAction.h b/src/openrct2/actions/MazeSetTrackAction.h index ad2619323a..bbd70abf54 100644 --- a/src/openrct2/actions/MazeSetTrackAction.h +++ b/src/openrct2/actions/MazeSetTrackAction.h @@ -11,23 +11,26 @@ #include "GameAction.h" -class MazeSetTrackAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - CoordsXYZD _loc; - bool _initialPlacement{}; - RideId _rideIndex{ RideId::GetNull() }; - uint8_t _mode{}; + class MazeSetTrackAction final : public GameActionBase + { + private: + CoordsXYZD _loc; + bool _initialPlacement{}; + RideId _rideIndex{ RideId::GetNull() }; + uint8_t _mode{}; -public: - MazeSetTrackAction() = default; - MazeSetTrackAction(const CoordsXYZD& location, bool initialPlacement, RideId rideIndex, uint8_t mode); + public: + MazeSetTrackAction() = default; + MazeSetTrackAction(const CoordsXYZD& location, bool initialPlacement, RideId rideIndex, uint8_t mode); - void AcceptParameters(GameActionParameterVisitor& visitor) override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; -private: - uint8_t MazeGetSegmentBit(const CoordsXY&) const; -}; + private: + uint8_t MazeGetSegmentBit(const CoordsXY&) const; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/NetworkModifyGroupAction.cpp b/src/openrct2/actions/NetworkModifyGroupAction.cpp index bda0261cb3..b8f00e5382 100644 --- a/src/openrct2/actions/NetworkModifyGroupAction.cpp +++ b/src/openrct2/actions/NetworkModifyGroupAction.cpp @@ -11,45 +11,47 @@ #include "../network/Network.h" -using namespace OpenRCT2; - -NetworkModifyGroupAction::NetworkModifyGroupAction( - ModifyGroupType type, uint8_t groupId, const std::string name, uint32_t permissionIndex, PermissionState permissionState) - : _type(type) - , _groupId(groupId) - , _name(name) - , _permissionIndex(permissionIndex) - , _permissionState(permissionState) +namespace OpenRCT2::GameActions { -} + NetworkModifyGroupAction::NetworkModifyGroupAction( + ModifyGroupType type, uint8_t groupId, const std::string name, uint32_t permissionIndex, + PermissionState permissionState) + : _type(type) + , _groupId(groupId) + , _name(name) + , _permissionIndex(permissionIndex) + , _permissionState(permissionState) + { + } -void NetworkModifyGroupAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit("type", _type); - visitor.Visit("groupId", _groupId); - visitor.Visit("name", _name); - visitor.Visit("permissionIndex", _permissionIndex); - visitor.Visit("permissionState", _permissionState); -} + void NetworkModifyGroupAction::AcceptParameters(GameActionParameterVisitor& visitor) + { + visitor.Visit("type", _type); + visitor.Visit("groupId", _groupId); + visitor.Visit("name", _name); + visitor.Visit("permissionIndex", _permissionIndex); + visitor.Visit("permissionState", _permissionState); + } -uint16_t NetworkModifyGroupAction::GetActionFlags() const -{ - return GameAction::GetActionFlags() | GameActions::Flags::AllowWhilePaused; -} + uint16_t NetworkModifyGroupAction::GetActionFlags() const + { + return GameAction::GetActionFlags() | Flags::AllowWhilePaused; + } -void NetworkModifyGroupAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); + void NetworkModifyGroupAction::Serialise(DataSerialiser& stream) + { + GameAction::Serialise(stream); - stream << DS_TAG(_type) << DS_TAG(_groupId) << DS_TAG(_name) << DS_TAG(_permissionIndex) << DS_TAG(_permissionState); -} + stream << DS_TAG(_type) << DS_TAG(_groupId) << DS_TAG(_name) << DS_TAG(_permissionIndex) << DS_TAG(_permissionState); + } -GameActions::Result NetworkModifyGroupAction::Query() const -{ - return NetworkModifyGroups(GetPlayer(), _type, _groupId, _name, _permissionIndex, _permissionState, false); -} + Result NetworkModifyGroupAction::Query() const + { + return NetworkModifyGroups(GetPlayer(), _type, _groupId, _name, _permissionIndex, _permissionState, false); + } -GameActions::Result NetworkModifyGroupAction::Execute() const -{ - return NetworkModifyGroups(GetPlayer(), _type, _groupId, _name, _permissionIndex, _permissionState, true); -} + Result NetworkModifyGroupAction::Execute() const + { + return NetworkModifyGroups(GetPlayer(), _type, _groupId, _name, _permissionIndex, _permissionState, true); + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/NetworkModifyGroupAction.h b/src/openrct2/actions/NetworkModifyGroupAction.h index ddd92af0f9..394c84780b 100644 --- a/src/openrct2/actions/NetworkModifyGroupAction.h +++ b/src/openrct2/actions/NetworkModifyGroupAction.h @@ -11,44 +11,47 @@ #include "GameAction.h" -enum class ModifyGroupType : uint8_t +namespace OpenRCT2::GameActions { - AddGroup, - RemoveGroup, - SetPermissions, - SetName, - SetDefault, - Count -}; + enum class ModifyGroupType : uint8_t + { + AddGroup, + RemoveGroup, + SetPermissions, + SetName, + SetDefault, + Count + }; -enum class PermissionState : uint8_t -{ - Toggle, - SetAll, - ClearAll, - Count -}; + enum class PermissionState : uint8_t + { + Toggle, + SetAll, + ClearAll, + Count + }; -class NetworkModifyGroupAction final : public GameActionBase -{ -private: - ModifyGroupType _type{ ModifyGroupType::Count }; - uint8_t _groupId{ std::numeric_limits::max() }; - std::string _name; - uint32_t _permissionIndex{ std::numeric_limits::max() }; - PermissionState _permissionState{ PermissionState::Count }; + class NetworkModifyGroupAction final : public GameActionBase + { + private: + ModifyGroupType _type{ ModifyGroupType::Count }; + uint8_t _groupId{ std::numeric_limits::max() }; + std::string _name; + uint32_t _permissionIndex{ std::numeric_limits::max() }; + PermissionState _permissionState{ PermissionState::Count }; -public: - NetworkModifyGroupAction() = default; - NetworkModifyGroupAction( - ModifyGroupType type, uint8_t groupId = std::numeric_limits::max(), const std::string name = "", - uint32_t permissionIndex = 0, PermissionState permissionState = PermissionState::Count); + public: + NetworkModifyGroupAction() = default; + NetworkModifyGroupAction( + ModifyGroupType type, uint8_t groupId = std::numeric_limits::max(), const std::string name = "", + uint32_t permissionIndex = 0, PermissionState permissionState = PermissionState::Count); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; -}; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/ParkEntrancePlaceAction.cpp b/src/openrct2/actions/ParkEntrancePlaceAction.cpp index 98c011a17b..5eb2a9c473 100644 --- a/src/openrct2/actions/ParkEntrancePlaceAction.cpp +++ b/src/openrct2/actions/ParkEntrancePlaceAction.cpp @@ -23,194 +23,192 @@ #include "../world/tile_element/EntranceElement.h" #include "../world/tile_element/SurfaceElement.h" -using namespace OpenRCT2; - -ParkEntrancePlaceAction::ParkEntrancePlaceAction( - const CoordsXYZD& location, ObjectEntryIndex pathType, ObjectEntryIndex entranceType) - : _loc(location) - , _pathType(pathType) - , _entranceType(entranceType) +namespace OpenRCT2::GameActions { -} - -void ParkEntrancePlaceAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit(_loc); - visitor.Visit("footpathSurfaceObject", _pathType); - visitor.Visit("entranceObject", _entranceType); -} - -uint16_t ParkEntrancePlaceAction::GetActionFlags() const -{ - return GameActionBase::GetActionFlags() | GameActions::Flags::EditorOnly; -} - -void ParkEntrancePlaceAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_loc); - stream << DS_TAG(_pathType); - stream << DS_TAG(_entranceType); -} - -GameActions::Result ParkEntrancePlaceAction::Query() const -{ - if (!isInEditorMode() && !getGameState().cheats.sandboxMode) + ParkEntrancePlaceAction::ParkEntrancePlaceAction( + const CoordsXYZD& location, ObjectEntryIndex pathType, ObjectEntryIndex entranceType) + : _loc(location) + , _pathType(pathType) + , _entranceType(entranceType) { - return GameActions::Result(GameActions::Status::NotInEditorMode, STR_CANT_BUILD_THIS_HERE, kStringIdNone); } - auto res = GameActions::Result(); - res.Expenditure = ExpenditureType::landPurchase; - res.Position = { _loc.x, _loc.y, _loc.z }; - - auto mapSizeUnits = GetMapSizeUnits() - CoordsXY{ kCoordsXYStep, kCoordsXYStep }; - if (!LocationValid(_loc) || _loc.x <= kCoordsXYStep || _loc.y <= kCoordsXYStep || _loc.x >= mapSizeUnits.x - || _loc.y >= mapSizeUnits.y) + void ParkEntrancePlaceAction::AcceptParameters(GameActionParameterVisitor& visitor) { - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_BUILD_THIS_HERE, STR_TOO_CLOSE_TO_EDGE_OF_MAP); + visitor.Visit(_loc); + visitor.Visit("footpathSurfaceObject", _pathType); + visitor.Visit("entranceObject", _entranceType); } - if (!CheckMapCapacity(3)) + uint16_t ParkEntrancePlaceAction::GetActionFlags() const { - return GameActions::Result( - GameActions::Status::NoFreeElements, STR_CANT_BUILD_THIS_HERE, STR_ERR_LANDSCAPE_DATA_AREA_FULL); + return GameActionBase::GetActionFlags() | Flags::EditorOnly; } - const auto& gameState = getGameState(); - if (gameState.park.entrances.size() >= OpenRCT2::Limits::kMaxParkEntrances) + void ParkEntrancePlaceAction::Serialise(DataSerialiser& stream) { - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_BUILD_THIS_HERE, STR_ERR_TOO_MANY_PARK_ENTRANCES); + GameAction::Serialise(stream); + + stream << DS_TAG(_loc); + stream << DS_TAG(_pathType); + stream << DS_TAG(_entranceType); } - auto zLow = _loc.z; - auto zHigh = zLow + ParkEntranceHeight; - CoordsXYZ entranceLoc = _loc; - for (uint8_t index = 0; index < 3; index++) + Result ParkEntrancePlaceAction::Query() const { - if (index == 1) + if (!isInEditorMode() && !getGameState().cheats.sandboxMode) { - entranceLoc += CoordsDirectionDelta[(_loc.direction - 1) & 0x3]; - } - else if (index == 2) - { - entranceLoc.x += CoordsDirectionDelta[(_loc.direction + 1) & 0x3].x * 2; - entranceLoc.y += CoordsDirectionDelta[(_loc.direction + 1) & 0x3].y * 2; + return Result(Status::NotInEditorMode, STR_CANT_BUILD_THIS_HERE, kStringIdNone); } - if (auto res2 = MapCanConstructAt({ entranceLoc, zLow, zHigh }, { 0b1111, 0 }); res2.Error != GameActions::Status::Ok) + auto res = Result(); + res.Expenditure = ExpenditureType::landPurchase; + res.Position = { _loc.x, _loc.y, _loc.z }; + + auto mapSizeUnits = GetMapSizeUnits() - CoordsXY{ kCoordsXYStep, kCoordsXYStep }; + if (!LocationValid(_loc) || _loc.x <= kCoordsXYStep || _loc.y <= kCoordsXYStep || _loc.x >= mapSizeUnits.x + || _loc.y >= mapSizeUnits.y) { - res2.ErrorTitle = STR_CANT_BUILD_THIS_HERE; - return res2; + return Result(Status::InvalidParameters, STR_CANT_BUILD_THIS_HERE, STR_TOO_CLOSE_TO_EDGE_OF_MAP); } - // Check that entrance element does not already exist at this location - EntranceElement* entranceElement = MapGetParkEntranceElementAt(entranceLoc, false); - if (entranceElement != nullptr) + if (!CheckMapCapacity(3)) { - return GameActions::Result(GameActions::Status::ItemAlreadyPlaced, STR_CANT_BUILD_THIS_HERE, kStringIdNone); - } - } - - return res; -} - -GameActions::Result ParkEntrancePlaceAction::Execute() const -{ - auto res = GameActions::Result(); - res.Expenditure = ExpenditureType::landPurchase; - res.Position = CoordsXYZ{ _loc.x, _loc.y, _loc.z }; - - uint32_t flags = GetFlags(); - - getGameState().park.entrances.push_back(_loc); - - auto zLow = _loc.z; - auto zHigh = zLow + ParkEntranceHeight; - CoordsXY entranceLoc = { _loc.x, _loc.y }; - for (uint8_t index = 0; index < 3; index++) - { - if (index == 1) - { - entranceLoc.x += CoordsDirectionDelta[(_loc.direction - 1) & 0x3].x; - entranceLoc.y += CoordsDirectionDelta[(_loc.direction - 1) & 0x3].y; - } - else if (index == 2) - { - entranceLoc.x += CoordsDirectionDelta[(_loc.direction + 1) & 0x3].x * 2; - entranceLoc.y += CoordsDirectionDelta[(_loc.direction + 1) & 0x3].y * 2; + return Result(Status::NoFreeElements, STR_CANT_BUILD_THIS_HERE, STR_ERR_LANDSCAPE_DATA_AREA_FULL); } - if (!(flags & GAME_COMMAND_FLAG_GHOST)) + const auto& gameState = getGameState(); + if (gameState.park.entrances.size() >= OpenRCT2::Limits::kMaxParkEntrances) { - SurfaceElement* surfaceElement = MapGetSurfaceElementAt(entranceLoc); - if (surfaceElement != nullptr) + return Result(Status::InvalidParameters, STR_CANT_BUILD_THIS_HERE, STR_ERR_TOO_MANY_PARK_ENTRANCES); + } + + auto zLow = _loc.z; + auto zHigh = zLow + ParkEntranceHeight; + CoordsXYZ entranceLoc = _loc; + for (uint8_t index = 0; index < 3; index++) + { + if (index == 1) { - surfaceElement->SetOwnership(OWNERSHIP_UNOWNED); + entranceLoc += CoordsDirectionDelta[(_loc.direction - 1) & 0x3]; + } + else if (index == 2) + { + entranceLoc.x += CoordsDirectionDelta[(_loc.direction + 1) & 0x3].x * 2; + entranceLoc.y += CoordsDirectionDelta[(_loc.direction + 1) & 0x3].y * 2; + } + + if (auto res2 = MapCanConstructAt({ entranceLoc, zLow, zHigh }, { 0b1111, 0 }); res2.Error != Status::Ok) + { + res2.ErrorTitle = STR_CANT_BUILD_THIS_HERE; + return res2; + } + + // Check that entrance element does not already exist at this location + EntranceElement* entranceElement = MapGetParkEntranceElementAt(entranceLoc, false); + if (entranceElement != nullptr) + { + return Result(Status::ItemAlreadyPlaced, STR_CANT_BUILD_THIS_HERE, kStringIdNone); } } - auto* entranceElement = TileElementInsert(CoordsXYZ{ entranceLoc, zLow }, 0b1111); - Guard::Assert(entranceElement != nullptr); - - entranceElement->SetClearanceZ(zHigh); - entranceElement->SetGhost(flags & GAME_COMMAND_FLAG_GHOST); - entranceElement->SetDirection(_loc.direction); - entranceElement->SetSequenceIndex(index); - entranceElement->SetEntranceType(ENTRANCE_TYPE_PARK_ENTRANCE); - entranceElement->setEntryIndex(_entranceType); - if (gFootpathSelection.LegacyPath == kObjectEntryIndexNull) - { - entranceElement->SetSurfaceEntryIndex(gFootpathSelection.NormalSurface); - } - else - { - entranceElement->SetLegacyPathEntryIndex(gFootpathSelection.LegacyPath); - } - - if (!entranceElement->IsGhost()) - { - FootpathConnectEdges(entranceLoc, entranceElement->as(), GAME_COMMAND_FLAG_APPLY); - } - - Park::UpdateFences(entranceLoc); - Park::UpdateFences({ entranceLoc.x - kCoordsXYStep, entranceLoc.y }); - Park::UpdateFences({ entranceLoc.x + kCoordsXYStep, entranceLoc.y }); - Park::UpdateFences({ entranceLoc.x, entranceLoc.y - kCoordsXYStep }); - Park::UpdateFences({ entranceLoc.x, entranceLoc.y + kCoordsXYStep }); - - MapInvalidateTile({ entranceLoc, entranceElement->GetBaseZ(), entranceElement->GetClearanceZ() }); - - if (index == 0) - { - MapAnimations::MarkTileForInvalidation(TileCoordsXY(entranceLoc)); - } + return res; } - return res; -} - -bool ParkEntrancePlaceAction::CheckMapCapacity(int16_t numTiles) const -{ - CoordsXYZ entranceLoc = _loc; - for (uint8_t index = 0; index < 3; index++) + Result ParkEntrancePlaceAction::Execute() const { - if (index == 1) + auto res = Result(); + res.Expenditure = ExpenditureType::landPurchase; + res.Position = CoordsXYZ{ _loc.x, _loc.y, _loc.z }; + + uint32_t flags = GetFlags(); + + getGameState().park.entrances.push_back(_loc); + + auto zLow = _loc.z; + auto zHigh = zLow + ParkEntranceHeight; + CoordsXY entranceLoc = { _loc.x, _loc.y }; + for (uint8_t index = 0; index < 3; index++) { - entranceLoc += CoordsDirectionDelta[(_loc.direction - 1) & 0x3]; - } - else if (index == 2) - { - entranceLoc.x += CoordsDirectionDelta[(_loc.direction + 1) & 0x3].x * 2; - entranceLoc.y += CoordsDirectionDelta[(_loc.direction + 1) & 0x3].y * 2; - } - if (!MapCheckCapacityAndReorganise(entranceLoc, numTiles)) - { - return false; + if (index == 1) + { + entranceLoc.x += CoordsDirectionDelta[(_loc.direction - 1) & 0x3].x; + entranceLoc.y += CoordsDirectionDelta[(_loc.direction - 1) & 0x3].y; + } + else if (index == 2) + { + entranceLoc.x += CoordsDirectionDelta[(_loc.direction + 1) & 0x3].x * 2; + entranceLoc.y += CoordsDirectionDelta[(_loc.direction + 1) & 0x3].y * 2; + } + + if (!(flags & GAME_COMMAND_FLAG_GHOST)) + { + SurfaceElement* surfaceElement = MapGetSurfaceElementAt(entranceLoc); + if (surfaceElement != nullptr) + { + surfaceElement->SetOwnership(OWNERSHIP_UNOWNED); + } + } + + auto* entranceElement = TileElementInsert(CoordsXYZ{ entranceLoc, zLow }, 0b1111); + Guard::Assert(entranceElement != nullptr); + + entranceElement->SetClearanceZ(zHigh); + entranceElement->SetGhost(flags & GAME_COMMAND_FLAG_GHOST); + entranceElement->SetDirection(_loc.direction); + entranceElement->SetSequenceIndex(index); + entranceElement->SetEntranceType(ENTRANCE_TYPE_PARK_ENTRANCE); + entranceElement->setEntryIndex(_entranceType); + if (gFootpathSelection.LegacyPath == kObjectEntryIndexNull) + { + entranceElement->SetSurfaceEntryIndex(gFootpathSelection.NormalSurface); + } + else + { + entranceElement->SetLegacyPathEntryIndex(gFootpathSelection.LegacyPath); + } + + if (!entranceElement->IsGhost()) + { + FootpathConnectEdges(entranceLoc, entranceElement->as(), GAME_COMMAND_FLAG_APPLY); + } + + Park::UpdateFences(entranceLoc); + Park::UpdateFences({ entranceLoc.x - kCoordsXYStep, entranceLoc.y }); + Park::UpdateFences({ entranceLoc.x + kCoordsXYStep, entranceLoc.y }); + Park::UpdateFences({ entranceLoc.x, entranceLoc.y - kCoordsXYStep }); + Park::UpdateFences({ entranceLoc.x, entranceLoc.y + kCoordsXYStep }); + + MapInvalidateTile({ entranceLoc, entranceElement->GetBaseZ(), entranceElement->GetClearanceZ() }); + + if (index == 0) + { + MapAnimations::MarkTileForInvalidation(TileCoordsXY(entranceLoc)); + } } + + return res; } - return true; -} + + bool ParkEntrancePlaceAction::CheckMapCapacity(int16_t numTiles) const + { + CoordsXYZ entranceLoc = _loc; + for (uint8_t index = 0; index < 3; index++) + { + if (index == 1) + { + entranceLoc += CoordsDirectionDelta[(_loc.direction - 1) & 0x3]; + } + else if (index == 2) + { + entranceLoc.x += CoordsDirectionDelta[(_loc.direction + 1) & 0x3].x * 2; + entranceLoc.y += CoordsDirectionDelta[(_loc.direction + 1) & 0x3].y * 2; + } + if (!MapCheckCapacityAndReorganise(entranceLoc, numTiles)) + { + return false; + } + } + return true; + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/ParkEntrancePlaceAction.h b/src/openrct2/actions/ParkEntrancePlaceAction.h index f7ef28a523..7e9cc7f1fd 100644 --- a/src/openrct2/actions/ParkEntrancePlaceAction.h +++ b/src/openrct2/actions/ParkEntrancePlaceAction.h @@ -11,26 +11,28 @@ #include "GameAction.h" -class ParkEntrancePlaceAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - CoordsXYZD _loc; - OpenRCT2::ObjectEntryIndex _pathType; - OpenRCT2::ObjectEntryIndex _entranceType; + class ParkEntrancePlaceAction final : public GameActionBase + { + private: + CoordsXYZD _loc; + ObjectEntryIndex _pathType; + ObjectEntryIndex _entranceType; -public: - ParkEntrancePlaceAction() = default; - ParkEntrancePlaceAction( - const CoordsXYZD& location, OpenRCT2::ObjectEntryIndex pathType, OpenRCT2::ObjectEntryIndex entranceType); + public: + ParkEntrancePlaceAction() = default; + ParkEntrancePlaceAction(const CoordsXYZD& location, ObjectEntryIndex pathType, ObjectEntryIndex entranceType); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; -private: - bool CheckMapCapacity(int16_t numTiles) const; -}; + private: + bool CheckMapCapacity(int16_t numTiles) const; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/ParkEntranceRemoveAction.cpp b/src/openrct2/actions/ParkEntranceRemoveAction.cpp index a25c0b665e..453335e58d 100644 --- a/src/openrct2/actions/ParkEntranceRemoveAction.cpp +++ b/src/openrct2/actions/ParkEntranceRemoveAction.cpp @@ -17,95 +17,96 @@ #include "../world/Park.h" #include "../world/tile_element/EntranceElement.h" -using namespace OpenRCT2; - -ParkEntranceRemoveAction::ParkEntranceRemoveAction(const CoordsXYZ& loc) - : _loc(loc) +namespace OpenRCT2::GameActions { -} - -void ParkEntranceRemoveAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit(_loc); -} - -uint16_t ParkEntranceRemoveAction::GetActionFlags() const -{ - return GameAction::GetActionFlags() | GameActions::Flags::EditorOnly; -} - -void ParkEntranceRemoveAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_loc); -} - -GameActions::Result ParkEntranceRemoveAction::Query() const -{ - if (!isInEditorMode() && !getGameState().cheats.sandboxMode) + ParkEntranceRemoveAction::ParkEntranceRemoveAction(const CoordsXYZ& loc) + : _loc(loc) { - return GameActions::Result(GameActions::Status::NotInEditorMode, STR_CANT_REMOVE_THIS, kStringIdNone); } - auto res = GameActions::Result(); - res.Expenditure = ExpenditureType::landPurchase; - res.Position = _loc; - res.ErrorTitle = STR_CANT_REMOVE_THIS; - - if (!LocationValid(_loc)) + void ParkEntranceRemoveAction::AcceptParameters(GameActionParameterVisitor& visitor) { - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_REMOVE_THIS, STR_OFF_EDGE_OF_MAP); - } - if (ParkEntranceGetIndex(_loc) == -1) - { - LOG_ERROR("No park entrance at x = %d, y = %d, z = %d", _loc.x, _loc.y, _loc.z); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_REMOVE_THIS, kStringIdNone); - } - return res; -} - -GameActions::Result ParkEntranceRemoveAction::Execute() const -{ - auto res = GameActions::Result(); - res.Expenditure = ExpenditureType::landPurchase; - res.Position = _loc; - res.ErrorTitle = STR_CANT_REMOVE_THIS; - - auto entranceIndex = ParkEntranceGetIndex(_loc); - if (entranceIndex == -1) - { - LOG_ERROR("No park entrance at x = %d, y = %d, z = %d", _loc.x, _loc.y, _loc.z); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_REMOVE_THIS, kStringIdNone); + visitor.Visit(_loc); } - auto& park = getGameState().park; - auto direction = (park.entrances[entranceIndex].direction - 1) & 3; - - // Centre (sign) - ParkEntranceRemoveSegment(_loc); - - // Left post - ParkEntranceRemoveSegment( - { _loc.x + CoordsDirectionDelta[direction].x, _loc.y + CoordsDirectionDelta[direction].y, _loc.z }); - - // Right post - ParkEntranceRemoveSegment( - { _loc.x - CoordsDirectionDelta[direction].x, _loc.y - CoordsDirectionDelta[direction].y, _loc.z }); - - park.entrances.erase(park.entrances.begin() + entranceIndex); - return res; -} - -void ParkEntranceRemoveAction::ParkEntranceRemoveSegment(const CoordsXYZ& loc) const -{ - auto entranceElement = MapGetParkEntranceElementAt(loc, true); - if (entranceElement == nullptr) + uint16_t ParkEntranceRemoveAction::GetActionFlags() const { - return; + return GameAction::GetActionFlags() | Flags::EditorOnly; } - MapInvalidateTile({ loc, entranceElement->GetBaseZ(), entranceElement->GetClearanceZ() }); - entranceElement->Remove(); - Park::UpdateFences({ loc.x, loc.y }); -} + void ParkEntranceRemoveAction::Serialise(DataSerialiser& stream) + { + GameAction::Serialise(stream); + + stream << DS_TAG(_loc); + } + + Result ParkEntranceRemoveAction::Query() const + { + if (!isInEditorMode() && !getGameState().cheats.sandboxMode) + { + return Result(Status::NotInEditorMode, STR_CANT_REMOVE_THIS, kStringIdNone); + } + + auto res = Result(); + res.Expenditure = ExpenditureType::landPurchase; + res.Position = _loc; + res.ErrorTitle = STR_CANT_REMOVE_THIS; + + if (!LocationValid(_loc)) + { + return Result(Status::InvalidParameters, STR_CANT_REMOVE_THIS, STR_OFF_EDGE_OF_MAP); + } + if (ParkEntranceGetIndex(_loc) == -1) + { + LOG_ERROR("No park entrance at x = %d, y = %d, z = %d", _loc.x, _loc.y, _loc.z); + return Result(Status::InvalidParameters, STR_CANT_REMOVE_THIS, kStringIdNone); + } + return res; + } + + Result ParkEntranceRemoveAction::Execute() const + { + auto res = Result(); + res.Expenditure = ExpenditureType::landPurchase; + res.Position = _loc; + res.ErrorTitle = STR_CANT_REMOVE_THIS; + + auto entranceIndex = ParkEntranceGetIndex(_loc); + if (entranceIndex == -1) + { + LOG_ERROR("No park entrance at x = %d, y = %d, z = %d", _loc.x, _loc.y, _loc.z); + return Result(Status::InvalidParameters, STR_CANT_REMOVE_THIS, kStringIdNone); + } + + auto& park = getGameState().park; + auto direction = (park.entrances[entranceIndex].direction - 1) & 3; + + // Centre (sign) + ParkEntranceRemoveSegment(_loc); + + // Left post + ParkEntranceRemoveSegment( + { _loc.x + CoordsDirectionDelta[direction].x, _loc.y + CoordsDirectionDelta[direction].y, _loc.z }); + + // Right post + ParkEntranceRemoveSegment( + { _loc.x - CoordsDirectionDelta[direction].x, _loc.y - CoordsDirectionDelta[direction].y, _loc.z }); + + park.entrances.erase(park.entrances.begin() + entranceIndex); + return res; + } + + void ParkEntranceRemoveAction::ParkEntranceRemoveSegment(const CoordsXYZ& loc) const + { + auto entranceElement = MapGetParkEntranceElementAt(loc, true); + if (entranceElement == nullptr) + { + return; + } + + MapInvalidateTile({ loc, entranceElement->GetBaseZ(), entranceElement->GetClearanceZ() }); + entranceElement->Remove(); + Park::UpdateFences({ loc.x, loc.y }); + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/ParkEntranceRemoveAction.h b/src/openrct2/actions/ParkEntranceRemoveAction.h index a9e6e3b621..76106403a8 100644 --- a/src/openrct2/actions/ParkEntranceRemoveAction.h +++ b/src/openrct2/actions/ParkEntranceRemoveAction.h @@ -11,23 +11,26 @@ #include "GameAction.h" -class ParkEntranceRemoveAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - CoordsXYZ _loc; + class ParkEntranceRemoveAction final : public GameActionBase + { + private: + CoordsXYZ _loc; -public: - ParkEntranceRemoveAction() = default; - ParkEntranceRemoveAction(const CoordsXYZ& loc); + public: + ParkEntranceRemoveAction() = default; + ParkEntranceRemoveAction(const CoordsXYZ& loc); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; -private: - void ParkEntranceRemoveSegment(const CoordsXYZ& loc) const; -}; + private: + void ParkEntranceRemoveSegment(const CoordsXYZ& loc) const; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/ParkMarketingAction.cpp b/src/openrct2/actions/ParkMarketingAction.cpp index cc2e8346f1..734492a63b 100644 --- a/src/openrct2/actions/ParkMarketingAction.cpp +++ b/src/openrct2/actions/ParkMarketingAction.cpp @@ -21,83 +21,82 @@ #include -using namespace OpenRCT2; - -ParkMarketingAction::ParkMarketingAction(int32_t type, int32_t item, int32_t numWeeks) - : _type(type) - , _item(item) - , _numWeeks(numWeeks) +namespace OpenRCT2::GameActions { -} - -void ParkMarketingAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit("type", _type); - visitor.Visit("item", _item); - visitor.Visit("duration", _numWeeks); -} - -uint16_t ParkMarketingAction::GetActionFlags() const -{ - return GameAction::GetActionFlags() | GameActions::Flags::AllowWhilePaused; -} - -void ParkMarketingAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - stream << DS_TAG(_type) << DS_TAG(_item) << DS_TAG(_numWeeks); -} - -GameActions::Result ParkMarketingAction::Query() const -{ - if (static_cast(_type) >= std::size(AdvertisingCampaignPricePerWeek) || _numWeeks >= 256) + ParkMarketingAction::ParkMarketingAction(int32_t type, int32_t item, int32_t numWeeks) + : _type(type) + , _item(item) + , _numWeeks(numWeeks) { - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_START_MARKETING_CAMPAIGN, STR_ERR_VALUE_OUT_OF_RANGE); - } - if (getGameState().park.flags & PARK_FLAGS_FORBID_MARKETING_CAMPAIGN) - { - return GameActions::Result( - GameActions::Status::Disallowed, STR_CANT_START_MARKETING_CAMPAIGN, - STR_MARKETING_CAMPAIGNS_FORBIDDEN_BY_LOCAL_AUTHORITY); } - return CreateResult(); -} - -GameActions::Result ParkMarketingAction::Execute() const -{ - MarketingCampaign campaign{}; - campaign.Type = _type; - campaign.WeeksLeft = _numWeeks; - campaign.flags = { MarketingCampaignFlag::firstWeek }; - if (campaign.Type == ADVERTISING_CAMPAIGN_RIDE_FREE || campaign.Type == ADVERTISING_CAMPAIGN_RIDE) + void ParkMarketingAction::AcceptParameters(GameActionParameterVisitor& visitor) { - campaign.RideId = RideId::FromUnderlying(_item); + visitor.Visit("type", _type); + visitor.Visit("item", _item); + visitor.Visit("duration", _numWeeks); } - else if (campaign.Type == ADVERTISING_CAMPAIGN_FOOD_OR_DRINK_FREE) + + uint16_t ParkMarketingAction::GetActionFlags() const { - campaign.ShopItemType = ShopItem(_item); + return GameAction::GetActionFlags() | Flags::AllowWhilePaused; } - MarketingNewCampaign(campaign); - // We are only interested in invalidating the finances (marketing) window - auto windowManager = OpenRCT2::Ui::GetWindowManager(); - windowManager->BroadcastIntent(Intent(INTENT_ACTION_UPDATE_CASH)); + void ParkMarketingAction::Serialise(DataSerialiser& stream) + { + GameAction::Serialise(stream); + stream << DS_TAG(_type) << DS_TAG(_item) << DS_TAG(_numWeeks); + } - return CreateResult(); -} + Result ParkMarketingAction::Query() const + { + if (static_cast(_type) >= std::size(AdvertisingCampaignPricePerWeek) || _numWeeks >= 256) + { + return Result(Status::InvalidParameters, STR_CANT_START_MARKETING_CAMPAIGN, STR_ERR_VALUE_OUT_OF_RANGE); + } + if (getGameState().park.flags & PARK_FLAGS_FORBID_MARKETING_CAMPAIGN) + { + return Result( + Status::Disallowed, STR_CANT_START_MARKETING_CAMPAIGN, STR_MARKETING_CAMPAIGNS_FORBIDDEN_BY_LOCAL_AUTHORITY); + } -GameActions::Result ParkMarketingAction::CreateResult() const -{ - auto result = GameActions::Result(); - result.ErrorTitle = STR_CANT_START_MARKETING_CAMPAIGN; - result.Expenditure = ExpenditureType::marketing; - result.Cost = CalculatePrice(); - return result; -} + return CreateResult(); + } -money64 ParkMarketingAction::CalculatePrice() const -{ - return _numWeeks * AdvertisingCampaignPricePerWeek[_type]; -} + Result ParkMarketingAction::Execute() const + { + MarketingCampaign campaign{}; + campaign.Type = _type; + campaign.WeeksLeft = _numWeeks; + campaign.flags = { MarketingCampaignFlag::firstWeek }; + if (campaign.Type == ADVERTISING_CAMPAIGN_RIDE_FREE || campaign.Type == ADVERTISING_CAMPAIGN_RIDE) + { + campaign.RideId = RideId::FromUnderlying(_item); + } + else if (campaign.Type == ADVERTISING_CAMPAIGN_FOOD_OR_DRINK_FREE) + { + campaign.ShopItemType = ShopItem(_item); + } + MarketingNewCampaign(campaign); + + // We are only interested in invalidating the finances (marketing) window + auto windowManager = OpenRCT2::Ui::GetWindowManager(); + windowManager->BroadcastIntent(Intent(INTENT_ACTION_UPDATE_CASH)); + + return CreateResult(); + } + + Result ParkMarketingAction::CreateResult() const + { + auto result = Result(); + result.ErrorTitle = STR_CANT_START_MARKETING_CAMPAIGN; + result.Expenditure = ExpenditureType::marketing; + result.Cost = CalculatePrice(); + return result; + } + + money64 ParkMarketingAction::CalculatePrice() const + { + return _numWeeks * AdvertisingCampaignPricePerWeek[_type]; + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/ParkMarketingAction.h b/src/openrct2/actions/ParkMarketingAction.h index 6947270afb..c1ec93257a 100644 --- a/src/openrct2/actions/ParkMarketingAction.h +++ b/src/openrct2/actions/ParkMarketingAction.h @@ -11,26 +11,29 @@ #include "GameAction.h" -class ParkMarketingAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - int32_t _type{}; - int32_t _item{}; - int32_t _numWeeks{}; + class ParkMarketingAction final : public GameActionBase + { + private: + int32_t _type{}; + int32_t _item{}; + int32_t _numWeeks{}; -public: - ParkMarketingAction() = default; - ParkMarketingAction(int32_t type, int32_t item, int32_t numWeeks); + public: + ParkMarketingAction() = default; + ParkMarketingAction(int32_t type, int32_t item, int32_t numWeeks); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; -private: - OpenRCT2::GameActions::Result CreateResult() const; - money64 CalculatePrice() const; -}; + private: + Result CreateResult() const; + money64 CalculatePrice() const; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/ParkSetDateAction.cpp b/src/openrct2/actions/ParkSetDateAction.cpp index 5b25fc0bac..097a2800ca 100644 --- a/src/openrct2/actions/ParkSetDateAction.cpp +++ b/src/openrct2/actions/ParkSetDateAction.cpp @@ -18,60 +18,58 @@ #include "../ui/WindowManager.h" #include "../windows/Intent.h" -using namespace OpenRCT2; - -ParkSetDateAction::ParkSetDateAction(int32_t year, int32_t month, int32_t day) - : _year(year) - , _month(month) - , _day(day) +namespace OpenRCT2::GameActions { -} - -void ParkSetDateAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit("year", _year); - visitor.Visit("month", _month); - visitor.Visit("day", _day); -} - -uint16_t ParkSetDateAction::GetActionFlags() const -{ - return GameAction::GetActionFlags() | GameActions::Flags::AllowWhilePaused; -} - -void ParkSetDateAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - stream << DS_TAG(_year) << DS_TAG(_month) << DS_TAG(_day); -} - -GameActions::Result ParkSetDateAction::Query() const -{ - if (_year < 0 || _year >= kMaxYear) + ParkSetDateAction::ParkSetDateAction(int32_t year, int32_t month, int32_t day) + : _year(year) + , _month(month) + , _day(day) { - LOG_ERROR("Invalid park date year %d", _year); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_VALUE_OUT_OF_RANGE); - } - else if (_month < 0 || _month >= MONTH_COUNT) - { - LOG_ERROR("Invalid park date month %d", _year); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_VALUE_OUT_OF_RANGE); - } - else if (_day < 0 || _day >= 31) - { - LOG_ERROR("Invalid park date day %d", _year); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_VALUE_OUT_OF_RANGE); } - return GameActions::Result(); -} + void ParkSetDateAction::AcceptParameters(GameActionParameterVisitor& visitor) + { + visitor.Visit("year", _year); + visitor.Visit("month", _month); + visitor.Visit("day", _day); + } -GameActions::Result ParkSetDateAction::Execute() const -{ - auto& gameState = getGameState(); - gameState.date = OpenRCT2::Date::FromYMD(_year, _month, _day); - return GameActions::Result(); -} + uint16_t ParkSetDateAction::GetActionFlags() const + { + return GameAction::GetActionFlags() | Flags::AllowWhilePaused; + } + + void ParkSetDateAction::Serialise(DataSerialiser& stream) + { + GameAction::Serialise(stream); + stream << DS_TAG(_year) << DS_TAG(_month) << DS_TAG(_day); + } + + Result ParkSetDateAction::Query() const + { + if (_year < 0 || _year >= kMaxYear) + { + LOG_ERROR("Invalid park date year %d", _year); + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_VALUE_OUT_OF_RANGE); + } + else if (_month < 0 || _month >= MONTH_COUNT) + { + LOG_ERROR("Invalid park date month %d", _year); + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_VALUE_OUT_OF_RANGE); + } + else if (_day < 0 || _day >= 31) + { + LOG_ERROR("Invalid park date day %d", _year); + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_VALUE_OUT_OF_RANGE); + } + + return Result(); + } + + Result ParkSetDateAction::Execute() const + { + auto& gameState = getGameState(); + gameState.date = Date::FromYMD(_year, _month, _day); + return Result(); + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/ParkSetDateAction.h b/src/openrct2/actions/ParkSetDateAction.h index 3475d5f594..cfe587ba4a 100644 --- a/src/openrct2/actions/ParkSetDateAction.h +++ b/src/openrct2/actions/ParkSetDateAction.h @@ -11,22 +11,25 @@ #include "GameAction.h" -class ParkSetDateAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - int32_t _year{}; - int32_t _month{}; - int32_t _day{}; + class ParkSetDateAction final : public GameActionBase + { + private: + int32_t _year{}; + int32_t _month{}; + int32_t _day{}; -public: - ParkSetDateAction() = default; - ParkSetDateAction(int32_t year, int32_t month, int32_t day); + public: + ParkSetDateAction() = default; + ParkSetDateAction(int32_t year, int32_t month, int32_t day); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; -}; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/ParkSetEntranceFeeAction.cpp b/src/openrct2/actions/ParkSetEntranceFeeAction.cpp index 52b2a8fe1e..25f95f8db8 100644 --- a/src/openrct2/actions/ParkSetEntranceFeeAction.cpp +++ b/src/openrct2/actions/ParkSetEntranceFeeAction.cpp @@ -17,58 +17,58 @@ #include "../ui/WindowManager.h" #include "../world/Park.h" -using namespace OpenRCT2; - -ParkSetEntranceFeeAction::ParkSetEntranceFeeAction(money64 fee) - : _fee(fee) +namespace OpenRCT2::GameActions { -} - -void ParkSetEntranceFeeAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit("value", _fee); -} - -uint16_t ParkSetEntranceFeeAction::GetActionFlags() const -{ - return GameAction::GetActionFlags() | GameActions::Flags::AllowWhilePaused; -} - -void ParkSetEntranceFeeAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_fee); -} - -GameActions::Result ParkSetEntranceFeeAction::Query() const -{ - if ((getGameState().park.flags & PARK_FLAGS_NO_MONEY) != 0) + ParkSetEntranceFeeAction::ParkSetEntranceFeeAction(money64 fee) + : _fee(fee) { - LOG_ERROR("Can't set park entrance fee because the park has no money"); - return GameActions::Result(GameActions::Status::Disallowed, STR_ERR_CANT_CHANGE_PARK_ENTRANCE_FEE, kStringIdNone); - } - else if (!Park::EntranceFeeUnlocked()) - { - LOG_ERROR("Park entrance fee is locked"); - return GameActions::Result(GameActions::Status::Disallowed, STR_ERR_CANT_CHANGE_PARK_ENTRANCE_FEE, kStringIdNone); - } - else if (_fee < 0.00_GBP || _fee > kMaxEntranceFee) - { - LOG_ERROR("Invalid park entrance fee %d", _fee); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_VALUE_OUT_OF_RANGE); } - return GameActions::Result(); -} + void ParkSetEntranceFeeAction::AcceptParameters(GameActionParameterVisitor& visitor) + { + visitor.Visit("value", _fee); + } -GameActions::Result ParkSetEntranceFeeAction::Execute() const -{ - getGameState().park.entranceFee = _fee; + uint16_t ParkSetEntranceFeeAction::GetActionFlags() const + { + return GameAction::GetActionFlags() | Flags::AllowWhilePaused; + } - auto* windowMgr = Ui::GetWindowManager(); - windowMgr->InvalidateByClass(WindowClass::ParkInformation); + void ParkSetEntranceFeeAction::Serialise(DataSerialiser& stream) + { + GameAction::Serialise(stream); - return GameActions::Result(); -} + stream << DS_TAG(_fee); + } + + Result ParkSetEntranceFeeAction::Query() const + { + if ((getGameState().park.flags & PARK_FLAGS_NO_MONEY) != 0) + { + LOG_ERROR("Can't set park entrance fee because the park has no money"); + return Result(Status::Disallowed, STR_ERR_CANT_CHANGE_PARK_ENTRANCE_FEE, kStringIdNone); + } + else if (!Park::EntranceFeeUnlocked()) + { + LOG_ERROR("Park entrance fee is locked"); + return Result(Status::Disallowed, STR_ERR_CANT_CHANGE_PARK_ENTRANCE_FEE, kStringIdNone); + } + else if (_fee < 0.00_GBP || _fee > kMaxEntranceFee) + { + LOG_ERROR("Invalid park entrance fee %d", _fee); + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_VALUE_OUT_OF_RANGE); + } + + return Result(); + } + + Result ParkSetEntranceFeeAction::Execute() const + { + getGameState().park.entranceFee = _fee; + + auto* windowMgr = Ui::GetWindowManager(); + windowMgr->InvalidateByClass(WindowClass::ParkInformation); + + return Result(); + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/ParkSetEntranceFeeAction.h b/src/openrct2/actions/ParkSetEntranceFeeAction.h index fde3aa3ab1..f77ff7a760 100644 --- a/src/openrct2/actions/ParkSetEntranceFeeAction.h +++ b/src/openrct2/actions/ParkSetEntranceFeeAction.h @@ -11,20 +11,23 @@ #include "GameAction.h" -class ParkSetEntranceFeeAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - money64 _fee{ kMoney64Undefined }; + class ParkSetEntranceFeeAction final : public GameActionBase + { + private: + money64 _fee{ kMoney64Undefined }; -public: - ParkSetEntranceFeeAction() = default; - ParkSetEntranceFeeAction(money64 fee); + public: + ParkSetEntranceFeeAction() = default; + ParkSetEntranceFeeAction(money64 fee); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; -}; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/ParkSetLoanAction.cpp b/src/openrct2/actions/ParkSetLoanAction.cpp index d9cc8d5cc2..0c6b23b386 100644 --- a/src/openrct2/actions/ParkSetLoanAction.cpp +++ b/src/openrct2/actions/ParkSetLoanAction.cpp @@ -17,60 +17,59 @@ #include "../ui/WindowManager.h" #include "../windows/Intent.h" -using namespace OpenRCT2; - -ParkSetLoanAction::ParkSetLoanAction(money64 value) - : _value(value) +namespace OpenRCT2::GameActions { -} - -void ParkSetLoanAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit("value", _value); -} - -uint16_t ParkSetLoanAction::GetActionFlags() const -{ - return GameAction::GetActionFlags() | GameActions::Flags::AllowWhilePaused; -} - -void ParkSetLoanAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - stream << DS_TAG(_value); -} - -GameActions::Result ParkSetLoanAction::Query() const -{ - auto& park = getGameState().park; - if (_value > park.bankLoan && _value > park.maxBankLoan) + ParkSetLoanAction::ParkSetLoanAction(money64 value) + : _value(value) { - return GameActions::Result( - GameActions::Status::Disallowed, STR_CANT_BORROW_ANY_MORE_MONEY, STR_BANK_REFUSES_TO_INCREASE_LOAN); } - if (_value < park.bankLoan && _value < 0.00_GBP) + + void ParkSetLoanAction::AcceptParameters(GameActionParameterVisitor& visitor) { - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_PAY_BACK_LOAN, STR_LOAN_CANT_BE_NEGATIVE); + visitor.Visit("value", _value); } - // The “isPayingBack” check is needed to allow increasing the loan when the player is in debt. - const auto isPayingBack = park.bankLoan > _value; - const auto amountToPayBack = park.bankLoan - _value; - if (isPayingBack && amountToPayBack > park.cash) + + uint16_t ParkSetLoanAction::GetActionFlags() const { - return GameActions::Result( - GameActions::Status::InsufficientFunds, STR_CANT_PAY_BACK_LOAN, STR_NOT_ENOUGH_CASH_AVAILABLE); + return GameAction::GetActionFlags() | Flags::AllowWhilePaused; } - return GameActions::Result(); -} -GameActions::Result ParkSetLoanAction::Execute() const -{ - auto& park = getGameState().park; + void ParkSetLoanAction::Serialise(DataSerialiser& stream) + { + GameAction::Serialise(stream); + stream << DS_TAG(_value); + } - park.cash -= (park.bankLoan - _value); - park.bankLoan = _value; + Result ParkSetLoanAction::Query() const + { + auto& park = getGameState().park; + if (_value > park.bankLoan && _value > park.maxBankLoan) + { + return Result(Status::Disallowed, STR_CANT_BORROW_ANY_MORE_MONEY, STR_BANK_REFUSES_TO_INCREASE_LOAN); + } + if (_value < park.bankLoan && _value < 0.00_GBP) + { + return Result(Status::InvalidParameters, STR_CANT_PAY_BACK_LOAN, STR_LOAN_CANT_BE_NEGATIVE); + } + // The “isPayingBack” check is needed to allow increasing the loan when the player is in debt. + const auto isPayingBack = park.bankLoan > _value; + const auto amountToPayBack = park.bankLoan - _value; + if (isPayingBack && amountToPayBack > park.cash) + { + return Result(Status::InsufficientFunds, STR_CANT_PAY_BACK_LOAN, STR_NOT_ENOUGH_CASH_AVAILABLE); + } + return Result(); + } - auto windowManager = OpenRCT2::Ui::GetWindowManager(); - windowManager->BroadcastIntent(Intent(INTENT_ACTION_UPDATE_CASH)); - return GameActions::Result(); -} + Result ParkSetLoanAction::Execute() const + { + auto& park = getGameState().park; + + park.cash -= (park.bankLoan - _value); + park.bankLoan = _value; + + auto windowManager = Ui::GetWindowManager(); + windowManager->BroadcastIntent(Intent(INTENT_ACTION_UPDATE_CASH)); + return Result(); + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/ParkSetLoanAction.h b/src/openrct2/actions/ParkSetLoanAction.h index bb8ffdf8ac..b85feb86a6 100644 --- a/src/openrct2/actions/ParkSetLoanAction.h +++ b/src/openrct2/actions/ParkSetLoanAction.h @@ -11,20 +11,23 @@ #include "GameAction.h" -class ParkSetLoanAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - money64 _value{ kMoney64Undefined }; + class ParkSetLoanAction final : public GameActionBase + { + private: + money64 _value{ kMoney64Undefined }; -public: - ParkSetLoanAction() = default; - ParkSetLoanAction(money64 value); + public: + ParkSetLoanAction() = default; + ParkSetLoanAction(money64 value); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; -}; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/ParkSetNameAction.cpp b/src/openrct2/actions/ParkSetNameAction.cpp index ca66d9c508..9241016125 100644 --- a/src/openrct2/actions/ParkSetNameAction.cpp +++ b/src/openrct2/actions/ParkSetNameAction.cpp @@ -20,48 +20,49 @@ #include "../windows/Intent.h" #include "../world/Park.h" -using namespace OpenRCT2; - -ParkSetNameAction::ParkSetNameAction(const std::string& name) - : _name(name) +namespace OpenRCT2::GameActions { -} - -void ParkSetNameAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit("name", _name); -} - -uint16_t ParkSetNameAction::GetActionFlags() const -{ - return GameAction::GetActionFlags() | GameActions::Flags::AllowWhilePaused; -} - -void ParkSetNameAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - stream << DS_TAG(_name); -} - -GameActions::Result ParkSetNameAction::Query() const -{ - if (_name.empty()) + ParkSetNameAction::ParkSetNameAction(const std::string& name) + : _name(name) { - LOG_ERROR("Can't set park name to empty string"); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_RENAME_PARK, STR_INVALID_NAME_FOR_PARK); } - return GameActions::Result(); -} -GameActions::Result ParkSetNameAction::Execute() const -{ - // Do a no-op if new name is the same as the current name is the same - auto& park = getGameState().park; - if (_name != park.name) + void ParkSetNameAction::AcceptParameters(GameActionParameterVisitor& visitor) { - park.name = _name; - ScrollingTextInvalidate(); - GfxInvalidateScreen(); + visitor.Visit("name", _name); } - return GameActions::Result(); -} + + uint16_t ParkSetNameAction::GetActionFlags() const + { + return GameAction::GetActionFlags() | Flags::AllowWhilePaused; + } + + void ParkSetNameAction::Serialise(DataSerialiser& stream) + { + GameAction::Serialise(stream); + stream << DS_TAG(_name); + } + + Result ParkSetNameAction::Query() const + { + if (_name.empty()) + { + LOG_ERROR("Can't set park name to empty string"); + return Result(Status::InvalidParameters, STR_CANT_RENAME_PARK, STR_INVALID_NAME_FOR_PARK); + } + return Result(); + } + + Result ParkSetNameAction::Execute() const + { + // Do a no-op if new name is the same as the current name is the same + auto& park = getGameState().park; + if (_name != park.name) + { + park.name = _name; + ScrollingTextInvalidate(); + GfxInvalidateScreen(); + } + return Result(); + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/ParkSetNameAction.h b/src/openrct2/actions/ParkSetNameAction.h index cd2faf7948..49e0302dcc 100644 --- a/src/openrct2/actions/ParkSetNameAction.h +++ b/src/openrct2/actions/ParkSetNameAction.h @@ -11,20 +11,23 @@ #include "GameAction.h" -class ParkSetNameAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - std::string _name; + class ParkSetNameAction final : public GameActionBase + { + private: + std::string _name; -public: - ParkSetNameAction() = default; - ParkSetNameAction(const std::string& name); + public: + ParkSetNameAction() = default; + ParkSetNameAction(const std::string& name); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; -}; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/ParkSetParameterAction.cpp b/src/openrct2/actions/ParkSetParameterAction.cpp index 352d2b4453..1076814e6e 100644 --- a/src/openrct2/actions/ParkSetParameterAction.cpp +++ b/src/openrct2/actions/ParkSetParameterAction.cpp @@ -16,77 +16,76 @@ #include "../ui/WindowManager.h" #include "../world/Park.h" -using namespace OpenRCT2; - -ParkSetParameterAction::ParkSetParameterAction(ParkParameter parameter, uint64_t value) - : _parameter(parameter) - , _value(value) +namespace OpenRCT2::GameActions { -} - -void ParkSetParameterAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit("parameter", _parameter); - visitor.Visit("value", _value); -} - -uint16_t ParkSetParameterAction::GetActionFlags() const -{ - return GameAction::GetActionFlags() | GameActions::Flags::AllowWhilePaused; -} - -void ParkSetParameterAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - stream << DS_TAG(_parameter) << DS_TAG(_value); -} - -GameActions::Result ParkSetParameterAction::Query() const -{ - if (_parameter >= ParkParameter::Count) + ParkSetParameterAction::ParkSetParameterAction(ParkParameter parameter, uint64_t value) + : _parameter(parameter) + , _value(value) { - LOG_ERROR("Invalid park parameter %d", _parameter); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_VALUE_OUT_OF_RANGE); } - auto res = GameActions::Result(); - res.ErrorTitle = kErrorTitles[EnumValue(_parameter)]; - return res; -} - -GameActions::Result ParkSetParameterAction::Execute() const -{ - auto& park = getGameState().park; - auto* windowMgr = Ui::GetWindowManager(); - - switch (_parameter) + void ParkSetParameterAction::AcceptParameters(GameActionParameterVisitor& visitor) { - case ParkParameter::Close: - if (park.flags & PARK_FLAGS_PARK_OPEN) - { - park.flags &= ~PARK_FLAGS_PARK_OPEN; - windowMgr->InvalidateByClass(WindowClass::ParkInformation); - } - break; - case ParkParameter::Open: - if (!(park.flags & PARK_FLAGS_PARK_OPEN)) - { - park.flags |= PARK_FLAGS_PARK_OPEN; - windowMgr->InvalidateByClass(WindowClass::ParkInformation); - } - break; - case ParkParameter::SamePriceInPark: - park.samePriceThroughoutPark = _value; - windowMgr->InvalidateByClass(WindowClass::Ride); - break; - default: + visitor.Visit("parameter", _parameter); + visitor.Visit("value", _value); + } + + uint16_t ParkSetParameterAction::GetActionFlags() const + { + return GameAction::GetActionFlags() | Flags::AllowWhilePaused; + } + + void ParkSetParameterAction::Serialise(DataSerialiser& stream) + { + GameAction::Serialise(stream); + stream << DS_TAG(_parameter) << DS_TAG(_value); + } + + Result ParkSetParameterAction::Query() const + { + if (_parameter >= ParkParameter::Count) + { LOG_ERROR("Invalid park parameter %d", _parameter); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_VALUE_OUT_OF_RANGE); + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_VALUE_OUT_OF_RANGE); + } + + auto res = Result(); + res.ErrorTitle = kErrorTitles[EnumValue(_parameter)]; + return res; } - auto res = GameActions::Result(); - res.ErrorTitle = kErrorTitles[EnumValue(_parameter)]; - return res; -} + Result ParkSetParameterAction::Execute() const + { + auto& park = getGameState().park; + auto* windowMgr = Ui::GetWindowManager(); + + switch (_parameter) + { + case ParkParameter::Close: + if (park.flags & PARK_FLAGS_PARK_OPEN) + { + park.flags &= ~PARK_FLAGS_PARK_OPEN; + windowMgr->InvalidateByClass(WindowClass::ParkInformation); + } + break; + case ParkParameter::Open: + if (!(park.flags & PARK_FLAGS_PARK_OPEN)) + { + park.flags |= PARK_FLAGS_PARK_OPEN; + windowMgr->InvalidateByClass(WindowClass::ParkInformation); + } + break; + case ParkParameter::SamePriceInPark: + park.samePriceThroughoutPark = _value; + windowMgr->InvalidateByClass(WindowClass::Ride); + break; + default: + LOG_ERROR("Invalid park parameter %d", _parameter); + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_VALUE_OUT_OF_RANGE); + } + + auto res = Result(); + res.ErrorTitle = kErrorTitles[EnumValue(_parameter)]; + return res; + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/ParkSetParameterAction.h b/src/openrct2/actions/ParkSetParameterAction.h index cfbcd9126a..4ccf87d888 100644 --- a/src/openrct2/actions/ParkSetParameterAction.h +++ b/src/openrct2/actions/ParkSetParameterAction.h @@ -11,36 +11,39 @@ #include "GameAction.h" -enum class ParkParameter : uint8_t +namespace OpenRCT2::GameActions { - Close, - Open, - SamePriceInPark, - Count -}; - -class ParkSetParameterAction final : public GameActionBase -{ -private: - ParkParameter _parameter{ ParkParameter::Count }; - uint64_t _value{}; - - constexpr static StringId kErrorTitles[] = { - STR_CANT_CLOSE_PARK, - STR_CANT_OPEN_PARK, - kStringIdNone, - kStringIdNone, + enum class ParkParameter : uint8_t + { + Close, + Open, + SamePriceInPark, + Count }; -public: - ParkSetParameterAction() = default; - ParkSetParameterAction(ParkParameter parameter, uint64_t value = 0); + class ParkSetParameterAction final : public GameActionBase + { + private: + ParkParameter _parameter{ ParkParameter::Count }; + uint64_t _value{}; - void AcceptParameters(GameActionParameterVisitor& visitor) override; + constexpr static StringId kErrorTitles[] = { + STR_CANT_CLOSE_PARK, + STR_CANT_OPEN_PARK, + kStringIdNone, + kStringIdNone, + }; - uint16_t GetActionFlags() const override; + public: + ParkSetParameterAction() = default; + ParkSetParameterAction(ParkParameter parameter, uint64_t value = 0); - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; -}; + void AcceptParameters(GameActionParameterVisitor& visitor) override; + + uint16_t GetActionFlags() const override; + + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/ParkSetResearchFundingAction.cpp b/src/openrct2/actions/ParkSetResearchFundingAction.cpp index 26aa1eb83a..90020778b1 100644 --- a/src/openrct2/actions/ParkSetResearchFundingAction.cpp +++ b/src/openrct2/actions/ParkSetResearchFundingAction.cpp @@ -18,49 +18,49 @@ #include "../ui/WindowManager.h" #include "../windows/Intent.h" -using namespace OpenRCT2; - -ParkSetResearchFundingAction::ParkSetResearchFundingAction(uint32_t priorities, uint8_t fundingAmount) - : _priorities(priorities) - , _fundingAmount(fundingAmount) +namespace OpenRCT2::GameActions { -} - -void ParkSetResearchFundingAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit("priorities", _priorities); - visitor.Visit("fundingAmount", _fundingAmount); -} - -uint16_t ParkSetResearchFundingAction::GetActionFlags() const -{ - return GameAction::GetActionFlags() | GameActions::Flags::AllowWhilePaused; -} - -void ParkSetResearchFundingAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - stream << DS_TAG(_priorities) << DS_TAG(_fundingAmount); -} - -GameActions::Result ParkSetResearchFundingAction::Query() const -{ - if (_fundingAmount >= RESEARCH_FUNDING_COUNT) + ParkSetResearchFundingAction::ParkSetResearchFundingAction(uint32_t priorities, uint8_t fundingAmount) + : _priorities(priorities) + , _fundingAmount(fundingAmount) { - LOG_ERROR("Invalid research funding amount %d", _fundingAmount); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_VALUE_OUT_OF_RANGE); } - return GameActions::Result(); -} -GameActions::Result ParkSetResearchFundingAction::Execute() const -{ - auto& gameState = getGameState(); - gameState.researchPriorities = _priorities; - gameState.researchFundingLevel = _fundingAmount; + void ParkSetResearchFundingAction::AcceptParameters(GameActionParameterVisitor& visitor) + { + visitor.Visit("priorities", _priorities); + visitor.Visit("fundingAmount", _fundingAmount); + } - auto windowManager = OpenRCT2::Ui::GetWindowManager(); - windowManager->BroadcastIntent(Intent(INTENT_ACTION_UPDATE_RESEARCH)); - return GameActions::Result(); -} + uint16_t ParkSetResearchFundingAction::GetActionFlags() const + { + return GameAction::GetActionFlags() | Flags::AllowWhilePaused; + } + + void ParkSetResearchFundingAction::Serialise(DataSerialiser& stream) + { + GameAction::Serialise(stream); + stream << DS_TAG(_priorities) << DS_TAG(_fundingAmount); + } + + Result ParkSetResearchFundingAction::Query() const + { + if (_fundingAmount >= RESEARCH_FUNDING_COUNT) + { + LOG_ERROR("Invalid research funding amount %d", _fundingAmount); + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_VALUE_OUT_OF_RANGE); + } + return Result(); + } + + Result ParkSetResearchFundingAction::Execute() const + { + auto& gameState = getGameState(); + gameState.researchPriorities = _priorities; + gameState.researchFundingLevel = _fundingAmount; + + auto windowManager = Ui::GetWindowManager(); + windowManager->BroadcastIntent(Intent(INTENT_ACTION_UPDATE_RESEARCH)); + return Result(); + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/ParkSetResearchFundingAction.h b/src/openrct2/actions/ParkSetResearchFundingAction.h index 9489e98f9a..ab663bdc7a 100644 --- a/src/openrct2/actions/ParkSetResearchFundingAction.h +++ b/src/openrct2/actions/ParkSetResearchFundingAction.h @@ -11,22 +11,25 @@ #include "GameAction.h" -class ParkSetResearchFundingAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - // TODO change to std::optional when C++17 - uint32_t _priorities{}; - uint8_t _fundingAmount{}; + class ParkSetResearchFundingAction final : public GameActionBase + { + private: + // TODO change to std::optional when C++17 + uint32_t _priorities{}; + uint8_t _fundingAmount{}; -public: - ParkSetResearchFundingAction() = default; - ParkSetResearchFundingAction(uint32_t priorities, uint8_t fundingAmount); + public: + ParkSetResearchFundingAction() = default; + ParkSetResearchFundingAction(uint32_t priorities, uint8_t fundingAmount); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; -}; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/PauseToggleAction.cpp b/src/openrct2/actions/PauseToggleAction.cpp index 4847f823e2..0e1646c91d 100644 --- a/src/openrct2/actions/PauseToggleAction.cpp +++ b/src/openrct2/actions/PauseToggleAction.cpp @@ -9,20 +9,21 @@ #include "PauseToggleAction.h" -using namespace OpenRCT2; - -uint16_t PauseToggleAction::GetActionFlags() const +namespace OpenRCT2::GameActions { - return GameAction::GetActionFlags() | GameActions::Flags::AllowWhilePaused | GameActions::Flags::IgnoreForReplays; -} + uint16_t PauseToggleAction::GetActionFlags() const + { + return GameAction::GetActionFlags() | Flags::AllowWhilePaused | Flags::IgnoreForReplays; + } -GameActions::Result PauseToggleAction::Query() const -{ - return GameActions::Result(); -} + Result PauseToggleAction::Query() const + { + return Result(); + } -GameActions::Result PauseToggleAction::Execute() const -{ - PauseToggle(); - return GameActions::Result(); -} + Result PauseToggleAction::Execute() const + { + PauseToggle(); + return Result(); + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/PauseToggleAction.h b/src/openrct2/actions/PauseToggleAction.h index 6113a2c41d..2061669f3f 100644 --- a/src/openrct2/actions/PauseToggleAction.h +++ b/src/openrct2/actions/PauseToggleAction.h @@ -11,16 +11,17 @@ #include "GameAction.h" -// Clang format is broken for small game actions -// clang-format off -class PauseToggleAction final : public GameActionBase +namespace OpenRCT2::GameActions { -public: - PauseToggleAction() = default; + class PauseToggleAction final : public GameActionBase + { + public: + PauseToggleAction() = default; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; -}; -// clang-format on + Result Query() const override; + Result Execute() const override; + }; + // clang-format on +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/PeepPickupAction.cpp b/src/openrct2/actions/PeepPickupAction.cpp index 68930945e3..e4f0c2a308 100644 --- a/src/openrct2/actions/PeepPickupAction.cpp +++ b/src/openrct2/actions/PeepPickupAction.cpp @@ -15,191 +15,192 @@ #include "../entity/Peep.h" #include "../network/Network.h" -using namespace OpenRCT2; - -PeepPickupAction::PeepPickupAction(PeepPickupType type, EntityId entityId, const CoordsXYZ& loc, NetworkPlayerId_t owner) - : _type(type) - , _entityId(entityId) - , _loc(loc) - , _owner(owner) +namespace OpenRCT2::GameActions { -} - -void PeepPickupAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit("type", _type); - visitor.Visit("id", _entityId); - visitor.Visit(_loc); - visitor.Visit("playerId", _owner); -} - -uint16_t PeepPickupAction::GetActionFlags() const -{ - return GameAction::GetActionFlags() | GameActions::Flags::AllowWhilePaused; -} - -void PeepPickupAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_type) << DS_TAG(_entityId) << DS_TAG(_loc) << DS_TAG(_owner); -} - -GameActions::Result PeepPickupAction::Query() const -{ - if (_entityId.ToUnderlying() >= kMaxEntities || _entityId.IsNull()) + PeepPickupAction::PeepPickupAction(PeepPickupType type, EntityId entityId, const CoordsXYZ& loc, NetworkPlayerId_t owner) + : _type(type) + , _entityId(entityId) + , _loc(loc) + , _owner(owner) { - LOG_ERROR("Failed to pick up peep for sprite %d", _entityId); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_ERR_CANT_PLACE_PERSON_HERE, kStringIdNone); } - if (!_loc.IsNull() && !LocationValid(_loc)) + void PeepPickupAction::AcceptParameters(GameActionParameterVisitor& visitor) { - return GameActions::Result(GameActions::Status::InvalidParameters, STR_ERR_CANT_PLACE_PERSON_HERE, kStringIdNone); + visitor.Visit("type", _type); + visitor.Visit("id", _entityId); + visitor.Visit(_loc); + visitor.Visit("playerId", _owner); } - auto* const peep = TryGetEntity(_entityId); - if (peep == nullptr) + uint16_t PeepPickupAction::GetActionFlags() const { - LOG_ERROR("Failed to pick up peep for sprite %d", _entityId); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_ERR_CANT_PLACE_PERSON_HERE, kStringIdNone); + return GameAction::GetActionFlags() | Flags::AllowWhilePaused; } - auto res = GameActions::Result(); - - switch (_type) + void PeepPickupAction::Serialise(DataSerialiser& stream) { - case PeepPickupType::Pickup: + GameAction::Serialise(stream); + + stream << DS_TAG(_type) << DS_TAG(_entityId) << DS_TAG(_loc) << DS_TAG(_owner); + } + + Result PeepPickupAction::Query() const + { + if (_entityId.ToUnderlying() >= kMaxEntities || _entityId.IsNull()) { - res.Position = peep->GetLocation(); - if (!peep->CanBePickedUp()) - { - return GameActions::Result(GameActions::Status::Disallowed, STR_ERR_CANT_PLACE_PERSON_HERE, kStringIdNone); - } - Peep* existing = NetworkGetPickupPeep(_owner); - if (existing != nullptr) - { - // already picking up a peep - PeepPickupAction existingPickupAction{ - PeepPickupType::Cancel, existing->Id, { NetworkGetPickupPeepOldX(_owner), 0, 0 }, _owner - }; - auto result = GameActions::QueryNested(&existingPickupAction); + LOG_ERROR("Failed to pick up peep for sprite %d", _entityId); + return Result(Status::InvalidParameters, STR_ERR_CANT_PLACE_PERSON_HERE, kStringIdNone); + } - if (existing == peep) + if (!_loc.IsNull() && !LocationValid(_loc)) + { + return Result(Status::InvalidParameters, STR_ERR_CANT_PLACE_PERSON_HERE, kStringIdNone); + } + + auto* const peep = TryGetEntity(_entityId); + if (peep == nullptr) + { + LOG_ERROR("Failed to pick up peep for sprite %d", _entityId); + return Result(Status::InvalidParameters, STR_ERR_CANT_PLACE_PERSON_HERE, kStringIdNone); + } + + auto res = Result(); + + switch (_type) + { + case PeepPickupType::Pickup: + { + res.Position = peep->GetLocation(); + if (!peep->CanBePickedUp()) { - return result; + return Result(Status::Disallowed, STR_ERR_CANT_PLACE_PERSON_HERE, kStringIdNone); + } + Peep* existing = NetworkGetPickupPeep(_owner); + if (existing != nullptr) + { + // already picking up a peep + PeepPickupAction existingPickupAction{ + PeepPickupType::Cancel, existing->Id, { NetworkGetPickupPeepOldX(_owner), 0, 0 }, _owner + }; + auto result = QueryNested(&existingPickupAction); + + if (existing == peep) + { + return result; + } } } - } - break; - case PeepPickupType::Cancel: - res.Position = peep->GetLocation(); break; - case PeepPickupType::Place: - res.Position = _loc; - if (NetworkGetPickupPeep(_owner) != peep) - { - return GameActions::Result(GameActions::Status::Unknown, STR_ERR_CANT_PLACE_PERSON_HERE, kStringIdNone); - } - - if (auto res2 = peep->Place(TileCoordsXYZ(_loc), false); res2.Error != GameActions::Status::Ok) - { - return res2; - } - break; - default: - LOG_ERROR("Invalid peep pickup type %u", _type); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_ERR_CANT_PLACE_PERSON_HERE, kStringIdNone); - } - return res; -} - -GameActions::Result PeepPickupAction::Execute() const -{ - Peep* const peep = TryGetEntity(_entityId); - if (peep == nullptr) - { - LOG_ERROR("Failed to pick up peep for sprite %d", _entityId); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_ERR_CANT_PLACE_PERSON_HERE, kStringIdNone); - } - - auto res = GameActions::Result(); - - switch (_type) - { - case PeepPickupType::Pickup: - { - res.Position = peep->GetLocation(); - - Peep* existing = NetworkGetPickupPeep(_owner); - if (existing != nullptr) - { - // already picking up a peep - PeepPickupAction existingPickupAction{ - PeepPickupType::Cancel, existing->Id, { NetworkGetPickupPeepOldX(_owner), 0, 0 }, _owner - }; - auto result = GameActions::ExecuteNested(&existingPickupAction); - - if (existing == peep) + case PeepPickupType::Cancel: + res.Position = peep->GetLocation(); + break; + case PeepPickupType::Place: + res.Position = _loc; + if (NetworkGetPickupPeep(_owner) != peep) { - return result; + return Result(Status::Unknown, STR_ERR_CANT_PLACE_PERSON_HERE, kStringIdNone); } - if (_owner == NetworkGetCurrentPlayerId()) + + if (auto res2 = peep->Place(TileCoordsXYZ(_loc), false); res2.Error != Status::Ok) { - // prevent tool_cancel() - gInputFlags.unset(InputFlag::toolActive); + return res2; } - } - - NetworkSetPickupPeep(_owner, peep); - NetworkSetPickupPeepOldX(_owner, peep->x); - peep->Pickup(); + break; + default: + LOG_ERROR("Invalid peep pickup type %u", _type); + return Result(Status::InvalidParameters, STR_ERR_CANT_PLACE_PERSON_HERE, kStringIdNone); } - break; - case PeepPickupType::Cancel: - { - res.Position = peep->GetLocation(); - - Peep* const pickedUpPeep = NetworkGetPickupPeep(_owner); - if (pickedUpPeep != nullptr) - { - pickedUpPeep->PickupAbort(_loc.x); - } - NetworkSetPickupPeep(_owner, nullptr); - } - break; - case PeepPickupType::Place: - res.Position = _loc; - if (auto res2 = peep->Place(TileCoordsXYZ(_loc), true); res2.Error != GameActions::Status::Ok) - { - return res2; - } - CancelConcurrentPickups(peep); - break; - default: - LOG_ERROR("Invalid peep pickup type %u", _type); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_ERR_CANT_PLACE_PERSON_HERE, kStringIdNone); + return res; } - return res; -} -void PeepPickupAction::CancelConcurrentPickups(Peep* pickedPeep) const -{ - // This part is only relevant in multiplayer games. - if (NetworkGetMode() == NETWORK_MODE_NONE) - return; + Result PeepPickupAction::Execute() const + { + Peep* const peep = TryGetEntity(_entityId); + if (peep == nullptr) + { + LOG_ERROR("Failed to pick up peep for sprite %d", _entityId); + return Result(Status::InvalidParameters, STR_ERR_CANT_PLACE_PERSON_HERE, kStringIdNone); + } - // Not relevant for owner, owner gets to place it normally. - NetworkPlayerId_t currentPlayerId = NetworkGetCurrentPlayerId(); - if (currentPlayerId == _owner) - return; + auto res = Result(); - Peep* peep = NetworkGetPickupPeep(NetworkGetCurrentPlayerId()); - if (peep != pickedPeep) - return; + switch (_type) + { + case PeepPickupType::Pickup: + { + res.Position = peep->GetLocation(); - // By assigning the peep to null before calling tool_cancel we can avoid - // resetting the peep to the initial position. - NetworkSetPickupPeep(currentPlayerId, nullptr); - ToolCancel(); -} + Peep* existing = NetworkGetPickupPeep(_owner); + if (existing != nullptr) + { + // already picking up a peep + PeepPickupAction existingPickupAction{ + PeepPickupType::Cancel, existing->Id, { NetworkGetPickupPeepOldX(_owner), 0, 0 }, _owner + }; + auto result = ExecuteNested(&existingPickupAction); + + if (existing == peep) + { + return result; + } + if (_owner == NetworkGetCurrentPlayerId()) + { + // prevent tool_cancel() + gInputFlags.unset(InputFlag::toolActive); + } + } + + NetworkSetPickupPeep(_owner, peep); + NetworkSetPickupPeepOldX(_owner, peep->x); + peep->Pickup(); + } + break; + case PeepPickupType::Cancel: + { + res.Position = peep->GetLocation(); + + Peep* const pickedUpPeep = NetworkGetPickupPeep(_owner); + if (pickedUpPeep != nullptr) + { + pickedUpPeep->PickupAbort(_loc.x); + } + NetworkSetPickupPeep(_owner, nullptr); + } + break; + case PeepPickupType::Place: + res.Position = _loc; + if (auto res2 = peep->Place(TileCoordsXYZ(_loc), true); res2.Error != Status::Ok) + { + return res2; + } + CancelConcurrentPickups(peep); + break; + default: + LOG_ERROR("Invalid peep pickup type %u", _type); + return Result(Status::InvalidParameters, STR_ERR_CANT_PLACE_PERSON_HERE, kStringIdNone); + } + return res; + } + + void PeepPickupAction::CancelConcurrentPickups(Peep* pickedPeep) const + { + // This part is only relevant in multiplayer games. + if (NetworkGetMode() == NETWORK_MODE_NONE) + return; + + // Not relevant for owner, owner gets to place it normally. + NetworkPlayerId_t currentPlayerId = NetworkGetCurrentPlayerId(); + if (currentPlayerId == _owner) + return; + + Peep* peep = NetworkGetPickupPeep(NetworkGetCurrentPlayerId()); + if (peep != pickedPeep) + return; + + // By assigning the peep to null before calling tool_cancel we can avoid + // resetting the peep to the initial position. + NetworkSetPickupPeep(currentPlayerId, nullptr); + ToolCancel(); + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/PeepPickupAction.h b/src/openrct2/actions/PeepPickupAction.h index 82c7b94c7f..903a15d7a7 100644 --- a/src/openrct2/actions/PeepPickupAction.h +++ b/src/openrct2/actions/PeepPickupAction.h @@ -12,34 +12,37 @@ #include "../Identifiers.h" #include "GameAction.h" -enum class PeepPickupType : uint8_t +namespace OpenRCT2::GameActions { - Pickup, - Cancel, - Place, - Count -}; + enum class PeepPickupType : uint8_t + { + Pickup, + Cancel, + Place, + Count + }; -class PeepPickupAction final : public GameActionBase -{ -private: - PeepPickupType _type{ PeepPickupType::Count }; - EntityId _entityId{ EntityId::GetNull() }; - CoordsXYZ _loc; - NetworkPlayerId_t _owner{ -1 }; + class PeepPickupAction final : public GameActionBase + { + private: + PeepPickupType _type{ PeepPickupType::Count }; + EntityId _entityId{ EntityId::GetNull() }; + CoordsXYZ _loc; + NetworkPlayerId_t _owner{ -1 }; -public: - PeepPickupAction() = default; - PeepPickupAction(PeepPickupType type, EntityId entityId, const CoordsXYZ& loc, NetworkPlayerId_t owner); + public: + PeepPickupAction() = default; + PeepPickupAction(PeepPickupType type, EntityId entityId, const CoordsXYZ& loc, NetworkPlayerId_t owner); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; -private: - void CancelConcurrentPickups(Peep* pickedPeep) const; -}; + private: + void CancelConcurrentPickups(Peep* pickedPeep) const; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/PeepSpawnPlaceAction.cpp b/src/openrct2/actions/PeepSpawnPlaceAction.cpp index c975cf242c..d751022379 100644 --- a/src/openrct2/actions/PeepSpawnPlaceAction.cpp +++ b/src/openrct2/actions/PeepSpawnPlaceAction.cpp @@ -19,124 +19,121 @@ #include "../world/Park.h" #include "../world/tile_element/SurfaceElement.h" -using namespace OpenRCT2; - -PeepSpawnPlaceAction::PeepSpawnPlaceAction(const CoordsXYZD& location) - : _location(location) +namespace OpenRCT2::GameActions { -} - -void PeepSpawnPlaceAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit(_location); -} - -uint16_t PeepSpawnPlaceAction::GetActionFlags() const -{ - return GameActionBase::GetActionFlags() | GameActions::Flags::EditorOnly | GameActions::Flags::AllowWhilePaused; -} - -void PeepSpawnPlaceAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_location.x) << DS_TAG(_location.y) << DS_TAG(_location.z) << DS_TAG(_location.direction); -} - -GameActions::Result PeepSpawnPlaceAction::Query() const -{ - if (!isInEditorMode() && !getGameState().cheats.sandboxMode) + PeepSpawnPlaceAction::PeepSpawnPlaceAction(const CoordsXYZD& location) + : _location(location) { - return GameActions::Result(GameActions::Status::NotInEditorMode, STR_ERR_CANT_PLACE_PEEP_SPAWN_HERE, kStringIdNone); } - auto res = GameActions::Result(); - res.Expenditure = ExpenditureType::landPurchase; - res.Position = _location; - - auto mapSizeUnits = GetMapSizeUnits() - CoordsXY{ 16, 16 }; - if (!LocationValid(_location) || _location.x <= 16 || _location.y <= 16 || _location.x >= mapSizeUnits.x - || _location.y >= mapSizeUnits.y) + void PeepSpawnPlaceAction::AcceptParameters(GameActionParameterVisitor& visitor) { - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_ERR_CANT_PLACE_PEEP_SPAWN_HERE, STR_OFF_EDGE_OF_MAP); + visitor.Visit(_location); } - // Verify footpath exists at location, and retrieve coordinates - auto pathElement = MapGetPathElementAt(TileCoordsXYZ{ _location }); - if (pathElement == nullptr) + uint16_t PeepSpawnPlaceAction::GetActionFlags() const { - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_ERR_CANT_PLACE_PEEP_SPAWN_HERE, STR_CAN_ONLY_BE_BUILT_ON_PATHS); + return GameActionBase::GetActionFlags() | Flags::EditorOnly | Flags::AllowWhilePaused; } - // Verify location is unowned - auto surfaceMapElement = MapGetSurfaceElementAt(_location); - if (surfaceMapElement == nullptr) + void PeepSpawnPlaceAction::Serialise(DataSerialiser& stream) { - return GameActions::Result( - GameActions::Status::Unknown, STR_ERR_CANT_PLACE_PEEP_SPAWN_HERE, STR_ERR_SURFACE_ELEMENT_NOT_FOUND); - } - if (surfaceMapElement->GetOwnership() != OWNERSHIP_UNOWNED) - { - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_ERR_CANT_PLACE_PEEP_SPAWN_HERE, - STR_ERR_MUST_BE_OUTSIDE_PARK_BOUNDARIES); + GameAction::Serialise(stream); + + stream << DS_TAG(_location.x) << DS_TAG(_location.y) << DS_TAG(_location.z) << DS_TAG(_location.direction); } - return res; -} - -GameActions::Result PeepSpawnPlaceAction::Execute() const -{ - auto res = GameActions::Result(); - res.Expenditure = ExpenditureType::landPurchase; - res.Position = _location; - - // Shift the spawn point to the edge of the tile - auto spawnPos = CoordsXY{ _location.ToTileCentre() } - + CoordsXY{ DirectionOffsets[_location.direction].x * 15, DirectionOffsets[_location.direction].y * 15 }; - - PeepSpawn spawn; - spawn.x = spawnPos.x; - spawn.y = spawnPos.y; - spawn.z = _location.z; - spawn.direction = _location.direction; - - auto& gameState = getGameState(); - // When attempting to place a peep spawn on a tile that already contains it, - // remove that peep spawn instead. - if (!gameState.peepSpawns.empty()) + Result PeepSpawnPlaceAction::Query() const { - // When searching for existing spawns, ignore the direction. - auto foundSpawn = std::find_if( - gameState.peepSpawns.begin(), gameState.peepSpawns.end(), [spawn](const CoordsXYZ& existingSpawn) { - { - return existingSpawn.ToTileStart() == spawn.ToTileStart(); - } - }); - - if (foundSpawn != std::end(gameState.peepSpawns)) + if (!isInEditorMode() && !getGameState().cheats.sandboxMode) { - gameState.peepSpawns.erase(foundSpawn); - MapInvalidateTileFull(spawn); - return res; + return Result(Status::NotInEditorMode, STR_ERR_CANT_PLACE_PEEP_SPAWN_HERE, kStringIdNone); } + + auto res = Result(); + res.Expenditure = ExpenditureType::landPurchase; + res.Position = _location; + + auto mapSizeUnits = GetMapSizeUnits() - CoordsXY{ 16, 16 }; + if (!LocationValid(_location) || _location.x <= 16 || _location.y <= 16 || _location.x >= mapSizeUnits.x + || _location.y >= mapSizeUnits.y) + { + return Result(Status::InvalidParameters, STR_ERR_CANT_PLACE_PEEP_SPAWN_HERE, STR_OFF_EDGE_OF_MAP); + } + + // Verify footpath exists at location, and retrieve coordinates + auto pathElement = MapGetPathElementAt(TileCoordsXYZ{ _location }); + if (pathElement == nullptr) + { + return Result(Status::InvalidParameters, STR_ERR_CANT_PLACE_PEEP_SPAWN_HERE, STR_CAN_ONLY_BE_BUILT_ON_PATHS); + } + + // Verify location is unowned + auto surfaceMapElement = MapGetSurfaceElementAt(_location); + if (surfaceMapElement == nullptr) + { + return Result(Status::Unknown, STR_ERR_CANT_PLACE_PEEP_SPAWN_HERE, STR_ERR_SURFACE_ELEMENT_NOT_FOUND); + } + if (surfaceMapElement->GetOwnership() != OWNERSHIP_UNOWNED) + { + return Result( + Status::InvalidParameters, STR_ERR_CANT_PLACE_PEEP_SPAWN_HERE, STR_ERR_MUST_BE_OUTSIDE_PARK_BOUNDARIES); + } + + return res; } - // If we have reached our max peep spawns, remove the oldest spawns - while (gameState.peepSpawns.size() >= Limits::kMaxPeepSpawns) + Result PeepSpawnPlaceAction::Execute() const { - PeepSpawn oldestSpawn = *gameState.peepSpawns.begin(); - gameState.peepSpawns.erase(gameState.peepSpawns.begin()); - MapInvalidateTileFull(oldestSpawn); + auto res = Result(); + res.Expenditure = ExpenditureType::landPurchase; + res.Position = _location; + + // Shift the spawn point to the edge of the tile + auto spawnPos = CoordsXY{ _location.ToTileCentre() } + + CoordsXY{ DirectionOffsets[_location.direction].x * 15, DirectionOffsets[_location.direction].y * 15 }; + + PeepSpawn spawn; + spawn.x = spawnPos.x; + spawn.y = spawnPos.y; + spawn.z = _location.z; + spawn.direction = _location.direction; + + auto& gameState = getGameState(); + // When attempting to place a peep spawn on a tile that already contains it, + // remove that peep spawn instead. + if (!gameState.peepSpawns.empty()) + { + // When searching for existing spawns, ignore the direction. + auto foundSpawn = std::find_if( + gameState.peepSpawns.begin(), gameState.peepSpawns.end(), [spawn](const CoordsXYZ& existingSpawn) { + { + return existingSpawn.ToTileStart() == spawn.ToTileStart(); + } + }); + + if (foundSpawn != std::end(gameState.peepSpawns)) + { + gameState.peepSpawns.erase(foundSpawn); + MapInvalidateTileFull(spawn); + return res; + } + } + + // If we have reached our max peep spawns, remove the oldest spawns + while (gameState.peepSpawns.size() >= Limits::kMaxPeepSpawns) + { + PeepSpawn oldestSpawn = *gameState.peepSpawns.begin(); + gameState.peepSpawns.erase(gameState.peepSpawns.begin()); + MapInvalidateTileFull(oldestSpawn); + } + + // Set peep spawn + gameState.peepSpawns.push_back(spawn); + + // Invalidate tile + MapInvalidateTileFull(_location); + + return res; } - - // Set peep spawn - gameState.peepSpawns.push_back(spawn); - - // Invalidate tile - MapInvalidateTileFull(_location); - - return res; -} +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/PeepSpawnPlaceAction.h b/src/openrct2/actions/PeepSpawnPlaceAction.h index ab14f39305..3696e71ec4 100644 --- a/src/openrct2/actions/PeepSpawnPlaceAction.h +++ b/src/openrct2/actions/PeepSpawnPlaceAction.h @@ -11,20 +11,23 @@ #include "GameAction.h" -class PeepSpawnPlaceAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - CoordsXYZD _location; + class PeepSpawnPlaceAction final : public GameActionBase + { + private: + CoordsXYZD _location; -public: - PeepSpawnPlaceAction() = default; - PeepSpawnPlaceAction(const CoordsXYZD& location); + public: + PeepSpawnPlaceAction() = default; + PeepSpawnPlaceAction(const CoordsXYZD& location); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; -}; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/PlayerKickAction.cpp b/src/openrct2/actions/PlayerKickAction.cpp index 6973f8020e..a4cb8ed914 100644 --- a/src/openrct2/actions/PlayerKickAction.cpp +++ b/src/openrct2/actions/PlayerKickAction.cpp @@ -11,35 +11,36 @@ #include "../network/Network.h" -using namespace OpenRCT2; - -PlayerKickAction::PlayerKickAction(NetworkPlayerId_t playerId) - : _playerId(playerId) +namespace OpenRCT2::GameActions { -} + PlayerKickAction::PlayerKickAction(NetworkPlayerId_t playerId) + : _playerId(playerId) + { + } -void PlayerKickAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit("playerId", _playerId); -} + void PlayerKickAction::AcceptParameters(GameActionParameterVisitor& visitor) + { + visitor.Visit("playerId", _playerId); + } -uint16_t PlayerKickAction::GetActionFlags() const -{ - return GameAction::GetActionFlags() | GameActions::Flags::AllowWhilePaused; -} + uint16_t PlayerKickAction::GetActionFlags() const + { + return GameAction::GetActionFlags() | Flags::AllowWhilePaused; + } -void PlayerKickAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); + void PlayerKickAction::Serialise(DataSerialiser& stream) + { + GameAction::Serialise(stream); - stream << DS_TAG(_playerId); -} -GameActions::Result PlayerKickAction::Query() const -{ - return NetworkKickPlayer(_playerId, false); -} + stream << DS_TAG(_playerId); + } + Result PlayerKickAction::Query() const + { + return NetworkKickPlayer(_playerId, false); + } -GameActions::Result PlayerKickAction::Execute() const -{ - return NetworkKickPlayer(_playerId, true); -} + Result PlayerKickAction::Execute() const + { + return NetworkKickPlayer(_playerId, true); + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/PlayerKickAction.h b/src/openrct2/actions/PlayerKickAction.h index 55242ab539..66d756bc73 100644 --- a/src/openrct2/actions/PlayerKickAction.h +++ b/src/openrct2/actions/PlayerKickAction.h @@ -11,21 +11,24 @@ #include "GameAction.h" -class PlayerKickAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - NetworkPlayerId_t _playerId{ -1 }; + class PlayerKickAction final : public GameActionBase + { + private: + NetworkPlayerId_t _playerId{ -1 }; -public: - PlayerKickAction() = default; + public: + PlayerKickAction() = default; - PlayerKickAction(NetworkPlayerId_t playerId); + PlayerKickAction(NetworkPlayerId_t playerId); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; -}; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/PlayerSetGroupAction.cpp b/src/openrct2/actions/PlayerSetGroupAction.cpp index 03cec60c29..838cc68a4f 100644 --- a/src/openrct2/actions/PlayerSetGroupAction.cpp +++ b/src/openrct2/actions/PlayerSetGroupAction.cpp @@ -11,37 +11,38 @@ #include "../network/Network.h" -using namespace OpenRCT2; - -PlayerSetGroupAction::PlayerSetGroupAction(NetworkPlayerId_t playerId, uint8_t groupId) - : _playerId(playerId) - , _groupId(groupId) +namespace OpenRCT2::GameActions { -} + PlayerSetGroupAction::PlayerSetGroupAction(NetworkPlayerId_t playerId, uint8_t groupId) + : _playerId(playerId) + , _groupId(groupId) + { + } -void PlayerSetGroupAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit("playerId", _playerId); - visitor.Visit("groupId", _groupId); -} + void PlayerSetGroupAction::AcceptParameters(GameActionParameterVisitor& visitor) + { + visitor.Visit("playerId", _playerId); + visitor.Visit("groupId", _groupId); + } -uint16_t PlayerSetGroupAction::GetActionFlags() const -{ - return GameAction::GetActionFlags() | GameActions::Flags::AllowWhilePaused; -} + uint16_t PlayerSetGroupAction::GetActionFlags() const + { + return GameAction::GetActionFlags() | Flags::AllowWhilePaused; + } -void PlayerSetGroupAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); + void PlayerSetGroupAction::Serialise(DataSerialiser& stream) + { + GameAction::Serialise(stream); - stream << DS_TAG(_playerId) << DS_TAG(_groupId); -} -GameActions::Result PlayerSetGroupAction::Query() const -{ - return NetworkSetPlayerGroup(GetPlayer(), _playerId, _groupId, false); -} + stream << DS_TAG(_playerId) << DS_TAG(_groupId); + } + Result PlayerSetGroupAction::Query() const + { + return NetworkSetPlayerGroup(GetPlayer(), _playerId, _groupId, false); + } -GameActions::Result PlayerSetGroupAction::Execute() const -{ - return NetworkSetPlayerGroup(GetPlayer(), _playerId, _groupId, true); -} + Result PlayerSetGroupAction::Execute() const + { + return NetworkSetPlayerGroup(GetPlayer(), _playerId, _groupId, true); + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/PlayerSetGroupAction.h b/src/openrct2/actions/PlayerSetGroupAction.h index 75eb9dc0f3..fd0bf591f7 100644 --- a/src/openrct2/actions/PlayerSetGroupAction.h +++ b/src/openrct2/actions/PlayerSetGroupAction.h @@ -11,21 +11,24 @@ #include "GameAction.h" -class PlayerSetGroupAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - NetworkPlayerId_t _playerId{ -1 }; - uint8_t _groupId{ std::numeric_limits::max() }; + class PlayerSetGroupAction final : public GameActionBase + { + private: + NetworkPlayerId_t _playerId{ -1 }; + uint8_t _groupId{ std::numeric_limits::max() }; -public: - PlayerSetGroupAction() = default; - PlayerSetGroupAction(NetworkPlayerId_t playerId, uint8_t groupId); + public: + PlayerSetGroupAction() = default; + PlayerSetGroupAction(NetworkPlayerId_t playerId, uint8_t groupId); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; -}; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/RideCreateAction.cpp b/src/openrct2/actions/RideCreateAction.cpp index 283daaaaa2..e01ebcff33 100644 --- a/src/openrct2/actions/RideCreateAction.cpp +++ b/src/openrct2/actions/RideCreateAction.cpp @@ -29,278 +29,275 @@ #include -using namespace OpenRCT2; - -RideCreateAction::RideCreateAction( - ride_type_t rideType, ObjectEntryIndex subType, colour_t colour1, colour_t colour2, ObjectEntryIndex entranceObjectIndex) - : _rideType(rideType) - , _subType(subType) - , _entranceObjectIndex(entranceObjectIndex) - , _colour1(colour1) - , _colour2(colour2) +namespace OpenRCT2::GameActions { -} - -void RideCreateAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit("rideType", _rideType); - visitor.Visit("rideObject", _subType); - visitor.Visit("entranceObject", _entranceObjectIndex); - visitor.Visit("colour1", _colour1); - visitor.Visit("colour2", _colour2); -} - -ride_type_t RideCreateAction::GetRideType() const -{ - return _rideType; -} - -ObjectEntryIndex RideCreateAction::GetRideObject() const -{ - return _subType; -} - -uint16_t RideCreateAction::GetActionFlags() const -{ - return GameAction::GetActionFlags() | GameActions::Flags::AllowWhilePaused; -} - -void RideCreateAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_rideType) << DS_TAG(_subType) << DS_TAG(_entranceObjectIndex) << DS_TAG(_colour1) << DS_TAG(_colour2); -} - -GameActions::Result RideCreateAction::Query() const -{ - auto rideIndex = GetNextFreeRideId(); - if (rideIndex.IsNull()) + RideCreateAction::RideCreateAction( + ride_type_t rideType, ObjectEntryIndex subType, colour_t colour1, colour_t colour2, + ObjectEntryIndex entranceObjectIndex) + : _rideType(rideType) + , _subType(subType) + , _entranceObjectIndex(entranceObjectIndex) + , _colour1(colour1) + , _colour2(colour2) { - // No more free slots available. - return GameActions::Result( - GameActions::Status::NoFreeElements, STR_CANT_CREATE_NEW_RIDE_ATTRACTION, STR_TOO_MANY_RIDES); } - if (_rideType >= RIDE_TYPE_COUNT) + void RideCreateAction::AcceptParameters(GameActionParameterVisitor& visitor) { - LOG_ERROR("Invalid ride type %d", _rideType); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_CREATE_NEW_RIDE_ATTRACTION, STR_INVALID_RIDE_TYPE); + visitor.Visit("rideType", _rideType); + visitor.Visit("rideObject", _subType); + visitor.Visit("entranceObject", _entranceObjectIndex); + visitor.Visit("colour1", _colour1); + visitor.Visit("colour2", _colour2); } - int32_t rideEntryIndex = RideGetEntryIndex(_rideType, _subType); - if (rideEntryIndex >= kMaxRideObjects) + ride_type_t RideCreateAction::GetRideType() const { - LOG_ERROR("Ride entry not found for rideType %d, subType %d", _rideType, _subType); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_CREATE_NEW_RIDE_ATTRACTION, STR_INVALID_RIDE_TYPE); + return _rideType; } - const auto& colourPresets = GetRideTypeDescriptor(_rideType).ColourPresets; - if (_colour1 >= colourPresets.count) + ObjectEntryIndex RideCreateAction::GetRideObject() const { - LOG_ERROR("Can't create ride, invalid colour preset %d", _colour1); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_CREATE_NEW_RIDE_ATTRACTION, STR_ERR_INVALID_COLOUR); + return _subType; } - const auto* rideEntry = GetRideEntryByIndex(rideEntryIndex); - if (rideEntry == nullptr) + uint16_t RideCreateAction::GetActionFlags() const { - LOG_ERROR("Ride entry not found for rideEntryIndex %d", rideEntryIndex); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_CREATE_NEW_RIDE_ATTRACTION, STR_UNKNOWN_OBJECT_TYPE); + return GameAction::GetActionFlags() | Flags::AllowWhilePaused; } - const auto* presetList = rideEntry->vehicle_preset_list; - if ((presetList->count > 0 && presetList->count != 255) && _colour2 >= presetList->count) + void RideCreateAction::Serialise(DataSerialiser& stream) { - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_CREATE_NEW_RIDE_ATTRACTION, kStringIdNone); + GameAction::Serialise(stream); + + stream << DS_TAG(_rideType) << DS_TAG(_subType) << DS_TAG(_entranceObjectIndex) << DS_TAG(_colour1) << DS_TAG(_colour2); } - auto res = GameActions::Result(); - res.SetData(RideId{ rideIndex }); - - return res; -} - -GameActions::Result RideCreateAction::Execute() const -{ - auto res = GameActions::Result(); - - int32_t rideEntryIndex = RideGetEntryIndex(_rideType, _subType); - auto rideIndex = GetNextFreeRideId(); - - auto ride = RideAllocateAtIndex(rideIndex); - const auto* rideEntry = GetRideEntryByIndex(rideEntryIndex); - if (rideEntry == nullptr) + Result RideCreateAction::Query() const { - LOG_ERROR( - "Ride entry not found for index rideEntryIndex %u (from rideType %u, subType %u)", rideEntryIndex, _rideType, - _subType); - return GameActions::Result(GameActions::Status::Unknown, STR_CANT_CREATE_NEW_RIDE_ATTRACTION, STR_UNKNOWN_OBJECT_TYPE); - } - - ride->type = _rideType; - ride->subtype = rideEntryIndex; - ride->setColourPreset(_colour1); - ride->overallView.SetNull(); - ride->setNameToDefault(); - - // Default initialize all stations. - RideStation station{}; - station.Start.SetNull(); - station.Entrance.SetNull(); - station.Exit.SetNull(); - std::ranges::fill(ride->getStations(), station); - - ride->status = RideStatus::closed; - ride->numTrains = 1; - - auto& gameState = getGameState(); - if (gameState.cheats.disableTrainLengthLimit) - { - // Reduce amount of proposed trains to prevent 32 trains from always spawning when limits are disabled - if (rideEntry->cars_per_flat_ride == kNoFlatRideCars) + auto rideIndex = GetNextFreeRideId(); + if (rideIndex.IsNull()) { - ride->proposedNumTrains = 12; + // No more free slots available. + return Result(Status::NoFreeElements, STR_CANT_CREATE_NEW_RIDE_ATTRACTION, STR_TOO_MANY_RIDES); + } + + if (_rideType >= RIDE_TYPE_COUNT) + { + LOG_ERROR("Invalid ride type %d", _rideType); + return Result(Status::InvalidParameters, STR_CANT_CREATE_NEW_RIDE_ATTRACTION, STR_INVALID_RIDE_TYPE); + } + + int32_t rideEntryIndex = RideGetEntryIndex(_rideType, _subType); + if (rideEntryIndex >= kMaxRideObjects) + { + LOG_ERROR("Ride entry not found for rideType %d, subType %d", _rideType, _subType); + return Result(Status::InvalidParameters, STR_CANT_CREATE_NEW_RIDE_ATTRACTION, STR_INVALID_RIDE_TYPE); + } + + const auto& colourPresets = GetRideTypeDescriptor(_rideType).ColourPresets; + if (_colour1 >= colourPresets.count) + { + LOG_ERROR("Can't create ride, invalid colour preset %d", _colour1); + return Result(Status::InvalidParameters, STR_CANT_CREATE_NEW_RIDE_ATTRACTION, STR_ERR_INVALID_COLOUR); + } + + const auto* rideEntry = GetRideEntryByIndex(rideEntryIndex); + if (rideEntry == nullptr) + { + LOG_ERROR("Ride entry not found for rideEntryIndex %d", rideEntryIndex); + return Result(Status::InvalidParameters, STR_CANT_CREATE_NEW_RIDE_ATTRACTION, STR_UNKNOWN_OBJECT_TYPE); + } + + const auto* presetList = rideEntry->vehicle_preset_list; + if ((presetList->count > 0 && presetList->count != 255) && _colour2 >= presetList->count) + { + return Result(Status::InvalidParameters, STR_CANT_CREATE_NEW_RIDE_ATTRACTION, kStringIdNone); + } + + auto res = Result(); + res.SetData(RideId{ rideIndex }); + + return res; + } + + Result RideCreateAction::Execute() const + { + auto res = Result(); + + int32_t rideEntryIndex = RideGetEntryIndex(_rideType, _subType); + auto rideIndex = GetNextFreeRideId(); + + auto ride = RideAllocateAtIndex(rideIndex); + const auto* rideEntry = GetRideEntryByIndex(rideEntryIndex); + if (rideEntry == nullptr) + { + LOG_ERROR( + "Ride entry not found for index rideEntryIndex %u (from rideType %u, subType %u)", rideEntryIndex, _rideType, + _subType); + return Result(Status::Unknown, STR_CANT_CREATE_NEW_RIDE_ATTRACTION, STR_UNKNOWN_OBJECT_TYPE); + } + + ride->type = _rideType; + ride->subtype = rideEntryIndex; + ride->setColourPreset(_colour1); + ride->overallView.SetNull(); + ride->setNameToDefault(); + + // Default initialize all stations. + RideStation station{}; + station.Start.SetNull(); + station.Entrance.SetNull(); + station.Exit.SetNull(); + std::ranges::fill(ride->getStations(), station); + + ride->status = RideStatus::closed; + ride->numTrains = 1; + + auto& gameState = getGameState(); + if (gameState.cheats.disableTrainLengthLimit) + { + // Reduce amount of proposed trains to prevent 32 trains from always spawning when limits are disabled + if (rideEntry->cars_per_flat_ride == kNoFlatRideCars) + { + ride->proposedNumTrains = 12; + } + else + { + ride->proposedNumTrains = rideEntry->cars_per_flat_ride; + } } else { - ride->proposedNumTrains = rideEntry->cars_per_flat_ride; + ride->proposedNumTrains = 32; } - } - else - { - ride->proposedNumTrains = 32; - } - ride->maxTrains = OpenRCT2::Limits::kMaxTrainsPerRide; - ride->numCarsPerTrain = 1; - ride->proposedNumCarsPerTrain = rideEntry->max_cars_in_train; - ride->minWaitingTime = 10; - ride->maxWaitingTime = 60; - ride->departFlags = RIDE_DEPART_WAIT_FOR_MINIMUM_LENGTH | 3; + ride->maxTrains = OpenRCT2::Limits::kMaxTrainsPerRide; + ride->numCarsPerTrain = 1; + ride->proposedNumCarsPerTrain = rideEntry->max_cars_in_train; + ride->minWaitingTime = 10; + ride->maxWaitingTime = 60; + ride->departFlags = RIDE_DEPART_WAIT_FOR_MINIMUM_LENGTH | 3; - const auto& rtd = ride->getRideTypeDescriptor(); - if (rtd.HasFlag(RtdFlag::allowMusic)) - { - auto& objManager = OpenRCT2::GetContext()->GetObjectManager(); - ride->music = objManager.GetLoadedObjectEntryIndex(rtd.DefaultMusic); - if (ride->music != kObjectEntryIndexNull) + const auto& rtd = ride->getRideTypeDescriptor(); + if (rtd.HasFlag(RtdFlag::allowMusic)) { - if (rtd.HasFlag(RtdFlag::hasMusicByDefault)) + auto& objManager = OpenRCT2::GetContext()->GetObjectManager(); + ride->music = objManager.GetLoadedObjectEntryIndex(rtd.DefaultMusic); + if (ride->music != kObjectEntryIndexNull) { - ride->lifecycleFlags |= RIDE_LIFECYCLE_MUSIC; + if (rtd.HasFlag(RtdFlag::hasMusicByDefault)) + { + ride->lifecycleFlags |= RIDE_LIFECYCLE_MUSIC; + } } } - } - const auto& operatingSettings = rtd.OperatingSettings; - ride->operationOption = (operatingSettings.MinValue * 3 + operatingSettings.MaxValue) / 4; + const auto& operatingSettings = rtd.OperatingSettings; + ride->operationOption = (operatingSettings.MinValue * 3 + operatingSettings.MaxValue) / 4; - ride->liftHillSpeed = rtd.LiftData.minimum_speed; + ride->liftHillSpeed = rtd.LiftData.minimum_speed; - ride->ratings.setNull(); + ride->ratings.setNull(); - if (!(gameState.park.flags & PARK_FLAGS_NO_MONEY)) - { - for (auto i = 0; i < RCT2::ObjectLimits::kMaxShopItemsPerRideEntry; i++) + if (!(gameState.park.flags & PARK_FLAGS_NO_MONEY)) { - ride->price[i] = rtd.DefaultPrices[i]; - } + for (auto i = 0; i < RCT2::ObjectLimits::kMaxShopItemsPerRideEntry; i++) + { + ride->price[i] = rtd.DefaultPrices[i]; + } - if (rideEntry->shop_item[0] == ShopItem::None) - { - if (!Park::RidePricesUnlocked() || gameState.park.entranceFee > 0) + if (rideEntry->shop_item[0] == ShopItem::None) + { + if (!Park::RidePricesUnlocked() || gameState.park.entranceFee > 0) + { + ride->price[0] = 0; + } + } + else + { + ride->price[0] = GetShopItemDescriptor(rideEntry->shop_item[0]).DefaultPrice; + } + if (rideEntry->shop_item[1] != ShopItem::None) + { + ride->price[1] = GetShopItemDescriptor(rideEntry->shop_item[1]).DefaultPrice; + } + + if (gameState.scenarioOptions.objective.Type == Scenario::ObjectiveType::buildTheBest) { ride->price[0] = 0; } - } - else - { - ride->price[0] = GetShopItemDescriptor(rideEntry->shop_item[0]).DefaultPrice; - } - if (rideEntry->shop_item[1] != ShopItem::None) - { - ride->price[1] = GetShopItemDescriptor(rideEntry->shop_item[1]).DefaultPrice; - } - if (gameState.scenarioOptions.objective.Type == Scenario::ObjectiveType::buildTheBest) - { - ride->price[0] = 0; - } - - if (rtd.specialType == RtdSpecialType::toilet) - { - if (ShopItemHasCommonPrice(ShopItem::Admission)) + if (rtd.specialType == RtdSpecialType::toilet) { - auto price = RideGetCommonPrice(*ride); - if (price != kMoney64Undefined) + if (ShopItemHasCommonPrice(ShopItem::Admission)) { - ride->price[0] = price; - } - } - } - - for (auto i = 0; i < RCT2::ObjectLimits::kMaxShopItemsPerRideEntry; i++) - { - if (rideEntry->shop_item[i] != ShopItem::None) - { - if (ShopItemHasCommonPrice(rideEntry->shop_item[i])) - { - auto price = ShopItemGetCommonPrice(ride, rideEntry->shop_item[i]); + auto price = RideGetCommonPrice(*ride); if (price != kMoney64Undefined) { - ride->price[i] = price; + ride->price[0] = price; } } } - } - // Set the on-ride photo price, whether the ride has one or not (except shops). - if (!rtd.HasFlag(RtdFlag::isShopOrFacility) && ShopItemHasCommonPrice(ShopItem::Photo)) - { - auto price = ShopItemGetCommonPrice(ride, ShopItem::Photo); - if (price != kMoney64Undefined) + for (auto i = 0; i < RCT2::ObjectLimits::kMaxShopItemsPerRideEntry; i++) { - ride->price[1] = price; + if (rideEntry->shop_item[i] != ShopItem::None) + { + if (ShopItemHasCommonPrice(rideEntry->shop_item[i])) + { + auto price = ShopItemGetCommonPrice(ride, rideEntry->shop_item[i]); + if (price != kMoney64Undefined) + { + ride->price[i] = price; + } + } + } + } + + // Set the on-ride photo price, whether the ride has one or not (except shops). + if (!rtd.HasFlag(RtdFlag::isShopOrFacility) && ShopItemHasCommonPrice(ShopItem::Photo)) + { + auto price = ShopItemGetCommonPrice(ride, ShopItem::Photo); + if (price != kMoney64Undefined) + { + ride->price[1] = price; + } } } + + ride->value = kRideValueUndefined; + ride->satisfaction = 255; + ride->popularity = 255; + ride->buildDate = GetDate().GetMonthsElapsed(); + ride->musicTuneId = kTuneIDNull; + + ride->breakdownReason = BREAKDOWN_NONE; + ride->upkeepCost = kMoney64Undefined; + ride->reliability = kRideInitialReliability; + ride->unreliabilityFactor = 1; + ride->inspectionInterval = RIDE_INSPECTION_EVERY_30_MINUTES; + ride->lastCrashType = RIDE_CRASH_TYPE_NONE; + ride->incomePerHour = kMoney64Undefined; + ride->profit = kMoney64Undefined; + + ride->entranceStyle = kObjectEntryIndexNull; + if (rtd.HasFlag(RtdFlag::hasEntranceAndExit)) + { + ride->entranceStyle = _entranceObjectIndex; + } + + ride->numCircuits = 1; + ride->mode = ride->getDefaultMode(); + ride->minCarsPerTrain = rideEntry->min_cars_in_train; + ride->maxCarsPerTrain = rideEntry->max_cars_in_train; + RideSetVehicleColoursToRandomPreset(*ride, _colour2); + + auto* windowMgr = Ui::GetWindowManager(); + windowMgr->InvalidateByClass(WindowClass::RideList); + + res.Expenditure = ExpenditureType::rideConstruction; + res.SetData(RideId{ rideIndex }); + + return res; } - - ride->value = kRideValueUndefined; - ride->satisfaction = 255; - ride->popularity = 255; - ride->buildDate = GetDate().GetMonthsElapsed(); - ride->musicTuneId = kTuneIDNull; - - ride->breakdownReason = BREAKDOWN_NONE; - ride->upkeepCost = kMoney64Undefined; - ride->reliability = kRideInitialReliability; - ride->unreliabilityFactor = 1; - ride->inspectionInterval = RIDE_INSPECTION_EVERY_30_MINUTES; - ride->lastCrashType = RIDE_CRASH_TYPE_NONE; - ride->incomePerHour = kMoney64Undefined; - ride->profit = kMoney64Undefined; - - ride->entranceStyle = kObjectEntryIndexNull; - if (rtd.HasFlag(RtdFlag::hasEntranceAndExit)) - { - ride->entranceStyle = _entranceObjectIndex; - } - - ride->numCircuits = 1; - ride->mode = ride->getDefaultMode(); - ride->minCarsPerTrain = rideEntry->min_cars_in_train; - ride->maxCarsPerTrain = rideEntry->max_cars_in_train; - RideSetVehicleColoursToRandomPreset(*ride, _colour2); - - auto* windowMgr = Ui::GetWindowManager(); - windowMgr->InvalidateByClass(WindowClass::RideList); - - res.Expenditure = ExpenditureType::rideConstruction; - res.SetData(RideId{ rideIndex }); - - return res; -} +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/RideCreateAction.h b/src/openrct2/actions/RideCreateAction.h index 524217e26b..191cb5e866 100644 --- a/src/openrct2/actions/RideCreateAction.h +++ b/src/openrct2/actions/RideCreateAction.h @@ -11,28 +11,31 @@ #include "GameAction.h" -class RideCreateAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - ride_type_t _rideType{ kRideTypeNull }; - OpenRCT2::ObjectEntryIndex _subType{ OpenRCT2::kObjectEntryIndexNull }; - OpenRCT2::ObjectEntryIndex _entranceObjectIndex{ OpenRCT2::kObjectEntryIndexNull }; - colour_t _colour1{ COLOUR_NULL }; - colour_t _colour2{ COLOUR_NULL }; + class RideCreateAction final : public GameActionBase + { + private: + ride_type_t _rideType{ kRideTypeNull }; + ObjectEntryIndex _subType{ kObjectEntryIndexNull }; + ObjectEntryIndex _entranceObjectIndex{ kObjectEntryIndexNull }; + colour_t _colour1{ COLOUR_NULL }; + colour_t _colour2{ COLOUR_NULL }; -public: - RideCreateAction() = default; - RideCreateAction( - ride_type_t rideType, OpenRCT2::ObjectEntryIndex subType, colour_t colour1, colour_t colour2, - OpenRCT2::ObjectEntryIndex entranceStyleIndex); + public: + RideCreateAction() = default; + RideCreateAction( + ride_type_t rideType, ObjectEntryIndex subType, colour_t colour1, colour_t colour2, + ObjectEntryIndex entranceStyleIndex); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - ride_type_t GetRideType() const; - OpenRCT2::ObjectEntryIndex GetRideObject() const; - uint16_t GetActionFlags() const override; + ride_type_t GetRideType() const; + ObjectEntryIndex GetRideObject() const; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; -}; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/RideDemolishAction.cpp b/src/openrct2/actions/RideDemolishAction.cpp index 0df74d5d62..92b85d7e55 100644 --- a/src/openrct2/actions/RideDemolishAction.cpp +++ b/src/openrct2/actions/RideDemolishAction.cpp @@ -28,276 +28,278 @@ #include "MazeSetTrackAction.h" #include "TrackRemoveAction.h" -using namespace OpenRCT2; - -RideDemolishAction::RideDemolishAction(RideId rideIndex, RideModifyType modifyType) - : _rideIndex(rideIndex) - , _modifyType(modifyType) +namespace OpenRCT2::GameActions { -} - -void RideDemolishAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit("ride", _rideIndex); - visitor.Visit("modifyType", _modifyType); -} - -uint32_t RideDemolishAction::GetCooldownTime() const -{ - return 1000; -} - -void RideDemolishAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_rideIndex) << DS_TAG(_modifyType); -} - -GameActions::Result RideDemolishAction::Query() const -{ - auto ride = GetRide(_rideIndex); - if (ride == nullptr) + RideDemolishAction::RideDemolishAction(RideId rideIndex, RideModifyType modifyType) + : _rideIndex(rideIndex) + , _modifyType(modifyType) { - LOG_ERROR("Ride not found for rideIndex %u", _rideIndex.ToUnderlying()); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_DEMOLISH_RIDE, STR_ERR_RIDE_NOT_FOUND); } - if ((ride->lifecycleFlags & (RIDE_LIFECYCLE_INDESTRUCTIBLE | RIDE_LIFECYCLE_INDESTRUCTIBLE_TRACK) - && _modifyType == RideModifyType::demolish) - && !getGameState().cheats.makeAllDestructible) + void RideDemolishAction::AcceptParameters(GameActionParameterVisitor& visitor) { - return GameActions::Result( - GameActions::Status::NoClearance, STR_CANT_DEMOLISH_RIDE, - STR_LOCAL_AUTHORITY_FORBIDS_DEMOLITION_OR_MODIFICATIONS_TO_THIS_RIDE); + visitor.Visit("ride", _rideIndex); + visitor.Visit("modifyType", _modifyType); } - GameActions::Result result = GameActions::Result(); - - if (_modifyType == RideModifyType::renew) + uint32_t RideDemolishAction::GetCooldownTime() const { - if (ride->status != RideStatus::closed && ride->status != RideStatus::simulating) + return 1000; + } + + void RideDemolishAction::Serialise(DataSerialiser& stream) + { + GameAction::Serialise(stream); + + stream << DS_TAG(_rideIndex) << DS_TAG(_modifyType); + } + + Result RideDemolishAction::Query() const + { + auto ride = GetRide(_rideIndex); + if (ride == nullptr) { - return GameActions::Result(GameActions::Status::Disallowed, STR_CANT_REFURBISH_RIDE, STR_MUST_BE_CLOSED_FIRST); + LOG_ERROR("Ride not found for rideIndex %u", _rideIndex.ToUnderlying()); + return Result(Status::InvalidParameters, STR_CANT_DEMOLISH_RIDE, STR_ERR_RIDE_NOT_FOUND); } - if (ride->numRiders > 0) + if ((ride->lifecycleFlags & (RIDE_LIFECYCLE_INDESTRUCTIBLE | RIDE_LIFECYCLE_INDESTRUCTIBLE_TRACK) + && _modifyType == RideModifyType::demolish) + && !getGameState().cheats.makeAllDestructible) { - return GameActions::Result(GameActions::Status::Disallowed, STR_CANT_REFURBISH_RIDE, STR_RIDE_NOT_YET_EMPTY); + return Result( + Status::NoClearance, STR_CANT_DEMOLISH_RIDE, + STR_LOCAL_AUTHORITY_FORBIDS_DEMOLITION_OR_MODIFICATIONS_TO_THIS_RIDE); } - if (!(ride->lifecycleFlags & RIDE_LIFECYCLE_EVER_BEEN_OPENED) || ride->getRideTypeDescriptor().AvailableBreakdowns == 0) + Result result = Result(); + + if (_modifyType == RideModifyType::renew) { - return GameActions::Result(GameActions::Status::Disallowed, STR_CANT_REFURBISH_RIDE, STR_CANT_REFURBISH_NOT_NEEDED); - } - - result.ErrorTitle = STR_CANT_REFURBISH_RIDE; - result.Cost = GetRefurbishPrice(*ride); - } - - return result; -} - -GameActions::Result RideDemolishAction::Execute() const -{ - auto ride = GetRide(_rideIndex); - if (ride == nullptr) - { - LOG_ERROR("Ride not found for rideIndex %u", _rideIndex.ToUnderlying()); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_DEMOLISH_RIDE, STR_ERR_RIDE_NOT_FOUND); - } - - switch (_modifyType) - { - case RideModifyType::demolish: - return DemolishRide(*ride); - case RideModifyType::renew: - return RefurbishRide(*ride); - default: - LOG_ERROR("Unknown ride demolish type %d", _modifyType); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_DO_THIS, STR_ERR_VALUE_OUT_OF_RANGE); - } -} - -GameActions::Result RideDemolishAction::DemolishRide(Ride& ride) const -{ - money64 refundPrice = DemolishTracks(); - - RideClearForConstruction(ride); - ride.removePeeps(); - ride.stopGuestsQueuing(); - - ride.validateStations(); - RideClearLeftoverEntrances(ride); - - const auto rideId = ride.id; - News::DisableNewsItems(News::ItemType::ride, rideId.ToUnderlying()); - - UnlinkAllBannersForRide(ride.id); - - RideUse::GetHistory().RemoveValue(ride.id); - for (auto peep : EntityList()) - { - peep->RemoveRideFromMemory(ride.id); - } - - MarketingCancelCampaignsForRide(_rideIndex); - - auto res = GameActions::Result(); - res.Expenditure = ExpenditureType::rideConstruction; - res.Cost = refundPrice; - - if (!ride.overallView.IsNull()) - { - auto xy = ride.overallView.ToTileCentre(); - res.Position = { xy, TileElementHeight(xy) }; - } - - ride.remove(); - getGameState().park.value = Park::CalculateParkValue(); - - // Close windows related to the demolished ride - auto* windowMgr = Ui::GetWindowManager(); - windowMgr->CloseByNumber(WindowClass::RideConstruction, rideId.ToUnderlying()); - windowMgr->CloseByNumber(WindowClass::Ride, rideId.ToUnderlying()); - windowMgr->CloseByNumber(WindowClass::DemolishRidePrompt, rideId.ToUnderlying()); - windowMgr->CloseByClass(WindowClass::NewCampaign); - - // Refresh windows that display the ride name - auto windowManager = OpenRCT2::Ui::GetWindowManager(); - windowManager->BroadcastIntent(Intent(INTENT_ACTION_REFRESH_CAMPAIGN_RIDE_LIST)); - windowManager->BroadcastIntent(Intent(INTENT_ACTION_REFRESH_RIDE_LIST)); - windowManager->BroadcastIntent(Intent(INTENT_ACTION_REFRESH_GUEST_LIST)); - - ScrollingTextInvalidate(); - GfxInvalidateScreen(); - - return res; -} - -money64 RideDemolishAction::MazeRemoveTrack(const CoordsXYZD& coords) const -{ - auto setMazeTrack = MazeSetTrackAction(coords, false, _rideIndex, GC_SET_MAZE_TRACK_FILL); - setMazeTrack.SetFlags(GetFlags()); - - auto execRes = GameActions::ExecuteNested(&setMazeTrack); - if (execRes.Error == GameActions::Status::Ok) - { - return execRes.Cost; - } - - return kMoney64Undefined; -} - -money64 RideDemolishAction::DemolishTracks() const -{ - money64 refundPrice = 0; - - uint8_t oldpaused = gGamePaused; - gGamePaused = 0; - auto& gameState = getGameState(); - - for (TileCoordsXY tilePos = {}; tilePos.x < gameState.mapSize.x; ++tilePos.x) - { - for (tilePos.y = 0; tilePos.y < gameState.mapSize.y; ++tilePos.y) - { - const auto tileCoords = tilePos.ToCoordsXY(); - // Loop over all elements of the tile until there are no more items to remove - int offset = -1; - bool lastForTileReached = false; - while (!lastForTileReached) + if (ride->status != RideStatus::closed && ride->status != RideStatus::simulating) { - offset++; - auto* tileElement = MapGetFirstElementAt(tileCoords) + offset; - if (tileElement == nullptr) - break; + return Result(Status::Disallowed, STR_CANT_REFURBISH_RIDE, STR_MUST_BE_CLOSED_FIRST); + } - lastForTileReached = tileElement->IsLastForTile(); - if (tileElement->GetType() != TileElementType::Track) - continue; + if (ride->numRiders > 0) + { + return Result(Status::Disallowed, STR_CANT_REFURBISH_RIDE, STR_RIDE_NOT_YET_EMPTY); + } - auto* trackElement = tileElement->AsTrack(); - if (trackElement->GetRideIndex() != _rideIndex) - continue; + if (!(ride->lifecycleFlags & RIDE_LIFECYCLE_EVER_BEEN_OPENED) + || ride->getRideTypeDescriptor().AvailableBreakdowns == 0) + { + return Result(Status::Disallowed, STR_CANT_REFURBISH_RIDE, STR_CANT_REFURBISH_NOT_NEEDED); + } - const auto location = CoordsXYZD(tileCoords, trackElement->GetBaseZ(), trackElement->GetDirection()); - const auto type = trackElement->GetTrackType(); + result.ErrorTitle = STR_CANT_REFURBISH_RIDE; + result.Cost = GetRefurbishPrice(*ride); + } - if (type != TrackElemType::Maze) + return result; + } + + Result RideDemolishAction::Execute() const + { + auto ride = GetRide(_rideIndex); + if (ride == nullptr) + { + LOG_ERROR("Ride not found for rideIndex %u", _rideIndex.ToUnderlying()); + return Result(Status::InvalidParameters, STR_CANT_DEMOLISH_RIDE, STR_ERR_RIDE_NOT_FOUND); + } + + switch (_modifyType) + { + case RideModifyType::demolish: + return DemolishRide(*ride); + case RideModifyType::renew: + return RefurbishRide(*ride); + default: + LOG_ERROR("Unknown ride demolish type %d", _modifyType); + return Result(Status::InvalidParameters, STR_CANT_DO_THIS, STR_ERR_VALUE_OUT_OF_RANGE); + } + } + + Result RideDemolishAction::DemolishRide(Ride& ride) const + { + money64 refundPrice = DemolishTracks(); + + RideClearForConstruction(ride); + ride.removePeeps(); + ride.stopGuestsQueuing(); + + ride.validateStations(); + RideClearLeftoverEntrances(ride); + + const auto rideId = ride.id; + News::DisableNewsItems(News::ItemType::ride, rideId.ToUnderlying()); + + UnlinkAllBannersForRide(ride.id); + + RideUse::GetHistory().RemoveValue(ride.id); + for (auto peep : EntityList()) + { + peep->RemoveRideFromMemory(ride.id); + } + + MarketingCancelCampaignsForRide(_rideIndex); + + auto res = Result(); + res.Expenditure = ExpenditureType::rideConstruction; + res.Cost = refundPrice; + + if (!ride.overallView.IsNull()) + { + auto xy = ride.overallView.ToTileCentre(); + res.Position = { xy, TileElementHeight(xy) }; + } + + ride.remove(); + getGameState().park.value = Park::CalculateParkValue(); + + // Close windows related to the demolished ride + auto* windowMgr = Ui::GetWindowManager(); + windowMgr->CloseByNumber(WindowClass::RideConstruction, rideId.ToUnderlying()); + windowMgr->CloseByNumber(WindowClass::Ride, rideId.ToUnderlying()); + windowMgr->CloseByNumber(WindowClass::DemolishRidePrompt, rideId.ToUnderlying()); + windowMgr->CloseByClass(WindowClass::NewCampaign); + + // Refresh windows that display the ride name + auto windowManager = OpenRCT2::Ui::GetWindowManager(); + windowManager->BroadcastIntent(Intent(INTENT_ACTION_REFRESH_CAMPAIGN_RIDE_LIST)); + windowManager->BroadcastIntent(Intent(INTENT_ACTION_REFRESH_RIDE_LIST)); + windowManager->BroadcastIntent(Intent(INTENT_ACTION_REFRESH_GUEST_LIST)); + + ScrollingTextInvalidate(); + GfxInvalidateScreen(); + + return res; + } + + money64 RideDemolishAction::MazeRemoveTrack(const CoordsXYZD& coords) const + { + auto setMazeTrack = MazeSetTrackAction(coords, false, _rideIndex, GC_SET_MAZE_TRACK_FILL); + setMazeTrack.SetFlags(GetFlags()); + + auto execRes = ExecuteNested(&setMazeTrack); + if (execRes.Error == Status::Ok) + { + return execRes.Cost; + } + + return kMoney64Undefined; + } + + money64 RideDemolishAction::DemolishTracks() const + { + money64 refundPrice = 0; + + uint8_t oldpaused = gGamePaused; + gGamePaused = 0; + auto& gameState = getGameState(); + + for (TileCoordsXY tilePos = {}; tilePos.x < gameState.mapSize.x; ++tilePos.x) + { + for (tilePos.y = 0; tilePos.y < gameState.mapSize.y; ++tilePos.y) + { + const auto tileCoords = tilePos.ToCoordsXY(); + // Loop over all elements of the tile until there are no more items to remove + int offset = -1; + bool lastForTileReached = false; + while (!lastForTileReached) { - auto trackRemoveAction = TrackRemoveAction(type, trackElement->GetSequenceIndex(), location); - trackRemoveAction.SetFlags(GAME_COMMAND_FLAG_NO_SPEND); + offset++; + auto* tileElement = MapGetFirstElementAt(tileCoords) + offset; + if (tileElement == nullptr) + break; - auto removRes = GameActions::ExecuteNested(&trackRemoveAction); - if (removRes.Error != GameActions::Status::Ok) + lastForTileReached = tileElement->IsLastForTile(); + if (tileElement->GetType() != TileElementType::Track) + continue; + + auto* trackElement = tileElement->AsTrack(); + if (trackElement->GetRideIndex() != _rideIndex) + continue; + + const auto location = CoordsXYZD(tileCoords, trackElement->GetBaseZ(), trackElement->GetDirection()); + const auto type = trackElement->GetTrackType(); + + if (type != TrackElemType::Maze) { - TileElementRemove(tileElement); + auto trackRemoveAction = TrackRemoveAction(type, trackElement->GetSequenceIndex(), location); + trackRemoveAction.SetFlags(GAME_COMMAND_FLAG_NO_SPEND); + + auto removRes = ExecuteNested(&trackRemoveAction); + if (removRes.Error != Status::Ok) + { + TileElementRemove(tileElement); + } + else + { + refundPrice += removRes.Cost; + } } else { - refundPrice += removRes.Cost; - } - } - else - { - static constexpr CoordsXY kDirOffsets[] = { - { 0, 0 }, - { 0, 16 }, - { 16, 16 }, - { 16, 0 }, - }; - for (Direction dir : kAllDirections) - { - const CoordsXYZ off = { kDirOffsets[dir], 0 }; - money64 removePrice = MazeRemoveTrack({ location + off, dir }); - if (removePrice != kMoney64Undefined) + static constexpr CoordsXY kDirOffsets[] = { + { 0, 0 }, + { 0, 16 }, + { 16, 16 }, + { 16, 0 }, + }; + for (Direction dir : kAllDirections) { - refundPrice += removePrice; + const CoordsXYZ off = { kDirOffsets[dir], 0 }; + money64 removePrice = MazeRemoveTrack({ location + off, dir }); + if (removePrice != kMoney64Undefined) + { + refundPrice += removePrice; + } } } - } - // Now we have removed an element, decrement the offset, or we may skip consecutive track elements - offset--; + // Now we have removed an element, decrement the offset, or we may skip consecutive track elements + offset--; + } } } + + gGamePaused = oldpaused; + return refundPrice; } - gGamePaused = oldpaused; - return refundPrice; -} - -GameActions::Result RideDemolishAction::RefurbishRide(Ride& ride) const -{ - auto res = GameActions::Result(); - res.Expenditure = ExpenditureType::rideConstruction; - res.Cost = GetRefurbishPrice(ride); - - ride.renew(); - - ride.lifecycleFlags &= ~RIDE_LIFECYCLE_EVER_BEEN_OPENED; - ride.lastCrashType = RIDE_CRASH_TYPE_NONE; - - ride.windowInvalidateFlags |= RIDE_INVALIDATE_RIDE_MAINTENANCE | RIDE_INVALIDATE_RIDE_CUSTOMER; - - if (!ride.overallView.IsNull()) + Result RideDemolishAction::RefurbishRide(Ride& ride) const { - auto location = ride.overallView.ToTileCentre(); - res.Position = { location, TileElementHeight(location) }; + auto res = Result(); + res.Expenditure = ExpenditureType::rideConstruction; + res.Cost = GetRefurbishPrice(ride); + + ride.renew(); + + ride.lifecycleFlags &= ~RIDE_LIFECYCLE_EVER_BEEN_OPENED; + ride.lastCrashType = RIDE_CRASH_TYPE_NONE; + + ride.windowInvalidateFlags |= RIDE_INVALIDATE_RIDE_MAINTENANCE | RIDE_INVALIDATE_RIDE_CUSTOMER; + + if (!ride.overallView.IsNull()) + { + auto location = ride.overallView.ToTileCentre(); + res.Position = { location, TileElementHeight(location) }; + } + + auto* windowMgr = Ui::GetWindowManager(); + windowMgr->CloseByNumber(WindowClass::DemolishRidePrompt, _rideIndex.ToUnderlying()); + + return res; } - auto* windowMgr = Ui::GetWindowManager(); - windowMgr->CloseByNumber(WindowClass::DemolishRidePrompt, _rideIndex.ToUnderlying()); + money64 RideDemolishAction::GetRefurbishPrice(const Ride& ride) const + { + return -GetRefundPrice(ride) / 2; + } - return res; -} - -money64 RideDemolishAction::GetRefurbishPrice(const Ride& ride) const -{ - return -GetRefundPrice(ride) / 2; -} - -money64 RideDemolishAction::GetRefundPrice(const Ride& ride) const -{ - return RideGetRefundPrice(ride); -} + money64 RideDemolishAction::GetRefundPrice(const Ride& ride) const + { + return RideGetRefundPrice(ride); + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/RideDemolishAction.h b/src/openrct2/actions/RideDemolishAction.h index 52376b4015..ff009dab53 100644 --- a/src/openrct2/actions/RideDemolishAction.h +++ b/src/openrct2/actions/RideDemolishAction.h @@ -11,35 +11,38 @@ #include "GameAction.h" -enum class RideModifyType : uint8_t +namespace OpenRCT2::GameActions { - demolish, - renew, -}; + enum class RideModifyType : uint8_t + { + demolish, + renew, + }; -class RideDemolishAction final : public GameActionBase -{ -private: - RideId _rideIndex{ RideId::GetNull() }; - RideModifyType _modifyType{ RideModifyType::demolish }; + class RideDemolishAction final : public GameActionBase + { + private: + RideId _rideIndex{ RideId::GetNull() }; + RideModifyType _modifyType{ RideModifyType::demolish }; -public: - RideDemolishAction() = default; - RideDemolishAction(RideId rideIndex, RideModifyType modifyType); + public: + RideDemolishAction() = default; + RideDemolishAction(RideId rideIndex, RideModifyType modifyType); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint32_t GetCooldownTime() const override; + uint32_t GetCooldownTime() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; -private: - OpenRCT2::GameActions::Result DemolishRide(Ride& ride) const; - money64 MazeRemoveTrack(const CoordsXYZD& coords) const; - money64 DemolishTracks() const; - OpenRCT2::GameActions::Result RefurbishRide(Ride& ride) const; - money64 GetRefurbishPrice(const Ride& ride) const; - money64 GetRefundPrice(const Ride& ride) const; -}; + private: + Result DemolishRide(Ride& ride) const; + money64 MazeRemoveTrack(const CoordsXYZD& coords) const; + money64 DemolishTracks() const; + Result RefurbishRide(Ride& ride) const; + money64 GetRefurbishPrice(const Ride& ride) const; + money64 GetRefundPrice(const Ride& ride) const; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/RideEntranceExitPlaceAction.cpp b/src/openrct2/actions/RideEntranceExitPlaceAction.cpp index 26dba45030..b48eb3961d 100644 --- a/src/openrct2/actions/RideEntranceExitPlaceAction.cpp +++ b/src/openrct2/actions/RideEntranceExitPlaceAction.cpp @@ -20,253 +20,257 @@ #include "../world/Wall.h" #include "../world/tile_element/EntranceElement.h" -using namespace OpenRCT2; - -RideEntranceExitPlaceAction::RideEntranceExitPlaceAction( - const CoordsXY& loc, Direction direction, RideId rideIndex, StationIndex stationNum, bool isExit) - : _loc(loc) - , _direction(direction) - , _rideIndex(rideIndex) - , _stationNum(stationNum) - , _isExit(isExit) +namespace OpenRCT2::GameActions { -} - -void RideEntranceExitPlaceAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit(_loc); - visitor.Visit("direction", _direction); - visitor.Visit("ride", _rideIndex); - visitor.Visit("station", _stationNum); - visitor.Visit("isExit", _isExit); -} - -uint16_t RideEntranceExitPlaceAction::GetActionFlags() const -{ - return GameAction::GetActionFlags(); -} - -void RideEntranceExitPlaceAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_loc) << DS_TAG(_direction) << DS_TAG(_rideIndex) << DS_TAG(_stationNum) << DS_TAG(_isExit); -} - -GameActions::Result RideEntranceExitPlaceAction::Query() const -{ - const auto errorTitle = _isExit ? STR_CANT_BUILD_MOVE_EXIT_FOR_THIS_RIDE_ATTRACTION - : STR_CANT_BUILD_MOVE_ENTRANCE_FOR_THIS_RIDE_ATTRACTION; - - auto ride = GetRide(_rideIndex); - if (ride == nullptr) + RideEntranceExitPlaceAction::RideEntranceExitPlaceAction( + const CoordsXY& loc, Direction direction, RideId rideIndex, StationIndex stationNum, bool isExit) + : _loc(loc) + , _direction(direction) + , _rideIndex(rideIndex) + , _stationNum(stationNum) + , _isExit(isExit) { - LOG_ERROR("Ride not found for rideIndex %u", _rideIndex.ToUnderlying()); - return GameActions::Result(GameActions::Status::InvalidParameters, errorTitle, STR_ERR_RIDE_NOT_FOUND); } - if (_stationNum.ToUnderlying() >= Limits::kMaxStationsPerRide) + void RideEntranceExitPlaceAction::AcceptParameters(GameActionParameterVisitor& visitor) { - LOG_ERROR("Invalid station number for ride. stationNum: %u", _stationNum.ToUnderlying()); - return GameActions::Result(GameActions::Status::InvalidParameters, errorTitle, STR_ERR_VALUE_OUT_OF_RANGE); + visitor.Visit(_loc); + visitor.Visit("direction", _direction); + visitor.Visit("ride", _rideIndex); + visitor.Visit("station", _stationNum); + visitor.Visit("isExit", _isExit); } - if (ride->status != RideStatus::closed && ride->status != RideStatus::simulating) + uint16_t RideEntranceExitPlaceAction::GetActionFlags() const { - return GameActions::Result(GameActions::Status::NotClosed, errorTitle, STR_MUST_BE_CLOSED_FIRST); + return GameAction::GetActionFlags(); } - if (ride->lifecycleFlags & RIDE_LIFECYCLE_INDESTRUCTIBLE_TRACK) + void RideEntranceExitPlaceAction::Serialise(DataSerialiser& stream) { - return GameActions::Result(GameActions::Status::Disallowed, errorTitle, STR_NOT_ALLOWED_TO_MODIFY_STATION); + GameAction::Serialise(stream); + + stream << DS_TAG(_loc) << DS_TAG(_direction) << DS_TAG(_rideIndex) << DS_TAG(_stationNum) << DS_TAG(_isExit); } - const auto& station = ride->getStation(_stationNum); - const auto location = _isExit ? station.Exit : station.Entrance; - - if (!location.IsNull()) + Result RideEntranceExitPlaceAction::Query() const { - auto rideEntranceExitRemove = RideEntranceExitRemoveAction(location.ToCoordsXY(), _rideIndex, _stationNum, _isExit); - rideEntranceExitRemove.SetFlags(GetFlags()); + const auto errorTitle = _isExit ? STR_CANT_BUILD_MOVE_EXIT_FOR_THIS_RIDE_ATTRACTION + : STR_CANT_BUILD_MOVE_ENTRANCE_FOR_THIS_RIDE_ATTRACTION; - auto result = GameActions::QueryNested(&rideEntranceExitRemove); - if (result.Error != GameActions::Status::Ok) + auto ride = GetRide(_rideIndex); + if (ride == nullptr) { - result.ErrorTitle = errorTitle; - return result; + LOG_ERROR("Ride not found for rideIndex %u", _rideIndex.ToUnderlying()); + return Result(Status::InvalidParameters, errorTitle, STR_ERR_RIDE_NOT_FOUND); } - } - auto z = ride->getStation(_stationNum).GetBaseZ(); - if (!LocationValid(_loc)) - { - return GameActions::Result(GameActions::Status::InvalidParameters, errorTitle, STR_OFF_EDGE_OF_MAP); - } - if (!getGameState().cheats.sandboxMode && !MapIsLocationOwned({ _loc, z })) - { - return GameActions::Result(GameActions::Status::NotOwned, errorTitle, STR_LAND_NOT_OWNED_BY_PARK); - } - - if (!MapCheckCapacityAndReorganise(_loc)) - { - return GameActions::Result(GameActions::Status::NoFreeElements, errorTitle, STR_TILE_ELEMENT_LIMIT_REACHED); - } - auto clear_z = z + (_isExit ? RideExitHeight : RideEntranceHeight); - auto canBuild = MapCanConstructWithClearAt({ _loc, z, clear_z }, &MapPlaceNonSceneryClearFunc, { 0b1111, 0 }, GetFlags()); - if (canBuild.Error != GameActions::Status::Ok) - { - canBuild.ErrorTitle = errorTitle; - return canBuild; - } - - const auto clearanceData = canBuild.GetData(); - if (clearanceData.GroundFlags & ELEMENT_IS_UNDERWATER) - { - return GameActions::Result(GameActions::Status::Disallowed, errorTitle, STR_RIDE_CANT_BUILD_THIS_UNDERWATER); - } - - if (z > MaxRideEntranceOrExitHeight) - { - return GameActions::Result(GameActions::Status::Disallowed, errorTitle, STR_TOO_HIGH); - } - - auto res = GameActions::Result(); - res.Position = { _loc.ToTileCentre(), z }; - res.Expenditure = ExpenditureType::rideConstruction; - res.Cost += canBuild.Cost; - return res; -} - -GameActions::Result RideEntranceExitPlaceAction::Execute() const -{ - // Remember when in unknown station num mode rideIndex is unknown and z is set - // When in known station num mode rideIndex is known and z is unknown - const auto errorTitle = _isExit ? STR_CANT_BUILD_MOVE_EXIT_FOR_THIS_RIDE_ATTRACTION - : STR_CANT_BUILD_MOVE_ENTRANCE_FOR_THIS_RIDE_ATTRACTION; - auto ride = GetRide(_rideIndex); - if (ride == nullptr) - { - LOG_ERROR("Ride not found for rideIndex %u", _rideIndex.ToUnderlying()); - return GameActions::Result(GameActions::Status::InvalidParameters, errorTitle, STR_ERR_RIDE_NOT_FOUND); - } - - if (!(GetFlags() & GAME_COMMAND_FLAG_GHOST)) - { - RideClearForConstruction(*ride); - ride->removePeeps(); - } - - auto& station = ride->getStation(_stationNum); - const auto location = _isExit ? station.Exit : station.Entrance; - if (!location.IsNull()) - { - auto rideEntranceExitRemove = RideEntranceExitRemoveAction(location.ToCoordsXY(), _rideIndex, _stationNum, _isExit); - rideEntranceExitRemove.SetFlags(GetFlags()); - - auto result = GameActions::ExecuteNested(&rideEntranceExitRemove); - if (result.Error != GameActions::Status::Ok) + if (_stationNum.ToUnderlying() >= Limits::kMaxStationsPerRide) { - result.ErrorTitle = errorTitle; - return result; + LOG_ERROR("Invalid station number for ride. stationNum: %u", _stationNum.ToUnderlying()); + return Result(Status::InvalidParameters, errorTitle, STR_ERR_VALUE_OUT_OF_RANGE); } + + if (ride->status != RideStatus::closed && ride->status != RideStatus::simulating) + { + return Result(Status::NotClosed, errorTitle, STR_MUST_BE_CLOSED_FIRST); + } + + if (ride->lifecycleFlags & RIDE_LIFECYCLE_INDESTRUCTIBLE_TRACK) + { + return Result(Status::Disallowed, errorTitle, STR_NOT_ALLOWED_TO_MODIFY_STATION); + } + + const auto& station = ride->getStation(_stationNum); + const auto location = _isExit ? station.Exit : station.Entrance; + + if (!location.IsNull()) + { + auto rideEntranceExitRemove = GameActions::RideEntranceExitRemoveAction( + location.ToCoordsXY(), _rideIndex, _stationNum, _isExit); + rideEntranceExitRemove.SetFlags(GetFlags()); + + auto result = QueryNested(&rideEntranceExitRemove); + if (result.Error != Status::Ok) + { + result.ErrorTitle = errorTitle; + return result; + } + } + + auto z = ride->getStation(_stationNum).GetBaseZ(); + if (!LocationValid(_loc)) + { + return Result(Status::InvalidParameters, errorTitle, STR_OFF_EDGE_OF_MAP); + } + if (!getGameState().cheats.sandboxMode && !MapIsLocationOwned({ _loc, z })) + { + return Result(Status::NotOwned, errorTitle, STR_LAND_NOT_OWNED_BY_PARK); + } + + if (!MapCheckCapacityAndReorganise(_loc)) + { + return Result(Status::NoFreeElements, errorTitle, STR_TILE_ELEMENT_LIMIT_REACHED); + } + auto clear_z = z + (_isExit ? RideExitHeight : RideEntranceHeight); + auto canBuild = MapCanConstructWithClearAt( + { _loc, z, clear_z }, &MapPlaceNonSceneryClearFunc, { 0b1111, 0 }, GetFlags()); + if (canBuild.Error != Status::Ok) + { + canBuild.ErrorTitle = errorTitle; + return canBuild; + } + + const auto clearanceData = canBuild.GetData(); + if (clearanceData.GroundFlags & ELEMENT_IS_UNDERWATER) + { + return Result(Status::Disallowed, errorTitle, STR_RIDE_CANT_BUILD_THIS_UNDERWATER); + } + + if (z > MaxRideEntranceOrExitHeight) + { + return Result(Status::Disallowed, errorTitle, STR_TOO_HIGH); + } + + auto res = Result(); + res.Position = { _loc.ToTileCentre(), z }; + res.Expenditure = ExpenditureType::rideConstruction; + res.Cost += canBuild.Cost; + return res; } - auto z = station.GetBaseZ(); - if (!(GetFlags() & GAME_COMMAND_FLAG_ALLOW_DURING_PAUSED) && !(GetFlags() & GAME_COMMAND_FLAG_GHOST) - && !getGameState().cheats.disableClearanceChecks) + Result RideEntranceExitPlaceAction::Execute() const { - FootpathRemoveLitter({ _loc, z }); - WallRemoveAtZ({ _loc, z }); + // Remember when in unknown station num mode rideIndex is unknown and z is set + // When in known station num mode rideIndex is known and z is unknown + const auto errorTitle = _isExit ? STR_CANT_BUILD_MOVE_EXIT_FOR_THIS_RIDE_ATTRACTION + : STR_CANT_BUILD_MOVE_ENTRANCE_FOR_THIS_RIDE_ATTRACTION; + auto ride = GetRide(_rideIndex); + if (ride == nullptr) + { + LOG_ERROR("Ride not found for rideIndex %u", _rideIndex.ToUnderlying()); + return Result(Status::InvalidParameters, errorTitle, STR_ERR_RIDE_NOT_FOUND); + } + + if (!(GetFlags() & GAME_COMMAND_FLAG_GHOST)) + { + RideClearForConstruction(*ride); + ride->removePeeps(); + } + + auto& station = ride->getStation(_stationNum); + const auto location = _isExit ? station.Exit : station.Entrance; + if (!location.IsNull()) + { + auto rideEntranceExitRemove = GameActions::RideEntranceExitRemoveAction( + location.ToCoordsXY(), _rideIndex, _stationNum, _isExit); + rideEntranceExitRemove.SetFlags(GetFlags()); + + auto result = ExecuteNested(&rideEntranceExitRemove); + if (result.Error != Status::Ok) + { + result.ErrorTitle = errorTitle; + return result; + } + } + + auto z = station.GetBaseZ(); + if (!(GetFlags() & GAME_COMMAND_FLAG_ALLOW_DURING_PAUSED) && !(GetFlags() & GAME_COMMAND_FLAG_GHOST) + && !getGameState().cheats.disableClearanceChecks) + { + FootpathRemoveLitter({ _loc, z }); + WallRemoveAtZ({ _loc, z }); + } + + auto clear_z = z + (_isExit ? RideExitHeight : RideEntranceHeight); + auto canBuild = MapCanConstructWithClearAt( + { _loc, z, clear_z }, &MapPlaceNonSceneryClearFunc, { 0b1111, 0 }, GetFlags() | GAME_COMMAND_FLAG_APPLY); + if (canBuild.Error != Status::Ok) + { + canBuild.ErrorTitle = errorTitle; + return canBuild; + } + + auto res = Result(); + res.Position = { _loc.ToTileCentre(), z }; + res.Expenditure = ExpenditureType::rideConstruction; + res.Cost += canBuild.Cost; + + auto* entranceElement = TileElementInsert(CoordsXYZ{ _loc, z }, 0b1111); + Guard::Assert(entranceElement != nullptr); + + entranceElement->SetDirection(_direction); + entranceElement->SetClearanceZ(clear_z); + entranceElement->SetEntranceType(_isExit ? ENTRANCE_TYPE_RIDE_EXIT : ENTRANCE_TYPE_RIDE_ENTRANCE); + entranceElement->SetStationIndex(_stationNum); + entranceElement->SetRideIndex(_rideIndex); + entranceElement->SetGhost(GetFlags() & GAME_COMMAND_FLAG_GHOST); + + if (_isExit) + { + station.Exit = TileCoordsXYZD(CoordsXYZD{ _loc, z, entranceElement->GetDirection() }); + } + else + { + station.Entrance = TileCoordsXYZD(CoordsXYZD{ _loc, z, entranceElement->GetDirection() }); + station.LastPeepInQueue = EntityId::GetNull(); + station.QueueLength = 0; + + MapAnimations::MarkTileForInvalidation(TileCoordsXY(_loc)); + } + + FootpathQueueChainReset(); + + if (!(GetFlags() & GAME_COMMAND_FLAG_GHOST)) + { + MazeEntranceHedgeRemoval({ _loc, entranceElement->as() }); + } + + FootpathConnectEdges(_loc, entranceElement->as(), GetFlags()); + FootpathUpdateQueueChains(); + + MapInvalidateTileFull(_loc); + + return res; } - auto clear_z = z + (_isExit ? RideExitHeight : RideEntranceHeight); - auto canBuild = MapCanConstructWithClearAt( - { _loc, z, clear_z }, &MapPlaceNonSceneryClearFunc, { 0b1111, 0 }, GetFlags() | GAME_COMMAND_FLAG_APPLY); - if (canBuild.Error != GameActions::Status::Ok) + Result RideEntranceExitPlaceAction::TrackPlaceQuery(const CoordsXYZ& loc, const bool isExit) { - canBuild.ErrorTitle = errorTitle; - return canBuild; + const auto errorTitle = isExit ? STR_CANT_BUILD_MOVE_EXIT_FOR_THIS_RIDE_ATTRACTION + : STR_CANT_BUILD_MOVE_ENTRANCE_FOR_THIS_RIDE_ATTRACTION; + + if (!getGameState().cheats.sandboxMode && !MapIsLocationOwned(loc)) + { + return Result(Status::NotOwned, errorTitle, STR_LAND_NOT_OWNED_BY_PARK); + } + + if (!MapCheckCapacityAndReorganise(loc)) + { + return Result(Status::NoFreeElements, errorTitle, STR_TILE_ELEMENT_LIMIT_REACHED); + } + int16_t baseZ = loc.z; + int16_t clearZ = baseZ + (isExit ? RideExitHeight : RideEntranceHeight); + auto canBuild = MapCanConstructWithClearAt({ loc, baseZ, clearZ }, &MapPlaceNonSceneryClearFunc, { 0b1111, 0 }, 0); + if (canBuild.Error != Status::Ok) + { + canBuild.ErrorTitle = errorTitle; + return canBuild; + } + + const auto clearanceData = canBuild.GetData(); + if (clearanceData.GroundFlags & ELEMENT_IS_UNDERWATER) + { + return Result(Status::Disallowed, errorTitle, STR_RIDE_CANT_BUILD_THIS_UNDERWATER); + } + + if (baseZ > MaxRideEntranceOrExitHeight) + { + return Result(Status::Disallowed, errorTitle, STR_TOO_HIGH); + } + auto res = Result(); + res.Position = { loc.ToTileCentre(), TileElementHeight(loc) }; + res.Expenditure = ExpenditureType::rideConstruction; + res.Cost += canBuild.Cost; + return res; } - - auto res = GameActions::Result(); - res.Position = { _loc.ToTileCentre(), z }; - res.Expenditure = ExpenditureType::rideConstruction; - res.Cost += canBuild.Cost; - - auto* entranceElement = TileElementInsert(CoordsXYZ{ _loc, z }, 0b1111); - Guard::Assert(entranceElement != nullptr); - - entranceElement->SetDirection(_direction); - entranceElement->SetClearanceZ(clear_z); - entranceElement->SetEntranceType(_isExit ? ENTRANCE_TYPE_RIDE_EXIT : ENTRANCE_TYPE_RIDE_ENTRANCE); - entranceElement->SetStationIndex(_stationNum); - entranceElement->SetRideIndex(_rideIndex); - entranceElement->SetGhost(GetFlags() & GAME_COMMAND_FLAG_GHOST); - - if (_isExit) - { - station.Exit = TileCoordsXYZD(CoordsXYZD{ _loc, z, entranceElement->GetDirection() }); - } - else - { - station.Entrance = TileCoordsXYZD(CoordsXYZD{ _loc, z, entranceElement->GetDirection() }); - station.LastPeepInQueue = EntityId::GetNull(); - station.QueueLength = 0; - - MapAnimations::MarkTileForInvalidation(TileCoordsXY(_loc)); - } - - FootpathQueueChainReset(); - - if (!(GetFlags() & GAME_COMMAND_FLAG_GHOST)) - { - MazeEntranceHedgeRemoval({ _loc, entranceElement->as() }); - } - - FootpathConnectEdges(_loc, entranceElement->as(), GetFlags()); - FootpathUpdateQueueChains(); - - MapInvalidateTileFull(_loc); - - return res; -} - -GameActions::Result RideEntranceExitPlaceAction::TrackPlaceQuery(const CoordsXYZ& loc, const bool isExit) -{ - const auto errorTitle = isExit ? STR_CANT_BUILD_MOVE_EXIT_FOR_THIS_RIDE_ATTRACTION - : STR_CANT_BUILD_MOVE_ENTRANCE_FOR_THIS_RIDE_ATTRACTION; - - if (!getGameState().cheats.sandboxMode && !MapIsLocationOwned(loc)) - { - return GameActions::Result(GameActions::Status::NotOwned, errorTitle, STR_LAND_NOT_OWNED_BY_PARK); - } - - if (!MapCheckCapacityAndReorganise(loc)) - { - return GameActions::Result(GameActions::Status::NoFreeElements, errorTitle, STR_TILE_ELEMENT_LIMIT_REACHED); - } - int16_t baseZ = loc.z; - int16_t clearZ = baseZ + (isExit ? RideExitHeight : RideEntranceHeight); - auto canBuild = MapCanConstructWithClearAt({ loc, baseZ, clearZ }, &MapPlaceNonSceneryClearFunc, { 0b1111, 0 }, 0); - if (canBuild.Error != GameActions::Status::Ok) - { - canBuild.ErrorTitle = errorTitle; - return canBuild; - } - - const auto clearanceData = canBuild.GetData(); - if (clearanceData.GroundFlags & ELEMENT_IS_UNDERWATER) - { - return GameActions::Result(GameActions::Status::Disallowed, errorTitle, STR_RIDE_CANT_BUILD_THIS_UNDERWATER); - } - - if (baseZ > MaxRideEntranceOrExitHeight) - { - return GameActions::Result(GameActions::Status::Disallowed, errorTitle, STR_TOO_HIGH); - } - auto res = GameActions::Result(); - res.Position = { loc.ToTileCentre(), TileElementHeight(loc) }; - res.Expenditure = ExpenditureType::rideConstruction; - res.Cost += canBuild.Cost; - return res; -} +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/RideEntranceExitPlaceAction.h b/src/openrct2/actions/RideEntranceExitPlaceAction.h index aecffe796e..d08d9965dc 100644 --- a/src/openrct2/actions/RideEntranceExitPlaceAction.h +++ b/src/openrct2/actions/RideEntranceExitPlaceAction.h @@ -12,27 +12,30 @@ #include "../world/Entrance.h" #include "GameAction.h" -class RideEntranceExitPlaceAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - CoordsXY _loc; - Direction _direction{ kInvalidDirection }; - RideId _rideIndex{ RideId::GetNull() }; - StationIndex _stationNum{ StationIndex::GetNull() }; - bool _isExit{}; + class RideEntranceExitPlaceAction final : public GameActionBase + { + private: + CoordsXY _loc; + Direction _direction{ kInvalidDirection }; + RideId _rideIndex{ RideId::GetNull() }; + StationIndex _stationNum{ StationIndex::GetNull() }; + bool _isExit{}; -public: - RideEntranceExitPlaceAction() = default; - RideEntranceExitPlaceAction( - const CoordsXY& loc, Direction direction, RideId rideIndex, StationIndex stationNum, bool isExit); + public: + RideEntranceExitPlaceAction() = default; + RideEntranceExitPlaceAction( + const CoordsXY& loc, Direction direction, RideId rideIndex, StationIndex stationNum, bool isExit); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; - static OpenRCT2::GameActions::Result TrackPlaceQuery(const CoordsXYZ& loc, const bool isExit); -}; + static Result TrackPlaceQuery(const CoordsXYZ& loc, const bool isExit); + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/RideEntranceExitRemoveAction.cpp b/src/openrct2/actions/RideEntranceExitRemoveAction.cpp index 553f8d0ba7..b4cfadcb2c 100644 --- a/src/openrct2/actions/RideEntranceExitRemoveAction.cpp +++ b/src/openrct2/actions/RideEntranceExitRemoveAction.cpp @@ -16,159 +16,156 @@ #include "../world/TileElementsView.h" #include "../world/tile_element/EntranceElement.h" -using namespace OpenRCT2; - -RideEntranceExitRemoveAction::RideEntranceExitRemoveAction( - const CoordsXY& loc, RideId rideIndex, StationIndex stationNum, bool isExit) - : _loc(loc) - , _rideIndex(rideIndex) - , _stationNum(stationNum) - , _isExit(isExit) +namespace OpenRCT2::GameActions { -} - -void RideEntranceExitRemoveAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit(_loc); - visitor.Visit("ride", _rideIndex); - visitor.Visit("station", _stationNum); - visitor.Visit("isExit", _isExit); -} - -uint16_t RideEntranceExitRemoveAction::GetActionFlags() const -{ - return GameAction::GetActionFlags(); -} - -void RideEntranceExitRemoveAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_loc) << DS_TAG(_rideIndex) << DS_TAG(_stationNum) << DS_TAG(_isExit); -} - -static TileElement* FindEntranceElement( - const CoordsXY& loc, RideId rideIndex, StationIndex stationNum, int32_t entranceType, uint32_t flags) -{ - for (auto* entranceElement : TileElementsView(loc)) + RideEntranceExitRemoveAction::RideEntranceExitRemoveAction( + const CoordsXY& loc, RideId rideIndex, StationIndex stationNum, bool isExit) + : _loc(loc) + , _rideIndex(rideIndex) + , _stationNum(stationNum) + , _isExit(isExit) { - if (entranceElement->GetRideIndex() != rideIndex) - continue; - - if (entranceElement->GetStationIndex() != stationNum) - continue; - - if (entranceElement->GetEntranceType() != entranceType) - continue; - - return entranceElement->as(); - } - return nullptr; -} - -GameActions::Result RideEntranceExitRemoveAction::Query() const -{ - auto ride = GetRide(_rideIndex); - if (ride == nullptr) - { - LOG_ERROR("Ride not found for rideIndex %u", _rideIndex.ToUnderlying()); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_RIDE_NOT_FOUND); } - if (ride->status != RideStatus::closed && ride->status != RideStatus::simulating) + void RideEntranceExitRemoveAction::AcceptParameters(GameActionParameterVisitor& visitor) { - return GameActions::Result(GameActions::Status::InvalidParameters, STR_MUST_BE_CLOSED_FIRST, kStringIdNone); + visitor.Visit(_loc); + visitor.Visit("ride", _rideIndex); + visitor.Visit("station", _stationNum); + visitor.Visit("isExit", _isExit); } - if (ride->lifecycleFlags & RIDE_LIFECYCLE_INDESTRUCTIBLE_TRACK) + uint16_t RideEntranceExitRemoveAction::GetActionFlags() const { - return GameActions::Result(GameActions::Status::InvalidParameters, STR_NOT_ALLOWED_TO_MODIFY_STATION, kStringIdNone); + return GameAction::GetActionFlags(); } - if (!LocationValid(_loc)) + void RideEntranceExitRemoveAction::Serialise(DataSerialiser& stream) { - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_REMOVE_THIS, STR_OFF_EDGE_OF_MAP); + GameAction::Serialise(stream); + + stream << DS_TAG(_loc) << DS_TAG(_rideIndex) << DS_TAG(_stationNum) << DS_TAG(_isExit); } - auto* entranceElement = FindEntranceElement( - _loc, _rideIndex, _stationNum, _isExit ? ENTRANCE_TYPE_RIDE_EXIT : ENTRANCE_TYPE_RIDE_ENTRANCE, GetFlags()); + static TileElement* FindEntranceElement( + const CoordsXY& loc, RideId rideIndex, StationIndex stationNum, int32_t entranceType, uint32_t flags) + { + for (auto* entranceElement : TileElementsView(loc)) + { + if (entranceElement->GetRideIndex() != rideIndex) + continue; - // If we are trying to remove a ghost and the element we found is real, return an error, but don't log a warning - if (entranceElement != nullptr && (GetFlags() & GAME_COMMAND_FLAG_GHOST) && !(entranceElement->IsGhost())) - { - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_GHOST_ELEMENT_NOT_FOUND); - } - else if (entranceElement == nullptr) - { - LOG_ERROR( - "Entrance/exit element not found. x = %d, y = %d, ride = %u, station = %u", _loc.x, _loc.y, - _rideIndex.ToUnderlying(), _stationNum.ToUnderlying()); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_ENTRANCE_ELEMENT_NOT_FOUND); + if (entranceElement->GetStationIndex() != stationNum) + continue; + + if (entranceElement->GetEntranceType() != entranceType) + continue; + + return entranceElement->as(); + } + return nullptr; } - return GameActions::Result(); -} - -GameActions::Result RideEntranceExitRemoveAction::Execute() const -{ - auto ride = GetRide(_rideIndex); - if (ride == nullptr) + Result RideEntranceExitRemoveAction::Query() const { - LOG_ERROR("Ride not found for rideIndex %u", _rideIndex.ToUnderlying()); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_RIDE_NOT_FOUND); + auto ride = GetRide(_rideIndex); + if (ride == nullptr) + { + LOG_ERROR("Ride not found for rideIndex %u", _rideIndex.ToUnderlying()); + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_RIDE_NOT_FOUND); + } + + if (ride->status != RideStatus::closed && ride->status != RideStatus::simulating) + { + return Result(Status::InvalidParameters, STR_MUST_BE_CLOSED_FIRST, kStringIdNone); + } + + if (ride->lifecycleFlags & RIDE_LIFECYCLE_INDESTRUCTIBLE_TRACK) + { + return Result(Status::InvalidParameters, STR_NOT_ALLOWED_TO_MODIFY_STATION, kStringIdNone); + } + + if (!LocationValid(_loc)) + { + return Result(Status::InvalidParameters, STR_CANT_REMOVE_THIS, STR_OFF_EDGE_OF_MAP); + } + + auto* entranceElement = FindEntranceElement( + _loc, _rideIndex, _stationNum, _isExit ? ENTRANCE_TYPE_RIDE_EXIT : ENTRANCE_TYPE_RIDE_ENTRANCE, GetFlags()); + + // If we are trying to remove a ghost and the element we found is real, return an error, but don't log a warning + if (entranceElement != nullptr && (GetFlags() & GAME_COMMAND_FLAG_GHOST) && !(entranceElement->IsGhost())) + { + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_GHOST_ELEMENT_NOT_FOUND); + } + else if (entranceElement == nullptr) + { + LOG_ERROR( + "Entrance/exit element not found. x = %d, y = %d, ride = %u, station = %u", _loc.x, _loc.y, + _rideIndex.ToUnderlying(), _stationNum.ToUnderlying()); + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_ENTRANCE_ELEMENT_NOT_FOUND); + } + + return Result(); } - const bool isGhost = GetFlags() & GAME_COMMAND_FLAG_GHOST; - if (!isGhost) + Result RideEntranceExitRemoveAction::Execute() const { - RideClearForConstruction(*ride); - ride->removePeeps(); - InvalidateTestResults(*ride); + auto ride = GetRide(_rideIndex); + if (ride == nullptr) + { + LOG_ERROR("Ride not found for rideIndex %u", _rideIndex.ToUnderlying()); + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_RIDE_NOT_FOUND); + } + + const bool isGhost = GetFlags() & GAME_COMMAND_FLAG_GHOST; + if (!isGhost) + { + RideClearForConstruction(*ride); + ride->removePeeps(); + InvalidateTestResults(*ride); + } + + auto* entranceElement = FindEntranceElement( + _loc, _rideIndex, _stationNum, _isExit ? ENTRANCE_TYPE_RIDE_EXIT : ENTRANCE_TYPE_RIDE_ENTRANCE, GetFlags()); + + // If we are trying to remove a ghost and the element we found is real, return an error, but don't log a warning + if (entranceElement != nullptr && isGhost && !(entranceElement->IsGhost())) + { + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_GHOST_ELEMENT_NOT_FOUND); + } + else if (entranceElement == nullptr) + { + LOG_ERROR( + "Entrance/exit element not found. x = %d, y = %d, ride = %u, station = %d", _loc.x, _loc.y, + _rideIndex.ToUnderlying(), _stationNum); + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_ENTRANCE_ELEMENT_NOT_FOUND); + } + + auto res = Result(); + res.Position.x = _loc.x + 16; + res.Position.y = _loc.y + 16; + res.Position.z = TileElementHeight(res.Position); + + FootpathQueueChainReset(); + MazeEntranceHedgeReplacement({ _loc, entranceElement }); + FootpathRemoveEdgesAt(_loc, entranceElement); + + TileElementRemove(entranceElement); + + auto& station = ride->getStation(_stationNum); + if (_isExit) + { + station.Exit.SetNull(); + } + else + { + station.Entrance.SetNull(); + } + + FootpathUpdateQueueChains(); + + MapInvalidateTileFull(_loc); + return res; } - - auto* entranceElement = FindEntranceElement( - _loc, _rideIndex, _stationNum, _isExit ? ENTRANCE_TYPE_RIDE_EXIT : ENTRANCE_TYPE_RIDE_ENTRANCE, GetFlags()); - - // If we are trying to remove a ghost and the element we found is real, return an error, but don't log a warning - if (entranceElement != nullptr && isGhost && !(entranceElement->IsGhost())) - { - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_GHOST_ELEMENT_NOT_FOUND); - } - else if (entranceElement == nullptr) - { - LOG_ERROR( - "Entrance/exit element not found. x = %d, y = %d, ride = %u, station = %d", _loc.x, _loc.y, - _rideIndex.ToUnderlying(), _stationNum); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_ENTRANCE_ELEMENT_NOT_FOUND); - } - - auto res = GameActions::Result(); - res.Position.x = _loc.x + 16; - res.Position.y = _loc.y + 16; - res.Position.z = TileElementHeight(res.Position); - - FootpathQueueChainReset(); - MazeEntranceHedgeReplacement({ _loc, entranceElement }); - FootpathRemoveEdgesAt(_loc, entranceElement); - - TileElementRemove(entranceElement); - - auto& station = ride->getStation(_stationNum); - if (_isExit) - { - station.Exit.SetNull(); - } - else - { - station.Entrance.SetNull(); - } - - FootpathUpdateQueueChains(); - - MapInvalidateTileFull(_loc); - return res; -} +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/RideEntranceExitRemoveAction.h b/src/openrct2/actions/RideEntranceExitRemoveAction.h index 662bb1d1a6..eb381bdbb5 100644 --- a/src/openrct2/actions/RideEntranceExitRemoveAction.h +++ b/src/openrct2/actions/RideEntranceExitRemoveAction.h @@ -11,23 +11,26 @@ #include "GameAction.h" -class RideEntranceExitRemoveAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - CoordsXY _loc; - RideId _rideIndex{ RideId::GetNull() }; - StationIndex _stationNum{ StationIndex::GetNull() }; - bool _isExit{}; + class RideEntranceExitRemoveAction final : public GameActionBase + { + private: + CoordsXY _loc; + RideId _rideIndex{ RideId::GetNull() }; + StationIndex _stationNum{ StationIndex::GetNull() }; + bool _isExit{}; -public: - RideEntranceExitRemoveAction() = default; - RideEntranceExitRemoveAction(const CoordsXY& loc, RideId rideIndex, StationIndex stationNum, bool isExit); + public: + RideEntranceExitRemoveAction() = default; + RideEntranceExitRemoveAction(const CoordsXY& loc, RideId rideIndex, StationIndex stationNum, bool isExit); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; -}; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/RideFreezeRatingAction.cpp b/src/openrct2/actions/RideFreezeRatingAction.cpp index 87d806ca37..0bd5d82430 100644 --- a/src/openrct2/actions/RideFreezeRatingAction.cpp +++ b/src/openrct2/actions/RideFreezeRatingAction.cpp @@ -12,69 +12,69 @@ #include "../Diagnostic.h" #include "../ui/WindowManager.h" -using namespace OpenRCT2; - -RideFreezeRatingAction::RideFreezeRatingAction(RideId rideIndex, RideRatingType type, RideRating_t value) - : _rideIndex(rideIndex) - , _type(type) - , _value(value) +namespace OpenRCT2::GameActions { -} - -void RideFreezeRatingAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit("ride", _rideIndex); - visitor.Visit("type", _type); - visitor.Visit("value", _value); -} - -void RideFreezeRatingAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - stream << DS_TAG(_rideIndex) << DS_TAG(_type) << DS_TAG(_value); -} - -GameActions::Result RideFreezeRatingAction::Query() const -{ - auto ride = GetRide(_rideIndex); - if (ride == nullptr) + RideFreezeRatingAction::RideFreezeRatingAction(RideId rideIndex, RideRatingType type, RideRating_t value) + : _rideIndex(rideIndex) + , _type(type) + , _value(value) { - LOG_ERROR("Ride not found for rideIndex %u", _rideIndex.ToUnderlying()); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_RIDE_NOT_FOUND); } - if (_value <= 0) + void RideFreezeRatingAction::AcceptParameters(GameActionParameterVisitor& visitor) { - LOG_ERROR("Rating value must be positive: %u", _rideIndex.ToUnderlying()); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_VALUE_OUT_OF_RANGE); + visitor.Visit("ride", _rideIndex); + visitor.Visit("type", _type); + visitor.Visit("value", _value); } - return GameActions::Result(); -} - -GameActions::Result RideFreezeRatingAction::Execute() const -{ - auto ride = GetRide(_rideIndex); - - switch (_type) + void RideFreezeRatingAction::Serialise(DataSerialiser& stream) { - case RideRatingType::Excitement: - ride->ratings.excitement = _value; - break; - case RideRatingType::Intensity: - ride->ratings.intensity = _value; - break; - case RideRatingType::Nausea: - ride->ratings.nausea = _value; - break; + GameAction::Serialise(stream); + stream << DS_TAG(_rideIndex) << DS_TAG(_type) << DS_TAG(_value); } - ride->lifecycleFlags |= RIDE_LIFECYCLE_FIXED_RATINGS; + Result RideFreezeRatingAction::Query() const + { + auto ride = GetRide(_rideIndex); + if (ride == nullptr) + { + LOG_ERROR("Ride not found for rideIndex %u", _rideIndex.ToUnderlying()); + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_RIDE_NOT_FOUND); + } - auto* windowMgr = Ui::GetWindowManager(); - windowMgr->InvalidateByNumber(WindowClass::Ride, _rideIndex.ToUnderlying()); + if (_value <= 0) + { + LOG_ERROR("Rating value must be positive: %u", _rideIndex.ToUnderlying()); + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_VALUE_OUT_OF_RANGE); + } - auto res = GameActions::Result(); - return res; -} + return Result(); + } + + Result RideFreezeRatingAction::Execute() const + { + auto ride = GetRide(_rideIndex); + + switch (_type) + { + case RideRatingType::Excitement: + ride->ratings.excitement = _value; + break; + case RideRatingType::Intensity: + ride->ratings.intensity = _value; + break; + case RideRatingType::Nausea: + ride->ratings.nausea = _value; + break; + } + + ride->lifecycleFlags |= RIDE_LIFECYCLE_FIXED_RATINGS; + + auto* windowMgr = Ui::GetWindowManager(); + windowMgr->InvalidateByNumber(WindowClass::Ride, _rideIndex.ToUnderlying()); + + auto res = Result(); + return res; + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/RideFreezeRatingAction.h b/src/openrct2/actions/RideFreezeRatingAction.h index 59c7929bf2..5a23e9b97a 100644 --- a/src/openrct2/actions/RideFreezeRatingAction.h +++ b/src/openrct2/actions/RideFreezeRatingAction.h @@ -11,27 +11,30 @@ #include "GameAction.h" -enum class RideRatingType : uint8_t +namespace OpenRCT2::GameActions { - Excitement, - Intensity, - Nausea, -}; -// -class RideFreezeRatingAction final : public GameActionBase -{ -private: - RideId _rideIndex{ RideId::GetNull() }; - RideRatingType _type{}; - OpenRCT2::RideRating_t _value{}; + enum class RideRatingType : uint8_t + { + Excitement, + Intensity, + Nausea, + }; -public: - RideFreezeRatingAction() = default; - RideFreezeRatingAction(RideId rideIndex, RideRatingType type, OpenRCT2::RideRating_t value); + class RideFreezeRatingAction final : public GameActionBase + { + private: + RideId _rideIndex{ RideId::GetNull() }; + RideRatingType _type{}; + RideRating_t _value{}; - void AcceptParameters(GameActionParameterVisitor& visitor) override; + public: + RideFreezeRatingAction() = default; + RideFreezeRatingAction(RideId rideIndex, RideRatingType type, RideRating_t value); - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; -}; + void AcceptParameters(GameActionParameterVisitor& visitor) override; + + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/RideSetAppearanceAction.cpp b/src/openrct2/actions/RideSetAppearanceAction.cpp index 958a3c50f1..caf8ccee0b 100644 --- a/src/openrct2/actions/RideSetAppearanceAction.cpp +++ b/src/openrct2/actions/RideSetAppearanceAction.cpp @@ -19,140 +19,144 @@ #include "../ui/WindowManager.h" #include "../world/Park.h" -using namespace OpenRCT2; - -RideSetAppearanceAction::RideSetAppearanceAction(RideId rideIndex, RideSetAppearanceType type, uint16_t value, uint32_t index) - : _rideIndex(rideIndex) - , _type(type) - , _value(value) - , _index(index) +namespace OpenRCT2::GameActions { -} - -void RideSetAppearanceAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit("ride", _rideIndex); - visitor.Visit("type", _type); - visitor.Visit("value", _value); - visitor.Visit("index", _index); -} - -uint16_t RideSetAppearanceAction::GetActionFlags() const -{ - return GameAction::GetActionFlags() | GameActions::Flags::AllowWhilePaused; -} - -void RideSetAppearanceAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - stream << DS_TAG(_rideIndex) << DS_TAG(_type) << DS_TAG(_value) << DS_TAG(_index); -} - -GameActions::Result RideSetAppearanceAction::Query() const -{ - auto ride = GetRide(_rideIndex); - if (ride == nullptr) + RideSetAppearanceAction::RideSetAppearanceAction( + RideId rideIndex, RideSetAppearanceType type, uint16_t value, uint32_t index) + : _rideIndex(rideIndex) + , _type(type) + , _value(value) + , _index(index) { - LOG_ERROR("Ride not found for rideIndex %u", _rideIndex.ToUnderlying()); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_RIDE_NOT_FOUND); } - switch (_type) + void RideSetAppearanceAction::AcceptParameters(GameActionParameterVisitor& visitor) { - case RideSetAppearanceType::TrackColourMain: - case RideSetAppearanceType::TrackColourAdditional: - case RideSetAppearanceType::TrackColourSupports: - if (_index >= std::size(ride->trackColours)) - { - LOG_ERROR("Invalid track colour %u", _index); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_INVALID_COLOUR); - } - break; - case RideSetAppearanceType::VehicleColourBody: - case RideSetAppearanceType::VehicleColourTrim: - case RideSetAppearanceType::VehicleColourTertiary: - if (_index >= std::size(ride->vehicleColours)) - { - LOG_ERROR("Invalid vehicle colour %u", _index); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_INVALID_COLOUR); - } - break; - case RideSetAppearanceType::VehicleColourScheme: - case RideSetAppearanceType::EntranceStyle: - case RideSetAppearanceType::SellingItemColourIsRandom: - break; - default: - LOG_ERROR("Invalid ride appearance type %u", _type); + visitor.Visit("ride", _rideIndex); + visitor.Visit("type", _type); + visitor.Visit("value", _value); + visitor.Visit("index", _index); + } + + uint16_t RideSetAppearanceAction::GetActionFlags() const + { + return GameAction::GetActionFlags() | GameActions::Flags::AllowWhilePaused; + } + + void RideSetAppearanceAction::Serialise(DataSerialiser& stream) + { + GameAction::Serialise(stream); + stream << DS_TAG(_rideIndex) << DS_TAG(_type) << DS_TAG(_value) << DS_TAG(_index); + } + + GameActions::Result RideSetAppearanceAction::Query() const + { + auto ride = GetRide(_rideIndex); + if (ride == nullptr) + { + LOG_ERROR("Ride not found for rideIndex %u", _rideIndex.ToUnderlying()); return GameActions::Result( - GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_VALUE_OUT_OF_RANGE); + GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_RIDE_NOT_FOUND); + } + + switch (_type) + { + case RideSetAppearanceType::TrackColourMain: + case RideSetAppearanceType::TrackColourAdditional: + case RideSetAppearanceType::TrackColourSupports: + if (_index >= std::size(ride->trackColours)) + { + LOG_ERROR("Invalid track colour %u", _index); + return GameActions::Result( + GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_INVALID_COLOUR); + } + break; + case RideSetAppearanceType::VehicleColourBody: + case RideSetAppearanceType::VehicleColourTrim: + case RideSetAppearanceType::VehicleColourTertiary: + if (_index >= std::size(ride->vehicleColours)) + { + LOG_ERROR("Invalid vehicle colour %u", _index); + return GameActions::Result( + GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_INVALID_COLOUR); + } + break; + case RideSetAppearanceType::VehicleColourScheme: + case RideSetAppearanceType::EntranceStyle: + case RideSetAppearanceType::SellingItemColourIsRandom: + break; + default: + LOG_ERROR("Invalid ride appearance type %u", _type); + return GameActions::Result( + GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_VALUE_OUT_OF_RANGE); + } + + return GameActions::Result(); } - return GameActions::Result(); -} - -GameActions::Result RideSetAppearanceAction::Execute() const -{ - auto ride = GetRide(_rideIndex); - if (ride == nullptr) + GameActions::Result RideSetAppearanceAction::Execute() const { - LOG_ERROR("Ride not found for rideIndex %u", _rideIndex.ToUnderlying()); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_RIDE_NOT_FOUND); + auto ride = GetRide(_rideIndex); + if (ride == nullptr) + { + LOG_ERROR("Ride not found for rideIndex %u", _rideIndex.ToUnderlying()); + return GameActions::Result( + GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_RIDE_NOT_FOUND); + } + + switch (_type) + { + case RideSetAppearanceType::TrackColourMain: + ride->trackColours[_index].main = _value; + GfxInvalidateScreen(); + break; + case RideSetAppearanceType::TrackColourAdditional: + ride->trackColours[_index].additional = _value; + GfxInvalidateScreen(); + break; + case RideSetAppearanceType::TrackColourSupports: + ride->trackColours[_index].supports = _value; + GfxInvalidateScreen(); + break; + case RideSetAppearanceType::VehicleColourBody: + ride->vehicleColours[_index].Body = _value; + RideUpdateVehicleColours(*ride); + break; + case RideSetAppearanceType::VehicleColourTrim: + ride->vehicleColours[_index].Trim = _value; + RideUpdateVehicleColours(*ride); + break; + case RideSetAppearanceType::VehicleColourTertiary: + ride->vehicleColours[_index].Tertiary = _value; + RideUpdateVehicleColours(*ride); + break; + case RideSetAppearanceType::VehicleColourScheme: + ride->vehicleColourSettings = static_cast(_value); + for (uint32_t i = 1; i < std::size(ride->vehicleColours); i++) + { + ride->vehicleColours[i] = ride->vehicleColours[0]; + } + RideUpdateVehicleColours(*ride); + break; + case RideSetAppearanceType::EntranceStyle: + ride->entranceStyle = _value; + GfxInvalidateScreen(); + break; + case RideSetAppearanceType::SellingItemColourIsRandom: + ride->setLifecycleFlag(RIDE_LIFECYCLE_RANDOM_SHOP_COLOURS, static_cast(_value)); + break; + } + + auto* windowMgr = Ui::GetWindowManager(); + windowMgr->InvalidateByNumber(WindowClass::Ride, _rideIndex.ToUnderlying()); + + auto res = GameActions::Result(); + if (!ride->overallView.IsNull()) + { + auto location = ride->overallView.ToTileCentre(); + res.Position = { location, TileElementHeight(location) }; + } + + return res; } - - switch (_type) - { - case RideSetAppearanceType::TrackColourMain: - ride->trackColours[_index].main = _value; - GfxInvalidateScreen(); - break; - case RideSetAppearanceType::TrackColourAdditional: - ride->trackColours[_index].additional = _value; - GfxInvalidateScreen(); - break; - case RideSetAppearanceType::TrackColourSupports: - ride->trackColours[_index].supports = _value; - GfxInvalidateScreen(); - break; - case RideSetAppearanceType::VehicleColourBody: - ride->vehicleColours[_index].Body = _value; - RideUpdateVehicleColours(*ride); - break; - case RideSetAppearanceType::VehicleColourTrim: - ride->vehicleColours[_index].Trim = _value; - RideUpdateVehicleColours(*ride); - break; - case RideSetAppearanceType::VehicleColourTertiary: - ride->vehicleColours[_index].Tertiary = _value; - RideUpdateVehicleColours(*ride); - break; - case RideSetAppearanceType::VehicleColourScheme: - ride->vehicleColourSettings = static_cast(_value); - for (uint32_t i = 1; i < std::size(ride->vehicleColours); i++) - { - ride->vehicleColours[i] = ride->vehicleColours[0]; - } - RideUpdateVehicleColours(*ride); - break; - case RideSetAppearanceType::EntranceStyle: - ride->entranceStyle = _value; - GfxInvalidateScreen(); - break; - case RideSetAppearanceType::SellingItemColourIsRandom: - ride->setLifecycleFlag(RIDE_LIFECYCLE_RANDOM_SHOP_COLOURS, static_cast(_value)); - break; - } - - auto* windowMgr = Ui::GetWindowManager(); - windowMgr->InvalidateByNumber(WindowClass::Ride, _rideIndex.ToUnderlying()); - - auto res = GameActions::Result(); - if (!ride->overallView.IsNull()) - { - auto location = ride->overallView.ToTileCentre(); - res.Position = { location, TileElementHeight(location) }; - } - - return res; -} +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/RideSetAppearanceAction.h b/src/openrct2/actions/RideSetAppearanceAction.h index cb32528ac8..53aea6f639 100644 --- a/src/openrct2/actions/RideSetAppearanceAction.h +++ b/src/openrct2/actions/RideSetAppearanceAction.h @@ -11,37 +11,40 @@ #include "GameAction.h" -enum class RideSetAppearanceType : uint8_t +namespace OpenRCT2::GameActions { - TrackColourMain, - TrackColourAdditional, - TrackColourSupports, - MazeStyle = TrackColourSupports, - VehicleColourBody, - VehicleColourTrim, - VehicleColourTertiary, - VehicleColourScheme, - EntranceStyle, - SellingItemColourIsRandom -}; + enum class RideSetAppearanceType : uint8_t + { + TrackColourMain, + TrackColourAdditional, + TrackColourSupports, + MazeStyle = TrackColourSupports, + VehicleColourBody, + VehicleColourTrim, + VehicleColourTertiary, + VehicleColourScheme, + EntranceStyle, + SellingItemColourIsRandom + }; -class RideSetAppearanceAction final : public GameActionBase -{ -private: - RideId _rideIndex{ RideId::GetNull() }; - RideSetAppearanceType _type{}; - uint16_t _value{}; - uint32_t _index{}; + class RideSetAppearanceAction final : public GameActionBase + { + private: + RideId _rideIndex{ RideId::GetNull() }; + RideSetAppearanceType _type{}; + uint16_t _value{}; + uint32_t _index{}; -public: - RideSetAppearanceAction() = default; - RideSetAppearanceAction(RideId rideIndex, RideSetAppearanceType type, uint16_t value, uint32_t index); + public: + RideSetAppearanceAction() = default; + RideSetAppearanceAction(RideId rideIndex, RideSetAppearanceType type, uint16_t value, uint32_t index); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; -}; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/RideSetColourSchemeAction.cpp b/src/openrct2/actions/RideSetColourSchemeAction.cpp index fa24171067..bf113918dd 100644 --- a/src/openrct2/actions/RideSetColourSchemeAction.cpp +++ b/src/openrct2/actions/RideSetColourSchemeAction.cpp @@ -17,67 +17,67 @@ #include "../ride/RideConstruction.h" #include "../world/Park.h" -using namespace OpenRCT2; - -RideSetColourSchemeAction::RideSetColourSchemeAction( - const CoordsXYZD& location, OpenRCT2::TrackElemType trackType, uint16_t newColourScheme) - : _loc(location) - , _trackType(trackType) - , _newColourScheme(newColourScheme) +namespace OpenRCT2::GameActions { -} - -void RideSetColourSchemeAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit(_loc); - visitor.Visit("trackType", _trackType); - visitor.Visit("colourScheme", _newColourScheme); -} - -uint16_t RideSetColourSchemeAction::GetActionFlags() const -{ - return GameAction::GetActionFlags() | GameActions::Flags::AllowWhilePaused; -} - -void RideSetColourSchemeAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_loc) << DS_TAG(_trackType) << DS_TAG(_newColourScheme); -} - -GameActions::Result RideSetColourSchemeAction::Query() const -{ - if (!LocationValid(_loc)) + RideSetColourSchemeAction::RideSetColourSchemeAction( + const CoordsXYZD& location, TrackElemType trackType, uint16_t newColourScheme) + : _loc(location) + , _trackType(trackType) + , _newColourScheme(newColourScheme) { - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_SET_COLOUR_SCHEME, STR_OFF_EDGE_OF_MAP); } - // Find the relevant track piece, prefer sequence 0 (logic copied from GetTrackElementOriginAndApplyChanges) - auto trackElement = MapGetTrackElementAtOfTypeSeq(_loc, _trackType, 0); - if (trackElement == nullptr) + + void RideSetColourSchemeAction::AcceptParameters(GameActionParameterVisitor& visitor) { - trackElement = MapGetTrackElementAtOfType(_loc, _trackType); + visitor.Visit(_loc); + visitor.Visit("trackType", _trackType); + visitor.Visit("colourScheme", _newColourScheme); + } + + uint16_t RideSetColourSchemeAction::GetActionFlags() const + { + return GameAction::GetActionFlags() | Flags::AllowWhilePaused; + } + + void RideSetColourSchemeAction::Serialise(DataSerialiser& stream) + { + GameAction::Serialise(stream); + + stream << DS_TAG(_loc) << DS_TAG(_trackType) << DS_TAG(_newColourScheme); + } + + Result RideSetColourSchemeAction::Query() const + { + if (!LocationValid(_loc)) + { + return Result(Status::InvalidParameters, STR_CANT_SET_COLOUR_SCHEME, STR_OFF_EDGE_OF_MAP); + } + // Find the relevant track piece, prefer sequence 0 (logic copied from GetTrackElementOriginAndApplyChanges) + auto trackElement = MapGetTrackElementAtOfTypeSeq(_loc, _trackType, 0); if (trackElement == nullptr) { - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_SET_COLOUR_SCHEME, STR_INVALID_TRACK_PARAMETERS); + trackElement = MapGetTrackElementAtOfType(_loc, _trackType); + if (trackElement == nullptr) + { + return Result(Status::InvalidParameters, STR_CANT_SET_COLOUR_SCHEME, STR_INVALID_TRACK_PARAMETERS); + } } + if (_newColourScheme >= kNumRideColourSchemes) + { + return Result(Status::InvalidParameters, STR_CANT_SET_COLOUR_SCHEME, STR_INVALID_COLOUR_SCHEME_PARAMETER); + } + return Result(); } - if (_newColourScheme >= kNumRideColourSchemes) + + Result RideSetColourSchemeAction::Execute() const { - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_SET_COLOUR_SCHEME, STR_INVALID_COLOUR_SCHEME_PARAMETER); + Result res = Result(); + res.Expenditure = ExpenditureType::rideConstruction; + res.ErrorTitle = STR_CANT_SET_COLOUR_SCHEME; + + GetTrackElementOriginAndApplyChanges( + _loc, _trackType, _newColourScheme, nullptr, { TrackElementSetFlag::colourScheme }); + + return res; } - return GameActions::Result(); -} - -GameActions::Result RideSetColourSchemeAction::Execute() const -{ - GameActions::Result res = GameActions::Result(); - res.Expenditure = ExpenditureType::rideConstruction; - res.ErrorTitle = STR_CANT_SET_COLOUR_SCHEME; - - GetTrackElementOriginAndApplyChanges(_loc, _trackType, _newColourScheme, nullptr, { TrackElementSetFlag::colourScheme }); - - return res; -} +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/RideSetColourSchemeAction.h b/src/openrct2/actions/RideSetColourSchemeAction.h index 770321ffa2..8995d1f531 100644 --- a/src/openrct2/actions/RideSetColourSchemeAction.h +++ b/src/openrct2/actions/RideSetColourSchemeAction.h @@ -11,22 +11,25 @@ #include "GameAction.h" -class RideSetColourSchemeAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - CoordsXYZD _loc; - OpenRCT2::TrackElemType _trackType{}; - uint16_t _newColourScheme{}; + class RideSetColourSchemeAction final : public GameActionBase + { + private: + CoordsXYZD _loc; + TrackElemType _trackType{}; + uint16_t _newColourScheme{}; -public: - RideSetColourSchemeAction() = default; - RideSetColourSchemeAction(const CoordsXYZD& location, OpenRCT2::TrackElemType trackType, uint16_t newColourScheme); + public: + RideSetColourSchemeAction() = default; + RideSetColourSchemeAction(const CoordsXYZD& location, TrackElemType trackType, uint16_t newColourScheme); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; -}; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/RideSetNameAction.cpp b/src/openrct2/actions/RideSetNameAction.cpp index 39b8b4f3ea..ced2f3727c 100644 --- a/src/openrct2/actions/RideSetNameAction.cpp +++ b/src/openrct2/actions/RideSetNameAction.cpp @@ -19,82 +19,80 @@ #include "../ui/WindowManager.h" #include "../world/Park.h" -using namespace OpenRCT2; - -RideSetNameAction::RideSetNameAction(RideId rideIndex, const std::string& name) - : _rideIndex(rideIndex) - , _name(name) +namespace OpenRCT2::GameActions { -} - -void RideSetNameAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit("ride", _rideIndex); - visitor.Visit("name", _name); -} - -uint16_t RideSetNameAction::GetActionFlags() const -{ - return GameAction::GetActionFlags() | GameActions::Flags::AllowWhilePaused; -} - -void RideSetNameAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_rideIndex) << DS_TAG(_name); -} - -GameActions::Result RideSetNameAction::Query() const -{ - auto ride = GetRide(_rideIndex); - if (ride == nullptr) + RideSetNameAction::RideSetNameAction(RideId rideIndex, const std::string& name) + : _rideIndex(rideIndex) + , _name(name) { - LOG_ERROR("Ride not found for rideIndex %u", _rideIndex.ToUnderlying()); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_RENAME_RIDE_ATTRACTION, STR_ERR_RIDE_NOT_FOUND); } - if (!_name.empty() && Ride::nameExists(_name, ride->id)) + void RideSetNameAction::AcceptParameters(GameActionParameterVisitor& visitor) { - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_RENAME_RIDE_ATTRACTION, STR_ERROR_EXISTING_NAME); + visitor.Visit("ride", _rideIndex); + visitor.Visit("name", _name); } - return GameActions::Result(); -} - -GameActions::Result RideSetNameAction::Execute() const -{ - auto ride = GetRide(_rideIndex); - if (ride == nullptr) + uint16_t RideSetNameAction::GetActionFlags() const { - LOG_ERROR("Ride not found for rideIndex %u", _rideIndex.ToUnderlying()); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_RENAME_RIDE_ATTRACTION, STR_ERR_RIDE_NOT_FOUND); + return GameAction::GetActionFlags() | Flags::AllowWhilePaused; } - if (_name.empty()) + void RideSetNameAction::Serialise(DataSerialiser& stream) { - ride->setNameToDefault(); - } - else - { - ride->customName = _name; + GameAction::Serialise(stream); + + stream << DS_TAG(_rideIndex) << DS_TAG(_name); } - ScrollingTextInvalidate(); - GfxInvalidateScreen(); + Result RideSetNameAction::Query() const + { + auto ride = GetRide(_rideIndex); + if (ride == nullptr) + { + LOG_ERROR("Ride not found for rideIndex %u", _rideIndex.ToUnderlying()); + return Result(Status::InvalidParameters, STR_CANT_RENAME_RIDE_ATTRACTION, STR_ERR_RIDE_NOT_FOUND); + } - // Refresh windows that display ride name - auto windowManager = OpenRCT2::Ui::GetWindowManager(); - windowManager->BroadcastIntent(Intent(INTENT_ACTION_REFRESH_CAMPAIGN_RIDE_LIST)); - windowManager->BroadcastIntent(Intent(INTENT_ACTION_REFRESH_RIDE_LIST)); - windowManager->BroadcastIntent(Intent(INTENT_ACTION_REFRESH_GUEST_LIST)); + if (!_name.empty() && Ride::nameExists(_name, ride->id)) + { + return Result(Status::InvalidParameters, STR_CANT_RENAME_RIDE_ATTRACTION, STR_ERROR_EXISTING_NAME); + } - auto res = GameActions::Result(); - auto location = ride->overallView.ToTileCentre(); - res.Position = { location, TileElementHeight(location) }; + return Result(); + } - return res; -} + Result RideSetNameAction::Execute() const + { + auto ride = GetRide(_rideIndex); + if (ride == nullptr) + { + LOG_ERROR("Ride not found for rideIndex %u", _rideIndex.ToUnderlying()); + return Result(Status::InvalidParameters, STR_CANT_RENAME_RIDE_ATTRACTION, STR_ERR_RIDE_NOT_FOUND); + } + + if (_name.empty()) + { + ride->setNameToDefault(); + } + else + { + ride->customName = _name; + } + + ScrollingTextInvalidate(); + GfxInvalidateScreen(); + + // Refresh windows that display ride name + auto windowManager = Ui::GetWindowManager(); + windowManager->BroadcastIntent(Intent(INTENT_ACTION_REFRESH_CAMPAIGN_RIDE_LIST)); + windowManager->BroadcastIntent(Intent(INTENT_ACTION_REFRESH_RIDE_LIST)); + windowManager->BroadcastIntent(Intent(INTENT_ACTION_REFRESH_GUEST_LIST)); + + auto res = Result(); + auto location = ride->overallView.ToTileCentre(); + res.Position = { location, TileElementHeight(location) }; + + return res; + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/RideSetNameAction.h b/src/openrct2/actions/RideSetNameAction.h index 6bf681b57f..1a4555a194 100644 --- a/src/openrct2/actions/RideSetNameAction.h +++ b/src/openrct2/actions/RideSetNameAction.h @@ -11,21 +11,24 @@ #include "GameAction.h" -class RideSetNameAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - RideId _rideIndex{ RideId::GetNull() }; - std::string _name; + class RideSetNameAction final : public GameActionBase + { + private: + RideId _rideIndex{ RideId::GetNull() }; + std::string _name; -public: - RideSetNameAction() = default; - RideSetNameAction(RideId rideIndex, const std::string& name); + public: + RideSetNameAction() = default; + RideSetNameAction(RideId rideIndex, const std::string& name); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; -}; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/RideSetPriceAction.cpp b/src/openrct2/actions/RideSetPriceAction.cpp index a395b20b98..cd63243820 100644 --- a/src/openrct2/actions/RideSetPriceAction.cpp +++ b/src/openrct2/actions/RideSetPriceAction.cpp @@ -21,186 +21,185 @@ #include "../ui/WindowManager.h" #include "../world/Park.h" -using namespace OpenRCT2; - -RideSetPriceAction::RideSetPriceAction(RideId rideIndex, money64 price, bool primaryPrice) - : _rideIndex(rideIndex) - , _price(price) - , _primaryPrice(primaryPrice) +namespace OpenRCT2::GameActions { -} - -void RideSetPriceAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit("ride", _rideIndex); - visitor.Visit("price", _price); - visitor.Visit("isPrimaryPrice", _primaryPrice); -} - -uint16_t RideSetPriceAction::GetActionFlags() const -{ - return GameAction::GetActionFlags() | GameActions::Flags::AllowWhilePaused; -} - -void RideSetPriceAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_rideIndex) << DS_TAG(_price) << DS_TAG(_primaryPrice); -} - -GameActions::Result RideSetPriceAction::Query() const -{ - auto ride = GetRide(_rideIndex); - if (ride == nullptr) + RideSetPriceAction::RideSetPriceAction(RideId rideIndex, money64 price, bool primaryPrice) + : _rideIndex(rideIndex) + , _price(price) + , _primaryPrice(primaryPrice) { - LOG_ERROR("Ride not found for rideIndex %u", _rideIndex.ToUnderlying()); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_RIDE_NOT_FOUND); } - const auto* rideEntry = GetRideEntryByIndex(ride->subtype); - if (rideEntry == nullptr) + void RideSetPriceAction::AcceptParameters(GameActionParameterVisitor& visitor) { - LOG_ERROR("Ride entry not found for ride subtype %u", ride->subtype); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_RIDE_OBJECT_ENTRY_NOT_FOUND); + visitor.Visit("ride", _rideIndex); + visitor.Visit("price", _price); + visitor.Visit("isPrimaryPrice", _primaryPrice); } - if (_price < kRideMinPrice || _price > kRideMaxPrice) + uint16_t RideSetPriceAction::GetActionFlags() const { - LOG_ERROR("Attempting to set an invalid price for rideIndex %u", _rideIndex.ToUnderlying()); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, kStringIdEmpty); + return GameAction::GetActionFlags() | Flags::AllowWhilePaused; } - return GameActions::Result(); -} - -GameActions::Result RideSetPriceAction::Execute() const -{ - GameActions::Result res = GameActions::Result(); - res.Expenditure = ExpenditureType::parkRideTickets; - - auto ride = GetRide(_rideIndex); - if (ride == nullptr) + void RideSetPriceAction::Serialise(DataSerialiser& stream) { - LOG_ERROR("Ride not found for rideIndex %u", _rideIndex.ToUnderlying()); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_RIDE_NOT_FOUND); + GameAction::Serialise(stream); + + stream << DS_TAG(_rideIndex) << DS_TAG(_price) << DS_TAG(_primaryPrice); } - const auto* rideEntry = GetRideEntryByIndex(ride->subtype); - if (rideEntry == nullptr) + Result RideSetPriceAction::Query() const { - LOG_ERROR("Ride entry not found for ride subtype %u", ride->subtype); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_RIDE_OBJECT_ENTRY_NOT_FOUND); - } - - if (_price < kRideMinPrice || _price > kRideMaxPrice) - { - LOG_ERROR("Attempting to set an invalid price for rideIndex %u", _rideIndex.ToUnderlying()); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, kStringIdEmpty); - } - - if (!ride->overallView.IsNull()) - { - auto location = ride->overallView.ToTileCentre(); - res.Position = { location, TileElementHeight(location) }; - } - - auto* windowMgr = Ui::GetWindowManager(); - - ShopItem shopItem; - if (_primaryPrice) - { - shopItem = ShopItem::Admission; - - const auto& rtd = ride->getRideTypeDescriptor(); - if (rtd.specialType != RtdSpecialType::toilet) + auto ride = GetRide(_rideIndex); + if (ride == nullptr) { - shopItem = rideEntry->shop_item[0]; - if (shopItem == ShopItem::None) + LOG_ERROR("Ride not found for rideIndex %u", _rideIndex.ToUnderlying()); + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_RIDE_NOT_FOUND); + } + + const auto* rideEntry = GetRideEntryByIndex(ride->subtype); + if (rideEntry == nullptr) + { + LOG_ERROR("Ride entry not found for ride subtype %u", ride->subtype); + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_RIDE_OBJECT_ENTRY_NOT_FOUND); + } + + if (_price < kRideMinPrice || _price > kRideMaxPrice) + { + LOG_ERROR("Attempting to set an invalid price for rideIndex %u", _rideIndex.ToUnderlying()); + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, kStringIdEmpty); + } + + return Result(); + } + + Result RideSetPriceAction::Execute() const + { + Result res = Result(); + res.Expenditure = ExpenditureType::parkRideTickets; + + auto ride = GetRide(_rideIndex); + if (ride == nullptr) + { + LOG_ERROR("Ride not found for rideIndex %u", _rideIndex.ToUnderlying()); + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_RIDE_NOT_FOUND); + } + + const auto* rideEntry = GetRideEntryByIndex(ride->subtype); + if (rideEntry == nullptr) + { + LOG_ERROR("Ride entry not found for ride subtype %u", ride->subtype); + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_RIDE_OBJECT_ENTRY_NOT_FOUND); + } + + if (_price < kRideMinPrice || _price > kRideMaxPrice) + { + LOG_ERROR("Attempting to set an invalid price for rideIndex %u", _rideIndex.ToUnderlying()); + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, kStringIdEmpty); + } + + if (!ride->overallView.IsNull()) + { + auto location = ride->overallView.ToTileCentre(); + res.Position = { location, TileElementHeight(location) }; + } + + auto* windowMgr = Ui::GetWindowManager(); + + ShopItem shopItem; + if (_primaryPrice) + { + shopItem = ShopItem::Admission; + + const auto& rtd = ride->getRideTypeDescriptor(); + if (rtd.specialType != RtdSpecialType::toilet) + { + shopItem = rideEntry->shop_item[0]; + if (shopItem == ShopItem::None) + { + ride->price[0] = _price; + windowMgr->InvalidateByClass(WindowClass::Ride); + return res; + } + } + // Check same price in park flags + if (!ShopItemHasCommonPrice(shopItem)) { ride->price[0] = _price; windowMgr->InvalidateByClass(WindowClass::Ride); return res; } } - // Check same price in park flags - if (!ShopItemHasCommonPrice(shopItem)) + else { - ride->price[0] = _price; - windowMgr->InvalidateByClass(WindowClass::Ride); - return res; - } - } - else - { - shopItem = rideEntry->shop_item[1]; - if (shopItem == ShopItem::None) - { - shopItem = ride->getRideTypeDescriptor().PhotoItem; - if ((ride->lifecycleFlags & RIDE_LIFECYCLE_ON_RIDE_PHOTO) == 0) + shopItem = rideEntry->shop_item[1]; + if (shopItem == ShopItem::None) + { + shopItem = ride->getRideTypeDescriptor().PhotoItem; + if ((ride->lifecycleFlags & RIDE_LIFECYCLE_ON_RIDE_PHOTO) == 0) + { + ride->price[1] = _price; + windowMgr->InvalidateByClass(WindowClass::Ride); + return res; + } + } + // Check same price in park flags + if (!ShopItemHasCommonPrice(shopItem)) { ride->price[1] = _price; windowMgr->InvalidateByClass(WindowClass::Ride); return res; } } - // Check same price in park flags - if (!ShopItemHasCommonPrice(shopItem)) - { - ride->price[1] = _price; - windowMgr->InvalidateByClass(WindowClass::Ride); - return res; - } + + // Synchronize prices if enabled. + RideSetCommonPrice(shopItem); + + return res; } - // Synchronize prices if enabled. - RideSetCommonPrice(shopItem); - - return res; -} - -void RideSetPriceAction::RideSetCommonPrice(ShopItem shopItem) const -{ - for (auto& ride : GetRideManager()) + void RideSetPriceAction::RideSetCommonPrice(ShopItem shopItem) const { - auto invalidate = false; - auto rideEntry = GetRideEntryByIndex(ride.subtype); - const auto& rtd = ride.getRideTypeDescriptor(); - if (rtd.specialType == RtdSpecialType::toilet && shopItem == ShopItem::Admission) + for (auto& ride : GetRideManager()) { - if (ride.price[0] != _price) + auto invalidate = false; + auto rideEntry = GetRideEntryByIndex(ride.subtype); + const auto& rtd = ride.getRideTypeDescriptor(); + if (rtd.specialType == RtdSpecialType::toilet && shopItem == ShopItem::Admission) { - ride.price[0] = _price; - invalidate = true; - } - } - else if (rideEntry != nullptr && rideEntry->shop_item[0] == shopItem) - { - if (ride.price[0] != _price) - { - ride.price[0] = _price; - invalidate = true; - } - } - if (rideEntry != nullptr) - { - // If the shop item is the same or an on-ride photo - if (rideEntry->shop_item[1] == shopItem - || (rideEntry->shop_item[1] == ShopItem::None && GetShopItemDescriptor(shopItem).IsPhoto())) - { - if (ride.price[1] != _price) + if (ride.price[0] != _price) { - ride.price[1] = _price; + ride.price[0] = _price; invalidate = true; } } - } - if (invalidate) - { - auto* windowMgr = Ui::GetWindowManager(); - windowMgr->InvalidateByNumber(WindowClass::Ride, ride.id.ToUnderlying()); + else if (rideEntry != nullptr && rideEntry->shop_item[0] == shopItem) + { + if (ride.price[0] != _price) + { + ride.price[0] = _price; + invalidate = true; + } + } + if (rideEntry != nullptr) + { + // If the shop item is the same or an on-ride photo + if (rideEntry->shop_item[1] == shopItem + || (rideEntry->shop_item[1] == ShopItem::None && GetShopItemDescriptor(shopItem).IsPhoto())) + { + if (ride.price[1] != _price) + { + ride.price[1] = _price; + invalidate = true; + } + } + } + if (invalidate) + { + auto* windowMgr = Ui::GetWindowManager(); + windowMgr->InvalidateByNumber(WindowClass::Ride, ride.id.ToUnderlying()); + } } } -} +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/RideSetPriceAction.h b/src/openrct2/actions/RideSetPriceAction.h index 6825946b7a..e8d8f89d93 100644 --- a/src/openrct2/actions/RideSetPriceAction.h +++ b/src/openrct2/actions/RideSetPriceAction.h @@ -11,25 +11,28 @@ #include "GameAction.h" -class RideSetPriceAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - RideId _rideIndex{ RideId::GetNull() }; - money64 _price{ kMoney64Undefined }; - bool _primaryPrice{ true }; + class RideSetPriceAction final : public GameActionBase + { + private: + RideId _rideIndex{ RideId::GetNull() }; + money64 _price{ kMoney64Undefined }; + bool _primaryPrice{ true }; -public: - RideSetPriceAction() = default; - RideSetPriceAction(RideId rideIndex, money64 price, bool primaryPrice); + public: + RideSetPriceAction() = default; + RideSetPriceAction(RideId rideIndex, money64 price, bool primaryPrice); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; -private: - void RideSetCommonPrice(ShopItem shopItem) const; -}; + private: + void RideSetCommonPrice(ShopItem shopItem) const; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/RideSetSettingAction.cpp b/src/openrct2/actions/RideSetSettingAction.cpp index 905841afed..f322b70f78 100644 --- a/src/openrct2/actions/RideSetSettingAction.cpp +++ b/src/openrct2/actions/RideSetSettingAction.cpp @@ -17,301 +17,289 @@ #include "../ride/RideData.h" #include "../ui/WindowManager.h" -using namespace OpenRCT2; - -RideSetSettingAction::RideSetSettingAction(RideId rideIndex, RideSetSetting setting, uint8_t value) - : _rideIndex(rideIndex) - , _setting(setting) - , _value(value) +namespace OpenRCT2::GameActions { -} - -void RideSetSettingAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit("ride", _rideIndex); - visitor.Visit("setting", _setting); - visitor.Visit("value", _value); -} - -uint16_t RideSetSettingAction::GetActionFlags() const -{ - return GameAction::GetActionFlags() | GameActions::Flags::AllowWhilePaused; -} - -void RideSetSettingAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_rideIndex) << DS_TAG(_setting) << DS_TAG(_value); -} - -GameActions::Result RideSetSettingAction::Query() const -{ - auto ride = GetRide(_rideIndex); - if (ride == nullptr) + RideSetSettingAction::RideSetSettingAction(RideId rideIndex, RideSetSetting setting, uint8_t value) + : _rideIndex(rideIndex) + , _setting(setting) + , _value(value) { - LOG_ERROR("Ride not found for rideIndex %u.", _rideIndex.ToUnderlying()); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_CHANGE_OPERATING_MODE, STR_ERR_RIDE_NOT_FOUND); } - switch (_setting) + void RideSetSettingAction::AcceptParameters(GameActionParameterVisitor& visitor) { - case RideSetSetting::Mode: - if (ride->lifecycleFlags & RIDE_LIFECYCLE_BROKEN_DOWN) - { - return GameActions::Result( - GameActions::Status::Disallowed, STR_CANT_CHANGE_OPERATING_MODE, STR_HAS_BROKEN_DOWN_AND_REQUIRES_FIXING); - } + visitor.Visit("ride", _rideIndex); + visitor.Visit("setting", _setting); + visitor.Visit("value", _value); + } - if (ride->status != RideStatus::closed && ride->status != RideStatus::simulating) - { - return GameActions::Result( - GameActions::Status::Disallowed, STR_CANT_CHANGE_OPERATING_MODE, STR_MUST_BE_CLOSED_FIRST); - } + uint16_t RideSetSettingAction::GetActionFlags() const + { + return GameAction::GetActionFlags() | Flags::AllowWhilePaused; + } - if (!RideIsModeValid(*ride) && !getGameState().cheats.showAllOperatingModes) - { - LOG_ERROR("Invalid ride mode: %u", _value); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_CHANGE_OPERATING_MODE, STR_ERR_VALUE_OUT_OF_RANGE); - } - break; - case RideSetSetting::Departure: - break; - case RideSetSetting::MinWaitingTime: - if (_value > 250) - { - LOG_ERROR("Invalid minimum waiting time: %u", _value); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_CHANGE_OPERATING_MODE, STR_ERR_VALUE_OUT_OF_RANGE); - } - break; - case RideSetSetting::MaxWaitingTime: - if (_value > 250) - { - LOG_ERROR("Invalid maximum waiting time: %u", _value); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_CHANGE_OPERATING_MODE, STR_ERR_VALUE_OUT_OF_RANGE); - } - break; - case RideSetSetting::Operation: - if (!RideIsValidOperationOption(*ride)) - { - LOG_ERROR("Invalid operation option value: %u", _value); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_CHANGE_OPERATING_MODE, GetOperationErrorMessage(*ride)); - } - break; - case RideSetSetting::InspectionInterval: - if (_value > RIDE_INSPECTION_NEVER) - { - LOG_ERROR("Invalid inspection interval: %u", _value); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_CHANGE_OPERATING_MODE, STR_ERR_VALUE_OUT_OF_RANGE); - } - break; - case RideSetSetting::Music: - break; - case RideSetSetting::MusicType: + void RideSetSettingAction::Serialise(DataSerialiser& stream) + { + GameAction::Serialise(stream); + + stream << DS_TAG(_rideIndex) << DS_TAG(_setting) << DS_TAG(_value); + } + + Result RideSetSettingAction::Query() const + { + auto ride = GetRide(_rideIndex); + if (ride == nullptr) { - auto& objManager = GetContext()->GetObjectManager(); - auto musicObj = objManager.GetLoadedObject(_value); - if (musicObj == nullptr) - { - LOG_ERROR("Invalid music style: %u", _value); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_CHANGE_OPERATING_MODE, STR_ERR_VALUE_OUT_OF_RANGE); - } - break; + LOG_ERROR("Ride not found for rideIndex %u.", _rideIndex.ToUnderlying()); + return Result(Status::InvalidParameters, STR_CANT_CHANGE_OPERATING_MODE, STR_ERR_RIDE_NOT_FOUND); } - case RideSetSetting::LiftHillSpeed: - if (!RideIsValidLiftHillSpeed(*ride)) - { - LOG_ERROR("Invalid lift hill speed: %u", _value); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_CHANGE_OPERATING_MODE, STR_ERR_VALUE_OUT_OF_RANGE); - } - break; - case RideSetSetting::NumCircuits: - if (ride->lifecycleFlags & RIDE_LIFECYCLE_CABLE_LIFT && _value > 1) - { - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_CHANGE_OPERATING_MODE, - STR_MULTICIRCUIT_NOT_POSSIBLE_WITH_CABLE_LIFT_HILL); - } - if (!RideIsValidNumCircuits()) + switch (_setting) + { + case RideSetSetting::Mode: + if (ride->lifecycleFlags & RIDE_LIFECYCLE_BROKEN_DOWN) + { + return Result(Status::Disallowed, STR_CANT_CHANGE_OPERATING_MODE, STR_HAS_BROKEN_DOWN_AND_REQUIRES_FIXING); + } + + if (ride->status != RideStatus::closed && ride->status != RideStatus::simulating) + { + return Result(Status::Disallowed, STR_CANT_CHANGE_OPERATING_MODE, STR_MUST_BE_CLOSED_FIRST); + } + + if (!RideIsModeValid(*ride) && !getGameState().cheats.showAllOperatingModes) + { + LOG_ERROR("Invalid ride mode: %u", _value); + return Result(Status::InvalidParameters, STR_CANT_CHANGE_OPERATING_MODE, STR_ERR_VALUE_OUT_OF_RANGE); + } + break; + case RideSetSetting::Departure: + break; + case RideSetSetting::MinWaitingTime: + if (_value > 250) + { + LOG_ERROR("Invalid minimum waiting time: %u", _value); + return Result(Status::InvalidParameters, STR_CANT_CHANGE_OPERATING_MODE, STR_ERR_VALUE_OUT_OF_RANGE); + } + break; + case RideSetSetting::MaxWaitingTime: + if (_value > 250) + { + LOG_ERROR("Invalid maximum waiting time: %u", _value); + return Result(Status::InvalidParameters, STR_CANT_CHANGE_OPERATING_MODE, STR_ERR_VALUE_OUT_OF_RANGE); + } + break; + case RideSetSetting::Operation: + if (!RideIsValidOperationOption(*ride)) + { + LOG_ERROR("Invalid operation option value: %u", _value); + return Result(Status::InvalidParameters, STR_CANT_CHANGE_OPERATING_MODE, GetOperationErrorMessage(*ride)); + } + break; + case RideSetSetting::InspectionInterval: + if (_value > RIDE_INSPECTION_NEVER) + { + LOG_ERROR("Invalid inspection interval: %u", _value); + return Result(Status::InvalidParameters, STR_CANT_CHANGE_OPERATING_MODE, STR_ERR_VALUE_OUT_OF_RANGE); + } + break; + case RideSetSetting::Music: + break; + case RideSetSetting::MusicType: { - LOG_ERROR("Invalid number of circuits: %u", _value); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_CHANGE_OPERATING_MODE, STR_ERR_VALUE_OUT_OF_RANGE); + auto& objManager = GetContext()->GetObjectManager(); + auto musicObj = objManager.GetLoadedObject(_value); + if (musicObj == nullptr) + { + LOG_ERROR("Invalid music style: %u", _value); + return Result(Status::InvalidParameters, STR_CANT_CHANGE_OPERATING_MODE, STR_ERR_VALUE_OUT_OF_RANGE); + } + break; } - break; - case RideSetSetting::RideType: - if (!getGameState().cheats.allowArbitraryRideTypeChanges) - { - LOG_ERROR("Arbitrary ride type changes not allowed."); - return GameActions::Result(GameActions::Status::Disallowed, STR_CANT_CHANGE_OPERATING_MODE, kStringIdNone); - } - break; - default: - LOG_ERROR("Invalid ride setting %u", static_cast(_setting)); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_CHANGE_OPERATING_MODE, STR_ERR_VALUE_OUT_OF_RANGE); + case RideSetSetting::LiftHillSpeed: + if (!RideIsValidLiftHillSpeed(*ride)) + { + LOG_ERROR("Invalid lift hill speed: %u", _value); + return Result(Status::InvalidParameters, STR_CANT_CHANGE_OPERATING_MODE, STR_ERR_VALUE_OUT_OF_RANGE); + } + break; + case RideSetSetting::NumCircuits: + if (ride->lifecycleFlags & RIDE_LIFECYCLE_CABLE_LIFT && _value > 1) + { + return Result( + Status::InvalidParameters, STR_CANT_CHANGE_OPERATING_MODE, + STR_MULTICIRCUIT_NOT_POSSIBLE_WITH_CABLE_LIFT_HILL); + } + + if (!RideIsValidNumCircuits()) + { + LOG_ERROR("Invalid number of circuits: %u", _value); + return Result(Status::InvalidParameters, STR_CANT_CHANGE_OPERATING_MODE, STR_ERR_VALUE_OUT_OF_RANGE); + } + break; + case RideSetSetting::RideType: + if (!getGameState().cheats.allowArbitraryRideTypeChanges) + { + LOG_ERROR("Arbitrary ride type changes not allowed."); + return Result(Status::Disallowed, STR_CANT_CHANGE_OPERATING_MODE, kStringIdNone); + } + break; + default: + LOG_ERROR("Invalid ride setting %u", static_cast(_setting)); + return Result(Status::InvalidParameters, STR_CANT_CHANGE_OPERATING_MODE, STR_ERR_VALUE_OUT_OF_RANGE); + } + + return Result(); } - return GameActions::Result(); -} - -GameActions::Result RideSetSettingAction::Execute() const -{ - auto ride = GetRide(_rideIndex); - if (ride == nullptr) + Result RideSetSettingAction::Execute() const { - LOG_ERROR("Ride not found for rideIndex %u", _rideIndex.ToUnderlying()); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_CHANGE_OPERATING_MODE, STR_ERR_RIDE_NOT_FOUND); - } + auto ride = GetRide(_rideIndex); + if (ride == nullptr) + { + LOG_ERROR("Ride not found for rideIndex %u", _rideIndex.ToUnderlying()); + return Result(Status::InvalidParameters, STR_CANT_CHANGE_OPERATING_MODE, STR_ERR_RIDE_NOT_FOUND); + } - switch (_setting) - { - case RideSetSetting::Mode: - InvalidateTestResults(*ride); - RideClearForConstruction(*ride); - ride->removePeeps(); - - ride->mode = static_cast(_value); - ride->updateMaxVehicles(); - ride->updateNumberOfCircuits(); - break; - case RideSetSetting::Departure: - ride->departFlags = _value; - break; - case RideSetSetting::MinWaitingTime: - ride->minWaitingTime = _value; - ride->maxWaitingTime = std::max(_value, ride->maxWaitingTime); - break; - case RideSetSetting::MaxWaitingTime: - ride->maxWaitingTime = _value; - ride->minWaitingTime = std::min(_value, ride->minWaitingTime); - break; - case RideSetSetting::Operation: - InvalidateTestResults(*ride); - ride->operationOption = _value; - break; - case RideSetSetting::InspectionInterval: - - if (_value == RIDE_INSPECTION_NEVER) - { - ride->lifecycleFlags &= ~RIDE_LIFECYCLE_DUE_INSPECTION; - } - - ride->inspectionInterval = _value; - break; - case RideSetSetting::Music: - ride->lifecycleFlags &= ~RIDE_LIFECYCLE_MUSIC; - if (_value) - { - ride->lifecycleFlags |= RIDE_LIFECYCLE_MUSIC; - } - ride->windowInvalidateFlags |= RIDE_INVALIDATE_RIDE_MUSIC; - break; - case RideSetSetting::MusicType: - if (_value != ride->music) - { - ride->music = _value; - ride->musicTuneId = kTuneIDNull; - } - break; - case RideSetSetting::LiftHillSpeed: - if (_value != ride->liftHillSpeed) - { - ride->liftHillSpeed = _value; + switch (_setting) + { + case RideSetSetting::Mode: InvalidateTestResults(*ride); - } - break; - case RideSetSetting::NumCircuits: - if (_value != ride->numCircuits) - { - ride->numCircuits = _value; + RideClearForConstruction(*ride); + ride->removePeeps(); + + ride->mode = static_cast(_value); + ride->updateMaxVehicles(); + ride->updateNumberOfCircuits(); + break; + case RideSetSetting::Departure: + ride->departFlags = _value; + break; + case RideSetSetting::MinWaitingTime: + ride->minWaitingTime = _value; + ride->maxWaitingTime = std::max(_value, ride->maxWaitingTime); + break; + case RideSetSetting::MaxWaitingTime: + ride->maxWaitingTime = _value; + ride->minWaitingTime = std::min(_value, ride->minWaitingTime); + break; + case RideSetSetting::Operation: InvalidateTestResults(*ride); - } + ride->operationOption = _value; + break; + case RideSetSetting::InspectionInterval: - break; - case RideSetSetting::RideType: - ride->type = _value; - ride->updateRideTypeForAllPieces(); - GfxInvalidateScreen(); - break; + if (_value == RIDE_INSPECTION_NEVER) + { + ride->lifecycleFlags &= ~RIDE_LIFECYCLE_DUE_INSPECTION; + } + + ride->inspectionInterval = _value; + break; + case RideSetSetting::Music: + ride->lifecycleFlags &= ~RIDE_LIFECYCLE_MUSIC; + if (_value) + { + ride->lifecycleFlags |= RIDE_LIFECYCLE_MUSIC; + } + ride->windowInvalidateFlags |= RIDE_INVALIDATE_RIDE_MUSIC; + break; + case RideSetSetting::MusicType: + if (_value != ride->music) + { + ride->music = _value; + ride->musicTuneId = kTuneIDNull; + } + break; + case RideSetSetting::LiftHillSpeed: + if (_value != ride->liftHillSpeed) + { + ride->liftHillSpeed = _value; + InvalidateTestResults(*ride); + } + break; + case RideSetSetting::NumCircuits: + if (_value != ride->numCircuits) + { + ride->numCircuits = _value; + InvalidateTestResults(*ride); + } + + break; + case RideSetSetting::RideType: + ride->type = _value; + ride->updateRideTypeForAllPieces(); + GfxInvalidateScreen(); + break; + } + + auto res = Result(); + if (!ride->overallView.IsNull()) + { + auto location = ride->overallView.ToTileCentre(); + res.Position = { location, TileElementHeight(location) }; + } + auto* windowMgr = Ui::GetWindowManager(); + windowMgr->InvalidateByNumber(WindowClass::Ride, _rideIndex.ToUnderlying()); + return res; } - auto res = GameActions::Result(); - if (!ride->overallView.IsNull()) + bool RideSetSettingAction::RideIsModeValid(const Ride& ride) const { - auto location = ride->overallView.ToTileCentre(); - res.Position = { location, TileElementHeight(location) }; + return ride.getRideTypeDescriptor().RideModes & (1uLL << _value); } - auto* windowMgr = Ui::GetWindowManager(); - windowMgr->InvalidateByNumber(WindowClass::Ride, _rideIndex.ToUnderlying()); - return res; -} -bool RideSetSettingAction::RideIsModeValid(const Ride& ride) const -{ - return ride.getRideTypeDescriptor().RideModes & (1uLL << _value); -} - -bool RideSetSettingAction::RideIsValidLiftHillSpeed(const Ride& ride) const -{ - auto& gameState = getGameState(); - int32_t minSpeed = gameState.cheats.unlockOperatingLimits ? 0 : ride.getRideTypeDescriptor().LiftData.minimum_speed; - int32_t maxSpeed = gameState.cheats.unlockOperatingLimits ? 255 : ride.getRideTypeDescriptor().LiftData.maximum_speed; - return _value >= minSpeed && _value <= maxSpeed; -} - -bool RideSetSettingAction::RideIsValidNumCircuits() const -{ - int32_t minNumCircuits = 1; - int32_t maxNumCircuits = getGameState().cheats.unlockOperatingLimits ? 255 : Limits::kMaxCircuitsPerRide; - return _value >= minNumCircuits && _value <= maxNumCircuits; -} - -bool RideSetSettingAction::RideIsValidOperationOption(const Ride& ride) const -{ - const auto& operatingSettings = ride.getRideTypeDescriptor().OperatingSettings; - uint8_t minValue = operatingSettings.MinValue; - uint8_t maxValue = operatingSettings.MaxValue; - if (getGameState().cheats.unlockOperatingLimits) + bool RideSetSettingAction::RideIsValidLiftHillSpeed(const Ride& ride) const { - minValue = 0; - maxValue = 255; + auto& gameState = getGameState(); + int32_t minSpeed = gameState.cheats.unlockOperatingLimits ? 0 : ride.getRideTypeDescriptor().LiftData.minimum_speed; + int32_t maxSpeed = gameState.cheats.unlockOperatingLimits ? 255 : ride.getRideTypeDescriptor().LiftData.maximum_speed; + return _value >= minSpeed && _value <= maxSpeed; } - return _value >= minValue && _value <= maxValue; -} - -StringId RideSetSettingAction::GetOperationErrorMessage(const Ride& ride) const -{ - switch (ride.mode) + bool RideSetSettingAction::RideIsValidNumCircuits() const { - case RideMode::stationToStation: - return STR_CANT_CHANGE_SPEED; - case RideMode::race: - return STR_CANT_CHANGE_NUMBER_OF_LAPS; - case RideMode::dodgems: - return STR_CANT_CHANGE_TIME_LIMIT; - case RideMode::swing: - return STR_CANT_CHANGE_NUMBER_OF_SWINGS; - case RideMode::rotation: - case RideMode::forwardRotation: - case RideMode::backwardRotation: - return STR_CANT_CHANGE_NUMBER_OF_ROTATIONS; - default: - if (ride.getRideTypeDescriptor().HasFlag(RtdFlag::noVehicles)) - { - return STR_CANT_CHANGE_THIS; - } - return STR_CANT_CHANGE_LAUNCH_SPEED; + int32_t minNumCircuits = 1; + int32_t maxNumCircuits = getGameState().cheats.unlockOperatingLimits ? 255 : Limits::kMaxCircuitsPerRide; + return _value >= minNumCircuits && _value <= maxNumCircuits; } -} + + bool RideSetSettingAction::RideIsValidOperationOption(const Ride& ride) const + { + const auto& operatingSettings = ride.getRideTypeDescriptor().OperatingSettings; + uint8_t minValue = operatingSettings.MinValue; + uint8_t maxValue = operatingSettings.MaxValue; + if (getGameState().cheats.unlockOperatingLimits) + { + minValue = 0; + maxValue = 255; + } + + return _value >= minValue && _value <= maxValue; + } + + StringId RideSetSettingAction::GetOperationErrorMessage(const Ride& ride) const + { + switch (ride.mode) + { + case RideMode::stationToStation: + return STR_CANT_CHANGE_SPEED; + case RideMode::race: + return STR_CANT_CHANGE_NUMBER_OF_LAPS; + case RideMode::dodgems: + return STR_CANT_CHANGE_TIME_LIMIT; + case RideMode::swing: + return STR_CANT_CHANGE_NUMBER_OF_SWINGS; + case RideMode::rotation: + case RideMode::forwardRotation: + case RideMode::backwardRotation: + return STR_CANT_CHANGE_NUMBER_OF_ROTATIONS; + default: + if (ride.getRideTypeDescriptor().HasFlag(RtdFlag::noVehicles)) + { + return STR_CANT_CHANGE_THIS; + } + return STR_CANT_CHANGE_LAUNCH_SPEED; + } + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/RideSetSettingAction.h b/src/openrct2/actions/RideSetSettingAction.h index d13e55f9de..5933b33624 100644 --- a/src/openrct2/actions/RideSetSettingAction.h +++ b/src/openrct2/actions/RideSetSettingAction.h @@ -11,44 +11,47 @@ #include "GameAction.h" -enum class RideSetSetting : uint8_t +namespace OpenRCT2::GameActions { - Mode, - Departure, - MinWaitingTime, - MaxWaitingTime, - Operation, - InspectionInterval, - Music, - MusicType, - LiftHillSpeed, - NumCircuits, - RideType, -}; + enum class RideSetSetting : uint8_t + { + Mode, + Departure, + MinWaitingTime, + MaxWaitingTime, + Operation, + InspectionInterval, + Music, + MusicType, + LiftHillSpeed, + NumCircuits, + RideType, + }; -class RideSetSettingAction final : public GameActionBase -{ -private: - RideId _rideIndex{ RideId::GetNull() }; - RideSetSetting _setting{}; - uint8_t _value{}; + class RideSetSettingAction final : public GameActionBase + { + private: + RideId _rideIndex{ RideId::GetNull() }; + RideSetSetting _setting{}; + uint8_t _value{}; -public: - RideSetSettingAction() = default; - RideSetSettingAction(RideId rideIndex, RideSetSetting setting, uint8_t value); + public: + RideSetSettingAction() = default; + RideSetSettingAction(RideId rideIndex, RideSetSetting setting, uint8_t value); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; -private: - bool RideIsModeValid(const Ride& ride) const; - bool RideIsValidLiftHillSpeed(const Ride& ride) const; - bool RideIsValidNumCircuits() const; - bool RideIsValidOperationOption(const Ride& ride) const; - StringId GetOperationErrorMessage(const Ride& ride) const; -}; + private: + bool RideIsModeValid(const Ride& ride) const; + bool RideIsValidLiftHillSpeed(const Ride& ride) const; + bool RideIsValidNumCircuits() const; + bool RideIsValidOperationOption(const Ride& ride) const; + StringId GetOperationErrorMessage(const Ride& ride) const; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/RideSetStatusAction.cpp b/src/openrct2/actions/RideSetStatusAction.cpp index e80e0f22b5..1823a7512b 100644 --- a/src/openrct2/actions/RideSetStatusAction.cpp +++ b/src/openrct2/actions/RideSetStatusAction.cpp @@ -19,231 +19,233 @@ #include "../ui/WindowManager.h" #include "../world/Park.h" -using namespace OpenRCT2; - -static StringId _StatusErrorTitles[] = { - STR_CANT_CLOSE, - STR_CANT_OPEN, - STR_CANT_TEST, - STR_CANT_SIMULATE, -}; - -RideSetStatusAction::RideSetStatusAction(RideId rideIndex, RideStatus status) - : _rideIndex(rideIndex) - , _status(status) +namespace OpenRCT2::GameActions { -} + static StringId _StatusErrorTitles[] = { + STR_CANT_CLOSE, + STR_CANT_OPEN, + STR_CANT_TEST, + STR_CANT_SIMULATE, + }; -void RideSetStatusAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit("ride", _rideIndex); - visitor.Visit("status", _status); -} - -uint16_t RideSetStatusAction::GetActionFlags() const -{ - return GameAction::GetActionFlags() | GameActions::Flags::AllowWhilePaused; -} - -void RideSetStatusAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_rideIndex) << DS_TAG(_status); -} - -GameActions::Result RideSetStatusAction::Query() const -{ - GameActions::Result res = GameActions::Result(); - - auto ride = GetRide(_rideIndex); - if (ride == nullptr) + RideSetStatusAction::RideSetStatusAction(RideId rideIndex, RideStatus status) + : _rideIndex(rideIndex) + , _status(status) { - LOG_ERROR("Ride not found for rideIndex %u", _rideIndex.ToUnderlying()); - res.Error = GameActions::Status::InvalidParameters; - res.ErrorTitle = STR_RIDE_DESCRIPTION_UNKNOWN; - res.ErrorMessage = STR_ERR_RIDE_NOT_FOUND; - return res; } - if (_status >= RideStatus::count) + void RideSetStatusAction::AcceptParameters(GameActionParameterVisitor& visitor) { - LOG_ERROR("Invalid ride status %u for ride %u", EnumValue(_status), _rideIndex.ToUnderlying()); - res.Error = GameActions::Status::InvalidParameters; - res.ErrorTitle = STR_RIDE_DESCRIPTION_UNKNOWN; - res.ErrorMessage = kStringIdNone; - return res; + visitor.Visit("ride", _rideIndex); + visitor.Visit("status", _status); } - res.ErrorTitle = _StatusErrorTitles[EnumValue(_status)]; - - Formatter ft(res.ErrorMessageArgs.data()); - ride->formatNameTo(ft); - if (_status != ride->status) + uint16_t RideSetStatusAction::GetActionFlags() const { - if (_status == RideStatus::simulating && (ride->lifecycleFlags & RIDE_LIFECYCLE_BROKEN_DOWN)) + return GameAction::GetActionFlags() | Flags::AllowWhilePaused; + } + + void RideSetStatusAction::Serialise(DataSerialiser& stream) + { + GameAction::Serialise(stream); + + stream << DS_TAG(_rideIndex) << DS_TAG(_status); + } + + Result RideSetStatusAction::Query() const + { + Result res = Result(); + + auto ride = GetRide(_rideIndex); + if (ride == nullptr) { - // Simulating will force clear the track, so make sure player can't cheat around a break down - res.Error = GameActions::Status::Disallowed; - res.ErrorMessage = STR_HAS_BROKEN_DOWN_AND_REQUIRES_FIXING; + LOG_ERROR("Ride not found for rideIndex %u", _rideIndex.ToUnderlying()); + res.Error = Status::InvalidParameters; + res.ErrorTitle = STR_RIDE_DESCRIPTION_UNKNOWN; + res.ErrorMessage = STR_ERR_RIDE_NOT_FOUND; return res; } - ResultWithMessage modeSwitchResult = { true }; - switch (_status) + if (_status >= RideStatus::count) { - case RideStatus::open: - modeSwitchResult = ride->open(false); - break; - case RideStatus::testing: - modeSwitchResult = ride->test(false); - break; - case RideStatus::simulating: - modeSwitchResult = ride->simulate(false); - break; - default: - break; - } - - if (!modeSwitchResult.Successful) - { - res.Error = GameActions::Status::Unknown; - res.ErrorMessage = modeSwitchResult.Message; + LOG_ERROR("Invalid ride status %u for ride %u", EnumValue(_status), _rideIndex.ToUnderlying()); + res.Error = Status::InvalidParameters; + res.ErrorTitle = STR_RIDE_DESCRIPTION_UNKNOWN; + res.ErrorMessage = kStringIdNone; return res; } - } - return GameActions::Result(); -} -GameActions::Result RideSetStatusAction::Execute() const -{ - GameActions::Result res = GameActions::Result(); - res.Expenditure = ExpenditureType::rideRunningCosts; + res.ErrorTitle = _StatusErrorTitles[EnumValue(_status)]; - auto ride = GetRide(_rideIndex); - if (ride == nullptr) - { - LOG_ERROR("Ride not found for rideIndex %u", _rideIndex.ToUnderlying()); - res.Error = GameActions::Status::InvalidParameters; - res.ErrorTitle = STR_RIDE_DESCRIPTION_UNKNOWN; - res.ErrorMessage = STR_ERR_RIDE_NOT_FOUND; - return res; - } - - res.ErrorTitle = _StatusErrorTitles[EnumValue(_status)]; - - Formatter ft(res.ErrorMessageArgs.data()); - ft.Increment(6); - ride->formatNameTo(ft); - if (!ride->overallView.IsNull()) - { - auto location = ride->overallView.ToTileCentre(); - res.Position = { location, TileElementHeight(location) }; - } - - auto* windowMgr = Ui::GetWindowManager(); - - switch (_status) - { - case RideStatus::closed: - if (ride->status == _status || ride->status == RideStatus::simulating) + Formatter ft(res.ErrorMessageArgs.data()); + ride->formatNameTo(ft); + if (_status != ride->status) + { + if (_status == RideStatus::simulating && (ride->lifecycleFlags & RIDE_LIFECYCLE_BROKEN_DOWN)) { - if (!(ride->lifecycleFlags & RIDE_LIFECYCLE_BROKEN_DOWN)) - { - ride->lifecycleFlags &= ~RIDE_LIFECYCLE_CRASHED; - RideClearForConstruction(*ride); - ride->removePeeps(); - } + // Simulating will force clear the track, so make sure player can't cheat around a break down + res.Error = Status::Disallowed; + res.ErrorMessage = STR_HAS_BROKEN_DOWN_AND_REQUIRES_FIXING; + return res; } - ride->status = RideStatus::closed; - ride->lifecycleFlags &= ~RIDE_LIFECYCLE_PASS_STATION_NO_STOPPING; - ride->raceWinner = EntityId::GetNull(); - ride->windowInvalidateFlags |= RIDE_INVALIDATE_RIDE_MAIN | RIDE_INVALIDATE_RIDE_LIST; - windowMgr->InvalidateByNumber(WindowClass::Ride, _rideIndex.ToUnderlying()); - break; - case RideStatus::simulating: - { - ride->lifecycleFlags &= ~RIDE_LIFECYCLE_CRASHED; - RideClearForConstruction(*ride); - ride->removePeeps(); + ResultWithMessage modeSwitchResult = { true }; + switch (_status) + { + case RideStatus::open: + modeSwitchResult = ride->open(false); + break; + case RideStatus::testing: + modeSwitchResult = ride->test(false); + break; + case RideStatus::simulating: + modeSwitchResult = ride->simulate(false); + break; + default: + break; + } - const auto modeSwitchResult = ride->simulate(true); if (!modeSwitchResult.Successful) { - res.Error = GameActions::Status::Unknown; + res.Error = Status::Unknown; res.ErrorMessage = modeSwitchResult.Message; return res; } - - ride->status = _status; - ride->lifecycleFlags &= ~RIDE_LIFECYCLE_PASS_STATION_NO_STOPPING; - ride->raceWinner = EntityId::GetNull(); - ride->currentIssues = 0; - ride->lastIssueTime = 0; - ride->getMeasurement(); - ride->windowInvalidateFlags |= RIDE_INVALIDATE_RIDE_MAIN | RIDE_INVALIDATE_RIDE_LIST; - windowMgr->InvalidateByNumber(WindowClass::Ride, _rideIndex.ToUnderlying()); - break; } - case RideStatus::testing: - case RideStatus::open: - { - if (ride->status == _status) - { - return res; - } + return Result(); + } - if (ride->status == RideStatus::simulating) + Result RideSetStatusAction::Execute() const + { + Result res = Result(); + res.Expenditure = ExpenditureType::rideRunningCosts; + + auto ride = GetRide(_rideIndex); + if (ride == nullptr) + { + LOG_ERROR("Ride not found for rideIndex %u", _rideIndex.ToUnderlying()); + res.Error = Status::InvalidParameters; + res.ErrorTitle = STR_RIDE_DESCRIPTION_UNKNOWN; + res.ErrorMessage = STR_ERR_RIDE_NOT_FOUND; + return res; + } + + res.ErrorTitle = _StatusErrorTitles[EnumValue(_status)]; + + Formatter ft(res.ErrorMessageArgs.data()); + ft.Increment(6); + ride->formatNameTo(ft); + if (!ride->overallView.IsNull()) + { + auto location = ride->overallView.ToTileCentre(); + res.Position = { location, TileElementHeight(location) }; + } + + auto* windowMgr = Ui::GetWindowManager(); + + switch (_status) + { + case RideStatus::closed: + if (ride->status == _status || ride->status == RideStatus::simulating) + { + if (!(ride->lifecycleFlags & RIDE_LIFECYCLE_BROKEN_DOWN)) + { + ride->lifecycleFlags &= ~RIDE_LIFECYCLE_CRASHED; + RideClearForConstruction(*ride); + ride->removePeeps(); + } + } + + ride->status = RideStatus::closed; + ride->lifecycleFlags &= ~RIDE_LIFECYCLE_PASS_STATION_NO_STOPPING; + ride->raceWinner = EntityId::GetNull(); + ride->windowInvalidateFlags |= RIDE_INVALIDATE_RIDE_MAIN | RIDE_INVALIDATE_RIDE_LIST; + windowMgr->InvalidateByNumber(WindowClass::Ride, _rideIndex.ToUnderlying()); + break; + case RideStatus::simulating: { + ride->lifecycleFlags &= ~RIDE_LIFECYCLE_CRASHED; RideClearForConstruction(*ride); ride->removePeeps(); - } - // Fix #3183: Make sure we close the construction window so the ride finishes any editing code before opening - // otherwise vehicles get added to the ride incorrectly (such as to a ghost station) - WindowBase* constructionWindow = windowMgr->FindByNumber(WindowClass::RideConstruction, _rideIndex.ToUnderlying()); - if (constructionWindow != nullptr) - { - windowMgr->Close(*constructionWindow); - } - - if (_status == RideStatus::testing) - { - const auto modeSwitchResult = ride->test(true); + const auto modeSwitchResult = ride->simulate(true); if (!modeSwitchResult.Successful) { - res.Error = GameActions::Status::Unknown; + res.Error = Status::Unknown; res.ErrorMessage = modeSwitchResult.Message; return res; } + + ride->status = _status; + ride->lifecycleFlags &= ~RIDE_LIFECYCLE_PASS_STATION_NO_STOPPING; + ride->raceWinner = EntityId::GetNull(); + ride->currentIssues = 0; + ride->lastIssueTime = 0; + ride->getMeasurement(); + ride->windowInvalidateFlags |= RIDE_INVALIDATE_RIDE_MAIN | RIDE_INVALIDATE_RIDE_LIST; + windowMgr->InvalidateByNumber(WindowClass::Ride, _rideIndex.ToUnderlying()); + break; } - else + case RideStatus::testing: + case RideStatus::open: { - const auto modeSwitchResult = ride->open(true); - if (!modeSwitchResult.Successful) + if (ride->status == _status) { - res.Error = GameActions::Status::Unknown; - res.ErrorMessage = modeSwitchResult.Message; return res; } - } - ride->raceWinner = EntityId::GetNull(); - ride->status = _status; - ride->currentIssues = 0; - ride->lastIssueTime = 0; - ride->getMeasurement(); - ride->windowInvalidateFlags |= RIDE_INVALIDATE_RIDE_MAIN | RIDE_INVALIDATE_RIDE_LIST; - windowMgr->InvalidateByNumber(WindowClass::Ride, _rideIndex.ToUnderlying()); - break; + if (ride->status == RideStatus::simulating) + { + RideClearForConstruction(*ride); + ride->removePeeps(); + } + + // Fix #3183: Make sure we close the construction window so the ride finishes any editing code before opening + // otherwise vehicles get added to the ride incorrectly (such as to a ghost station) + WindowBase* constructionWindow = windowMgr->FindByNumber( + WindowClass::RideConstruction, _rideIndex.ToUnderlying()); + if (constructionWindow != nullptr) + { + windowMgr->Close(*constructionWindow); + } + + if (_status == RideStatus::testing) + { + const auto modeSwitchResult = ride->test(true); + if (!modeSwitchResult.Successful) + { + res.Error = Status::Unknown; + res.ErrorMessage = modeSwitchResult.Message; + return res; + } + } + else + { + const auto modeSwitchResult = ride->open(true); + if (!modeSwitchResult.Successful) + { + res.Error = Status::Unknown; + res.ErrorMessage = modeSwitchResult.Message; + return res; + } + } + + ride->raceWinner = EntityId::GetNull(); + ride->status = _status; + ride->currentIssues = 0; + ride->lastIssueTime = 0; + ride->getMeasurement(); + ride->windowInvalidateFlags |= RIDE_INVALIDATE_RIDE_MAIN | RIDE_INVALIDATE_RIDE_LIST; + windowMgr->InvalidateByNumber(WindowClass::Ride, _rideIndex.ToUnderlying()); + break; + } + default: + Guard::Assert(false, "Invalid ride status %u", _status); + break; } - default: - Guard::Assert(false, "Invalid ride status %u", _status); - break; - } - auto windowManager = OpenRCT2::Ui::GetWindowManager(); - windowManager->BroadcastIntent(Intent(INTENT_ACTION_REFRESH_CAMPAIGN_RIDE_LIST)); + auto windowManager = OpenRCT2::Ui::GetWindowManager(); + windowManager->BroadcastIntent(Intent(INTENT_ACTION_REFRESH_CAMPAIGN_RIDE_LIST)); - return res; -} + return res; + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/RideSetStatusAction.h b/src/openrct2/actions/RideSetStatusAction.h index 0f602919a0..53f683f6ae 100644 --- a/src/openrct2/actions/RideSetStatusAction.h +++ b/src/openrct2/actions/RideSetStatusAction.h @@ -11,21 +11,24 @@ #include "GameAction.h" -class RideSetStatusAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - RideId _rideIndex{ RideId::GetNull() }; - RideStatus _status{ RideStatus::closed }; + class RideSetStatusAction final : public GameActionBase + { + private: + RideId _rideIndex{ RideId::GetNull() }; + RideStatus _status{ RideStatus::closed }; -public: - RideSetStatusAction() = default; - RideSetStatusAction(RideId rideIndex, RideStatus status); + public: + RideSetStatusAction() = default; + RideSetStatusAction(RideId rideIndex, RideStatus status); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; -}; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/RideSetVehicleAction.cpp b/src/openrct2/actions/RideSetVehicleAction.cpp index 629ca3cddb..621e20b0a4 100644 --- a/src/openrct2/actions/RideSetVehicleAction.cpp +++ b/src/openrct2/actions/RideSetVehicleAction.cpp @@ -24,254 +24,255 @@ #include "../ui/WindowManager.h" #include "../world/Park.h" -using namespace OpenRCT2; - -constexpr static StringId kSetVehicleTypeErrorTitle[] = { - STR_RIDE_SET_VEHICLE_SET_NUM_TRAINS_FAIL, - STR_RIDE_SET_VEHICLE_SET_NUM_CARS_PER_TRAIN_FAIL, - STR_RIDE_SET_VEHICLE_TYPE_FAIL, - STR_RIDE_SET_VEHICLE_REVERSED_FAIL, -}; - -RideSetVehicleAction::RideSetVehicleAction(RideId rideIndex, RideSetVehicleType type, uint16_t value, uint8_t colour) - : _rideIndex(rideIndex) - , _type(type) - , _value(value) - , _colour(colour) +namespace OpenRCT2::GameActions { -} + constexpr static StringId kSetVehicleTypeErrorTitle[] = { + STR_RIDE_SET_VEHICLE_SET_NUM_TRAINS_FAIL, + STR_RIDE_SET_VEHICLE_SET_NUM_CARS_PER_TRAIN_FAIL, + STR_RIDE_SET_VEHICLE_TYPE_FAIL, + STR_RIDE_SET_VEHICLE_REVERSED_FAIL, + }; -void RideSetVehicleAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit("ride", _rideIndex); - visitor.Visit("type", _type); - visitor.Visit("value", _value); - visitor.Visit("colour", _colour); -} - -uint16_t RideSetVehicleAction::GetActionFlags() const -{ - return GameAction::GetActionFlags() | GameActions::Flags::AllowWhilePaused; -} - -void RideSetVehicleAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - stream << DS_TAG(_rideIndex) << DS_TAG(_type) << DS_TAG(_value) << DS_TAG(_colour); -} - -GameActions::Result RideSetVehicleAction::Query() const -{ - if (_type >= RideSetVehicleType::Count) + RideSetVehicleAction::RideSetVehicleAction(RideId rideIndex, RideSetVehicleType type, uint16_t value, uint8_t colour) + : _rideIndex(rideIndex) + , _type(type) + , _value(value) + , _colour(colour) { - LOG_ERROR("Invalid ride vehicle type %d", _type); - } - auto errTitle = kSetVehicleTypeErrorTitle[EnumValue(_type)]; - - auto ride = GetRide(_rideIndex); - if (ride == nullptr) - { - LOG_ERROR("Ride not found for rideIndex %u", _rideIndex.ToUnderlying()); - return GameActions::Result(GameActions::Status::InvalidParameters, errTitle, STR_ERR_RIDE_NOT_FOUND); } - if (ride->lifecycleFlags & RIDE_LIFECYCLE_BROKEN_DOWN) + void RideSetVehicleAction::AcceptParameters(GameActionParameterVisitor& visitor) { - return GameActions::Result(GameActions::Status::Broken, errTitle, STR_HAS_BROKEN_DOWN_AND_REQUIRES_FIXING); + visitor.Visit("ride", _rideIndex); + visitor.Visit("type", _type); + visitor.Visit("value", _value); + visitor.Visit("colour", _colour); } - if (ride->status != RideStatus::closed && ride->status != RideStatus::simulating) + uint16_t RideSetVehicleAction::GetActionFlags() const { - return GameActions::Result(GameActions::Status::NotClosed, errTitle, STR_MUST_BE_CLOSED_FIRST); + return GameAction::GetActionFlags() | Flags::AllowWhilePaused; } - switch (_type) + void RideSetVehicleAction::Serialise(DataSerialiser& stream) { - case RideSetVehicleType::NumTrains: - case RideSetVehicleType::NumCarsPerTrain: - case RideSetVehicleType::TrainsReversed: - break; - case RideSetVehicleType::RideEntry: + GameAction::Serialise(stream); + stream << DS_TAG(_rideIndex) << DS_TAG(_type) << DS_TAG(_value) << DS_TAG(_colour); + } + + Result RideSetVehicleAction::Query() const + { + if (_type >= RideSetVehicleType::Count) { - if (!RideIsVehicleTypeValid(*ride)) - { - LOG_ERROR("Invalid vehicle type %d", _value); - return GameActions::Result(GameActions::Status::InvalidParameters, errTitle, STR_ERR_VALUE_OUT_OF_RANGE); - } - auto rideEntry = GetRideEntryByIndex(_value); - if (rideEntry == nullptr) - { - LOG_ERROR("Ride entry not found for _value %d", _value); - return GameActions::Result(GameActions::Status::InvalidParameters, errTitle, kStringIdNone); - } + LOG_ERROR("Invalid ride vehicle type %d", _type); + } + auto errTitle = kSetVehicleTypeErrorTitle[EnumValue(_type)]; - // Validate preset - VehicleColourPresetList* presetList = rideEntry->vehicle_preset_list; - if (_colour >= presetList->count && _colour != 255 && _colour != 0) - { - LOG_ERROR("Unknown vehicle colour preset. colour = %d", _colour); - return GameActions::Result(GameActions::Status::InvalidParameters, errTitle, STR_ERR_INVALID_COLOUR); - } - break; + auto ride = GetRide(_rideIndex); + if (ride == nullptr) + { + LOG_ERROR("Ride not found for rideIndex %u", _rideIndex.ToUnderlying()); + return Result(Status::InvalidParameters, errTitle, STR_ERR_RIDE_NOT_FOUND); } - default: - LOG_ERROR("Invalid ride vehicle setting %d", _type); - return GameActions::Result(GameActions::Status::InvalidParameters, errTitle, STR_ERR_VALUE_OUT_OF_RANGE); - } - - return GameActions::Result(); -} - -GameActions::Result RideSetVehicleAction::Execute() const -{ - auto errTitle = kSetVehicleTypeErrorTitle[EnumValue(_type)]; - auto ride = GetRide(_rideIndex); - if (ride == nullptr) - { - LOG_ERROR("Ride not found for rideIndex %u", _rideIndex.ToUnderlying()); - return GameActions::Result(GameActions::Status::InvalidParameters, errTitle, STR_ERR_RIDE_NOT_FOUND); - } - - switch (_type) - { - case RideSetVehicleType::NumTrains: - RideClearForConstruction(*ride); - ride->removePeeps(); - ride->vehicleChangeTimeout = 100; - - ride->proposedNumTrains = _value; - break; - case RideSetVehicleType::NumCarsPerTrain: + if (ride->lifecycleFlags & RIDE_LIFECYCLE_BROKEN_DOWN) { - RideClearForConstruction(*ride); - ride->removePeeps(); - ride->vehicleChangeTimeout = 100; + return Result(Status::Broken, errTitle, STR_HAS_BROKEN_DOWN_AND_REQUIRES_FIXING); + } - InvalidateTestResults(*ride); - auto rideEntry = GetRideEntryByIndex(ride->subtype); - if (rideEntry == nullptr) + if (ride->status != RideStatus::closed && ride->status != RideStatus::simulating) + { + return Result(Status::NotClosed, errTitle, STR_MUST_BE_CLOSED_FIRST); + } + + switch (_type) + { + case RideSetVehicleType::NumTrains: + case RideSetVehicleType::NumCarsPerTrain: + case RideSetVehicleType::TrainsReversed: + break; + case RideSetVehicleType::RideEntry: { - LOG_ERROR("Ride entry not found for index %d", ride->subtype); - return GameActions::Result(GameActions::Status::InvalidParameters, errTitle, kStringIdNone); - } - uint8_t clampValue = _value; - static_assert(sizeof(clampValue) == sizeof(ride->proposedNumCarsPerTrain)); - if (!getGameState().cheats.disableTrainLengthLimit) - { - clampValue = std::clamp(clampValue, rideEntry->min_cars_in_train, rideEntry->max_cars_in_train); - } - ride->proposedNumCarsPerTrain = clampValue; - break; - } - case RideSetVehicleType::RideEntry: - { - RideClearForConstruction(*ride); - ride->removePeeps(); - ride->vehicleChangeTimeout = 100; - - InvalidateTestResults(*ride); - ride->subtype = _value; - auto rideEntry = GetRideEntryByIndex(ride->subtype); - if (rideEntry == nullptr) - { - LOG_ERROR("Ride entry not found for index %d", ride->subtype); - return GameActions::Result(GameActions::Status::InvalidParameters, errTitle, kStringIdNone); - } - - RideSetVehicleColoursToRandomPreset(*ride, _colour); - if (!getGameState().cheats.disableTrainLengthLimit) - { - ride->proposedNumCarsPerTrain = std::clamp( - ride->proposedNumCarsPerTrain, rideEntry->min_cars_in_train, rideEntry->max_cars_in_train); - } - break; - } - case RideSetVehicleType::TrainsReversed: - { - RideClearForConstruction(*ride); - ride->removePeeps(); - ride->vehicleChangeTimeout = 100; - - ride->setLifecycleFlag(RIDE_LIFECYCLE_REVERSED_TRAINS, _value); - break; - } - - default: - LOG_ERROR("Invalid ride vehicle setting %d", _type); - return GameActions::Result(GameActions::Status::InvalidParameters, errTitle, kStringIdNone); - } - - ride->numCircuits = 1; - ride->updateMaxVehicles(); - - auto res = GameActions::Result(); - if (!ride->overallView.IsNull()) - { - auto location = ride->overallView.ToTileCentre(); - res.Position = { location, TileElementHeight(res.Position) }; - } - - auto intent = Intent(INTENT_ACTION_RIDE_PAINT_RESET_VEHICLE); - intent.PutExtra(INTENT_EXTRA_RIDE_ID, _rideIndex.ToUnderlying()); - ContextBroadcastIntent(&intent); - - GfxInvalidateScreen(); - return res; -} - -bool RideSetVehicleAction::RideIsVehicleTypeValid(const Ride& ride) const -{ - bool selectionShouldBeExpanded; - ride_type_t rideTypeIterator, rideTypeIteratorMax; - auto& gameState = getGameState(); - - { - const auto& rtd = ride.getRideTypeDescriptor(); - if (gameState.cheats.showVehiclesFromOtherTrackTypes - && !( - ride.getRideTypeDescriptor().HasFlag(RtdFlag::isFlatRide) || rtd.specialType == RtdSpecialType::maze - || rtd.specialType == RtdSpecialType::miniGolf)) - { - selectionShouldBeExpanded = true; - rideTypeIterator = 0; - rideTypeIteratorMax = RIDE_TYPE_COUNT - 1; - } - else - { - selectionShouldBeExpanded = false; - rideTypeIterator = ride.type; - rideTypeIteratorMax = ride.type; - } - } - - for (; rideTypeIterator <= rideTypeIteratorMax; rideTypeIterator++) - { - if (selectionShouldBeExpanded) - { - if (GetRideTypeDescriptor(rideTypeIterator).HasFlag(RtdFlag::isFlatRide)) - continue; - - const auto& rtd = GetRideTypeDescriptor(rideTypeIterator); - if (rtd.specialType == RtdSpecialType::maze || rtd.specialType == RtdSpecialType::miniGolf) - continue; - } - - auto& objManager = GetContext()->GetObjectManager(); - auto& rideEntries = objManager.GetAllRideEntries(rideTypeIterator); - for (auto rideEntryIndex : rideEntries) - { - if (rideEntryIndex == _value) - { - if (!RideEntryIsInvented(rideEntryIndex) && !gameState.cheats.ignoreResearchStatus) + if (!RideIsVehicleTypeValid(*ride)) { - return false; + LOG_ERROR("Invalid vehicle type %d", _value); + return Result(Status::InvalidParameters, errTitle, STR_ERR_VALUE_OUT_OF_RANGE); + } + auto rideEntry = GetRideEntryByIndex(_value); + if (rideEntry == nullptr) + { + LOG_ERROR("Ride entry not found for _value %d", _value); + return Result(Status::InvalidParameters, errTitle, kStringIdNone); } - return true; + // Validate preset + VehicleColourPresetList* presetList = rideEntry->vehicle_preset_list; + if (_colour >= presetList->count && _colour != 255 && _colour != 0) + { + LOG_ERROR("Unknown vehicle colour preset. colour = %d", _colour); + return Result(Status::InvalidParameters, errTitle, STR_ERR_INVALID_COLOUR); + } + break; } + + default: + LOG_ERROR("Invalid ride vehicle setting %d", _type); + return Result(Status::InvalidParameters, errTitle, STR_ERR_VALUE_OUT_OF_RANGE); } + + return Result(); } - return false; -} + Result RideSetVehicleAction::Execute() const + { + auto errTitle = kSetVehicleTypeErrorTitle[EnumValue(_type)]; + auto ride = GetRide(_rideIndex); + if (ride == nullptr) + { + LOG_ERROR("Ride not found for rideIndex %u", _rideIndex.ToUnderlying()); + return Result(Status::InvalidParameters, errTitle, STR_ERR_RIDE_NOT_FOUND); + } + + switch (_type) + { + case RideSetVehicleType::NumTrains: + RideClearForConstruction(*ride); + ride->removePeeps(); + ride->vehicleChangeTimeout = 100; + + ride->proposedNumTrains = _value; + break; + case RideSetVehicleType::NumCarsPerTrain: + { + RideClearForConstruction(*ride); + ride->removePeeps(); + ride->vehicleChangeTimeout = 100; + + InvalidateTestResults(*ride); + auto rideEntry = GetRideEntryByIndex(ride->subtype); + if (rideEntry == nullptr) + { + LOG_ERROR("Ride entry not found for index %d", ride->subtype); + return Result(Status::InvalidParameters, errTitle, kStringIdNone); + } + uint8_t clampValue = _value; + static_assert(sizeof(clampValue) == sizeof(ride->proposedNumCarsPerTrain)); + if (!getGameState().cheats.disableTrainLengthLimit) + { + clampValue = std::clamp(clampValue, rideEntry->min_cars_in_train, rideEntry->max_cars_in_train); + } + ride->proposedNumCarsPerTrain = clampValue; + break; + } + case RideSetVehicleType::RideEntry: + { + RideClearForConstruction(*ride); + ride->removePeeps(); + ride->vehicleChangeTimeout = 100; + + InvalidateTestResults(*ride); + ride->subtype = _value; + auto rideEntry = GetRideEntryByIndex(ride->subtype); + if (rideEntry == nullptr) + { + LOG_ERROR("Ride entry not found for index %d", ride->subtype); + return Result(Status::InvalidParameters, errTitle, kStringIdNone); + } + + RideSetVehicleColoursToRandomPreset(*ride, _colour); + if (!getGameState().cheats.disableTrainLengthLimit) + { + ride->proposedNumCarsPerTrain = std::clamp( + ride->proposedNumCarsPerTrain, rideEntry->min_cars_in_train, rideEntry->max_cars_in_train); + } + break; + } + case RideSetVehicleType::TrainsReversed: + { + RideClearForConstruction(*ride); + ride->removePeeps(); + ride->vehicleChangeTimeout = 100; + + ride->setLifecycleFlag(RIDE_LIFECYCLE_REVERSED_TRAINS, _value); + break; + } + + default: + LOG_ERROR("Invalid ride vehicle setting %d", _type); + return Result(Status::InvalidParameters, errTitle, kStringIdNone); + } + + ride->numCircuits = 1; + ride->updateMaxVehicles(); + + auto res = Result(); + if (!ride->overallView.IsNull()) + { + auto location = ride->overallView.ToTileCentre(); + res.Position = { location, TileElementHeight(res.Position) }; + } + + auto intent = Intent(INTENT_ACTION_RIDE_PAINT_RESET_VEHICLE); + intent.PutExtra(INTENT_EXTRA_RIDE_ID, _rideIndex.ToUnderlying()); + ContextBroadcastIntent(&intent); + + GfxInvalidateScreen(); + return res; + } + + bool RideSetVehicleAction::RideIsVehicleTypeValid(const Ride& ride) const + { + bool selectionShouldBeExpanded; + ride_type_t rideTypeIterator, rideTypeIteratorMax; + auto& gameState = getGameState(); + + { + const auto& rtd = ride.getRideTypeDescriptor(); + if (gameState.cheats.showVehiclesFromOtherTrackTypes + && !( + ride.getRideTypeDescriptor().HasFlag(RtdFlag::isFlatRide) || rtd.specialType == RtdSpecialType::maze + || rtd.specialType == RtdSpecialType::miniGolf)) + { + selectionShouldBeExpanded = true; + rideTypeIterator = 0; + rideTypeIteratorMax = RIDE_TYPE_COUNT - 1; + } + else + { + selectionShouldBeExpanded = false; + rideTypeIterator = ride.type; + rideTypeIteratorMax = ride.type; + } + } + + for (; rideTypeIterator <= rideTypeIteratorMax; rideTypeIterator++) + { + if (selectionShouldBeExpanded) + { + if (GetRideTypeDescriptor(rideTypeIterator).HasFlag(RtdFlag::isFlatRide)) + continue; + + const auto& rtd = GetRideTypeDescriptor(rideTypeIterator); + if (rtd.specialType == RtdSpecialType::maze || rtd.specialType == RtdSpecialType::miniGolf) + continue; + } + + auto& objManager = GetContext()->GetObjectManager(); + auto& rideEntries = objManager.GetAllRideEntries(rideTypeIterator); + for (auto rideEntryIndex : rideEntries) + { + if (rideEntryIndex == _value) + { + if (!RideEntryIsInvented(rideEntryIndex) && !gameState.cheats.ignoreResearchStatus) + { + return false; + } + + return true; + } + } + } + + return false; + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/RideSetVehicleAction.h b/src/openrct2/actions/RideSetVehicleAction.h index cc7dfd6e3a..147fd7ab75 100644 --- a/src/openrct2/actions/RideSetVehicleAction.h +++ b/src/openrct2/actions/RideSetVehicleAction.h @@ -11,37 +11,40 @@ #include "GameAction.h" -enum class RideSetVehicleType : uint8_t +namespace OpenRCT2::GameActions { - NumTrains, - NumCarsPerTrain, - RideEntry, - TrainsReversed, - Count, -}; + enum class RideSetVehicleType : uint8_t + { + NumTrains, + NumCarsPerTrain, + RideEntry, + TrainsReversed, + Count, + }; -class RideSetVehicleAction final : public GameActionBase -{ -private: - RideId _rideIndex{ RideId::GetNull() }; - RideSetVehicleType _type{}; - uint16_t _value{}; - uint8_t _colour{}; + class RideSetVehicleAction final : public GameActionBase + { + private: + RideId _rideIndex{ RideId::GetNull() }; + RideSetVehicleType _type{}; + uint16_t _value{}; + uint8_t _colour{}; -public: - RideSetVehicleAction() = default; - RideSetVehicleAction(RideId rideIndex, RideSetVehicleType type, uint16_t value, uint8_t colour = 0); + public: + RideSetVehicleAction() = default; + RideSetVehicleAction(RideId rideIndex, RideSetVehicleType type, uint16_t value, uint8_t colour = 0); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; -private: - bool RideIsVehicleTypeValid(const Ride& ride) const; + private: + bool RideIsVehicleTypeValid(const Ride& ride) const; - static_assert(sizeof(_value) >= sizeof(OpenRCT2::ObjectEntryIndex)); -}; + static_assert(sizeof(_value) >= sizeof(ObjectEntryIndex)); + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/ScenerySetRestrictedAction.cpp b/src/openrct2/actions/ScenerySetRestrictedAction.cpp index 18c4af81b6..2270091068 100644 --- a/src/openrct2/actions/ScenerySetRestrictedAction.cpp +++ b/src/openrct2/actions/ScenerySetRestrictedAction.cpp @@ -12,47 +12,48 @@ #include "../object/SceneryGroupObject.h" #include "../world/Scenery.h" -using namespace OpenRCT2; - -ScenerySetRestrictedAction::ScenerySetRestrictedAction(ObjectType objectType, ObjectEntryIndex entryIndex, bool isRestricted) - : _objectType(objectType) - , _objectIndex(entryIndex) - , _isRestricted(isRestricted) +namespace OpenRCT2::GameActions { -} - -void ScenerySetRestrictedAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_objectType) << DS_TAG(_objectIndex) << DS_TAG(_isRestricted); -} - -uint16_t ScenerySetRestrictedAction::GetActionFlags() const -{ - return GameAction::GetActionFlags() | GameActions::Flags::AllowWhilePaused; -} - -GameActions::Result ScenerySetRestrictedAction::Query() const -{ - if (!ObjectTypeCanBeRestricted(_objectType)) + ScenerySetRestrictedAction::ScenerySetRestrictedAction( + ObjectType objectType, ObjectEntryIndex entryIndex, bool isRestricted) + : _objectType(objectType) + , _objectIndex(entryIndex) + , _isRestricted(isRestricted) { - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_RESTRICT_OBJECT, STR_OBJECT_TYPE_CANNOT_BE_RESTRICTED); - } - const auto* loadedObject = ObjectEntryGetObject(_objectType, _objectIndex); - if (loadedObject == nullptr) - { - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_RESTRICT_OBJECT, STR_OBJECT_NOT_FOUND); } - return GameActions::Result(); -} + void ScenerySetRestrictedAction::Serialise(DataSerialiser& stream) + { + GameAction::Serialise(stream); -GameActions::Result ScenerySetRestrictedAction::Execute() const -{ - auto sceneryType = GetSceneryTypeFromObjectType(_objectType); - SetSceneryItemRestricted({ sceneryType, _objectIndex }, _isRestricted); + stream << DS_TAG(_objectType) << DS_TAG(_objectIndex) << DS_TAG(_isRestricted); + } - return GameActions::Result(); -} + uint16_t ScenerySetRestrictedAction::GetActionFlags() const + { + return GameAction::GetActionFlags() | Flags::AllowWhilePaused; + } + + Result ScenerySetRestrictedAction::Query() const + { + if (!ObjectTypeCanBeRestricted(_objectType)) + { + return Result(Status::InvalidParameters, STR_CANT_RESTRICT_OBJECT, STR_OBJECT_TYPE_CANNOT_BE_RESTRICTED); + } + const auto* loadedObject = ObjectEntryGetObject(_objectType, _objectIndex); + if (loadedObject == nullptr) + { + return Result(Status::InvalidParameters, STR_CANT_RESTRICT_OBJECT, STR_OBJECT_NOT_FOUND); + } + + return Result(); + } + + Result ScenerySetRestrictedAction::Execute() const + { + auto sceneryType = GetSceneryTypeFromObjectType(_objectType); + SetSceneryItemRestricted({ sceneryType, _objectIndex }, _isRestricted); + + return Result(); + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/ScenerySetRestrictedAction.h b/src/openrct2/actions/ScenerySetRestrictedAction.h index 523e140620..cbaec7bb53 100644 --- a/src/openrct2/actions/ScenerySetRestrictedAction.h +++ b/src/openrct2/actions/ScenerySetRestrictedAction.h @@ -11,20 +11,23 @@ #include "GameAction.h" -class ScenerySetRestrictedAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - OpenRCT2::ObjectType _objectType; - OpenRCT2::ObjectEntryIndex _objectIndex; - bool _isRestricted; + class ScenerySetRestrictedAction final : public GameActionBase + { + private: + ObjectType _objectType; + ObjectEntryIndex _objectIndex; + bool _isRestricted; -public: - ScenerySetRestrictedAction() = default; - ScenerySetRestrictedAction(OpenRCT2::ObjectType objectType, OpenRCT2::ObjectEntryIndex entryIndex, bool isRestricted); + public: + ScenerySetRestrictedAction() = default; + ScenerySetRestrictedAction(ObjectType objectType, ObjectEntryIndex entryIndex, bool isRestricted); - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; -}; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/SignSetNameAction.cpp b/src/openrct2/actions/SignSetNameAction.cpp index d6b680c11d..dbb209d848 100644 --- a/src/openrct2/actions/SignSetNameAction.cpp +++ b/src/openrct2/actions/SignSetNameAction.cpp @@ -18,97 +18,97 @@ #include -using namespace OpenRCT2; - -SignSetNameAction::SignSetNameAction(BannerIndex bannerIndex, const std::string& name) - : _bannerIndex(bannerIndex) - , _name(name) +namespace OpenRCT2::GameActions { -} - -void SignSetNameAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit("id", _bannerIndex); - visitor.Visit("name", _name); -} - -uint16_t SignSetNameAction::GetActionFlags() const -{ - return GameAction::GetActionFlags() | GameActions::Flags::AllowWhilePaused; -} - -void SignSetNameAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - stream << DS_TAG(_bannerIndex) << DS_TAG(_name); -} - -GameActions::Result SignSetNameAction::Query() const -{ - auto banner = GetBanner(_bannerIndex); - if (banner == nullptr) + SignSetNameAction::SignSetNameAction(BannerIndex bannerIndex, const std::string& name) + : _bannerIndex(bannerIndex) + , _name(name) { - LOG_ERROR("Banner not found for bannerIndex %d", _bannerIndex); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_RENAME_SIGN, kStringIdNone); } - TileElement* tileElement = BannerGetTileElement(_bannerIndex); - - if (tileElement == nullptr) + void SignSetNameAction::AcceptParameters(GameActionParameterVisitor& visitor) { - LOG_ERROR("Banner tile element not found for bannerIndex %d", _bannerIndex); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_RENAME_BANNER, STR_ERR_BANNER_ELEMENT_NOT_FOUND); + visitor.Visit("id", _bannerIndex); + visitor.Visit("name", _name); } - CoordsXYZ loc = { banner->position.ToCoordsXY(), tileElement->GetBaseZ() }; - - if (!LocationValid(loc)) + uint16_t SignSetNameAction::GetActionFlags() const { - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_RENAME_BANNER, STR_OFF_EDGE_OF_MAP); - } - if (!MapCanBuildAt({ loc.x, loc.y, loc.z - 16 })) - { - return GameActions::Result(GameActions::Status::NotOwned, STR_CANT_RENAME_BANNER, STR_LAND_NOT_OWNED_BY_PARK); + return GameAction::GetActionFlags() | Flags::AllowWhilePaused; } - return GameActions::Result(); -} - -GameActions::Result SignSetNameAction::Execute() const -{ - auto banner = GetBanner(_bannerIndex); - if (banner == nullptr) + void SignSetNameAction::Serialise(DataSerialiser& stream) { - LOG_ERROR("Banner not found for bannerIndex %d", _bannerIndex); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_RENAME_SIGN, kStringIdNone); + GameAction::Serialise(stream); + stream << DS_TAG(_bannerIndex) << DS_TAG(_name); } - if (!_name.empty()) + Result SignSetNameAction::Query() const { - banner->flags.unset(BannerFlag::linkedToRide); - banner->rideIndex = RideId::GetNull(); - banner->text = _name; + auto banner = GetBanner(_bannerIndex); + if (banner == nullptr) + { + LOG_ERROR("Banner not found for bannerIndex %d", _bannerIndex); + return Result(Status::InvalidParameters, STR_CANT_RENAME_SIGN, kStringIdNone); + } + + TileElement* tileElement = BannerGetTileElement(_bannerIndex); + + if (tileElement == nullptr) + { + LOG_ERROR("Banner tile element not found for bannerIndex %d", _bannerIndex); + return Result(Status::InvalidParameters, STR_CANT_RENAME_BANNER, STR_ERR_BANNER_ELEMENT_NOT_FOUND); + } + + CoordsXYZ loc = { banner->position.ToCoordsXY(), tileElement->GetBaseZ() }; + + if (!LocationValid(loc)) + { + return Result(Status::InvalidParameters, STR_CANT_RENAME_BANNER, STR_OFF_EDGE_OF_MAP); + } + if (!MapCanBuildAt({ loc.x, loc.y, loc.z - 16 })) + { + return Result(Status::NotOwned, STR_CANT_RENAME_BANNER, STR_LAND_NOT_OWNED_BY_PARK); + } + + return Result(); } - else + + Result SignSetNameAction::Execute() const { - // If empty name take closest ride name. - RideId rideIndex = BannerGetClosestRideIndex({ banner->position.ToCoordsXY(), 16 }); - if (rideIndex.IsNull()) + auto banner = GetBanner(_bannerIndex); + if (banner == nullptr) + { + LOG_ERROR("Banner not found for bannerIndex %d", _bannerIndex); + return Result(Status::InvalidParameters, STR_CANT_RENAME_SIGN, kStringIdNone); + } + + if (!_name.empty()) { banner->flags.unset(BannerFlag::linkedToRide); banner->rideIndex = RideId::GetNull(); - banner->text = {}; + banner->text = _name; } else { - banner->flags.set(BannerFlag::linkedToRide); - banner->rideIndex = rideIndex; - banner->text = {}; + // If empty name take closest ride name. + RideId rideIndex = BannerGetClosestRideIndex({ banner->position.ToCoordsXY(), 16 }); + if (rideIndex.IsNull()) + { + banner->flags.unset(BannerFlag::linkedToRide); + banner->rideIndex = RideId::GetNull(); + banner->text = {}; + } + else + { + banner->flags.set(BannerFlag::linkedToRide); + banner->rideIndex = rideIndex; + banner->text = {}; + } } - } - ScrollingTextInvalidate(); - GfxInvalidateScreen(); - return GameActions::Result(); -} + ScrollingTextInvalidate(); + GfxInvalidateScreen(); + return Result(); + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/SignSetNameAction.h b/src/openrct2/actions/SignSetNameAction.h index 73cbfccc9e..6965b4b7b5 100644 --- a/src/openrct2/actions/SignSetNameAction.h +++ b/src/openrct2/actions/SignSetNameAction.h @@ -11,21 +11,24 @@ #include "GameAction.h" -class SignSetNameAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - BannerIndex _bannerIndex{ BannerIndex::GetNull() }; - std::string _name; + class SignSetNameAction final : public GameActionBase + { + private: + BannerIndex _bannerIndex{ BannerIndex::GetNull() }; + std::string _name; -public: - SignSetNameAction() = default; - SignSetNameAction(BannerIndex bannerIndex, const std::string& name); + public: + SignSetNameAction() = default; + SignSetNameAction(BannerIndex bannerIndex, const std::string& name); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; -}; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/SignSetStyleAction.cpp b/src/openrct2/actions/SignSetStyleAction.cpp index a97d50db5b..103bd72451 100644 --- a/src/openrct2/actions/SignSetStyleAction.cpp +++ b/src/openrct2/actions/SignSetStyleAction.cpp @@ -20,119 +20,121 @@ #include "../world/tile_element/LargeSceneryElement.h" #include "../world/tile_element/WallElement.h" -using namespace OpenRCT2; - -SignSetStyleAction::SignSetStyleAction(BannerIndex bannerIndex, uint8_t mainColour, uint8_t textColour, bool isLarge) - : _bannerIndex(bannerIndex) - , _mainColour(mainColour) - , _textColour(textColour) - , _isLarge(isLarge) +namespace OpenRCT2::GameActions { -} - -void SignSetStyleAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit("id", _bannerIndex); - visitor.Visit("mainColour", _mainColour); - visitor.Visit("textColour", _textColour); - visitor.Visit("isLarge", _isLarge); -} - -uint16_t SignSetStyleAction::GetActionFlags() const -{ - return GameAction::GetActionFlags() | GameActions::Flags::AllowWhilePaused; -} - -void SignSetStyleAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - stream << DS_TAG(_bannerIndex) << DS_TAG(_mainColour) << DS_TAG(_textColour) << DS_TAG(_isLarge); -} - -GameActions::Result SignSetStyleAction::Query() const -{ - auto banner = GetBanner(_bannerIndex); - if (banner == nullptr) + SignSetStyleAction::SignSetStyleAction(BannerIndex bannerIndex, uint8_t mainColour, uint8_t textColour, bool isLarge) + : _bannerIndex(bannerIndex) + , _mainColour(mainColour) + , _textColour(textColour) + , _isLarge(isLarge) { - LOG_ERROR("Banner not found for bannerIndex %u", _bannerIndex); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_REPAINT_THIS, kStringIdNone); } - CoordsXYZ loc; - - if (_isLarge) + void SignSetStyleAction::AcceptParameters(GameActionParameterVisitor& visitor) { - TileElement* tileElement = BannerGetTileElement(_bannerIndex); - if (tileElement == nullptr) + visitor.Visit("id", _bannerIndex); + visitor.Visit("mainColour", _mainColour); + visitor.Visit("textColour", _textColour); + visitor.Visit("isLarge", _isLarge); + } + + uint16_t SignSetStyleAction::GetActionFlags() const + { + return GameAction::GetActionFlags() | Flags::AllowWhilePaused; + } + + void SignSetStyleAction::Serialise(DataSerialiser& stream) + { + GameAction::Serialise(stream); + stream << DS_TAG(_bannerIndex) << DS_TAG(_mainColour) << DS_TAG(_textColour) << DS_TAG(_isLarge); + } + + Result SignSetStyleAction::Query() const + { + auto banner = GetBanner(_bannerIndex); + if (banner == nullptr) { - LOG_ERROR("Banner tile element not found for bannerIndex %u", _bannerIndex); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_REPAINT_THIS, kStringIdNone); + LOG_ERROR("Banner not found for bannerIndex %u", _bannerIndex); + return Result(Status::InvalidParameters, STR_CANT_REPAINT_THIS, kStringIdNone); } - if (tileElement->GetType() != TileElementType::LargeScenery) + + CoordsXYZ loc; + + if (_isLarge) { - LOG_ERROR( - "Tile element has type %u, expected %d (LargeScenery)", tileElement->GetType(), TileElementType::LargeScenery); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_REPAINT_THIS, kStringIdNone); + TileElement* tileElement = BannerGetTileElement(_bannerIndex); + if (tileElement == nullptr) + { + LOG_ERROR("Banner tile element not found for bannerIndex %u", _bannerIndex); + return Result(Status::InvalidParameters, STR_CANT_REPAINT_THIS, kStringIdNone); + } + if (tileElement->GetType() != TileElementType::LargeScenery) + { + LOG_ERROR( + "Tile element has type %u, expected %d (LargeScenery)", tileElement->GetType(), + TileElementType::LargeScenery); + return Result(Status::InvalidParameters, STR_CANT_REPAINT_THIS, kStringIdNone); + } + loc = { banner->position.ToCoordsXY(), tileElement->GetBaseZ() }; } - loc = { banner->position.ToCoordsXY(), tileElement->GetBaseZ() }; - } - else - { - WallElement* wallElement = BannerGetScrollingWallTileElement(_bannerIndex); - - if (wallElement == nullptr) + else { - LOG_ERROR("Wall element not found for bannerIndex", _bannerIndex); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_REPAINT_THIS, kStringIdNone); + WallElement* wallElement = BannerGetScrollingWallTileElement(_bannerIndex); + + if (wallElement == nullptr) + { + LOG_ERROR("Wall element not found for bannerIndex", _bannerIndex); + return Result(Status::InvalidParameters, STR_CANT_REPAINT_THIS, kStringIdNone); + } + loc = { banner->position.ToCoordsXY(), wallElement->GetBaseZ() }; } - loc = { banner->position.ToCoordsXY(), wallElement->GetBaseZ() }; - } - if (!LocationValid(loc)) - { - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_RENAME_BANNER, STR_OFF_EDGE_OF_MAP); - } - if (!MapCanBuildAt({ loc.x, loc.y, loc.z - 16 })) - { - return GameActions::Result(GameActions::Status::NotOwned, STR_CANT_RENAME_BANNER, STR_LAND_NOT_OWNED_BY_PARK); - } - - return GameActions::Result(); -} - -GameActions::Result SignSetStyleAction::Execute() const -{ - auto banner = GetBanner(_bannerIndex); - if (banner == nullptr) - { - LOG_ERROR("Invalid banner id %u", _bannerIndex); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_REPAINT_THIS, kStringIdNone); - } - - CoordsXY coords = banner->position.ToCoordsXY(); - - if (_isLarge) - { - TileElement* tileElement = BannerGetTileElement(_bannerIndex); - if (!MapLargeScenerySignSetColour( - { coords, tileElement->GetBaseZ(), tileElement->GetDirection() }, - tileElement->AsLargeScenery()->GetSequenceIndex(), _mainColour, _textColour)) + if (!LocationValid(loc)) { - return GameActions::Result(GameActions::Status::Unknown, STR_CANT_REPAINT_THIS, kStringIdNone); + return Result(Status::InvalidParameters, STR_CANT_RENAME_BANNER, STR_OFF_EDGE_OF_MAP); } + if (!MapCanBuildAt({ loc.x, loc.y, loc.z - 16 })) + { + return Result(Status::NotOwned, STR_CANT_RENAME_BANNER, STR_LAND_NOT_OWNED_BY_PARK); + } + + return Result(); } - else + + Result SignSetStyleAction::Execute() const { - WallElement* wallElement = BannerGetScrollingWallTileElement(_bannerIndex); + auto banner = GetBanner(_bannerIndex); + if (banner == nullptr) + { + LOG_ERROR("Invalid banner id %u", _bannerIndex); + return Result(Status::InvalidParameters, STR_CANT_REPAINT_THIS, kStringIdNone); + } - wallElement->SetPrimaryColour(_mainColour); - wallElement->SetSecondaryColour(_textColour); - MapInvalidateTile({ coords, wallElement->GetBaseZ(), wallElement->GetClearanceZ() }); + CoordsXY coords = banner->position.ToCoordsXY(); + + if (_isLarge) + { + TileElement* tileElement = BannerGetTileElement(_bannerIndex); + if (!MapLargeScenerySignSetColour( + { coords, tileElement->GetBaseZ(), tileElement->GetDirection() }, + tileElement->AsLargeScenery()->GetSequenceIndex(), _mainColour, _textColour)) + { + return Result(Status::Unknown, STR_CANT_REPAINT_THIS, kStringIdNone); + } + } + else + { + WallElement* wallElement = BannerGetScrollingWallTileElement(_bannerIndex); + + wallElement->SetPrimaryColour(_mainColour); + wallElement->SetSecondaryColour(_textColour); + MapInvalidateTile({ coords, wallElement->GetBaseZ(), wallElement->GetClearanceZ() }); + } + + auto intent = Intent(INTENT_ACTION_UPDATE_BANNER); + intent.PutExtra(INTENT_EXTRA_BANNER_INDEX, _bannerIndex); + ContextBroadcastIntent(&intent); + + return Result(); } - - auto intent = Intent(INTENT_ACTION_UPDATE_BANNER); - intent.PutExtra(INTENT_EXTRA_BANNER_INDEX, _bannerIndex); - ContextBroadcastIntent(&intent); - - return GameActions::Result(); -} +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/SignSetStyleAction.h b/src/openrct2/actions/SignSetStyleAction.h index ccc5bceaf9..95502dd978 100644 --- a/src/openrct2/actions/SignSetStyleAction.h +++ b/src/openrct2/actions/SignSetStyleAction.h @@ -11,23 +11,26 @@ #include "GameAction.h" -class SignSetStyleAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - BannerIndex _bannerIndex{ BannerIndex::GetNull() }; - uint8_t _mainColour{}; - uint8_t _textColour{}; - bool _isLarge{}; + class SignSetStyleAction final : public GameActionBase + { + private: + BannerIndex _bannerIndex{ BannerIndex::GetNull() }; + uint8_t _mainColour{}; + uint8_t _textColour{}; + bool _isLarge{}; -public: - SignSetStyleAction() = default; - SignSetStyleAction(BannerIndex bannerIndex, uint8_t mainColour, uint8_t textColour, bool isLarge); + public: + SignSetStyleAction() = default; + SignSetStyleAction(BannerIndex bannerIndex, uint8_t mainColour, uint8_t textColour, bool isLarge); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; -}; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/SmallSceneryPlaceAction.cpp b/src/openrct2/actions/SmallSceneryPlaceAction.cpp index b71e3cf5f4..cdc1ebe5f3 100644 --- a/src/openrct2/actions/SmallSceneryPlaceAction.cpp +++ b/src/openrct2/actions/SmallSceneryPlaceAction.cpp @@ -33,431 +33,425 @@ #include "GameAction.h" #include "SmallSceneryRemoveAction.h" -using namespace OpenRCT2; -using namespace OpenRCT2::Numerics; - -SmallSceneryPlaceAction::SmallSceneryPlaceAction( - const CoordsXYZD& loc, uint8_t quadrant, ObjectEntryIndex sceneryType, uint8_t primaryColour, uint8_t secondaryColour, - uint8_t tertiaryColour) - : _loc(loc) - , _quadrant(quadrant) - , _sceneryType(sceneryType) - , _primaryColour(primaryColour) - , _secondaryColour(secondaryColour) - , _tertiaryColour(tertiaryColour) +namespace OpenRCT2::GameActions { -} + using namespace OpenRCT2::Numerics; -void SmallSceneryPlaceAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit(_loc); - visitor.Visit("quadrant", _quadrant); - visitor.Visit("object", _sceneryType); - visitor.Visit("primaryColour", _primaryColour); - visitor.Visit("secondaryColour", _secondaryColour); - visitor.Visit("tertiaryColour", _tertiaryColour); -} - -uint32_t SmallSceneryPlaceAction::GetCooldownTime() const -{ - return 20; -} - -uint16_t SmallSceneryPlaceAction::GetActionFlags() const -{ - return GameAction::GetActionFlags(); -} - -void SmallSceneryPlaceAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_loc) << DS_TAG(_quadrant) << DS_TAG(_sceneryType) << DS_TAG(_primaryColour) << DS_TAG(_secondaryColour) - << DS_TAG(_tertiaryColour); -} - -GameActions::Result SmallSceneryPlaceAction::Query() const -{ - bool isOnWater = false; - bool supportsRequired = false; - if (_loc.z != 0) + SmallSceneryPlaceAction::SmallSceneryPlaceAction( + const CoordsXYZD& loc, uint8_t quadrant, ObjectEntryIndex sceneryType, uint8_t primaryColour, uint8_t secondaryColour, + uint8_t tertiaryColour) + : _loc(loc) + , _quadrant(quadrant) + , _sceneryType(sceneryType) + , _primaryColour(primaryColour) + , _secondaryColour(secondaryColour) + , _tertiaryColour(tertiaryColour) { - supportsRequired = true; } - int32_t landHeight = TileElementHeight(_loc); - int16_t waterHeight = TileElementWaterHeight(_loc); - int32_t surfaceHeight = landHeight; - // If on water - if (waterHeight > 0) + void SmallSceneryPlaceAction::AcceptParameters(GameActionParameterVisitor& visitor) { - surfaceHeight = waterHeight; + visitor.Visit(_loc); + visitor.Visit("quadrant", _quadrant); + visitor.Visit("object", _sceneryType); + visitor.Visit("primaryColour", _primaryColour); + visitor.Visit("secondaryColour", _secondaryColour); + visitor.Visit("tertiaryColour", _tertiaryColour); } - auto res = GameActions::Result(); - auto centre = _loc.ToTileCentre(); - res.Position.x = centre.x; - res.Position.y = centre.y; - res.Position.z = surfaceHeight; - if (_loc.z != 0) + + uint32_t SmallSceneryPlaceAction::GetCooldownTime() const { - surfaceHeight = _loc.z; + return 20; + } + + uint16_t SmallSceneryPlaceAction::GetActionFlags() const + { + return GameAction::GetActionFlags(); + } + + void SmallSceneryPlaceAction::Serialise(DataSerialiser& stream) + { + GameAction::Serialise(stream); + + stream << DS_TAG(_loc) << DS_TAG(_quadrant) << DS_TAG(_sceneryType) << DS_TAG(_primaryColour) + << DS_TAG(_secondaryColour) << DS_TAG(_tertiaryColour); + } + + Result SmallSceneryPlaceAction::Query() const + { + bool isOnWater = false; + bool supportsRequired = false; + if (_loc.z != 0) + { + supportsRequired = true; + } + int32_t landHeight = TileElementHeight(_loc); + int16_t waterHeight = TileElementWaterHeight(_loc); + + int32_t surfaceHeight = landHeight; + // If on water + if (waterHeight > 0) + { + surfaceHeight = waterHeight; + } + auto res = Result(); + auto centre = _loc.ToTileCentre(); + res.Position.x = centre.x; + res.Position.y = centre.y; res.Position.z = surfaceHeight; - } - - if (!LocationValid(_loc)) - { - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_OFF_EDGE_OF_MAP); - } - - if (!MapCheckCapacityAndReorganise(_loc)) - { - return GameActions::Result( - GameActions::Status::NoFreeElements, STR_CANT_POSITION_THIS_HERE, STR_TILE_ELEMENT_LIMIT_REACHED); - } - - auto maxSizeMax = GetMapSizeMaxXY(); - if (!_trackDesignDrawingPreview && (_loc.x > maxSizeMax.x || _loc.y > maxSizeMax.y)) - { - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_ERR_VALUE_OUT_OF_RANGE); - } - - auto* sceneryEntry = ObjectManager::GetObjectEntry(_sceneryType); - if (sceneryEntry == nullptr) - { - LOG_ERROR("Small scenery object entry not found for sceneryType %u", _sceneryType); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_UNKNOWN_OBJECT_TYPE); - } - - auto quadrant = _quadrant; - if (sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_FULL_TILE) || !sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_DIAGONAL)) - { - if (sceneryEntry->HasFlag( - SMALL_SCENERY_FLAG_DIAGONAL | SMALL_SCENERY_FLAG_HALF_SPACE | SMALL_SCENERY_FLAG_THREE_QUARTERS)) + if (_loc.z != 0) { - quadrant = 0; - } - } - - // Check if sub tile height is any different compared to actual surface tile height - auto loc2 = _loc; - if (sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_FULL_TILE)) - { - loc2 = loc2.ToTileCentre(); - } - else - { - loc2.x += SceneryQuadrantOffsets[quadrant & 3].x; - loc2.y += SceneryQuadrantOffsets[quadrant & 3].y; - } - landHeight = TileElementHeight(loc2); - waterHeight = TileElementWaterHeight(loc2); - - surfaceHeight = landHeight; - // If on water - if (waterHeight > 0) - { - // BaseHeight2 is now the water height - surfaceHeight = waterHeight; - if (_loc.z == 0) - { - isOnWater = true; - } - } - auto targetHeight = _loc.z; - if (_loc.z == 0) - { - targetHeight = surfaceHeight; - } - - auto& gameState = getGameState(); - if (gLegacyScene != LegacyScene::scenarioEditor && !gameState.cheats.sandboxMode - && !MapIsLocationOwned({ _loc.x, _loc.y, targetHeight })) - { - return GameActions::Result(GameActions::Status::NotOwned, STR_CANT_POSITION_THIS_HERE, STR_LAND_NOT_OWNED_BY_PARK); - } - - auto* surfaceElement = MapGetSurfaceElementAt(_loc); - - if (surfaceElement != nullptr && !gameState.cheats.disableClearanceChecks && surfaceElement->GetWaterHeight() > 0) - { - int32_t water_height = surfaceElement->GetWaterHeight() - 1; - if (water_height > targetHeight) - { - return GameActions::Result( - GameActions::Status::Disallowed, STR_CANT_POSITION_THIS_HERE, STR_CANT_BUILD_THIS_UNDERWATER); - } - } - - if (!gameState.cheats.disableClearanceChecks && !(sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_STACKABLE))) - { - if (isOnWater) - { - return GameActions::Result( - GameActions::Status::Disallowed, STR_CANT_POSITION_THIS_HERE, STR_CAN_ONLY_BUILD_THIS_ON_LAND); + surfaceHeight = _loc.z; + res.Position.z = surfaceHeight; } - if (surfaceElement != nullptr && surfaceElement->GetWaterHeight() > 0) + if (!LocationValid(_loc)) { - if (surfaceElement->GetWaterHeight() > targetHeight) + return Result(Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_OFF_EDGE_OF_MAP); + } + + if (!MapCheckCapacityAndReorganise(_loc)) + { + return Result(Status::NoFreeElements, STR_CANT_POSITION_THIS_HERE, STR_TILE_ELEMENT_LIMIT_REACHED); + } + + auto maxSizeMax = GetMapSizeMaxXY(); + if (!_trackDesignDrawingPreview && (_loc.x > maxSizeMax.x || _loc.y > maxSizeMax.y)) + { + return Result(Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_ERR_VALUE_OUT_OF_RANGE); + } + + auto* sceneryEntry = ObjectManager::GetObjectEntry(_sceneryType); + if (sceneryEntry == nullptr) + { + LOG_ERROR("Small scenery object entry not found for sceneryType %u", _sceneryType); + return Result(Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_UNKNOWN_OBJECT_TYPE); + } + + auto quadrant = _quadrant; + if (sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_FULL_TILE) || !sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_DIAGONAL)) + { + if (sceneryEntry->HasFlag( + SMALL_SCENERY_FLAG_DIAGONAL | SMALL_SCENERY_FLAG_HALF_SPACE | SMALL_SCENERY_FLAG_THREE_QUARTERS)) { - return GameActions::Result( - GameActions::Status::Disallowed, STR_CANT_POSITION_THIS_HERE, STR_CAN_ONLY_BUILD_THIS_ON_LAND); + quadrant = 0; } } - } - if (!gameState.cheats.disableClearanceChecks && (sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_REQUIRE_FLAT_SURFACE)) - && !supportsRequired && !isOnWater && surfaceElement != nullptr && (surfaceElement->GetSlope() != kTileSlopeFlat)) - { - return GameActions::Result(GameActions::Status::Disallowed, STR_CANT_POSITION_THIS_HERE, STR_LEVEL_LAND_REQUIRED); - } - - if (!gameState.cheats.disableSupportLimits && !(sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_STACKABLE)) && supportsRequired) - { - if (!isOnWater) + // Check if sub tile height is any different compared to actual surface tile height + auto loc2 = _loc; + if (sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_FULL_TILE)) { - if (surfaceElement != nullptr) + loc2 = loc2.ToTileCentre(); + } + else + { + loc2.x += SceneryQuadrantOffsets[quadrant & 3].x; + loc2.y += SceneryQuadrantOffsets[quadrant & 3].y; + } + landHeight = TileElementHeight(loc2); + waterHeight = TileElementWaterHeight(loc2); + + surfaceHeight = landHeight; + // If on water + if (waterHeight > 0) + { + // BaseHeight2 is now the water height + surfaceHeight = waterHeight; + if (_loc.z == 0) { - if (surfaceElement->GetWaterHeight() > 0 || (surfaceElement->GetBaseZ()) != targetHeight) + isOnWater = true; + } + } + auto targetHeight = _loc.z; + if (_loc.z == 0) + { + targetHeight = surfaceHeight; + } + + auto& gameState = getGameState(); + if (gLegacyScene != LegacyScene::scenarioEditor && !gameState.cheats.sandboxMode + && !MapIsLocationOwned({ _loc.x, _loc.y, targetHeight })) + { + return Result(Status::NotOwned, STR_CANT_POSITION_THIS_HERE, STR_LAND_NOT_OWNED_BY_PARK); + } + + auto* surfaceElement = MapGetSurfaceElementAt(_loc); + + if (surfaceElement != nullptr && !gameState.cheats.disableClearanceChecks && surfaceElement->GetWaterHeight() > 0) + { + int32_t water_height = surfaceElement->GetWaterHeight() - 1; + if (water_height > targetHeight) + { + return Result(Status::Disallowed, STR_CANT_POSITION_THIS_HERE, STR_CANT_BUILD_THIS_UNDERWATER); + } + } + + if (!gameState.cheats.disableClearanceChecks && !(sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_STACKABLE))) + { + if (isOnWater) + { + return Result(Status::Disallowed, STR_CANT_POSITION_THIS_HERE, STR_CAN_ONLY_BUILD_THIS_ON_LAND); + } + + if (surfaceElement != nullptr && surfaceElement->GetWaterHeight() > 0) + { + if (surfaceElement->GetWaterHeight() > targetHeight) { - return GameActions::Result( - GameActions::Status::Disallowed, STR_CANT_POSITION_THIS_HERE, STR_LEVEL_LAND_REQUIRED); + return Result(Status::Disallowed, STR_CANT_POSITION_THIS_HERE, STR_CAN_ONLY_BUILD_THIS_ON_LAND); + } + } + } + + if (!gameState.cheats.disableClearanceChecks && (sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_REQUIRE_FLAT_SURFACE)) + && !supportsRequired && !isOnWater && surfaceElement != nullptr && (surfaceElement->GetSlope() != kTileSlopeFlat)) + { + return Result(Status::Disallowed, STR_CANT_POSITION_THIS_HERE, STR_LEVEL_LAND_REQUIRED); + } + + if (!gameState.cheats.disableSupportLimits && !(sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_STACKABLE)) + && supportsRequired) + { + if (!isOnWater) + { + if (surfaceElement != nullptr) + { + if (surfaceElement->GetWaterHeight() > 0 || (surfaceElement->GetBaseZ()) != targetHeight) + { + return Result(Status::Disallowed, STR_CANT_POSITION_THIS_HERE, STR_LEVEL_LAND_REQUIRED); + } + } + } + else + { + return Result(Status::Disallowed, STR_CANT_POSITION_THIS_HERE, STR_CAN_ONLY_BUILD_THIS_ON_LAND); + } + } + + int32_t zLow = targetHeight; + int32_t zHigh = zLow + ceil2(sceneryEntry->height, kCoordsZStep); + uint8_t collisionQuadrants = 0b1111; + auto quadRotation{ 0 }; + if (!(sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_FULL_TILE))) + { + quadRotation = (quadrant ^ 2); + collisionQuadrants = 0b0001; + } + if (!(sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_HALF_SPACE))) + { + if (sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_DIAGONAL) && sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_FULL_TILE)) + { + if (sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_THREE_QUARTERS)) + { + quadRotation = ((quadrant ^ 2) + _loc.direction) & 3; + collisionQuadrants = 0b1011; + } + else + { + quadRotation = (quadrant + _loc.direction) & 1; + collisionQuadrants = 0b1010; } } } else { - return GameActions::Result( - GameActions::Status::Disallowed, STR_CANT_POSITION_THIS_HERE, STR_CAN_ONLY_BUILD_THIS_ON_LAND); + quadRotation = ((quadrant ^ 2) + _loc.direction) & 3; + collisionQuadrants = 0b0011; } - } - - int32_t zLow = targetHeight; - int32_t zHigh = zLow + ceil2(sceneryEntry->height, kCoordsZStep); - uint8_t collisionQuadrants = 0b1111; - auto quadRotation{ 0 }; - if (!(sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_FULL_TILE))) - { - quadRotation = (quadrant ^ 2); - collisionQuadrants = 0b0001; - } - if (!(sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_HALF_SPACE))) - { - if (sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_DIAGONAL) && sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_FULL_TILE)) + uint8_t supports = 0; + if (!supportsRequired) { - if (sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_THREE_QUARTERS)) - { - quadRotation = ((quadrant ^ 2) + _loc.direction) & 3; - collisionQuadrants = 0b1011; - } - else - { - quadRotation = (quadrant + _loc.direction) & 1; - collisionQuadrants = 0b1010; - } + supports = 0b1111; } - } - else - { - quadRotation = ((quadrant ^ 2) + _loc.direction) & 3; - collisionQuadrants = 0b0011; - } - uint8_t supports = 0; - if (!supportsRequired) - { - supports = 0b1111; + + QuarterTile quarterTile = QuarterTile{ collisionQuadrants, supports }.Rotate(quadRotation); + const auto isTree = sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_IS_TREE); + auto canBuild = MapCanConstructWithClearAt( + { _loc, zLow, zHigh }, &MapPlaceSceneryClearFunc, quarterTile, GetFlags(), CreateCrossingMode::none, isTree); + if (canBuild.Error != Status::Ok) + { + canBuild.ErrorTitle = STR_CANT_POSITION_THIS_HERE; + return canBuild; + } + + const auto clearanceData = canBuild.GetData(); + const uint8_t groundFlags = clearanceData.GroundFlags & (ELEMENT_IS_ABOVE_GROUND | ELEMENT_IS_UNDERGROUND); + res.SetData(SmallSceneryPlaceActionResult{ groundFlags, 0, 0 }); + + res.Expenditure = ExpenditureType::landscaping; + res.Cost = sceneryEntry->price + canBuild.Cost; + + return res; } - QuarterTile quarterTile = QuarterTile{ collisionQuadrants, supports }.Rotate(quadRotation); - const auto isTree = sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_IS_TREE); - auto canBuild = MapCanConstructWithClearAt( - { _loc, zLow, zHigh }, &MapPlaceSceneryClearFunc, quarterTile, GetFlags(), CreateCrossingMode::none, isTree); - if (canBuild.Error != GameActions::Status::Ok) + Result SmallSceneryPlaceAction::Execute() const { - canBuild.ErrorTitle = STR_CANT_POSITION_THIS_HERE; - return canBuild; - } + bool supportsRequired = false; + if (_loc.z != 0) + { + supportsRequired = true; + } + int32_t landHeight = TileElementHeight(_loc); + int16_t waterHeight = TileElementWaterHeight(_loc); - const auto clearanceData = canBuild.GetData(); - const uint8_t groundFlags = clearanceData.GroundFlags & (ELEMENT_IS_ABOVE_GROUND | ELEMENT_IS_UNDERGROUND); - res.SetData(SmallSceneryPlaceActionResult{ groundFlags, 0, 0 }); - - res.Expenditure = ExpenditureType::landscaping; - res.Cost = sceneryEntry->price + canBuild.Cost; - - return res; -} - -GameActions::Result SmallSceneryPlaceAction::Execute() const -{ - bool supportsRequired = false; - if (_loc.z != 0) - { - supportsRequired = true; - } - int32_t landHeight = TileElementHeight(_loc); - int16_t waterHeight = TileElementWaterHeight(_loc); - - int32_t surfaceHeight = landHeight; - // If on water - if (waterHeight > 0) - { - surfaceHeight = waterHeight; - } - auto res = GameActions::Result(); - auto centre = _loc.ToTileCentre(); - res.Position.x = centre.x; - res.Position.y = centre.y; - res.Position.z = surfaceHeight; - if (_loc.z != 0) - { - surfaceHeight = _loc.z; + int32_t surfaceHeight = landHeight; + // If on water + if (waterHeight > 0) + { + surfaceHeight = waterHeight; + } + auto res = Result(); + auto centre = _loc.ToTileCentre(); + res.Position.x = centre.x; + res.Position.y = centre.y; res.Position.z = surfaceHeight; - } - - auto* sceneryEntry = ObjectManager::GetObjectEntry(_sceneryType); - if (sceneryEntry == nullptr) - { - LOG_ERROR("Small scenery object entry not found for sceneryType %u", _sceneryType); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_UNKNOWN_OBJECT_TYPE); - } - - auto quadrant = _quadrant; - if (sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_FULL_TILE) || !sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_DIAGONAL)) - { - if (sceneryEntry->HasFlag( - SMALL_SCENERY_FLAG_DIAGONAL | SMALL_SCENERY_FLAG_HALF_SPACE | SMALL_SCENERY_FLAG_THREE_QUARTERS)) + if (_loc.z != 0) { - quadrant = 0; + surfaceHeight = _loc.z; + res.Position.z = surfaceHeight; } - } - // Check if sub tile height is any different compared to actual surface tile height - int32_t x2 = _loc.x; - int32_t y2 = _loc.y; - if (sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_FULL_TILE)) - { - x2 += 16; - y2 += 16; - } - else - { - x2 += SceneryQuadrantOffsets[quadrant & 3].x; - y2 += SceneryQuadrantOffsets[quadrant & 3].y; - } - landHeight = TileElementHeight({ x2, y2 }); - waterHeight = TileElementWaterHeight({ x2, y2 }); - - surfaceHeight = landHeight; - // If on water - if (waterHeight > 0) - { - // BaseHeight2 is now the water height - surfaceHeight = waterHeight; - } - auto targetHeight = _loc.z; - if (_loc.z == 0) - { - targetHeight = surfaceHeight; - } - - if (!(GetFlags() & GAME_COMMAND_FLAG_GHOST)) - { - FootpathRemoveLitter({ _loc, targetHeight }); - if (!getGameState().cheats.disableClearanceChecks && (sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_NO_WALLS))) + auto* sceneryEntry = ObjectManager::GetObjectEntry(_sceneryType); + if (sceneryEntry == nullptr) { - WallRemoveAt({ _loc, targetHeight, targetHeight + sceneryEntry->height }); + LOG_ERROR("Small scenery object entry not found for sceneryType %u", _sceneryType); + return Result(Status::InvalidParameters, STR_CANT_POSITION_THIS_HERE, STR_UNKNOWN_OBJECT_TYPE); } - } - int32_t zLow = targetHeight; - int32_t zHigh = zLow + ceil2(sceneryEntry->height, 8); - uint8_t collisionQuadrants = 0b1111; - auto quadRotation{ 0 }; - if (!(sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_FULL_TILE))) - { - quadRotation = (quadrant ^ 2); - collisionQuadrants = 0b0001; - } - if (!(sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_HALF_SPACE))) - { - if (sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_DIAGONAL) && sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_FULL_TILE)) + auto quadrant = _quadrant; + if (sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_FULL_TILE) || !sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_DIAGONAL)) { - if (sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_THREE_QUARTERS)) + if (sceneryEntry->HasFlag( + SMALL_SCENERY_FLAG_DIAGONAL | SMALL_SCENERY_FLAG_HALF_SPACE | SMALL_SCENERY_FLAG_THREE_QUARTERS)) { - quadRotation = ((quadrant ^ 2) + _loc.direction) & 3; - collisionQuadrants = 0b1011; - } - else - { - quadRotation = (quadrant + _loc.direction) & 1; - collisionQuadrants = 0b1010; + quadrant = 0; } } - } - else - { - quadRotation = ((quadrant ^ 2) + _loc.direction) & 3; - collisionQuadrants = 0b0011; - } - uint8_t supports = 0; - if (!supportsRequired) - { - supports = 0b1111; - } - QuarterTile quarterTile = QuarterTile{ collisionQuadrants, supports }.Rotate(quadRotation); - const auto isTree = sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_IS_TREE); - auto canBuild = MapCanConstructWithClearAt( - { _loc, zLow, zHigh }, &MapPlaceSceneryClearFunc, quarterTile, GetFlags() | GAME_COMMAND_FLAG_APPLY, - CreateCrossingMode::none, isTree); - if (canBuild.Error != GameActions::Status::Ok) - { - canBuild.ErrorTitle = STR_CANT_POSITION_THIS_HERE; - return canBuild; + // Check if sub tile height is any different compared to actual surface tile height + int32_t x2 = _loc.x; + int32_t y2 = _loc.y; + if (sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_FULL_TILE)) + { + x2 += 16; + y2 += 16; + } + else + { + x2 += SceneryQuadrantOffsets[quadrant & 3].x; + y2 += SceneryQuadrantOffsets[quadrant & 3].y; + } + landHeight = TileElementHeight({ x2, y2 }); + waterHeight = TileElementWaterHeight({ x2, y2 }); + + surfaceHeight = landHeight; + // If on water + if (waterHeight > 0) + { + // BaseHeight2 is now the water height + surfaceHeight = waterHeight; + } + auto targetHeight = _loc.z; + if (_loc.z == 0) + { + targetHeight = surfaceHeight; + } + + if (!(GetFlags() & GAME_COMMAND_FLAG_GHOST)) + { + FootpathRemoveLitter({ _loc, targetHeight }); + if (!getGameState().cheats.disableClearanceChecks && (sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_NO_WALLS))) + { + WallRemoveAt({ _loc, targetHeight, targetHeight + sceneryEntry->height }); + } + } + + int32_t zLow = targetHeight; + int32_t zHigh = zLow + ceil2(sceneryEntry->height, 8); + uint8_t collisionQuadrants = 0b1111; + auto quadRotation{ 0 }; + if (!(sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_FULL_TILE))) + { + quadRotation = (quadrant ^ 2); + collisionQuadrants = 0b0001; + } + if (!(sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_HALF_SPACE))) + { + if (sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_DIAGONAL) && sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_FULL_TILE)) + { + if (sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_THREE_QUARTERS)) + { + quadRotation = ((quadrant ^ 2) + _loc.direction) & 3; + collisionQuadrants = 0b1011; + } + else + { + quadRotation = (quadrant + _loc.direction) & 1; + collisionQuadrants = 0b1010; + } + } + } + else + { + quadRotation = ((quadrant ^ 2) + _loc.direction) & 3; + collisionQuadrants = 0b0011; + } + uint8_t supports = 0; + if (!supportsRequired) + { + supports = 0b1111; + } + + QuarterTile quarterTile = QuarterTile{ collisionQuadrants, supports }.Rotate(quadRotation); + const auto isTree = sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_IS_TREE); + auto canBuild = MapCanConstructWithClearAt( + { _loc, zLow, zHigh }, &MapPlaceSceneryClearFunc, quarterTile, GetFlags() | GAME_COMMAND_FLAG_APPLY, + CreateCrossingMode::none, isTree); + if (canBuild.Error != Status::Ok) + { + canBuild.ErrorTitle = STR_CANT_POSITION_THIS_HERE; + return canBuild; + } + + res.Expenditure = ExpenditureType::landscaping; + res.Cost = sceneryEntry->price + canBuild.Cost; + + auto* sceneryElement = TileElementInsert( + CoordsXYZ{ _loc, zLow }, quarterTile.GetBaseQuarterOccupied()); + if (sceneryElement == nullptr) + { + return Result(Status::NoFreeElements, STR_CANT_POSITION_THIS_HERE, STR_TILE_ELEMENT_LIMIT_REACHED); + } + + sceneryElement->SetDirection(_loc.direction); + sceneryElement->SetSceneryQuadrant(quadrant); + sceneryElement->SetEntryIndex(_sceneryType); + sceneryElement->SetAge(0); + sceneryElement->SetPrimaryColour(_primaryColour); + sceneryElement->SetSecondaryColour(_secondaryColour); + sceneryElement->SetTertiaryColour(_tertiaryColour); + sceneryElement->SetClearanceZ(sceneryElement->GetBaseZ() + sceneryEntry->height + 7); + sceneryElement->SetGhost(GetFlags() & GAME_COMMAND_FLAG_GHOST); + if (supportsRequired) + { + sceneryElement->SetNeedsSupports(); + } + + const auto clearanceData = canBuild.GetData(); + const uint8_t groundFlags = clearanceData.GroundFlags & (ELEMENT_IS_ABOVE_GROUND | ELEMENT_IS_UNDERGROUND); + res.SetData( + SmallSceneryPlaceActionResult{ groundFlags, sceneryElement->GetBaseZ(), sceneryElement->GetSceneryQuadrant() }); + + MapInvalidateTileFull(_loc); + if (sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_IS_CLOCK)) + { + MapAnimations::MarkTileForUpdate(TileCoordsXY(_loc)); + } + else if (sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_ANIMATED)) + { + MapAnimations::MarkTileForInvalidation(TileCoordsXY(_loc)); + } + + return res; } - - res.Expenditure = ExpenditureType::landscaping; - res.Cost = sceneryEntry->price + canBuild.Cost; - - auto* sceneryElement = TileElementInsert( - CoordsXYZ{ _loc, zLow }, quarterTile.GetBaseQuarterOccupied()); - if (sceneryElement == nullptr) - { - return GameActions::Result( - GameActions::Status::NoFreeElements, STR_CANT_POSITION_THIS_HERE, STR_TILE_ELEMENT_LIMIT_REACHED); - } - - sceneryElement->SetDirection(_loc.direction); - sceneryElement->SetSceneryQuadrant(quadrant); - sceneryElement->SetEntryIndex(_sceneryType); - sceneryElement->SetAge(0); - sceneryElement->SetPrimaryColour(_primaryColour); - sceneryElement->SetSecondaryColour(_secondaryColour); - sceneryElement->SetTertiaryColour(_tertiaryColour); - sceneryElement->SetClearanceZ(sceneryElement->GetBaseZ() + sceneryEntry->height + 7); - sceneryElement->SetGhost(GetFlags() & GAME_COMMAND_FLAG_GHOST); - if (supportsRequired) - { - sceneryElement->SetNeedsSupports(); - } - - const auto clearanceData = canBuild.GetData(); - const uint8_t groundFlags = clearanceData.GroundFlags & (ELEMENT_IS_ABOVE_GROUND | ELEMENT_IS_UNDERGROUND); - res.SetData(SmallSceneryPlaceActionResult{ groundFlags, sceneryElement->GetBaseZ(), sceneryElement->GetSceneryQuadrant() }); - - MapInvalidateTileFull(_loc); - if (sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_IS_CLOCK)) - { - MapAnimations::MarkTileForUpdate(TileCoordsXY(_loc)); - } - else if (sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_ANIMATED)) - { - MapAnimations::MarkTileForInvalidation(TileCoordsXY(_loc)); - } - - return res; -} +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/SmallSceneryPlaceAction.h b/src/openrct2/actions/SmallSceneryPlaceAction.h index a55cd96830..acb4f7e6e6 100644 --- a/src/openrct2/actions/SmallSceneryPlaceAction.h +++ b/src/openrct2/actions/SmallSceneryPlaceAction.h @@ -11,35 +11,38 @@ #include "GameAction.h" -struct SmallSceneryPlaceActionResult +namespace OpenRCT2::GameActions { - uint8_t GroundFlags{}; - int32_t BaseHeight{}; - uint8_t SceneryQuadrant{}; -}; + struct SmallSceneryPlaceActionResult + { + uint8_t GroundFlags{}; + int32_t BaseHeight{}; + uint8_t SceneryQuadrant{}; + }; -class SmallSceneryPlaceAction final : public GameActionBase -{ -private: - CoordsXYZD _loc; - uint8_t _quadrant{}; - OpenRCT2::ObjectEntryIndex _sceneryType{}; - uint8_t _primaryColour{}; - uint8_t _secondaryColour{}; - uint8_t _tertiaryColour{}; + class SmallSceneryPlaceAction final : public GameActionBase + { + private: + CoordsXYZD _loc; + uint8_t _quadrant{}; + ObjectEntryIndex _sceneryType{}; + uint8_t _primaryColour{}; + uint8_t _secondaryColour{}; + uint8_t _tertiaryColour{}; -public: - SmallSceneryPlaceAction() = default; - SmallSceneryPlaceAction( - const CoordsXYZD& loc, uint8_t quadrant, OpenRCT2::ObjectEntryIndex sceneryType, uint8_t primaryColour, - uint8_t secondaryColour, uint8_t tertiaryColour); + public: + SmallSceneryPlaceAction() = default; + SmallSceneryPlaceAction( + const CoordsXYZD& loc, uint8_t quadrant, ObjectEntryIndex sceneryType, uint8_t primaryColour, + uint8_t secondaryColour, uint8_t tertiaryColour); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint32_t GetCooldownTime() const override; - uint16_t GetActionFlags() const override; + uint32_t GetCooldownTime() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; -}; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/SmallSceneryRemoveAction.cpp b/src/openrct2/actions/SmallSceneryRemoveAction.cpp index b241f99610..b425bcbb6c 100644 --- a/src/openrct2/actions/SmallSceneryRemoveAction.cpp +++ b/src/openrct2/actions/SmallSceneryRemoveAction.cpp @@ -25,139 +25,137 @@ #include "GameAction.h" #include "SmallSceneryPlaceAction.h" -using namespace OpenRCT2; - -SmallSceneryRemoveAction::SmallSceneryRemoveAction(const CoordsXYZ& location, uint8_t quadrant, ObjectEntryIndex sceneryType) - : _loc(location) - , _quadrant(quadrant) - , _sceneryType(sceneryType) +namespace OpenRCT2::GameActions { -} - -void SmallSceneryRemoveAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit(_loc); - visitor.Visit("object", _sceneryType); - visitor.Visit("quadrant", _quadrant); -} - -uint16_t SmallSceneryRemoveAction::GetActionFlags() const -{ - return GameAction::GetActionFlags(); -} - -void SmallSceneryRemoveAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_loc) << DS_TAG(_quadrant) << DS_TAG(_sceneryType); -} - -GameActions::Result SmallSceneryRemoveAction::Query() const -{ - GameActions::Result res = GameActions::Result(); - - if (!LocationValid(_loc)) + SmallSceneryRemoveAction::SmallSceneryRemoveAction( + const CoordsXYZ& location, uint8_t quadrant, ObjectEntryIndex sceneryType) + : _loc(location) + , _quadrant(quadrant) + , _sceneryType(sceneryType) { - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_REMOVE_THIS, STR_OFF_EDGE_OF_MAP); } - auto* entry = OpenRCT2::ObjectManager::GetObjectEntry(_sceneryType); - if (entry == nullptr) + void SmallSceneryRemoveAction::AcceptParameters(GameActionParameterVisitor& visitor) { - LOG_ERROR("Invalid small scenery type %u", _sceneryType); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_REMOVE_THIS, STR_INVALID_SELECTION_OF_OBJECTS); + visitor.Visit(_loc); + visitor.Visit("object", _sceneryType); + visitor.Visit("quadrant", _quadrant); } - res.Cost = entry->removal_price; - res.Expenditure = ExpenditureType::landscaping; - res.Position = _loc; - - if (gLegacyScene != LegacyScene::scenarioEditor && !(GetFlags() & GAME_COMMAND_FLAG_GHOST) - && !getGameState().cheats.sandboxMode) + uint16_t SmallSceneryRemoveAction::GetActionFlags() const { - // Check if allowed to remove item - if (getGameState().park.flags & PARK_FLAGS_FORBID_TREE_REMOVAL) + return GameAction::GetActionFlags(); + } + + void SmallSceneryRemoveAction::Serialise(DataSerialiser& stream) + { + GameAction::Serialise(stream); + + stream << DS_TAG(_loc) << DS_TAG(_quadrant) << DS_TAG(_sceneryType); + } + + Result SmallSceneryRemoveAction::Query() const + { + Result res = Result(); + + if (!LocationValid(_loc)) { - if (entry->HasFlag(SMALL_SCENERY_FLAG_IS_TREE)) + return Result(Status::InvalidParameters, STR_CANT_REMOVE_THIS, STR_OFF_EDGE_OF_MAP); + } + + auto* entry = OpenRCT2::ObjectManager::GetObjectEntry(_sceneryType); + if (entry == nullptr) + { + LOG_ERROR("Invalid small scenery type %u", _sceneryType); + return Result(Status::InvalidParameters, STR_CANT_REMOVE_THIS, STR_INVALID_SELECTION_OF_OBJECTS); + } + + res.Cost = entry->removal_price; + res.Expenditure = ExpenditureType::landscaping; + res.Position = _loc; + + if (gLegacyScene != LegacyScene::scenarioEditor && !(GetFlags() & GAME_COMMAND_FLAG_GHOST) + && !getGameState().cheats.sandboxMode) + { + // Check if allowed to remove item + if (getGameState().park.flags & PARK_FLAGS_FORBID_TREE_REMOVAL) { - res.Error = GameActions::Status::NoClearance; + if (entry->HasFlag(SMALL_SCENERY_FLAG_IS_TREE)) + { + res.Error = Status::NoClearance; + res.ErrorTitle = STR_CANT_REMOVE_THIS; + res.ErrorMessage = STR_FORBIDDEN_BY_THE_LOCAL_AUTHORITY; + return res; + } + } + + // Check if the land is owned + if (!MapIsLocationOwned(_loc)) + { + res.Error = Status::NoClearance; res.ErrorTitle = STR_CANT_REMOVE_THIS; - res.ErrorMessage = STR_FORBIDDEN_BY_THE_LOCAL_AUTHORITY; + res.ErrorMessage = STR_LAND_NOT_OWNED_BY_PARK; return res; } } - // Check if the land is owned - if (!MapIsLocationOwned(_loc)) + TileElement* tileElement = FindSceneryElement(); + if (tileElement == nullptr) { - res.Error = GameActions::Status::NoClearance; - res.ErrorTitle = STR_CANT_REMOVE_THIS; - res.ErrorMessage = STR_LAND_NOT_OWNED_BY_PARK; - return res; + LOG_ERROR("Small scenery of type %u not found at x = %d, y = %d, z = &d", _sceneryType, _loc.x, _loc.y, _loc.z); + return Result(Status::InvalidParameters, STR_CANT_REMOVE_THIS, STR_INVALID_SELECTION_OF_OBJECTS); } + + return res; } - TileElement* tileElement = FindSceneryElement(); - if (tileElement == nullptr) + Result SmallSceneryRemoveAction::Execute() const { - LOG_ERROR("Small scenery of type %u not found at x = %d, y = %d, z = &d", _sceneryType, _loc.x, _loc.y, _loc.z); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_REMOVE_THIS, STR_INVALID_SELECTION_OF_OBJECTS); + Result res = Result(); + + auto* entry = OpenRCT2::ObjectManager::GetObjectEntry(_sceneryType); + if (entry == nullptr) + { + LOG_ERROR("Invalid small scenery type %u", _sceneryType); + return Result(Status::InvalidParameters, STR_CANT_REMOVE_THIS, STR_INVALID_SELECTION_OF_OBJECTS); + } + + res.Cost = entry->removal_price; + res.Expenditure = ExpenditureType::landscaping; + res.Position = _loc; + + TileElement* tileElement = FindSceneryElement(); + if (tileElement == nullptr) + { + return Result(Status::InvalidParameters, STR_CANT_REMOVE_THIS, STR_INVALID_SELECTION_OF_OBJECTS); + } + + MapInvalidateTileFull(_loc); + TileElementRemove(tileElement); + + return res; } - return res; -} - -GameActions::Result SmallSceneryRemoveAction::Execute() const -{ - GameActions::Result res = GameActions::Result(); - - auto* entry = OpenRCT2::ObjectManager::GetObjectEntry(_sceneryType); - if (entry == nullptr) + TileElement* SmallSceneryRemoveAction::FindSceneryElement() const { - LOG_ERROR("Invalid small scenery type %u", _sceneryType); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_REMOVE_THIS, STR_INVALID_SELECTION_OF_OBJECTS); + const bool isGhost = GetFlags() & GAME_COMMAND_FLAG_GHOST; + for (auto* sceneryElement : TileElementsView(_loc)) + { + // If we are removing ghost elements + if (isGhost && sceneryElement->IsGhost() == false) + continue; + + if (sceneryElement->GetSceneryQuadrant() != _quadrant) + continue; + + if (sceneryElement->GetBaseZ() != _loc.z) + continue; + + if (sceneryElement->GetEntryIndex() != _sceneryType) + continue; + + return sceneryElement->as(); + } + return nullptr; } - - res.Cost = entry->removal_price; - res.Expenditure = ExpenditureType::landscaping; - res.Position = _loc; - - TileElement* tileElement = FindSceneryElement(); - if (tileElement == nullptr) - { - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_REMOVE_THIS, STR_INVALID_SELECTION_OF_OBJECTS); - } - - MapInvalidateTileFull(_loc); - TileElementRemove(tileElement); - - return res; -} - -TileElement* SmallSceneryRemoveAction::FindSceneryElement() const -{ - const bool isGhost = GetFlags() & GAME_COMMAND_FLAG_GHOST; - for (auto* sceneryElement : TileElementsView(_loc)) - { - // If we are removing ghost elements - if (isGhost && sceneryElement->IsGhost() == false) - continue; - - if (sceneryElement->GetSceneryQuadrant() != _quadrant) - continue; - - if (sceneryElement->GetBaseZ() != _loc.z) - continue; - - if (sceneryElement->GetEntryIndex() != _sceneryType) - continue; - - return sceneryElement->as(); - } - return nullptr; -} +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/SmallSceneryRemoveAction.h b/src/openrct2/actions/SmallSceneryRemoveAction.h index 4dc377cde0..3636599d1e 100644 --- a/src/openrct2/actions/SmallSceneryRemoveAction.h +++ b/src/openrct2/actions/SmallSceneryRemoveAction.h @@ -11,25 +11,28 @@ #include "GameAction.h" -class SmallSceneryRemoveAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - CoordsXYZ _loc; - uint8_t _quadrant{}; - OpenRCT2::ObjectEntryIndex _sceneryType{}; + class SmallSceneryRemoveAction final : public GameActionBase + { + private: + CoordsXYZ _loc; + uint8_t _quadrant{}; + ObjectEntryIndex _sceneryType{}; -public: - SmallSceneryRemoveAction() = default; - SmallSceneryRemoveAction(const CoordsXYZ& location, uint8_t quadrant, OpenRCT2::ObjectEntryIndex sceneryType); + public: + SmallSceneryRemoveAction() = default; + SmallSceneryRemoveAction(const CoordsXYZ& location, uint8_t quadrant, ObjectEntryIndex sceneryType); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; -private: - OpenRCT2::TileElement* FindSceneryElement() const; -}; + private: + TileElement* FindSceneryElement() const; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/SmallScenerySetColourAction.cpp b/src/openrct2/actions/SmallScenerySetColourAction.cpp index 40ac2a47e3..2b35c05754 100644 --- a/src/openrct2/actions/SmallScenerySetColourAction.cpp +++ b/src/openrct2/actions/SmallScenerySetColourAction.cpp @@ -21,96 +21,97 @@ #include "../world/Park.h" #include "../world/tile_element/SmallSceneryElement.h" -using namespace OpenRCT2; - -SmallScenerySetColourAction::SmallScenerySetColourAction( - const CoordsXYZ& loc, uint8_t quadrant, ObjectEntryIndex sceneryType, uint8_t primaryColour, uint8_t secondaryColour, - uint8_t tertiaryColour) - : _loc(loc) - , _quadrant(quadrant) - , _sceneryType(sceneryType) - , _primaryColour(primaryColour) - , _secondaryColour(secondaryColour) - , _tertiaryColour(tertiaryColour) +namespace OpenRCT2::GameActions { -} - -void SmallScenerySetColourAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit(_loc); - visitor.Visit("quadrant", _quadrant); - visitor.Visit("sceneryType", _sceneryType); - visitor.Visit("primaryColour", _primaryColour); - visitor.Visit("secondaryColour", _secondaryColour); - visitor.Visit("tertiaryColour", _tertiaryColour); -} - -uint16_t SmallScenerySetColourAction::GetActionFlags() const -{ - return GameAction::GetActionFlags() | GameActions::Flags::AllowWhilePaused; -} - -void SmallScenerySetColourAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_loc) << DS_TAG(_quadrant) << DS_TAG(_sceneryType) << DS_TAG(_primaryColour) << DS_TAG(_secondaryColour) - << DS_TAG(_tertiaryColour); -} - -GameActions::Result SmallScenerySetColourAction::Query() const -{ - return QueryExecute(false); -} - -GameActions::Result SmallScenerySetColourAction::Execute() const -{ - return QueryExecute(true); -} - -GameActions::Result SmallScenerySetColourAction::QueryExecute(bool isExecuting) const -{ - auto res = GameActions::Result(); - res.Expenditure = ExpenditureType::landscaping; - res.Position.x = _loc.x + 16; - res.Position.y = _loc.y + 16; - res.Position.z = _loc.z; - res.ErrorTitle = STR_CANT_REPAINT_THIS; - - if (!LocationValid(_loc)) + SmallScenerySetColourAction::SmallScenerySetColourAction( + const CoordsXYZ& loc, uint8_t quadrant, ObjectEntryIndex sceneryType, uint8_t primaryColour, uint8_t secondaryColour, + uint8_t tertiaryColour) + : _loc(loc) + , _quadrant(quadrant) + , _sceneryType(sceneryType) + , _primaryColour(primaryColour) + , _secondaryColour(secondaryColour) + , _tertiaryColour(tertiaryColour) { - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_REPAINT_THIS, STR_OFF_EDGE_OF_MAP); } - if (gLegacyScene != LegacyScene::scenarioEditor && !getGameState().cheats.sandboxMode) + void SmallScenerySetColourAction::AcceptParameters(GameActionParameterVisitor& visitor) { - if (!MapIsLocationOwned(_loc)) + visitor.Visit(_loc); + visitor.Visit("quadrant", _quadrant); + visitor.Visit("sceneryType", _sceneryType); + visitor.Visit("primaryColour", _primaryColour); + visitor.Visit("secondaryColour", _secondaryColour); + visitor.Visit("tertiaryColour", _tertiaryColour); + } + + uint16_t SmallScenerySetColourAction::GetActionFlags() const + { + return GameAction::GetActionFlags() | Flags::AllowWhilePaused; + } + + void SmallScenerySetColourAction::Serialise(DataSerialiser& stream) + { + GameAction::Serialise(stream); + + stream << DS_TAG(_loc) << DS_TAG(_quadrant) << DS_TAG(_sceneryType) << DS_TAG(_primaryColour) + << DS_TAG(_secondaryColour) << DS_TAG(_tertiaryColour); + } + + Result SmallScenerySetColourAction::Query() const + { + return QueryExecute(false); + } + + Result SmallScenerySetColourAction::Execute() const + { + return QueryExecute(true); + } + + Result SmallScenerySetColourAction::QueryExecute(bool isExecuting) const + { + auto res = Result(); + res.Expenditure = ExpenditureType::landscaping; + res.Position.x = _loc.x + 16; + res.Position.y = _loc.y + 16; + res.Position.z = _loc.z; + res.ErrorTitle = STR_CANT_REPAINT_THIS; + + if (!LocationValid(_loc)) { - return GameActions::Result(GameActions::Status::NotOwned, STR_CANT_REPAINT_THIS, STR_LAND_NOT_OWNED_BY_PARK); + return Result(Status::InvalidParameters, STR_CANT_REPAINT_THIS, STR_OFF_EDGE_OF_MAP); } - } - auto sceneryElement = MapGetSmallSceneryElementAt(_loc, _sceneryType, _quadrant); + if (gLegacyScene != LegacyScene::scenarioEditor && !getGameState().cheats.sandboxMode) + { + if (!MapIsLocationOwned(_loc)) + { + return Result(Status::NotOwned, STR_CANT_REPAINT_THIS, STR_LAND_NOT_OWNED_BY_PARK); + } + } - if (sceneryElement == nullptr) - { - LOG_ERROR("Small scenery not found at: x = %d, y = %d, z = %d", _loc.x, _loc.y, _loc.z); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_REPAINT_THIS, kStringIdNone); - } + auto sceneryElement = MapGetSmallSceneryElementAt(_loc, _sceneryType, _quadrant); + + if (sceneryElement == nullptr) + { + LOG_ERROR("Small scenery not found at: x = %d, y = %d, z = %d", _loc.x, _loc.y, _loc.z); + return Result(Status::InvalidParameters, STR_CANT_REPAINT_THIS, kStringIdNone); + } + + if ((GetFlags() & GAME_COMMAND_FLAG_GHOST) && !(sceneryElement->IsGhost())) + { + return res; + } + + if (isExecuting) + { + sceneryElement->SetPrimaryColour(_primaryColour); + sceneryElement->SetSecondaryColour(_secondaryColour); + sceneryElement->SetTertiaryColour(_tertiaryColour); + + MapInvalidateTileFull(_loc); + } - if ((GetFlags() & GAME_COMMAND_FLAG_GHOST) && !(sceneryElement->IsGhost())) - { return res; } - - if (isExecuting) - { - sceneryElement->SetPrimaryColour(_primaryColour); - sceneryElement->SetSecondaryColour(_secondaryColour); - sceneryElement->SetTertiaryColour(_tertiaryColour); - - MapInvalidateTileFull(_loc); - } - - return res; -} +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/SmallScenerySetColourAction.h b/src/openrct2/actions/SmallScenerySetColourAction.h index fc7249fa93..292e641eab 100644 --- a/src/openrct2/actions/SmallScenerySetColourAction.h +++ b/src/openrct2/actions/SmallScenerySetColourAction.h @@ -11,30 +11,33 @@ #include "GameAction.h" -class SmallScenerySetColourAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - CoordsXYZ _loc; - uint8_t _quadrant{}; - OpenRCT2::ObjectEntryIndex _sceneryType{}; - uint8_t _primaryColour{}; - uint8_t _secondaryColour{}; - uint8_t _tertiaryColour{}; + class SmallScenerySetColourAction final : public GameActionBase + { + private: + CoordsXYZ _loc; + uint8_t _quadrant{}; + ObjectEntryIndex _sceneryType{}; + uint8_t _primaryColour{}; + uint8_t _secondaryColour{}; + uint8_t _tertiaryColour{}; -public: - SmallScenerySetColourAction() = default; - SmallScenerySetColourAction( - const CoordsXYZ& loc, uint8_t quadrant, OpenRCT2::ObjectEntryIndex sceneryType, uint8_t primaryColour, - uint8_t secondaryColour, uint8_t tertiaryColour); + public: + SmallScenerySetColourAction() = default; + SmallScenerySetColourAction( + const CoordsXYZ& loc, uint8_t quadrant, ObjectEntryIndex sceneryType, uint8_t primaryColour, + uint8_t secondaryColour, uint8_t tertiaryColour); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; -private: - OpenRCT2::GameActions::Result QueryExecute(bool isExecuting) const; -}; + private: + Result QueryExecute(bool isExecuting) const; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/StaffFireAction.cpp b/src/openrct2/actions/StaffFireAction.cpp index 1d055eecf0..5cc4830379 100644 --- a/src/openrct2/actions/StaffFireAction.cpp +++ b/src/openrct2/actions/StaffFireAction.cpp @@ -14,72 +14,72 @@ #include "../entity/Staff.h" #include "../ui/WindowManager.h" -using namespace OpenRCT2; - -StaffFireAction::StaffFireAction(EntityId spriteId) - : _spriteId(spriteId) +namespace OpenRCT2::GameActions { -} - -void StaffFireAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit("id", _spriteId); -} - -uint16_t StaffFireAction::GetActionFlags() const -{ - return GameAction::GetActionFlags() | GameActions::Flags::AllowWhilePaused; -} - -void StaffFireAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - stream << DS_TAG(_spriteId); -} - -GameActions::Result StaffFireAction::Query() const -{ - if (_spriteId.ToUnderlying() >= kMaxEntities || _spriteId.IsNull()) + StaffFireAction::StaffFireAction(EntityId spriteId) + : _spriteId(spriteId) { - LOG_ERROR("Invalid spriteId %u", _spriteId); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_VALUE_OUT_OF_RANGE); } - auto staff = TryGetEntity(_spriteId); - if (staff == nullptr) + void StaffFireAction::AcceptParameters(GameActionParameterVisitor& visitor) { - LOG_ERROR("Staff entity not found for spriteId %u", _spriteId); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_STAFF_NOT_FOUND); + visitor.Visit("id", _spriteId); } - if (staff->State == PeepState::Fixing) + uint16_t StaffFireAction::GetActionFlags() const { - return GameActions::Result(GameActions::Status::Disallowed, STR_CANT_FIRE_STAFF_FIXING, kStringIdNone); - } - else if (staff->State == PeepState::Inspecting) - { - return GameActions::Result(GameActions::Status::Disallowed, STR_CANT_FIRE_STAFF_INSPECTING, kStringIdNone); + return GameAction::GetActionFlags() | Flags::AllowWhilePaused; } - return GameActions::Result(); -} - -GameActions::Result StaffFireAction::Execute() const -{ - auto staff = TryGetEntity(_spriteId); - if (staff == nullptr) + void StaffFireAction::Serialise(DataSerialiser& stream) { - LOG_ERROR("Staff entity not found for spriteId %u", _spriteId); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_STAFF_NOT_FOUND); + GameAction::Serialise(stream); + stream << DS_TAG(_spriteId); } - auto* windowMgr = Ui::GetWindowManager(); - windowMgr->CloseByClass(WindowClass::FirePrompt); + Result StaffFireAction::Query() const + { + if (_spriteId.ToUnderlying() >= kMaxEntities || _spriteId.IsNull()) + { + LOG_ERROR("Invalid spriteId %u", _spriteId); + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_VALUE_OUT_OF_RANGE); + } - PeepEntityRemove(staff); - // Due to patrol areas best to invalidate the whole screen on removal of staff - GfxInvalidateScreen(); + auto staff = TryGetEntity(_spriteId); + if (staff == nullptr) + { + LOG_ERROR("Staff entity not found for spriteId %u", _spriteId); + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_STAFF_NOT_FOUND); + } - return GameActions::Result(); -} + if (staff->State == PeepState::Fixing) + { + return Result(Status::Disallowed, STR_CANT_FIRE_STAFF_FIXING, kStringIdNone); + } + else if (staff->State == PeepState::Inspecting) + { + return Result(Status::Disallowed, STR_CANT_FIRE_STAFF_INSPECTING, kStringIdNone); + } + + return Result(); + } + + Result StaffFireAction::Execute() const + { + auto staff = TryGetEntity(_spriteId); + if (staff == nullptr) + { + LOG_ERROR("Staff entity not found for spriteId %u", _spriteId); + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_STAFF_NOT_FOUND); + } + + auto* windowMgr = Ui::GetWindowManager(); + windowMgr->CloseByClass(WindowClass::FirePrompt); + + PeepEntityRemove(staff); + // Due to patrol areas best to invalidate the whole screen on removal of staff + GfxInvalidateScreen(); + + return Result(); + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/StaffFireAction.h b/src/openrct2/actions/StaffFireAction.h index 276a4e0793..00e9a2d910 100644 --- a/src/openrct2/actions/StaffFireAction.h +++ b/src/openrct2/actions/StaffFireAction.h @@ -11,20 +11,23 @@ #include "GameAction.h" -class StaffFireAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - EntityId _spriteId{ EntityId::GetNull() }; + class StaffFireAction final : public GameActionBase + { + private: + EntityId _spriteId{ EntityId::GetNull() }; -public: - StaffFireAction() = default; - StaffFireAction(EntityId spriteId); + public: + StaffFireAction() = default; + StaffFireAction(EntityId spriteId); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; -}; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/StaffHireNewAction.cpp b/src/openrct2/actions/StaffHireNewAction.cpp index 7d5a3e4948..2da9417bbe 100644 --- a/src/openrct2/actions/StaffHireNewAction.cpp +++ b/src/openrct2/actions/StaffHireNewAction.cpp @@ -30,275 +30,275 @@ #include -using namespace OpenRCT2; - -StaffHireNewAction::StaffHireNewAction( - bool autoPosition, StaffType staffType, ObjectEntryIndex costumeIndex, uint32_t staffOrders) - : _autoPosition(autoPosition) - , _staffType(static_cast(staffType)) - , _costumeIndex(costumeIndex) - , _staffOrders(staffOrders) +namespace OpenRCT2::GameActions { -} - -void StaffHireNewAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit("autoPosition", _autoPosition); - visitor.Visit("staffType", _staffType); - visitor.Visit("costumeIndex", _costumeIndex); - visitor.Visit("staffOrders", _staffOrders); -} - -uint16_t StaffHireNewAction::GetActionFlags() const -{ - return GameAction::GetActionFlags() | GameActions::Flags::AllowWhilePaused; -} - -void StaffHireNewAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_autoPosition) << DS_TAG(_staffType) << DS_TAG(_costumeIndex) << DS_TAG(_staffOrders); -} - -GameActions::Result StaffHireNewAction::Query() const -{ - return QueryExecute(false); -} - -GameActions::Result StaffHireNewAction::Execute() const -{ - return QueryExecute(true); -} - -GameActions::Result StaffHireNewAction::QueryExecute(bool execute) const -{ - auto res = GameActions::Result(); - res.Expenditure = ExpenditureType::wages; - - if (_staffType >= static_cast(StaffType::Count)) + StaffHireNewAction::StaffHireNewAction( + bool autoPosition, StaffType staffType, ObjectEntryIndex costumeIndex, uint32_t staffOrders) + : _autoPosition(autoPosition) + , _staffType(static_cast(staffType)) + , _costumeIndex(costumeIndex) + , _staffOrders(staffOrders) { - LOG_ERROR("Invalid staff type %u", static_cast(_staffType)); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_HIRE_NEW_STAFF, STR_ERR_VALUE_OUT_OF_RANGE); } - if (GetNumFreeEntities() < 400) + void StaffHireNewAction::AcceptParameters(GameActionParameterVisitor& visitor) { - return GameActions::Result(GameActions::Status::NoFreeElements, STR_CANT_HIRE_NEW_STAFF, STR_TOO_MANY_PEOPLE_IN_GAME); + visitor.Visit("autoPosition", _autoPosition); + visitor.Visit("staffType", _staffType); + visitor.Visit("costumeIndex", _costumeIndex); + visitor.Visit("staffOrders", _staffOrders); } - if (_staffType == static_cast(StaffType::Entertainer)) + uint16_t StaffHireNewAction::GetActionFlags() const { - auto costumes = findAllPeepAnimationsIndexesForType(AnimationPeepType::Entertainer); - if (std::find(costumes.begin(), costumes.end(), _costumeIndex) == costumes.end()) + return GameAction::GetActionFlags() | Flags::AllowWhilePaused; + } + + void StaffHireNewAction::Serialise(DataSerialiser& stream) + { + GameAction::Serialise(stream); + + stream << DS_TAG(_autoPosition) << DS_TAG(_staffType) << DS_TAG(_costumeIndex) << DS_TAG(_staffOrders); + } + + Result StaffHireNewAction::Query() const + { + return QueryExecute(false); + } + + Result StaffHireNewAction::Execute() const + { + return QueryExecute(true); + } + + Result StaffHireNewAction::QueryExecute(bool execute) const + { + auto res = Result(); + res.Expenditure = ExpenditureType::wages; + + if (_staffType >= static_cast(StaffType::Count)) { - LOG_ERROR("Unavailable entertainer costume %u", static_cast(_costumeIndex)); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_HIRE_NEW_STAFF, STR_ERR_VALUE_OUT_OF_RANGE); - } - } - - Staff* newPeep = CreateEntity(); - if (newPeep == nullptr) - { - // Too many peeps exist already. - return GameActions::Result(GameActions::Status::NoFreeElements, STR_CANT_HIRE_NEW_STAFF, STR_TOO_MANY_PEOPLE_IN_GAME); - } - - if (execute == false) - { - // In query we just want to see if we can obtain a sprite slot. - EntityRemove(newPeep); - - res.SetData(StaffHireNewActionResult{ EntityId::GetNull() }); - } - else - { - newPeep->WindowInvalidateFlags = 0; - newPeep->Action = PeepActionType::Walking; - newPeep->SpecialSprite = 0; - newPeep->AnimationImageIdOffset = 0; - newPeep->WalkingAnimationFrameNum = 0; - newPeep->AnimationType = PeepAnimationType::Walking; - newPeep->PathCheckOptimisation = 0; - newPeep->PeepFlags = 0; - newPeep->StaffLawnsMown = 0; - newPeep->StaffGardensWatered = 0; - newPeep->StaffLitterSwept = 0; - newPeep->StaffBinsEmptied = 0; - newPeep->StaffOrders = _staffOrders; - - // We search for the first available Id for a given staff type - std::set usedStaffIds; - - for (auto searchPeep : EntityList()) - { - if (static_cast(searchPeep->AssignedStaffType) != _staffType) - continue; - - usedStaffIds.insert(searchPeep->PeepId); + LOG_ERROR("Invalid staff type %u", static_cast(_staffType)); + return Result(Status::InvalidParameters, STR_CANT_HIRE_NEW_STAFF, STR_ERR_VALUE_OUT_OF_RANGE); } - uint32_t newStaffId = 1; - while (usedStaffIds.find(newStaffId) != usedStaffIds.end()) + if (GetNumFreeEntities() < 400) { - newStaffId++; + return Result(Status::NoFreeElements, STR_CANT_HIRE_NEW_STAFF, STR_TOO_MANY_PEOPLE_IN_GAME); } - newPeep->PeepId = newStaffId; - newPeep->AssignedStaffType = static_cast(_staffType); - - auto animPeepType = AnimationPeepType(static_cast(_staffType) + 1); - ObjectEntryIndex animObjectIndex = _costumeIndex; - if (animPeepType != AnimationPeepType::Entertainer) - animObjectIndex = findPeepAnimationsIndexForType(animPeepType); - - newPeep->Name = nullptr; - newPeep->AnimationObjectIndex = animObjectIndex; - newPeep->AnimationGroup = PeepAnimationGroup::Normal; - - auto& objManager = GetContext()->GetObjectManager(); - auto* animObj = objManager.GetLoadedObject(animObjectIndex); - - newPeep->PeepFlags &= ~PEEP_FLAGS_SLOW_WALK; - if (animObj->IsSlowWalking(PeepAnimationGroup::Normal)) - newPeep->PeepFlags |= PEEP_FLAGS_SLOW_WALK; - - const auto& spriteBounds = animObj->GetSpriteBounds(newPeep->AnimationGroup); - newPeep->SpriteData.Width = spriteBounds.sprite_width; - newPeep->SpriteData.HeightMin = spriteBounds.sprite_height_negative; - newPeep->SpriteData.HeightMax = spriteBounds.sprite_height_positive; - - if (_autoPosition) + if (_staffType == static_cast(StaffType::Entertainer)) { - AutoPositionNewStaff(newPeep); + auto costumes = findAllPeepAnimationsIndexesForType(AnimationPeepType::Entertainer); + if (std::find(costumes.begin(), costumes.end(), _costumeIndex) == costumes.end()) + { + LOG_ERROR("Unavailable entertainer costume %u", static_cast(_costumeIndex)); + return Result(Status::InvalidParameters, STR_CANT_HIRE_NEW_STAFF, STR_ERR_VALUE_OUT_OF_RANGE); + } + } + + Staff* newPeep = CreateEntity(); + if (newPeep == nullptr) + { + // Too many peeps exist already. + return Result(Status::NoFreeElements, STR_CANT_HIRE_NEW_STAFF, STR_TOO_MANY_PEOPLE_IN_GAME); + } + + if (execute == false) + { + // In query we just want to see if we can obtain a sprite slot. + EntityRemove(newPeep); + + res.SetData(StaffHireNewActionResult{ EntityId::GetNull() }); } else { - // NOTE: This state is required for the window to act. - newPeep->State = PeepState::Picked; + newPeep->WindowInvalidateFlags = 0; + newPeep->Action = PeepActionType::Walking; + newPeep->SpecialSprite = 0; + newPeep->AnimationImageIdOffset = 0; + newPeep->WalkingAnimationFrameNum = 0; + newPeep->AnimationType = PeepAnimationType::Walking; + newPeep->PathCheckOptimisation = 0; + newPeep->PeepFlags = 0; + newPeep->StaffLawnsMown = 0; + newPeep->StaffGardensWatered = 0; + newPeep->StaffLitterSwept = 0; + newPeep->StaffBinsEmptied = 0; + newPeep->StaffOrders = _staffOrders; - // INVESTIGATE: x and y are LOCATION_NULL at this point. - newPeep->MoveTo(newPeep->GetLocation()); - } + // We search for the first available Id for a given staff type + std::set usedStaffIds; - // Staff uses this - newPeep->As()->SetHireDate(GetDate().GetMonthsElapsed()); - newPeep->PathfindGoal.x = 0xFF; - newPeep->PathfindGoal.y = 0xFF; - newPeep->PathfindGoal.z = 0xFF; - newPeep->PathfindGoal.direction = kInvalidDirection; - - uint8_t colour = StaffGetColour(static_cast(_staffType)); - newPeep->TshirtColour = colour; - newPeep->TrousersColour = colour; - - // Staff energy determines their walking speed - switch (getGameState().cheats.selectedStaffSpeed) - { - case StaffSpeedCheat::None: - newPeep->Energy = kCheatsStaffNormalSpeed; - newPeep->EnergyTarget = kCheatsStaffNormalSpeed; - break; - - case StaffSpeedCheat::Frozen: - newPeep->Energy = kCheatsStaffFreezeSpeed; - newPeep->EnergyTarget = kCheatsStaffFreezeSpeed; - break; - - case StaffSpeedCheat::Fast: - newPeep->Energy = kCheatsStaffFastSpeed; - newPeep->EnergyTarget = kCheatsStaffFastSpeed; - break; - } - - newPeep->StaffMowingTimeout = 0; - newPeep->PatrolInfo = nullptr; - - res.SetData(StaffHireNewActionResult{ newPeep->Id }); - } - - return res; -} - -void StaffHireNewAction::AutoPositionNewStaff(Peep* newPeep) const -{ - // Find a location to place new staff member - newPeep->State = PeepState::Falling; - - uint32_t count = 0; - PathElement* guest_tile = nullptr; - - // Count number of walking guests - { - for (auto guest : EntityList()) - { - if (guest->State == PeepState::Walking) + for (auto searchPeep : EntityList()) { - // Check the walking guest's tile. Only count them if they're on a path tile. - guest_tile = MapGetPathElementAt(TileCoordsXYZ{ guest->NextLoc }); - if (guest_tile != nullptr) - ++count; + if (static_cast(searchPeep->AssignedStaffType) != _staffType) + continue; + + usedStaffIds.insert(searchPeep->PeepId); } + + uint32_t newStaffId = 1; + while (usedStaffIds.find(newStaffId) != usedStaffIds.end()) + { + newStaffId++; + } + + newPeep->PeepId = newStaffId; + newPeep->AssignedStaffType = static_cast(_staffType); + + auto animPeepType = AnimationPeepType(static_cast(_staffType) + 1); + ObjectEntryIndex animObjectIndex = _costumeIndex; + if (animPeepType != AnimationPeepType::Entertainer) + animObjectIndex = findPeepAnimationsIndexForType(animPeepType); + + newPeep->Name = nullptr; + newPeep->AnimationObjectIndex = animObjectIndex; + newPeep->AnimationGroup = PeepAnimationGroup::Normal; + + auto& objManager = GetContext()->GetObjectManager(); + auto* animObj = objManager.GetLoadedObject(animObjectIndex); + + newPeep->PeepFlags &= ~PEEP_FLAGS_SLOW_WALK; + if (animObj->IsSlowWalking(PeepAnimationGroup::Normal)) + newPeep->PeepFlags |= PEEP_FLAGS_SLOW_WALK; + + const auto& spriteBounds = animObj->GetSpriteBounds(newPeep->AnimationGroup); + newPeep->SpriteData.Width = spriteBounds.sprite_width; + newPeep->SpriteData.HeightMin = spriteBounds.sprite_height_negative; + newPeep->SpriteData.HeightMax = spriteBounds.sprite_height_positive; + + if (_autoPosition) + { + AutoPositionNewStaff(newPeep); + } + else + { + // NOTE: This state is required for the window to act. + newPeep->State = PeepState::Picked; + + // INVESTIGATE: x and y are LOCATION_NULL at this point. + newPeep->MoveTo(newPeep->GetLocation()); + } + + // Staff uses this + newPeep->As()->SetHireDate(GetDate().GetMonthsElapsed()); + newPeep->PathfindGoal.x = 0xFF; + newPeep->PathfindGoal.y = 0xFF; + newPeep->PathfindGoal.z = 0xFF; + newPeep->PathfindGoal.direction = kInvalidDirection; + + uint8_t colour = StaffGetColour(static_cast(_staffType)); + newPeep->TshirtColour = colour; + newPeep->TrousersColour = colour; + + // Staff energy determines their walking speed + switch (getGameState().cheats.selectedStaffSpeed) + { + case StaffSpeedCheat::None: + newPeep->Energy = kCheatsStaffNormalSpeed; + newPeep->EnergyTarget = kCheatsStaffNormalSpeed; + break; + + case StaffSpeedCheat::Frozen: + newPeep->Energy = kCheatsStaffFreezeSpeed; + newPeep->EnergyTarget = kCheatsStaffFreezeSpeed; + break; + + case StaffSpeedCheat::Fast: + newPeep->Energy = kCheatsStaffFastSpeed; + newPeep->EnergyTarget = kCheatsStaffFastSpeed; + break; + } + + newPeep->StaffMowingTimeout = 0; + newPeep->PatrolInfo = nullptr; + + res.SetData(StaffHireNewActionResult{ newPeep->Id }); } + + return res; } - CoordsXYZ newLocation{}; - if (count > 0) + void StaffHireNewAction::AutoPositionNewStaff(Peep* newPeep) const { - // Place staff at a random guest - uint32_t rand = ScenarioRandMax(count); - Guest* chosenGuest = nullptr; + // Find a location to place new staff member + newPeep->State = PeepState::Falling; - for (auto guest : EntityList()) + uint32_t count = 0; + PathElement* guest_tile = nullptr; + + // Count number of walking guests { - if (guest->State == PeepState::Walking) + for (auto guest : EntityList()) { - guest_tile = MapGetPathElementAt(TileCoordsXYZ{ guest->NextLoc }); - if (guest_tile != nullptr) + if (guest->State == PeepState::Walking) { - if (rand == 0) - { - chosenGuest = guest; - break; - } - --rand; + // Check the walking guest's tile. Only count them if they're on a path tile. + guest_tile = MapGetPathElementAt(TileCoordsXYZ{ guest->NextLoc }); + if (guest_tile != nullptr) + ++count; } } } - if (chosenGuest != nullptr) + CoordsXYZ newLocation{}; + if (count > 0) { - newLocation = chosenGuest->GetLocation(); - } - else - { - // User must pick a location - newPeep->State = PeepState::Picked; - newLocation = newPeep->GetLocation(); - } - } - else - { - // No walking guests; pick random park entrance - const auto& park = getGameState().park; - if (!park.entrances.empty()) - { - auto rand = ScenarioRandMax(static_cast(park.entrances.size())); - const auto& entrance = park.entrances[rand]; - auto dir = entrance.direction; - newLocation = entrance; - // TODO: Replace with CoordsDirectionDelta - newLocation.x += 16 + ((dir & 1) == 0 ? ((dir & 2) ? 32 : -32) : 0); - newLocation.y += 16 + ((dir & 1) == 1 ? ((dir & 2) ? -32 : 32) : 0); - } - else - { - // User must pick a location - newPeep->State = PeepState::Picked; - newLocation = newPeep->GetLocation(); - } - } + // Place staff at a random guest + uint32_t rand = ScenarioRandMax(count); + Guest* chosenGuest = nullptr; - newPeep->MoveTo(newLocation + CoordsXYZ{ 0, 0, 16 }); -} + for (auto guest : EntityList()) + { + if (guest->State == PeepState::Walking) + { + guest_tile = MapGetPathElementAt(TileCoordsXYZ{ guest->NextLoc }); + if (guest_tile != nullptr) + { + if (rand == 0) + { + chosenGuest = guest; + break; + } + --rand; + } + } + } + + if (chosenGuest != nullptr) + { + newLocation = chosenGuest->GetLocation(); + } + else + { + // User must pick a location + newPeep->State = PeepState::Picked; + newLocation = newPeep->GetLocation(); + } + } + else + { + // No walking guests; pick random park entrance + const auto& park = getGameState().park; + if (!park.entrances.empty()) + { + auto rand = ScenarioRandMax(static_cast(park.entrances.size())); + const auto& entrance = park.entrances[rand]; + auto dir = entrance.direction; + newLocation = entrance; + // TODO: Replace with CoordsDirectionDelta + newLocation.x += 16 + ((dir & 1) == 0 ? ((dir & 2) ? 32 : -32) : 0); + newLocation.y += 16 + ((dir & 1) == 1 ? ((dir & 2) ? -32 : 32) : 0); + } + else + { + // User must pick a location + newPeep->State = PeepState::Picked; + newLocation = newPeep->GetLocation(); + } + } + + newPeep->MoveTo(newLocation + CoordsXYZ{ 0, 0, 16 }); + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/StaffHireNewAction.h b/src/openrct2/actions/StaffHireNewAction.h index 3c1cfd228f..5040d33b9a 100644 --- a/src/openrct2/actions/StaffHireNewAction.h +++ b/src/openrct2/actions/StaffHireNewAction.h @@ -12,32 +12,35 @@ #include "../entity/Staff.h" #include "GameAction.h" -struct StaffHireNewActionResult +namespace OpenRCT2::GameActions { - EntityId StaffEntityId = EntityId::GetNull(); -}; + struct StaffHireNewActionResult + { + EntityId StaffEntityId = EntityId::GetNull(); + }; -class StaffHireNewAction final : public GameActionBase -{ -private: - bool _autoPosition{}; - uint8_t _staffType{ EnumValue(StaffType::Count) }; - OpenRCT2::ObjectEntryIndex _costumeIndex; - uint32_t _staffOrders{}; + class StaffHireNewAction final : public GameActionBase + { + private: + bool _autoPosition{}; + uint8_t _staffType{ EnumValue(StaffType::Count) }; + ObjectEntryIndex _costumeIndex; + uint32_t _staffOrders{}; -public: - StaffHireNewAction() = default; - StaffHireNewAction(bool autoPosition, StaffType staffType, OpenRCT2::ObjectEntryIndex costumeIndex, uint32_t staffOrders); + public: + StaffHireNewAction() = default; + StaffHireNewAction(bool autoPosition, StaffType staffType, ObjectEntryIndex costumeIndex, uint32_t staffOrders); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; -private: - OpenRCT2::GameActions::Result QueryExecute(bool execute) const; - void AutoPositionNewStaff(Peep* newPeep) const; -}; + private: + Result QueryExecute(bool execute) const; + void AutoPositionNewStaff(Peep* newPeep) const; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/StaffSetColourAction.cpp b/src/openrct2/actions/StaffSetColourAction.cpp index aa083d5203..3400462ed9 100644 --- a/src/openrct2/actions/StaffSetColourAction.cpp +++ b/src/openrct2/actions/StaffSetColourAction.cpp @@ -19,62 +19,62 @@ #include "../ui/WindowManager.h" #include "../windows/Intent.h" -using namespace OpenRCT2; - -StaffSetColourAction::StaffSetColourAction(StaffType staffType, uint8_t colour) - : _staffType(static_cast(staffType)) - , _colour(colour) +namespace OpenRCT2::GameActions { -} - -void StaffSetColourAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit("staffType", _staffType); - visitor.Visit("colour", _colour); -} - -uint16_t StaffSetColourAction::GetActionFlags() const -{ - return GameAction::GetActionFlags() | GameActions::Flags::AllowWhilePaused; -} - -void StaffSetColourAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - stream << DS_TAG(_staffType) << DS_TAG(_colour); -} - -GameActions::Result StaffSetColourAction::Query() const -{ - auto staffType = static_cast(_staffType); - if (staffType != StaffType::Handyman && staffType != StaffType::Mechanic && staffType != StaffType::Security) + StaffSetColourAction::StaffSetColourAction(StaffType staffType, uint8_t colour) + : _staffType(static_cast(staffType)) + , _colour(colour) { - LOG_ERROR("Staff color can't be changed for staff type %d", _staffType); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_ACTION_INVALID_FOR_THAT_STAFF_TYPE); - } - return GameActions::Result(); -} - -GameActions::Result StaffSetColourAction::Execute() const -{ - // Update global uniform colour property - auto res = StaffSetColour(static_cast(_staffType), _colour); - if (res.Error != GameActions::Status::Ok) - { - return res; } - // Update each staff member's uniform - for (auto peep : EntityList()) + void StaffSetColourAction::AcceptParameters(GameActionParameterVisitor& visitor) { - if (peep->AssignedStaffType == static_cast(_staffType)) + visitor.Visit("staffType", _staffType); + visitor.Visit("colour", _colour); + } + + uint16_t StaffSetColourAction::GetActionFlags() const + { + return GameAction::GetActionFlags() | Flags::AllowWhilePaused; + } + + void StaffSetColourAction::Serialise(DataSerialiser& stream) + { + GameAction::Serialise(stream); + stream << DS_TAG(_staffType) << DS_TAG(_colour); + } + + Result StaffSetColourAction::Query() const + { + auto staffType = static_cast(_staffType); + if (staffType != StaffType::Handyman && staffType != StaffType::Mechanic && staffType != StaffType::Security) { - peep->TshirtColour = _colour; - peep->TrousersColour = _colour; + LOG_ERROR("Staff color can't be changed for staff type %d", _staffType); + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_ACTION_INVALID_FOR_THAT_STAFF_TYPE); } + return Result(); } - GfxInvalidateScreen(); - return GameActions::Result(); -} + Result StaffSetColourAction::Execute() const + { + // Update global uniform colour property + auto res = StaffSetColour(static_cast(_staffType), _colour); + if (res.Error != Status::Ok) + { + return res; + } + + // Update each staff member's uniform + for (auto peep : EntityList()) + { + if (peep->AssignedStaffType == static_cast(_staffType)) + { + peep->TshirtColour = _colour; + peep->TrousersColour = _colour; + } + } + + GfxInvalidateScreen(); + return Result(); + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/StaffSetColourAction.h b/src/openrct2/actions/StaffSetColourAction.h index 2fc990fd69..2ee3787814 100644 --- a/src/openrct2/actions/StaffSetColourAction.h +++ b/src/openrct2/actions/StaffSetColourAction.h @@ -12,21 +12,24 @@ #include "../entity/Staff.h" #include "GameAction.h" -class StaffSetColourAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - uint8_t _staffType{}; - uint8_t _colour{}; + class StaffSetColourAction final : public GameActionBase + { + private: + uint8_t _staffType{}; + uint8_t _colour{}; -public: - StaffSetColourAction() = default; - StaffSetColourAction(StaffType staffType, uint8_t colour); + public: + StaffSetColourAction() = default; + StaffSetColourAction(StaffType staffType, uint8_t colour); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; -}; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/StaffSetCostumeAction.cpp b/src/openrct2/actions/StaffSetCostumeAction.cpp index 0be4fe9873..281fd34e49 100644 --- a/src/openrct2/actions/StaffSetCostumeAction.cpp +++ b/src/openrct2/actions/StaffSetCostumeAction.cpp @@ -18,92 +18,91 @@ #include "../ui/WindowManager.h" #include "../windows/Intent.h" -using namespace OpenRCT2; - -StaffSetCostumeAction::StaffSetCostumeAction(EntityId spriteIndex, ObjectEntryIndex costume) - : _spriteIndex(spriteIndex) - , _costume(costume) +namespace OpenRCT2::GameActions { -} - -void StaffSetCostumeAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit("id", _spriteIndex); - visitor.Visit("costume", _costume); -} - -uint16_t StaffSetCostumeAction::GetActionFlags() const -{ - return GameAction::GetActionFlags() | GameActions::Flags::AllowWhilePaused; -} - -void StaffSetCostumeAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_spriteIndex) << DS_TAG(_costume); -} - -GameActions::Result StaffSetCostumeAction::Query() const -{ - if (_spriteIndex.ToUnderlying() >= kMaxEntities || _spriteIndex.IsNull()) + StaffSetCostumeAction::StaffSetCostumeAction(EntityId spriteIndex, ObjectEntryIndex costume) + : _spriteIndex(spriteIndex) + , _costume(costume) { - LOG_ERROR("Invalid sprite index %u", _spriteIndex); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_VALUE_OUT_OF_RANGE); } - auto* staff = TryGetEntity(_spriteIndex); - if (staff == nullptr) + void StaffSetCostumeAction::AcceptParameters(GameActionParameterVisitor& visitor) { - LOG_ERROR("Staff entity not found for spriteIndex %u", _spriteIndex); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_STAFF_NOT_FOUND); + visitor.Visit("id", _spriteIndex); + visitor.Visit("costume", _costume); } - auto& objManager = GetContext()->GetObjectManager(); - auto* animObj = objManager.GetLoadedObject(_costume); - - auto animPeepType = AnimationPeepType(static_cast(staff->AssignedStaffType) + 1); - if (animObj->GetPeepType() != animPeepType) + uint16_t StaffSetCostumeAction::GetActionFlags() const { - LOG_ERROR("Invalid entertainer costume %u", _costume); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_VALUE_OUT_OF_RANGE); - } - return GameActions::Result(); -} - -GameActions::Result StaffSetCostumeAction::Execute() const -{ - auto* staff = TryGetEntity(_spriteIndex); - if (staff == nullptr) - { - LOG_ERROR("Staff entity not found for spriteIndex %u", _spriteIndex); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_STAFF_NOT_FOUND); + return GameAction::GetActionFlags() | Flags::AllowWhilePaused; } - staff->AnimationObjectIndex = _costume; - staff->AnimationGroup = PeepAnimationGroup::Normal; + void StaffSetCostumeAction::Serialise(DataSerialiser& stream) + { + GameAction::Serialise(stream); - auto& objManager = GetContext()->GetObjectManager(); - auto* animObj = objManager.GetLoadedObject(_costume); + stream << DS_TAG(_spriteIndex) << DS_TAG(_costume); + } - staff->PeepFlags &= ~PEEP_FLAGS_SLOW_WALK; - if (animObj->IsSlowWalking(PeepAnimationGroup::Normal)) - staff->PeepFlags |= PEEP_FLAGS_SLOW_WALK; + Result StaffSetCostumeAction::Query() const + { + if (_spriteIndex.ToUnderlying() >= kMaxEntities || _spriteIndex.IsNull()) + { + LOG_ERROR("Invalid sprite index %u", _spriteIndex); + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_VALUE_OUT_OF_RANGE); + } - staff->AnimationFrameNum = 0; - staff->UpdateCurrentAnimationType(); - staff->Invalidate(); + auto* staff = TryGetEntity(_spriteIndex); + if (staff == nullptr) + { + LOG_ERROR("Staff entity not found for spriteIndex %u", _spriteIndex); + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_STAFF_NOT_FOUND); + } - auto* windowMgr = Ui::GetWindowManager(); - windowMgr->InvalidateByNumber(WindowClass::Peep, _spriteIndex); + auto& objManager = GetContext()->GetObjectManager(); + auto* animObj = objManager.GetLoadedObject(_costume); - auto intent = Intent(INTENT_ACTION_REFRESH_STAFF_LIST); - ContextBroadcastIntent(&intent); + auto animPeepType = AnimationPeepType(static_cast(staff->AssignedStaffType) + 1); + if (animObj->GetPeepType() != animPeepType) + { + LOG_ERROR("Invalid entertainer costume %u", _costume); + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_VALUE_OUT_OF_RANGE); + } + return Result(); + } - auto res = GameActions::Result(); - res.Position = staff->GetLocation(); + Result StaffSetCostumeAction::Execute() const + { + auto* staff = TryGetEntity(_spriteIndex); + if (staff == nullptr) + { + LOG_ERROR("Staff entity not found for spriteIndex %u", _spriteIndex); + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_STAFF_NOT_FOUND); + } - return res; -} + staff->AnimationObjectIndex = _costume; + staff->AnimationGroup = PeepAnimationGroup::Normal; + + auto& objManager = GetContext()->GetObjectManager(); + auto* animObj = objManager.GetLoadedObject(_costume); + + staff->PeepFlags &= ~PEEP_FLAGS_SLOW_WALK; + if (animObj->IsSlowWalking(PeepAnimationGroup::Normal)) + staff->PeepFlags |= PEEP_FLAGS_SLOW_WALK; + + staff->AnimationFrameNum = 0; + staff->UpdateCurrentAnimationType(); + staff->Invalidate(); + + auto* windowMgr = Ui::GetWindowManager(); + windowMgr->InvalidateByNumber(WindowClass::Peep, _spriteIndex); + + auto intent = Intent(INTENT_ACTION_REFRESH_STAFF_LIST); + ContextBroadcastIntent(&intent); + + auto res = Result(); + res.Position = staff->GetLocation(); + + return res; + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/StaffSetCostumeAction.h b/src/openrct2/actions/StaffSetCostumeAction.h index dcb353dd6f..2cdd356383 100644 --- a/src/openrct2/actions/StaffSetCostumeAction.h +++ b/src/openrct2/actions/StaffSetCostumeAction.h @@ -12,21 +12,24 @@ #include "../entity/Staff.h" #include "GameAction.h" -class StaffSetCostumeAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - EntityId _spriteIndex{ EntityId::GetNull() }; - OpenRCT2::ObjectEntryIndex _costume = OpenRCT2::kObjectEntryIndexNull; + class StaffSetCostumeAction final : public GameActionBase + { + private: + EntityId _spriteIndex{ EntityId::GetNull() }; + ObjectEntryIndex _costume = OpenRCT2::kObjectEntryIndexNull; -public: - StaffSetCostumeAction() = default; - StaffSetCostumeAction(EntityId spriteIndex, OpenRCT2::ObjectEntryIndex costume); + public: + StaffSetCostumeAction() = default; + StaffSetCostumeAction(EntityId spriteIndex, OpenRCT2::ObjectEntryIndex costume); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; -}; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/StaffSetNameAction.cpp b/src/openrct2/actions/StaffSetNameAction.cpp index a90c49f98f..09596c3f31 100644 --- a/src/openrct2/actions/StaffSetNameAction.cpp +++ b/src/openrct2/actions/StaffSetNameAction.cpp @@ -20,80 +20,78 @@ #include "../windows/Intent.h" #include "../world/Park.h" -using namespace OpenRCT2; - -StaffSetNameAction::StaffSetNameAction(EntityId spriteIndex, const std::string& name) - : _spriteIndex(spriteIndex) - , _name(name) +namespace OpenRCT2::GameActions { -} - -void StaffSetNameAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit("id", _spriteIndex); - visitor.Visit("name", _name); -} - -uint16_t StaffSetNameAction::GetActionFlags() const -{ - return GameAction::GetActionFlags() | GameActions::Flags::AllowWhilePaused; -} - -void StaffSetNameAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_spriteIndex) << DS_TAG(_name); -} - -GameActions::Result StaffSetNameAction::Query() const -{ - if (_spriteIndex.ToUnderlying() >= kMaxEntities || _spriteIndex.IsNull()) + StaffSetNameAction::StaffSetNameAction(EntityId spriteIndex, const std::string& name) + : _spriteIndex(spriteIndex) + , _name(name) { - LOG_ERROR("Invalid sprite index %u", _spriteIndex); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_STAFF_ERROR_CANT_NAME_STAFF_MEMBER, STR_ERR_VALUE_OUT_OF_RANGE); } - auto staff = TryGetEntity(_spriteIndex); - if (staff == nullptr) + void StaffSetNameAction::AcceptParameters(GameActionParameterVisitor& visitor) { - LOG_ERROR("Staff entity not found for spriteIndex %u", _spriteIndex); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_STAFF_ERROR_CANT_NAME_STAFF_MEMBER, STR_ERR_STAFF_NOT_FOUND); + visitor.Visit("id", _spriteIndex); + visitor.Visit("name", _name); } - return GameActions::Result(); -} - -GameActions::Result StaffSetNameAction::Execute() const -{ - auto staff = TryGetEntity(_spriteIndex); - if (staff == nullptr) + uint16_t StaffSetNameAction::GetActionFlags() const { - LOG_ERROR("Staff entity not found for spriteIndex %u", _spriteIndex); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_STAFF_ERROR_CANT_NAME_STAFF_MEMBER, STR_ERR_STAFF_NOT_FOUND); + return GameAction::GetActionFlags() | Flags::AllowWhilePaused; } - auto curName = staff->GetName(); - if (curName == _name) + void StaffSetNameAction::Serialise(DataSerialiser& stream) { - return GameActions::Result(); + GameAction::Serialise(stream); + + stream << DS_TAG(_spriteIndex) << DS_TAG(_name); } - if (!staff->SetName(_name)) + Result StaffSetNameAction::Query() const { - return GameActions::Result(GameActions::Status::Unknown, STR_CANT_NAME_GUEST, kStringIdNone); + if (_spriteIndex.ToUnderlying() >= kMaxEntities || _spriteIndex.IsNull()) + { + LOG_ERROR("Invalid sprite index %u", _spriteIndex); + return Result(Status::InvalidParameters, STR_STAFF_ERROR_CANT_NAME_STAFF_MEMBER, STR_ERR_VALUE_OUT_OF_RANGE); + } + + auto staff = TryGetEntity(_spriteIndex); + if (staff == nullptr) + { + LOG_ERROR("Staff entity not found for spriteIndex %u", _spriteIndex); + return Result(Status::InvalidParameters, STR_STAFF_ERROR_CANT_NAME_STAFF_MEMBER, STR_ERR_STAFF_NOT_FOUND); + } + + return Result(); } - GfxInvalidateScreen(); + Result StaffSetNameAction::Execute() const + { + auto staff = TryGetEntity(_spriteIndex); + if (staff == nullptr) + { + LOG_ERROR("Staff entity not found for spriteIndex %u", _spriteIndex); + return Result(Status::InvalidParameters, STR_STAFF_ERROR_CANT_NAME_STAFF_MEMBER, STR_ERR_STAFF_NOT_FOUND); + } - auto intent = Intent(INTENT_ACTION_REFRESH_STAFF_LIST); - ContextBroadcastIntent(&intent); + auto curName = staff->GetName(); + if (curName == _name) + { + return Result(); + } - auto res = GameActions::Result(); - res.Position = staff->GetLocation(); + if (!staff->SetName(_name)) + { + return Result(Status::Unknown, STR_CANT_NAME_GUEST, kStringIdNone); + } - return res; -} + GfxInvalidateScreen(); + + auto intent = Intent(INTENT_ACTION_REFRESH_STAFF_LIST); + ContextBroadcastIntent(&intent); + + auto res = Result(); + res.Position = staff->GetLocation(); + + return res; + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/StaffSetNameAction.h b/src/openrct2/actions/StaffSetNameAction.h index 5df2048f69..59bab0c6e7 100644 --- a/src/openrct2/actions/StaffSetNameAction.h +++ b/src/openrct2/actions/StaffSetNameAction.h @@ -11,20 +11,23 @@ #include "GameAction.h" -class StaffSetNameAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - EntityId _spriteIndex{ EntityId::GetNull() }; - std::string _name; + class StaffSetNameAction final : public GameActionBase + { + private: + EntityId _spriteIndex{ EntityId::GetNull() }; + std::string _name; -public: - StaffSetNameAction() = default; - StaffSetNameAction(EntityId spriteIndex, const std::string& name); + public: + StaffSetNameAction() = default; + StaffSetNameAction(EntityId spriteIndex, const std::string& name); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; -}; + uint16_t GetActionFlags() const override; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/StaffSetOrdersAction.cpp b/src/openrct2/actions/StaffSetOrdersAction.cpp index 54c0d8353c..1f5f3f6a3e 100644 --- a/src/openrct2/actions/StaffSetOrdersAction.cpp +++ b/src/openrct2/actions/StaffSetOrdersAction.cpp @@ -17,70 +17,69 @@ #include "../ui/WindowManager.h" #include "../windows/Intent.h" -using namespace OpenRCT2; - -StaffSetOrdersAction::StaffSetOrdersAction(EntityId spriteIndex, uint8_t ordersId) - : _spriteIndex(spriteIndex) - , _ordersId(ordersId) +namespace OpenRCT2::GameActions { -} - -void StaffSetOrdersAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit("id", _spriteIndex); - visitor.Visit("staffOrders", _ordersId); -} - -uint16_t StaffSetOrdersAction::GetActionFlags() const -{ - return GameAction::GetActionFlags() | GameActions::Flags::AllowWhilePaused; -} - -void StaffSetOrdersAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_spriteIndex) << DS_TAG(_ordersId); -} - -GameActions::Result StaffSetOrdersAction::Query() const -{ - if (_spriteIndex.ToUnderlying() >= kMaxEntities || _spriteIndex.IsNull()) + StaffSetOrdersAction::StaffSetOrdersAction(EntityId spriteIndex, uint8_t ordersId) + : _spriteIndex(spriteIndex) + , _ordersId(ordersId) { - LOG_ERROR("Invalid sprite index %u", _spriteIndex); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_VALUE_OUT_OF_RANGE); } - auto* staff = TryGetEntity(_spriteIndex); - if (staff == nullptr - || (staff->AssignedStaffType != StaffType::Handyman && staff->AssignedStaffType != StaffType::Mechanic)) + void StaffSetOrdersAction::AcceptParameters(GameActionParameterVisitor& visitor) { - LOG_ERROR("Staff orders can't be changed for staff of type %u", _spriteIndex); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_ACTION_INVALID_FOR_THAT_STAFF_TYPE); + visitor.Visit("id", _spriteIndex); + visitor.Visit("staffOrders", _ordersId); } - return GameActions::Result(); -} - -GameActions::Result StaffSetOrdersAction::Execute() const -{ - auto* staff = TryGetEntity(_spriteIndex); - if (staff == nullptr) + uint16_t StaffSetOrdersAction::GetActionFlags() const { - LOG_ERROR("Staff entity not found for spriteIndex %u", _spriteIndex); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_STAFF_NOT_FOUND); + return GameAction::GetActionFlags() | Flags::AllowWhilePaused; } - staff->StaffOrders = _ordersId; - auto* windowMgr = Ui::GetWindowManager(); - windowMgr->InvalidateByNumber(WindowClass::Peep, _spriteIndex); - auto intent = Intent(INTENT_ACTION_REFRESH_STAFF_LIST); - ContextBroadcastIntent(&intent); + void StaffSetOrdersAction::Serialise(DataSerialiser& stream) + { + GameAction::Serialise(stream); - auto res = GameActions::Result(); - res.Position = staff->GetLocation(); + stream << DS_TAG(_spriteIndex) << DS_TAG(_ordersId); + } - return res; -} + Result StaffSetOrdersAction::Query() const + { + if (_spriteIndex.ToUnderlying() >= kMaxEntities || _spriteIndex.IsNull()) + { + LOG_ERROR("Invalid sprite index %u", _spriteIndex); + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_VALUE_OUT_OF_RANGE); + } + + auto* staff = TryGetEntity(_spriteIndex); + if (staff == nullptr + || (staff->AssignedStaffType != StaffType::Handyman && staff->AssignedStaffType != StaffType::Mechanic)) + { + LOG_ERROR("Staff orders can't be changed for staff of type %u", _spriteIndex); + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_ACTION_INVALID_FOR_THAT_STAFF_TYPE); + } + + return Result(); + } + + Result StaffSetOrdersAction::Execute() const + { + auto* staff = TryGetEntity(_spriteIndex); + if (staff == nullptr) + { + LOG_ERROR("Staff entity not found for spriteIndex %u", _spriteIndex); + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_STAFF_NOT_FOUND); + } + staff->StaffOrders = _ordersId; + + auto* windowMgr = Ui::GetWindowManager(); + windowMgr->InvalidateByNumber(WindowClass::Peep, _spriteIndex); + auto intent = Intent(INTENT_ACTION_REFRESH_STAFF_LIST); + ContextBroadcastIntent(&intent); + + auto res = Result(); + res.Position = staff->GetLocation(); + + return res; + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/StaffSetOrdersAction.h b/src/openrct2/actions/StaffSetOrdersAction.h index f68bdc5c4b..24a0d6be14 100644 --- a/src/openrct2/actions/StaffSetOrdersAction.h +++ b/src/openrct2/actions/StaffSetOrdersAction.h @@ -11,21 +11,24 @@ #include "GameAction.h" -class StaffSetOrdersAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - EntityId _spriteIndex{ EntityId::GetNull() }; - uint8_t _ordersId{}; + class StaffSetOrdersAction final : public GameActionBase + { + private: + EntityId _spriteIndex{ EntityId::GetNull() }; + uint8_t _ordersId{}; -public: - StaffSetOrdersAction() = default; - StaffSetOrdersAction(EntityId spriteIndex, uint8_t ordersId); + public: + StaffSetOrdersAction() = default; + StaffSetOrdersAction(EntityId spriteIndex, uint8_t ordersId); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; -}; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/StaffSetPatrolAreaAction.cpp b/src/openrct2/actions/StaffSetPatrolAreaAction.cpp index a1c0d506fd..2aa14504fe 100644 --- a/src/openrct2/actions/StaffSetPatrolAreaAction.cpp +++ b/src/openrct2/actions/StaffSetPatrolAreaAction.cpp @@ -15,91 +15,93 @@ #include "../entity/Peep.h" #include "../entity/Staff.h" -using namespace OpenRCT2; - -StaffSetPatrolAreaAction::StaffSetPatrolAreaAction(EntityId spriteId, const MapRange& range, const StaffSetPatrolAreaMode mode) - : _spriteId(spriteId) - , _range(range) - , _mode(mode) +namespace OpenRCT2::GameActions { -} - -void StaffSetPatrolAreaAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit("id", _spriteId); - visitor.Visit(_range); - visitor.Visit("mode", _mode); -} - -uint16_t StaffSetPatrolAreaAction::GetActionFlags() const -{ - return GameAction::GetActionFlags() | GameActions::Flags::AllowWhilePaused; -} - -void StaffSetPatrolAreaAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - stream << DS_TAG(_spriteId) << DS_TAG(_range) << DS_TAG(_mode); -} - -GameActions::Result StaffSetPatrolAreaAction::Query() const -{ - return QueryExecute(false); -} - -GameActions::Result StaffSetPatrolAreaAction::Execute() const -{ - return QueryExecute(true); -} - -static void InvalidatePatrolTiles(const MapRange& range) -{ - MapInvalidateRegion(range.Point1, range.Point2); -} - -GameActions::Result StaffSetPatrolAreaAction::QueryExecute(bool executing) const -{ - auto staff = TryGetEntity(_spriteId); - if (staff == nullptr) + StaffSetPatrolAreaAction::StaffSetPatrolAreaAction( + EntityId spriteId, const MapRange& range, const StaffSetPatrolAreaMode mode) + : _spriteId(spriteId) + , _range(range) + , _mode(mode) { - LOG_ERROR("Staff entity not found for spriteID %u", _spriteId.ToUnderlying()); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_STAFF_NOT_FOUND); } - auto validRange = ClampRangeWithinMap(_range); - for (int32_t y = validRange.GetTop(); y <= validRange.GetBottom(); y += kCoordsXYStep) + void StaffSetPatrolAreaAction::AcceptParameters(GameActionParameterVisitor& visitor) { - for (int32_t x = validRange.GetLeft(); x <= validRange.GetRight(); x += kCoordsXYStep) + visitor.Visit("id", _spriteId); + visitor.Visit(_range); + visitor.Visit("mode", _mode); + } + + uint16_t StaffSetPatrolAreaAction::GetActionFlags() const + { + return GameAction::GetActionFlags() | Flags::AllowWhilePaused; + } + + void StaffSetPatrolAreaAction::Serialise(DataSerialiser& stream) + { + GameAction::Serialise(stream); + stream << DS_TAG(_spriteId) << DS_TAG(_range) << DS_TAG(_mode); + } + + Result StaffSetPatrolAreaAction::Query() const + { + return QueryExecute(false); + } + + Result StaffSetPatrolAreaAction::Execute() const + { + return QueryExecute(true); + } + + static void InvalidatePatrolTiles(const MapRange& range) + { + MapInvalidateRegion(range.Point1, range.Point2); + } + + Result StaffSetPatrolAreaAction::QueryExecute(bool executing) const + { + auto staff = TryGetEntity(_spriteId); + if (staff == nullptr) { - if (!LocationValid({ x, y })) + LOG_ERROR("Staff entity not found for spriteID %u", _spriteId.ToUnderlying()); + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_STAFF_NOT_FOUND); + } + + auto validRange = ClampRangeWithinMap(_range); + for (int32_t y = validRange.GetTop(); y <= validRange.GetBottom(); y += kCoordsXYStep) + { + for (int32_t x = validRange.GetLeft(); x <= validRange.GetRight(); x += kCoordsXYStep) { - return GameActions::Result(GameActions::Status::InvalidParameters, STR_SET_PATROL_AREA, STR_OFF_EDGE_OF_MAP); + if (!LocationValid({ x, y })) + { + return Result(Status::InvalidParameters, STR_SET_PATROL_AREA, STR_OFF_EDGE_OF_MAP); + } } } - } - if (executing) - { - switch (_mode) + if (executing) { - case StaffSetPatrolAreaMode::Set: - staff->SetPatrolArea(_range, true); - InvalidatePatrolTiles(_range); - break; - case StaffSetPatrolAreaMode::Unset: - staff->SetPatrolArea(_range, false); - if (!staff->HasPatrolArea()) - { + switch (_mode) + { + case StaffSetPatrolAreaMode::Set: + staff->SetPatrolArea(_range, true); + InvalidatePatrolTiles(_range); + break; + case StaffSetPatrolAreaMode::Unset: + staff->SetPatrolArea(_range, false); + if (!staff->HasPatrolArea()) + { + staff->ClearPatrolArea(); + } + InvalidatePatrolTiles(_range); + break; + case StaffSetPatrolAreaMode::ClearAll: staff->ClearPatrolArea(); - } - InvalidatePatrolTiles(_range); - break; - case StaffSetPatrolAreaMode::ClearAll: - staff->ClearPatrolArea(); - GfxInvalidateScreen(); - break; + GfxInvalidateScreen(); + break; + } + UpdateConsolidatedPatrolAreas(); } - UpdateConsolidatedPatrolAreas(); + return Result(); } - return GameActions::Result(); -} +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/StaffSetPatrolAreaAction.h b/src/openrct2/actions/StaffSetPatrolAreaAction.h index 188cacf45e..f18ee9a9cc 100644 --- a/src/openrct2/actions/StaffSetPatrolAreaAction.h +++ b/src/openrct2/actions/StaffSetPatrolAreaAction.h @@ -11,30 +11,33 @@ #include "GameAction.h" -enum class StaffSetPatrolAreaMode : uint8_t +namespace OpenRCT2::GameActions { - Set, - Unset, - ClearAll -}; + enum class StaffSetPatrolAreaMode : uint8_t + { + Set, + Unset, + ClearAll + }; -class StaffSetPatrolAreaAction final : public GameActionBase -{ -private: - EntityId _spriteId{ EntityId::GetNull() }; - MapRange _range; - StaffSetPatrolAreaMode _mode; + class StaffSetPatrolAreaAction final : public GameActionBase + { + private: + EntityId _spriteId{ EntityId::GetNull() }; + MapRange _range; + StaffSetPatrolAreaMode _mode; - OpenRCT2::GameActions::Result QueryExecute(bool executing) const; + Result QueryExecute(bool executing) const; -public: - StaffSetPatrolAreaAction() = default; - StaffSetPatrolAreaAction(EntityId spriteId, const MapRange& range, const StaffSetPatrolAreaMode mode); + public: + StaffSetPatrolAreaAction() = default; + StaffSetPatrolAreaAction(EntityId spriteId, const MapRange& range, const StaffSetPatrolAreaMode mode); - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void AcceptParameters(GameActionParameterVisitor& visitor) override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; -}; + void AcceptParameters(GameActionParameterVisitor& visitor) override; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/SurfaceSetStyleAction.cpp b/src/openrct2/actions/SurfaceSetStyleAction.cpp index d43ace39e5..d44effaaf4 100644 --- a/src/openrct2/actions/SurfaceSetStyleAction.cpp +++ b/src/openrct2/actions/SurfaceSetStyleAction.cpp @@ -21,210 +21,208 @@ #include "../world/Park.h" #include "../world/tile_element/SurfaceElement.h" -using namespace OpenRCT2; - -SurfaceSetStyleAction::SurfaceSetStyleAction(MapRange range, ObjectEntryIndex surfaceStyle, ObjectEntryIndex edgeStyle) - : _range(range) - , _surfaceStyle(surfaceStyle) - , _edgeStyle(edgeStyle) +namespace OpenRCT2::GameActions { -} - -void SurfaceSetStyleAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit(_range); - visitor.Visit("surfaceStyle", _surfaceStyle); - visitor.Visit("edgeStyle", _edgeStyle); -} - -void SurfaceSetStyleAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_range) << DS_TAG(_surfaceStyle) << DS_TAG(_edgeStyle); -} - -GameActions::Result SurfaceSetStyleAction::Query() const -{ - auto res = GameActions::Result(); - res.ErrorTitle = STR_CANT_CHANGE_LAND_TYPE; - res.Expenditure = ExpenditureType::landscaping; - - auto validRange = ClampRangeWithinMap(_range.Normalise()); - auto& objManager = OpenRCT2::GetContext()->GetObjectManager(); - if (_surfaceStyle != kObjectEntryIndexNull) + SurfaceSetStyleAction::SurfaceSetStyleAction(MapRange range, ObjectEntryIndex surfaceStyle, ObjectEntryIndex edgeStyle) + : _range(range) + , _surfaceStyle(surfaceStyle) + , _edgeStyle(edgeStyle) { - const auto surfaceObj = static_cast( - objManager.GetLoadedObject(_surfaceStyle)); - - if (surfaceObj == nullptr) - { - LOG_ERROR("Invalid surface style %u", _surfaceStyle); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_CHANGE_LAND_TYPE, STR_UNKNOWN_OBJECT_TYPE); - } } - if (_edgeStyle != kObjectEntryIndexNull) + void SurfaceSetStyleAction::AcceptParameters(GameActionParameterVisitor& visitor) { - const auto edgeObj = objManager.GetLoadedObject(_edgeStyle); - - if (edgeObj == nullptr) - { - LOG_ERROR("Invalid edge style %u", _edgeStyle); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_CHANGE_LAND_TYPE, STR_UNKNOWN_OBJECT_TYPE); - } + visitor.Visit(_range); + visitor.Visit("surfaceStyle", _surfaceStyle); + visitor.Visit("edgeStyle", _edgeStyle); } - auto xMid = (validRange.GetLeft() + validRange.GetRight()) / 2 + 16; - auto yMid = (validRange.GetTop() + validRange.GetBottom()) / 2 + 16; - auto heightMid = TileElementHeight({ xMid, yMid }); - - res.Position.x = xMid; - res.Position.y = yMid; - res.Position.z = heightMid; - - auto& gameState = getGameState(); - - // Do nothing if not in editor, sandbox mode or landscaping is forbidden - if (gLegacyScene != LegacyScene::scenarioEditor && !gameState.cheats.sandboxMode - && (gameState.park.flags & PARK_FLAGS_FORBID_LANDSCAPE_CHANGES)) + void SurfaceSetStyleAction::Serialise(DataSerialiser& stream) { - return GameActions::Result( - GameActions::Status::Disallowed, STR_CANT_CHANGE_LAND_TYPE, STR_FORBIDDEN_BY_THE_LOCAL_AUTHORITY); + GameAction::Serialise(stream); + + stream << DS_TAG(_range) << DS_TAG(_surfaceStyle) << DS_TAG(_edgeStyle); } - money64 surfaceCost = 0; - money64 edgeCost = 0; - for (CoordsXY coords = { validRange.GetLeft(), validRange.GetTop() }; coords.x <= validRange.GetRight(); - coords.x += kCoordsXYStep) + Result SurfaceSetStyleAction::Query() const { - for (coords.y = validRange.GetTop(); coords.y <= validRange.GetBottom(); coords.y += kCoordsXYStep) - { - if (!LocationValid(coords)) - continue; + auto res = Result(); + res.ErrorTitle = STR_CANT_CHANGE_LAND_TYPE; + res.Expenditure = ExpenditureType::landscaping; - if (gLegacyScene != LegacyScene::scenarioEditor && !gameState.cheats.sandboxMode) + auto validRange = ClampRangeWithinMap(_range.Normalise()); + auto& objManager = OpenRCT2::GetContext()->GetObjectManager(); + if (_surfaceStyle != kObjectEntryIndexNull) + { + const auto surfaceObj = static_cast( + objManager.GetLoadedObject(_surfaceStyle)); + + if (surfaceObj == nullptr) { - if (!MapIsLocationInPark(coords)) + LOG_ERROR("Invalid surface style %u", _surfaceStyle); + return Result(Status::InvalidParameters, STR_CANT_CHANGE_LAND_TYPE, STR_UNKNOWN_OBJECT_TYPE); + } + } + + if (_edgeStyle != kObjectEntryIndexNull) + { + const auto edgeObj = objManager.GetLoadedObject(_edgeStyle); + + if (edgeObj == nullptr) + { + LOG_ERROR("Invalid edge style %u", _edgeStyle); + return Result(Status::InvalidParameters, STR_CANT_CHANGE_LAND_TYPE, STR_UNKNOWN_OBJECT_TYPE); + } + } + + auto xMid = (validRange.GetLeft() + validRange.GetRight()) / 2 + 16; + auto yMid = (validRange.GetTop() + validRange.GetBottom()) / 2 + 16; + auto heightMid = TileElementHeight({ xMid, yMid }); + + res.Position.x = xMid; + res.Position.y = yMid; + res.Position.z = heightMid; + + auto& gameState = getGameState(); + + // Do nothing if not in editor, sandbox mode or landscaping is forbidden + if (gLegacyScene != LegacyScene::scenarioEditor && !gameState.cheats.sandboxMode + && (gameState.park.flags & PARK_FLAGS_FORBID_LANDSCAPE_CHANGES)) + { + return Result(Status::Disallowed, STR_CANT_CHANGE_LAND_TYPE, STR_FORBIDDEN_BY_THE_LOCAL_AUTHORITY); + } + + money64 surfaceCost = 0; + money64 edgeCost = 0; + for (CoordsXY coords = { validRange.GetLeft(), validRange.GetTop() }; coords.x <= validRange.GetRight(); + coords.x += kCoordsXYStep) + { + for (coords.y = validRange.GetTop(); coords.y <= validRange.GetBottom(); coords.y += kCoordsXYStep) + { + if (!LocationValid(coords)) continue; - } - auto surfaceElement = MapGetSurfaceElementAt(coords); - if (surfaceElement == nullptr) - { - continue; - } - - if (_surfaceStyle != kObjectEntryIndexNull) - { - uint8_t curSurfaceStyle = surfaceElement->GetSurfaceObjectIndex(); - - if (_surfaceStyle != curSurfaceStyle) + if (gLegacyScene != LegacyScene::scenarioEditor && !gameState.cheats.sandboxMode) { - const auto* surfaceObject = objManager.GetLoadedObject(_surfaceStyle); - if (surfaceObject != nullptr) + if (!MapIsLocationInPark(coords)) + continue; + } + + auto surfaceElement = MapGetSurfaceElementAt(coords); + if (surfaceElement == nullptr) + { + continue; + } + + if (_surfaceStyle != kObjectEntryIndexNull) + { + uint8_t curSurfaceStyle = surfaceElement->GetSurfaceObjectIndex(); + + if (_surfaceStyle != curSurfaceStyle) { - surfaceCost += surfaceObject->Price; + const auto* surfaceObject = objManager.GetLoadedObject(_surfaceStyle); + if (surfaceObject != nullptr) + { + surfaceCost += surfaceObject->Price; + } + } + } + + if (_edgeStyle != kObjectEntryIndexNull) + { + uint8_t curEdgeStyle = surfaceElement->GetEdgeObjectIndex(); + + if (_edgeStyle != curEdgeStyle) + { + edgeCost += 100; } } } - - if (_edgeStyle != kObjectEntryIndexNull) - { - uint8_t curEdgeStyle = surfaceElement->GetEdgeObjectIndex(); - - if (_edgeStyle != curEdgeStyle) - { - edgeCost += 100; - } - } } + res.Cost = surfaceCost + edgeCost; + + return res; } - res.Cost = surfaceCost + edgeCost; - return res; -} - -GameActions::Result SurfaceSetStyleAction::Execute() const -{ - auto res = GameActions::Result(); - res.ErrorTitle = STR_CANT_CHANGE_LAND_TYPE; - res.Expenditure = ExpenditureType::landscaping; - - auto validRange = ClampRangeWithinMap(_range.Normalise()); - auto xMid = (validRange.GetLeft() + validRange.GetRight()) / 2 + 16; - auto yMid = (validRange.GetTop() + validRange.GetBottom()) / 2 + 16; - auto heightMid = TileElementHeight({ xMid, yMid }); - - res.Position.x = xMid; - res.Position.y = yMid; - res.Position.z = heightMid; - - money64 surfaceCost = 0; - money64 edgeCost = 0; - for (CoordsXY coords = { validRange.GetLeft(), validRange.GetTop() }; coords.x <= validRange.GetRight(); - coords.x += kCoordsXYStep) + Result SurfaceSetStyleAction::Execute() const { - for (coords.y = validRange.GetTop(); coords.y <= validRange.GetBottom(); coords.y += kCoordsXYStep) + auto res = Result(); + res.ErrorTitle = STR_CANT_CHANGE_LAND_TYPE; + res.Expenditure = ExpenditureType::landscaping; + + auto validRange = ClampRangeWithinMap(_range.Normalise()); + auto xMid = (validRange.GetLeft() + validRange.GetRight()) / 2 + 16; + auto yMid = (validRange.GetTop() + validRange.GetBottom()) / 2 + 16; + auto heightMid = TileElementHeight({ xMid, yMid }); + + res.Position.x = xMid; + res.Position.y = yMid; + res.Position.z = heightMid; + + money64 surfaceCost = 0; + money64 edgeCost = 0; + for (CoordsXY coords = { validRange.GetLeft(), validRange.GetTop() }; coords.x <= validRange.GetRight(); + coords.x += kCoordsXYStep) { - if (!LocationValid(coords)) - continue; - - if (gLegacyScene != LegacyScene::scenarioEditor && !getGameState().cheats.sandboxMode) + for (coords.y = validRange.GetTop(); coords.y <= validRange.GetBottom(); coords.y += kCoordsXYStep) { - if (!MapIsLocationInPark(coords)) + if (!LocationValid(coords)) continue; - } - auto surfaceElement = MapGetSurfaceElementAt(coords); - if (surfaceElement == nullptr) - { - continue; - } - - if (_surfaceStyle != kObjectEntryIndexNull) - { - uint8_t curSurfaceStyle = surfaceElement->GetSurfaceObjectIndex(); - - if (_surfaceStyle != curSurfaceStyle) + if (gLegacyScene != LegacyScene::scenarioEditor && !getGameState().cheats.sandboxMode) { - auto& objManager = OpenRCT2::GetContext()->GetObjectManager(); - const auto* surfaceObject = objManager.GetLoadedObject(_surfaceStyle); - if (surfaceObject != nullptr) + if (!MapIsLocationInPark(coords)) + continue; + } + + auto surfaceElement = MapGetSurfaceElementAt(coords); + if (surfaceElement == nullptr) + { + continue; + } + + if (_surfaceStyle != kObjectEntryIndexNull) + { + uint8_t curSurfaceStyle = surfaceElement->GetSurfaceObjectIndex(); + + if (_surfaceStyle != curSurfaceStyle) { - surfaceCost += surfaceObject->Price; + auto& objManager = OpenRCT2::GetContext()->GetObjectManager(); + const auto* surfaceObject = objManager.GetLoadedObject(_surfaceStyle); + if (surfaceObject != nullptr) + { + surfaceCost += surfaceObject->Price; - surfaceElement->SetSurfaceObjectIndex(_surfaceStyle); + surfaceElement->SetSurfaceObjectIndex(_surfaceStyle); + MapInvalidateTileFull(coords); + FootpathRemoveLitter({ coords, TileElementHeight(coords) }); + } + } + } + + if (_edgeStyle != kObjectEntryIndexNull) + { + uint8_t curEdgeStyle = surfaceElement->GetEdgeObjectIndex(); + + if (_edgeStyle != curEdgeStyle) + { + edgeCost += 100; + + surfaceElement->SetEdgeObjectIndex(_edgeStyle); MapInvalidateTileFull(coords); - FootpathRemoveLitter({ coords, TileElementHeight(coords) }); } } - } - if (_edgeStyle != kObjectEntryIndexNull) - { - uint8_t curEdgeStyle = surfaceElement->GetEdgeObjectIndex(); - - if (_edgeStyle != curEdgeStyle) + if (surfaceElement->CanGrassGrow() && (surfaceElement->GetGrassLength() & 7) != GRASS_LENGTH_CLEAR_0) { - edgeCost += 100; - - surfaceElement->SetEdgeObjectIndex(_edgeStyle); + surfaceElement->SetGrassLength(GRASS_LENGTH_CLEAR_0); MapInvalidateTileFull(coords); } } - - if (surfaceElement->CanGrassGrow() && (surfaceElement->GetGrassLength() & 7) != GRASS_LENGTH_CLEAR_0) - { - surfaceElement->SetGrassLength(GRASS_LENGTH_CLEAR_0); - MapInvalidateTileFull(coords); - } } - } - res.Cost = surfaceCost + edgeCost; + res.Cost = surfaceCost + edgeCost; - return res; -} + return res; + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/SurfaceSetStyleAction.h b/src/openrct2/actions/SurfaceSetStyleAction.h index 1225e7a29f..fbf2483235 100644 --- a/src/openrct2/actions/SurfaceSetStyleAction.h +++ b/src/openrct2/actions/SurfaceSetStyleAction.h @@ -11,20 +11,23 @@ #include "GameAction.h" -class SurfaceSetStyleAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - MapRange _range; - OpenRCT2::ObjectEntryIndex _surfaceStyle{}; - OpenRCT2::ObjectEntryIndex _edgeStyle{}; + class SurfaceSetStyleAction final : public GameActionBase + { + private: + MapRange _range; + ObjectEntryIndex _surfaceStyle{}; + ObjectEntryIndex _edgeStyle{}; -public: - SurfaceSetStyleAction() = default; - SurfaceSetStyleAction(MapRange range, OpenRCT2::ObjectEntryIndex surfaceStyle, OpenRCT2::ObjectEntryIndex edgeStyle); + public: + SurfaceSetStyleAction() = default; + SurfaceSetStyleAction(MapRange range, ObjectEntryIndex surfaceStyle, ObjectEntryIndex edgeStyle); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; -}; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/TileModifyAction.cpp b/src/openrct2/actions/TileModifyAction.cpp index 6e9dc12be5..d06eb28adf 100644 --- a/src/openrct2/actions/TileModifyAction.cpp +++ b/src/openrct2/actions/TileModifyAction.cpp @@ -14,245 +14,245 @@ #include "../windows/Intent.h" #include "../world/TileInspector.h" -using namespace OpenRCT2; - -TileModifyAction::TileModifyAction( - CoordsXY loc, TileModifyType setting, uint32_t value1, uint32_t value2, TileElement pasteElement, Banner pasteBanner) - : _loc(loc) - , _setting(setting) - , _value1(value1) - , _value2(value2) - , _pasteElement(pasteElement) - , _pasteBanner(pasteBanner) +namespace OpenRCT2::GameActions { -} - -void TileModifyAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit(_loc); - visitor.Visit("setting", _setting); - visitor.Visit("value1", _value1); - visitor.Visit("value2", _value2); -} - -uint16_t TileModifyAction::GetActionFlags() const -{ - return GameAction::GetActionFlags() | GameActions::Flags::AllowWhilePaused; -} - -void TileModifyAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_loc) << DS_TAG(_setting) << DS_TAG(_value1) << DS_TAG(_value2) << DS_TAG(_pasteElement) - << DS_TAG(_pasteBanner); -} - -GameActions::Result TileModifyAction::Query() const -{ - return QueryExecute(false); -} - -GameActions::Result TileModifyAction::Execute() const -{ - return QueryExecute(true); -} - -GameActions::Result TileModifyAction::QueryExecute(bool isExecuting) const -{ - if (!LocationValid(_loc)) + TileModifyAction::TileModifyAction( + CoordsXY loc, TileModifyType setting, uint32_t value1, uint32_t value2, TileElement pasteElement, Banner pasteBanner) + : _loc(loc) + , _setting(setting) + , _value1(value1) + , _value2(value2) + , _pasteElement(pasteElement) + , _pasteBanner(pasteBanner) { - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_CHANGE_THIS, STR_OFF_EDGE_OF_MAP); - } - auto res = GameActions::Result(); - switch (_setting) - { - case TileModifyType::AnyRemove: - { - const auto elementIndex = _value1; - res = TileInspector::RemoveElementAt(_loc, elementIndex, isExecuting); - break; - } - case TileModifyType::AnySwap: - { - const auto firstIndex = _value1; - const auto secondIndex = _value2; - res = TileInspector::SwapElementsAt(_loc, firstIndex, secondIndex, isExecuting); - break; - } - case TileModifyType::AnyToggleInvisilibity: - { - const auto elementIndex = _value1; - res = TileInspector::ToggleInvisibilityOfElementAt(_loc, elementIndex, isExecuting); - break; - } - case TileModifyType::AnyRotate: - { - const auto elementIndex = _value1; - res = TileInspector::RotateElementAt(_loc, elementIndex, isExecuting); - break; - } - case TileModifyType::AnyPaste: - { - res = TileInspector::PasteElementAt(_loc, _pasteElement, _pasteBanner, isExecuting); - break; - } - case TileModifyType::AnySort: - { - res = TileInspector::SortElementsAt(_loc, isExecuting); - break; - } - case TileModifyType::AnyBaseHeightOffset: - { - const auto elementIndex = _value1; - const auto heightOffset = _value2; - res = TileInspector::AnyBaseHeightOffset(_loc, elementIndex, heightOffset, isExecuting); - break; - } - case TileModifyType::SurfaceShowParkFences: - { - const bool showFences = _value1; - res = TileInspector::SurfaceShowParkFences(_loc, showFences, isExecuting); - break; - } - case TileModifyType::SurfaceToggleCorner: - { - const auto cornerIndex = _value1; - res = TileInspector::SurfaceToggleCorner(_loc, cornerIndex, isExecuting); - break; - } - case TileModifyType::SurfaceToggleDiagonal: - { - res = TileInspector::SurfaceToggleDiagonal(_loc, isExecuting); - break; - } - case TileModifyType::PathSetSlope: - { - const auto elementIndex = _value1; - const bool sloped = _value2; - res = TileInspector::PathSetSloped(_loc, elementIndex, sloped, isExecuting); - break; - } - case TileModifyType::PathSetJunctionRailings: - { - const auto elementIndex = _value1; - const bool hasJunctionRailing = _value2; - res = TileInspector::PathSetJunctionRailings(_loc, elementIndex, hasJunctionRailing, isExecuting); - break; - } - case TileModifyType::PathSetBroken: - { - const auto elementIndex = _value1; - const bool broken = _value2; - res = TileInspector::PathSetBroken(_loc, elementIndex, broken, isExecuting); - break; - } - case TileModifyType::PathToggleEdge: - { - const auto elementIndex = _value1; - const auto edgeIndex = _value2; - res = TileInspector::PathToggleEdge(_loc, elementIndex, edgeIndex, isExecuting); - break; - } - case TileModifyType::EntranceMakeUsable: - { - const auto elementIndex = _value1; - res = TileInspector::EntranceMakeUsable(_loc, elementIndex, isExecuting); - break; - } - case TileModifyType::WallSetSlope: - { - const auto elementIndex = _value1; - const auto slopeValue = _value2; - res = TileInspector::WallSetSlope(_loc, elementIndex, slopeValue, isExecuting); - break; - } - case TileModifyType::WallSetAnimationFrame: - { - const auto elementIndex = _value1; - const auto animationFrameOffset = _value2; - res = TileInspector::WallAnimationFrameOffset(_loc, elementIndex, animationFrameOffset, isExecuting); - break; - } - case TileModifyType::TrackBaseHeightOffset: - { - const auto elementIndex = _value1; - const auto heightOffset = _value2; - res = TileInspector::TrackBaseHeightOffset(_loc, elementIndex, heightOffset, isExecuting); - break; - } - case TileModifyType::TrackSetChainBlock: - { - const auto elementIndex = _value1; - const bool setChain = _value2; - res = TileInspector::TrackSetChain(_loc, elementIndex, true, setChain, isExecuting); - break; - } - case TileModifyType::TrackSetChain: - { - const auto elementIndex = _value1; - const bool setChain = _value2; - res = TileInspector::TrackSetChain(_loc, elementIndex, false, setChain, isExecuting); - break; - } - case TileModifyType::TrackSetBrake: - { - const auto elementIndex = _value1; - const bool isClosed = _value2; - res = TileInspector::TrackSetBrakeClosed(_loc, elementIndex, isClosed, isExecuting); - break; - } - case TileModifyType::TrackSetIndestructible: - { - const auto elementIndex = _value1; - const bool isIndestructible = _value2; - res = TileInspector::TrackSetIndestructible(_loc, elementIndex, isIndestructible, isExecuting); - break; - } - case TileModifyType::ScenerySetQuarterLocation: - { - const auto elementIndex = _value1; - const auto quarterIndex = _value2; - res = TileInspector::ScenerySetQuarterLocation(_loc, elementIndex, quarterIndex, isExecuting); - break; - } - case TileModifyType::ScenerySetQuarterCollision: - { - const auto elementIndex = _value1; - const auto quarterIndex = _value2; - res = TileInspector::ScenerySetQuarterCollision(_loc, elementIndex, quarterIndex, isExecuting); - break; - } - case TileModifyType::BannerToggleBlockingEdge: - { - const auto elementIndex = _value1; - const auto edgeIndex = _value2; - res = TileInspector::BannerToggleBlockingEdge(_loc, elementIndex, edgeIndex, isExecuting); - break; - } - case TileModifyType::WallSetAnimationIsBackwards: - { - const auto elementIndex = _value1; - const bool broken = _value2; - res = TileInspector::WallSetAnimationIsBackwards(_loc, elementIndex, broken, isExecuting); - break; - } - default: - LOG_ERROR("Invalid tile modification type %u", _setting); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_VALUE_OUT_OF_RANGE); } - res.Position.x = _loc.x; - res.Position.y = _loc.y; - res.Position.z = TileElementHeight(_loc); - - if (isExecuting) + void TileModifyAction::AcceptParameters(GameActionParameterVisitor& visitor) { - MapInvalidateTileFull(_loc); - auto intent = Intent(INTENT_ACTION_TILE_MODIFY); - ContextBroadcastIntent(&intent); + visitor.Visit(_loc); + visitor.Visit("setting", _setting); + visitor.Visit("value1", _value1); + visitor.Visit("value2", _value2); } - return res; -} + uint16_t TileModifyAction::GetActionFlags() const + { + return GameAction::GetActionFlags() | Flags::AllowWhilePaused; + } + + void TileModifyAction::Serialise(DataSerialiser& stream) + { + GameAction::Serialise(stream); + + stream << DS_TAG(_loc) << DS_TAG(_setting) << DS_TAG(_value1) << DS_TAG(_value2) << DS_TAG(_pasteElement) + << DS_TAG(_pasteBanner); + } + + Result TileModifyAction::Query() const + { + return QueryExecute(false); + } + + Result TileModifyAction::Execute() const + { + return QueryExecute(true); + } + + Result TileModifyAction::QueryExecute(bool isExecuting) const + { + if (!LocationValid(_loc)) + { + return Result(Status::InvalidParameters, STR_CANT_CHANGE_THIS, STR_OFF_EDGE_OF_MAP); + } + auto res = Result(); + switch (_setting) + { + case TileModifyType::AnyRemove: + { + const auto elementIndex = _value1; + res = TileInspector::RemoveElementAt(_loc, elementIndex, isExecuting); + break; + } + case TileModifyType::AnySwap: + { + const auto firstIndex = _value1; + const auto secondIndex = _value2; + res = TileInspector::SwapElementsAt(_loc, firstIndex, secondIndex, isExecuting); + break; + } + case TileModifyType::AnyToggleInvisilibity: + { + const auto elementIndex = _value1; + res = TileInspector::ToggleInvisibilityOfElementAt(_loc, elementIndex, isExecuting); + break; + } + case TileModifyType::AnyRotate: + { + const auto elementIndex = _value1; + res = TileInspector::RotateElementAt(_loc, elementIndex, isExecuting); + break; + } + case TileModifyType::AnyPaste: + { + res = TileInspector::PasteElementAt(_loc, _pasteElement, _pasteBanner, isExecuting); + break; + } + case TileModifyType::AnySort: + { + res = TileInspector::SortElementsAt(_loc, isExecuting); + break; + } + case TileModifyType::AnyBaseHeightOffset: + { + const auto elementIndex = _value1; + const auto heightOffset = _value2; + res = TileInspector::AnyBaseHeightOffset(_loc, elementIndex, heightOffset, isExecuting); + break; + } + case TileModifyType::SurfaceShowParkFences: + { + const bool showFences = _value1; + res = TileInspector::SurfaceShowParkFences(_loc, showFences, isExecuting); + break; + } + case TileModifyType::SurfaceToggleCorner: + { + const auto cornerIndex = _value1; + res = TileInspector::SurfaceToggleCorner(_loc, cornerIndex, isExecuting); + break; + } + case TileModifyType::SurfaceToggleDiagonal: + { + res = TileInspector::SurfaceToggleDiagonal(_loc, isExecuting); + break; + } + case TileModifyType::PathSetSlope: + { + const auto elementIndex = _value1; + const bool sloped = _value2; + res = TileInspector::PathSetSloped(_loc, elementIndex, sloped, isExecuting); + break; + } + case TileModifyType::PathSetJunctionRailings: + { + const auto elementIndex = _value1; + const bool hasJunctionRailing = _value2; + res = TileInspector::PathSetJunctionRailings(_loc, elementIndex, hasJunctionRailing, isExecuting); + break; + } + case TileModifyType::PathSetBroken: + { + const auto elementIndex = _value1; + const bool broken = _value2; + res = TileInspector::PathSetBroken(_loc, elementIndex, broken, isExecuting); + break; + } + case TileModifyType::PathToggleEdge: + { + const auto elementIndex = _value1; + const auto edgeIndex = _value2; + res = TileInspector::PathToggleEdge(_loc, elementIndex, edgeIndex, isExecuting); + break; + } + case TileModifyType::EntranceMakeUsable: + { + const auto elementIndex = _value1; + res = TileInspector::EntranceMakeUsable(_loc, elementIndex, isExecuting); + break; + } + case TileModifyType::WallSetSlope: + { + const auto elementIndex = _value1; + const auto slopeValue = _value2; + res = TileInspector::WallSetSlope(_loc, elementIndex, slopeValue, isExecuting); + break; + } + case TileModifyType::WallSetAnimationFrame: + { + const auto elementIndex = _value1; + const auto animationFrameOffset = _value2; + res = TileInspector::WallAnimationFrameOffset(_loc, elementIndex, animationFrameOffset, isExecuting); + break; + } + case TileModifyType::TrackBaseHeightOffset: + { + const auto elementIndex = _value1; + const auto heightOffset = _value2; + res = TileInspector::TrackBaseHeightOffset(_loc, elementIndex, heightOffset, isExecuting); + break; + } + case TileModifyType::TrackSetChainBlock: + { + const auto elementIndex = _value1; + const bool setChain = _value2; + res = TileInspector::TrackSetChain(_loc, elementIndex, true, setChain, isExecuting); + break; + } + case TileModifyType::TrackSetChain: + { + const auto elementIndex = _value1; + const bool setChain = _value2; + res = TileInspector::TrackSetChain(_loc, elementIndex, false, setChain, isExecuting); + break; + } + case TileModifyType::TrackSetBrake: + { + const auto elementIndex = _value1; + const bool isClosed = _value2; + res = TileInspector::TrackSetBrakeClosed(_loc, elementIndex, isClosed, isExecuting); + break; + } + case TileModifyType::TrackSetIndestructible: + { + const auto elementIndex = _value1; + const bool isIndestructible = _value2; + res = TileInspector::TrackSetIndestructible(_loc, elementIndex, isIndestructible, isExecuting); + break; + } + case TileModifyType::ScenerySetQuarterLocation: + { + const auto elementIndex = _value1; + const auto quarterIndex = _value2; + res = TileInspector::ScenerySetQuarterLocation(_loc, elementIndex, quarterIndex, isExecuting); + break; + } + case TileModifyType::ScenerySetQuarterCollision: + { + const auto elementIndex = _value1; + const auto quarterIndex = _value2; + res = TileInspector::ScenerySetQuarterCollision(_loc, elementIndex, quarterIndex, isExecuting); + break; + } + case TileModifyType::BannerToggleBlockingEdge: + { + const auto elementIndex = _value1; + const auto edgeIndex = _value2; + res = TileInspector::BannerToggleBlockingEdge(_loc, elementIndex, edgeIndex, isExecuting); + break; + } + case TileModifyType::WallSetAnimationIsBackwards: + { + const auto elementIndex = _value1; + const bool broken = _value2; + res = TileInspector::WallSetAnimationIsBackwards(_loc, elementIndex, broken, isExecuting); + break; + } + default: + LOG_ERROR("Invalid tile modification type %u", _setting); + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_VALUE_OUT_OF_RANGE); + } + + res.Position.x = _loc.x; + res.Position.y = _loc.y; + res.Position.z = TileElementHeight(_loc); + + if (isExecuting) + { + MapInvalidateTileFull(_loc); + auto intent = Intent(INTENT_ACTION_TILE_MODIFY); + ContextBroadcastIntent(&intent); + } + + return res; + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/TileModifyAction.h b/src/openrct2/actions/TileModifyAction.h index 8c7135f032..a11e1e000c 100644 --- a/src/openrct2/actions/TileModifyAction.h +++ b/src/openrct2/actions/TileModifyAction.h @@ -11,61 +11,64 @@ #include "GameAction.h" -enum class TileModifyType : uint8_t +namespace OpenRCT2::GameActions { - AnyRemove, - AnySwap, - AnyToggleInvisilibity, - AnyRotate, - AnyPaste, - AnySort, - AnyBaseHeightOffset, - SurfaceShowParkFences, - SurfaceToggleCorner, - SurfaceToggleDiagonal, - PathSetSlope, - PathSetBroken, - PathToggleEdge, - PathSetJunctionRailings, - EntranceMakeUsable, - WallSetSlope, - WallSetAnimationFrame, - TrackBaseHeightOffset, - TrackSetChain, - TrackSetChainBlock, - TrackSetBrake, - TrackSetIndestructible, - ScenerySetQuarterLocation, - ScenerySetQuarterCollision, - BannerToggleBlockingEdge, - WallSetAnimationIsBackwards, - Count, -}; + enum class TileModifyType : uint8_t + { + AnyRemove, + AnySwap, + AnyToggleInvisilibity, + AnyRotate, + AnyPaste, + AnySort, + AnyBaseHeightOffset, + SurfaceShowParkFences, + SurfaceToggleCorner, + SurfaceToggleDiagonal, + PathSetSlope, + PathSetBroken, + PathToggleEdge, + PathSetJunctionRailings, + EntranceMakeUsable, + WallSetSlope, + WallSetAnimationFrame, + TrackBaseHeightOffset, + TrackSetChain, + TrackSetChainBlock, + TrackSetBrake, + TrackSetIndestructible, + ScenerySetQuarterLocation, + ScenerySetQuarterCollision, + BannerToggleBlockingEdge, + WallSetAnimationIsBackwards, + Count, + }; -class TileModifyAction final : public GameActionBase -{ -private: - CoordsXY _loc; - TileModifyType _setting{}; - uint32_t _value1{}; - uint32_t _value2{}; - OpenRCT2::TileElement _pasteElement{}; - Banner _pasteBanner{}; + class TileModifyAction final : public GameActionBase + { + private: + CoordsXY _loc; + TileModifyType _setting{}; + uint32_t _value1{}; + uint32_t _value2{}; + TileElement _pasteElement{}; + Banner _pasteBanner{}; -public: - TileModifyAction() = default; - TileModifyAction( - CoordsXY loc, TileModifyType setting, uint32_t value1 = 0, uint32_t value2 = 0, OpenRCT2::TileElement pasteElement = {}, - Banner _pasteBanner = {}); + public: + TileModifyAction() = default; + TileModifyAction( + CoordsXY loc, TileModifyType setting, uint32_t value1 = 0, uint32_t value2 = 0, TileElement pasteElement = {}, + Banner _pasteBanner = {}); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; -private: - OpenRCT2::GameActions::Result QueryExecute(bool isExecuting) const; -}; + private: + Result QueryExecute(bool isExecuting) const; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/TrackDesignAction.cpp b/src/openrct2/actions/TrackDesignAction.cpp index 73a379c337..2caa02d2fa 100644 --- a/src/openrct2/actions/TrackDesignAction.cpp +++ b/src/openrct2/actions/TrackDesignAction.cpp @@ -25,253 +25,252 @@ #include "RideSetSettingAction.h" #include "RideSetVehicleAction.h" -using namespace OpenRCT2; - -TrackDesignAction::TrackDesignAction(const CoordsXYZD& location, const TrackDesign& td) - : _loc(location) - , _td(td) +namespace OpenRCT2::GameActions { -} - -void TrackDesignAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit(_loc); - // TODO visit the track design (it has a lot of sub fields) -} - -uint16_t TrackDesignAction::GetActionFlags() const -{ - return GameActionBase::GetActionFlags(); -} - -void TrackDesignAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_loc); - _td.Serialise(stream); -} - -GameActions::Result TrackDesignAction::Query() const -{ - auto res = GameActions::Result(); - res.Position.x = _loc.x + 16; - res.Position.y = _loc.y + 16; - res.Position.z = _loc.z; - res.Expenditure = ExpenditureType::rideConstruction; - - if (!LocationValid(_loc)) + TrackDesignAction::TrackDesignAction(const CoordsXYZD& location, const TrackDesign& td) + : _loc(location) + , _td(td) { - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_OFF_EDGE_OF_MAP); } - auto& gameState = getGameState(); - auto& objManager = GetContext()->GetObjectManager(); - auto entryIndex = objManager.GetLoadedObjectEntryIndex(_td.trackAndVehicle.vehicleObject); - if (entryIndex == kObjectEntryIndexNull) + void TrackDesignAction::AcceptParameters(GameActionParameterVisitor& visitor) { - // Force a fallback if the entry is not invented yet a track design of it is selected, - // which can happen in select-by-track-type mode - if (!RideEntryIsInvented(entryIndex) && !gameState.cheats.ignoreResearchStatus) + visitor.Visit(_loc); + // TODO visit the track design (it has a lot of sub fields) + } + + uint16_t TrackDesignAction::GetActionFlags() const + { + return GameActionBase::GetActionFlags(); + } + + void TrackDesignAction::Serialise(DataSerialiser& stream) + { + GameAction::Serialise(stream); + + stream << DS_TAG(_loc); + _td.Serialise(stream); + } + + Result TrackDesignAction::Query() const + { + auto res = Result(); + res.Position.x = _loc.x + 16; + res.Position.y = _loc.y + 16; + res.Position.z = _loc.z; + res.Expenditure = ExpenditureType::rideConstruction; + + if (!LocationValid(_loc)) { - entryIndex = kObjectEntryIndexNull; + return Result(Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_OFF_EDGE_OF_MAP); } - } - // Colours do not matter as will be overwritten - auto rideCreateAction = RideCreateAction(_td.trackAndVehicle.rtdIndex, entryIndex, 0, 0, gameState.lastEntranceStyle); - rideCreateAction.SetFlags(GetFlags()); - auto r = GameActions::ExecuteNested(&rideCreateAction); - if (r.Error != GameActions::Status::Ok) - { - return GameActions::Result(GameActions::Status::NoFreeElements, STR_CANT_CREATE_NEW_RIDE_ATTRACTION, kStringIdNone); - } - - const auto rideIndex = r.GetData(); - auto ride = GetRide(rideIndex); - if (ride == nullptr) - { - LOG_ERROR("Ride not found for rideIndex %d", rideIndex); - return GameActions::Result( - GameActions::Status::Unknown, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_ERR_RIDE_NOT_FOUND); - } - - bool placeScenery = true; - - uint32_t flags = 0; - if (GetFlags() & GAME_COMMAND_FLAG_GHOST) - flags |= GAME_COMMAND_FLAG_GHOST; - if (GetFlags() & GAME_COMMAND_FLAG_REPLAY) - flags |= GAME_COMMAND_FLAG_REPLAY; - - auto queryRes = TrackDesignPlace(_td, flags, placeScenery, *ride, _loc); - if (_trackDesignPlaceStateSceneryUnavailable) - { - placeScenery = false; - queryRes = TrackDesignPlace(_td, flags, placeScenery, *ride, _loc); - } - - auto gameAction = RideDemolishAction(ride->id, RideModifyType::demolish); - gameAction.SetFlags(GetFlags()); - - GameActions::ExecuteNested(&gameAction); - - if (queryRes.Error != GameActions::Status::Ok) - { - res.Error = queryRes.Error; - res.ErrorTitle = STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE; - res.ErrorMessage = queryRes.ErrorMessage; - res.ErrorMessageArgs = queryRes.ErrorMessageArgs; - return res; - } - - res.Cost = queryRes.Cost; - res.SetData(RideId{ RideId::GetNull() }); - - return res; -} - -GameActions::Result TrackDesignAction::Execute() const -{ - auto res = GameActions::Result(); - res.Position.x = _loc.x + 16; - res.Position.y = _loc.y + 16; - res.Position.z = _loc.z; - res.Expenditure = ExpenditureType::rideConstruction; - - auto& gameState = getGameState(); - auto& objManager = GetContext()->GetObjectManager(); - auto entryIndex = objManager.GetLoadedObjectEntryIndex(_td.trackAndVehicle.vehicleObject); - if (entryIndex != kObjectEntryIndexNull) - { - // Force a fallback if the entry is not invented yet a track design using it is selected. - // This can happen on rides with multiple vehicles where some have been invented and some haven’t. - if (!RideEntryIsInvented(entryIndex) && !gameState.cheats.ignoreResearchStatus) + auto& gameState = getGameState(); + auto& objManager = GetContext()->GetObjectManager(); + auto entryIndex = objManager.GetLoadedObjectEntryIndex(_td.trackAndVehicle.vehicleObject); + if (entryIndex == kObjectEntryIndexNull) { - entryIndex = kObjectEntryIndexNull; + // Force a fallback if the entry is not invented yet a track design of it is selected, + // which can happen in select-by-track-type mode + if (!RideEntryIsInvented(entryIndex) && !gameState.cheats.ignoreResearchStatus) + { + entryIndex = kObjectEntryIndexNull; + } } - } - // Colours do not matter as will be overwritten - auto rideCreateAction = RideCreateAction(_td.trackAndVehicle.rtdIndex, entryIndex, 0, 0, gameState.lastEntranceStyle); - rideCreateAction.SetFlags(GetFlags()); - auto r = GameActions::ExecuteNested(&rideCreateAction); - if (r.Error != GameActions::Status::Ok) - { - return GameActions::Result(GameActions::Status::NoFreeElements, STR_CANT_CREATE_NEW_RIDE_ATTRACTION, kStringIdNone); - } + // Colours do not matter as will be overwritten + auto rideCreateAction = RideCreateAction(_td.trackAndVehicle.rtdIndex, entryIndex, 0, 0, gameState.lastEntranceStyle); + rideCreateAction.SetFlags(GetFlags()); + auto r = ExecuteNested(&rideCreateAction); + if (r.Error != Status::Ok) + { + return Result(Status::NoFreeElements, STR_CANT_CREATE_NEW_RIDE_ATTRACTION, kStringIdNone); + } - const auto rideIndex = r.GetData(); - auto ride = GetRide(rideIndex); - if (ride == nullptr) - { - LOG_ERROR("Ride not found for rideIndex %d", rideIndex); - return GameActions::Result( - GameActions::Status::Unknown, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_ERR_RIDE_NOT_FOUND); - } + const auto rideIndex = r.GetData(); + auto ride = GetRide(rideIndex); + if (ride == nullptr) + { + LOG_ERROR("Ride not found for rideIndex %d", rideIndex); + return Result(Status::Unknown, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_ERR_RIDE_NOT_FOUND); + } - // Query first, this is required again to determine if scenery is available. - uint32_t flags = GetFlags() & ~GAME_COMMAND_FLAG_APPLY; + bool placeScenery = true; - bool placeScenery = true; + uint32_t flags = 0; + if (GetFlags() & GAME_COMMAND_FLAG_GHOST) + flags |= GAME_COMMAND_FLAG_GHOST; + if (GetFlags() & GAME_COMMAND_FLAG_REPLAY) + flags |= GAME_COMMAND_FLAG_REPLAY; - auto queryRes = TrackDesignPlace(_td, flags, placeScenery, *ride, _loc); - if (_trackDesignPlaceStateSceneryUnavailable) - { - placeScenery = false; - queryRes = TrackDesignPlace(_td, flags, placeScenery, *ride, _loc); - } + auto queryRes = TrackDesignPlace(_td, flags, placeScenery, *ride, _loc); + if (_trackDesignPlaceStateSceneryUnavailable) + { + placeScenery = false; + queryRes = TrackDesignPlace(_td, flags, placeScenery, *ride, _loc); + } - if (queryRes.Error != GameActions::Status::Ok) - { auto gameAction = RideDemolishAction(ride->id, RideModifyType::demolish); gameAction.SetFlags(GetFlags()); - GameActions::ExecuteNested(&gameAction); - res.Error = queryRes.Error; - res.ErrorTitle = STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE; - res.ErrorMessage = queryRes.ErrorMessage; - res.ErrorMessageArgs = queryRes.ErrorMessageArgs; + ExecuteNested(&gameAction); + + if (queryRes.Error != Status::Ok) + { + res.Error = queryRes.Error; + res.ErrorTitle = STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE; + res.ErrorMessage = queryRes.ErrorMessage; + res.ErrorMessageArgs = queryRes.ErrorMessageArgs; + return res; + } + + res.Cost = queryRes.Cost; + res.SetData(RideId{ RideId::GetNull() }); return res; } - // Execute. - flags |= GAME_COMMAND_FLAG_APPLY; - - auto execRes = TrackDesignPlace(_td, flags, placeScenery, *ride, _loc); - if (execRes.Error != GameActions::Status::Ok) + Result TrackDesignAction::Execute() const { - auto gameAction = RideDemolishAction(ride->id, RideModifyType::demolish); - gameAction.SetFlags(GetFlags()); - GameActions::ExecuteNested(&gameAction); + auto res = Result(); + res.Position.x = _loc.x + 16; + res.Position.y = _loc.y + 16; + res.Position.z = _loc.z; + res.Expenditure = ExpenditureType::rideConstruction; - res.Error = execRes.Error; - res.ErrorTitle = STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE; - res.ErrorMessage = execRes.ErrorMessage; - res.ErrorMessageArgs = execRes.ErrorMessageArgs; + auto& gameState = getGameState(); + auto& objManager = GetContext()->GetObjectManager(); + auto entryIndex = objManager.GetLoadedObjectEntryIndex(_td.trackAndVehicle.vehicleObject); + if (entryIndex != kObjectEntryIndexNull) + { + // Force a fallback if the entry is not invented yet a track design using it is selected. + // This can happen on rides with multiple vehicles where some have been invented and some haven’t. + if (!RideEntryIsInvented(entryIndex) && !gameState.cheats.ignoreResearchStatus) + { + entryIndex = kObjectEntryIndexNull; + } + } + + // Colours do not matter as will be overwritten + auto rideCreateAction = RideCreateAction(_td.trackAndVehicle.rtdIndex, entryIndex, 0, 0, gameState.lastEntranceStyle); + rideCreateAction.SetFlags(GetFlags()); + auto r = ExecuteNested(&rideCreateAction); + if (r.Error != Status::Ok) + { + return Result(Status::NoFreeElements, STR_CANT_CREATE_NEW_RIDE_ATTRACTION, kStringIdNone); + } + + const auto rideIndex = r.GetData(); + auto ride = GetRide(rideIndex); + if (ride == nullptr) + { + LOG_ERROR("Ride not found for rideIndex %d", rideIndex); + return Result(Status::Unknown, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_ERR_RIDE_NOT_FOUND); + } + + // Query first, this is required again to determine if scenery is available. + uint32_t flags = GetFlags() & ~GAME_COMMAND_FLAG_APPLY; + + bool placeScenery = true; + + auto queryRes = TrackDesignPlace(_td, flags, placeScenery, *ride, _loc); + if (_trackDesignPlaceStateSceneryUnavailable) + { + placeScenery = false; + queryRes = TrackDesignPlace(_td, flags, placeScenery, *ride, _loc); + } + + if (queryRes.Error != Status::Ok) + { + auto gameAction = RideDemolishAction(ride->id, RideModifyType::demolish); + gameAction.SetFlags(GetFlags()); + ExecuteNested(&gameAction); + + res.Error = queryRes.Error; + res.ErrorTitle = STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE; + res.ErrorMessage = queryRes.ErrorMessage; + res.ErrorMessageArgs = queryRes.ErrorMessageArgs; + + return res; + } + + // Execute. + flags |= GAME_COMMAND_FLAG_APPLY; + + auto execRes = TrackDesignPlace(_td, flags, placeScenery, *ride, _loc); + if (execRes.Error != Status::Ok) + { + auto gameAction = RideDemolishAction(ride->id, RideModifyType::demolish); + gameAction.SetFlags(GetFlags()); + ExecuteNested(&gameAction); + + res.Error = execRes.Error; + res.ErrorTitle = STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE; + res.ErrorMessage = execRes.ErrorMessage; + res.ErrorMessageArgs = execRes.ErrorMessageArgs; + + return res; + } + + if (entryIndex != kObjectEntryIndexNull) + { + auto colour = RideGetUnusedPresetVehicleColour(entryIndex); + auto rideSetVehicleAction = GameActions::RideSetVehicleAction( + ride->id, GameActions::RideSetVehicleType::RideEntry, entryIndex, colour); + ExecuteNested(&rideSetVehicleAction); + } + + SetOperatingSettingNested(ride->id, RideSetSetting::Mode, static_cast(_td.operation.rideMode), flags); + auto rideSetVehicleAction2 = GameActions::RideSetVehicleAction( + ride->id, GameActions::RideSetVehicleType::NumTrains, _td.trackAndVehicle.numberOfTrains); + ExecuteNested(&rideSetVehicleAction2); + + auto rideSetVehicleAction3 = GameActions::RideSetVehicleAction( + ride->id, GameActions::RideSetVehicleType::NumCarsPerTrain, _td.trackAndVehicle.numberOfCarsPerTrain); + ExecuteNested(&rideSetVehicleAction3); + + SetOperatingSettingNested(ride->id, RideSetSetting::Departure, _td.operation.departFlags, flags); + SetOperatingSettingNested(ride->id, RideSetSetting::MinWaitingTime, _td.operation.minWaitingTime, flags); + SetOperatingSettingNested(ride->id, RideSetSetting::MaxWaitingTime, _td.operation.maxWaitingTime, flags); + SetOperatingSettingNested(ride->id, RideSetSetting::Operation, _td.operation.operationSetting, flags); + SetOperatingSettingNested(ride->id, RideSetSetting::LiftHillSpeed, _td.operation.liftHillSpeed, flags); + + auto numCircuits = std::max(1, _td.operation.numCircuits); + SetOperatingSettingNested(ride->id, RideSetSetting::NumCircuits, numCircuits, flags); + + uint8_t defaultInspectionInterval = Config::Get().general.DefaultInspectionInterval; + if (defaultInspectionInterval <= RIDE_INSPECTION_NEVER) + SetOperatingSettingNested(ride->id, RideSetSetting::InspectionInterval, defaultInspectionInterval, flags); + + ride->lifecycleFlags |= RIDE_LIFECYCLE_NOT_CUSTOM_DESIGN; + ride->vehicleColourSettings = _td.appearance.vehicleColourSettings; + + ride->entranceStyle = objManager.GetLoadedObjectEntryIndex(_td.appearance.stationObjectIdentifier); + if (ride->entranceStyle == kObjectEntryIndexNull) + { + ride->entranceStyle = gameState.lastEntranceStyle; + } + + for (size_t i = 0; i < std::min(std::size(ride->trackColours), std::size(_td.appearance.trackColours)); i++) + { + ride->trackColours[i] = _td.appearance.trackColours[i]; + } + + for (size_t i = 0; i < Limits::kMaxVehicleColours; i++) + { + ride->vehicleColours[i] = _td.appearance.vehicleColours[i]; + } + + for (int32_t count = 1; count == 1 || r.Error != Status::Ok; ++count) + { + auto name = count == 1 ? _td.gameStateData.name : (_td.gameStateData.name + " " + std::to_string(count)); + auto gameAction = RideSetNameAction(ride->id, name); + gameAction.SetFlags(GetFlags()); + r = ExecuteNested(&gameAction); + } + res.Cost = execRes.Cost; + res.SetData(RideId{ ride->id }); return res; } - - if (entryIndex != kObjectEntryIndexNull) - { - auto colour = RideGetUnusedPresetVehicleColour(entryIndex); - auto rideSetVehicleAction = RideSetVehicleAction(ride->id, RideSetVehicleType::RideEntry, entryIndex, colour); - GameActions::ExecuteNested(&rideSetVehicleAction); - } - - SetOperatingSettingNested(ride->id, RideSetSetting::Mode, static_cast(_td.operation.rideMode), flags); - auto rideSetVehicleAction2 = RideSetVehicleAction( - ride->id, RideSetVehicleType::NumTrains, _td.trackAndVehicle.numberOfTrains); - GameActions::ExecuteNested(&rideSetVehicleAction2); - - auto rideSetVehicleAction3 = RideSetVehicleAction( - ride->id, RideSetVehicleType::NumCarsPerTrain, _td.trackAndVehicle.numberOfCarsPerTrain); - GameActions::ExecuteNested(&rideSetVehicleAction3); - - SetOperatingSettingNested(ride->id, RideSetSetting::Departure, _td.operation.departFlags, flags); - SetOperatingSettingNested(ride->id, RideSetSetting::MinWaitingTime, _td.operation.minWaitingTime, flags); - SetOperatingSettingNested(ride->id, RideSetSetting::MaxWaitingTime, _td.operation.maxWaitingTime, flags); - SetOperatingSettingNested(ride->id, RideSetSetting::Operation, _td.operation.operationSetting, flags); - SetOperatingSettingNested(ride->id, RideSetSetting::LiftHillSpeed, _td.operation.liftHillSpeed, flags); - - auto numCircuits = std::max(1, _td.operation.numCircuits); - SetOperatingSettingNested(ride->id, RideSetSetting::NumCircuits, numCircuits, flags); - - uint8_t defaultInspectionInterval = Config::Get().general.DefaultInspectionInterval; - if (defaultInspectionInterval <= RIDE_INSPECTION_NEVER) - SetOperatingSettingNested(ride->id, RideSetSetting::InspectionInterval, defaultInspectionInterval, flags); - - ride->lifecycleFlags |= RIDE_LIFECYCLE_NOT_CUSTOM_DESIGN; - ride->vehicleColourSettings = _td.appearance.vehicleColourSettings; - - ride->entranceStyle = objManager.GetLoadedObjectEntryIndex(_td.appearance.stationObjectIdentifier); - if (ride->entranceStyle == kObjectEntryIndexNull) - { - ride->entranceStyle = gameState.lastEntranceStyle; - } - - for (size_t i = 0; i < std::min(std::size(ride->trackColours), std::size(_td.appearance.trackColours)); i++) - { - ride->trackColours[i] = _td.appearance.trackColours[i]; - } - - for (size_t i = 0; i < Limits::kMaxVehicleColours; i++) - { - ride->vehicleColours[i] = _td.appearance.vehicleColours[i]; - } - - for (int32_t count = 1; count == 1 || r.Error != GameActions::Status::Ok; ++count) - { - auto name = count == 1 ? _td.gameStateData.name : (_td.gameStateData.name + " " + std::to_string(count)); - auto gameAction = RideSetNameAction(ride->id, name); - gameAction.SetFlags(GetFlags()); - r = GameActions::ExecuteNested(&gameAction); - } - res.Cost = execRes.Cost; - res.SetData(RideId{ ride->id }); - - return res; -} +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/TrackDesignAction.h b/src/openrct2/actions/TrackDesignAction.h index c82affbd69..df8bd1fbd4 100644 --- a/src/openrct2/actions/TrackDesignAction.h +++ b/src/openrct2/actions/TrackDesignAction.h @@ -12,22 +12,25 @@ #include "../ride/TrackDesign.h" #include "GameAction.h" -class TrackDesignAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - CoordsXYZD _loc; - TrackDesign _td; + class TrackDesignAction final : public GameActionBase + { + private: + CoordsXYZD _loc; + TrackDesign _td; -public: - TrackDesignAction() = default; - TrackDesignAction(const CoordsXYZD& location, const TrackDesign& td); + public: + TrackDesignAction() = default; + TrackDesignAction(const CoordsXYZD& location, const TrackDesign& td); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; + void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; -}; + Result Query() const override; + Result Execute() const override; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/TrackPlaceAction.cpp b/src/openrct2/actions/TrackPlaceAction.cpp index 81e0c55acc..029777559b 100644 --- a/src/openrct2/actions/TrackPlaceAction.cpp +++ b/src/openrct2/actions/TrackPlaceAction.cpp @@ -29,737 +29,721 @@ #include "../world/tile_element/TrackElement.h" #include "RideSetSettingAction.h" -using namespace OpenRCT2; -using namespace OpenRCT2::Numerics; -using namespace OpenRCT2::TrackMetaData; - -TrackPlaceAction::TrackPlaceAction( - RideId rideIndex, OpenRCT2::TrackElemType trackType, ride_type_t rideType, const CoordsXYZD& origin, int32_t brakeSpeed, - int32_t colour, int32_t seatRotation, SelectedLiftAndInverted liftHillAndAlternativeState, bool fromTrackDesign) - : _rideIndex(rideIndex) - , _trackType(trackType) - , _rideType(rideType) - , _origin(origin) - , _brakeSpeed(brakeSpeed) - , _colour(colour) - , _seatRotation(seatRotation) - , _trackPlaceFlags(liftHillAndAlternativeState) - , _fromTrackDesign(fromTrackDesign) +namespace OpenRCT2::GameActions { - _origin.direction &= 3; -} + using namespace OpenRCT2::Numerics; + using namespace OpenRCT2::TrackMetaData; -void TrackPlaceAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit(_origin); - visitor.Visit("ride", _rideIndex); - visitor.Visit("trackType", _trackType); - visitor.Visit("rideType", _rideType); - visitor.Visit("brakeSpeed", _brakeSpeed); - visitor.Visit("colour", _colour); - visitor.Visit("seatRotation", _seatRotation); - visitor.Visit("trackPlaceFlags", _trackPlaceFlags.holder); - visitor.Visit("isFromTrackDesign", _fromTrackDesign); -} - -uint16_t TrackPlaceAction::GetActionFlags() const -{ - return GameAction::GetActionFlags(); -} - -void TrackPlaceAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_rideIndex) << DS_TAG(_trackType) << DS_TAG(_rideType) << DS_TAG(_origin) << DS_TAG(_brakeSpeed) - << DS_TAG(_colour) << DS_TAG(_seatRotation) << DS_TAG(_trackPlaceFlags.holder); -} - -GameActions::Result TrackPlaceAction::Query() const -{ - auto ride = GetRide(_rideIndex); - if (ride == nullptr) + TrackPlaceAction::TrackPlaceAction( + RideId rideIndex, TrackElemType trackType, ride_type_t rideType, const CoordsXYZD& origin, int32_t brakeSpeed, + int32_t colour, int32_t seatRotation, SelectedLiftAndInverted liftHillAndAlternativeState, bool fromTrackDesign) + : _rideIndex(rideIndex) + , _trackType(trackType) + , _rideType(rideType) + , _origin(origin) + , _brakeSpeed(brakeSpeed) + , _colour(colour) + , _seatRotation(seatRotation) + , _trackPlaceFlags(liftHillAndAlternativeState) + , _fromTrackDesign(fromTrackDesign) { - LOG_ERROR("Ride not found for rideIndex %d", _rideIndex.ToUnderlying()); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_ERR_RIDE_NOT_FOUND); - } - const auto* rideEntry = GetRideEntryByIndex(ride->subtype); - if (rideEntry == nullptr) - { - LOG_ERROR("Invalid ride subtype for track placement, rideIndex = %d", _rideIndex.ToUnderlying()); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_UNKNOWN_OBJECT_TYPE); + _origin.direction &= 3; } - if (!DirectionValid(_origin.direction)) + void TrackPlaceAction::AcceptParameters(GameActionParameterVisitor& visitor) { - LOG_ERROR("Invalid direction for track placement, direction = %d", _origin.direction); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_ERR_VALUE_OUT_OF_RANGE); + visitor.Visit(_origin); + visitor.Visit("ride", _rideIndex); + visitor.Visit("trackType", _trackType); + visitor.Visit("rideType", _rideType); + visitor.Visit("brakeSpeed", _brakeSpeed); + visitor.Visit("colour", _colour); + visitor.Visit("seatRotation", _seatRotation); + visitor.Visit("trackPlaceFlags", _trackPlaceFlags.holder); + visitor.Visit("isFromTrackDesign", _fromTrackDesign); } - auto& gameState = getGameState(); - if (_rideType != ride->type && !gameState.cheats.allowArbitraryRideTypeChanges) + uint16_t TrackPlaceAction::GetActionFlags() const { - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, kStringIdNone); + return GameAction::GetActionFlags(); } - if (_rideType > RIDE_TYPE_COUNT) + void TrackPlaceAction::Serialise(DataSerialiser& stream) { - LOG_ERROR("Invalid ride type for track placement, rideType = %d", _rideType); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_ERR_VALUE_OUT_OF_RANGE); + GameAction::Serialise(stream); + + stream << DS_TAG(_rideIndex) << DS_TAG(_trackType) << DS_TAG(_rideType) << DS_TAG(_origin) << DS_TAG(_brakeSpeed) + << DS_TAG(_colour) << DS_TAG(_seatRotation) << DS_TAG(_trackPlaceFlags.holder); } - if (_brakeSpeed > kMaximumTrackSpeed) + Result TrackPlaceAction::Query() const { - LOG_WARNING("Invalid speed for track placement, speed = %d", _brakeSpeed); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_SPEED_TOO_HIGH); - } - - auto res = GameActions::Result(); - res.Expenditure = ExpenditureType::rideConstruction; - res.Position.x = _origin.x + 16; - res.Position.y = _origin.y + 16; - res.Position.z = _origin.z; - - auto resultData = TrackPlaceActionResult{}; - - const auto& rtd = ride->getRideTypeDescriptor(); - - if ((ride->lifecycleFlags & RIDE_LIFECYCLE_INDESTRUCTIBLE_TRACK) && _trackType == TrackElemType::EndStation) - { - return GameActions::Result( - GameActions::Status::Disallowed, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_NOT_ALLOWED_TO_MODIFY_STATION); - } - - if (!(GetActionFlags() & GameActions::Flags::AllowWhilePaused)) - { - if (GameIsPaused() && !gameState.cheats.buildInPauseMode) + auto ride = GetRide(_rideIndex); + if (ride == nullptr) { - return GameActions::Result( - GameActions::Status::Disallowed, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, - STR_CONSTRUCTION_NOT_POSSIBLE_WHILE_GAME_IS_PAUSED); + LOG_ERROR("Ride not found for rideIndex %d", _rideIndex.ToUnderlying()); + return Result(Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_ERR_RIDE_NOT_FOUND); } - } - - if (!rtd.HasFlag(RtdFlag::isFlatRide)) - { - if (_trackType == TrackElemType::OnRidePhoto) + const auto* rideEntry = GetRideEntryByIndex(ride->subtype); + if (rideEntry == nullptr) { - if (ride->lifecycleFlags & RIDE_LIFECYCLE_ON_RIDE_PHOTO) - { - return GameActions::Result( - GameActions::Status::Disallowed, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, - STR_ONLY_ONE_ON_RIDE_PHOTO_PER_RIDE); - } - } - else if (_trackType == TrackElemType::CableLiftHill) - { - if (ride->lifecycleFlags & RIDE_LIFECYCLE_CABLE_LIFT_HILL_COMPONENT_USED) - { - return GameActions::Result( - GameActions::Status::Disallowed, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, - STR_ONLY_ONE_CABLE_LIFT_HILL_PER_RIDE); - } - } - // Backwards steep lift hills are allowed, even on roller coasters that do not support forwards steep lift hills. - if (_trackPlaceFlags.has(LiftHillAndInverted::liftHill) && !rtd.SupportsTrackGroup(TrackGroup::liftHillSteep) - && !gameState.cheats.enableChainLiftOnAllTrack) - { - const auto& ted = GetTrackElementDescriptor(_trackType); - if (ted.flags & TRACK_ELEM_FLAG_IS_STEEP_UP) - { - return GameActions::Result( - GameActions::Status::Disallowed, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, - STR_TOO_STEEP_FOR_LIFT_HILL); - } - } - } - - const auto& ted = GetTrackElementDescriptor(_trackType); - uint32_t numElements = 0; - // First check if any of the track pieces are outside the park - for (uint8_t i = 0; i < ted.numSequences; i++) - { - const auto& trackBlock = ted.sequences[i].clearance; - auto rotatedTrack = CoordsXYZ{ CoordsXY{ trackBlock.x, trackBlock.y }.Rotate(_origin.direction), 0 }; - auto tileCoords = CoordsXYZ{ _origin.x, _origin.y, _origin.z } + rotatedTrack; - - if (!LocationValid(tileCoords)) - { - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_OFF_EDGE_OF_MAP); - } - if (!MapIsLocationOwned(tileCoords) && !gameState.cheats.sandboxMode) - { - return GameActions::Result( - GameActions::Status::Disallowed, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_LAND_NOT_OWNED_BY_PARK); - } - numElements++; - } - - if (!CheckMapCapacity(numElements)) - { - LOG_ERROR("Not enough free map elements to place track."); - return GameActions::Result( - GameActions::Status::NoFreeElements, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, - STR_TILE_ELEMENT_LIMIT_REACHED); - } - - if (!gameState.cheats.allowTrackPlaceInvalidHeights) - { - if (ted.flags & TRACK_ELEM_FLAG_STARTS_AT_HALF_HEIGHT) - { - if ((_origin.z & 0x0F) != 8) - { - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_INVALID_HEIGHT); - } - } - else - { - if ((_origin.z & 0x0F) != 0) - { - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_INVALID_HEIGHT); - } - } - } - - // If that is not the case, then perform the remaining checks - auto clearanceHeight = rideEntry->Clearance; - - money64 costs = 0; - money64 supportCosts = 0; - for (int32_t blockIndex = 0; blockIndex < ted.numSequences; blockIndex++) - { - const auto& trackBlock = ted.sequences[blockIndex].clearance; - auto rotatedTrack = CoordsXYZ{ CoordsXY{ trackBlock.x, trackBlock.y }.Rotate(_origin.direction), trackBlock.z }; - auto mapLoc = CoordsXYZ{ _origin.x, _origin.y, _origin.z } + rotatedTrack; - auto quarterTile = trackBlock.quarterTile.Rotate(_origin.direction); - - if (mapLoc.z < 16) - { - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_TOO_LOW); + LOG_ERROR("Invalid ride subtype for track placement, rideIndex = %d", _rideIndex.ToUnderlying()); + return Result(Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_UNKNOWN_OBJECT_TYPE); } - int32_t baseZ = floor2(mapLoc.z, kCoordsZStep); - - int32_t clearanceZ = trackBlock.clearanceZ; - if (trackBlock.flags & RCT_PREVIEW_TRACK_FLAG_IS_VERTICAL && clearanceHeight > 24) + if (!DirectionValid(_origin.direction)) { - clearanceZ += 24; - } - else - { - clearanceZ += clearanceHeight; - } - - clearanceZ = floor2(clearanceZ, kCoordsZStep) + baseZ; - - if (clearanceZ > MAX_TRACK_HEIGHT) - { - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_TOO_HIGH); - } - - auto crossingMode = (rtd.HasFlag(RtdFlag::supportsLevelCrossings) && _trackType == TrackElemType::Flat) - ? CreateCrossingMode::trackOverPath - : CreateCrossingMode::none; - auto canBuild = MapCanConstructWithClearAt( - { mapLoc, baseZ, clearanceZ }, &MapPlaceNonSceneryClearFunc, quarterTile, GetFlags(), crossingMode); - if (canBuild.Error != GameActions::Status::Ok) - { - canBuild.ErrorTitle = STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE; - return canBuild; - } - costs += canBuild.Cost; - - const auto clearanceData = canBuild.GetData(); - uint8_t mapGroundFlags = clearanceData.GroundFlags & (ELEMENT_IS_ABOVE_GROUND | ELEMENT_IS_UNDERGROUND); - if (!(ted.flags & TRACK_ELEM_FLAG_CAN_BE_PARTLY_UNDERGROUND)) - { - if (resultData.GroundFlags != 0 && (resultData.GroundFlags & mapGroundFlags) == 0) - { - return GameActions::Result( - GameActions::Status::Disallowed, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, - STR_CANT_BUILD_PARTLY_ABOVE_AND_PARTLY_BELOW_GROUND); - } - } - - resultData.GroundFlags = mapGroundFlags; - if (ted.flags & TRACK_ELEM_FLAG_ONLY_ABOVE_GROUND) - { - if (resultData.GroundFlags & ELEMENT_IS_UNDERGROUND) - { - return GameActions::Result( - GameActions::Status::Disallowed, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, - STR_CAN_ONLY_BUILD_THIS_ABOVE_GROUND); - } - } - - if (ted.flags & TRACK_ELEM_FLAG_ONLY_UNDERWATER) - { // No element has this flag - if (clearanceData.GroundFlags & ELEMENT_IS_UNDERWATER) - { - return GameActions::Result( - GameActions::Status::Disallowed, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, - STR_CAN_ONLY_BUILD_THIS_UNDERWATER); - } - } - - if (clearanceData.GroundFlags & ELEMENT_IS_UNDERWATER && !gameState.cheats.disableClearanceChecks) - { - return GameActions::Result( - GameActions::Status::Disallowed, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, - STR_RIDE_CANT_BUILD_THIS_UNDERWATER); - } - - if (rtd.HasFlag(RtdFlag::trackMustBeOnWater) && !_trackDesignDrawingPreview) - { - auto surfaceElement = MapGetSurfaceElementAt(mapLoc); - if (surfaceElement == nullptr) - { - return GameActions::Result( - GameActions::Status::Unknown, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, - STR_ERR_SURFACE_ELEMENT_NOT_FOUND); - } - - auto waterHeight = surfaceElement->GetWaterHeight(); - if (waterHeight == 0) - { - return GameActions::Result( - GameActions::Status::Disallowed, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, - STR_CAN_ONLY_BUILD_THIS_ON_WATER); - } - - if (waterHeight != baseZ) - { - return GameActions::Result( - GameActions::Status::Disallowed, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, - STR_CAN_ONLY_BUILD_THIS_ON_WATER); - } - waterHeight -= kLandHeightStep; - if (waterHeight == surfaceElement->GetBaseZ()) - { - uint8_t slope = surfaceElement->GetSlope() & kTileSlopeRaisedCornersMask; - if (slope == kTileSlopeWCornerDown || slope == kTileSlopeSCornerDown || slope == kTileSlopeECornerDown - || slope == kTileSlopeNCornerDown) - { - return GameActions::Result( - GameActions::Status::Disallowed, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, - STR_CAN_ONLY_BUILD_THIS_ON_WATER); - } - } - } - - int32_t entranceDirections = ted.sequences[0].flags; - if ((entranceDirections & TRACK_SEQUENCE_FLAG_ORIGIN) && blockIndex == 0) - { - const auto addElementResult = TrackAddStationElement( - { mapLoc, baseZ, _origin.direction }, _rideIndex, 0, _fromTrackDesign); - if (!addElementResult.Successful) - { - return GameActions::Result( - GameActions::Status::Unknown, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, addElementResult.Message); - } - } - - // 6c5648 12 push - auto surfaceElement = MapGetSurfaceElementAt(mapLoc); - if (surfaceElement == nullptr) - { - return GameActions::Result( - GameActions::Status::Unknown, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, - STR_ERR_SURFACE_ELEMENT_NOT_FOUND); - } - - if (!gameState.cheats.disableSupportLimits) - { - int32_t ride_height = clearanceZ - surfaceElement->GetBaseZ(); - if (ride_height >= 0) - { - uint16_t maxHeight; - - if (rtd.HasFlag(RtdFlag::listVehiclesSeparately) && rideEntry->max_height != 0) - { - maxHeight = rideEntry->max_height; - } - else - { - maxHeight = rtd.Heights.MaxHeight; - } - - ride_height /= kCoordsZPerTinyZ; - if (ride_height > maxHeight && !_trackDesignDrawingPreview) - { - return GameActions::Result( - GameActions::Status::Disallowed, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, - STR_TOO_HIGH_FOR_SUPPORTS); - } - } - } - - int32_t supportHeight = baseZ - surfaceElement->GetBaseZ(); - if (supportHeight < 0) - { - supportHeight = (10 * kCoordsZStep); - } - - supportCosts += ((supportHeight / (2 * kCoordsZStep)) * rtd.BuildCosts.SupportPrice); - } - - money64 price = rtd.BuildCosts.TrackPrice; - price *= ted.priceModifier; - - price >>= 16; - res.Cost = costs + supportCosts + price; - res.SetData(std::move(resultData)); - - return res; -} - -GameActions::Result TrackPlaceAction::Execute() const -{ - auto ride = GetRide(_rideIndex); - if (ride == nullptr) - { - LOG_ERROR("Invalid ride for track placement, rideIndex = %d", _rideIndex.ToUnderlying()); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_ERR_RIDE_NOT_FOUND); - } - - const auto* rideEntry = GetRideEntryByIndex(ride->subtype); - if (rideEntry == nullptr) - { - LOG_ERROR("Invalid ride subtype for track placement, rideIndex = %d", _rideIndex.ToUnderlying()); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_UNKNOWN_OBJECT_TYPE); - } - - auto res = GameActions::Result(); - res.Expenditure = ExpenditureType::rideConstruction; - res.Position.x = _origin.x + 16; - res.Position.y = _origin.y + 16; - res.Position.z = _origin.z; - - auto resultData = TrackPlaceActionResult{}; - - const auto& rtd = ride->getRideTypeDescriptor(); - - const auto& ted = GetTrackElementDescriptor(_trackType); - - money64 costs = 0; - money64 supportCosts = 0; - const auto& block0 = ted.sequences[0].clearance; - auto clearanceHeight = rideEntry->Clearance; - CoordsXYZ originLocation = CoordsXYZ{ _origin.x, _origin.y, _origin.z } - + CoordsXYZ{ CoordsXY{ block0.x, block0.y }.Rotate(_origin.direction), block0.z }; - for (int32_t blockIndex = 0; blockIndex < ted.numSequences; blockIndex++) - { - const auto& trackBlock = ted.sequences[blockIndex].clearance; - auto rotatedTrack = CoordsXYZ{ CoordsXY{ trackBlock.x, trackBlock.y }.Rotate(_origin.direction), trackBlock.z }; - auto mapLoc = CoordsXYZ{ _origin.x, _origin.y, _origin.z } + rotatedTrack; - - auto quarterTile = trackBlock.quarterTile.Rotate(_origin.direction); - - int32_t baseZ = floor2(mapLoc.z, kCoordsZStep); - int32_t clearanceZ = trackBlock.clearanceZ; - if (trackBlock.flags & RCT_PREVIEW_TRACK_FLAG_IS_VERTICAL && clearanceHeight > 24) - { - clearanceZ += 24; - } - else - { - clearanceZ += clearanceHeight; - } - - clearanceZ = floor2(clearanceZ, kCoordsZStep) + baseZ; - const auto mapLocWithClearance = CoordsXYRangedZ(mapLoc, baseZ, clearanceZ); - - auto crossingMode = (rtd.HasFlag(RtdFlag::supportsLevelCrossings) && _trackType == TrackElemType::Flat) - ? CreateCrossingMode::trackOverPath - : CreateCrossingMode::none; - auto canBuild = MapCanConstructWithClearAt( - mapLocWithClearance, &MapPlaceNonSceneryClearFunc, quarterTile, GetFlags() | GAME_COMMAND_FLAG_APPLY, crossingMode); - if (canBuild.Error != GameActions::Status::Ok) - { - canBuild.ErrorTitle = STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE; - return canBuild; - } - costs += canBuild.Cost; - - // When building a level crossing, remove any pre-existing path furniture. - if (crossingMode == CreateCrossingMode::trackOverPath && !(GetFlags() & GAME_COMMAND_FLAG_GHOST)) - { - auto footpathElement = MapGetFootpathElement(mapLoc); - if (footpathElement != nullptr && footpathElement->HasAddition()) - { - footpathElement->SetAddition(0); - } + LOG_ERROR("Invalid direction for track placement, direction = %d", _origin.direction); + return Result( + Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_ERR_VALUE_OUT_OF_RANGE); } auto& gameState = getGameState(); - if (!(GetFlags() & GAME_COMMAND_FLAG_GHOST) && !gameState.cheats.disableClearanceChecks) + if (_rideType != ride->type && !gameState.cheats.allowArbitraryRideTypeChanges) { - FootpathRemoveLitter(mapLoc); - if (rtd.HasFlag(RtdFlag::noWallsAroundTrack)) + return Result(Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, kStringIdNone); + } + + if (_rideType > RIDE_TYPE_COUNT) + { + LOG_ERROR("Invalid ride type for track placement, rideType = %d", _rideType); + return Result( + Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_ERR_VALUE_OUT_OF_RANGE); + } + + if (_brakeSpeed > kMaximumTrackSpeed) + { + LOG_WARNING("Invalid speed for track placement, speed = %d", _brakeSpeed); + return Result(Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_SPEED_TOO_HIGH); + } + + auto res = Result(); + res.Expenditure = ExpenditureType::rideConstruction; + res.Position.x = _origin.x + 16; + res.Position.y = _origin.y + 16; + res.Position.z = _origin.z; + + auto resultData = TrackPlaceActionResult{}; + + const auto& rtd = ride->getRideTypeDescriptor(); + + if ((ride->lifecycleFlags & RIDE_LIFECYCLE_INDESTRUCTIBLE_TRACK) && _trackType == TrackElemType::EndStation) + { + return Result( + Status::Disallowed, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_NOT_ALLOWED_TO_MODIFY_STATION); + } + + if (!(GetActionFlags() & Flags::AllowWhilePaused)) + { + if (GameIsPaused() && !gameState.cheats.buildInPauseMode) { - WallRemoveAt(mapLocWithClearance); + return Result( + Status::Disallowed, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, + STR_CONSTRUCTION_NOT_POSSIBLE_WHILE_GAME_IS_PAUSED); + } + } + + if (!rtd.HasFlag(RtdFlag::isFlatRide)) + { + if (_trackType == TrackElemType::OnRidePhoto) + { + if (ride->lifecycleFlags & RIDE_LIFECYCLE_ON_RIDE_PHOTO) + { + return Result( + Status::Disallowed, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, + STR_ONLY_ONE_ON_RIDE_PHOTO_PER_RIDE); + } + } + else if (_trackType == TrackElemType::CableLiftHill) + { + if (ride->lifecycleFlags & RIDE_LIFECYCLE_CABLE_LIFT_HILL_COMPONENT_USED) + { + return Result( + Status::Disallowed, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, + STR_ONLY_ONE_CABLE_LIFT_HILL_PER_RIDE); + } + } + // Backwards steep lift hills are allowed, even on roller coasters that do not support forwards steep lift hills. + if (_trackPlaceFlags.has(LiftHillAndInverted::liftHill) && !rtd.SupportsTrackGroup(TrackGroup::liftHillSteep) + && !gameState.cheats.enableChainLiftOnAllTrack) + { + const auto& ted = GetTrackElementDescriptor(_trackType); + if (ted.flags & TRACK_ELEM_FLAG_IS_STEEP_UP) + { + return Result( + Status::Disallowed, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_TOO_STEEP_FOR_LIFT_HILL); + } + } + } + + const auto& ted = GetTrackElementDescriptor(_trackType); + uint32_t numElements = 0; + // First check if any of the track pieces are outside the park + for (uint8_t i = 0; i < ted.numSequences; i++) + { + const auto& trackBlock = ted.sequences[i].clearance; + auto rotatedTrack = CoordsXYZ{ CoordsXY{ trackBlock.x, trackBlock.y }.Rotate(_origin.direction), 0 }; + auto tileCoords = CoordsXYZ{ _origin.x, _origin.y, _origin.z } + rotatedTrack; + + if (!LocationValid(tileCoords)) + { + return Result(Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_OFF_EDGE_OF_MAP); + } + if (!MapIsLocationOwned(tileCoords) && !gameState.cheats.sandboxMode) + { + return Result(Status::Disallowed, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_LAND_NOT_OWNED_BY_PARK); + } + numElements++; + } + + if (!CheckMapCapacity(numElements)) + { + LOG_ERROR("Not enough free map elements to place track."); + return Result( + Status::NoFreeElements, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_TILE_ELEMENT_LIMIT_REACHED); + } + + if (!gameState.cheats.allowTrackPlaceInvalidHeights) + { + if (ted.flags & TRACK_ELEM_FLAG_STARTS_AT_HALF_HEIGHT) + { + if ((_origin.z & 0x0F) != 8) + { + return Result( + Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_INVALID_HEIGHT); + } } else { - // Remove walls in the directions this track intersects - uint8_t intersectingDirections = ted.sequences[blockIndex].allowedWallEdges; - intersectingDirections ^= 0x0F; - intersectingDirections = Numerics::rol4(intersectingDirections, _origin.direction); - for (int32_t i = 0; i < kNumOrthogonalDirections; i++) + if ((_origin.z & 0x0F) != 0) { - if (intersectingDirections & (1 << i)) - { - WallRemoveIntersectingWalls(mapLocWithClearance, i); - } + return Result( + Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_INVALID_HEIGHT); } } } - const auto clearanceData = canBuild.GetData(); - uint8_t mapGroundFlags = clearanceData.GroundFlags & (ELEMENT_IS_ABOVE_GROUND | ELEMENT_IS_UNDERGROUND); - if (!(ted.flags & TRACK_ELEM_FLAG_CAN_BE_PARTLY_UNDERGROUND)) + // If that is not the case, then perform the remaining checks + auto clearanceHeight = rideEntry->Clearance; + + money64 costs = 0; + money64 supportCosts = 0; + for (int32_t blockIndex = 0; blockIndex < ted.numSequences; blockIndex++) { - if (resultData.GroundFlags != 0 && (resultData.GroundFlags & mapGroundFlags) == 0) + const auto& trackBlock = ted.sequences[blockIndex].clearance; + auto rotatedTrack = CoordsXYZ{ CoordsXY{ trackBlock.x, trackBlock.y }.Rotate(_origin.direction), trackBlock.z }; + auto mapLoc = CoordsXYZ{ _origin.x, _origin.y, _origin.z } + rotatedTrack; + auto quarterTile = trackBlock.quarterTile.Rotate(_origin.direction); + + if (mapLoc.z < 16) { - return GameActions::Result( - GameActions::Status::Disallowed, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, - STR_CANT_BUILD_PARTLY_ABOVE_AND_PARTLY_BELOW_GROUND); + return Result(Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_TOO_LOW); } - } - resultData.GroundFlags = mapGroundFlags; + int32_t baseZ = floor2(mapLoc.z, kCoordsZStep); - // 6c5648 12 push - auto surfaceElement = MapGetSurfaceElementAt(mapLoc); - if (surfaceElement == nullptr) - { - return GameActions::Result( - GameActions::Status::Unknown, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, - STR_ERR_SURFACE_ELEMENT_NOT_FOUND); - } - - int32_t supportHeight = baseZ - surfaceElement->GetBaseZ(); - if (supportHeight < 0) - { - supportHeight = (10 * kCoordsZStep); - } - - supportCosts += (supportHeight / (2 * kCoordsZStep)) * rtd.BuildCosts.SupportPrice; - - int32_t entranceDirections = 0; - if (!ride->overallView.IsNull()) - { - if (!(GetFlags() & GAME_COMMAND_FLAG_NO_SPEND)) + int32_t clearanceZ = trackBlock.clearanceZ; + if (trackBlock.flags & RCT_PREVIEW_TRACK_FLAG_IS_VERTICAL && clearanceHeight > 24) { - entranceDirections = ted.sequences[0].flags; + clearanceZ += 24; } - } - - if (entranceDirections & TRACK_SEQUENCE_FLAG_ORIGIN || ride->overallView.IsNull()) - { - ride->overallView = mapLoc; - } - - auto* trackElement = TileElementInsert(mapLoc, quarterTile.GetBaseQuarterOccupied()); - if (trackElement == nullptr) - { - LOG_ERROR("Cannot create track element for ride = %d", _rideIndex.ToUnderlying()); - return GameActions::Result( - GameActions::Status::NoFreeElements, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, - STR_TILE_ELEMENT_LIMIT_REACHED); - } - - trackElement->SetClearanceZ(clearanceZ); - trackElement->SetDirection(_origin.direction); - trackElement->SetHasChain(_trackPlaceFlags.has(LiftHillAndInverted::liftHill)); - trackElement->SetSequenceIndex(blockIndex); - trackElement->SetRideIndex(_rideIndex); - trackElement->SetTrackType(_trackType); - trackElement->SetRideType(_rideType); - trackElement->SetGhost(GetFlags() & GAME_COMMAND_FLAG_GHOST); - - switch (_trackType) - { - case TrackElemType::Waterfall: - case TrackElemType::Rapids: - case TrackElemType::Whirlpool: - case TrackElemType::SpinningTunnel: - MapAnimations::MarkTileForInvalidation(TileCoordsXY(mapLoc)); - break; - case TrackElemType::Brakes: - case TrackElemType::DiagBrakes: - trackElement->SetBrakeClosed(true); - break; - default: - break; - } - if (TrackTypeHasSpeedSetting(_trackType)) - { - trackElement->SetBrakeBoosterSpeed(_brakeSpeed); - } - - if (rtd.HasFlag(RtdFlag::hasLandscapeDoors)) - { - trackElement->SetDoorAState(kLandEdgeDoorFrameClosed); - trackElement->SetDoorBState(kLandEdgeDoorFrameClosed); - } - else - { - trackElement->SetSeatRotation(_seatRotation); - } - - if (_trackPlaceFlags.has(LiftHillAndInverted::inverted)) - { - trackElement->SetInverted(true); - } - trackElement->SetColourScheme(static_cast(_colour)); - - entranceDirections = ted.sequences[0].flags; - if (entranceDirections & TRACK_SEQUENCE_FLAG_CONNECTS_TO_PATH) - { - uint32_t availableDirections = entranceDirections & 0x0F; - if (availableDirections != 0) + else { - if (!(GetFlags() & GAME_COMMAND_FLAG_GHOST) && !gameState.cheats.disableClearanceChecks) + clearanceZ += clearanceHeight; + } + + clearanceZ = floor2(clearanceZ, kCoordsZStep) + baseZ; + + if (clearanceZ > MAX_TRACK_HEIGHT) + { + return Result(Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_TOO_HIGH); + } + + auto crossingMode = (rtd.HasFlag(RtdFlag::supportsLevelCrossings) && _trackType == TrackElemType::Flat) + ? CreateCrossingMode::trackOverPath + : CreateCrossingMode::none; + auto canBuild = MapCanConstructWithClearAt( + { mapLoc, baseZ, clearanceZ }, &MapPlaceNonSceneryClearFunc, quarterTile, GetFlags(), crossingMode); + if (canBuild.Error != Status::Ok) + { + canBuild.ErrorTitle = STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE; + return canBuild; + } + costs += canBuild.Cost; + + const auto clearanceData = canBuild.GetData(); + uint8_t mapGroundFlags = clearanceData.GroundFlags & (ELEMENT_IS_ABOVE_GROUND | ELEMENT_IS_UNDERGROUND); + if (!(ted.flags & TRACK_ELEM_FLAG_CAN_BE_PARTLY_UNDERGROUND)) + { + if (resultData.GroundFlags != 0 && (resultData.GroundFlags & mapGroundFlags) == 0) { - for (int32_t chosenDirection = Numerics::bitScanForward(availableDirections); chosenDirection != -1; - chosenDirection = Numerics::bitScanForward(availableDirections)) + return Result( + Status::Disallowed, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, + STR_CANT_BUILD_PARTLY_ABOVE_AND_PARTLY_BELOW_GROUND); + } + } + + resultData.GroundFlags = mapGroundFlags; + if (ted.flags & TRACK_ELEM_FLAG_ONLY_ABOVE_GROUND) + { + if (resultData.GroundFlags & ELEMENT_IS_UNDERGROUND) + { + return Result( + Status::Disallowed, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, + STR_CAN_ONLY_BUILD_THIS_ABOVE_GROUND); + } + } + + if (ted.flags & TRACK_ELEM_FLAG_ONLY_UNDERWATER) + { // No element has this flag + if (clearanceData.GroundFlags & ELEMENT_IS_UNDERWATER) + { + return Result( + Status::Disallowed, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_CAN_ONLY_BUILD_THIS_UNDERWATER); + } + } + + if (clearanceData.GroundFlags & ELEMENT_IS_UNDERWATER && !gameState.cheats.disableClearanceChecks) + { + return Result( + Status::Disallowed, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_RIDE_CANT_BUILD_THIS_UNDERWATER); + } + + if (rtd.HasFlag(RtdFlag::trackMustBeOnWater) && !_trackDesignDrawingPreview) + { + auto surfaceElement = MapGetSurfaceElementAt(mapLoc); + if (surfaceElement == nullptr) + { + return Result( + Status::Unknown, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_ERR_SURFACE_ELEMENT_NOT_FOUND); + } + + auto waterHeight = surfaceElement->GetWaterHeight(); + if (waterHeight == 0) + { + return Result( + Status::Disallowed, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_CAN_ONLY_BUILD_THIS_ON_WATER); + } + + if (waterHeight != baseZ) + { + return Result( + Status::Disallowed, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_CAN_ONLY_BUILD_THIS_ON_WATER); + } + waterHeight -= kLandHeightStep; + if (waterHeight == surfaceElement->GetBaseZ()) + { + uint8_t slope = surfaceElement->GetSlope() & kTileSlopeRaisedCornersMask; + if (slope == kTileSlopeWCornerDown || slope == kTileSlopeSCornerDown || slope == kTileSlopeECornerDown + || slope == kTileSlopeNCornerDown) { - availableDirections &= ~(1 << chosenDirection); - CoordsXY tempLoc{ mapLoc.x, mapLoc.y }; - int32_t tempDirection = (_origin.direction + chosenDirection) & 3; - tempLoc.x += CoordsDirectionDelta[tempDirection].x; - tempLoc.y += CoordsDirectionDelta[tempDirection].y; - tempDirection = DirectionReverse(tempDirection); - WallRemoveIntersectingWalls({ tempLoc, baseZ, clearanceZ }, tempDirection & 3); + return Result( + Status::Disallowed, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, + STR_CAN_ONLY_BUILD_THIS_ON_WATER); } } } - } - // If the placed tile is a station modify station properties. - // Don't do this if the tile is a ghost to prevent desyncs - // However, ghost tiles from track designs need to modify station data to display properly - if (entranceDirections & TRACK_SEQUENCE_FLAG_ORIGIN && (!(GetFlags() & GAME_COMMAND_FLAG_GHOST) || _fromTrackDesign)) - { - if (blockIndex == 0) + int32_t entranceDirections = ted.sequences[0].flags; + if ((entranceDirections & TRACK_SEQUENCE_FLAG_ORIGIN) && blockIndex == 0) { - TrackAddStationElement({ mapLoc, _origin.direction }, _rideIndex, GAME_COMMAND_FLAG_APPLY, _fromTrackDesign); - } - ride->validateStations(); - ride->updateMaxVehicles(); - } - - auto* tileElement = trackElement->as(); - - if (rtd.HasFlag(RtdFlag::trackMustBeOnWater)) - { - auto* waterSurfaceElement = MapGetSurfaceElementAt(mapLoc); - if (waterSurfaceElement != nullptr) - { - waterSurfaceElement->SetHasTrackThatNeedsWater(true); - tileElement = waterSurfaceElement->as(); - } - } - - if (!gameState.cheats.disableClearanceChecks || !(GetFlags() & GAME_COMMAND_FLAG_GHOST)) - { - FootpathConnectEdges(mapLoc, tileElement, GetFlags()); - } - MapInvalidateTileFull(mapLoc); - } - - // Update ride stats and block brake count if the piece was successfully built - if (!(GetFlags() & GAME_COMMAND_FLAG_GHOST)) - { - InvalidateTestResults(*ride); - switch (_trackType) - { - case TrackElemType::OnRidePhoto: - ride->lifecycleFlags |= RIDE_LIFECYCLE_ON_RIDE_PHOTO; - break; - case TrackElemType::CableLiftHill: - ride->lifecycleFlags |= RIDE_LIFECYCLE_CABLE_LIFT_HILL_COMPONENT_USED; - ride->cableLiftLoc = originLocation; - break; - case TrackElemType::DiagBlockBrakes: - case TrackElemType::BlockBrakes: - { - ride->numBlockBrakes++; - ride->windowInvalidateFlags |= RIDE_INVALIDATE_RIDE_OPERATING; - - // change the current mode to its circuit blocked equivalent - RideMode newMode = RideMode::continuousCircuitBlockSectioned; - if (ride->mode == RideMode::poweredLaunch) + const auto addElementResult = TrackAddStationElement( + { mapLoc, baseZ, _origin.direction }, _rideIndex, 0, _fromTrackDesign); + if (!addElementResult.Successful) { - if (rtd.SupportsRideMode(RideMode::poweredLaunchBlockSectioned) - || getGameState().cheats.showAllOperatingModes) - newMode = RideMode::poweredLaunchBlockSectioned; + return Result(Status::Unknown, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, addElementResult.Message); + } + } + + // 6c5648 12 push + auto surfaceElement = MapGetSurfaceElementAt(mapLoc); + if (surfaceElement == nullptr) + { + return Result( + Status::Unknown, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_ERR_SURFACE_ELEMENT_NOT_FOUND); + } + + if (!gameState.cheats.disableSupportLimits) + { + int32_t ride_height = clearanceZ - surfaceElement->GetBaseZ(); + if (ride_height >= 0) + { + uint16_t maxHeight; + + if (rtd.HasFlag(RtdFlag::listVehiclesSeparately) && rideEntry->max_height != 0) + { + maxHeight = rideEntry->max_height; + } else - newMode = RideMode::poweredLaunch; + { + maxHeight = rtd.Heights.MaxHeight; + } + + ride_height /= kCoordsZPerTinyZ; + if (ride_height > maxHeight && !_trackDesignDrawingPreview) + { + return Result( + Status::Disallowed, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_TOO_HIGH_FOR_SUPPORTS); + } } - - auto rideSetSetting = RideSetSettingAction(ride->id, RideSetSetting::Mode, static_cast(newMode)); - GameActions::ExecuteNested(&rideSetSetting); - break; } - default: - break; + + int32_t supportHeight = baseZ - surfaceElement->GetBaseZ(); + if (supportHeight < 0) + { + supportHeight = (10 * kCoordsZStep); + } + + supportCosts += ((supportHeight / (2 * kCoordsZStep)) * rtd.BuildCosts.SupportPrice); } - switch (_trackType) - { - case TrackElemType::Up25ToFlat: - case TrackElemType::Up60ToFlat: - case TrackElemType::DiagUp25ToFlat: - case TrackElemType::DiagUp60ToFlat: - if (!_trackPlaceFlags.has(LiftHillAndInverted::liftHill)) - break; - [[fallthrough]]; - case TrackElemType::CableLiftHill: - ride->numBlockBrakes++; - break; - default: - break; - } + money64 price = rtd.BuildCosts.TrackPrice; + price *= ted.priceModifier; + + price >>= 16; + res.Cost = costs + supportCosts + price; + res.SetData(std::move(resultData)); + + return res; } - money64 price = rtd.BuildCosts.TrackPrice; - price *= ted.priceModifier; - - price >>= 16; - res.Cost = costs + supportCosts + price; - res.SetData(std::move(resultData)); - - return res; -} - -bool TrackPlaceAction::CheckMapCapacity(int16_t numTiles) const -{ - const auto& ted = GetTrackElementDescriptor(_trackType); - for (uint8_t i = 0; i < ted.numSequences; i++) + Result TrackPlaceAction::Execute() const { - const auto& trackBlock = ted.sequences[i].clearance; - auto rotatedTrack = CoordsXY{ trackBlock.x, trackBlock.y }.Rotate(_origin.direction); - - auto tileCoords = CoordsXY{ _origin.x, _origin.y } + rotatedTrack; - if (!MapCheckCapacityAndReorganise(tileCoords, numTiles)) + auto ride = GetRide(_rideIndex); + if (ride == nullptr) { - return false; + LOG_ERROR("Invalid ride for track placement, rideIndex = %d", _rideIndex.ToUnderlying()); + return Result(Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_ERR_RIDE_NOT_FOUND); } + + const auto* rideEntry = GetRideEntryByIndex(ride->subtype); + if (rideEntry == nullptr) + { + LOG_ERROR("Invalid ride subtype for track placement, rideIndex = %d", _rideIndex.ToUnderlying()); + return Result(Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_UNKNOWN_OBJECT_TYPE); + } + + auto res = Result(); + res.Expenditure = ExpenditureType::rideConstruction; + res.Position.x = _origin.x + 16; + res.Position.y = _origin.y + 16; + res.Position.z = _origin.z; + + auto resultData = TrackPlaceActionResult{}; + + const auto& rtd = ride->getRideTypeDescriptor(); + + const auto& ted = GetTrackElementDescriptor(_trackType); + + money64 costs = 0; + money64 supportCosts = 0; + const auto& block0 = ted.sequences[0].clearance; + auto clearanceHeight = rideEntry->Clearance; + CoordsXYZ originLocation = CoordsXYZ{ _origin.x, _origin.y, _origin.z } + + CoordsXYZ{ CoordsXY{ block0.x, block0.y }.Rotate(_origin.direction), block0.z }; + for (int32_t blockIndex = 0; blockIndex < ted.numSequences; blockIndex++) + { + const auto& trackBlock = ted.sequences[blockIndex].clearance; + auto rotatedTrack = CoordsXYZ{ CoordsXY{ trackBlock.x, trackBlock.y }.Rotate(_origin.direction), trackBlock.z }; + auto mapLoc = CoordsXYZ{ _origin.x, _origin.y, _origin.z } + rotatedTrack; + + auto quarterTile = trackBlock.quarterTile.Rotate(_origin.direction); + + int32_t baseZ = floor2(mapLoc.z, kCoordsZStep); + int32_t clearanceZ = trackBlock.clearanceZ; + if (trackBlock.flags & RCT_PREVIEW_TRACK_FLAG_IS_VERTICAL && clearanceHeight > 24) + { + clearanceZ += 24; + } + else + { + clearanceZ += clearanceHeight; + } + + clearanceZ = floor2(clearanceZ, kCoordsZStep) + baseZ; + const auto mapLocWithClearance = CoordsXYRangedZ(mapLoc, baseZ, clearanceZ); + + auto crossingMode = (rtd.HasFlag(RtdFlag::supportsLevelCrossings) && _trackType == TrackElemType::Flat) + ? CreateCrossingMode::trackOverPath + : CreateCrossingMode::none; + auto canBuild = MapCanConstructWithClearAt( + mapLocWithClearance, &MapPlaceNonSceneryClearFunc, quarterTile, GetFlags() | GAME_COMMAND_FLAG_APPLY, + crossingMode); + if (canBuild.Error != Status::Ok) + { + canBuild.ErrorTitle = STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE; + return canBuild; + } + costs += canBuild.Cost; + + // When building a level crossing, remove any pre-existing path furniture. + if (crossingMode == CreateCrossingMode::trackOverPath && !(GetFlags() & GAME_COMMAND_FLAG_GHOST)) + { + auto footpathElement = MapGetFootpathElement(mapLoc); + if (footpathElement != nullptr && footpathElement->HasAddition()) + { + footpathElement->SetAddition(0); + } + } + + auto& gameState = getGameState(); + if (!(GetFlags() & GAME_COMMAND_FLAG_GHOST) && !gameState.cheats.disableClearanceChecks) + { + FootpathRemoveLitter(mapLoc); + if (rtd.HasFlag(RtdFlag::noWallsAroundTrack)) + { + WallRemoveAt(mapLocWithClearance); + } + else + { + // Remove walls in the directions this track intersects + uint8_t intersectingDirections = ted.sequences[blockIndex].allowedWallEdges; + intersectingDirections ^= 0x0F; + intersectingDirections = Numerics::rol4(intersectingDirections, _origin.direction); + for (int32_t i = 0; i < kNumOrthogonalDirections; i++) + { + if (intersectingDirections & (1 << i)) + { + WallRemoveIntersectingWalls(mapLocWithClearance, i); + } + } + } + } + + const auto clearanceData = canBuild.GetData(); + uint8_t mapGroundFlags = clearanceData.GroundFlags & (ELEMENT_IS_ABOVE_GROUND | ELEMENT_IS_UNDERGROUND); + if (!(ted.flags & TRACK_ELEM_FLAG_CAN_BE_PARTLY_UNDERGROUND)) + { + if (resultData.GroundFlags != 0 && (resultData.GroundFlags & mapGroundFlags) == 0) + { + return Result( + Status::Disallowed, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, + STR_CANT_BUILD_PARTLY_ABOVE_AND_PARTLY_BELOW_GROUND); + } + } + + resultData.GroundFlags = mapGroundFlags; + + // 6c5648 12 push + auto surfaceElement = MapGetSurfaceElementAt(mapLoc); + if (surfaceElement == nullptr) + { + return Result( + Status::Unknown, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_ERR_SURFACE_ELEMENT_NOT_FOUND); + } + + int32_t supportHeight = baseZ - surfaceElement->GetBaseZ(); + if (supportHeight < 0) + { + supportHeight = (10 * kCoordsZStep); + } + + supportCosts += (supportHeight / (2 * kCoordsZStep)) * rtd.BuildCosts.SupportPrice; + + int32_t entranceDirections = 0; + if (!ride->overallView.IsNull()) + { + if (!(GetFlags() & GAME_COMMAND_FLAG_NO_SPEND)) + { + entranceDirections = ted.sequences[0].flags; + } + } + + if (entranceDirections & TRACK_SEQUENCE_FLAG_ORIGIN || ride->overallView.IsNull()) + { + ride->overallView = mapLoc; + } + + auto* trackElement = TileElementInsert(mapLoc, quarterTile.GetBaseQuarterOccupied()); + if (trackElement == nullptr) + { + LOG_ERROR("Cannot create track element for ride = %d", _rideIndex.ToUnderlying()); + return Result( + Status::NoFreeElements, STR_RIDE_CONSTRUCTION_CANT_CONSTRUCT_THIS_HERE, STR_TILE_ELEMENT_LIMIT_REACHED); + } + + trackElement->SetClearanceZ(clearanceZ); + trackElement->SetDirection(_origin.direction); + trackElement->SetHasChain(_trackPlaceFlags.has(LiftHillAndInverted::liftHill)); + trackElement->SetSequenceIndex(blockIndex); + trackElement->SetRideIndex(_rideIndex); + trackElement->SetTrackType(_trackType); + trackElement->SetRideType(_rideType); + trackElement->SetGhost(GetFlags() & GAME_COMMAND_FLAG_GHOST); + + switch (_trackType) + { + case TrackElemType::Waterfall: + case TrackElemType::Rapids: + case TrackElemType::Whirlpool: + case TrackElemType::SpinningTunnel: + MapAnimations::MarkTileForInvalidation(TileCoordsXY(mapLoc)); + break; + case TrackElemType::Brakes: + case TrackElemType::DiagBrakes: + trackElement->SetBrakeClosed(true); + break; + default: + break; + } + if (TrackTypeHasSpeedSetting(_trackType)) + { + trackElement->SetBrakeBoosterSpeed(_brakeSpeed); + } + + if (rtd.HasFlag(RtdFlag::hasLandscapeDoors)) + { + trackElement->SetDoorAState(kLandEdgeDoorFrameClosed); + trackElement->SetDoorBState(kLandEdgeDoorFrameClosed); + } + else + { + trackElement->SetSeatRotation(_seatRotation); + } + + if (_trackPlaceFlags.has(LiftHillAndInverted::inverted)) + { + trackElement->SetInverted(true); + } + trackElement->SetColourScheme(static_cast(_colour)); + + entranceDirections = ted.sequences[0].flags; + if (entranceDirections & TRACK_SEQUENCE_FLAG_CONNECTS_TO_PATH) + { + uint32_t availableDirections = entranceDirections & 0x0F; + if (availableDirections != 0) + { + if (!(GetFlags() & GAME_COMMAND_FLAG_GHOST) && !gameState.cheats.disableClearanceChecks) + { + for (int32_t chosenDirection = Numerics::bitScanForward(availableDirections); chosenDirection != -1; + chosenDirection = Numerics::bitScanForward(availableDirections)) + { + availableDirections &= ~(1 << chosenDirection); + CoordsXY tempLoc{ mapLoc.x, mapLoc.y }; + int32_t tempDirection = (_origin.direction + chosenDirection) & 3; + tempLoc.x += CoordsDirectionDelta[tempDirection].x; + tempLoc.y += CoordsDirectionDelta[tempDirection].y; + tempDirection = DirectionReverse(tempDirection); + WallRemoveIntersectingWalls({ tempLoc, baseZ, clearanceZ }, tempDirection & 3); + } + } + } + } + + // If the placed tile is a station modify station properties. + // Don't do this if the tile is a ghost to prevent desyncs + // However, ghost tiles from track designs need to modify station data to display properly + if (entranceDirections & TRACK_SEQUENCE_FLAG_ORIGIN + && (!(GetFlags() & GAME_COMMAND_FLAG_GHOST) || _fromTrackDesign)) + { + if (blockIndex == 0) + { + TrackAddStationElement( + { mapLoc, _origin.direction }, _rideIndex, GAME_COMMAND_FLAG_APPLY, _fromTrackDesign); + } + ride->validateStations(); + ride->updateMaxVehicles(); + } + + auto* tileElement = trackElement->as(); + + if (rtd.HasFlag(RtdFlag::trackMustBeOnWater)) + { + auto* waterSurfaceElement = MapGetSurfaceElementAt(mapLoc); + if (waterSurfaceElement != nullptr) + { + waterSurfaceElement->SetHasTrackThatNeedsWater(true); + tileElement = waterSurfaceElement->as(); + } + } + + if (!gameState.cheats.disableClearanceChecks || !(GetFlags() & GAME_COMMAND_FLAG_GHOST)) + { + FootpathConnectEdges(mapLoc, tileElement, GetFlags()); + } + MapInvalidateTileFull(mapLoc); + } + + // Update ride stats and block brake count if the piece was successfully built + if (!(GetFlags() & GAME_COMMAND_FLAG_GHOST)) + { + InvalidateTestResults(*ride); + switch (_trackType) + { + case TrackElemType::OnRidePhoto: + ride->lifecycleFlags |= RIDE_LIFECYCLE_ON_RIDE_PHOTO; + break; + case TrackElemType::CableLiftHill: + ride->lifecycleFlags |= RIDE_LIFECYCLE_CABLE_LIFT_HILL_COMPONENT_USED; + ride->cableLiftLoc = originLocation; + break; + case TrackElemType::DiagBlockBrakes: + case TrackElemType::BlockBrakes: + { + ride->numBlockBrakes++; + ride->windowInvalidateFlags |= RIDE_INVALIDATE_RIDE_OPERATING; + + // change the current mode to its circuit blocked equivalent + RideMode newMode = RideMode::continuousCircuitBlockSectioned; + if (ride->mode == RideMode::poweredLaunch) + { + if (rtd.SupportsRideMode(RideMode::poweredLaunchBlockSectioned) + || getGameState().cheats.showAllOperatingModes) + newMode = RideMode::poweredLaunchBlockSectioned; + else + newMode = RideMode::poweredLaunch; + } + + auto rideSetSetting = GameActions::RideSetSettingAction( + ride->id, GameActions::RideSetSetting::Mode, static_cast(newMode)); + ExecuteNested(&rideSetSetting); + break; + } + default: + break; + } + + switch (_trackType) + { + case TrackElemType::Up25ToFlat: + case TrackElemType::Up60ToFlat: + case TrackElemType::DiagUp25ToFlat: + case TrackElemType::DiagUp60ToFlat: + if (!_trackPlaceFlags.has(LiftHillAndInverted::liftHill)) + break; + [[fallthrough]]; + case TrackElemType::CableLiftHill: + ride->numBlockBrakes++; + break; + default: + break; + } + } + + money64 price = rtd.BuildCosts.TrackPrice; + price *= ted.priceModifier; + + price >>= 16; + res.Cost = costs + supportCosts + price; + res.SetData(std::move(resultData)); + + return res; } - return true; -} + + bool TrackPlaceAction::CheckMapCapacity(int16_t numTiles) const + { + const auto& ted = GetTrackElementDescriptor(_trackType); + for (uint8_t i = 0; i < ted.numSequences; i++) + { + const auto& trackBlock = ted.sequences[i].clearance; + auto rotatedTrack = CoordsXY{ trackBlock.x, trackBlock.y }.Rotate(_origin.direction); + + auto tileCoords = CoordsXY{ _origin.x, _origin.y } + rotatedTrack; + if (!MapCheckCapacityAndReorganise(tileCoords, numTiles)) + { + return false; + } + } + return true; + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/TrackPlaceAction.h b/src/openrct2/actions/TrackPlaceAction.h index 75c61d778c..6ac393b1b6 100644 --- a/src/openrct2/actions/TrackPlaceAction.h +++ b/src/openrct2/actions/TrackPlaceAction.h @@ -12,40 +12,41 @@ #include "../ride/RideConstruction.h" #include "GameAction.h" -using namespace OpenRCT2; - -struct TrackPlaceActionResult +namespace OpenRCT2::GameActions { - uint8_t GroundFlags{ 0 }; -}; + struct TrackPlaceActionResult + { + uint8_t GroundFlags{ 0 }; + }; -class TrackPlaceAction final : public GameActionBase -{ -private: - RideId _rideIndex{ RideId::GetNull() }; - OpenRCT2::TrackElemType _trackType{}; - ride_type_t _rideType{}; - CoordsXYZD _origin; - int32_t _brakeSpeed{}; - int32_t _colour{}; - int32_t _seatRotation{}; - SelectedLiftAndInverted _trackPlaceFlags{}; - bool _fromTrackDesign{}; + class TrackPlaceAction final : public GameActionBase + { + private: + RideId _rideIndex{ RideId::GetNull() }; + TrackElemType _trackType{}; + ride_type_t _rideType{}; + CoordsXYZD _origin; + int32_t _brakeSpeed{}; + int32_t _colour{}; + int32_t _seatRotation{}; + SelectedLiftAndInverted _trackPlaceFlags{}; + bool _fromTrackDesign{}; -public: - TrackPlaceAction() = default; - TrackPlaceAction( - RideId rideIndex, OpenRCT2::TrackElemType trackType, ride_type_t rideType, const CoordsXYZD& origin, int32_t brakeSpeed, - int32_t colour, int32_t seatRotation, SelectedLiftAndInverted liftHillAndAlternativeState, bool fromTrackDesign); + public: + TrackPlaceAction() = default; + TrackPlaceAction( + RideId rideIndex, TrackElemType trackType, ride_type_t rideType, const CoordsXYZD& origin, int32_t brakeSpeed, + int32_t colour, int32_t seatRotation, SelectedLiftAndInverted liftHillAndAlternativeState, bool fromTrackDesign); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override final; + uint16_t GetActionFlags() const override final; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; + void Serialise(DataSerialiser& stream) override; + GameActions::Result Query() const override; + GameActions::Result Execute() const override; -private: - bool CheckMapCapacity(int16_t numTiles) const; -}; + private: + bool CheckMapCapacity(int16_t numTiles) const; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/TrackRemoveAction.cpp b/src/openrct2/actions/TrackRemoveAction.cpp index d328f4cfac..a0a7f19171 100644 --- a/src/openrct2/actions/TrackRemoveAction.cpp +++ b/src/openrct2/actions/TrackRemoveAction.cpp @@ -21,186 +21,88 @@ #include "../world/tile_element/TrackElement.h" #include "RideSetSettingAction.h" -using namespace OpenRCT2; -using namespace OpenRCT2::TrackMetaData; - -TrackRemoveAction::TrackRemoveAction(OpenRCT2::TrackElemType trackType, int32_t sequence, const CoordsXYZD& origin) - : _trackType(trackType) - , _sequence(sequence) - , _origin(origin) +namespace OpenRCT2::GameActions { - _origin.direction &= 3; -} + using namespace OpenRCT2::TrackMetaData; -void TrackRemoveAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit(_origin); - visitor.Visit("trackType", _trackType); - visitor.Visit("sequence", _sequence); -} - -uint16_t TrackRemoveAction::GetActionFlags() const -{ - return GameAction::GetActionFlags(); -} - -static OpenRCT2::TrackElemType normaliseTrackType(OpenRCT2::TrackElemType trackType) -{ - switch (trackType) + TrackRemoveAction::TrackRemoveAction(TrackElemType trackType, int32_t sequence, const CoordsXYZD& origin) + : _trackType(trackType) + , _sequence(sequence) + , _origin(origin) { - case TrackElemType::BeginStation: - case TrackElemType::MiddleStation: - return TrackElemType::EndStation; - default: - return trackType; - } -} - -void TrackRemoveAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_trackType) << DS_TAG(_sequence) << DS_TAG(_origin); -} - -GameActions::Result TrackRemoveAction::Query() const -{ - auto res = GameActions::Result(); - res.Position.x = _origin.x + 16; - res.Position.y = _origin.y + 16; - res.Position.z = _origin.z; - res.Expenditure = ExpenditureType::rideConstruction; - - auto comparableTrackType = normaliseTrackType(_trackType); - - bool found = false; - bool isGhost = GetFlags() & GAME_COMMAND_FLAG_GHOST; - TileElement* tileElement = MapGetFirstElementAt(_origin); - - do - { - if (tileElement == nullptr) - break; - - if (tileElement->GetBaseZ() != _origin.z) - continue; - - if (tileElement->GetType() != TileElementType::Track) - continue; - - if ((tileElement->GetDirection()) != _origin.direction) - continue; - - if (tileElement->AsTrack()->GetSequenceIndex() != _sequence) - continue; - - if (tileElement->IsGhost() != isGhost) - continue; - - auto tileTrackType = normaliseTrackType(tileElement->AsTrack()->GetTrackType()); - - if (tileTrackType != comparableTrackType) - continue; - - found = true; - break; - } while (!(tileElement++)->IsLastForTile()); - - if (!found) - { - LOG_ERROR( - "Track Element not found. x = %d, y = %d, z = %d, d = %d, seq = %d.", _origin.x, _origin.y, _origin.z, - _origin.direction, _sequence); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_REMOVE_THIS, STR_ERR_TRACK_ELEMENT_NOT_FOUND); + _origin.direction &= 3; } - if (tileElement->AsTrack()->IsIndestructible()) + void TrackRemoveAction::AcceptParameters(GameActionParameterVisitor& visitor) { - return GameActions::Result( - GameActions::Status::Disallowed, STR_RIDE_CONSTRUCTION_CANT_REMOVE_THIS, - STR_YOU_ARE_NOT_ALLOWED_TO_REMOVE_THIS_SECTION); + visitor.Visit(_origin); + visitor.Visit("trackType", _trackType); + visitor.Visit("sequence", _sequence); } - RideId rideIndex = tileElement->AsTrack()->GetRideIndex(); - const auto trackType = tileElement->AsTrack()->GetTrackType(); - - auto ride = GetRide(rideIndex); - if (ride == nullptr) + uint16_t TrackRemoveAction::GetActionFlags() const { - LOG_ERROR("Ride not found for rideIndex %d.", rideIndex); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_REMOVE_THIS, STR_ERR_RIDE_NOT_FOUND); + return GameAction::GetActionFlags(); } - if (ride->type >= RIDE_TYPE_COUNT) + static TrackElemType normaliseTrackType(TrackElemType trackType) { - LOG_ERROR("Ride type not found. ride type = %d.", ride->type); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_REMOVE_THIS, STR_ERR_VALUE_OUT_OF_RANGE); - } - const auto& ted = GetTrackElementDescriptor(trackType); - auto sequenceIndex = tileElement->AsTrack()->GetSequenceIndex(); - if (sequenceIndex >= ted.numSequences) - { - LOG_ERROR("Track block %d not found for track type %d.", sequenceIndex, trackType); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_REMOVE_THIS, STR_ERR_TRACK_BLOCK_NOT_FOUND); - } - const auto& currentTrackBlock = ted.sequences[sequenceIndex].clearance; - - auto startLoc = _origin; - startLoc.direction = tileElement->GetDirection(); - - auto rotatedTrack = CoordsXYZ{ CoordsXY{ currentTrackBlock.x, currentTrackBlock.y }.Rotate(startLoc.direction), - currentTrackBlock.z }; - startLoc.x -= rotatedTrack.x; - startLoc.y -= rotatedTrack.y; - startLoc.z -= rotatedTrack.z; - res.Position.x = startLoc.x; - res.Position.y = startLoc.y; - res.Position.z = startLoc.z; - - money64 supportCosts = 0; - - for (uint8_t i = 0; i < ted.numSequences; i++) - { - const auto& trackBlock = ted.sequences[i].clearance; - rotatedTrack = CoordsXYZ{ CoordsXY{ trackBlock.x, trackBlock.y }.Rotate(startLoc.direction), trackBlock.z }; - auto mapLoc = CoordsXYZ{ startLoc.x, startLoc.y, startLoc.z } + rotatedTrack; - - if (!LocationValid(mapLoc)) + switch (trackType) { - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_REMOVE_THIS, STR_OFF_EDGE_OF_MAP); + case TrackElemType::BeginStation: + case TrackElemType::MiddleStation: + return TrackElemType::EndStation; + default: + return trackType; } - MapInvalidateTileFull(mapLoc); + } + + void TrackRemoveAction::Serialise(DataSerialiser& stream) + { + GameAction::Serialise(stream); + + stream << DS_TAG(_trackType) << DS_TAG(_sequence) << DS_TAG(_origin); + } + + Result TrackRemoveAction::Query() const + { + auto res = Result(); + res.Position.x = _origin.x + 16; + res.Position.y = _origin.y + 16; + res.Position.z = _origin.z; + res.Expenditure = ExpenditureType::rideConstruction; + + auto comparableTrackType = normaliseTrackType(_trackType); + + bool found = false; + bool isGhost = GetFlags() & GAME_COMMAND_FLAG_GHOST; + TileElement* tileElement = MapGetFirstElementAt(_origin); - found = false; - tileElement = MapGetFirstElementAt(mapLoc); do { if (tileElement == nullptr) break; - if (tileElement->GetBaseZ() != mapLoc.z) + if (tileElement->GetBaseZ() != _origin.z) continue; if (tileElement->GetType() != TileElementType::Track) continue; - if (tileElement->GetDirection() != _origin.direction) + if ((tileElement->GetDirection()) != _origin.direction) continue; - if (tileElement->AsTrack()->GetSequenceIndex() != i) - continue; - - if (tileElement->AsTrack()->GetTrackType() != trackType) + if (tileElement->AsTrack()->GetSequenceIndex() != _sequence) continue; if (tileElement->IsGhost() != isGhost) continue; + auto tileTrackType = normaliseTrackType(tileElement->AsTrack()->GetTrackType()); + + if (tileTrackType != comparableTrackType) + continue; + found = true; break; } while (!(tileElement++)->IsLastForTile()); @@ -208,175 +110,183 @@ GameActions::Result TrackRemoveAction::Query() const if (!found) { LOG_ERROR( - "Track Element not found. x = %d, y = %d, z = %d, d = %d, seq = %d.", mapLoc.x, mapLoc.y, mapLoc.z, - _origin.direction, i); - return GameActions::Result( - GameActions::Status::Unknown, STR_RIDE_CONSTRUCTION_CANT_REMOVE_THIS, STR_ERR_TRACK_ELEMENT_NOT_FOUND); + "Track Element not found. x = %d, y = %d, z = %d, d = %d, seq = %d.", _origin.x, _origin.y, _origin.z, + _origin.direction, _sequence); + return Result(Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_REMOVE_THIS, STR_ERR_TRACK_ELEMENT_NOT_FOUND); } - int32_t entranceDirections = ted.sequences[0].flags; - if (entranceDirections & TRACK_SEQUENCE_FLAG_ORIGIN && (tileElement->AsTrack()->GetSequenceIndex() == 0)) + if (tileElement->AsTrack()->IsIndestructible()) { - const auto removeElementResult = TrackRemoveStationElement({ mapLoc, _origin.direction }, rideIndex, 0); - if (!removeElementResult.Successful) + return Result( + Status::Disallowed, STR_RIDE_CONSTRUCTION_CANT_REMOVE_THIS, STR_YOU_ARE_NOT_ALLOWED_TO_REMOVE_THIS_SECTION); + } + + RideId rideIndex = tileElement->AsTrack()->GetRideIndex(); + const auto trackType = tileElement->AsTrack()->GetTrackType(); + + auto ride = GetRide(rideIndex); + if (ride == nullptr) + { + LOG_ERROR("Ride not found for rideIndex %d.", rideIndex); + return Result(Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_REMOVE_THIS, STR_ERR_RIDE_NOT_FOUND); + } + + if (ride->type >= RIDE_TYPE_COUNT) + { + LOG_ERROR("Ride type not found. ride type = %d.", ride->type); + return Result(Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_REMOVE_THIS, STR_ERR_VALUE_OUT_OF_RANGE); + } + const auto& ted = GetTrackElementDescriptor(trackType); + auto sequenceIndex = tileElement->AsTrack()->GetSequenceIndex(); + if (sequenceIndex >= ted.numSequences) + { + LOG_ERROR("Track block %d not found for track type %d.", sequenceIndex, trackType); + return Result(Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_REMOVE_THIS, STR_ERR_TRACK_BLOCK_NOT_FOUND); + } + const auto& currentTrackBlock = ted.sequences[sequenceIndex].clearance; + + auto startLoc = _origin; + startLoc.direction = tileElement->GetDirection(); + + auto rotatedTrack = CoordsXYZ{ CoordsXY{ currentTrackBlock.x, currentTrackBlock.y }.Rotate(startLoc.direction), + currentTrackBlock.z }; + startLoc.x -= rotatedTrack.x; + startLoc.y -= rotatedTrack.y; + startLoc.z -= rotatedTrack.z; + res.Position.x = startLoc.x; + res.Position.y = startLoc.y; + res.Position.z = startLoc.z; + + money64 supportCosts = 0; + + for (uint8_t i = 0; i < ted.numSequences; i++) + { + const auto& trackBlock = ted.sequences[i].clearance; + rotatedTrack = CoordsXYZ{ CoordsXY{ trackBlock.x, trackBlock.y }.Rotate(startLoc.direction), trackBlock.z }; + auto mapLoc = CoordsXYZ{ startLoc.x, startLoc.y, startLoc.z } + rotatedTrack; + + if (!LocationValid(mapLoc)) { - return GameActions::Result( - GameActions::Status::Unknown, STR_RIDE_CONSTRUCTION_CANT_REMOVE_THIS, removeElementResult.Message); + return Result(Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_REMOVE_THIS, STR_OFF_EDGE_OF_MAP); } + MapInvalidateTileFull(mapLoc); + + found = false; + tileElement = MapGetFirstElementAt(mapLoc); + do + { + if (tileElement == nullptr) + break; + + if (tileElement->GetBaseZ() != mapLoc.z) + continue; + + if (tileElement->GetType() != TileElementType::Track) + continue; + + if (tileElement->GetDirection() != _origin.direction) + continue; + + if (tileElement->AsTrack()->GetSequenceIndex() != i) + continue; + + if (tileElement->AsTrack()->GetTrackType() != trackType) + continue; + + if (tileElement->IsGhost() != isGhost) + continue; + + found = true; + break; + } while (!(tileElement++)->IsLastForTile()); + + if (!found) + { + LOG_ERROR( + "Track Element not found. x = %d, y = %d, z = %d, d = %d, seq = %d.", mapLoc.x, mapLoc.y, mapLoc.z, + _origin.direction, i); + return Result(Status::Unknown, STR_RIDE_CONSTRUCTION_CANT_REMOVE_THIS, STR_ERR_TRACK_ELEMENT_NOT_FOUND); + } + + int32_t entranceDirections = ted.sequences[0].flags; + if (entranceDirections & TRACK_SEQUENCE_FLAG_ORIGIN && (tileElement->AsTrack()->GetSequenceIndex() == 0)) + { + const auto removeElementResult = TrackRemoveStationElement({ mapLoc, _origin.direction }, rideIndex, 0); + if (!removeElementResult.Successful) + { + return Result(Status::Unknown, STR_RIDE_CONSTRUCTION_CANT_REMOVE_THIS, removeElementResult.Message); + } + } + + auto* surfaceElement = MapGetSurfaceElementAt(mapLoc); + if (surfaceElement == nullptr) + { + LOG_ERROR("Surface Element not found. x = %d, y = %d", mapLoc.x, mapLoc.y); + return Result(Status::Unknown, STR_RIDE_CONSTRUCTION_CANT_REMOVE_THIS, STR_ERR_SURFACE_ELEMENT_NOT_FOUND); + } + + int16_t _support_height = tileElement->BaseHeight - surfaceElement->BaseHeight; + if (_support_height < 0) + { + _support_height = 10; + } + + supportCosts += (_support_height / 2) * ride->getRideTypeDescriptor().BuildCosts.SupportPrice; } - auto* surfaceElement = MapGetSurfaceElementAt(mapLoc); - if (surfaceElement == nullptr) + money64 price = ride->getRideTypeDescriptor().BuildCosts.TrackPrice; + price *= ted.priceModifier; + price >>= 16; + price = supportCosts + price; + if (ride->lifecycleFlags & RIDE_LIFECYCLE_EVER_BEEN_OPENED) { - LOG_ERROR("Surface Element not found. x = %d, y = %d", mapLoc.x, mapLoc.y); - return GameActions::Result( - GameActions::Status::Unknown, STR_RIDE_CONSTRUCTION_CANT_REMOVE_THIS, STR_ERR_SURFACE_ELEMENT_NOT_FOUND); + // 70% modifier for opened rides + price = (price * 45875) / 65536; } - int16_t _support_height = tileElement->BaseHeight - surfaceElement->BaseHeight; - if (_support_height < 0) - { - _support_height = 10; - } - - supportCosts += (_support_height / 2) * ride->getRideTypeDescriptor().BuildCosts.SupportPrice; + res.Cost = -price; + return res; } - money64 price = ride->getRideTypeDescriptor().BuildCosts.TrackPrice; - price *= ted.priceModifier; - price >>= 16; - price = supportCosts + price; - if (ride->lifecycleFlags & RIDE_LIFECYCLE_EVER_BEEN_OPENED) + Result TrackRemoveAction::Execute() const { - // 70% modifier for opened rides - price = (price * 45875) / 65536; - } + auto res = Result(); + res.Position.x = _origin.x + 16; + res.Position.y = _origin.y + 16; + res.Position.z = _origin.z; + res.Expenditure = ExpenditureType::rideConstruction; - res.Cost = -price; - return res; -} + auto comparableTrackType = normaliseTrackType(_trackType); -GameActions::Result TrackRemoveAction::Execute() const -{ - auto res = GameActions::Result(); - res.Position.x = _origin.x + 16; - res.Position.y = _origin.y + 16; - res.Position.z = _origin.z; - res.Expenditure = ExpenditureType::rideConstruction; + bool found = false; + bool isGhost = GetFlags() & GAME_COMMAND_FLAG_GHOST; + TileElement* tileElement = MapGetFirstElementAt(_origin); - auto comparableTrackType = normaliseTrackType(_trackType); - - bool found = false; - bool isGhost = GetFlags() & GAME_COMMAND_FLAG_GHOST; - TileElement* tileElement = MapGetFirstElementAt(_origin); - - do - { - if (tileElement == nullptr) - break; - - if (tileElement->GetBaseZ() != _origin.z) - continue; - - if (tileElement->GetType() != TileElementType::Track) - continue; - - if ((tileElement->GetDirection()) != _origin.direction) - continue; - - if (tileElement->AsTrack()->GetSequenceIndex() != _sequence) - continue; - - if (tileElement->IsGhost() != isGhost) - continue; - - auto tileTrackType = normaliseTrackType(tileElement->AsTrack()->GetTrackType()); - - if (tileTrackType != comparableTrackType) - continue; - - found = true; - break; - } while (!(tileElement++)->IsLastForTile()); - - if (!found) - { - LOG_ERROR( - "Track Element not found. x = %d, y = %d, z = %d, d = %d, seq = %d.", _origin.x, _origin.y, _origin.z, - _origin.direction, _sequence); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_REMOVE_THIS, STR_ERR_TRACK_ELEMENT_NOT_FOUND); - } - - RideId rideIndex = tileElement->AsTrack()->GetRideIndex(); - const auto trackType = tileElement->AsTrack()->GetTrackType(); - bool isLiftHill = tileElement->AsTrack()->HasChain(); - - auto ride = GetRide(rideIndex); - if (ride == nullptr) - { - LOG_ERROR("Ride not found. ride index = %d.", rideIndex); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_REMOVE_THIS, STR_ERR_RIDE_NOT_FOUND); - } - const auto& ted = GetTrackElementDescriptor(trackType); - auto sequenceIndex = tileElement->AsTrack()->GetSequenceIndex(); - if (sequenceIndex >= ted.numSequences) - { - LOG_ERROR("Track block %d not found for track type %d.", sequenceIndex, trackType); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_REMOVE_THIS, STR_ERR_TRACK_BLOCK_NOT_FOUND); - } - - auto startLoc = _origin; - startLoc.direction = tileElement->GetDirection(); - - const auto& currentTrackBlock = ted.sequences[sequenceIndex].clearance; - auto rotatedTrackLoc = CoordsXYZ{ CoordsXY{ currentTrackBlock.x, currentTrackBlock.y }.Rotate(startLoc.direction), - currentTrackBlock.z }; - startLoc.x -= rotatedTrackLoc.x; - startLoc.y -= rotatedTrackLoc.y; - startLoc.z -= rotatedTrackLoc.z; - res.Position.x = startLoc.x; - res.Position.y = startLoc.y; - res.Position.z = startLoc.z; - - money64 supportCosts = 0; - - for (uint8_t i = 0; i < ted.numSequences; i++) - { - const auto& trackBlock = ted.sequences[i].clearance; - - rotatedTrackLoc = CoordsXYZ{ CoordsXY{ trackBlock.x, trackBlock.y }.Rotate(startLoc.direction), trackBlock.z }; - auto mapLoc = CoordsXYZ{ startLoc.x, startLoc.y, startLoc.z } + rotatedTrackLoc; - - MapInvalidateTileFull(mapLoc); - - found = false; - tileElement = MapGetFirstElementAt(mapLoc); do { if (tileElement == nullptr) break; - if (tileElement->GetBaseZ() != mapLoc.z) + if (tileElement->GetBaseZ() != _origin.z) continue; if (tileElement->GetType() != TileElementType::Track) continue; - if (tileElement->GetDirection() != _origin.direction) + if ((tileElement->GetDirection()) != _origin.direction) continue; - if (tileElement->AsTrack()->GetSequenceIndex() != i) - continue; - - if (tileElement->AsTrack()->GetTrackType() != trackType) + if (tileElement->AsTrack()->GetSequenceIndex() != _sequence) continue; if (tileElement->IsGhost() != isGhost) continue; + auto tileTrackType = normaliseTrackType(tileElement->AsTrack()->GetTrackType()); + + if (tileTrackType != comparableTrackType) + continue; + found = true; break; } while (!(tileElement++)->IsLastForTile()); @@ -384,131 +294,208 @@ GameActions::Result TrackRemoveAction::Execute() const if (!found) { LOG_ERROR( - "Track Element not found. x = %d, y = %d, z = %d, d = %d, seq = %d.", mapLoc.x, mapLoc.y, mapLoc.z, - _origin.direction, i); - return GameActions::Result( - GameActions::Status::Unknown, STR_RIDE_CONSTRUCTION_CANT_REMOVE_THIS, STR_ERR_TRACK_ELEMENT_NOT_FOUND); + "Track Element not found. x = %d, y = %d, z = %d, d = %d, seq = %d.", _origin.x, _origin.y, _origin.z, + _origin.direction, _sequence); + return Result(Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_REMOVE_THIS, STR_ERR_TRACK_ELEMENT_NOT_FOUND); } - int32_t entranceDirections = ted.sequences[0].flags; - if (entranceDirections & TRACK_SEQUENCE_FLAG_ORIGIN && (tileElement->AsTrack()->GetSequenceIndex() == 0)) + RideId rideIndex = tileElement->AsTrack()->GetRideIndex(); + const auto trackType = tileElement->AsTrack()->GetTrackType(); + bool isLiftHill = tileElement->AsTrack()->HasChain(); + + auto ride = GetRide(rideIndex); + if (ride == nullptr) { - const auto removeElementResult = TrackRemoveStationElement({ mapLoc, _origin.direction }, rideIndex, 0); - if (!removeElementResult.Successful) + LOG_ERROR("Ride not found. ride index = %d.", rideIndex); + return Result(Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_REMOVE_THIS, STR_ERR_RIDE_NOT_FOUND); + } + const auto& ted = GetTrackElementDescriptor(trackType); + auto sequenceIndex = tileElement->AsTrack()->GetSequenceIndex(); + if (sequenceIndex >= ted.numSequences) + { + LOG_ERROR("Track block %d not found for track type %d.", sequenceIndex, trackType); + return Result(Status::InvalidParameters, STR_RIDE_CONSTRUCTION_CANT_REMOVE_THIS, STR_ERR_TRACK_BLOCK_NOT_FOUND); + } + + auto startLoc = _origin; + startLoc.direction = tileElement->GetDirection(); + + const auto& currentTrackBlock = ted.sequences[sequenceIndex].clearance; + auto rotatedTrackLoc = CoordsXYZ{ CoordsXY{ currentTrackBlock.x, currentTrackBlock.y }.Rotate(startLoc.direction), + currentTrackBlock.z }; + startLoc.x -= rotatedTrackLoc.x; + startLoc.y -= rotatedTrackLoc.y; + startLoc.z -= rotatedTrackLoc.z; + res.Position.x = startLoc.x; + res.Position.y = startLoc.y; + res.Position.z = startLoc.z; + + money64 supportCosts = 0; + + for (uint8_t i = 0; i < ted.numSequences; i++) + { + const auto& trackBlock = ted.sequences[i].clearance; + + rotatedTrackLoc = CoordsXYZ{ CoordsXY{ trackBlock.x, trackBlock.y }.Rotate(startLoc.direction), trackBlock.z }; + auto mapLoc = CoordsXYZ{ startLoc.x, startLoc.y, startLoc.z } + rotatedTrackLoc; + + MapInvalidateTileFull(mapLoc); + + found = false; + tileElement = MapGetFirstElementAt(mapLoc); + do { - return GameActions::Result( - GameActions::Status::Unknown, STR_RIDE_CONSTRUCTION_CANT_REMOVE_THIS, removeElementResult.Message); + if (tileElement == nullptr) + break; + + if (tileElement->GetBaseZ() != mapLoc.z) + continue; + + if (tileElement->GetType() != TileElementType::Track) + continue; + + if (tileElement->GetDirection() != _origin.direction) + continue; + + if (tileElement->AsTrack()->GetSequenceIndex() != i) + continue; + + if (tileElement->AsTrack()->GetTrackType() != trackType) + continue; + + if (tileElement->IsGhost() != isGhost) + continue; + + found = true; + break; + } while (!(tileElement++)->IsLastForTile()); + + if (!found) + { + LOG_ERROR( + "Track Element not found. x = %d, y = %d, z = %d, d = %d, seq = %d.", mapLoc.x, mapLoc.y, mapLoc.z, + _origin.direction, i); + return Result(Status::Unknown, STR_RIDE_CONSTRUCTION_CANT_REMOVE_THIS, STR_ERR_TRACK_ELEMENT_NOT_FOUND); + } + + int32_t entranceDirections = ted.sequences[0].flags; + if (entranceDirections & TRACK_SEQUENCE_FLAG_ORIGIN && (tileElement->AsTrack()->GetSequenceIndex() == 0)) + { + const auto removeElementResult = TrackRemoveStationElement({ mapLoc, _origin.direction }, rideIndex, 0); + if (!removeElementResult.Successful) + { + return Result(Status::Unknown, STR_RIDE_CONSTRUCTION_CANT_REMOVE_THIS, removeElementResult.Message); + } + } + + auto* surfaceElement = MapGetSurfaceElementAt(mapLoc); + if (surfaceElement == nullptr) + { + LOG_ERROR("Surface Element not found. x = %d, y = %d", mapLoc.x, mapLoc.y); + return Result(Status::Unknown, STR_RIDE_CONSTRUCTION_CANT_REMOVE_THIS, STR_ERR_SURFACE_ELEMENT_NOT_FOUND); + } + + int16_t _support_height = tileElement->BaseHeight - surfaceElement->BaseHeight; + if (_support_height < 0) + { + _support_height = 10; + } + + supportCosts += (_support_height / 2) * ride->getRideTypeDescriptor().BuildCosts.SupportPrice; + + // If the removed tile is a station modify station properties. + // Don't do this if the ride is simulating and the tile is a ghost to prevent desyncs. + if (entranceDirections & TRACK_SEQUENCE_FLAG_ORIGIN + && (!(GetFlags() & GAME_COMMAND_FLAG_GHOST) || (GetFlags() & GAME_COMMAND_FLAG_TRACK_DESIGN)) + && (tileElement->AsTrack()->GetSequenceIndex() == 0)) + { + const auto removeElementResult = TrackRemoveStationElement( + { mapLoc, _origin.direction }, rideIndex, GAME_COMMAND_FLAG_APPLY); + if (!removeElementResult.Successful) + { + return Result(Status::Unknown, STR_RIDE_CONSTRUCTION_CANT_REMOVE_THIS, removeElementResult.Message); + } + } + + if (ride->getRideTypeDescriptor().HasFlag(RtdFlag::trackMustBeOnWater)) + { + surfaceElement->SetHasTrackThatNeedsWater(false); + } + + InvalidateTestResults(*ride); + FootpathQueueChainReset(); + if (!getGameState().cheats.disableClearanceChecks || !(tileElement->IsGhost())) + { + FootpathRemoveEdgesAt(mapLoc, tileElement); + } + TileElementRemove(tileElement); + ride->validateStations(); + if (!(GetFlags() & GAME_COMMAND_FLAG_GHOST)) + { + ride->updateMaxVehicles(); } } - auto* surfaceElement = MapGetSurfaceElementAt(mapLoc); - if (surfaceElement == nullptr) - { - LOG_ERROR("Surface Element not found. x = %d, y = %d", mapLoc.x, mapLoc.y); - return GameActions::Result( - GameActions::Status::Unknown, STR_RIDE_CONSTRUCTION_CANT_REMOVE_THIS, STR_ERR_SURFACE_ELEMENT_NOT_FOUND); - } - - int16_t _support_height = tileElement->BaseHeight - surfaceElement->BaseHeight; - if (_support_height < 0) - { - _support_height = 10; - } - - supportCosts += (_support_height / 2) * ride->getRideTypeDescriptor().BuildCosts.SupportPrice; - - // If the removed tile is a station modify station properties. - // Don't do this if the ride is simulating and the tile is a ghost to prevent desyncs. - if (entranceDirections & TRACK_SEQUENCE_FLAG_ORIGIN - && (!(GetFlags() & GAME_COMMAND_FLAG_GHOST) || (GetFlags() & GAME_COMMAND_FLAG_TRACK_DESIGN)) - && (tileElement->AsTrack()->GetSequenceIndex() == 0)) - { - const auto removeElementResult = TrackRemoveStationElement( - { mapLoc, _origin.direction }, rideIndex, GAME_COMMAND_FLAG_APPLY); - if (!removeElementResult.Successful) - { - return GameActions::Result( - GameActions::Status::Unknown, STR_RIDE_CONSTRUCTION_CANT_REMOVE_THIS, removeElementResult.Message); - } - } - - if (ride->getRideTypeDescriptor().HasFlag(RtdFlag::trackMustBeOnWater)) - { - surfaceElement->SetHasTrackThatNeedsWater(false); - } - - InvalidateTestResults(*ride); - FootpathQueueChainReset(); - if (!getGameState().cheats.disableClearanceChecks || !(tileElement->IsGhost())) - { - FootpathRemoveEdgesAt(mapLoc, tileElement); - } - TileElementRemove(tileElement); - ride->validateStations(); if (!(GetFlags() & GAME_COMMAND_FLAG_GHOST)) { - ride->updateMaxVehicles(); - } - } - - if (!(GetFlags() & GAME_COMMAND_FLAG_GHOST)) - { - switch (trackType) - { - case TrackElemType::OnRidePhoto: - ride->lifecycleFlags &= ~RIDE_LIFECYCLE_ON_RIDE_PHOTO; - break; - case TrackElemType::CableLiftHill: - ride->lifecycleFlags &= ~RIDE_LIFECYCLE_CABLE_LIFT_HILL_COMPONENT_USED; - break; - case TrackElemType::BlockBrakes: - case TrackElemType::DiagBlockBrakes: - ride->numBlockBrakes--; - if (ride->numBlockBrakes == 0) - { - ride->windowInvalidateFlags |= RIDE_INVALIDATE_RIDE_OPERATING; - RideMode newMode = RideMode::continuousCircuit; - if (ride->mode == RideMode::poweredLaunchBlockSectioned) + switch (trackType) + { + case TrackElemType::OnRidePhoto: + ride->lifecycleFlags &= ~RIDE_LIFECYCLE_ON_RIDE_PHOTO; + break; + case TrackElemType::CableLiftHill: + ride->lifecycleFlags &= ~RIDE_LIFECYCLE_CABLE_LIFT_HILL_COMPONENT_USED; + break; + case TrackElemType::BlockBrakes: + case TrackElemType::DiagBlockBrakes: + ride->numBlockBrakes--; + if (ride->numBlockBrakes == 0) { - newMode = RideMode::poweredLaunch; + ride->windowInvalidateFlags |= RIDE_INVALIDATE_RIDE_OPERATING; + RideMode newMode = RideMode::continuousCircuit; + if (ride->mode == RideMode::poweredLaunchBlockSectioned) + { + newMode = RideMode::poweredLaunch; + } + + auto rideSetSetting = GameActions::RideSetSettingAction( + ride->id, GameActions::RideSetSetting::Mode, static_cast(newMode)); + ExecuteNested(&rideSetSetting); } - auto rideSetSetting = RideSetSettingAction(ride->id, RideSetSetting::Mode, static_cast(newMode)); - GameActions::ExecuteNested(&rideSetSetting); - } - - break; - default: - break; - } - - switch (trackType) - { - case TrackElemType::Up25ToFlat: - case TrackElemType::Up60ToFlat: - case TrackElemType::DiagUp25ToFlat: - case TrackElemType::DiagUp60ToFlat: - if (!isLiftHill) break; - [[fallthrough]]; - case TrackElemType::CableLiftHill: - ride->numBlockBrakes--; - break; - default: - break; + default: + break; + } + + switch (trackType) + { + case TrackElemType::Up25ToFlat: + case TrackElemType::Up60ToFlat: + case TrackElemType::DiagUp25ToFlat: + case TrackElemType::DiagUp60ToFlat: + if (!isLiftHill) + break; + [[fallthrough]]; + case TrackElemType::CableLiftHill: + ride->numBlockBrakes--; + break; + default: + break; + } } - } - money64 price = ride->getRideTypeDescriptor().BuildCosts.TrackPrice; - price *= ted.priceModifier; - price >>= 16; - price = supportCosts + price; - if (ride->lifecycleFlags & RIDE_LIFECYCLE_EVER_BEEN_OPENED) - { - // 70% modifier for opened rides - price = (price * 45875) / 65536; - } + money64 price = ride->getRideTypeDescriptor().BuildCosts.TrackPrice; + price *= ted.priceModifier; + price >>= 16; + price = supportCosts + price; + if (ride->lifecycleFlags & RIDE_LIFECYCLE_EVER_BEEN_OPENED) + { + // 70% modifier for opened rides + price = (price * 45875) / 65536; + } - res.Cost = -price; - return res; -} + res.Cost = -price; + return res; + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/TrackRemoveAction.h b/src/openrct2/actions/TrackRemoveAction.h index 51b74b1857..6207dd14b5 100644 --- a/src/openrct2/actions/TrackRemoveAction.h +++ b/src/openrct2/actions/TrackRemoveAction.h @@ -11,22 +11,25 @@ #include "GameAction.h" -class TrackRemoveAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - OpenRCT2::TrackElemType _trackType{}; - int32_t _sequence{}; - CoordsXYZD _origin; + class TrackRemoveAction final : public GameActionBase + { + private: + TrackElemType _trackType{}; + int32_t _sequence{}; + CoordsXYZD _origin; -public: - TrackRemoveAction() = default; - TrackRemoveAction(OpenRCT2::TrackElemType trackType, int32_t sequence, const CoordsXYZD& origin); + public: + TrackRemoveAction() = default; + TrackRemoveAction(TrackElemType trackType, int32_t sequence, const CoordsXYZD& origin); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override final; + uint16_t GetActionFlags() const override final; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; -}; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/TrackSetBrakeSpeedAction.cpp b/src/openrct2/actions/TrackSetBrakeSpeedAction.cpp index 9884cb0ab1..ba042387d7 100644 --- a/src/openrct2/actions/TrackSetBrakeSpeedAction.cpp +++ b/src/openrct2/actions/TrackSetBrakeSpeedAction.cpp @@ -14,76 +14,77 @@ #include "../ride/RideConstruction.h" #include "../world/tile_element/TrackElement.h" -using namespace OpenRCT2; - -TrackSetBrakeSpeedAction::TrackSetBrakeSpeedAction(const CoordsXYZ& loc, OpenRCT2::TrackElemType trackType, uint8_t brakeSpeed) - : _loc(loc) - , _trackType(trackType) - , _brakeSpeed(brakeSpeed) +namespace OpenRCT2::GameActions { -} - -void TrackSetBrakeSpeedAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit(_loc); - visitor.Visit("trackType", _trackType); - visitor.Visit("brakeSpeed", _brakeSpeed); -} - -uint16_t TrackSetBrakeSpeedAction::GetActionFlags() const -{ - return GameAction::GetActionFlags() | GameActions::Flags::AllowWhilePaused; -} - -void TrackSetBrakeSpeedAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - stream << DS_TAG(_loc) << DS_TAG(_trackType) << DS_TAG(_brakeSpeed); -} - -GameActions::Result TrackSetBrakeSpeedAction::Query() const -{ - return QueryExecute(false); -} - -GameActions::Result TrackSetBrakeSpeedAction::Execute() const -{ - return QueryExecute(true); -} - -GameActions::Result TrackSetBrakeSpeedAction::QueryExecute(bool isExecuting) const -{ - auto res = GameActions::Result(); - - res.Position = _loc; - res.Position.x += 16; - res.Position.y += 16; - res.Expenditure = ExpenditureType::rideConstruction; - - if (!LocationValid(_loc)) + TrackSetBrakeSpeedAction::TrackSetBrakeSpeedAction( + const CoordsXYZ& loc, OpenRCT2::TrackElemType trackType, uint8_t brakeSpeed) + : _loc(loc) + , _trackType(trackType) + , _brakeSpeed(brakeSpeed) { - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_CHANGE_THIS, STR_OFF_EDGE_OF_MAP); } - TileElement* tileElement = MapGetTrackElementAtOfType(_loc, _trackType); - if (tileElement == nullptr) + void TrackSetBrakeSpeedAction::AcceptParameters(GameActionParameterVisitor& visitor) { - LOG_ERROR("Track element of type %u not found at x = %d, y = %d, z = %d", _trackType, _loc.x, _loc.y, _loc.z); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_TILE_ELEMENT_NOT_FOUND); + visitor.Visit(_loc); + visitor.Visit("trackType", _trackType); + visitor.Visit("brakeSpeed", _brakeSpeed); } - if (_brakeSpeed > kMaximumTrackSpeed) + uint16_t TrackSetBrakeSpeedAction::GetActionFlags() const { - LOG_WARNING("Invalid speed for track, speed = %d", _brakeSpeed); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_SPEED_TOO_HIGH, kStringIdNone); + return GameAction::GetActionFlags() | Flags::AllowWhilePaused; } - if (isExecuting) + void TrackSetBrakeSpeedAction::Serialise(DataSerialiser& stream) { - GetTrackElementOriginAndApplyChanges( - { _loc, tileElement->GetDirection() }, tileElement->AsTrack()->GetTrackType(), _brakeSpeed, nullptr, - { TrackElementSetFlag::brakeBoosterSpeed }); + GameAction::Serialise(stream); + stream << DS_TAG(_loc) << DS_TAG(_trackType) << DS_TAG(_brakeSpeed); } - return res; -} + + Result TrackSetBrakeSpeedAction::Query() const + { + return QueryExecute(false); + } + + Result TrackSetBrakeSpeedAction::Execute() const + { + return QueryExecute(true); + } + + Result TrackSetBrakeSpeedAction::QueryExecute(bool isExecuting) const + { + auto res = Result(); + + res.Position = _loc; + res.Position.x += 16; + res.Position.y += 16; + res.Expenditure = ExpenditureType::rideConstruction; + + if (!LocationValid(_loc)) + { + return Result(Status::InvalidParameters, STR_CANT_CHANGE_THIS, STR_OFF_EDGE_OF_MAP); + } + + TileElement* tileElement = MapGetTrackElementAtOfType(_loc, _trackType); + if (tileElement == nullptr) + { + LOG_ERROR("Track element of type %u not found at x = %d, y = %d, z = %d", _trackType, _loc.x, _loc.y, _loc.z); + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_TILE_ELEMENT_NOT_FOUND); + } + + if (_brakeSpeed > kMaximumTrackSpeed) + { + LOG_WARNING("Invalid speed for track, speed = %d", _brakeSpeed); + return Result(Status::InvalidParameters, STR_SPEED_TOO_HIGH, kStringIdNone); + } + + if (isExecuting) + { + GetTrackElementOriginAndApplyChanges( + { _loc, tileElement->GetDirection() }, tileElement->AsTrack()->GetTrackType(), _brakeSpeed, nullptr, + { TrackElementSetFlag::brakeBoosterSpeed }); + } + return res; + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/TrackSetBrakeSpeedAction.h b/src/openrct2/actions/TrackSetBrakeSpeedAction.h index 3301d1d4a6..399737f783 100644 --- a/src/openrct2/actions/TrackSetBrakeSpeedAction.h +++ b/src/openrct2/actions/TrackSetBrakeSpeedAction.h @@ -11,25 +11,28 @@ #include "GameAction.h" -class TrackSetBrakeSpeedAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - CoordsXYZ _loc; - OpenRCT2::TrackElemType _trackType{}; - uint8_t _brakeSpeed{}; + class TrackSetBrakeSpeedAction final : public GameActionBase + { + private: + CoordsXYZ _loc; + TrackElemType _trackType{}; + uint8_t _brakeSpeed{}; -public: - TrackSetBrakeSpeedAction() = default; - TrackSetBrakeSpeedAction(const CoordsXYZ& loc, OpenRCT2::TrackElemType trackType, uint8_t brakeSpeed); + public: + TrackSetBrakeSpeedAction() = default; + TrackSetBrakeSpeedAction(const CoordsXYZ& loc, OpenRCT2::TrackElemType trackType, uint8_t brakeSpeed); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override final; + uint16_t GetActionFlags() const override final; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; -private: - OpenRCT2::GameActions::Result QueryExecute(bool isExecuting) const; -}; + private: + Result QueryExecute(bool isExecuting) const; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/WallPlaceAction.cpp b/src/openrct2/actions/WallPlaceAction.cpp index a59eac5376..295abf18d8 100644 --- a/src/openrct2/actions/WallPlaceAction.cpp +++ b/src/openrct2/actions/WallPlaceAction.cpp @@ -31,587 +31,575 @@ #include "../world/tile_element/TrackElement.h" #include "../world/tile_element/WallElement.h" -using namespace OpenRCT2; -using namespace OpenRCT2::TrackMetaData; - -WallPlaceAction::WallPlaceAction( - ObjectEntryIndex wallType, const CoordsXYZ& loc, uint8_t edge, int32_t primaryColour, int32_t secondaryColour, - int32_t tertiaryColour) - : _wallType(wallType) - , _loc(loc) - , _edge(edge) - , _primaryColour(primaryColour) - , _secondaryColour(secondaryColour) - , _tertiaryColour(tertiaryColour) +namespace OpenRCT2::GameActions { -} + using namespace OpenRCT2::TrackMetaData; -void WallPlaceAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit(_loc); - visitor.Visit("object", _wallType); - visitor.Visit("edge", _edge); - visitor.Visit("primaryColour", _primaryColour); - visitor.Visit("secondaryColour", _secondaryColour); - visitor.Visit("tertiaryColour", _tertiaryColour); -} - -uint16_t WallPlaceAction::GetActionFlags() const -{ - return GameAction::GetActionFlags(); -} - -void WallPlaceAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_wallType) << DS_TAG(_loc) << DS_TAG(_edge) << DS_TAG(_primaryColour) << DS_TAG(_secondaryColour) - << DS_TAG(_tertiaryColour); -} - -GameActions::Result WallPlaceAction::Query() const -{ - auto res = GameActions::Result(); - res.ErrorTitle = STR_CANT_BUILD_THIS_HERE; - res.Position = _loc; - - res.Expenditure = ExpenditureType::landscaping; - res.Position.x += 16; - res.Position.y += 16; - - if (_loc.z == 0) + WallPlaceAction::WallPlaceAction( + ObjectEntryIndex wallType, const CoordsXYZ& loc, uint8_t edge, int32_t primaryColour, int32_t secondaryColour, + int32_t tertiaryColour) + : _wallType(wallType) + , _loc(loc) + , _edge(edge) + , _primaryColour(primaryColour) + , _secondaryColour(secondaryColour) + , _tertiaryColour(tertiaryColour) { - res.Position.z = TileElementHeight(res.Position); } - if (!LocationValid(_loc)) + void WallPlaceAction::AcceptParameters(GameActionParameterVisitor& visitor) { - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_BUILD_THIS_HERE, STR_OFF_EDGE_OF_MAP); + visitor.Visit(_loc); + visitor.Visit("object", _wallType); + visitor.Visit("edge", _edge); + visitor.Visit("primaryColour", _primaryColour); + visitor.Visit("secondaryColour", _secondaryColour); + visitor.Visit("tertiaryColour", _tertiaryColour); } - auto& gameState = getGameState(); - auto mapSizeMax = GetMapSizeMaxXY(); - if (gLegacyScene != LegacyScene::scenarioEditor && !(GetFlags() & GAME_COMMAND_FLAG_TRACK_DESIGN) - && !gameState.cheats.sandboxMode) + uint16_t WallPlaceAction::GetActionFlags() const { + return GameAction::GetActionFlags(); + } + + void WallPlaceAction::Serialise(DataSerialiser& stream) + { + GameAction::Serialise(stream); + + stream << DS_TAG(_wallType) << DS_TAG(_loc) << DS_TAG(_edge) << DS_TAG(_primaryColour) << DS_TAG(_secondaryColour) + << DS_TAG(_tertiaryColour); + } + + Result WallPlaceAction::Query() const + { + auto res = Result(); + res.ErrorTitle = STR_CANT_BUILD_THIS_HERE; + res.Position = _loc; + + res.Expenditure = ExpenditureType::landscaping; + res.Position.x += 16; + res.Position.y += 16; + if (_loc.z == 0) { - if (!MapIsLocationInPark(_loc)) + res.Position.z = TileElementHeight(res.Position); + } + + if (!LocationValid(_loc)) + { + return Result(Status::InvalidParameters, STR_CANT_BUILD_THIS_HERE, STR_OFF_EDGE_OF_MAP); + } + + auto& gameState = getGameState(); + auto mapSizeMax = GetMapSizeMaxXY(); + if (gLegacyScene != LegacyScene::scenarioEditor && !(GetFlags() & GAME_COMMAND_FLAG_TRACK_DESIGN) + && !gameState.cheats.sandboxMode) + { + if (_loc.z == 0) { - return GameActions::Result(GameActions::Status::NotOwned, STR_CANT_BUILD_THIS_HERE, STR_LAND_NOT_OWNED_BY_PARK); + if (!MapIsLocationInPark(_loc)) + { + return Result(Status::NotOwned, STR_CANT_BUILD_THIS_HERE, STR_LAND_NOT_OWNED_BY_PARK); + } + } + else if (!MapIsLocationOwned(_loc)) + { + return Result(Status::NotOwned, STR_CANT_BUILD_THIS_HERE, STR_LAND_NOT_OWNED_BY_PARK); } } - else if (!MapIsLocationOwned(_loc)) + else if (!_trackDesignDrawingPreview && (_loc.x > mapSizeMax.x || _loc.y > mapSizeMax.y)) { - return GameActions::Result(GameActions::Status::NotOwned, STR_CANT_BUILD_THIS_HERE, STR_LAND_NOT_OWNED_BY_PARK); + LOG_ERROR("Invalid x/y coordinates. x = %d y = %d", _loc.x, _loc.y); + return Result(Status::InvalidParameters, STR_CANT_BUILD_THIS_HERE, STR_OFF_EDGE_OF_MAP); } - } - else if (!_trackDesignDrawingPreview && (_loc.x > mapSizeMax.x || _loc.y > mapSizeMax.y)) - { - LOG_ERROR("Invalid x/y coordinates. x = %d y = %d", _loc.x, _loc.y); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_BUILD_THIS_HERE, STR_OFF_EDGE_OF_MAP); - } - if (_edge > 3) - { - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_BUILD_THIS_HERE, kStringIdNone); - } + if (_edge > 3) + { + return Result(Status::InvalidParameters, STR_CANT_BUILD_THIS_HERE, kStringIdNone); + } + + uint8_t edgeSlope = 0; + auto targetHeight = _loc.z; + if (targetHeight == 0) + { + auto* surfaceElement = MapGetSurfaceElementAt(_loc); + if (surfaceElement == nullptr) + { + LOG_ERROR("Surface element not found at %d, %d.", _loc.x, _loc.y); + return Result(Status::InvalidParameters, STR_CANT_BUILD_THIS_HERE, STR_ERR_SURFACE_ELEMENT_NOT_FOUND); + } + targetHeight = surfaceElement->GetBaseZ(); + + uint8_t slope = surfaceElement->GetSlope(); + edgeSlope = GetWallSlopeFromEdgeSlope(slope, _edge & 3); + if (edgeSlope & EDGE_SLOPE_ELEVATED) + { + targetHeight += 16; + edgeSlope &= ~EDGE_SLOPE_ELEVATED; + } + } - uint8_t edgeSlope = 0; - auto targetHeight = _loc.z; - if (targetHeight == 0) - { auto* surfaceElement = MapGetSurfaceElementAt(_loc); if (surfaceElement == nullptr) { LOG_ERROR("Surface element not found at %d, %d.", _loc.x, _loc.y); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_BUILD_THIS_HERE, STR_ERR_SURFACE_ELEMENT_NOT_FOUND); + return Result(Status::InvalidParameters, STR_CANT_BUILD_THIS_HERE, STR_ERR_SURFACE_ELEMENT_NOT_FOUND); } - targetHeight = surfaceElement->GetBaseZ(); - uint8_t slope = surfaceElement->GetSlope(); - edgeSlope = GetWallSlopeFromEdgeSlope(slope, _edge & 3); - if (edgeSlope & EDGE_SLOPE_ELEVATED) + if (surfaceElement->GetWaterHeight() > 0) { - targetHeight += 16; - edgeSlope &= ~EDGE_SLOPE_ELEVATED; - } - } + uint16_t waterHeight = surfaceElement->GetWaterHeight(); - auto* surfaceElement = MapGetSurfaceElementAt(_loc); - if (surfaceElement == nullptr) - { - LOG_ERROR("Surface element not found at %d, %d.", _loc.x, _loc.y); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_BUILD_THIS_HERE, STR_ERR_SURFACE_ELEMENT_NOT_FOUND); - } - - if (surfaceElement->GetWaterHeight() > 0) - { - uint16_t waterHeight = surfaceElement->GetWaterHeight(); - - if (targetHeight < waterHeight && !gameState.cheats.disableClearanceChecks) - { - return GameActions::Result( - GameActions::Status::Disallowed, STR_CANT_BUILD_THIS_HERE, STR_CANT_BUILD_THIS_UNDERWATER); - } - } - - if (targetHeight < surfaceElement->GetBaseZ() && !gameState.cheats.disableClearanceChecks) - { - return GameActions::Result( - GameActions::Status::Disallowed, STR_CANT_BUILD_THIS_HERE, STR_CAN_ONLY_BUILD_THIS_ABOVE_GROUND); - } - - if (!(edgeSlope & (EDGE_SLOPE_UPWARDS | EDGE_SLOPE_DOWNWARDS))) - { - uint8_t newEdge = (_edge + 2) & 3; - uint8_t newBaseHeight = surfaceElement->BaseHeight; - newBaseHeight += 2; - if (surfaceElement->GetSlope() & (1 << newEdge)) - { - if (targetHeight / 8 < newBaseHeight && !gameState.cheats.disableClearanceChecks) + if (targetHeight < waterHeight && !gameState.cheats.disableClearanceChecks) { - return GameActions::Result( - GameActions::Status::Disallowed, STR_CANT_BUILD_THIS_HERE, STR_CAN_ONLY_BUILD_THIS_ABOVE_GROUND); + return Result(Status::Disallowed, STR_CANT_BUILD_THIS_HERE, STR_CANT_BUILD_THIS_UNDERWATER); } + } - if (surfaceElement->GetSlope() & kTileSlopeDiagonalFlag) + if (targetHeight < surfaceElement->GetBaseZ() && !gameState.cheats.disableClearanceChecks) + { + return Result(Status::Disallowed, STR_CANT_BUILD_THIS_HERE, STR_CAN_ONLY_BUILD_THIS_ABOVE_GROUND); + } + + if (!(edgeSlope & (EDGE_SLOPE_UPWARDS | EDGE_SLOPE_DOWNWARDS))) + { + uint8_t newEdge = (_edge + 2) & 3; + uint8_t newBaseHeight = surfaceElement->BaseHeight; + newBaseHeight += 2; + if (surfaceElement->GetSlope() & (1 << newEdge)) { - newEdge = (newEdge - 1) & 3; - - if (surfaceElement->GetSlope() & (1 << newEdge)) + if (targetHeight / 8 < newBaseHeight && !gameState.cheats.disableClearanceChecks) { - newEdge = (newEdge + 2) & 3; + return Result(Status::Disallowed, STR_CANT_BUILD_THIS_HERE, STR_CAN_ONLY_BUILD_THIS_ABOVE_GROUND); + } + + if (surfaceElement->GetSlope() & kTileSlopeDiagonalFlag) + { + newEdge = (newEdge - 1) & 3; + if (surfaceElement->GetSlope() & (1 << newEdge)) { - newBaseHeight += 2; - if (targetHeight / 8 < newBaseHeight && !gameState.cheats.disableClearanceChecks) + newEdge = (newEdge + 2) & 3; + if (surfaceElement->GetSlope() & (1 << newEdge)) { - return GameActions::Result( - GameActions::Status::Disallowed, STR_CANT_BUILD_THIS_HERE, - STR_CAN_ONLY_BUILD_THIS_ABOVE_GROUND); + newBaseHeight += 2; + if (targetHeight / 8 < newBaseHeight && !gameState.cheats.disableClearanceChecks) + { + return Result( + Status::Disallowed, STR_CANT_BUILD_THIS_HERE, STR_CAN_ONLY_BUILD_THIS_ABOVE_GROUND); + } + newBaseHeight -= 2; } - newBaseHeight -= 2; } } } - } - newEdge = (_edge + 3) & 3; - if (surfaceElement->GetSlope() & (1 << newEdge)) - { - if (targetHeight / 8 < newBaseHeight && !gameState.cheats.disableClearanceChecks) + newEdge = (_edge + 3) & 3; + if (surfaceElement->GetSlope() & (1 << newEdge)) { - return GameActions::Result( - GameActions::Status::Disallowed, STR_CANT_BUILD_THIS_HERE, STR_CAN_ONLY_BUILD_THIS_ABOVE_GROUND); - } - - if (surfaceElement->GetSlope() & kTileSlopeDiagonalFlag) - { - newEdge = (newEdge - 1) & 3; - - if (surfaceElement->GetSlope() & (1 << newEdge)) + if (targetHeight / 8 < newBaseHeight && !gameState.cheats.disableClearanceChecks) { - newEdge = (newEdge + 2) & 3; + return Result(Status::Disallowed, STR_CANT_BUILD_THIS_HERE, STR_CAN_ONLY_BUILD_THIS_ABOVE_GROUND); + } + + if (surfaceElement->GetSlope() & kTileSlopeDiagonalFlag) + { + newEdge = (newEdge - 1) & 3; + if (surfaceElement->GetSlope() & (1 << newEdge)) { - newBaseHeight += 2; - if (targetHeight / 8 < newBaseHeight && !gameState.cheats.disableClearanceChecks) + newEdge = (newEdge + 2) & 3; + if (surfaceElement->GetSlope() & (1 << newEdge)) { - return GameActions::Result( - GameActions::Status::Disallowed, STR_CANT_BUILD_THIS_HERE, - STR_CAN_ONLY_BUILD_THIS_ABOVE_GROUND); + newBaseHeight += 2; + if (targetHeight / 8 < newBaseHeight && !gameState.cheats.disableClearanceChecks) + { + return Result( + Status::Disallowed, STR_CANT_BUILD_THIS_HERE, STR_CAN_ONLY_BUILD_THIS_ABOVE_GROUND); + } } } } } } - } - auto* wallEntry = ObjectManager::GetObjectEntry(_wallType); + auto* wallEntry = ObjectManager::GetObjectEntry(_wallType); - if (wallEntry == nullptr) - { - LOG_ERROR("Wall Type not found %d", _wallType); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_BUILD_THIS_HERE, STR_UNKNOWN_OBJECT_TYPE); - } - - if (wallEntry->scrolling_mode != kScrollingModeNone) - { - if (HasReachedBannerLimit()) + if (wallEntry == nullptr) { - LOG_ERROR("No free banners available"); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_BUILD_THIS_HERE, STR_TOO_MANY_BANNERS_IN_GAME); - } - } - - uint8_t clearanceHeight = targetHeight / 8; - if (edgeSlope & (EDGE_SLOPE_UPWARDS | EDGE_SLOPE_DOWNWARDS)) - { - if (wallEntry->flags & WALL_SCENERY_CANT_BUILD_ON_SLOPE) - { - return GameActions::Result( - GameActions::Status::Disallowed, STR_CANT_BUILD_THIS_HERE, STR_ERR_UNABLE_TO_BUILD_THIS_ON_SLOPE); - } - clearanceHeight += 2; - } - clearanceHeight += wallEntry->height; - - bool wallAcrossTrack = false; - if (!(GetFlags() & GAME_COMMAND_FLAG_TRACK_DESIGN) && !gameState.cheats.disableClearanceChecks) - { - auto result = WallCheckObstruction(wallEntry, targetHeight / 8, clearanceHeight, &wallAcrossTrack); - if (result.Error != GameActions::Status::Ok) - { - return result; - } - } - - if (!MapCheckCapacityAndReorganise(_loc)) - { - return GameActions::Result( - GameActions::Status::NoFreeElements, STR_CANT_BUILD_THIS_HERE, STR_TILE_ELEMENT_LIMIT_REACHED); - } - - res.Cost = wallEntry->price; - - res.SetData(WallPlaceActionResult{}); - - return res; -} - -GameActions::Result WallPlaceAction::Execute() const -{ - auto res = GameActions::Result(); - auto& gameState = getGameState(); - - res.ErrorTitle = STR_CANT_BUILD_THIS_HERE; - res.Position = _loc; - - res.Expenditure = ExpenditureType::landscaping; - res.Position.x += 16; - res.Position.y += 16; - - if (res.Position.z == 0) - { - res.Position.z = TileElementHeight(res.Position); - } - - uint8_t edgeSlope = 0; - auto targetHeight = _loc.z; - if (targetHeight == 0) - { - auto* surfaceElement = MapGetSurfaceElementAt(_loc); - if (surfaceElement == nullptr) - { - LOG_ERROR("Surface element not found at %d, %d.", _loc.x, _loc.y); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_BUILD_THIS_HERE, STR_ERR_SURFACE_ELEMENT_NOT_FOUND); - } - targetHeight = surfaceElement->GetBaseZ(); - - uint8_t slope = surfaceElement->GetSlope(); - edgeSlope = GetWallSlopeFromEdgeSlope(slope, _edge & 3); - if (edgeSlope & EDGE_SLOPE_ELEVATED) - { - targetHeight += 16; - edgeSlope &= ~EDGE_SLOPE_ELEVATED; - } - } - auto targetLoc = CoordsXYZ(_loc, targetHeight); - - auto* wallEntry = ObjectManager::GetObjectEntry(_wallType); - - if (wallEntry == nullptr) - { - LOG_ERROR("Wall Type not found %d", _wallType); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_BUILD_THIS_HERE, STR_UNKNOWN_OBJECT_TYPE); - } - - uint8_t clearanceHeight = targetHeight / kCoordsZStep; - if (edgeSlope & (EDGE_SLOPE_UPWARDS | EDGE_SLOPE_DOWNWARDS)) - { - clearanceHeight += 2; - } - clearanceHeight += wallEntry->height; - - bool wallAcrossTrack = false; - if (!(GetFlags() & GAME_COMMAND_FLAG_TRACK_DESIGN) && !gameState.cheats.disableClearanceChecks) - { - auto result = WallCheckObstruction(wallEntry, targetHeight / kCoordsZStep, clearanceHeight, &wallAcrossTrack); - if (result.Error != GameActions::Status::Ok) - { - return result; - } - } - - Banner* banner = nullptr; - if (wallEntry->scrolling_mode != kScrollingModeNone) - { - banner = CreateBanner(); - if (banner == nullptr) - { - LOG_ERROR("No free banners available"); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_BUILD_THIS_HERE, STR_TOO_MANY_BANNERS_IN_GAME); + LOG_ERROR("Wall Type not found %d", _wallType); + return Result(Status::InvalidParameters, STR_CANT_BUILD_THIS_HERE, STR_UNKNOWN_OBJECT_TYPE); } - banner->text = {}; - banner->colour = COLOUR_WHITE; - banner->textColour = TextColour::white; - banner->flags = { BannerFlag::isWall }; - banner->type = 0; // Banner must be deleted after this point in an early return - banner->position = TileCoordsXY(_loc); - - RideId rideIndex = BannerGetClosestRideIndex(targetLoc); - if (!rideIndex.IsNull()) + if (wallEntry->scrolling_mode != kScrollingModeNone) { - banner->rideIndex = rideIndex; - banner->flags.set(BannerFlag::linkedToRide); + if (HasReachedBannerLimit()) + { + LOG_ERROR("No free banners available"); + return Result(Status::InvalidParameters, STR_CANT_BUILD_THIS_HERE, STR_TOO_MANY_BANNERS_IN_GAME); + } } + + uint8_t clearanceHeight = targetHeight / 8; + if (edgeSlope & (EDGE_SLOPE_UPWARDS | EDGE_SLOPE_DOWNWARDS)) + { + if (wallEntry->flags & WALL_SCENERY_CANT_BUILD_ON_SLOPE) + { + return Result(Status::Disallowed, STR_CANT_BUILD_THIS_HERE, STR_ERR_UNABLE_TO_BUILD_THIS_ON_SLOPE); + } + clearanceHeight += 2; + } + clearanceHeight += wallEntry->height; + + bool wallAcrossTrack = false; + if (!(GetFlags() & GAME_COMMAND_FLAG_TRACK_DESIGN) && !gameState.cheats.disableClearanceChecks) + { + auto result = WallCheckObstruction(wallEntry, targetHeight / 8, clearanceHeight, &wallAcrossTrack); + if (result.Error != Status::Ok) + { + return result; + } + } + + if (!MapCheckCapacityAndReorganise(_loc)) + { + return Result(Status::NoFreeElements, STR_CANT_BUILD_THIS_HERE, STR_TILE_ELEMENT_LIMIT_REACHED); + } + + res.Cost = wallEntry->price; + + res.SetData(WallPlaceActionResult{}); + + return res; } - auto* wallElement = TileElementInsert(targetLoc, 0b0000); - if (wallElement == nullptr) + Result WallPlaceAction::Execute() const { - return GameActions::Result( - GameActions::Status::NoFreeElements, STR_CANT_POSITION_THIS_HERE, STR_TILE_ELEMENT_LIMIT_REACHED); + auto res = Result(); + auto& gameState = getGameState(); + + res.ErrorTitle = STR_CANT_BUILD_THIS_HERE; + res.Position = _loc; + + res.Expenditure = ExpenditureType::landscaping; + res.Position.x += 16; + res.Position.y += 16; + + if (res.Position.z == 0) + { + res.Position.z = TileElementHeight(res.Position); + } + + uint8_t edgeSlope = 0; + auto targetHeight = _loc.z; + if (targetHeight == 0) + { + auto* surfaceElement = MapGetSurfaceElementAt(_loc); + if (surfaceElement == nullptr) + { + LOG_ERROR("Surface element not found at %d, %d.", _loc.x, _loc.y); + return Result(Status::InvalidParameters, STR_CANT_BUILD_THIS_HERE, STR_ERR_SURFACE_ELEMENT_NOT_FOUND); + } + targetHeight = surfaceElement->GetBaseZ(); + + uint8_t slope = surfaceElement->GetSlope(); + edgeSlope = GetWallSlopeFromEdgeSlope(slope, _edge & 3); + if (edgeSlope & EDGE_SLOPE_ELEVATED) + { + targetHeight += 16; + edgeSlope &= ~EDGE_SLOPE_ELEVATED; + } + } + auto targetLoc = CoordsXYZ(_loc, targetHeight); + + auto* wallEntry = ObjectManager::GetObjectEntry(_wallType); + + if (wallEntry == nullptr) + { + LOG_ERROR("Wall Type not found %d", _wallType); + return Result(Status::InvalidParameters, STR_CANT_BUILD_THIS_HERE, STR_UNKNOWN_OBJECT_TYPE); + } + + uint8_t clearanceHeight = targetHeight / kCoordsZStep; + if (edgeSlope & (EDGE_SLOPE_UPWARDS | EDGE_SLOPE_DOWNWARDS)) + { + clearanceHeight += 2; + } + clearanceHeight += wallEntry->height; + + bool wallAcrossTrack = false; + if (!(GetFlags() & GAME_COMMAND_FLAG_TRACK_DESIGN) && !gameState.cheats.disableClearanceChecks) + { + auto result = WallCheckObstruction(wallEntry, targetHeight / kCoordsZStep, clearanceHeight, &wallAcrossTrack); + if (result.Error != Status::Ok) + { + return result; + } + } + + Banner* banner = nullptr; + if (wallEntry->scrolling_mode != kScrollingModeNone) + { + banner = CreateBanner(); + if (banner == nullptr) + { + LOG_ERROR("No free banners available"); + return Result(Status::InvalidParameters, STR_CANT_BUILD_THIS_HERE, STR_TOO_MANY_BANNERS_IN_GAME); + } + + banner->text = {}; + banner->colour = COLOUR_WHITE; + banner->textColour = TextColour::white; + banner->flags = { BannerFlag::isWall }; + banner->type = 0; // Banner must be deleted after this point in an early return + banner->position = TileCoordsXY(_loc); + + RideId rideIndex = BannerGetClosestRideIndex(targetLoc); + if (!rideIndex.IsNull()) + { + banner->rideIndex = rideIndex; + banner->flags.set(BannerFlag::linkedToRide); + } + } + + auto* wallElement = TileElementInsert(targetLoc, 0b0000); + if (wallElement == nullptr) + { + return Result(Status::NoFreeElements, STR_CANT_POSITION_THIS_HERE, STR_TILE_ELEMENT_LIMIT_REACHED); + } + + wallElement->ClearanceHeight = clearanceHeight; + wallElement->SetDirection(_edge); + wallElement->SetSlope(edgeSlope); + + wallElement->SetPrimaryColour(_primaryColour); + wallElement->SetSecondaryColour(_secondaryColour); + wallElement->SetAcrossTrack(wallAcrossTrack); + + wallElement->SetEntryIndex(_wallType); + wallElement->SetBannerIndex(banner != nullptr ? banner->id : BannerIndex::GetNull()); + + if (wallEntry->flags & WALL_SCENERY_HAS_TERTIARY_COLOUR) + { + wallElement->SetTertiaryColour(_tertiaryColour); + } + + wallElement->SetGhost(GetFlags() & GAME_COMMAND_FLAG_GHOST); + + MapAnimations::MarkTileForInvalidation(TileCoordsXY(targetLoc)); + MapInvalidateTileZoom1({ _loc, wallElement->GetBaseZ(), wallElement->GetBaseZ() + 72 }); + + res.Cost = wallEntry->price; + + const auto bannerId = banner != nullptr ? banner->id : BannerIndex::GetNull(); + res.SetData(WallPlaceActionResult{ wallElement->GetBaseZ(), bannerId }); + + return res; } - wallElement->ClearanceHeight = clearanceHeight; - wallElement->SetDirection(_edge); - wallElement->SetSlope(edgeSlope); - - wallElement->SetPrimaryColour(_primaryColour); - wallElement->SetSecondaryColour(_secondaryColour); - wallElement->SetAcrossTrack(wallAcrossTrack); - - wallElement->SetEntryIndex(_wallType); - wallElement->SetBannerIndex(banner != nullptr ? banner->id : BannerIndex::GetNull()); - - if (wallEntry->flags & WALL_SCENERY_HAS_TERTIARY_COLOUR) + /** + * + * rct2: 0x006E5CBA + */ + bool WallPlaceAction::WallCheckObstructionWithTrack( + const WallSceneryEntry* wall, int32_t z0, TrackElement* trackElement, bool* wallAcrossTrack) const { - wallElement->SetTertiaryColour(_tertiaryColour); - } + OpenRCT2::TrackElemType trackType = trackElement->GetTrackType(); - wallElement->SetGhost(GetFlags() & GAME_COMMAND_FLAG_GHOST); - - MapAnimations::MarkTileForInvalidation(TileCoordsXY(targetLoc)); - MapInvalidateTileZoom1({ _loc, wallElement->GetBaseZ(), wallElement->GetBaseZ() + 72 }); - - res.Cost = wallEntry->price; - - const auto bannerId = banner != nullptr ? banner->id : BannerIndex::GetNull(); - res.SetData(WallPlaceActionResult{ wallElement->GetBaseZ(), bannerId }); - - return res; -} - -/** - * - * rct2: 0x006E5CBA - */ -bool WallPlaceAction::WallCheckObstructionWithTrack( - const WallSceneryEntry* wall, int32_t z0, TrackElement* trackElement, bool* wallAcrossTrack) const -{ - OpenRCT2::TrackElemType trackType = trackElement->GetTrackType(); - - using namespace OpenRCT2::TrackMetaData; - const auto& ted = GetTrackElementDescriptor(trackType); - int32_t sequence = trackElement->GetSequenceIndex(); - int32_t direction = (_edge - trackElement->GetDirection()) & kTileElementDirectionMask; - auto ride = GetRide(trackElement->GetRideIndex()); - if (ride == nullptr) - { - return false; - } - - if (TrackIsAllowedWallEdges(ride->type, trackType, sequence, direction)) - { - return true; - } - - if (!(wall->flags & WALL_SCENERY_IS_DOOR)) - { - return false; - } - - if (!ride->getRideTypeDescriptor().HasFlag(RtdFlag::allowDoorsOnTrack)) - { - return false; - } - - *wallAcrossTrack = true; - if (z0 & 1) - { - return false; - } - - int32_t z; - if (sequence == 0) - { - if (ted.sequences[0].flags & TRACK_SEQUENCE_FLAG_DISALLOW_DOORS) + using namespace OpenRCT2::TrackMetaData; + const auto& ted = GetTrackElementDescriptor(trackType); + int32_t sequence = trackElement->GetSequenceIndex(); + int32_t direction = (_edge - trackElement->GetDirection()) & kTileElementDirectionMask; + auto ride = GetRide(trackElement->GetRideIndex()); + if (ride == nullptr) { return false; } - if (ted.definition.rollStart == TrackRoll::None) + if (TrackIsAllowedWallEdges(ride->type, trackType, sequence, direction)) { - if (!(ted.coordinates.rotationBegin & 4)) + return true; + } + + if (!(wall->flags & WALL_SCENERY_IS_DOOR)) + { + return false; + } + + if (!ride->getRideTypeDescriptor().HasFlag(RtdFlag::allowDoorsOnTrack)) + { + return false; + } + + *wallAcrossTrack = true; + if (z0 & 1) + { + return false; + } + + int32_t z; + if (sequence == 0) + { + if (ted.sequences[0].flags & TRACK_SEQUENCE_FLAG_DISALLOW_DOORS) { - direction = DirectionReverse(trackElement->GetDirection()); - if (direction == _edge) + return false; + } + + if (ted.definition.rollStart == TrackRoll::None) + { + if (!(ted.coordinates.rotationBegin & 4)) { - z = ted.coordinates.zBegin; - z = trackElement->BaseHeight + ((z - ted.sequences[sequence].clearance.z) * 8); - if (z == z0) + direction = DirectionReverse(trackElement->GetDirection()); + if (direction == _edge) { - return true; + z = ted.coordinates.zBegin; + z = trackElement->BaseHeight + ((z - ted.sequences[sequence].clearance.z) * 8); + if (z == z0) + { + return true; + } } } } } - } - bool isLastInSequence = (sequence + 1) == ted.numSequences; - if (!isLastInSequence) - { - return false; - } - - if (ted.definition.rollEnd != TrackRoll::None) - { - return false; - } - - direction = ted.coordinates.rotationEnd; - if (direction & 4) - { - return false; - } - - direction = (trackElement->GetDirection() + ted.coordinates.rotationEnd) & kTileElementDirectionMask; - if (direction != _edge) - { - return false; - } - - z = ted.coordinates.zEnd; - z = trackElement->BaseHeight + ((z - ted.sequences[sequence].clearance.z) * kCoordsZStep); - return z == z0; -} - -/** - * - * rct2: 0x006E5C1A - */ -GameActions::Result WallPlaceAction::WallCheckObstruction( - const WallSceneryEntry* wall, int32_t z0, int32_t z1, bool* wallAcrossTrack) const -{ - *wallAcrossTrack = false; - if (MapIsLocationAtEdge(_loc)) - { - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_BUILD_THIS_HERE, STR_OFF_EDGE_OF_MAP); - } - - TileElement* tileElement = MapGetFirstElementAt(_loc); - do - { - if (tileElement == nullptr) - break; - auto elementType = tileElement->GetType(); - if (elementType == TileElementType::Surface) - continue; - if (tileElement->IsGhost()) - continue; - if (z0 >= tileElement->ClearanceHeight) - continue; - if (z1 <= tileElement->BaseHeight) - continue; - if (elementType == TileElementType::Wall) + bool isLastInSequence = (sequence + 1) == ted.numSequences; + if (!isLastInSequence) { - int32_t direction = tileElement->GetDirection(); - if (_edge == direction) - { - auto res = GameActions::Result(GameActions::Status::NoClearance, STR_CANT_BUILD_THIS_HERE, kStringIdNone); - MapGetObstructionErrorText(tileElement, res); - return res; - } - continue; + return false; } - if (tileElement->GetOccupiedQuadrants() == 0) - continue; - auto res = GameActions::Result(GameActions::Status::NoClearance, STR_CANT_BUILD_THIS_HERE, kStringIdNone); - switch (elementType) + + if (ted.definition.rollEnd != TrackRoll::None) { - case TileElementType::Entrance: - MapGetObstructionErrorText(tileElement, res); - return res; - case TileElementType::Path: - if (tileElement->AsPath()->GetEdges() & (1 << _edge)) + return false; + } + + direction = ted.coordinates.rotationEnd; + if (direction & 4) + { + return false; + } + + direction = (trackElement->GetDirection() + ted.coordinates.rotationEnd) & kTileElementDirectionMask; + if (direction != _edge) + { + return false; + } + + z = ted.coordinates.zEnd; + z = trackElement->BaseHeight + ((z - ted.sequences[sequence].clearance.z) * kCoordsZStep); + return z == z0; + } + + /** + * + * rct2: 0x006E5C1A + */ + Result WallPlaceAction::WallCheckObstruction( + const WallSceneryEntry* wall, int32_t z0, int32_t z1, bool* wallAcrossTrack) const + { + *wallAcrossTrack = false; + if (MapIsLocationAtEdge(_loc)) + { + return Result(Status::InvalidParameters, STR_CANT_BUILD_THIS_HERE, STR_OFF_EDGE_OF_MAP); + } + + TileElement* tileElement = MapGetFirstElementAt(_loc); + do + { + if (tileElement == nullptr) + break; + auto elementType = tileElement->GetType(); + if (elementType == TileElementType::Surface) + continue; + if (tileElement->IsGhost()) + continue; + if (z0 >= tileElement->ClearanceHeight) + continue; + if (z1 <= tileElement->BaseHeight) + continue; + if (elementType == TileElementType::Wall) + { + int32_t direction = tileElement->GetDirection(); + if (_edge == direction) { + auto res = Result(Status::NoClearance, STR_CANT_BUILD_THIS_HERE, kStringIdNone); MapGetObstructionErrorText(tileElement, res); return res; } - break; - case TileElementType::LargeScenery: + continue; + } + if (tileElement->GetOccupiedQuadrants() == 0) + continue; + auto res = Result(Status::NoClearance, STR_CANT_BUILD_THIS_HERE, kStringIdNone); + switch (elementType) { - const auto* largeSceneryElement = tileElement->AsLargeScenery(); - const auto* sceneryEntry = largeSceneryElement->GetEntry(); - - // If there is no entry, assume the object is not in the way. - if (sceneryEntry == nullptr) + case TileElementType::Entrance: + MapGetObstructionErrorText(tileElement, res); + return res; + case TileElementType::Path: + if (tileElement->AsPath()->GetEdges() & (1 << _edge)) + { + MapGetObstructionErrorText(tileElement, res); + return res; + } break; - - auto sequence = largeSceneryElement->GetSequenceIndex(); - const LargeSceneryTile& tile = sceneryEntry->tiles[sequence]; - - int32_t direction = ((_edge - tileElement->GetDirection()) & kTileElementDirectionMask); - if (!(tile.walls & (1 << direction))) + case TileElementType::LargeScenery: { - MapGetObstructionErrorText(tileElement, res); - return res; + const auto* largeSceneryElement = tileElement->AsLargeScenery(); + const auto* sceneryEntry = largeSceneryElement->GetEntry(); + + // If there is no entry, assume the object is not in the way. + if (sceneryEntry == nullptr) + break; + + auto sequence = largeSceneryElement->GetSequenceIndex(); + const LargeSceneryTile& tile = sceneryEntry->tiles[sequence]; + + int32_t direction = ((_edge - tileElement->GetDirection()) & kTileElementDirectionMask); + if (!(tile.walls & (1 << direction))) + { + MapGetObstructionErrorText(tileElement, res); + return res; + } + break; } - break; + case TileElementType::SmallScenery: + { + auto sceneryEntry = tileElement->AsSmallScenery()->GetEntry(); + if (sceneryEntry != nullptr && sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_NO_WALLS)) + { + MapGetObstructionErrorText(tileElement, res); + return res; + } + break; + } + case TileElementType::Track: + if (!WallCheckObstructionWithTrack(wall, z0, tileElement->AsTrack(), wallAcrossTrack)) + { + MapGetObstructionErrorText(tileElement, res); + return res; + } + break; + default: + break; } - case TileElementType::SmallScenery: - { - auto sceneryEntry = tileElement->AsSmallScenery()->GetEntry(); - if (sceneryEntry != nullptr && sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_NO_WALLS)) - { - MapGetObstructionErrorText(tileElement, res); - return res; - } - break; - } - case TileElementType::Track: - if (!WallCheckObstructionWithTrack(wall, z0, tileElement->AsTrack(), wallAcrossTrack)) - { - MapGetObstructionErrorText(tileElement, res); - return res; - } - break; - default: - break; - } - } while (!(tileElement++)->IsLastForTile()); + } while (!(tileElement++)->IsLastForTile()); - return GameActions::Result(); -} - -bool WallPlaceAction::TrackIsAllowedWallEdges( - ride_type_t rideType, OpenRCT2::TrackElemType trackType, uint8_t trackSequence, uint8_t direction) -{ - if (!GetRideTypeDescriptor(rideType).HasFlag(RtdFlag::noWallsAroundTrack)) - { - const auto& ted = GetTrackElementDescriptor(trackType); - if (ted.sequences[trackSequence].allowedWallEdges & (1 << direction)) - { - return true; - } + return Result(); } - return false; -} + + bool WallPlaceAction::TrackIsAllowedWallEdges( + ride_type_t rideType, OpenRCT2::TrackElemType trackType, uint8_t trackSequence, uint8_t direction) + { + if (!GetRideTypeDescriptor(rideType).HasFlag(RtdFlag::noWallsAroundTrack)) + { + const auto& ted = GetTrackElementDescriptor(trackType); + if (ted.sequences[trackSequence].allowedWallEdges & (1 << direction)) + { + return true; + } + } + return false; + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/WallPlaceAction.h b/src/openrct2/actions/WallPlaceAction.h index 9e23ce7c24..19a2ab1d4e 100644 --- a/src/openrct2/actions/WallPlaceAction.h +++ b/src/openrct2/actions/WallPlaceAction.h @@ -20,54 +20,56 @@ namespace OpenRCT2 struct WallSceneryEntry; } -struct WallPlaceActionResult +namespace OpenRCT2::GameActions { - int32_t BaseHeight{}; - BannerIndex BannerId = BannerIndex::GetNull(); -}; + struct WallPlaceActionResult + { + int32_t BaseHeight{}; + BannerIndex BannerId = BannerIndex::GetNull(); + }; -class WallPlaceAction final : public GameActionBase -{ -private: - OpenRCT2::ObjectEntryIndex _wallType{ OpenRCT2::kObjectEntryIndexNull }; - CoordsXYZ _loc; - Direction _edge{ kInvalidDirection }; - int32_t _primaryColour{ COLOUR_BLACK }; - int32_t _secondaryColour{ COLOUR_BLACK }; - int32_t _tertiaryColour{ COLOUR_BLACK }; + class WallPlaceAction final : public GameActionBase + { + private: + ObjectEntryIndex _wallType{ kObjectEntryIndexNull }; + CoordsXYZ _loc; + Direction _edge{ kInvalidDirection }; + int32_t _primaryColour{ COLOUR_BLACK }; + int32_t _secondaryColour{ COLOUR_BLACK }; + int32_t _tertiaryColour{ COLOUR_BLACK }; -public: - WallPlaceAction() = default; - WallPlaceAction( - OpenRCT2::ObjectEntryIndex wallType, const CoordsXYZ& loc, uint8_t edge, int32_t primaryColour, int32_t secondaryColour, - int32_t tertiaryColour); + public: + WallPlaceAction() = default; + WallPlaceAction( + ObjectEntryIndex wallType, const CoordsXYZ& loc, uint8_t edge, int32_t primaryColour, int32_t secondaryColour, + int32_t tertiaryColour); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override final; + uint16_t GetActionFlags() const override final; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; -private: - /** - * - * rct2: 0x006E5CBA - */ - bool WallCheckObstructionWithTrack( - const WallSceneryEntry* wall, int32_t z0, TrackElement* trackElement, bool* wallAcrossTrack) const; - /** - * - * rct2: 0x006E5C1A - */ - OpenRCT2::GameActions::Result WallCheckObstruction( - const WallSceneryEntry* wall, int32_t z0, int32_t z1, bool* wallAcrossTrack) const; + private: + /** + * + * rct2: 0x006E5CBA + */ + bool WallCheckObstructionWithTrack( + const WallSceneryEntry* wall, int32_t z0, TrackElement* trackElement, bool* wallAcrossTrack) const; + /** + * + * rct2: 0x006E5C1A + */ + Result WallCheckObstruction(const WallSceneryEntry* wall, int32_t z0, int32_t z1, bool* wallAcrossTrack) const; - /** - * Gets whether the given track type can have a wall placed on the edge of the given direction. - * Some thin tracks for example are allowed to have walls either side of the track, but wider tracks can not. - */ - static bool TrackIsAllowedWallEdges( - ride_type_t rideType, OpenRCT2::TrackElemType trackType, uint8_t trackSequence, uint8_t direction); -}; + /** + * Gets whether the given track type can have a wall placed on the edge of the given direction. + * Some thin tracks for example are allowed to have walls either side of the track, but wider tracks can not. + */ + static bool TrackIsAllowedWallEdges( + ride_type_t rideType, OpenRCT2::TrackElemType trackType, uint8_t trackSequence, uint8_t direction); + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/WallRemoveAction.cpp b/src/openrct2/actions/WallRemoveAction.cpp index a5f911319d..323e5ed467 100644 --- a/src/openrct2/actions/WallRemoveAction.cpp +++ b/src/openrct2/actions/WallRemoveAction.cpp @@ -19,92 +19,91 @@ #include "../world/TileElementsView.h" #include "../world/tile_element/WallElement.h" -using namespace OpenRCT2; - -WallRemoveAction::WallRemoveAction(const CoordsXYZD& loc) - : _loc(loc) +namespace OpenRCT2::GameActions { -} - -void WallRemoveAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit(_loc); -} - -void WallRemoveAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_loc); -} - -GameActions::Result WallRemoveAction::Query() const -{ - GameActions::Result res = GameActions::Result(); - res.Cost = 0; - res.Expenditure = ExpenditureType::landscaping; - - if (!LocationValid(_loc)) + WallRemoveAction::WallRemoveAction(const CoordsXYZD& loc) + : _loc(loc) { - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_REMOVE_THIS, STR_OFF_EDGE_OF_MAP); } - const bool isGhost = GetFlags() & GAME_COMMAND_FLAG_GHOST; - if (!isGhost && gLegacyScene != LegacyScene::scenarioEditor && !getGameState().cheats.sandboxMode - && !MapIsLocationOwned(_loc)) + void WallRemoveAction::AcceptParameters(GameActionParameterVisitor& visitor) { - return GameActions::Result(GameActions::Status::NotOwned, STR_CANT_REMOVE_THIS, STR_LAND_NOT_OWNED_BY_PARK); + visitor.Visit(_loc); } - TileElement* wallElement = GetFirstWallElementAt(_loc, isGhost); - if (wallElement == nullptr) + void WallRemoveAction::Serialise(DataSerialiser& stream) { - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_REMOVE_THIS, STR_INVALID_SELECTION_OF_OBJECTS); + GameAction::Serialise(stream); + + stream << DS_TAG(_loc); } - res.Cost = 0; - return res; -} - -GameActions::Result WallRemoveAction::Execute() const -{ - GameActions::Result res = GameActions::Result(); - res.Cost = 0; - res.Expenditure = ExpenditureType::landscaping; - - const bool isGhost = GetFlags() & GAME_COMMAND_FLAG_GHOST; - - TileElement* wallElement = GetFirstWallElementAt(_loc, isGhost); - if (wallElement == nullptr) + Result WallRemoveAction::Query() const { - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_REMOVE_THIS, STR_INVALID_SELECTION_OF_OBJECTS); + Result res = Result(); + res.Cost = 0; + res.Expenditure = ExpenditureType::landscaping; + + if (!LocationValid(_loc)) + { + return Result(Status::InvalidParameters, STR_CANT_REMOVE_THIS, STR_OFF_EDGE_OF_MAP); + } + + const bool isGhost = GetFlags() & GAME_COMMAND_FLAG_GHOST; + if (!isGhost && gLegacyScene != LegacyScene::scenarioEditor && !getGameState().cheats.sandboxMode + && !MapIsLocationOwned(_loc)) + { + return Result(Status::NotOwned, STR_CANT_REMOVE_THIS, STR_LAND_NOT_OWNED_BY_PARK); + } + + TileElement* wallElement = GetFirstWallElementAt(_loc, isGhost); + if (wallElement == nullptr) + { + return Result(Status::InvalidParameters, STR_CANT_REMOVE_THIS, STR_INVALID_SELECTION_OF_OBJECTS); + } + + res.Cost = 0; + return res; } - res.Position.x = _loc.x + 16; - res.Position.y = _loc.y + 16; - res.Position.z = _loc.z; - - wallElement->RemoveBannerEntry(); - MapInvalidateTileZoom1({ _loc, wallElement->GetBaseZ(), (wallElement->GetBaseZ()) + 72 }); - TileElementRemove(wallElement); - - return res; -} - -TileElement* WallRemoveAction::GetFirstWallElementAt(const CoordsXYZD& location, bool isGhost) const -{ - for (auto* wallElement : TileElementsView(location)) + Result WallRemoveAction::Execute() const { - if (wallElement->GetBaseZ() != location.z) - continue; - if (wallElement->GetDirection() != location.direction) - continue; - if (wallElement->IsGhost() != isGhost) - continue; + Result res = Result(); + res.Cost = 0; + res.Expenditure = ExpenditureType::landscaping; - return wallElement->as(); + const bool isGhost = GetFlags() & GAME_COMMAND_FLAG_GHOST; + + TileElement* wallElement = GetFirstWallElementAt(_loc, isGhost); + if (wallElement == nullptr) + { + return Result(Status::InvalidParameters, STR_CANT_REMOVE_THIS, STR_INVALID_SELECTION_OF_OBJECTS); + } + + res.Position.x = _loc.x + 16; + res.Position.y = _loc.y + 16; + res.Position.z = _loc.z; + + wallElement->RemoveBannerEntry(); + MapInvalidateTileZoom1({ _loc, wallElement->GetBaseZ(), (wallElement->GetBaseZ()) + 72 }); + TileElementRemove(wallElement); + + return res; } - return nullptr; -} + + TileElement* WallRemoveAction::GetFirstWallElementAt(const CoordsXYZD& location, bool isGhost) const + { + for (auto* wallElement : TileElementsView(location)) + { + if (wallElement->GetBaseZ() != location.z) + continue; + if (wallElement->GetDirection() != location.direction) + continue; + if (wallElement->IsGhost() != isGhost) + continue; + + return wallElement->as(); + } + return nullptr; + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/WallRemoveAction.h b/src/openrct2/actions/WallRemoveAction.h index 2fb39e0628..6ac00ca752 100644 --- a/src/openrct2/actions/WallRemoveAction.h +++ b/src/openrct2/actions/WallRemoveAction.h @@ -11,20 +11,23 @@ #include "GameAction.h" -class WallRemoveAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - CoordsXYZD _loc; + class WallRemoveAction final : public GameActionBase + { + private: + CoordsXYZD _loc; -public: - WallRemoveAction() = default; - WallRemoveAction(const CoordsXYZD& loc); + public: + WallRemoveAction() = default; + WallRemoveAction(const CoordsXYZD& loc); - void AcceptParameters(GameActionParameterVisitor& visitor) override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; -private: - OpenRCT2::TileElement* GetFirstWallElementAt(const CoordsXYZD& location, bool isGhost) const; -}; + private: + TileElement* GetFirstWallElementAt(const CoordsXYZD& location, bool isGhost) const; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/WallSetColourAction.cpp b/src/openrct2/actions/WallSetColourAction.cpp index fe5808004c..754de2971f 100644 --- a/src/openrct2/actions/WallSetColourAction.cpp +++ b/src/openrct2/actions/WallSetColourAction.cpp @@ -20,140 +20,142 @@ #include "../world/Scenery.h" #include "../world/tile_element/WallElement.h" -using namespace OpenRCT2; - -WallSetColourAction::WallSetColourAction( - const CoordsXYZD& loc, int32_t primaryColour, int32_t secondaryColour, int32_t tertiaryColour) - : _loc(loc) - , _primaryColour(primaryColour) - , _secondaryColour(secondaryColour) - , _tertiaryColour(tertiaryColour) +namespace OpenRCT2::GameActions { -} - -void WallSetColourAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit(_loc); - visitor.Visit("primaryColour", _primaryColour); - visitor.Visit("secondaryColour", _secondaryColour); - visitor.Visit("tertiaryColour", _tertiaryColour); -} - -uint16_t WallSetColourAction::GetActionFlags() const -{ - return GameAction::GetActionFlags() | GameActions::Flags::AllowWhilePaused; -} - -void WallSetColourAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_loc) << DS_TAG(_primaryColour) << DS_TAG(_secondaryColour) << DS_TAG(_tertiaryColour); -} - -GameActions::Result WallSetColourAction::Query() const -{ - auto res = GameActions::Result(); - res.ErrorTitle = STR_CANT_REPAINT_THIS; - res.Position.x = _loc.x + 16; - res.Position.y = _loc.y + 16; - res.Position.z = _loc.z; - - res.Expenditure = ExpenditureType::landscaping; - - if (!LocationValid(_loc)) + WallSetColourAction::WallSetColourAction( + const CoordsXYZD& loc, int32_t primaryColour, int32_t secondaryColour, int32_t tertiaryColour) + : _loc(loc) + , _primaryColour(primaryColour) + , _secondaryColour(secondaryColour) + , _tertiaryColour(tertiaryColour) { - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_REPAINT_THIS, STR_OFF_EDGE_OF_MAP); } - if (gLegacyScene != LegacyScene::scenarioEditor && !MapIsLocationInPark(_loc) && !getGameState().cheats.sandboxMode) + void WallSetColourAction::AcceptParameters(GameActionParameterVisitor& visitor) { - return GameActions::Result(GameActions::Status::NotOwned, STR_CANT_REPAINT_THIS, STR_LAND_NOT_OWNED_BY_PARK); + visitor.Visit(_loc); + visitor.Visit("primaryColour", _primaryColour); + visitor.Visit("secondaryColour", _secondaryColour); + visitor.Visit("tertiaryColour", _tertiaryColour); } - auto wallElement = MapGetWallElementAt(_loc); - if (wallElement == nullptr) + uint16_t WallSetColourAction::GetActionFlags() const { - LOG_ERROR( - "Could not find wall element at: x = %d, y = %d, z = %d, direction = %u", _loc.x, _loc.y, _loc.z, _loc.direction); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_CANT_REPAINT_THIS, STR_ERR_WALL_ELEMENT_NOT_FOUND); + return GameAction::GetActionFlags() | Flags::AllowWhilePaused; } - if ((GetFlags() & GAME_COMMAND_FLAG_GHOST) && !(wallElement->IsGhost())) + void WallSetColourAction::Serialise(DataSerialiser& stream) { - return res; + GameAction::Serialise(stream); + + stream << DS_TAG(_loc) << DS_TAG(_primaryColour) << DS_TAG(_secondaryColour) << DS_TAG(_tertiaryColour); } - auto* wallEntry = wallElement->GetEntry(); - if (wallEntry == nullptr) + Result WallSetColourAction::Query() const { - LOG_ERROR( - "Wall element does not have wall entry at x = %d, y = %d, z = %d, direction = %u", _loc.x, _loc.y, _loc.z, - _loc.direction); - return GameActions::Result(GameActions::Status::Unknown, STR_CANT_REPAINT_THIS, kStringIdNone); - } + auto res = Result(); + res.ErrorTitle = STR_CANT_REPAINT_THIS; + res.Position.x = _loc.x + 16; + res.Position.y = _loc.y + 16; + res.Position.z = _loc.z; - if (_primaryColour >= COLOUR_COUNT) - { - LOG_ERROR("Primary colour invalid: colour = %d", _primaryColour); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_REPAINT_THIS, STR_ERR_INVALID_COLOUR); - } - else if (_secondaryColour >= COLOUR_COUNT) - { - LOG_ERROR("Secondary colour invalid: colour = %d", _secondaryColour); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_REPAINT_THIS, STR_ERR_INVALID_COLOUR); - } - else if (wallEntry->flags & WALL_SCENERY_HAS_TERTIARY_COLOUR) - { - if (_tertiaryColour >= COLOUR_COUNT) + res.Expenditure = ExpenditureType::landscaping; + + if (!LocationValid(_loc)) { - LOG_ERROR("Tertiary colour invalid: colour = %d", _tertiaryColour); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_REPAINT_THIS, kStringIdNone); + return Result(Status::InvalidParameters, STR_CANT_REPAINT_THIS, STR_OFF_EDGE_OF_MAP); } - } - return res; -} -GameActions::Result WallSetColourAction::Execute() const -{ - auto res = GameActions::Result(); - res.ErrorTitle = STR_CANT_REPAINT_THIS; - res.Position.x = _loc.x + 16; - res.Position.y = _loc.y + 16; - res.Position.z = _loc.z; - res.Expenditure = ExpenditureType::landscaping; + if (gLegacyScene != LegacyScene::scenarioEditor && !MapIsLocationInPark(_loc) && !getGameState().cheats.sandboxMode) + { + return Result(Status::NotOwned, STR_CANT_REPAINT_THIS, STR_LAND_NOT_OWNED_BY_PARK); + } - auto wallElement = MapGetWallElementAt(_loc); - if (wallElement == nullptr) - { - LOG_ERROR( - "Could not find wall element at: x = %d, y = %d, z = %d, direction = %u", _loc.x, _loc.y, _loc.z, _loc.direction); - return GameActions::Result(GameActions::Status::InvalidParameters, STR_CANT_REPAINT_THIS, kStringIdNone); - } + auto wallElement = MapGetWallElementAt(_loc); + if (wallElement == nullptr) + { + LOG_ERROR( + "Could not find wall element at: x = %d, y = %d, z = %d, direction = %u", _loc.x, _loc.y, _loc.z, + _loc.direction); + return Result(Status::InvalidParameters, STR_CANT_REPAINT_THIS, STR_ERR_WALL_ELEMENT_NOT_FOUND); + } - if ((GetFlags() & GAME_COMMAND_FLAG_GHOST) && !(wallElement->IsGhost())) - { + if ((GetFlags() & GAME_COMMAND_FLAG_GHOST) && !(wallElement->IsGhost())) + { + return res; + } + + auto* wallEntry = wallElement->GetEntry(); + if (wallEntry == nullptr) + { + LOG_ERROR( + "Wall element does not have wall entry at x = %d, y = %d, z = %d, direction = %u", _loc.x, _loc.y, _loc.z, + _loc.direction); + return Result(Status::Unknown, STR_CANT_REPAINT_THIS, kStringIdNone); + } + + if (_primaryColour >= COLOUR_COUNT) + { + LOG_ERROR("Primary colour invalid: colour = %d", _primaryColour); + return Result(Status::InvalidParameters, STR_CANT_REPAINT_THIS, STR_ERR_INVALID_COLOUR); + } + else if (_secondaryColour >= COLOUR_COUNT) + { + LOG_ERROR("Secondary colour invalid: colour = %d", _secondaryColour); + return Result(Status::InvalidParameters, STR_CANT_REPAINT_THIS, STR_ERR_INVALID_COLOUR); + } + else if (wallEntry->flags & WALL_SCENERY_HAS_TERTIARY_COLOUR) + { + if (_tertiaryColour >= COLOUR_COUNT) + { + LOG_ERROR("Tertiary colour invalid: colour = %d", _tertiaryColour); + return Result(Status::InvalidParameters, STR_CANT_REPAINT_THIS, kStringIdNone); + } + } return res; } - auto* wallEntry = wallElement->GetEntry(); - if (wallEntry == nullptr) + Result WallSetColourAction::Execute() const { - LOG_ERROR( - "Wall element does not have wall entry at x = %d, y = %d, z = %d, direction = %u", _loc.x, _loc.y, _loc.z, - _loc.direction); - return GameActions::Result(GameActions::Status::Unknown, STR_CANT_REPAINT_THIS, kStringIdNone); + auto res = Result(); + res.ErrorTitle = STR_CANT_REPAINT_THIS; + res.Position.x = _loc.x + 16; + res.Position.y = _loc.y + 16; + res.Position.z = _loc.z; + res.Expenditure = ExpenditureType::landscaping; + + auto wallElement = MapGetWallElementAt(_loc); + if (wallElement == nullptr) + { + LOG_ERROR( + "Could not find wall element at: x = %d, y = %d, z = %d, direction = %u", _loc.x, _loc.y, _loc.z, + _loc.direction); + return Result(Status::InvalidParameters, STR_CANT_REPAINT_THIS, kStringIdNone); + } + + if ((GetFlags() & GAME_COMMAND_FLAG_GHOST) && !(wallElement->IsGhost())) + { + return res; + } + + auto* wallEntry = wallElement->GetEntry(); + if (wallEntry == nullptr) + { + LOG_ERROR( + "Wall element does not have wall entry at x = %d, y = %d, z = %d, direction = %u", _loc.x, _loc.y, _loc.z, + _loc.direction); + return Result(Status::Unknown, STR_CANT_REPAINT_THIS, kStringIdNone); + } + + wallElement->SetPrimaryColour(_primaryColour); + wallElement->SetSecondaryColour(_secondaryColour); + + if (wallEntry->flags & WALL_SCENERY_HAS_TERTIARY_COLOUR) + { + wallElement->SetTertiaryColour(_tertiaryColour); + } + MapInvalidateTileZoom1({ _loc, _loc.z, _loc.z + 72 }); + + return res; } - - wallElement->SetPrimaryColour(_primaryColour); - wallElement->SetSecondaryColour(_secondaryColour); - - if (wallEntry->flags & WALL_SCENERY_HAS_TERTIARY_COLOUR) - { - wallElement->SetTertiaryColour(_tertiaryColour); - } - MapInvalidateTileZoom1({ _loc, _loc.z, _loc.z + 72 }); - - return res; -} +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/WallSetColourAction.h b/src/openrct2/actions/WallSetColourAction.h index d44ceb5b2c..89259d4137 100644 --- a/src/openrct2/actions/WallSetColourAction.h +++ b/src/openrct2/actions/WallSetColourAction.h @@ -11,23 +11,26 @@ #include "GameAction.h" -class WallSetColourAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - CoordsXYZD _loc; - int32_t _primaryColour{}; - int32_t _secondaryColour{}; - int32_t _tertiaryColour{}; + class WallSetColourAction final : public GameActionBase + { + private: + CoordsXYZD _loc; + int32_t _primaryColour{}; + int32_t _secondaryColour{}; + int32_t _tertiaryColour{}; -public: - WallSetColourAction() = default; - WallSetColourAction(const CoordsXYZD& loc, int32_t primaryColour, int32_t secondaryColour, int32_t tertiaryColour); + public: + WallSetColourAction() = default; + WallSetColourAction(const CoordsXYZD& loc, int32_t primaryColour, int32_t secondaryColour, int32_t tertiaryColour); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; -}; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/WaterLowerAction.cpp b/src/openrct2/actions/WaterLowerAction.cpp index 96809000fb..80b2a27fe0 100644 --- a/src/openrct2/actions/WaterLowerAction.cpp +++ b/src/openrct2/actions/WaterLowerAction.cpp @@ -16,151 +16,150 @@ #include "../world/tile_element/SurfaceElement.h" #include "WaterSetHeightAction.h" -using namespace OpenRCT2; - -WaterLowerAction::WaterLowerAction(MapRange range) - : _range(range) +namespace OpenRCT2::GameActions { -} - -void WaterLowerAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit(_range); -} - -uint16_t WaterLowerAction::GetActionFlags() const -{ - return GameAction::GetActionFlags(); -} - -void WaterLowerAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_range); -} - -GameActions::Result WaterLowerAction::Query() const -{ - return QueryExecute(false); -} - -GameActions::Result WaterLowerAction::Execute() const -{ - return QueryExecute(true); -} - -GameActions::Result WaterLowerAction::QueryExecute(bool isExecuting) const -{ - auto res = GameActions::Result(); - - auto validRange = ClampRangeWithinMap(_range); - res.Position.x = ((validRange.GetLeft() + validRange.GetRight()) / 2) + 16; - res.Position.y = ((validRange.GetTop() + validRange.GetBottom()) / 2) + 16; - int16_t z = TileElementHeight(res.Position); - int16_t waterHeight = TileElementWaterHeight(res.Position); - if (waterHeight != 0) + WaterLowerAction::WaterLowerAction(MapRange range) + : _range(range) { - z = waterHeight; } - res.Position.z = z; - res.Expenditure = ExpenditureType::landscaping; - uint8_t minHeight = GetLowestHeight(validRange); - bool hasChanged = false; - bool withinOwnership = false; - for (int32_t y = validRange.GetTop(); y <= validRange.GetBottom(); y += kCoordsXYStep) + void WaterLowerAction::AcceptParameters(GameActionParameterVisitor& visitor) { - for (int32_t x = validRange.GetLeft(); x <= validRange.GetRight(); x += kCoordsXYStep) + visitor.Visit(_range); + } + + uint16_t WaterLowerAction::GetActionFlags() const + { + return GameAction::GetActionFlags(); + } + + void WaterLowerAction::Serialise(DataSerialiser& stream) + { + GameAction::Serialise(stream); + + stream << DS_TAG(_range); + } + + Result WaterLowerAction::Query() const + { + return QueryExecute(false); + } + + Result WaterLowerAction::Execute() const + { + return QueryExecute(true); + } + + Result WaterLowerAction::QueryExecute(bool isExecuting) const + { + auto res = Result(); + + auto validRange = ClampRangeWithinMap(_range); + res.Position.x = ((validRange.GetLeft() + validRange.GetRight()) / 2) + 16; + res.Position.y = ((validRange.GetTop() + validRange.GetBottom()) / 2) + 16; + int16_t z = TileElementHeight(res.Position); + int16_t waterHeight = TileElementWaterHeight(res.Position); + if (waterHeight != 0) { - if (!LocationValid({ x, y })) - continue; + z = waterHeight; + } + res.Position.z = z; + res.Expenditure = ExpenditureType::landscaping; - auto* surfaceElement = MapGetSurfaceElementAt(CoordsXY{ x, y }); - if (surfaceElement == nullptr) - continue; - - if (gLegacyScene != LegacyScene::scenarioEditor && !getGameState().cheats.sandboxMode) + uint8_t minHeight = GetLowestHeight(validRange); + bool hasChanged = false; + bool withinOwnership = false; + for (int32_t y = validRange.GetTop(); y <= validRange.GetBottom(); y += kCoordsXYStep) + { + for (int32_t x = validRange.GetLeft(); x <= validRange.GetRight(); x += kCoordsXYStep) { - if (!MapIsLocationInPark(CoordsXY{ x, y })) - { + if (!LocationValid({ x, y })) continue; + + auto* surfaceElement = MapGetSurfaceElementAt(CoordsXY{ x, y }); + if (surfaceElement == nullptr) + continue; + + if (gLegacyScene != LegacyScene::scenarioEditor && !getGameState().cheats.sandboxMode) + { + if (!MapIsLocationInPark(CoordsXY{ x, y })) + { + continue; + } + } + withinOwnership = true; + + uint8_t height = surfaceElement->GetWaterHeight() / kCoordsZStep; + if (height == 0) + continue; + + if (height < minHeight) + continue; + + height -= 2; + auto waterSetHeightAction = WaterSetHeightAction({ x, y }, height); + waterSetHeightAction.SetFlags(GetFlags()); + auto result = isExecuting ? ExecuteNested(&waterSetHeightAction) : QueryNested(&waterSetHeightAction); + if (result.Error == Status::Ok) + { + res.Cost += result.Cost; + hasChanged = true; + } + else + { + result.ErrorTitle = STR_CANT_LOWER_WATER_LEVEL_HERE; + return result; } } - withinOwnership = true; - - uint8_t height = surfaceElement->GetWaterHeight() / kCoordsZStep; - if (height == 0) - continue; - - if (height < minHeight) - continue; - - height -= 2; - auto waterSetHeightAction = WaterSetHeightAction({ x, y }, height); - waterSetHeightAction.SetFlags(GetFlags()); - auto result = isExecuting ? GameActions::ExecuteNested(&waterSetHeightAction) - : GameActions::QueryNested(&waterSetHeightAction); - if (result.Error == GameActions::Status::Ok) - { - res.Cost += result.Cost; - hasChanged = true; - } - else - { - result.ErrorTitle = STR_CANT_LOWER_WATER_LEVEL_HERE; - return result; - } } - } - if (!withinOwnership) - { - return GameActions::Result( - GameActions::Status::Disallowed, STR_CANT_LOWER_WATER_LEVEL_HERE, STR_LAND_NOT_OWNED_BY_PARK); - ; - } - - if (isExecuting && hasChanged) - { - Audio::Play3D(Audio::SoundId::LayingOutWater, res.Position); - } - // Force ride construction to recheck area - _currentTrackSelectionFlags.set(TrackSelectionFlag::recheck); - - return res; -} - -uint8_t WaterLowerAction::GetLowestHeight(const MapRange& validRange) const -{ - // The lowest height to lower the water to is the highest water level in the selection - uint8_t minHeight{ 0 }; - for (int32_t y = validRange.GetTop(); y <= validRange.GetBottom(); y += kCoordsXYStep) - { - for (int32_t x = validRange.GetLeft(); x <= validRange.GetRight(); x += kCoordsXYStep) + if (!withinOwnership) { - if (gLegacyScene != LegacyScene::scenarioEditor && !getGameState().cheats.sandboxMode) + return Result(Status::Disallowed, STR_CANT_LOWER_WATER_LEVEL_HERE, STR_LAND_NOT_OWNED_BY_PARK); + ; + } + + if (isExecuting && hasChanged) + { + Audio::Play3D(Audio::SoundId::LayingOutWater, res.Position); + } + // Force ride construction to recheck area + _currentTrackSelectionFlags.set(TrackSelectionFlag::recheck); + + return res; + } + + uint8_t WaterLowerAction::GetLowestHeight(const MapRange& validRange) const + { + // The lowest height to lower the water to is the highest water level in the selection + uint8_t minHeight{ 0 }; + for (int32_t y = validRange.GetTop(); y <= validRange.GetBottom(); y += kCoordsXYStep) + { + for (int32_t x = validRange.GetLeft(); x <= validRange.GetRight(); x += kCoordsXYStep) { - if (!MapIsLocationInPark(CoordsXY{ x, y })) + if (gLegacyScene != LegacyScene::scenarioEditor && !getGameState().cheats.sandboxMode) { + if (!MapIsLocationInPark(CoordsXY{ x, y })) + { + continue; + } + } + + auto* surfaceElement = MapGetSurfaceElementAt(CoordsXY{ x, y }); + if (surfaceElement == nullptr) continue; + + uint8_t height = surfaceElement->GetWaterHeight() / kCoordsZStep; + if (height == 0) + continue; + + if (height > minHeight) + { + minHeight = height; } } - - auto* surfaceElement = MapGetSurfaceElementAt(CoordsXY{ x, y }); - if (surfaceElement == nullptr) - continue; - - uint8_t height = surfaceElement->GetWaterHeight() / kCoordsZStep; - if (height == 0) - continue; - - if (height > minHeight) - { - minHeight = height; - } } - } - return minHeight; -} + return minHeight; + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/WaterLowerAction.h b/src/openrct2/actions/WaterLowerAction.h index f74beb82f1..6820d602f8 100644 --- a/src/openrct2/actions/WaterLowerAction.h +++ b/src/openrct2/actions/WaterLowerAction.h @@ -11,24 +11,27 @@ #include "GameAction.h" -class WaterLowerAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - MapRange _range; + class WaterLowerAction final : public GameActionBase + { + private: + MapRange _range; -public: - WaterLowerAction() = default; - WaterLowerAction(MapRange range); + public: + WaterLowerAction() = default; + WaterLowerAction(MapRange range); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; -private: - OpenRCT2::GameActions::Result QueryExecute(bool isExecuting) const; - uint8_t GetLowestHeight(const MapRange& validRange) const; -}; + private: + Result QueryExecute(bool isExecuting) const; + uint8_t GetLowestHeight(const MapRange& validRange) const; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/WaterRaiseAction.cpp b/src/openrct2/actions/WaterRaiseAction.cpp index 80de805495..edf8e6814e 100644 --- a/src/openrct2/actions/WaterRaiseAction.cpp +++ b/src/openrct2/actions/WaterRaiseAction.cpp @@ -16,166 +16,165 @@ #include "../world/tile_element/SurfaceElement.h" #include "WaterSetHeightAction.h" -using namespace OpenRCT2; - -WaterRaiseAction::WaterRaiseAction(MapRange range) - : _range(range) +namespace OpenRCT2::GameActions { -} - -void WaterRaiseAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit(_range); -} - -uint16_t WaterRaiseAction::GetActionFlags() const -{ - return GameAction::GetActionFlags(); -} - -void WaterRaiseAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_range); -} - -GameActions::Result WaterRaiseAction::Query() const -{ - return QueryExecute(false); -} - -GameActions::Result WaterRaiseAction::Execute() const -{ - return QueryExecute(true); -} - -GameActions::Result WaterRaiseAction::QueryExecute(bool isExecuting) const -{ - auto res = GameActions::Result(); - - auto validRange = ClampRangeWithinMap(_range); - res.Position.x = ((validRange.GetLeft() + validRange.GetRight()) / 2) + 16; - res.Position.y = ((validRange.GetTop() + validRange.GetBottom()) / 2) + 16; - int32_t z = TileElementHeight(res.Position); - int16_t waterHeight = TileElementWaterHeight(res.Position); - if (waterHeight != 0) + WaterRaiseAction::WaterRaiseAction(MapRange range) + : _range(range) { - z = waterHeight; } - res.Position.z = z; - res.Expenditure = ExpenditureType::landscaping; - auto maxHeight = GetHighestHeight(validRange) / kCoordsZStep; - bool hasChanged = false; - bool withinOwnership = false; - for (int32_t y = validRange.GetTop(); y <= validRange.GetBottom(); y += kCoordsXYStep) + void WaterRaiseAction::AcceptParameters(GameActionParameterVisitor& visitor) { - for (int32_t x = validRange.GetLeft(); x <= validRange.GetRight(); x += kCoordsXYStep) + visitor.Visit(_range); + } + + uint16_t WaterRaiseAction::GetActionFlags() const + { + return GameAction::GetActionFlags(); + } + + void WaterRaiseAction::Serialise(DataSerialiser& stream) + { + GameAction::Serialise(stream); + + stream << DS_TAG(_range); + } + + Result WaterRaiseAction::Query() const + { + return QueryExecute(false); + } + + Result WaterRaiseAction::Execute() const + { + return QueryExecute(true); + } + + Result WaterRaiseAction::QueryExecute(bool isExecuting) const + { + auto res = Result(); + + auto validRange = ClampRangeWithinMap(_range); + res.Position.x = ((validRange.GetLeft() + validRange.GetRight()) / 2) + 16; + res.Position.y = ((validRange.GetTop() + validRange.GetBottom()) / 2) + 16; + int32_t z = TileElementHeight(res.Position); + int16_t waterHeight = TileElementWaterHeight(res.Position); + if (waterHeight != 0) { - if (!LocationValid({ x, y })) - continue; + z = waterHeight; + } + res.Position.z = z; + res.Expenditure = ExpenditureType::landscaping; - auto surfaceElement = MapGetSurfaceElementAt(CoordsXY{ x, y }); - if (surfaceElement == nullptr) - continue; - - if (gLegacyScene != LegacyScene::scenarioEditor && !getGameState().cheats.sandboxMode) + auto maxHeight = GetHighestHeight(validRange) / kCoordsZStep; + bool hasChanged = false; + bool withinOwnership = false; + for (int32_t y = validRange.GetTop(); y <= validRange.GetBottom(); y += kCoordsXYStep) + { + for (int32_t x = validRange.GetLeft(); x <= validRange.GetRight(); x += kCoordsXYStep) { - if (!MapIsLocationInPark(CoordsXY{ x, y })) - { + if (!LocationValid({ x, y })) continue; + + auto surfaceElement = MapGetSurfaceElementAt(CoordsXY{ x, y }); + if (surfaceElement == nullptr) + continue; + + if (gLegacyScene != LegacyScene::scenarioEditor && !getGameState().cheats.sandboxMode) + { + if (!MapIsLocationInPark(CoordsXY{ x, y })) + { + continue; + } } - } - withinOwnership = true; + withinOwnership = true; - uint8_t height = surfaceElement->GetWaterHeight() / kCoordsZStep; + uint8_t height = surfaceElement->GetWaterHeight() / kCoordsZStep; - if (surfaceElement->BaseHeight > maxHeight) - continue; - - if (height != 0) - { - if (height > maxHeight) + if (surfaceElement->BaseHeight > maxHeight) continue; - if (height + 2 > UINT8_MAX) + + if (height != 0) { - height = UINT8_MAX; + if (height > maxHeight) + continue; + if (height + 2 > UINT8_MAX) + { + height = UINT8_MAX; + } + else + { + height += 2; + } } else { - height += 2; + height = surfaceElement->BaseHeight + 2; } - } - else - { - height = surfaceElement->BaseHeight + 2; - } - auto waterSetHeightAction = WaterSetHeightAction({ x, y }, height); - waterSetHeightAction.SetFlags(GetFlags()); - auto result = isExecuting ? GameActions::ExecuteNested(&waterSetHeightAction) - : GameActions::QueryNested(&waterSetHeightAction); - if (result.Error == GameActions::Status::Ok) - { - res.Cost += result.Cost; - hasChanged = true; - } - else - { - result.ErrorTitle = STR_CANT_RAISE_WATER_LEVEL_HERE; - return result; - } - } - } - - if (!withinOwnership) - { - return GameActions::Result( - GameActions::Status::Disallowed, STR_CANT_RAISE_WATER_LEVEL_HERE, STR_LAND_NOT_OWNED_BY_PARK); - } - - if (isExecuting && hasChanged) - { - OpenRCT2::Audio::Play3D(OpenRCT2::Audio::SoundId::LayingOutWater, res.Position); - } - // Force ride construction to recheck area - _currentTrackSelectionFlags.set(TrackSelectionFlag::recheck); - - return res; -} - -uint16_t WaterRaiseAction::GetHighestHeight(const MapRange& validRange) const -{ - // The highest height to raise the water to is the lowest water level in the selection - uint16_t maxHeight = 255 * kCoordsZStep; - for (int32_t y = validRange.GetTop(); y <= validRange.GetBottom(); y += kCoordsXYStep) - { - for (int32_t x = validRange.GetLeft(); x <= validRange.GetRight(); x += kCoordsXYStep) - { - if (gLegacyScene != LegacyScene::scenarioEditor && !getGameState().cheats.sandboxMode) - { - if (!MapIsLocationInPark(CoordsXY{ x, y })) + auto waterSetHeightAction = WaterSetHeightAction({ x, y }, height); + waterSetHeightAction.SetFlags(GetFlags()); + auto result = isExecuting ? ExecuteNested(&waterSetHeightAction) : QueryNested(&waterSetHeightAction); + if (result.Error == Status::Ok) { - continue; + res.Cost += result.Cost; + hasChanged = true; + } + else + { + result.ErrorTitle = STR_CANT_RAISE_WATER_LEVEL_HERE; + return result; } } - - auto* surfaceElement = MapGetSurfaceElementAt(CoordsXY{ x, y }); - if (surfaceElement == nullptr) - continue; - - auto height = surfaceElement->GetBaseZ(); - if (surfaceElement->GetWaterHeight() > 0) - { - height = surfaceElement->GetWaterHeight(); - } - - if (maxHeight > height) - { - maxHeight = height; - } } + + if (!withinOwnership) + { + return Result(Status::Disallowed, STR_CANT_RAISE_WATER_LEVEL_HERE, STR_LAND_NOT_OWNED_BY_PARK); + } + + if (isExecuting && hasChanged) + { + OpenRCT2::Audio::Play3D(OpenRCT2::Audio::SoundId::LayingOutWater, res.Position); + } + // Force ride construction to recheck area + _currentTrackSelectionFlags.set(TrackSelectionFlag::recheck); + + return res; } - return maxHeight; -} + uint16_t WaterRaiseAction::GetHighestHeight(const MapRange& validRange) const + { + // The highest height to raise the water to is the lowest water level in the selection + uint16_t maxHeight = 255 * kCoordsZStep; + for (int32_t y = validRange.GetTop(); y <= validRange.GetBottom(); y += kCoordsXYStep) + { + for (int32_t x = validRange.GetLeft(); x <= validRange.GetRight(); x += kCoordsXYStep) + { + if (gLegacyScene != LegacyScene::scenarioEditor && !getGameState().cheats.sandboxMode) + { + if (!MapIsLocationInPark(CoordsXY{ x, y })) + { + continue; + } + } + + auto* surfaceElement = MapGetSurfaceElementAt(CoordsXY{ x, y }); + if (surfaceElement == nullptr) + continue; + + auto height = surfaceElement->GetBaseZ(); + if (surfaceElement->GetWaterHeight() > 0) + { + height = surfaceElement->GetWaterHeight(); + } + + if (maxHeight > height) + { + maxHeight = height; + } + } + } + + return maxHeight; + } +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/WaterRaiseAction.h b/src/openrct2/actions/WaterRaiseAction.h index e6dfa8cb4a..8382615348 100644 --- a/src/openrct2/actions/WaterRaiseAction.h +++ b/src/openrct2/actions/WaterRaiseAction.h @@ -11,24 +11,27 @@ #include "GameAction.h" -class WaterRaiseAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - MapRange _range; + class WaterRaiseAction final : public GameActionBase + { + private: + MapRange _range; -public: - WaterRaiseAction() = default; - WaterRaiseAction(MapRange range); + public: + WaterRaiseAction() = default; + WaterRaiseAction(MapRange range); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; -private: - OpenRCT2::GameActions::Result QueryExecute(bool isExecuting) const; - uint16_t GetHighestHeight(const MapRange& validRange) const; -}; + private: + Result QueryExecute(bool isExecuting) const; + uint16_t GetHighestHeight(const MapRange& validRange) const; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/WaterSetHeightAction.cpp b/src/openrct2/actions/WaterSetHeightAction.cpp index 21a5954830..688f5bfb50 100644 --- a/src/openrct2/actions/WaterSetHeightAction.cpp +++ b/src/openrct2/actions/WaterSetHeightAction.cpp @@ -19,151 +19,149 @@ #include "../world/Wall.h" #include "../world/tile_element/SurfaceElement.h" -using namespace OpenRCT2; - -WaterSetHeightAction::WaterSetHeightAction(const CoordsXY& coords, uint8_t height) - : _coords(coords) - , _height(height) +namespace OpenRCT2::GameActions { -} - -void WaterSetHeightAction::AcceptParameters(GameActionParameterVisitor& visitor) -{ - visitor.Visit(_coords); - visitor.Visit("height", _height); -} - -uint16_t WaterSetHeightAction::GetActionFlags() const -{ - return GameAction::GetActionFlags(); -} - -void WaterSetHeightAction::Serialise(DataSerialiser& stream) -{ - GameAction::Serialise(stream); - - stream << DS_TAG(_coords) << DS_TAG(_height); -} - -GameActions::Result WaterSetHeightAction::Query() const -{ - auto res = GameActions::Result(); - res.Expenditure = ExpenditureType::landscaping; - res.Position = { _coords, _height * kCoordsZStep }; - - auto& gameState = getGameState(); - if (gLegacyScene != LegacyScene::scenarioEditor && !gameState.cheats.sandboxMode - && gameState.park.flags & PARK_FLAGS_FORBID_LANDSCAPE_CHANGES) + WaterSetHeightAction::WaterSetHeightAction(const CoordsXY& coords, uint8_t height) + : _coords(coords) + , _height(height) { - return GameActions::Result(GameActions::Status::Disallowed, kStringIdNone, STR_FORBIDDEN_BY_THE_LOCAL_AUTHORITY); } - StringId errorMsg = CheckParameters(); - if (errorMsg != kStringIdNone) + void WaterSetHeightAction::AcceptParameters(GameActionParameterVisitor& visitor) { - return GameActions::Result(GameActions::Status::InvalidParameters, kStringIdNone, errorMsg); + visitor.Visit(_coords); + visitor.Visit("height", _height); } - if (!LocationValid(_coords)) + uint16_t WaterSetHeightAction::GetActionFlags() const { - return GameActions::Result(GameActions::Status::NotOwned, kStringIdNone, STR_LAND_NOT_OWNED_BY_PARK); + return GameAction::GetActionFlags(); } - if (gLegacyScene != LegacyScene::scenarioEditor && !gameState.cheats.sandboxMode) + void WaterSetHeightAction::Serialise(DataSerialiser& stream) { - if (!MapIsLocationInPark(_coords)) + GameAction::Serialise(stream); + + stream << DS_TAG(_coords) << DS_TAG(_height); + } + + Result WaterSetHeightAction::Query() const + { + auto res = Result(); + res.Expenditure = ExpenditureType::landscaping; + res.Position = { _coords, _height * kCoordsZStep }; + + auto& gameState = getGameState(); + if (gLegacyScene != LegacyScene::scenarioEditor && !gameState.cheats.sandboxMode + && gameState.park.flags & PARK_FLAGS_FORBID_LANDSCAPE_CHANGES) { - return GameActions::Result(GameActions::Status::Disallowed, kStringIdNone, STR_LAND_NOT_OWNED_BY_PARK); + return Result(Status::Disallowed, kStringIdNone, STR_FORBIDDEN_BY_THE_LOCAL_AUTHORITY); } + + StringId errorMsg = CheckParameters(); + if (errorMsg != kStringIdNone) + { + return Result(Status::InvalidParameters, kStringIdNone, errorMsg); + } + + if (!LocationValid(_coords)) + { + return Result(Status::NotOwned, kStringIdNone, STR_LAND_NOT_OWNED_BY_PARK); + } + + if (gLegacyScene != LegacyScene::scenarioEditor && !gameState.cheats.sandboxMode) + { + if (!MapIsLocationInPark(_coords)) + { + return Result(Status::Disallowed, kStringIdNone, STR_LAND_NOT_OWNED_BY_PARK); + } + } + + SurfaceElement* surfaceElement = MapGetSurfaceElementAt(_coords); + if (surfaceElement == nullptr) + { + LOG_ERROR("No surface element at: x %u, y %u", _coords.x, _coords.y); + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_SURFACE_ELEMENT_NOT_FOUND); + } + + int32_t zHigh = surfaceElement->GetBaseZ(); + int32_t zLow = _height * kCoordsZStep; + if (surfaceElement->GetWaterHeight() > 0) + { + zHigh = surfaceElement->GetWaterHeight(); + } + if (zLow > zHigh) + { + int32_t temp = zHigh; + zHigh = zLow; + zLow = temp; + } + + if (auto res2 = MapCanConstructAt({ _coords, zLow, zHigh }, { 0b1111, 0b1111 }); res2.Error != Status::Ok) + { + return res2; + } + if (surfaceElement->HasTrackThatNeedsWater()) + { + return Result(Status::Disallowed, STR_ERR_INVALID_PARAMETER, STR_ERR_TRACK_ON_THIS_TILE_NEEDS_WATER); + } + + res.Cost = 250; + + return res; } - SurfaceElement* surfaceElement = MapGetSurfaceElementAt(_coords); - if (surfaceElement == nullptr) + Result WaterSetHeightAction::Execute() const { - LOG_ERROR("No surface element at: x %u, y %u", _coords.x, _coords.y); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_SURFACE_ELEMENT_NOT_FOUND); + auto res = Result(); + res.Expenditure = ExpenditureType::landscaping; + res.Position = { _coords, _height * kCoordsZStep }; + + int32_t surfaceHeight = TileElementHeight(_coords); + FootpathRemoveLitter({ _coords, surfaceHeight }); + if (!getGameState().cheats.disableClearanceChecks) + WallRemoveAtZ({ _coords, surfaceHeight }); + + SurfaceElement* surfaceElement = MapGetSurfaceElementAt(_coords); + if (surfaceElement == nullptr) + { + LOG_ERROR("No surface element at: x %u, y %u", _coords.x, _coords.y); + return Result(Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_SURFACE_ELEMENT_NOT_FOUND); + } + + if (_height > surfaceElement->BaseHeight) + { + surfaceElement->SetWaterHeight(_height * kCoordsZStep); + } + else + { + surfaceElement->SetWaterHeight(0); + } + MapInvalidateTileFull(_coords); + + res.Cost = 250; + + return res; } - int32_t zHigh = surfaceElement->GetBaseZ(); - int32_t zLow = _height * kCoordsZStep; - if (surfaceElement->GetWaterHeight() > 0) + StringId WaterSetHeightAction::CheckParameters() const { - zHigh = surfaceElement->GetWaterHeight(); + auto mapSizeMax = GetMapSizeMaxXY(); + if (_coords.x > mapSizeMax.x || _coords.y > mapSizeMax.y) + { + return STR_OFF_EDGE_OF_MAP; + } + + if (_height < kMinimumWaterHeight) + { + return STR_TOO_LOW; + } + + if (_height > kMaximumWaterHeight) + { + return STR_TOO_HIGH; + } + + return kStringIdNone; } - if (zLow > zHigh) - { - int32_t temp = zHigh; - zHigh = zLow; - zLow = temp; - } - - if (auto res2 = MapCanConstructAt({ _coords, zLow, zHigh }, { 0b1111, 0b1111 }); res2.Error != GameActions::Status::Ok) - { - return res2; - } - if (surfaceElement->HasTrackThatNeedsWater()) - { - return GameActions::Result( - GameActions::Status::Disallowed, STR_ERR_INVALID_PARAMETER, STR_ERR_TRACK_ON_THIS_TILE_NEEDS_WATER); - } - - res.Cost = 250; - - return res; -} - -GameActions::Result WaterSetHeightAction::Execute() const -{ - auto res = GameActions::Result(); - res.Expenditure = ExpenditureType::landscaping; - res.Position = { _coords, _height * kCoordsZStep }; - - int32_t surfaceHeight = TileElementHeight(_coords); - FootpathRemoveLitter({ _coords, surfaceHeight }); - if (!getGameState().cheats.disableClearanceChecks) - WallRemoveAtZ({ _coords, surfaceHeight }); - - SurfaceElement* surfaceElement = MapGetSurfaceElementAt(_coords); - if (surfaceElement == nullptr) - { - LOG_ERROR("No surface element at: x %u, y %u", _coords.x, _coords.y); - return GameActions::Result( - GameActions::Status::InvalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_SURFACE_ELEMENT_NOT_FOUND); - } - - if (_height > surfaceElement->BaseHeight) - { - surfaceElement->SetWaterHeight(_height * kCoordsZStep); - } - else - { - surfaceElement->SetWaterHeight(0); - } - MapInvalidateTileFull(_coords); - - res.Cost = 250; - - return res; -} - -StringId WaterSetHeightAction::CheckParameters() const -{ - auto mapSizeMax = GetMapSizeMaxXY(); - if (_coords.x > mapSizeMax.x || _coords.y > mapSizeMax.y) - { - return STR_OFF_EDGE_OF_MAP; - } - - if (_height < kMinimumWaterHeight) - { - return STR_TOO_LOW; - } - - if (_height > kMaximumWaterHeight) - { - return STR_TOO_HIGH; - } - - return kStringIdNone; -} +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/actions/WaterSetHeightAction.h b/src/openrct2/actions/WaterSetHeightAction.h index 5b550980bc..af86074962 100644 --- a/src/openrct2/actions/WaterSetHeightAction.h +++ b/src/openrct2/actions/WaterSetHeightAction.h @@ -11,24 +11,27 @@ #include "GameAction.h" -class WaterSetHeightAction final : public GameActionBase +namespace OpenRCT2::GameActions { -private: - CoordsXY _coords; - uint8_t _height{}; + class WaterSetHeightAction final : public GameActionBase + { + private: + CoordsXY _coords; + uint8_t _height{}; -public: - WaterSetHeightAction() = default; - WaterSetHeightAction(const CoordsXY& coords, uint8_t height); + public: + WaterSetHeightAction() = default; + WaterSetHeightAction(const CoordsXY& coords, uint8_t height); - void AcceptParameters(GameActionParameterVisitor& visitor) override; + void AcceptParameters(GameActionParameterVisitor& visitor) override; - uint16_t GetActionFlags() const override; + uint16_t GetActionFlags() const override; - void Serialise(DataSerialiser& stream) override; - OpenRCT2::GameActions::Result Query() const override; - OpenRCT2::GameActions::Result Execute() const override; + void Serialise(DataSerialiser& stream) override; + Result Query() const override; + Result Execute() const override; -private: - StringId CheckParameters() const; -}; + private: + StringId CheckParameters() const; + }; +} // namespace OpenRCT2::GameActions diff --git a/src/openrct2/interface/InteractiveConsole.cpp b/src/openrct2/interface/InteractiveConsole.cpp index 43ff25f3a0..37752df0fb 100644 --- a/src/openrct2/interface/InteractiveConsole.cpp +++ b/src/openrct2/interface/InteractiveConsole.cpp @@ -200,7 +200,8 @@ static void ConsoleCommandRides(InteractiveConsole& console, const arguments_t& } else { - auto res = SetOperatingSetting(RideId::FromUnderlying(ride_index), RideSetSetting::RideType, type); + auto res = SetOperatingSetting( + RideId::FromUnderlying(ride_index), GameActions::RideSetSetting::RideType, type); if (res == kMoney64Undefined) { if (!getGameState().cheats.allowArbitraryRideTypeChanges) @@ -312,7 +313,8 @@ static void ConsoleCommandRides(InteractiveConsole& console, const arguments_t& } else { - auto rideAction = RideFreezeRatingAction(rideIndex, RideRatingType::Excitement, excitement); + auto rideAction = GameActions::RideFreezeRatingAction( + rideIndex, GameActions::RideRatingType::Excitement, excitement); GameActions::Execute(&rideAction); } } @@ -345,7 +347,8 @@ static void ConsoleCommandRides(InteractiveConsole& console, const arguments_t& } else { - auto rideAction = RideFreezeRatingAction(rideIndex, RideRatingType::Intensity, intensity); + auto rideAction = GameActions::RideFreezeRatingAction( + rideIndex, GameActions::RideRatingType::Intensity, intensity); GameActions::Execute(&rideAction); } } @@ -378,7 +381,8 @@ static void ConsoleCommandRides(InteractiveConsole& console, const arguments_t& } else { - auto rideAction = RideFreezeRatingAction(rideIndex, RideRatingType::Nausea, nausea); + auto rideAction = GameActions::RideFreezeRatingAction( + rideIndex, GameActions::RideRatingType::Nausea, nausea); GameActions::Execute(&rideAction); } } @@ -396,7 +400,7 @@ static void ConsoleCommandRides(InteractiveConsole& console, const arguments_t& { for (const auto& ride : GetRideManager()) { - auto rideSetPrice = RideSetPriceAction(ride.id, price, true); + auto rideSetPrice = GameActions::RideSetPriceAction(ride.id, price, true); GameActions::Execute(&rideSetPrice); } } @@ -416,7 +420,7 @@ static void ConsoleCommandRides(InteractiveConsole& console, const arguments_t& { if (ride.type == rideType) { - auto rideSetPrice = RideSetPriceAction(ride.id, price, true); + auto rideSetPrice = GameActions::RideSetPriceAction(ride.id, price, true); GameActions::Execute(&rideSetPrice); } } @@ -438,7 +442,7 @@ static void ConsoleCommandRides(InteractiveConsole& console, const arguments_t& } else { - auto rideSetPrice = RideSetPriceAction(RideId::FromUnderlying(rideId), price, true); + auto rideSetPrice = GameActions::RideSetPriceAction(RideId::FromUnderlying(rideId), price, true); GameActions::Execute(&rideSetPrice); } } @@ -530,7 +534,7 @@ static void ConsoleCommandStaff(InteractiveConsole& console, const arguments_t& } auto costume = static_cast(int_val[1]); - auto staffSetCostumeAction = StaffSetCostumeAction(EntityId::FromUnderlying(int_val[0]), costume); + auto staffSetCostumeAction = GameActions::StaffSetCostumeAction(EntityId::FromUnderlying(int_val[0]), costume); GameActions::Execute(&staffSetCostumeAction); } } @@ -790,7 +794,7 @@ static void ConsoleCommandSet(InteractiveConsole& console, const arguments_t& ar money64 money = ToMoney64FromGBP(double_val[0]); if (gameState.park.cash != money) { - ConsoleSetVariableAction(console, varName, CheatType::SetMoney, money); + ConsoleSetVariableAction(console, varName, CheatType::SetMoney, money); } else { @@ -876,7 +880,7 @@ static void ConsoleCommandSet(InteractiveConsole& console, const arguments_t& ar } else if (varName == "no_money" && InvalidArguments(&invalidArgs, int_valid[0])) { - ConsoleSetVariableAction(console, varName, CheatType::NoMoney, int_val[0] != 0); + ConsoleSetVariableAction(console, varName, CheatType::NoMoney, int_val[0] != 0); } else if (varName == "difficult_park_rating" && InvalidArguments(&invalidArgs, int_valid[0])) { @@ -890,8 +894,8 @@ static void ConsoleCommandSet(InteractiveConsole& console, const arguments_t& ar } else if (varName == "park_open" && InvalidArguments(&invalidArgs, int_valid[0])) { - ConsoleSetVariableAction( - console, varName, (int_val[0] == 1) ? ParkParameter::Open : ParkParameter::Close); + ConsoleSetVariableAction( + console, varName, (int_val[0] == 1) ? GameActions::ParkParameter::Open : GameActions::ParkParameter::Close); } else if (varName == "land_rights_cost" && InvalidArguments(&invalidArgs, double_valid[0])) { @@ -907,7 +911,7 @@ static void ConsoleCommandSet(InteractiveConsole& console, const arguments_t& ar } else if (varName == "game_speed" && InvalidArguments(&invalidArgs, int_valid[0])) { - ConsoleSetVariableAction(console, varName, int_val[0]); + ConsoleSetVariableAction(console, varName, int_val[0]); } else if (varName == "console_small_font" && InvalidArguments(&invalidArgs, int_valid[0])) { @@ -957,7 +961,8 @@ static void ConsoleCommandSet(InteractiveConsole& console, const arguments_t& ar { if (getGameState().cheats.sandboxMode != (int_val[0] != 0)) { - ConsoleSetVariableAction(console, varName, CheatType::SandboxMode, int_val[0] != 0); + ConsoleSetVariableAction( + console, varName, CheatType::SandboxMode, int_val[0] != 0); } else { @@ -968,7 +973,8 @@ static void ConsoleCommandSet(InteractiveConsole& console, const arguments_t& ar { if (getGameState().cheats.disableClearanceChecks != (int_val[0] != 0)) { - ConsoleSetVariableAction(console, varName, CheatType::DisableClearanceChecks, int_val[0] != 0); + ConsoleSetVariableAction( + console, varName, CheatType::DisableClearanceChecks, int_val[0] != 0); } else { @@ -979,7 +985,8 @@ static void ConsoleCommandSet(InteractiveConsole& console, const arguments_t& ar { if (getGameState().cheats.disableSupportLimits != (int_val[0] != 0)) { - ConsoleSetVariableAction(console, varName, CheatType::DisableSupportLimits, int_val[0] != 0); + ConsoleSetVariableAction( + console, varName, CheatType::DisableSupportLimits, int_val[0] != 0); } else { @@ -1292,7 +1299,7 @@ static void ConsoleCommandForceDate([[maybe_unused]] InteractiveConsole& console } } - auto setDateAction = ParkSetDateAction(year - 1, month - 1, day - 1); + auto setDateAction = GameActions::ParkSetDateAction(year - 1, month - 1, day - 1); GameActions::Execute(&setDateAction); auto* windowMgr = Ui::GetWindowManager(); diff --git a/src/openrct2/management/Research.cpp b/src/openrct2/management/Research.cpp index 67ee65fa2e..7a858ab23d 100644 --- a/src/openrct2/management/Research.cpp +++ b/src/openrct2/management/Research.cpp @@ -140,7 +140,7 @@ static void ResearchMarkAsFullyCompleted() gameState.researchProgressStage = RESEARCH_STAGE_FINISHED_ALL; ResearchInvalidateRelatedWindows(); // Reset funding to 0 if no more rides. - auto gameAction = ParkSetResearchFundingAction(gameState.researchPriorities, 0); + auto gameAction = GameActions::ParkSetResearchFundingAction(gameState.researchPriorities, 0); GameActions::Execute(&gameAction); } diff --git a/src/openrct2/network/Network.h b/src/openrct2/network/Network.h index af6f7ed59f..af0b191983 100644 --- a/src/openrct2/network/Network.h +++ b/src/openrct2/network/Network.h @@ -30,10 +30,10 @@ struct Peep; struct CoordsXYZ; namespace OpenRCT2::GameActions { + enum class ModifyGroupType : uint8_t; + enum class PermissionState : uint8_t; class Result; -} -enum class ModifyGroupType : uint8_t; -enum class PermissionState : uint8_t; +} // namespace OpenRCT2::GameActions enum class NetworkPermission : uint32_t; void NetworkReconnect(); @@ -82,8 +82,8 @@ void NetworkSetPlayerGroup(uint32_t index, uint32_t groupindex); [[nodiscard]] OpenRCT2::GameActions::Result NetworkSetPlayerGroup( NetworkPlayerId_t actionPlayerId, NetworkPlayerId_t playerId, uint8_t groupId, bool isExecuting); [[nodiscard]] OpenRCT2::GameActions::Result NetworkModifyGroups( - NetworkPlayerId_t actionPlayerId, ModifyGroupType type, uint8_t groupId, const std::string& name, uint32_t permissionIndex, - PermissionState permissionState, bool isExecuting); + NetworkPlayerId_t actionPlayerId, OpenRCT2::GameActions::ModifyGroupType type, uint8_t groupId, const std::string& name, + uint32_t permissionIndex, OpenRCT2::GameActions::PermissionState permissionState, bool isExecuting); [[nodiscard]] OpenRCT2::GameActions::Result NetworkKickPlayer(NetworkPlayerId_t playerId, bool isExecuting); [[nodiscard]] uint8_t NetworkGetDefaultGroup(); [[nodiscard]] int32_t NetworkGetNumActions(); diff --git a/src/openrct2/network/NetworkBase.cpp b/src/openrct2/network/NetworkBase.cpp index ee3a71d959..ad3eb0519d 100644 --- a/src/openrct2/network/NetworkBase.cpp +++ b/src/openrct2/network/NetworkBase.cpp @@ -2062,10 +2062,10 @@ void NetworkBase::ServerClientDisconnected(std::unique_ptr& c Peep* pickup_peep = NetworkGetPickupPeep(connection_player->Id); if (pickup_peep != nullptr) { - PeepPickupAction pickupAction{ PeepPickupType::Cancel, - pickup_peep->Id, - { NetworkGetPickupPeepOldX(connection_player->Id), 0, 0 }, - NetworkGetCurrentPlayerId() }; + GameActions::PeepPickupAction pickupAction{ GameActions::PeepPickupType::Cancel, + pickup_peep->Id, + { NetworkGetPickupPeepOldX(connection_player->Id), 0, 0 }, + NetworkGetCurrentPlayerId() }; auto res = GameActions::Execute(&pickupAction); } ServerSendEventPlayerDisconnected( @@ -2827,7 +2827,8 @@ void NetworkBase::Client_Handle_MAP([[maybe_unused]] NetworkConnection& connecti else { // Something went wrong, game is not loaded. Return to main screen. - auto loadOrQuitAction = LoadOrQuitAction(LoadOrQuitModes::OpenSavePrompt, PromptMode::saveBeforeQuit); + auto loadOrQuitAction = GameActions::LoadOrQuitAction( + GameActions::LoadOrQuitModes::OpenSavePrompt, PromptMode::saveBeforeQuit); GameActions::Execute(&loadOrQuitAction); } if (has_to_free) @@ -3633,13 +3634,13 @@ GameActions::Result NetworkSetPlayerGroup( } GameActions::Result NetworkModifyGroups( - NetworkPlayerId_t actionPlayerId, ModifyGroupType type, uint8_t groupId, const std::string& name, uint32_t permissionIndex, - PermissionState permissionState, bool isExecuting) + NetworkPlayerId_t actionPlayerId, GameActions::ModifyGroupType type, uint8_t groupId, const std::string& name, + uint32_t permissionIndex, GameActions::PermissionState permissionState, bool isExecuting) { auto& network = OpenRCT2::GetContext()->GetNetwork(); switch (type) { - case ModifyGroupType::AddGroup: + case GameActions::ModifyGroupType::AddGroup: { if (isExecuting) { @@ -3651,7 +3652,7 @@ GameActions::Result NetworkModifyGroups( } } break; - case ModifyGroupType::RemoveGroup: + case GameActions::ModifyGroupType::RemoveGroup: { if (groupId == 0) { @@ -3671,7 +3672,7 @@ GameActions::Result NetworkModifyGroups( } } break; - case ModifyGroupType::SetPermissions: + case GameActions::ModifyGroupType::SetPermissions: { if (groupId == 0) { // can't change admin group permissions @@ -3680,7 +3681,7 @@ GameActions::Result NetworkModifyGroups( NetworkGroup* mygroup = nullptr; NetworkPlayer* player = network.GetPlayerByID(actionPlayerId); auto networkPermission = static_cast(permissionIndex); - if (player != nullptr && permissionState == PermissionState::Toggle) + if (player != nullptr && permissionState == GameActions::PermissionState::Toggle) { mygroup = network.GetGroupByID(player->Group); if (mygroup == nullptr || !mygroup->CanPerformAction(networkPermission)) @@ -3695,11 +3696,11 @@ GameActions::Result NetworkModifyGroups( NetworkGroup* group = network.GetGroupByID(groupId); if (group != nullptr) { - if (permissionState != PermissionState::Toggle) + if (permissionState != GameActions::PermissionState::Toggle) { if (mygroup != nullptr) { - if (permissionState == PermissionState::SetAll) + if (permissionState == GameActions::PermissionState::SetAll) { group->ActionsAllowed = mygroup->ActionsAllowed; } @@ -3717,7 +3718,7 @@ GameActions::Result NetworkModifyGroups( } } break; - case ModifyGroupType::SetName: + case GameActions::ModifyGroupType::SetName: { NetworkGroup* group = network.GetGroupByID(groupId); if (group == nullptr) @@ -3747,7 +3748,7 @@ GameActions::Result NetworkModifyGroups( } } break; - case ModifyGroupType::SetDefault: + case GameActions::ModifyGroupType::SetDefault: { if (groupId == 0) { @@ -4233,8 +4234,8 @@ GameActions::Result NetworkSetPlayerGroup( return GameActions::Result(); } GameActions::Result NetworkModifyGroups( - NetworkPlayerId_t actionPlayerId, ModifyGroupType type, uint8_t groupId, const std::string& name, uint32_t permissionIndex, - PermissionState permissionState, bool isExecuting) + NetworkPlayerId_t actionPlayerId, GameActions::ModifyGroupType type, uint8_t groupId, const std::string& name, + uint32_t permissionIndex, GameActions::PermissionState permissionState, bool isExecuting) { return GameActions::Result(); } diff --git a/src/openrct2/rct12/ScenarioPatcher.cpp b/src/openrct2/rct12/ScenarioPatcher.cpp index ad5db38144..a4eaa1603b 100644 --- a/src/openrct2/rct12/ScenarioPatcher.cpp +++ b/src/openrct2/rct12/ScenarioPatcher.cpp @@ -656,7 +656,7 @@ static void ApplyPathFixes(const json_t& scenarioPatch) for (auto coordinate : coordinates) { auto slope = direction != kInvalidDirection ? direction + 4 : 0; - auto footpathPlaceAction = FootpathPlaceAction( + auto footpathPlaceAction = GameActions::FootpathPlaceAction( coordinate.ToCoordsXYZ(), slope, surfaceObjIndex, railingsObjIndex, direction, constructionFlags); auto result = footpathPlaceAction.Execute(); if (result.Error != GameActions::Status::Ok) diff --git a/src/openrct2/ride/Ride.cpp b/src/openrct2/ride/Ride.cpp index fc0f974dc2..65d471d0a4 100644 --- a/src/openrct2/ride/Ride.cpp +++ b/src/openrct2/ride/Ride.cpp @@ -1129,13 +1129,13 @@ void Ride::update() if (mode == RideMode::continuousCircuitBlockSectioned || mode == RideMode::poweredLaunchBlockSectioned) { // We require this to execute right away during the simulation, always ignore network and queue. - RideSetStatusAction gameAction = RideSetStatusAction(id, RideStatus::closed); + auto gameAction = GameActions::RideSetStatusAction(id, RideStatus::closed); GameActions::ExecuteNested(&gameAction); } else { // We require this to execute right away during the simulation, always ignore network and queue. - RideSetStatusAction gameAction = RideSetStatusAction(id, RideStatus::simulating); + auto gameAction = GameActions::RideSetStatusAction(id, RideStatus::simulating); GameActions::ExecuteNested(&gameAction); } } @@ -5233,25 +5233,28 @@ void Ride::updateNumberOfCircuits() void Ride::setRideEntry(ObjectEntryIndex entryIndex) { auto colour = RideGetUnusedPresetVehicleColour(entryIndex); - auto rideSetVehicleAction = RideSetVehicleAction(id, RideSetVehicleType::RideEntry, entryIndex, colour); + auto rideSetVehicleAction = GameActions::RideSetVehicleAction( + id, GameActions::RideSetVehicleType::RideEntry, entryIndex, colour); GameActions::Execute(&rideSetVehicleAction); } void Ride::setNumTrains(int32_t newNumTrains) { - auto rideSetVehicleAction = RideSetVehicleAction(id, RideSetVehicleType::NumTrains, newNumTrains); + auto rideSetVehicleAction = GameActions::RideSetVehicleAction(id, GameActions::RideSetVehicleType::NumTrains, newNumTrains); GameActions::Execute(&rideSetVehicleAction); } void Ride::setNumCarsPerTrain(int32_t numCarsPerVehicle) { - auto rideSetVehicleAction = RideSetVehicleAction(id, RideSetVehicleType::NumCarsPerTrain, numCarsPerVehicle); + auto rideSetVehicleAction = GameActions::RideSetVehicleAction( + id, GameActions::RideSetVehicleType::NumCarsPerTrain, numCarsPerVehicle); GameActions::Execute(&rideSetVehicleAction); } void Ride::setReversedTrains(bool reverseTrains) { - auto rideSetVehicleAction = RideSetVehicleAction(id, RideSetVehicleType::TrainsReversed, reverseTrains); + auto rideSetVehicleAction = GameActions::RideSetVehicleAction( + id, GameActions::RideSetVehicleType::TrainsReversed, reverseTrains); GameActions::Execute(&rideSetVehicleAction); } @@ -5262,7 +5265,7 @@ void Ride::setToDefaultInspectionInterval() { if (defaultInspectionInterval <= RIDE_INSPECTION_NEVER) { - SetOperatingSetting(id, RideSetSetting::InspectionInterval, defaultInspectionInterval); + SetOperatingSetting(id, GameActions::RideSetSetting::InspectionInterval, defaultInspectionInterval); } } } diff --git a/src/openrct2/ride/Ride.h b/src/openrct2/ride/Ride.h index eac423ec3b..608a44fa7e 100644 --- a/src/openrct2/ride/Ride.h +++ b/src/openrct2/ride/Ride.h @@ -919,10 +919,6 @@ void RideUpdateVehicleColours(const Ride& ride); OpenRCT2::BitSet RideEntryGetSupportedTrackPieces(const RideObjectEntry& rideEntry); -enum class RideSetSetting : uint8_t; -money64 SetOperatingSetting(RideId rideId, RideSetSetting setting, uint8_t value); -money64 SetOperatingSettingNested(RideId rideId, RideSetSetting setting, uint8_t value, uint8_t flags); - uint32_t RideCustomersPerHour(const Ride& ride); uint32_t RideCustomersInLast5Minutes(const Ride& ride); diff --git a/src/openrct2/ride/RideConstruction.cpp b/src/openrct2/ride/RideConstruction.cpp index d73a9ab4c5..80cda484e7 100644 --- a/src/openrct2/ride/RideConstruction.cpp +++ b/src/openrct2/ride/RideConstruction.cpp @@ -12,11 +12,9 @@ #include "../Context.h" #include "../GameState.h" #include "../Input.h" -#include "../actions/MazeSetTrackAction.h" #include "../actions/RideEntranceExitRemoveAction.h" #include "../actions/RideSetSettingAction.h" #include "../actions/RideSetStatusAction.h" -#include "../actions/RideSetVehicleAction.h" #include "../actions/TrackRemoveAction.h" #include "../entity/EntityList.h" #include "../entity/EntityRegistry.h" @@ -37,6 +35,7 @@ #include "../world/TileElementsView.h" #include "../world/tile_element/EntranceElement.h" #include "../world/tile_element/PathElement.h" +#include "../world/tile_element/TileElement.h" #include "../world/tile_element/TrackElement.h" #include "Ride.h" #include "RideData.h" @@ -895,7 +894,7 @@ static bool ride_modify_entrance_or_exit(const CoordsXYE& tileElement) else { // Remove entrance / exit - auto rideEntranceExitRemove = RideEntranceExitRemoveAction( + auto rideEntranceExitRemove = GameActions::RideEntranceExitRemoveAction( { tileElement.x, tileElement.y }, rideIndex, stationIndex, entranceType == ENTRANCE_TYPE_RIDE_EXIT); rideEntranceExitRemove.SetCallback([=](const GameAction* ga, const GameActions::Result* result) { @@ -977,7 +976,7 @@ bool RideModify(const CoordsXYE& input) // Stop the ride again to clear all vehicles and peeps (compatible with network games) if (ride->status != RideStatus::simulating) { - auto gameAction = RideSetStatusAction(ride->id, RideStatus::closed); + auto gameAction = GameActions::RideSetStatusAction(ride->id, RideStatus::closed); GameActions::Execute(&gameAction); } @@ -1123,7 +1122,7 @@ money64 RideGetRefundPrice(const Ride& ride) do { - auto trackRemoveAction = TrackRemoveAction( + auto trackRemoveAction = GameActions::TrackRemoveAction( trackElement.element->AsTrack()->GetTrackType(), trackElement.element->AsTrack()->GetSequenceIndex(), { trackElement.x, trackElement.y, trackElement.element->GetBaseZ(), direction }); trackRemoveAction.SetFlags(GAME_COMMAND_FLAG_ALLOW_DURING_PAUSED); @@ -1153,16 +1152,16 @@ money64 RideGetRefundPrice(const Ride& ride) return cost; } -money64 SetOperatingSetting(RideId rideId, RideSetSetting setting, uint8_t value) +money64 SetOperatingSetting(RideId rideId, GameActions::RideSetSetting setting, uint8_t value) { - auto rideSetSetting = RideSetSettingAction(rideId, setting, value); + auto rideSetSetting = GameActions::RideSetSettingAction(rideId, setting, value); auto res = GameActions::Execute(&rideSetSetting); return res.Error == GameActions::Status::Ok ? 0 : kMoney64Undefined; } -money64 SetOperatingSettingNested(RideId rideId, RideSetSetting setting, uint8_t value, uint8_t flags) +money64 SetOperatingSettingNested(RideId rideId, GameActions::RideSetSetting setting, uint8_t value, uint8_t flags) { - auto rideSetSetting = RideSetSettingAction(rideId, setting, value); + auto rideSetSetting = GameActions::RideSetSettingAction(rideId, setting, value); rideSetSetting.SetFlags(flags); auto res = flags & GAME_COMMAND_FLAG_APPLY ? GameActions::ExecuteNested(&rideSetSetting) : GameActions::QueryNested(&rideSetSetting); diff --git a/src/openrct2/ride/RideConstruction.h b/src/openrct2/ride/RideConstruction.h index 072e92b29a..57541a6c68 100644 --- a/src/openrct2/ride/RideConstruction.h +++ b/src/openrct2/ride/RideConstruction.h @@ -25,6 +25,11 @@ namespace OpenRCT2 struct TileElement; } +namespace OpenRCT2::GameActions +{ + enum class RideSetSetting : uint8_t; +} + struct CoordsXYE; struct RideTypeDescriptor; struct TrackDrawerDescriptor; @@ -132,6 +137,9 @@ void RideSelectPreviousSection(); bool RideModify(const CoordsXYE& input); +money64 SetOperatingSetting(RideId rideId, OpenRCT2::GameActions::RideSetSetting setting, uint8_t value); +money64 SetOperatingSettingNested(RideId rideId, OpenRCT2::GameActions::RideSetSetting setting, uint8_t value, uint8_t flags); + bool RideSelectBackwardsFromFront(); bool RideSelectForwardsFromBack(); diff --git a/src/openrct2/ride/TrackDesign.cpp b/src/openrct2/ride/TrackDesign.cpp index bea573dd9f..8f52672869 100644 --- a/src/openrct2/ride/TrackDesign.cpp +++ b/src/openrct2/ride/TrackDesign.cpp @@ -961,7 +961,7 @@ static GameActions::Result TrackDesignPlaceSceneryElementRemoveGhost( uint8_t quadrant = scenery.getQuadrant() + _currentTrackPieceDirection; quadrant &= 3; - auto* sceneryEntry = OpenRCT2::ObjectManager::GetObjectEntry(entryInfo->Index); + auto* sceneryEntry = ObjectManager::GetObjectEntry(entryInfo->Index); if (!(!sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_FULL_TILE) && sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_DIAGONAL)) && sceneryEntry->HasFlag( SMALL_SCENERY_FLAG_DIAGONAL | SMALL_SCENERY_FLAG_HALF_SPACE | SMALL_SCENERY_FLAG_THREE_QUARTERS)) @@ -969,18 +969,20 @@ static GameActions::Result TrackDesignPlaceSceneryElementRemoveGhost( quadrant = 0; } - ga = std::make_unique(CoordsXYZ{ mapCoord.x, mapCoord.y, z }, quadrant, entryInfo->Index); + ga = std::make_unique( + CoordsXYZ{ mapCoord.x, mapCoord.y, z }, quadrant, entryInfo->Index); break; } case ObjectType::largeScenery: - ga = std::make_unique(CoordsXYZD{ mapCoord.x, mapCoord.y, z, sceneryRotation }, 0); + ga = std::make_unique( + CoordsXYZD{ mapCoord.x, mapCoord.y, z, sceneryRotation }, 0); break; case ObjectType::walls: - ga = std::make_unique(CoordsXYZD{ mapCoord.x, mapCoord.y, z, sceneryRotation }); + ga = std::make_unique(CoordsXYZD{ mapCoord.x, mapCoord.y, z, sceneryRotation }); break; case ObjectType::paths: case ObjectType::footpathSurface: - ga = std::make_unique(CoordsXYZ{ mapCoord.x, mapCoord.y, z }); + ga = std::make_unique(CoordsXYZ{ mapCoord.x, mapCoord.y, z }); break; default: return GameActions::Result(); @@ -1075,7 +1077,7 @@ static GameActions::Result TrackDesignPlaceSceneryElement( flags |= GAME_COMMAND_FLAG_REPLAY; } - auto smallSceneryPlace = SmallSceneryPlaceAction( + auto smallSceneryPlace = GameActions::SmallSceneryPlaceAction( { mapCoord.x, mapCoord.y, z, rotation }, quadrant, entryInfo->Index, scenery.primaryColour, scenery.secondaryColour, scenery.tertiaryColour); @@ -1117,7 +1119,7 @@ static GameActions::Result TrackDesignPlaceSceneryElement( { flags |= GAME_COMMAND_FLAG_REPLAY; } - auto sceneryPlaceAction = LargeSceneryPlaceAction( + auto sceneryPlaceAction = GameActions::LargeSceneryPlaceAction( { mapCoord.x, mapCoord.y, z, rotation }, entryInfo->Index, scenery.primaryColour, scenery.secondaryColour, scenery.tertiaryColour); sceneryPlaceAction.SetFlags(flags); @@ -1157,7 +1159,7 @@ static GameActions::Result TrackDesignPlaceSceneryElement( { flags |= GAME_COMMAND_FLAG_REPLAY; } - auto wallPlaceAction = WallPlaceAction( + auto wallPlaceAction = GameActions::WallPlaceAction( entryInfo->Index, { mapCoord.x, mapCoord.y, z }, rotation, scenery.primaryColour, scenery.secondaryColour, scenery.tertiaryColour); wallPlaceAction.SetFlags(flags); @@ -1199,7 +1201,7 @@ static GameActions::Result TrackDesignPlaceSceneryElement( constructFlags |= PathConstructFlag::IsQueue; if (entryInfo->Type == ObjectType::paths) constructFlags |= PathConstructFlag::IsLegacyPathObject; - auto footpathPlaceAction = FootpathLayoutPlaceAction( + auto footpathPlaceAction = GameActions::FootpathLayoutPlaceAction( { mapCoord.x, mapCoord.y, z }, slope, entryInfo->Index, entryInfo->SecondaryIndex, edges, constructFlags); footpathPlaceAction.SetFlags(flags); auto res = flags & GAME_COMMAND_FLAG_APPLY ? GameActions::ExecuteNested(&footpathPlaceAction) @@ -1376,7 +1378,7 @@ static std::optional TrackDesignPlaceEntrances( flags |= GAME_COMMAND_FLAG_REPLAY; } - auto rideEntranceExitPlaceAction = RideEntranceExitPlaceAction( + auto rideEntranceExitPlaceAction = GameActions::RideEntranceExitPlaceAction( newCoords, rotation, rideId, stationIndex, entrance.isExit); rideEntranceExitPlaceAction.SetFlags(flags); auto res = flags & GAME_COMMAND_FLAG_APPLY ? GameActions::ExecuteNested(&rideEntranceExitPlaceAction) @@ -1394,7 +1396,7 @@ static std::optional TrackDesignPlaceEntrances( } else { - auto res = RideEntranceExitPlaceAction::TrackPlaceQuery(newCoords, false); + auto res = GameActions::RideEntranceExitPlaceAction::TrackPlaceQuery(newCoords, false); if (res.Error != GameActions::Status::Ok) { return res; @@ -1473,7 +1475,7 @@ static GameActions::Result TrackDesignPlaceMaze( flags |= GAME_COMMAND_FLAG_REPLAY; } - auto mazePlace = MazePlaceTrackAction({ mapCoord, origin.z }, ride.id, mazeEntry); + auto mazePlace = GameActions::MazePlaceTrackAction({ mapCoord, origin.z }, ride.id, mazeEntry); mazePlace.SetFlags(flags); auto res = flags & GAME_COMMAND_FLAG_APPLY ? GameActions::ExecuteNested(&mazePlace) : GameActions::QueryNested(&mazePlace); @@ -1530,7 +1532,7 @@ static GameActions::Result TrackDesignPlaceMaze( if (tds.placeOperation == TrackPlaceOperation::removeGhost) { - auto gameAction = RideDemolishAction(ride.id, RideModifyType::demolish); + auto gameAction = GameActions::RideDemolishAction(ride.id, GameActions::RideModifyType::demolish); gameAction.SetFlags(GAME_COMMAND_FLAG_ALLOW_DURING_PAUSED | GAME_COMMAND_FLAG_NO_SPEND | GAME_COMMAND_FLAG_GHOST); GameActions::Execute(&gameAction); } @@ -1580,7 +1582,7 @@ static GameActions::Result TrackDesignPlaceRide( { const TrackCoordinates* trackCoordinates = &ted.coordinates; int32_t tempZ = newCoords.z - trackCoordinates->zBegin + ted.sequences[0].clearance.z; - auto trackRemoveAction = TrackRemoveAction( + auto trackRemoveAction = GameActions::TrackRemoveAction( trackType, 0, { newCoords, tempZ, static_cast(rotation & 3) }); trackRemoveAction.SetFlags( GAME_COMMAND_FLAG_ALLOW_DURING_PAUSED | GAME_COMMAND_FLAG_NO_SPEND | GAME_COMMAND_FLAG_GHOST @@ -1629,7 +1631,7 @@ static GameActions::Result TrackDesignPlaceRide( flags |= GAME_COMMAND_FLAG_REPLAY; } - auto trackPlaceAction = TrackPlaceAction( + auto trackPlaceAction = GameActions::TrackPlaceAction( ride.id, trackType, ride.type, { newCoords, tempZ, static_cast(rotation) }, track.brakeBoosterSpeed, track.colourScheme, track.seatRotation, liftHillAndAlternativeState, true); trackPlaceAction.SetFlags(flags); @@ -1849,7 +1851,7 @@ int32_t TrackDesignGetZPlacement(const TrackDesign& td, Ride& ride, const Coords static money64 TrackDesignCreateRide(int32_t type, int32_t subType, int32_t flags, RideId* outRideIndex) { // Don't set colours as will be set correctly later. - auto gameAction = RideCreateAction(type, subType, 0, 0, getGameState().lastEntranceStyle); + auto gameAction = GameActions::RideCreateAction(type, subType, 0, 0, getGameState().lastEntranceStyle); gameAction.SetFlags(flags); auto res = GameActions::ExecuteNested(&gameAction); diff --git a/src/openrct2/ride/Vehicle.cpp b/src/openrct2/ride/Vehicle.cpp index 5d684bc596..f7758929ca 100644 --- a/src/openrct2/ride/Vehicle.cpp +++ b/src/openrct2/ride/Vehicle.cpp @@ -2865,7 +2865,7 @@ void Vehicle::UpdateCollisionSetup() if (curRide->status != RideStatus::closed) { // We require this to execute right away during the simulation, always ignore network and queue. - auto gameAction = RideSetStatusAction(curRide->id, RideStatus::closed); + auto gameAction = GameActions::RideSetStatusAction(curRide->id, RideStatus::closed); GameActions::ExecuteNested(&gameAction); } } @@ -4657,7 +4657,7 @@ void Vehicle::CrashOnLand() if (curRide->status != RideStatus::closed) { // We require this to execute right away during the simulation, always ignore network and queue. - auto gameAction = RideSetStatusAction(curRide->id, RideStatus::closed); + auto gameAction = GameActions::RideSetStatusAction(curRide->id, RideStatus::closed); GameActions::ExecuteNested(&gameAction); } } @@ -4725,7 +4725,7 @@ void Vehicle::CrashOnWater() if (curRide->status != RideStatus::closed) { // We require this to execute right away during the simulation, always ignore network and queue. - auto gameAction = RideSetStatusAction(curRide->id, RideStatus::closed); + auto gameAction = GameActions::RideSetStatusAction(curRide->id, RideStatus::closed); GameActions::ExecuteNested(&gameAction); } } diff --git a/src/openrct2/scripting/ScriptEngine.cpp b/src/openrct2/scripting/ScriptEngine.cpp index bcaa6fdb01..afae8a8ea2 100644 --- a/src/openrct2/scripting/ScriptEngine.cpp +++ b/src/openrct2/scripting/ScriptEngine.cpp @@ -1072,7 +1072,7 @@ void ScriptEngine::RemoveNetworkPlugins() } } -GameActions::Result ScriptEngine::QueryOrExecuteCustomGameAction(const CustomAction& customAction, bool isExecute) +GameActions::Result ScriptEngine::QueryOrExecuteCustomGameAction(const GameActions::CustomAction& customAction, bool isExecute) { std::string actionz = customAction.GetId(); auto kvp = _customActions.find(actionz); @@ -1234,7 +1234,7 @@ DukValue ScriptEngine::GameActionResultToDuk(const GameAction& action, const Gam { if (result.Error == GameActions::Status::Ok) { - const auto actionResult = result.GetData(); + const auto actionResult = result.GetData(); if (!actionResult.StaffEntityId.IsNull()) { obj.Set("peep", actionResult.StaffEntityId.ToUnderlying()); @@ -1246,13 +1246,13 @@ DukValue ScriptEngine::GameActionResultToDuk(const GameAction& action, const Gam switch (action.GetType()) { case GameCommand::PlaceBanner: - bannerId = result.GetData().bannerId; + bannerId = result.GetData().bannerId; break; case GameCommand::PlaceLargeScenery: - bannerId = result.GetData().bannerId; + bannerId = result.GetData().bannerId; break; case GameCommand::PlaceWall: - bannerId = result.GetData().BannerId; + bannerId = result.GetData().BannerId; break; default: break; @@ -1473,7 +1473,7 @@ void ScriptEngine::RunGameActionHooks(const GameAction& action, GameActions::Res auto actionId = action.GetType(); if (action.GetType() == GameCommand::Custom) { - auto customAction = static_cast(action); + auto customAction = static_cast(action); obj.Set("action", customAction.GetId()); auto dukArgs = DuktapeTryParseJson(_context, customAction.GetJson()); @@ -1559,7 +1559,7 @@ std::unique_ptr ScriptEngine::CreateGameAction( auto jsonz = duk_json_encode(ctx, -1); auto json = std::string(jsonz); duk_pop(ctx); - auto customAction = std::make_unique(actionid, json, pluginName); + auto customAction = std::make_unique(actionid, json, pluginName); if (customAction->GetPlayer() == -1 && NetworkGetMode() != NETWORK_MODE_NONE) { diff --git a/src/openrct2/scripting/ScriptEngine.h b/src/openrct2/scripting/ScriptEngine.h index 38919c5cbf..dcb2ae9a36 100644 --- a/src/openrct2/scripting/ScriptEngine.h +++ b/src/openrct2/scripting/ScriptEngine.h @@ -248,7 +248,8 @@ namespace OpenRCT2::Scripting void AddNetworkPlugin(std::string_view code); void RemoveNetworkPlugins(); - [[nodiscard]] GameActions::Result QueryOrExecuteCustomGameAction(const CustomAction& action, bool isExecute); + [[nodiscard]] GameActions::Result QueryOrExecuteCustomGameAction( + const GameActions::CustomAction& action, bool isExecute); bool RegisterCustomAction( const std::shared_ptr& plugin, std::string_view action, const DukValue& query, const DukValue& execute); void RunGameActionHooks(const GameAction& action, GameActions::Result& result, bool isExecute); diff --git a/src/openrct2/scripting/bindings/network/ScNetwork.cpp b/src/openrct2/scripting/bindings/network/ScNetwork.cpp index c1b68ef818..def44d2266 100644 --- a/src/openrct2/scripting/bindings/network/ScNetwork.cpp +++ b/src/openrct2/scripting/bindings/network/ScNetwork.cpp @@ -68,7 +68,7 @@ namespace OpenRCT2::Scripting void ScNetwork::defaultGroup_set(int32_t value) { #ifndef DISABLE_NETWORK - auto action = NetworkModifyGroupAction(ModifyGroupType::SetDefault, value); + auto action = GameActions::NetworkModifyGroupAction(GameActions::ModifyGroupType::SetDefault, value); GameActions::Execute(&action); #endif } @@ -198,7 +198,7 @@ namespace OpenRCT2::Scripting void ScNetwork::addGroup() { #ifndef DISABLE_NETWORK - auto networkModifyGroup = NetworkModifyGroupAction(ModifyGroupType::AddGroup); + auto networkModifyGroup = GameActions::NetworkModifyGroupAction(GameActions::ModifyGroupType::AddGroup); GameActions::Execute(&networkModifyGroup); #endif } @@ -213,7 +213,7 @@ namespace OpenRCT2::Scripting if (index < numGroups) { auto groupId = NetworkGetGroupID(index); - auto networkAction = NetworkModifyGroupAction(ModifyGroupType::RemoveGroup, groupId); + auto networkAction = GameActions::NetworkModifyGroupAction(GameActions::ModifyGroupType::RemoveGroup, groupId); GameActions::Execute(&networkAction); } } @@ -222,7 +222,7 @@ namespace OpenRCT2::Scripting auto index = NetworkGetGroupIndex(id); if (index != -1) { - auto networkAction = NetworkModifyGroupAction(ModifyGroupType::RemoveGroup, id); + auto networkAction = GameActions::NetworkModifyGroupAction(GameActions::ModifyGroupType::RemoveGroup, id); GameActions::Execute(&networkAction); } } @@ -239,7 +239,7 @@ namespace OpenRCT2::Scripting if (index < numPlayers) { auto playerId = NetworkGetPlayerID(index); - auto kickPlayerAction = PlayerKickAction(playerId); + auto kickPlayerAction = GameActions::PlayerKickAction(playerId); GameActions::Execute(&kickPlayerAction); } } @@ -248,7 +248,7 @@ namespace OpenRCT2::Scripting auto index = NetworkGetPlayerIndex(id); if (index != -1) { - auto kickPlayerAction = PlayerKickAction(id); + auto kickPlayerAction = GameActions::PlayerKickAction(id); GameActions::Execute(&kickPlayerAction); } } diff --git a/src/openrct2/scripting/bindings/network/ScPlayer.cpp b/src/openrct2/scripting/bindings/network/ScPlayer.cpp index 6a6dd6ba4a..e123e6a4c4 100644 --- a/src/openrct2/scripting/bindings/network/ScPlayer.cpp +++ b/src/openrct2/scripting/bindings/network/ScPlayer.cpp @@ -54,7 +54,7 @@ namespace OpenRCT2::Scripting void ScPlayer::group_set(int32_t value) { #ifndef DISABLE_NETWORK - auto playerSetGroupAction = PlayerSetGroupAction(_id, value); + auto playerSetGroupAction = GameActions::PlayerSetGroupAction(_id, value); GameActions::Execute(&playerSetGroupAction); #endif } diff --git a/src/openrct2/scripting/bindings/network/ScPlayerGroup.cpp b/src/openrct2/scripting/bindings/network/ScPlayerGroup.cpp index 072d5a21cc..ddd297098d 100644 --- a/src/openrct2/scripting/bindings/network/ScPlayerGroup.cpp +++ b/src/openrct2/scripting/bindings/network/ScPlayerGroup.cpp @@ -46,7 +46,7 @@ namespace OpenRCT2::Scripting void ScPlayerGroup::name_set(std::string value) { #ifndef DISABLE_NETWORK - auto action = NetworkModifyGroupAction(ModifyGroupType::SetName, _id, value); + auto action = GameActions::NetworkModifyGroupAction(GameActions::ModifyGroupType::SetName, _id, value); GameActions::Execute(&action); #endif } @@ -100,7 +100,8 @@ namespace OpenRCT2::Scripting return; // First clear all permissions - auto networkAction = NetworkModifyGroupAction(ModifyGroupType::SetPermissions, _id, "", 0, PermissionState::ClearAll); + auto networkAction = GameActions::NetworkModifyGroupAction( + GameActions::ModifyGroupType::SetPermissions, _id, "", 0, GameActions::PermissionState::ClearAll); GameActions::Execute(&networkAction); std::vector enabledPermissions; @@ -126,8 +127,9 @@ namespace OpenRCT2::Scripting = (enabledPermissions[i] != (NetworkCanPerformAction(groupIndex, static_cast(i)) != 0)); if (toggle) { - auto networkAction2 = NetworkModifyGroupAction( - ModifyGroupType::SetPermissions, _id, "", static_cast(i), PermissionState::Toggle); + auto networkAction2 = GameActions::NetworkModifyGroupAction( + GameActions::ModifyGroupType::SetPermissions, _id, "", static_cast(i), + GameActions::PermissionState::Toggle); GameActions::Execute(&networkAction2); } } diff --git a/src/openrct2/world/Entrance.cpp b/src/openrct2/world/Entrance.cpp index 25ca7b449f..35921d441f 100644 --- a/src/openrct2/world/Entrance.cpp +++ b/src/openrct2/world/Entrance.cpp @@ -43,7 +43,7 @@ StationIndex gRideEntranceExitGhostStationIndex; static money64 RideEntranceExitPlaceGhost( RideId rideIndex, const CoordsXY& entranceExitCoords, Direction direction, uint8_t placeType, StationIndex stationNum) { - auto rideEntranceExitPlaceAction = RideEntranceExitPlaceAction( + auto rideEntranceExitPlaceAction = GameActions::RideEntranceExitPlaceAction( entranceExitCoords, direction, rideIndex, stationNum, placeType == ENTRANCE_TYPE_RIDE_EXIT); rideEntranceExitPlaceAction.SetFlags(GAME_COMMAND_FLAG_ALLOW_DURING_PAUSED | GAME_COMMAND_FLAG_GHOST); auto res = GameActions::Execute(&rideEntranceExitPlaceAction); @@ -60,7 +60,7 @@ void ParkEntranceRemoveGhost() if (gParkEntranceGhostExists) { gParkEntranceGhostExists = false; - auto parkEntranceRemoveAction = ParkEntranceRemoveAction(gParkEntranceGhostPosition); + auto parkEntranceRemoveAction = GameActions::ParkEntranceRemoveAction(gParkEntranceGhostPosition); parkEntranceRemoveAction.SetFlags(GAME_COMMAND_FLAG_ALLOW_DURING_PAUSED); GameActions::Execute(&parkEntranceRemoveAction); } @@ -99,7 +99,7 @@ void RideEntranceExitRemoveGhost() { if (_currentTrackSelectionFlags.has(TrackSelectionFlag::entranceOrExit)) { - auto rideEntranceExitRemove = RideEntranceExitRemoveAction( + auto rideEntranceExitRemove = GameActions::RideEntranceExitRemoveAction( gRideEntranceExitGhostPosition, _currentRideIndex, gRideEntranceExitGhostStationIndex, gRideEntranceExitPlaceType == ENTRANCE_TYPE_RIDE_EXIT); diff --git a/src/openrct2/world/Footpath.cpp b/src/openrct2/world/Footpath.cpp index e3725ec5ed..4cf92a1c91 100644 --- a/src/openrct2/world/Footpath.cpp +++ b/src/openrct2/world/Footpath.cpp @@ -1012,7 +1012,8 @@ static void FootpathFixOwnership(const CoordsXY& mapPos) ownership = OWNERSHIP_UNOWNED; } - auto landSetRightsAction = LandSetRightsAction(mapPos, LandSetRightSetting::SetOwnershipWithChecks, ownership); + auto landSetRightsAction = GameActions::LandSetRightsAction( + mapPos, GameActions::LandSetRightSetting::SetOwnershipWithChecks, ownership); landSetRightsAction.SetFlags(GAME_COMMAND_FLAG_NO_SPEND); GameActions::Execute(&landSetRightsAction); } diff --git a/src/openrct2/world/Map.cpp b/src/openrct2/world/Map.cpp index f56a4f9b15..16d15f4661 100644 --- a/src/openrct2/world/Map.cpp +++ b/src/openrct2/world/Map.cpp @@ -1490,7 +1490,7 @@ void ClearElementAt(const CoordsXY& loc, TileElement** elementPtr) seqLoc -= CoordsDirectionDelta[rotation]; break; } - auto parkEntranceRemoveAction = ParkEntranceRemoveAction(CoordsXYZ{ seqLoc, element->GetBaseZ() }); + auto parkEntranceRemoveAction = GameActions::ParkEntranceRemoveAction(CoordsXYZ{ seqLoc, element->GetBaseZ() }); auto result = GameActions::ExecuteNested(&parkEntranceRemoveAction); // If asking nicely did not work, forcibly remove this to avoid an infinite loop. if (result.Error != GameActions::Status::Ok) @@ -1502,7 +1502,7 @@ void ClearElementAt(const CoordsXY& loc, TileElement** elementPtr) case TileElementType::Wall: { CoordsXYZD wallLocation = { loc.x, loc.y, element->GetBaseZ(), element->GetDirection() }; - auto wallRemoveAction = WallRemoveAction(wallLocation); + auto wallRemoveAction = GameActions::WallRemoveAction(wallLocation); auto result = GameActions::ExecuteNested(&wallRemoveAction); // If asking nicely did not work, forcibly remove this to avoid an infinite loop. if (result.Error != GameActions::Status::Ok) @@ -1513,7 +1513,7 @@ void ClearElementAt(const CoordsXY& loc, TileElement** elementPtr) break; case TileElementType::LargeScenery: { - auto removeSceneryAction = LargeSceneryRemoveAction( + auto removeSceneryAction = GameActions::LargeSceneryRemoveAction( { loc.x, loc.y, element->GetBaseZ(), element->GetDirection() }, element->AsLargeScenery()->GetSequenceIndex()); auto result = GameActions::ExecuteNested(&removeSceneryAction); // If asking nicely did not work, forcibly remove this to avoid an infinite loop. @@ -1525,7 +1525,7 @@ void ClearElementAt(const CoordsXY& loc, TileElement** elementPtr) break; case TileElementType::Banner: { - auto bannerRemoveAction = BannerRemoveAction( + auto bannerRemoveAction = GameActions::BannerRemoveAction( { loc.x, loc.y, element->GetBaseZ(), element->AsBanner()->GetPosition() }); auto result = GameActions::ExecuteNested(&bannerRemoveAction); // If asking nicely did not work, forcibly remove this to avoid an infinite loop. diff --git a/src/openrct2/world/Park.cpp b/src/openrct2/world/Park.cpp index d853fce2cf..b8333c907c 100644 --- a/src/openrct2/world/Park.cpp +++ b/src/openrct2/world/Park.cpp @@ -671,7 +671,8 @@ namespace OpenRCT2::Park void SetOpen(bool open) { - auto parkSetParameter = ParkSetParameterAction(open ? ParkParameter::Open : ParkParameter::Close); + auto parkSetParameter = GameActions::ParkSetParameterAction( + open ? GameActions::ParkParameter::Open : GameActions::ParkParameter::Close); GameActions::Execute(&parkSetParameter); } diff --git a/src/openrct2/world/Scenery.cpp b/src/openrct2/world/Scenery.cpp index 456ed9ece4..a119595d34 100644 --- a/src/openrct2/world/Scenery.cpp +++ b/src/openrct2/world/Scenery.cpp @@ -237,7 +237,7 @@ void SceneryRemoveGhostToolPlacement() { gSceneryGhostType &= ~SCENERY_GHOST_FLAG_0; - auto removeSceneryAction = SmallSceneryRemoveAction( + auto removeSceneryAction = GameActions::SmallSceneryRemoveAction( gSceneryGhostPosition, gSceneryQuadrant, gSceneryPlaceObject.EntryIndex); removeSceneryAction.SetFlags( GAME_COMMAND_FLAG_ALLOW_DURING_PAUSED | GAME_COMMAND_FLAG_NO_SPEND | GAME_COMMAND_FLAG_GHOST); @@ -260,7 +260,7 @@ void SceneryRemoveGhostToolPlacement() if (tileElement->GetBaseZ() != gSceneryGhostPosition.z) continue; - auto footpathAdditionRemoveAction = FootpathAdditionRemoveAction(gSceneryGhostPosition); + auto footpathAdditionRemoveAction = GameActions::FootpathAdditionRemoveAction(gSceneryGhostPosition); footpathAdditionRemoveAction.SetFlags( GAME_COMMAND_FLAG_ALLOW_DURING_PAUSED | GAME_COMMAND_FLAG_NO_SPEND | GAME_COMMAND_FLAG_GHOST); GameActions::Execute(&footpathAdditionRemoveAction); @@ -273,7 +273,7 @@ void SceneryRemoveGhostToolPlacement() gSceneryGhostType &= ~SCENERY_GHOST_FLAG_2; CoordsXYZD wallLocation = { gSceneryGhostPosition, gSceneryGhostWallRotation }; - auto wallRemoveAction = WallRemoveAction(wallLocation); + auto wallRemoveAction = GameActions::WallRemoveAction(wallLocation); wallRemoveAction.SetFlags(GAME_COMMAND_FLAG_ALLOW_DURING_PAUSED | GAME_COMMAND_FLAG_NO_SPEND | GAME_COMMAND_FLAG_GHOST); wallRemoveAction.Execute(); } @@ -282,7 +282,7 @@ void SceneryRemoveGhostToolPlacement() { gSceneryGhostType &= ~SCENERY_GHOST_FLAG_3; - auto removeSceneryAction = LargeSceneryRemoveAction({ gSceneryGhostPosition, gSceneryPlaceRotation }, 0); + auto removeSceneryAction = GameActions::LargeSceneryRemoveAction({ gSceneryGhostPosition, gSceneryPlaceRotation }, 0); removeSceneryAction.SetFlags( GAME_COMMAND_FLAG_ALLOW_DURING_PAUSED | GAME_COMMAND_FLAG_NO_SPEND | GAME_COMMAND_FLAG_GHOST); removeSceneryAction.Execute(); @@ -292,7 +292,7 @@ void SceneryRemoveGhostToolPlacement() { gSceneryGhostType &= ~SCENERY_GHOST_FLAG_4; - auto removeSceneryAction = BannerRemoveAction({ gSceneryGhostPosition, gSceneryPlaceRotation }); + auto removeSceneryAction = GameActions::BannerRemoveAction({ gSceneryGhostPosition, gSceneryPlaceRotation }); removeSceneryAction.SetFlags( GAME_COMMAND_FLAG_ALLOW_DURING_PAUSED | GAME_COMMAND_FLAG_NO_SPEND | GAME_COMMAND_FLAG_GHOST); GameActions::Execute(&removeSceneryAction); diff --git a/test/tests/PlayTests.cpp b/test/tests/PlayTests.cpp index ad5b22b9ab..2dd6f13c62 100644 --- a/test/tests/PlayTests.cpp +++ b/test/tests/PlayTests.cpp @@ -102,8 +102,8 @@ TEST_F(PlayTests, SecondGuestInQueueShouldNotRideIfNoFunds) auto& gameState = getGameState(); // Open park for free but charging for rides - execute(ParkParameter::Open); - execute(0); + execute(GameActions::ParkParameter::Open); + execute(0); gameState.park.flags |= PARK_FLAGS_UNLOCK_ALL_PRICES; // Find ferris wheel @@ -114,8 +114,8 @@ TEST_F(PlayTests, SecondGuestInQueueShouldNotRideIfNoFunds) Ride& ferrisWheel = *it; // Open it for free - execute(ferrisWheel.id, RideStatus::open); - execute(ferrisWheel.id, 0, true); + execute(ferrisWheel.id, RideStatus::open); + execute(ferrisWheel.id, 0, true); // Ignore intensity to stimulate peeps to queue into ferris wheel gameState.cheats.ignoreRideIntensity = true; @@ -137,7 +137,7 @@ TEST_F(PlayTests, SecondGuestInQueueShouldNotRideIfNoFunds) ASSERT_TRUE(matched); // Raise the price of the ride to a value poor guest can't pay - execute(ferrisWheel.id, 10, true); + execute(ferrisWheel.id, 10, true); // Verify that the poor guest goes back to walking without riding // since it doesn't have enough money to pay for it @@ -162,8 +162,8 @@ TEST_F(PlayTests, CarRideWithOneCarOnlyAcceptsTwoGuests) auto& gameState = getGameState(); // Open park for free but charging for rides - execute(ParkParameter::Open); - execute(0); + execute(GameActions::ParkParameter::Open); + execute(0); gameState.park.flags |= PARK_FLAGS_UNLOCK_ALL_PRICES; // Find car ride @@ -173,8 +173,8 @@ TEST_F(PlayTests, CarRideWithOneCarOnlyAcceptsTwoGuests) Ride& carRide = *it; // Open it for free - execute(carRide.id, RideStatus::open); - execute(carRide.id, 0, true); + execute(carRide.id, RideStatus::open); + execute(carRide.id, 0, true); // Ignore intensity to stimulate peeps to queue into the ride gameState.cheats.ignoreRideIntensity = true;