From 586c2edb57cfe21d9933d43bfa9fa3b6c0c2dd32 Mon Sep 17 00:00:00 2001 From: Aaron van Geffen Date: Tue, 10 Mar 2026 07:39:53 +0100 Subject: [PATCH] Move entities into OpenRCT2 namespace (#26173) --- src/openrct2-ui/windows/Windows.h | 2 +- src/openrct2/GameStateSnapshots.h | 2 +- src/openrct2/drawing/LightFX.h | 4 +- src/openrct2/entity/Balloon.cpp | 271 +- src/openrct2/entity/Balloon.h | 38 +- src/openrct2/entity/Duck.cpp | 551 +- src/openrct2/entity/Duck.h | 64 +- src/openrct2/entity/EntityBase.cpp | 113 +- src/openrct2/entity/EntityBase.h | 174 +- src/openrct2/entity/Fountain.cpp | 736 +- src/openrct2/entity/Fountain.h | 71 +- src/openrct2/entity/Guest.cpp | 14703 ++++++++-------- src/openrct2/entity/Guest.h | 843 +- src/openrct2/entity/Litter.cpp | 309 +- src/openrct2/entity/Litter.h | 54 +- src/openrct2/entity/MoneyEffect.cpp | 333 +- src/openrct2/entity/MoneyEffect.h | 38 +- src/openrct2/entity/Particle.cpp | 633 +- src/openrct2/entity/Particle.h | 132 +- src/openrct2/entity/PatrolArea.cpp | 278 +- src/openrct2/entity/PatrolArea.h | 87 +- src/openrct2/entity/Peep.cpp | 4578 ++--- src/openrct2/entity/Peep.h | 828 +- src/openrct2/entity/Staff.cpp | 4682 ++--- src/openrct2/entity/Staff.h | 273 +- src/openrct2/interface/Viewport.h | 6 +- src/openrct2/management/Marketing.h | 6 +- src/openrct2/network/Network.h | 6 +- src/openrct2/network/NetworkBase.cpp | 2 +- src/openrct2/network/NetworkPlayer.h | 5 +- src/openrct2/paint/Paint.h | 8 +- src/openrct2/paint/entity/Paint.Guest.h | 12 +- src/openrct2/paint/entity/Paint.Peep.h | 12 +- src/openrct2/paint/entity/Paint.Staff.cpp | 2 + src/openrct2/paint/entity/Paint.Staff.h | 12 +- src/openrct2/peep/GuestPathfinding.h | 7 +- src/openrct2/peep/PeepAnimations.h | 3 +- src/openrct2/ride/Ride.h | 15 +- src/openrct2/ride/RideData.h | 13 +- src/openrct2/ride/ShopItem.h | 11 +- src/openrct2/ride/Vehicle.h | 4 +- .../scripting/bindings/entity/ScBalloon.hpp | 5 +- .../scripting/bindings/entity/ScGuest.hpp | 5 +- .../scripting/bindings/entity/ScLitter.hpp | 5 +- .../bindings/entity/ScMoneyEffect.hpp | 5 +- .../scripting/bindings/entity/ScStaff.hpp | 7 +- src/openrct2/world/Park.h | 3 +- 47 files changed, 15015 insertions(+), 14936 deletions(-) diff --git a/src/openrct2-ui/windows/Windows.h b/src/openrct2-ui/windows/Windows.h index 3e2cf3ea55..c18023a427 100644 --- a/src/openrct2-ui/windows/Windows.h +++ b/src/openrct2-ui/windows/Windows.h @@ -16,7 +16,6 @@ #include struct StringWithArgs; -struct Peep; struct Ride; struct RideSelection; struct TrackDesign; @@ -32,6 +31,7 @@ namespace OpenRCT2 { class Formatter; struct ObjectEntryDescriptor; + struct Peep; struct TileElement; } // namespace OpenRCT2 diff --git a/src/openrct2/GameStateSnapshots.h b/src/openrct2/GameStateSnapshots.h index d759a5ad69..68172227e8 100644 --- a/src/openrct2/GameStateSnapshots.h +++ b/src/openrct2/GameStateSnapshots.h @@ -38,7 +38,7 @@ struct GameStateSpriteChange }; uint8_t changeType; - EntityType entityType; + OpenRCT2::EntityType entityType; uint32_t spriteIndex; std::vector diffs; diff --git a/src/openrct2/drawing/LightFX.h b/src/openrct2/drawing/LightFX.h index 4a6a9ff2db..1a58862b5c 100644 --- a/src/openrct2/drawing/LightFX.h +++ b/src/openrct2/drawing/LightFX.h @@ -16,12 +16,12 @@ struct CoordsXY; struct Vehicle; struct CoordsXYZ; -struct EntityBase; namespace OpenRCT2 { + struct EntityBase; struct Viewport; -} +} // namespace OpenRCT2 namespace OpenRCT2::Drawing { diff --git a/src/openrct2/entity/Balloon.cpp b/src/openrct2/entity/Balloon.cpp index a77a45d5a9..465118d407 100644 --- a/src/openrct2/entity/Balloon.cpp +++ b/src/openrct2/entity/Balloon.cpp @@ -22,161 +22,162 @@ #include "../world/tile_element/TrackElement.h" #include "EntityRegistry.h" -using namespace OpenRCT2; - -template<> -bool EntityBase::Is() const +namespace OpenRCT2 { - return Type == EntityType::balloon; -} - -void Balloon::Update() -{ - Invalidate(); - if (popped == 1) + template<> + bool EntityBase::Is() const { - frame++; - if (frame >= 5) - { - getGameState().entities.EntityRemove(this); - } + return Type == EntityType::balloon; } - else + + void Balloon::Update() { - time_to_move++; - if (time_to_move >= 3) + Invalidate(); + if (popped == 1) { - time_to_move = 0; frame++; - // NOTE: To keep S6 Compatibility this field needs to roll over after 1 byte - if (frame == 256) + if (frame >= 5) { - frame = 0; + getGameState().entities.EntityRemove(this); } - - if (Collides()) - { - Pop(false); - return; - } - - MoveTo({ x, y, z + 1 }); - - int32_t maxZ = 1967 - ((x ^ y) & 31); - if (z >= maxZ) - { - Pop(true); - } - } - } -} - -void Balloon::Press() -{ - if (popped != 1) - { - // There is a random chance that pressing the balloon will not pop it - // and instead shift it slightly - uint32_t random = ScenarioRand(); - if ((Id.ToUnderlying() & 7) || (random & 0xFFFF) < 0x2000) - { - Pop(true); } else { - int16_t shift = ((random & 0x80000000) ? -6 : 6); - MoveTo({ x + shift, y, z }); - } - } -} - -void Balloon::Pop(bool playSound) -{ - popped = 1; - frame = 0; - if (playSound) - { - Audio::Play3D(Audio::SoundId::balloonPop, { x, y, z }); - } -} - -void Balloon::Create(const CoordsXYZ& balloonPos, Drawing::Colour colour, bool isPopped) -{ - auto* balloon = getGameState().entities.CreateEntity(); - if (balloon == nullptr) - return; - - balloon->SpriteData.Width = 13; - balloon->SpriteData.HeightMin = 22; - balloon->SpriteData.HeightMax = 11; - balloon->MoveTo(balloonPos); - balloon->time_to_move = 0; - balloon->frame = 0; - balloon->colour = colour; - balloon->popped = (isPopped ? 1 : 0); -} - -void Balloon::Serialise(DataSerialiser& stream) -{ - EntityBase::Serialise(stream); - stream << frame; - stream << popped; - stream << time_to_move; - stream << colour; -} - -void Balloon::Paint(PaintSession& session, int32_t imageDirection) const -{ - PROFILED_FUNCTION(); - - uint32_t imageId = 22651 + (frame & 7); - if (popped != 0) - { - imageId += 8; - } - - auto image = ImageId(imageId, colour); - PaintAddImageAsParent(session, image, { 0, 0, z }, { 1, 1, 0 }); -} - -bool Balloon::Collides() const -{ - const TileElement* tileElement = MapGetFirstElementAt(CoordsXY({ x, y })); - if (tileElement == nullptr) - return false; - do - { - // the balloon has height so we add some padding to prevent it clipping through things. - int32_t balloon_top = z + kCoordsZStep * 2; - if (balloon_top == tileElement->GetBaseZ()) - { - return true; - } - - // check for situations where guests can drop a balloon inside a covered building - bool check_ceiling = tileElement->GetType() == TileElementType::Entrance; - if (tileElement->GetType() == TileElementType::Track) - { - const TrackElement* trackElement = tileElement->AsTrack(); - const auto* ride = GetRide(trackElement->GetRideIndex()); - if (ride != nullptr && ride->getRideTypeDescriptor().flags.has(RtdFlag::hasRoofOverWholeRide)) + time_to_move++; + if (time_to_move >= 3) { - check_ceiling = true; + time_to_move = 0; + frame++; + // NOTE: To keep S6 Compatibility this field needs to roll over after 1 byte + if (frame == 256) + { + frame = 0; + } + + if (Collides()) + { + Pop(false); + return; + } + + MoveTo({ x, y, z + 1 }); + + int32_t maxZ = 1967 - ((x ^ y) & 31); + if (z >= maxZ) + { + Pop(true); + } + } + } + } + + void Balloon::Press() + { + if (popped != 1) + { + // There is a random chance that pressing the balloon will not pop it + // and instead shift it slightly + uint32_t random = ScenarioRand(); + if ((Id.ToUnderlying() & 7) || (random & 0xFFFF) < 0x2000) + { + Pop(true); } else { - check_ceiling = (ride != nullptr) ? RideHasStationShelter(*ride) : false; + int16_t shift = ((random & 0x80000000) ? -6 : 6); + MoveTo({ x + shift, y, z }); } } + } - if (check_ceiling) + void Balloon::Pop(bool playSound) + { + popped = 1; + frame = 0; + if (playSound) { - if (balloon_top > tileElement->GetBaseZ() && z < tileElement->GetClearanceZ()) + Audio::Play3D(Audio::SoundId::balloonPop, { x, y, z }); + } + } + + void Balloon::Create(const CoordsXYZ& balloonPos, Drawing::Colour colour, bool isPopped) + { + auto* balloon = getGameState().entities.CreateEntity(); + if (balloon == nullptr) + return; + + balloon->SpriteData.Width = 13; + balloon->SpriteData.HeightMin = 22; + balloon->SpriteData.HeightMax = 11; + balloon->MoveTo(balloonPos); + balloon->time_to_move = 0; + balloon->frame = 0; + balloon->colour = colour; + balloon->popped = (isPopped ? 1 : 0); + } + + void Balloon::Serialise(DataSerialiser& stream) + { + EntityBase::Serialise(stream); + stream << frame; + stream << popped; + stream << time_to_move; + stream << colour; + } + + void Balloon::Paint(PaintSession& session, int32_t imageDirection) const + { + PROFILED_FUNCTION(); + + uint32_t imageId = 22651 + (frame & 7); + if (popped != 0) + { + imageId += 8; + } + + auto image = ImageId(imageId, colour); + PaintAddImageAsParent(session, image, { 0, 0, z }, { 1, 1, 0 }); + } + + bool Balloon::Collides() const + { + const TileElement* tileElement = MapGetFirstElementAt(CoordsXY({ x, y })); + if (tileElement == nullptr) + return false; + do + { + // the balloon has height so we add some padding to prevent it clipping through things. + int32_t balloon_top = z + kCoordsZStep * 2; + if (balloon_top == tileElement->GetBaseZ()) { return true; } - } - } while (!(tileElement++)->IsLastForTile()); - return false; -} + // check for situations where guests can drop a balloon inside a covered building + bool check_ceiling = tileElement->GetType() == TileElementType::Entrance; + if (tileElement->GetType() == TileElementType::Track) + { + const TrackElement* trackElement = tileElement->AsTrack(); + const auto* ride = GetRide(trackElement->GetRideIndex()); + if (ride != nullptr && ride->getRideTypeDescriptor().flags.has(RtdFlag::hasRoofOverWholeRide)) + { + check_ceiling = true; + } + else + { + check_ceiling = (ride != nullptr) ? RideHasStationShelter(*ride) : false; + } + } + + if (check_ceiling) + { + if (balloon_top > tileElement->GetBaseZ() && z < tileElement->GetClearanceZ()) + { + return true; + } + } + + } while (!(tileElement++)->IsLastForTile()); + return false; + } +} // namespace OpenRCT2 diff --git a/src/openrct2/entity/Balloon.h b/src/openrct2/entity/Balloon.h index 1e9e8e3e4f..388a809f5d 100644 --- a/src/openrct2/entity/Balloon.h +++ b/src/openrct2/entity/Balloon.h @@ -14,28 +14,28 @@ struct CoordsXYZ; struct PaintSession; -namespace OpenRCT2 -{ - class DataSerialiser; -} - namespace OpenRCT2::Drawing { enum class Colour : uint8_t; } -struct Balloon : EntityBase +namespace OpenRCT2 { - static constexpr auto cEntityType = EntityType::balloon; - uint16_t frame; - uint16_t popped; - uint8_t time_to_move; - OpenRCT2::Drawing::Colour colour; - static void Create(const CoordsXYZ& balloonPos, OpenRCT2::Drawing::Colour colour, bool isPopped); - void Update(); - void Pop(bool playSound); - void Press(); - void Serialise(OpenRCT2::DataSerialiser& stream); - void Paint(PaintSession& session, int32_t imageDirection) const; - bool Collides() const; -}; + class DataSerialiser; + + struct Balloon : EntityBase + { + static constexpr auto cEntityType = EntityType::balloon; + uint16_t frame; + uint16_t popped; + uint8_t time_to_move; + Drawing::Colour colour; + static void Create(const CoordsXYZ& balloonPos, Drawing::Colour colour, bool isPopped); + void Update(); + void Pop(bool playSound); + void Press(); + void Serialise(DataSerialiser& stream); + void Paint(PaintSession& session, int32_t imageDirection) const; + bool Collides() const; + }; +} // namespace OpenRCT2 diff --git a/src/openrct2/entity/Duck.cpp b/src/openrct2/entity/Duck.cpp index 35ef72048f..aa6786e150 100644 --- a/src/openrct2/entity/Duck.cpp +++ b/src/openrct2/entity/Duck.cpp @@ -25,11 +25,11 @@ #include #include -using namespace OpenRCT2; +namespace OpenRCT2 +{ + constexpr int32_t kDuckMaxStates = 5; -constexpr int32_t kDuckMaxStates = 5; - -// clang-format off + // clang-format off static constexpr CoordsXY kDuckMoveOffset[] = { { -1, 0 }, @@ -63,327 +63,328 @@ static constexpr uint8_t kDuckAnimationFlyAway[] = { 8, 9, 10, 11, 12, 13 }; -// clang-format on + // clang-format on -static constexpr const uint8_t* kDuckAnimations[] = { - kDuckAnimationFlyToWater, // DuckState::FlyToWater, - kDuckAnimationSwim, // DuckState::Swim, - kDuckAnimationDrink, // DuckState::Drink, - kDuckAnimationDoubleDrink, // DuckState::DoubleDrink, - kDuckAnimationFlyAway, // DuckState::FlyAway, -}; + static constexpr const uint8_t* kDuckAnimations[] = { + kDuckAnimationFlyToWater, // DuckState::FlyToWater, + kDuckAnimationSwim, // DuckState::Swim, + kDuckAnimationDrink, // DuckState::Drink, + kDuckAnimationDoubleDrink, // DuckState::DoubleDrink, + kDuckAnimationFlyAway, // DuckState::FlyAway, + }; -template<> -bool EntityBase::Is() const -{ - return Type == EntityType::duck; -} - -bool Duck::IsFlying() -{ - return this->state == DuckState::FlyAway || this->state == DuckState::FlyToWater; -} - -void Duck::Remove() -{ - Invalidate(); - getGameState().entities.EntityRemove(this); -} - -void Duck::UpdateFlyToWater() -{ - const auto currentTicks = getGameState().currentTicks; - - if ((currentTicks & 3) != 0) - return; - - frame++; - if (frame >= std::size(kDuckAnimationFlyToWater)) + template<> + bool EntityBase::Is() const { - frame = 0; + return Type == EntityType::duck; } - Invalidate(); - int32_t manhattanDistance = abs(target_x - x) + abs(target_y - y); - int32_t direction = Orientation >> 3; - auto destination = CoordsXYZ{ CoordsXY{ x, y } + kDuckMoveOffset[direction], 0 }; - int32_t manhattanDistanceN = abs(target_x - destination.x) + abs(target_y - destination.y); - - auto surfaceElement = MapGetSurfaceElementAt(CoordsXY{ target_x, target_y }); - int32_t waterHeight = surfaceElement != nullptr ? surfaceElement->GetWaterHeight() : 0; - if (waterHeight == 0) + bool Duck::IsFlying() { - state = DuckState::FlyAway; - UpdateFlyAway(); + return this->state == DuckState::FlyAway || this->state == DuckState::FlyToWater; } - else - { - destination.z = abs(z - waterHeight); - if (manhattanDistanceN <= manhattanDistance) - { - if (destination.z > manhattanDistanceN) - { - destination.z = z - 2; - if (waterHeight >= z) - { - destination.z += 4; - } - frame = 1; - } - else - { - destination.z = z; - } - MoveTo(destination); - } - else - { - if (destination.z > 4) - { - state = DuckState::FlyAway; - UpdateFlyAway(); - } - else - { - state = DuckState::Swim; - frame = 0; - UpdateSwim(); - } - } + void Duck::Remove() + { + Invalidate(); + getGameState().entities.EntityRemove(this); } -} -void Duck::UpdateSwim() -{ - const auto currentTicks = getGameState().currentTicks; - - if (((currentTicks + Id.ToUnderlying()) & 3) != 0) - return; - - uint32_t randomNumber = ScenarioRand(); - if ((randomNumber & 0xFFFF) < 0x666) + void Duck::UpdateFlyToWater() { - if (randomNumber & 0x80000000) + const auto currentTicks = getGameState().currentTicks; + + if ((currentTicks & 3) != 0) + return; + + frame++; + if (frame >= std::size(kDuckAnimationFlyToWater)) { - state = DuckState::DoubleDrink; - frame = std::numeric_limits::max(); - UpdateDoubleDrink(); + frame = 0; } - else - { - state = DuckState::Drink; - frame = std::numeric_limits::max(); - UpdateDrink(); - } - } - else - { - int32_t currentMonth = GetDate().GetMonth(); - if (currentMonth >= MONTH_SEPTEMBER && (randomNumber >> 16) < 218) + + Invalidate(); + int32_t manhattanDistance = abs(target_x - x) + abs(target_y - y); + int32_t direction = Orientation >> 3; + auto destination = CoordsXYZ{ CoordsXY{ x, y } + kDuckMoveOffset[direction], 0 }; + int32_t manhattanDistanceN = abs(target_x - destination.x) + abs(target_y - destination.y); + + auto surfaceElement = MapGetSurfaceElementAt(CoordsXY{ target_x, target_y }); + int32_t waterHeight = surfaceElement != nullptr ? surfaceElement->GetWaterHeight() : 0; + if (waterHeight == 0) { state = DuckState::FlyAway; UpdateFlyAway(); } else { - Invalidate(); - int16_t landZ = TileElementHeight({ x, y }); - int16_t waterZ = TileElementWaterHeight({ x, y }); + destination.z = abs(z - waterHeight); - if (z < landZ || waterZ == 0) + if (manhattanDistanceN <= manhattanDistance) + { + if (destination.z > manhattanDistanceN) + { + destination.z = z - 2; + if (waterHeight >= z) + { + destination.z += 4; + } + frame = 1; + } + else + { + destination.z = z; + } + MoveTo(destination); + } + else + { + if (destination.z > 4) + { + state = DuckState::FlyAway; + UpdateFlyAway(); + } + else + { + state = DuckState::Swim; + frame = 0; + UpdateSwim(); + } + } + } + } + + void Duck::UpdateSwim() + { + const auto currentTicks = getGameState().currentTicks; + + if (((currentTicks + Id.ToUnderlying()) & 3) != 0) + return; + + uint32_t randomNumber = ScenarioRand(); + if ((randomNumber & 0xFFFF) < 0x666) + { + if (randomNumber & 0x80000000) + { + state = DuckState::DoubleDrink; + frame = std::numeric_limits::max(); + UpdateDoubleDrink(); + } + else + { + state = DuckState::Drink; + frame = std::numeric_limits::max(); + UpdateDrink(); + } + } + else + { + int32_t currentMonth = GetDate().GetMonth(); + if (currentMonth >= MONTH_SEPTEMBER && (randomNumber >> 16) < 218) { state = DuckState::FlyAway; UpdateFlyAway(); } else { - z = waterZ; - randomNumber = ScenarioRand(); - if ((randomNumber & 0xFFFF) <= 0xAAA) + Invalidate(); + int16_t landZ = TileElementHeight({ x, y }); + int16_t waterZ = TileElementWaterHeight({ x, y }); + + if (z < landZ || waterZ == 0) { - randomNumber >>= 16; - Orientation = randomNumber & 0x18; + state = DuckState::FlyAway; + UpdateFlyAway(); } - - int32_t direction = Orientation >> 3; - auto destination = CoordsXYZ{ CoordsXY{ x, y } + kDuckMoveOffset[direction], 0 }; - landZ = TileElementHeight(destination); - waterZ = TileElementWaterHeight(destination); - - if (z > landZ && z == waterZ) + else { - destination.z = waterZ; - MoveTo(destination); - Invalidate(); + z = waterZ; + randomNumber = ScenarioRand(); + if ((randomNumber & 0xFFFF) <= 0xAAA) + { + randomNumber >>= 16; + Orientation = randomNumber & 0x18; + } + + int32_t direction = Orientation >> 3; + auto destination = CoordsXYZ{ CoordsXY{ x, y } + kDuckMoveOffset[direction], 0 }; + landZ = TileElementHeight(destination); + waterZ = TileElementWaterHeight(destination); + + if (z > landZ && z == waterZ) + { + destination.z = waterZ; + MoveTo(destination); + Invalidate(); + } } } } } -} -void Duck::UpdateDrink() -{ - frame++; - if (kDuckAnimationDrink[frame] == 0xFF) - { - state = DuckState::Swim; - frame = 0; - UpdateSwim(); - } - else - { - Invalidate(); - } -} - -void Duck::UpdateDoubleDrink() -{ - frame++; - if (kDuckAnimationDoubleDrink[frame] == 0xFF) - { - state = DuckState::Swim; - frame = 0; - UpdateSwim(); - } - else - { - Invalidate(); - } -} - -void Duck::UpdateFlyAway() -{ - if ((getGameState().currentTicks & 3) == 0) + void Duck::UpdateDrink() { frame++; - if (frame >= std::size(kDuckAnimationFlyAway)) + if (kDuckAnimationDrink[frame] == 0xFF) { + state = DuckState::Swim; frame = 0; - } - - Invalidate(); - - int32_t direction = Orientation >> 3; - auto destination = CoordsXYZ{ x + (kDuckMoveOffset[direction].x * 2), y + (kDuckMoveOffset[direction].y * 2), - std::min(z + 2, 496) }; - if (MapIsLocationValid(destination)) - { - MoveTo(destination); + UpdateSwim(); } else { - Remove(); + Invalidate(); } } -} -uint32_t Duck::GetFrameImage(int32_t direction) const -{ - uint32_t imageId = 0; - if (EnumValue(state) < kDuckMaxStates) + void Duck::UpdateDoubleDrink() { - // TODO: Check frame is in range - uint8_t imageOffset = kDuckAnimations[EnumValue(state)][frame]; - imageId = SPR_DUCK + (imageOffset * 4) + (direction / 8); - } - return imageId; -} - -void Duck::Create(const CoordsXY& pos) -{ - auto* duck = getGameState().entities.CreateEntity(); - if (duck == nullptr) - return; - - CoordsXY targetPos = pos; - - int32_t offsetXY = ScenarioRand() & 0x1E; - targetPos.x += offsetXY; - targetPos.y += offsetXY; - - duck->SpriteData.Width = 9; - duck->SpriteData.HeightMin = 12; - duck->SpriteData.HeightMax = 9; - duck->target_x = targetPos.x; - duck->target_y = targetPos.y; - uint8_t direction = ScenarioRand() & 3; - switch (direction) - { - case 0: - targetPos.x = GetMapSizeMaxXY().x - (ScenarioRand() & 0x3F); - break; - case 1: - targetPos.y = ScenarioRand() & 0x3F; - break; - case 2: - targetPos.x = ScenarioRand() & 0x3F; - break; - case 3: - targetPos.y = GetMapSizeMaxXY().y - (ScenarioRand() & 0x3F); - break; - } - duck->Orientation = direction << 3; - duck->MoveTo({ targetPos.x, targetPos.y, 496 }); - duck->state = DuckState::FlyToWater; - duck->frame = 0; -} - -void Duck::Update() -{ - switch (state) - { - case DuckState::FlyToWater: - UpdateFlyToWater(); - break; - case DuckState::Swim: + frame++; + if (kDuckAnimationDoubleDrink[frame] == 0xFF) + { + state = DuckState::Swim; + frame = 0; UpdateSwim(); - break; - case DuckState::Drink: - UpdateDrink(); - break; - case DuckState::DoubleDrink: - UpdateDoubleDrink(); - break; - case DuckState::FlyAway: - UpdateFlyAway(); - break; + } + else + { + Invalidate(); + } } -} -void Duck::Press() -{ - OpenRCT2::Audio::Play3D(Audio::SoundId::quack, { x, y, z }); -} - -void Duck::RemoveAll() -{ - for (auto duck : EntityList()) + void Duck::UpdateFlyAway() { - duck->Remove(); + if ((getGameState().currentTicks & 3) == 0) + { + frame++; + if (frame >= std::size(kDuckAnimationFlyAway)) + { + frame = 0; + } + + Invalidate(); + + int32_t direction = Orientation >> 3; + auto destination = CoordsXYZ{ x + (kDuckMoveOffset[direction].x * 2), y + (kDuckMoveOffset[direction].y * 2), + std::min(z + 2, 496) }; + if (MapIsLocationValid(destination)) + { + MoveTo(destination); + } + else + { + Remove(); + } + } } -} -void Duck::Serialise(DataSerialiser& stream) -{ - EntityBase::Serialise(stream); - stream << frame; - stream << target_x; - stream << target_y; - stream << state; -} - -void Duck::Paint(PaintSession& session, int32_t imageDirection) const -{ - PROFILED_FUNCTION(); - - auto& rt = session.rt; - if (rt.zoom_level > ZoomLevel{ 1 }) - return; - - uint32_t imageId = GetFrameImage(imageDirection); - if (imageId != 0) + uint32_t Duck::GetFrameImage(int32_t direction) const { - PaintAddImageAsParent(session, ImageId(imageId), { 0, 0, z }, { 1, 1, 0 }); + uint32_t imageId = 0; + if (EnumValue(state) < kDuckMaxStates) + { + // TODO: Check frame is in range + uint8_t imageOffset = kDuckAnimations[EnumValue(state)][frame]; + imageId = SPR_DUCK + (imageOffset * 4) + (direction / 8); + } + return imageId; } -} + + void Duck::Create(const CoordsXY& pos) + { + auto* duck = getGameState().entities.CreateEntity(); + if (duck == nullptr) + return; + + CoordsXY targetPos = pos; + + int32_t offsetXY = ScenarioRand() & 0x1E; + targetPos.x += offsetXY; + targetPos.y += offsetXY; + + duck->SpriteData.Width = 9; + duck->SpriteData.HeightMin = 12; + duck->SpriteData.HeightMax = 9; + duck->target_x = targetPos.x; + duck->target_y = targetPos.y; + uint8_t direction = ScenarioRand() & 3; + switch (direction) + { + case 0: + targetPos.x = GetMapSizeMaxXY().x - (ScenarioRand() & 0x3F); + break; + case 1: + targetPos.y = ScenarioRand() & 0x3F; + break; + case 2: + targetPos.x = ScenarioRand() & 0x3F; + break; + case 3: + targetPos.y = GetMapSizeMaxXY().y - (ScenarioRand() & 0x3F); + break; + } + duck->Orientation = direction << 3; + duck->MoveTo({ targetPos.x, targetPos.y, 496 }); + duck->state = DuckState::FlyToWater; + duck->frame = 0; + } + + void Duck::Update() + { + switch (state) + { + case DuckState::FlyToWater: + UpdateFlyToWater(); + break; + case DuckState::Swim: + UpdateSwim(); + break; + case DuckState::Drink: + UpdateDrink(); + break; + case DuckState::DoubleDrink: + UpdateDoubleDrink(); + break; + case DuckState::FlyAway: + UpdateFlyAway(); + break; + } + } + + void Duck::Press() + { + OpenRCT2::Audio::Play3D(Audio::SoundId::quack, { x, y, z }); + } + + void Duck::RemoveAll() + { + for (auto duck : EntityList()) + { + duck->Remove(); + } + } + + void Duck::Serialise(DataSerialiser& stream) + { + EntityBase::Serialise(stream); + stream << frame; + stream << target_x; + stream << target_y; + stream << state; + } + + void Duck::Paint(PaintSession& session, int32_t imageDirection) const + { + PROFILED_FUNCTION(); + + auto& rt = session.rt; + if (rt.zoom_level > ZoomLevel{ 1 }) + return; + + uint32_t imageId = GetFrameImage(imageDirection); + if (imageId != 0) + { + PaintAddImageAsParent(session, ImageId(imageId), { 0, 0, z }, { 1, 1, 0 }); + } + } +} // namespace OpenRCT2 diff --git a/src/openrct2/entity/Duck.h b/src/openrct2/entity/Duck.h index 67be79185a..e96ddee35a 100644 --- a/src/openrct2/entity/Duck.h +++ b/src/openrct2/entity/Duck.h @@ -17,38 +17,38 @@ struct PaintSession; namespace OpenRCT2 { class DataSerialiser; -} -struct Duck : EntityBase -{ - static constexpr auto cEntityType = EntityType::duck; - enum class DuckState : uint8_t + struct Duck : EntityBase { - FlyToWater, - Swim, - Drink, - DoubleDrink, - FlyAway, + static constexpr auto cEntityType = EntityType::duck; + enum class DuckState : uint8_t + { + FlyToWater, + Swim, + Drink, + DoubleDrink, + FlyAway, + }; + uint16_t frame; + int16_t target_x; + int16_t target_y; + DuckState state; + + static void Create(const CoordsXY& pos); + static void RemoveAll(); + void Press(); + void Update(); + uint32_t GetFrameImage(int32_t direction) const; + bool IsFlying(); + void Remove(); + void Serialise(DataSerialiser& stream); + void Paint(PaintSession& session, int32_t imageDirection) const; + + private: + void UpdateFlyToWater(); + void UpdateSwim(); + void UpdateDrink(); + void UpdateDoubleDrink(); + void UpdateFlyAway(); }; - uint16_t frame; - int16_t target_x; - int16_t target_y; - DuckState state; - - static void Create(const CoordsXY& pos); - static void RemoveAll(); - void Press(); - void Update(); - uint32_t GetFrameImage(int32_t direction) const; - bool IsFlying(); - void Remove(); - void Serialise(OpenRCT2::DataSerialiser& stream); - void Paint(PaintSession& session, int32_t imageDirection) const; - -private: - void UpdateFlyToWater(); - void UpdateSwim(); - void UpdateDrink(); - void UpdateDoubleDrink(); - void UpdateFlyAway(); -}; +} // namespace OpenRCT2 diff --git a/src/openrct2/entity/EntityBase.cpp b/src/openrct2/entity/EntityBase.cpp index c477fedd1a..5d0234965b 100644 --- a/src/openrct2/entity/EntityBase.cpp +++ b/src/openrct2/entity/EntityBase.cpp @@ -13,65 +13,66 @@ #include "../core/Guard.hpp" #include "../interface/Viewport.h" -using namespace OpenRCT2; - -// Required for GetEntity to return a default -template<> -bool EntityBase::Is() const +namespace OpenRCT2 { - return true; -} - -void EntityBase::Invalidate() -{ - if (x == kLocationNull) - return; - - ZoomLevel maxZoom{ 0 }; - switch (Type) + // Required for GetEntity to return a default + template<> + bool EntityBase::Is() const { - case EntityType::vehicle: - case EntityType::guest: - case EntityType::staff: - maxZoom = ZoomLevel{ 2 }; - break; - case EntityType::crashedVehicleParticle: - case EntityType::jumpingFountain: - maxZoom = ZoomLevel{ 0 }; - break; - case EntityType::duck: - maxZoom = ZoomLevel{ 1 }; - break; - case EntityType::steamParticle: - case EntityType::moneyEffect: - case EntityType::explosionCloud: - case EntityType::crashSplash: - case EntityType::explosionFlare: - case EntityType::balloon: - maxZoom = ZoomLevel{ 2 }; - break; - case EntityType::litter: - maxZoom = ZoomLevel{ 0 }; - break; - default: - break; + return true; } - ViewportsInvalidate(GetLocation(), SpriteData.Width, SpriteData.HeightMin, SpriteData.HeightMax, maxZoom); -} + void EntityBase::Invalidate() + { + if (x == kLocationNull) + return; -void EntityBase::Serialise(DataSerialiser& stream) -{ - stream << Type; - stream << Id; - stream << x; - stream << y; - stream << z; - stream << Orientation; -} + ZoomLevel maxZoom{ 0 }; + switch (Type) + { + case EntityType::vehicle: + case EntityType::guest: + case EntityType::staff: + maxZoom = ZoomLevel{ 2 }; + break; + case EntityType::crashedVehicleParticle: + case EntityType::jumpingFountain: + maxZoom = ZoomLevel{ 0 }; + break; + case EntityType::duck: + maxZoom = ZoomLevel{ 1 }; + break; + case EntityType::steamParticle: + case EntityType::moneyEffect: + case EntityType::explosionCloud: + case EntityType::crashSplash: + case EntityType::explosionFlare: + case EntityType::balloon: + maxZoom = ZoomLevel{ 2 }; + break; + case EntityType::litter: + maxZoom = ZoomLevel{ 0 }; + break; + default: + break; + } -// Exists only for signature -void EntityBase::Paint() const -{ - Guard::Assert(false, "You are not supposed to call this"); -} + ViewportsInvalidate(GetLocation(), SpriteData.Width, SpriteData.HeightMin, SpriteData.HeightMax, maxZoom); + } + + void EntityBase::Serialise(DataSerialiser& stream) + { + stream << Type; + stream << Id; + stream << x; + stream << y; + stream << z; + stream << Orientation; + } + + // Exists only for signature + void EntityBase::Paint() const + { + Guard::Assert(false, "You are not supposed to call this"); + } +} // namespace OpenRCT2 diff --git a/src/openrct2/entity/EntityBase.h b/src/openrct2/entity/EntityBase.h index c00231624a..6357a73c4c 100644 --- a/src/openrct2/entity/EntityBase.h +++ b/src/openrct2/entity/EntityBase.h @@ -3,101 +3,101 @@ #include "../Identifiers.h" #include "../world/Location.hpp" -enum class EntityType : uint8_t -{ - vehicle, - guest, - staff, - litter, - steamParticle, - moneyEffect, - crashedVehicleParticle, - explosionCloud, - crashSplash, - explosionFlare, - jumpingFountain, - balloon, - duck, - count, - null = 255 -}; - -struct EntitySpriteData -{ - // Width from centre of sprite to edge - uint8_t Width; - // Height from centre of sprite to bottom - uint8_t HeightMin; - // Height from centre of sprite to top - uint8_t HeightMax; - // Screen Coordinates of sprite - ScreenRect SpriteRect; -}; - namespace OpenRCT2 { class DataSerialiser; -} -struct EntityBase -{ - EntityType Type; - EntityId Id; - int32_t x; - int32_t y; - int32_t z; - EntitySpriteData SpriteData; - // Used as direction or rotation depending on the entity. - uint8_t Orientation; - uint32_t SpatialIndex; - - /** - * Moves a sprite to a new location, invalidates the current position if valid - * and also the new position. - * - * rct2: 0x0069E9D3 - */ - void MoveTo(const CoordsXYZ& newLocation); - - void MoveToAndUpdateSpatialIndex(const CoordsXYZ& newLocation); - - /** - * Sets the entity location without screen invalidation. - */ - void SetLocation(const CoordsXYZ& newLocation); - - /** - * Gets the entity current location. - */ - CoordsXYZ GetLocation() const; - - void Invalidate(); - template - bool Is() const; - template - T* As() + enum class EntityType : uint8_t { - return Is() ? reinterpret_cast(this) : nullptr; - } - template - const T* As() const + vehicle, + guest, + staff, + litter, + steamParticle, + moneyEffect, + crashedVehicleParticle, + explosionCloud, + crashSplash, + explosionFlare, + jumpingFountain, + balloon, + duck, + count, + null = 255 + }; + + struct EntitySpriteData { - return Is() ? reinterpret_cast(this) : nullptr; - } + // Width from centre of sprite to edge + uint8_t Width; + // Height from centre of sprite to bottom + uint8_t HeightMin; + // Height from centre of sprite to top + uint8_t HeightMax; + // Screen Coordinates of sprite + ScreenRect SpriteRect; + }; - template - T* cast() + struct EntityBase { - return reinterpret_cast(this); - } + EntityType Type; + EntityId Id; + int32_t x; + int32_t y; + int32_t z; + EntitySpriteData SpriteData; + // Used as direction or rotation depending on the entity. + uint8_t Orientation; + uint32_t SpatialIndex; - template - const T* cast() const - { - return reinterpret_cast(this); - } + /** + * Moves a sprite to a new location, invalidates the current position if valid + * and also the new position. + * + * rct2: 0x0069E9D3 + */ + void MoveTo(const CoordsXYZ& newLocation); - void Serialise(class OpenRCT2::DataSerialiser& stream); + void MoveToAndUpdateSpatialIndex(const CoordsXYZ& newLocation); - void Paint() const; -}; + /** + * Sets the entity location without screen invalidation. + */ + void SetLocation(const CoordsXYZ& newLocation); + + /** + * Gets the entity current location. + */ + CoordsXYZ GetLocation() const; + + void Invalidate(); + template + bool Is() const; + template + T* As() + { + return Is() ? reinterpret_cast(this) : nullptr; + } + template + const T* As() const + { + return Is() ? reinterpret_cast(this) : nullptr; + } + + template + T* cast() + { + return reinterpret_cast(this); + } + + template + const T* cast() const + { + return reinterpret_cast(this); + } + + void Serialise(class DataSerialiser& stream); + + void Paint() const; + }; +} // namespace OpenRCT2 diff --git a/src/openrct2/entity/Fountain.cpp b/src/openrct2/entity/Fountain.cpp index 33f2410c2b..0b2eefca33 100644 --- a/src/openrct2/entity/Fountain.cpp +++ b/src/openrct2/entity/Fountain.cpp @@ -23,429 +23,431 @@ #include "../world/tile_element/PathElement.h" #include "EntityRegistry.h" -using namespace OpenRCT2; - -enum class Pattern +namespace OpenRCT2 { - cyclicSquares, - continuousChasers, - bouncingPairs, - sproutingBlooms, - racingPairs, - splittingChasers, - dopeyJumpers, - fastRandomChasers, -}; - -static constexpr std::array _fountainDirectionsNegative = { - CoordsXY{ -kCoordsXYStep, 0 }, - CoordsXY{ -kCoordsXYStep, -kCoordsXYStep }, - CoordsXY{ 0, 0 }, - CoordsXY{ -kCoordsXYStep, 0 }, - CoordsXY{ 0, 0 }, - CoordsXY{ 0, -kCoordsXYStep }, - CoordsXY{ 0, -kCoordsXYStep }, - CoordsXY{ -kCoordsXYStep, -kCoordsXYStep }, -}; - -static constexpr std::array _fountainDirectionsPositive = { - CoordsXY{ kCoordsXYStep, 0 }, - CoordsXY{ 0, 0 }, - CoordsXY{ 0, kCoordsXYStep }, - CoordsXY{ kCoordsXYStep, kCoordsXYStep }, - CoordsXY{ kCoordsXYStep, kCoordsXYStep }, - CoordsXY{ kCoordsXYStep, 0 }, - CoordsXY{ 0, 0 }, - CoordsXY{ 0, kCoordsXYStep }, -}; -static constexpr auto kFountainChanceOfStoppingEdgeMode = 0x3333; // 0.200 -static constexpr auto kFountainChanceOfStoppingRandomMode = 0x2000; // 0.125 - -// rct2: 0x0097F040 -const uint8_t _fountainDirections[] = { - 0, 1, 2, 3, 0, 1, 2, 3, -}; - -// rct2: 0x0097F048 -const FountainFlags _fountainDirectionFlags[] = { - {}, {}, FountainFlag::direction, FountainFlag::direction, FountainFlag::direction, FountainFlag::direction, {}, {}, -}; - -// rct2: 0x0097F050 -const FountainFlags _fountainPatternFlags[] = { - { FountainFlag::terminate }, // cyclicSquares - { FountainFlag::fast, FountainFlag::goToEdge }, // continuousChasers - { FountainFlag::bounce }, // bouncingPairs - { FountainFlag::fast, FountainFlag::split }, // sproutingBlooms - { FountainFlag::goToEdge }, // racingPairs - { FountainFlag::fast, FountainFlag::goToEdge, FountainFlag::split }, // splittingChasers - {}, // dopeyJumpers - { FountainFlag::fast }, // fastRandomChasers -}; - -template<> -bool EntityBase::Is() const -{ - return Type == EntityType::jumpingFountain; -} - -void JumpingFountain::StartAnimation(const JumpingFountainType newType, const CoordsXY& newLoc, const TileElement* tileElement) -{ - const auto currentTicks = getGameState().currentTicks; - - int32_t randomIndex; - auto newZ = tileElement->GetBaseZ(); - - // Change pattern approximately every 51 seconds - uint32_t pattern = (currentTicks >> 11) & 7; - switch (static_cast(pattern)) + enum class Pattern { - case Pattern::cyclicSquares: - // 0, 1, 2, 3 - for (int32_t i = 0; i < kNumOrthogonalDirections; i++) - { - Create( - newType, { newLoc + _fountainDirectionsPositive[i], newZ }, _fountainDirections[i], - _fountainDirectionFlags[i] | _fountainPatternFlags[pattern], 0); - } - break; - case Pattern::bouncingPairs: - // random [0, 2 or 1, 3] - randomIndex = ScenarioRand() & 1; - for (int32_t i = randomIndex; i < kNumOrthogonalDirections; i += 2) - { - Create( - newType, { newLoc + _fountainDirectionsPositive[i], newZ }, _fountainDirections[i], - _fountainDirectionFlags[i] | _fountainPatternFlags[pattern], 0); - } - break; - case Pattern::racingPairs: - // random [0 - 3 and 4 - 7] - randomIndex = ScenarioRand() & 3; - Create( - newType, { newLoc + _fountainDirectionsPositive[randomIndex], newZ }, _fountainDirections[randomIndex], - _fountainDirectionFlags[randomIndex] | _fountainPatternFlags[pattern], 0); - randomIndex += 4; - Create( - newType, { newLoc + _fountainDirectionsPositive[randomIndex], newZ }, _fountainDirections[randomIndex], - _fountainDirectionFlags[randomIndex] | _fountainPatternFlags[pattern], 0); - break; - default: - // random [0 - 7] - randomIndex = ScenarioRand() & 7; - Create( - newType, { newLoc + _fountainDirectionsPositive[randomIndex], newZ }, _fountainDirections[randomIndex], - _fountainDirectionFlags[randomIndex] | _fountainPatternFlags[pattern], 0); - break; - } -} + cyclicSquares, + continuousChasers, + bouncingPairs, + sproutingBlooms, + racingPairs, + splittingChasers, + dopeyJumpers, + fastRandomChasers, + }; -void JumpingFountain::Create( - const JumpingFountainType newType, const CoordsXYZ& newLoc, const int32_t direction, const FountainFlags newFlags, - const int32_t iteration) -{ - auto* jumpingFountain = getGameState().entities.CreateEntity(); - if (jumpingFountain != nullptr) - { - jumpingFountain->Iteration = iteration; - jumpingFountain->fountainFlags = newFlags; - jumpingFountain->Orientation = direction << 3; - jumpingFountain->SpriteData.Width = 33; - jumpingFountain->SpriteData.HeightMin = 36; - jumpingFountain->SpriteData.HeightMax = 12; - jumpingFountain->MoveTo(newLoc); - jumpingFountain->FountainType = newType; - jumpingFountain->NumTicksAlive = 0; - jumpingFountain->frame = 0; - } -} + static constexpr std::array _fountainDirectionsNegative = { + CoordsXY{ -kCoordsXYStep, 0 }, + CoordsXY{ -kCoordsXYStep, -kCoordsXYStep }, + CoordsXY{ 0, 0 }, + CoordsXY{ -kCoordsXYStep, 0 }, + CoordsXY{ 0, 0 }, + CoordsXY{ 0, -kCoordsXYStep }, + CoordsXY{ 0, -kCoordsXYStep }, + CoordsXY{ -kCoordsXYStep, -kCoordsXYStep }, + }; -void JumpingFountain::Update() -{ - NumTicksAlive++; - // Originally this would not update the frame on the following - // ticks: 1, 3, 6, 9, 11, 14, 17, 19, 22, 25 - // This change was to simplify the code base. There is a small increase - // in speed of the fountain jump because of this change. - if (NumTicksAlive % 3 == 0) + static constexpr std::array _fountainDirectionsPositive = { + CoordsXY{ kCoordsXYStep, 0 }, + CoordsXY{ 0, 0 }, + CoordsXY{ 0, kCoordsXYStep }, + CoordsXY{ kCoordsXYStep, kCoordsXYStep }, + CoordsXY{ kCoordsXYStep, kCoordsXYStep }, + CoordsXY{ kCoordsXYStep, 0 }, + CoordsXY{ 0, 0 }, + CoordsXY{ 0, kCoordsXYStep }, + }; + static constexpr auto kFountainChanceOfStoppingEdgeMode = 0x3333; // 0.200 + static constexpr auto kFountainChanceOfStoppingRandomMode = 0x2000; // 0.125 + + // rct2: 0x0097F040 + const uint8_t _fountainDirections[] = { + 0, 1, 2, 3, 0, 1, 2, 3, + }; + + // rct2: 0x0097F048 + const FountainFlags _fountainDirectionFlags[] = { + {}, {}, FountainFlag::direction, FountainFlag::direction, FountainFlag::direction, FountainFlag::direction, {}, {}, + }; + + // rct2: 0x0097F050 + const FountainFlags _fountainPatternFlags[] = { + { FountainFlag::terminate }, // cyclicSquares + { FountainFlag::fast, FountainFlag::goToEdge }, // continuousChasers + { FountainFlag::bounce }, // bouncingPairs + { FountainFlag::fast, FountainFlag::split }, // sproutingBlooms + { FountainFlag::goToEdge }, // racingPairs + { FountainFlag::fast, FountainFlag::goToEdge, FountainFlag::split }, // splittingChasers + {}, // dopeyJumpers + { FountainFlag::fast }, // fastRandomChasers + }; + + template<> + bool EntityBase::Is() const { - return; + return Type == EntityType::jumpingFountain; } - Invalidate(); - frame++; - - switch (FountainType) + void JumpingFountain::StartAnimation( + const JumpingFountainType newType, const CoordsXY& newLoc, const TileElement* tileElement) { - case JumpingFountainType::Water: - if (frame == 11 && fountainFlags.has(FountainFlag::fast)) - { - AdvanceAnimation(); - } - if (frame == 16 && !fountainFlags.has(FountainFlag::fast)) - { - AdvanceAnimation(); - } - break; - case JumpingFountainType::Snow: - if (frame == 16) - { - AdvanceAnimation(); - } - break; - default: - break; - } + const auto currentTicks = getGameState().currentTicks; - if (frame == 16) - { - getGameState().entities.EntityRemove(this); - } -} + int32_t randomIndex; + auto newZ = tileElement->GetBaseZ(); -JumpingFountainType JumpingFountain::GetType() const -{ - return FountainType; -} - -void JumpingFountain::AdvanceAnimation() -{ - const JumpingFountainType newType = GetType(); - const int32_t direction = (Orientation >> 3) & 7; - const CoordsXY newLoc = CoordsXY{ x, y } + CoordsDirectionDelta[direction]; - - int32_t availableDirections = 0; - for (uint32_t i = 0; i < _fountainDirectionsNegative.size(); i++) - { - if (IsJumpingFountain(newType, { newLoc + _fountainDirectionsNegative[i], z })) + // Change pattern approximately every 51 seconds + uint32_t pattern = (currentTicks >> 11) & 7; + switch (static_cast(pattern)) { - availableDirections |= 1 << i; + case Pattern::cyclicSquares: + // 0, 1, 2, 3 + for (int32_t i = 0; i < kNumOrthogonalDirections; i++) + { + Create( + newType, { newLoc + _fountainDirectionsPositive[i], newZ }, _fountainDirections[i], + _fountainDirectionFlags[i] | _fountainPatternFlags[pattern], 0); + } + break; + case Pattern::bouncingPairs: + // random [0, 2 or 1, 3] + randomIndex = ScenarioRand() & 1; + for (int32_t i = randomIndex; i < kNumOrthogonalDirections; i += 2) + { + Create( + newType, { newLoc + _fountainDirectionsPositive[i], newZ }, _fountainDirections[i], + _fountainDirectionFlags[i] | _fountainPatternFlags[pattern], 0); + } + break; + case Pattern::racingPairs: + // random [0 - 3 and 4 - 7] + randomIndex = ScenarioRand() & 3; + Create( + newType, { newLoc + _fountainDirectionsPositive[randomIndex], newZ }, _fountainDirections[randomIndex], + _fountainDirectionFlags[randomIndex] | _fountainPatternFlags[pattern], 0); + randomIndex += 4; + Create( + newType, { newLoc + _fountainDirectionsPositive[randomIndex], newZ }, _fountainDirections[randomIndex], + _fountainDirectionFlags[randomIndex] | _fountainPatternFlags[pattern], 0); + break; + default: + // random [0 - 7] + randomIndex = ScenarioRand() & 7; + Create( + newType, { newLoc + _fountainDirectionsPositive[randomIndex], newZ }, _fountainDirections[randomIndex], + _fountainDirectionFlags[randomIndex] | _fountainPatternFlags[pattern], 0); + break; } } - if (availableDirections == 0) + void JumpingFountain::Create( + const JumpingFountainType newType, const CoordsXYZ& newLoc, const int32_t direction, const FountainFlags newFlags, + const int32_t iteration) { - return; + auto* jumpingFountain = getGameState().entities.CreateEntity(); + if (jumpingFountain != nullptr) + { + jumpingFountain->Iteration = iteration; + jumpingFountain->fountainFlags = newFlags; + jumpingFountain->Orientation = direction << 3; + jumpingFountain->SpriteData.Width = 33; + jumpingFountain->SpriteData.HeightMin = 36; + jumpingFountain->SpriteData.HeightMax = 12; + jumpingFountain->MoveTo(newLoc); + jumpingFountain->FountainType = newType; + jumpingFountain->NumTicksAlive = 0; + jumpingFountain->frame = 0; + } } - if (fountainFlags.has(FountainFlag::terminate)) + void JumpingFountain::Update() { - return; + NumTicksAlive++; + // Originally this would not update the frame on the following + // ticks: 1, 3, 6, 9, 11, 14, 17, 19, 22, 25 + // This change was to simplify the code base. There is a small increase + // in speed of the fountain jump because of this change. + if (NumTicksAlive % 3 == 0) + { + return; + } + + Invalidate(); + frame++; + + switch (FountainType) + { + case JumpingFountainType::Water: + if (frame == 11 && fountainFlags.has(FountainFlag::fast)) + { + AdvanceAnimation(); + } + if (frame == 16 && !fountainFlags.has(FountainFlag::fast)) + { + AdvanceAnimation(); + } + break; + case JumpingFountainType::Snow: + if (frame == 16) + { + AdvanceAnimation(); + } + break; + default: + break; + } + + if (frame == 16) + { + getGameState().entities.EntityRemove(this); + } } - if (fountainFlags.has(FountainFlag::goToEdge)) + JumpingFountainType JumpingFountain::GetType() const { - GoToEdge({ newLoc, z }, availableDirections); - return; + return FountainType; } - if (fountainFlags.has(FountainFlag::bounce)) + void JumpingFountain::AdvanceAnimation() { - Bounce({ newLoc, z }, availableDirections); - return; + const JumpingFountainType newType = GetType(); + const int32_t direction = (Orientation >> 3) & 7; + const CoordsXY newLoc = CoordsXY{ x, y } + CoordsDirectionDelta[direction]; + + int32_t availableDirections = 0; + for (uint32_t i = 0; i < _fountainDirectionsNegative.size(); i++) + { + if (IsJumpingFountain(newType, { newLoc + _fountainDirectionsNegative[i], z })) + { + availableDirections |= 1 << i; + } + } + + if (availableDirections == 0) + { + return; + } + + if (fountainFlags.has(FountainFlag::terminate)) + { + return; + } + + if (fountainFlags.has(FountainFlag::goToEdge)) + { + GoToEdge({ newLoc, z }, availableDirections); + return; + } + + if (fountainFlags.has(FountainFlag::bounce)) + { + Bounce({ newLoc, z }, availableDirections); + return; + } + + if (fountainFlags.has(FountainFlag::split)) + { + Split({ newLoc, z }, availableDirections); + return; + } + + Random({ newLoc, z }, availableDirections); } - if (fountainFlags.has(FountainFlag::split)) + bool JumpingFountain::IsJumpingFountain(const JumpingFountainType newType, const CoordsXYZ& newLoc) { - Split({ newLoc, z }, availableDirections); - return; - } + const int32_t pathAdditionFlagMask = newType == JumpingFountainType::Snow ? PATH_ADDITION_FLAG_JUMPING_FOUNTAIN_SNOW + : PATH_ADDITION_FLAG_JUMPING_FOUNTAIN_WATER; - Random({ newLoc, z }, availableDirections); -} + TileElement* tileElement = MapGetFirstElementAt(newLoc); + if (tileElement == nullptr) + return false; + do + { + if (tileElement->GetType() != TileElementType::Path) + continue; + if (tileElement->GetBaseZ() != newLoc.z) + continue; + if (tileElement->AsPath()->AdditionIsGhost()) + continue; + if (!tileElement->AsPath()->HasAddition()) + continue; -bool JumpingFountain::IsJumpingFountain(const JumpingFountainType newType, const CoordsXYZ& newLoc) -{ - const int32_t pathAdditionFlagMask = newType == JumpingFountainType::Snow ? PATH_ADDITION_FLAG_JUMPING_FOUNTAIN_SNOW - : PATH_ADDITION_FLAG_JUMPING_FOUNTAIN_WATER; + auto* pathAdditionEntry = tileElement->AsPath()->GetAdditionEntry(); + if (pathAdditionEntry != nullptr && pathAdditionEntry->flags & pathAdditionFlagMask) + { + return true; + } + } while (!(tileElement++)->IsLastForTile()); - TileElement* tileElement = MapGetFirstElementAt(newLoc); - if (tileElement == nullptr) return false; - do - { - if (tileElement->GetType() != TileElementType::Path) - continue; - if (tileElement->GetBaseZ() != newLoc.z) - continue; - if (tileElement->AsPath()->AdditionIsGhost()) - continue; - if (!tileElement->AsPath()->HasAddition()) - continue; - - auto* pathAdditionEntry = tileElement->AsPath()->GetAdditionEntry(); - if (pathAdditionEntry != nullptr && pathAdditionEntry->flags & pathAdditionFlagMask) - { - return true; - } - } while (!(tileElement++)->IsLastForTile()); - - return false; -} - -void JumpingFountain::GoToEdge(const CoordsXYZ& newLoc, const int32_t availableDirections) const -{ - int32_t direction = (Orientation >> 3) << 1; - if (availableDirections & (1 << direction)) - { - CreateNext(newLoc, direction); - return; } - direction++; - if (availableDirections & (1 << direction)) + void JumpingFountain::GoToEdge(const CoordsXYZ& newLoc, const int32_t availableDirections) const { - CreateNext(newLoc, direction); - return; - } - - const uint32_t randomIndex = ScenarioRand(); - if ((randomIndex & 0xFFFF) < kFountainChanceOfStoppingEdgeMode) - { - return; - } - - if (fountainFlags.has(FountainFlag::split)) - { - Split(newLoc, availableDirections); - return; - } - - direction = randomIndex & 7; - while (!(availableDirections & (1 << direction))) - { - direction = (direction + 1) & 7; - } - - CreateNext(newLoc, direction); -} - -void JumpingFountain::Bounce(const CoordsXYZ& newLoc, const int32_t availableDirections) -{ - Iteration++; - if (Iteration < 8) - { - int32_t direction = ((Orientation >> 3) ^ 2) << 1; + int32_t direction = (Orientation >> 3) << 1; if (availableDirections & (1 << direction)) { CreateNext(newLoc, direction); + return; } - else + + direction++; + if (availableDirections & (1 << direction)) { - direction++; - if (availableDirections & (1 << direction)) - { - CreateNext(newLoc, direction); - } + CreateNext(newLoc, direction); + return; } - } -} -void JumpingFountain::Split(const CoordsXYZ& newLoc, int32_t availableDirections) const -{ - if (Iteration < 3) - { - const auto newType = GetType(); - int32_t direction = ((Orientation >> 3) ^ 2) << 1; - availableDirections &= ~(1 << direction); - availableDirections &= ~(1 << (direction + 1)); - - for (direction = 0; direction < 8; direction++) + const uint32_t randomIndex = ScenarioRand(); + if ((randomIndex & 0xFFFF) < kFountainChanceOfStoppingEdgeMode) { - if (availableDirections & (1 << direction)) - { - auto copiedFlags = fountainFlags; - copiedFlags.unset(FountainFlag::direction); - Create(newType, newLoc, direction >> 1, copiedFlags, Iteration + 1); - } - direction++; - if (availableDirections & (1 << direction)) - { - auto copiedFlags = fountainFlags; - copiedFlags.set(FountainFlag::direction); - Create(newType, newLoc, direction >> 1, copiedFlags, Iteration + 1); - } + return; } - } -} -void JumpingFountain::Random(const CoordsXYZ& newLoc, int32_t availableDirections) const -{ - const uint32_t randomIndex = ScenarioRand(); - if ((randomIndex & 0xFFFF) >= kFountainChanceOfStoppingRandomMode) - { - int32_t direction = randomIndex & 7; + if (fountainFlags.has(FountainFlag::split)) + { + Split(newLoc, availableDirections); + return; + } + + direction = randomIndex & 7; while (!(availableDirections & (1 << direction))) { direction = (direction + 1) & 7; } + CreateNext(newLoc, direction); } -} -void JumpingFountain::CreateNext(const CoordsXYZ& newLoc, int32_t direction) const -{ - const auto newType = GetType(); - auto newFlags = fountainFlags; - newFlags.set(FountainFlag::direction, !!(direction & 1)); - Create(newType, newLoc, direction >> 1, newFlags, Iteration); -} - -void JumpingFountain::Serialise(DataSerialiser& stream) -{ - EntityBase::Serialise(stream); - stream << frame; - stream << FountainType; - stream << NumTicksAlive; - stream << fountainFlags.holder; - stream << TargetX; - stream << TargetY; - stream << Iteration; -} - -void JumpingFountain::Paint(PaintSession& session, int32_t imageDirection) const -{ - PROFILED_FUNCTION(); - - // TODO: Move into SpriteIds.h - constexpr uint32_t kJumpingFountainSnowBaseImage = 23037; - constexpr uint32_t kJumpingFountainWaterBaseImage = 22973; - - auto& rt = session.rt; - if (rt.zoom_level > ZoomLevel{ 0 }) + void JumpingFountain::Bounce(const CoordsXYZ& newLoc, const int32_t availableDirections) { - return; + Iteration++; + if (Iteration < 8) + { + int32_t direction = ((Orientation >> 3) ^ 2) << 1; + if (availableDirections & (1 << direction)) + { + CreateNext(newLoc, direction); + } + else + { + direction++; + if (availableDirections & (1 << direction)) + { + CreateNext(newLoc, direction); + } + } + } } - uint16_t height = z + 6; - imageDirection = imageDirection / 8; - - // Fountain is firing anti clockwise - bool reversed = fountainFlags.has(FountainFlag::direction); - // Fountain rotation - bool rotated = (Orientation / 16) & 1; - bool isAntiClockwise = (imageDirection / 2) & 1; // Clockwise or Anti-clockwise - - // These cancel each other out - if (reversed != rotated) + void JumpingFountain::Split(const CoordsXYZ& newLoc, int32_t availableDirections) const { - isAntiClockwise = !isAntiClockwise; + if (Iteration < 3) + { + const auto newType = GetType(); + int32_t direction = ((Orientation >> 3) ^ 2) << 1; + availableDirections &= ~(1 << direction); + availableDirections &= ~(1 << (direction + 1)); + + for (direction = 0; direction < 8; direction++) + { + if (availableDirections & (1 << direction)) + { + auto copiedFlags = fountainFlags; + copiedFlags.unset(FountainFlag::direction); + Create(newType, newLoc, direction >> 1, copiedFlags, Iteration + 1); + } + direction++; + if (availableDirections & (1 << direction)) + { + auto copiedFlags = fountainFlags; + copiedFlags.set(FountainFlag::direction); + Create(newType, newLoc, direction >> 1, copiedFlags, Iteration + 1); + } + } + } } - uint32_t baseImageId = (FountainType == JumpingFountainType::Snow) ? kJumpingFountainSnowBaseImage - : kJumpingFountainWaterBaseImage; - auto imageId = ImageId(baseImageId + imageDirection * 16 + frame); - constexpr std::array antiClockWiseBoundingBoxes = { - CoordsXY{ -kCoordsXYStep, -3 }, - CoordsXY{ 0, -3 }, - }; - constexpr std::array clockWiseBoundingBoxes = { - CoordsXY{ -kCoordsXYStep, 3 }, - CoordsXY{ 0, 3 }, - }; + void JumpingFountain::Random(const CoordsXYZ& newLoc, int32_t availableDirections) const + { + const uint32_t randomIndex = ScenarioRand(); + if ((randomIndex & 0xFFFF) >= kFountainChanceOfStoppingRandomMode) + { + int32_t direction = randomIndex & 7; + while (!(availableDirections & (1 << direction))) + { + direction = (direction + 1) & 7; + } + CreateNext(newLoc, direction); + } + } - auto bb = isAntiClockwise ? antiClockWiseBoundingBoxes : clockWiseBoundingBoxes; + void JumpingFountain::CreateNext(const CoordsXYZ& newLoc, int32_t direction) const + { + const auto newType = GetType(); + auto newFlags = fountainFlags; + newFlags.set(FountainFlag::direction, !!(direction & 1)); + Create(newType, newLoc, direction >> 1, newFlags, Iteration); + } - PaintAddImageAsParentRotated( - session, imageDirection, imageId, { 0, 0, height }, { { bb[imageDirection & 1], height }, { 32, 1, 3 } }); -} + void JumpingFountain::Serialise(DataSerialiser& stream) + { + EntityBase::Serialise(stream); + stream << frame; + stream << FountainType; + stream << NumTicksAlive; + stream << fountainFlags.holder; + stream << TargetX; + stream << TargetY; + stream << Iteration; + } + + void JumpingFountain::Paint(PaintSession& session, int32_t imageDirection) const + { + PROFILED_FUNCTION(); + + // TODO: Move into SpriteIds.h + constexpr uint32_t kJumpingFountainSnowBaseImage = 23037; + constexpr uint32_t kJumpingFountainWaterBaseImage = 22973; + + auto& rt = session.rt; + if (rt.zoom_level > ZoomLevel{ 0 }) + { + return; + } + + uint16_t height = z + 6; + imageDirection = imageDirection / 8; + + // Fountain is firing anti clockwise + bool reversed = fountainFlags.has(FountainFlag::direction); + // Fountain rotation + bool rotated = (Orientation / 16) & 1; + bool isAntiClockwise = (imageDirection / 2) & 1; // Clockwise or Anti-clockwise + + // These cancel each other out + if (reversed != rotated) + { + isAntiClockwise = !isAntiClockwise; + } + + uint32_t baseImageId = (FountainType == JumpingFountainType::Snow) ? kJumpingFountainSnowBaseImage + : kJumpingFountainWaterBaseImage; + auto imageId = ImageId(baseImageId + imageDirection * 16 + frame); + constexpr std::array antiClockWiseBoundingBoxes = { + CoordsXY{ -kCoordsXYStep, -3 }, + CoordsXY{ 0, -3 }, + }; + constexpr std::array clockWiseBoundingBoxes = { + CoordsXY{ -kCoordsXYStep, 3 }, + CoordsXY{ 0, 3 }, + }; + + auto bb = isAntiClockwise ? antiClockWiseBoundingBoxes : clockWiseBoundingBoxes; + + PaintAddImageAsParentRotated( + session, imageDirection, imageId, { 0, 0, height }, { { bb[imageDirection & 1], height }, { 32, 1, 3 } }); + } +} // namespace OpenRCT2 diff --git a/src/openrct2/entity/Fountain.h b/src/openrct2/entity/Fountain.h index 2244138231..774c4da97d 100644 --- a/src/openrct2/entity/Fountain.h +++ b/src/openrct2/entity/Fountain.h @@ -31,40 +31,39 @@ namespace OpenRCT2 using FountainFlags = FlagHolder; struct TileElement; + + enum class JumpingFountainType : uint8_t + { + Water, + Snow + }; + + struct JumpingFountain : EntityBase + { + static constexpr auto cEntityType = EntityType::jumpingFountain; + + uint16_t frame; + JumpingFountainType FountainType; + uint8_t NumTicksAlive; + FountainFlags fountainFlags; + int16_t TargetX; + int16_t TargetY; + uint16_t Iteration; + void Update(); + static void StartAnimation(JumpingFountainType newType, const CoordsXY& newLoc, const TileElement* tileElement); + void Serialise(DataSerialiser& stream); + void Paint(PaintSession& session, int32_t imageDirection) const; + + private: + JumpingFountainType GetType() const; + void AdvanceAnimation(); + void GoToEdge(const CoordsXYZ& newLoc, int32_t availableDirections) const; + void Bounce(const CoordsXYZ& newLoc, int32_t availableDirections); + void Split(const CoordsXYZ& newLoc, int32_t availableDirections) const; + void Random(const CoordsXYZ& newLoc, int32_t availableDirections) const; + void CreateNext(const CoordsXYZ& newLoc, int32_t direction) const; + static void Create( + JumpingFountainType newType, const CoordsXYZ& newLoc, int32_t direction, FountainFlags newFlags, int32_t iteration); + static bool IsJumpingFountain(JumpingFountainType newType, const CoordsXYZ& newLoc); + }; } // namespace OpenRCT2 - -enum class JumpingFountainType : uint8_t -{ - Water, - Snow -}; - -struct JumpingFountain : EntityBase -{ - static constexpr auto cEntityType = EntityType::jumpingFountain; - - uint16_t frame; - JumpingFountainType FountainType; - uint8_t NumTicksAlive; - OpenRCT2::FountainFlags fountainFlags; - int16_t TargetX; - int16_t TargetY; - uint16_t Iteration; - void Update(); - static void StartAnimation(JumpingFountainType newType, const CoordsXY& newLoc, const OpenRCT2::TileElement* tileElement); - void Serialise(OpenRCT2::DataSerialiser& stream); - void Paint(PaintSession& session, int32_t imageDirection) const; - -private: - JumpingFountainType GetType() const; - void AdvanceAnimation(); - void GoToEdge(const CoordsXYZ& newLoc, int32_t availableDirections) const; - void Bounce(const CoordsXYZ& newLoc, int32_t availableDirections); - void Split(const CoordsXYZ& newLoc, int32_t availableDirections) const; - void Random(const CoordsXYZ& newLoc, int32_t availableDirections) const; - void CreateNext(const CoordsXYZ& newLoc, int32_t direction) const; - static void Create( - JumpingFountainType newType, const CoordsXYZ& newLoc, int32_t direction, OpenRCT2::FountainFlags newFlags, - int32_t iteration); - static bool IsJumpingFountain(JumpingFountainType newType, const CoordsXYZ& newLoc); -}; diff --git a/src/openrct2/entity/Guest.cpp b/src/openrct2/entity/Guest.cpp index a397142999..7f91156816 100644 --- a/src/openrct2/entity/Guest.cpp +++ b/src/openrct2/entity/Guest.cpp @@ -80,2148 +80,2013 @@ #include #include -using namespace OpenRCT2; - -static const uint8_t kTicksToGoUpSpiralSlide = 30; - -// Locations of the spiral slide platform that a peep walks from the entrance of the ride to the -// entrance of the slide. Up to 4 waypoints for each 4 sides that an ride entrance can be located -// and 4 different rotations of the ride. 4 * 4 * 4 = 64 locations. -// clang-format off -static constexpr CoordsXY kSpiralSlideWalkingPath[64] = { - { 56, 8 }, - { 8, 8 }, - { 8, 32 }, - { 32, 32 }, - { 8, 8 }, - { 8, 8 }, - { 8, 32 }, - { 32, 32 }, - { 8, 32 }, - { 8, 32 }, - { 8, 32 }, - { 32, 32 }, - { 8, 56 }, - { 8, 32 }, - { 8, 32 }, - { 32, 32 }, - { 56, 24 }, - { 32, 24 }, - { 32, 24 }, - { 32, 0 }, - { 56, -24 }, - { 56, 24 }, - { 32, 24 }, - { 32, 0 }, - { 8, 24 }, - { 32, 24 }, - { 32, 24 }, - { 32, 0 }, - { 32, 24 }, - { 32, 24 }, - { 32, 24 }, - { 32, 0 }, - { 24, 0 }, - { 24, 0 }, - { 24, 0 }, - { 0, 0 }, - { 24, -24 }, - { 24, 0 }, - { 24, 0 }, - { 0, 0 }, - { -24, -24 }, - { 24, -24 }, - { 24, 0 }, - { 0, 0 }, - { 24, 24 }, - { 24, 0 }, - { 24, 0 }, - { 0, 0 }, - { 24, 8 }, - { 0, 8 }, - { 0, 8 }, - { 0, 32 }, - { 0, 8 }, - { 0, 8 }, - { 0, 8 }, - { 0, 32 }, - { -24, 8 }, - { 0, 8 }, - { 0, 8 }, - { 0, 32 }, - { -24, 56 }, - { -24, 8 }, - { 0, 8 }, - { 0, 32 }, -}; - -/** rct2: 0x00981F4C, 0x00981F4E */ -static constexpr CoordsXY kWatchingPositionOffsets[] = { - { 7, 5 }, - { 5, 25 }, - { 25, 5 }, - { 5, 7 }, - { 7, 9 }, - { 9, 25 }, - { 25, 9 }, - { 9, 7 }, - { 7, 23 }, - { 23, 25 }, - { 25, 23 }, - { 23, 7 }, - { 7, 27 }, - { 27, 25 }, - { 25, 27 }, - { 27, 7 }, - { 7, 0 }, - { 0, 25 }, - { 25, 0 }, - { 0, 7 }, - { 7, 0 }, - { 0, 25 }, - { 25, 0 }, - { 0, 7 }, - { 7, 0 }, - { 0, 25 }, - { 25, 0 }, - { 0, 7 }, - { 7, 0 }, - { 0, 25 }, - { 25, 0 }, - { 0, 7 }, -}; - -static constexpr RideRating_t NauseaMaximumThresholds[] = { - 300, - 600, - 800, - 1000, -}; - -/** rct2: 009823AC */ -static constexpr PeepThoughtType kCrowdedThoughts[] = { - PeepThoughtType::Lost, - PeepThoughtType::Tired, - PeepThoughtType::BadLitter, - PeepThoughtType::Hungry, - PeepThoughtType::Thirsty, - PeepThoughtType::VeryClean, - PeepThoughtType::Crowded, - PeepThoughtType::Scenery, - PeepThoughtType::VeryClean, - PeepThoughtType::Music, - PeepThoughtType::Watched, - PeepThoughtType::NotHungry, - PeepThoughtType::NotThirsty, - PeepThoughtType::Toilet, - PeepThoughtType::None, - PeepThoughtType::None, -}; - -static constexpr const char *gPeepEasterEggNames[] = { - "MICHAEL SCHUMACHER", - "JACQUES VILLENEUVE", - "DAMON HILL", - "MR BEAN", - "CHRIS SAWYER", - "KATIE BRAYSHAW", - "MELANIE WARN", - "SIMON FOSTER", - "JOHN WARDLEY", - "LISA STIRLING", - "DONALD MACRAE", - "KATHERINE MCGOWAN", - "FRANCES MCGOWAN", - "CORINA MASSOURA", - "CAROL YOUNG", - "MIA SHERIDAN", - "KATIE RODGER", - "EMMA GARRELL", - "JOANNE BARTON", - "FELICITY ANDERSON", - "KATIE SMITH", - "EILIDH BELL", - "NANCY STILLWAGON", - "DAVID ELLIS", -}; -// clang-format on - -// Flags used by PeepThoughtToActionMap -enum PeepThoughtToActionFlag : uint8_t +namespace OpenRCT2 { - PEEP_THOUGHT_ACTION_NO_FLAGS = 0, - PEEP_THOUGHT_ACTION_FLAG_RIDE = (1 << 0), - PEEP_THOUGHT_ACTION_FLAG_SHOP_ITEM_SINGULAR = (1 << 1), - PEEP_THOUGHT_ACTION_FLAG_SHOP_ITEM_INDEFINITE = (1 << 2), -}; + static const uint8_t kTicksToGoUpSpiralSlide = 30; -/** rct2: 0x00981DB0 */ -static struct -{ - PeepActionType action; - PeepThoughtToActionFlag flags; -} PeepThoughtToActionMap[] = { - { PeepActionType::shakeHead, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::emptyPockets, PEEP_THOUGHT_ACTION_NO_FLAGS }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_NO_FLAGS }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_NO_FLAGS }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::wow, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_SHOP_ITEM_SINGULAR }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_NO_FLAGS }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_SHOP_ITEM_INDEFINITE }, - { PeepActionType::shakeHead, PEEP_THOUGHT_ACTION_FLAG_SHOP_ITEM_INDEFINITE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_NO_FLAGS }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_NO_FLAGS }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_NO_FLAGS }, - { PeepActionType::wave, PEEP_THOUGHT_ACTION_NO_FLAGS }, - { PeepActionType::joy, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::checkTime, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_NO_FLAGS }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_NO_FLAGS }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_NO_FLAGS }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_NO_FLAGS }, - { PeepActionType::wave, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_NO_FLAGS }, - { PeepActionType::wave, PEEP_THOUGHT_ACTION_NO_FLAGS }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::disgust, PEEP_THOUGHT_ACTION_NO_FLAGS }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_NO_FLAGS }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_NO_FLAGS }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_NO_FLAGS }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_NO_FLAGS }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_NO_FLAGS }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_NO_FLAGS }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_NO_FLAGS }, - { PeepActionType::beingWatched, PEEP_THOUGHT_ACTION_NO_FLAGS }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_NO_FLAGS }, - { PeepActionType::shakeHead, PEEP_THOUGHT_ACTION_NO_FLAGS }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_NO_FLAGS }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_NO_FLAGS }, - { PeepActionType::joy, PEEP_THOUGHT_ACTION_NO_FLAGS }, - { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, -}; + // Locations of the spiral slide platform that a peep walks from the entrance of the ride to the + // entrance of the slide. Up to 4 waypoints for each 4 sides that an ride entrance can be located + // and 4 different rotations of the ride. 4 * 4 * 4 = 64 locations. + // clang-format off + static constexpr CoordsXY kSpiralSlideWalkingPath[64] = { + { 56, 8 }, + { 8, 8 }, + { 8, 32 }, + { 32, 32 }, + { 8, 8 }, + { 8, 8 }, + { 8, 32 }, + { 32, 32 }, + { 8, 32 }, + { 8, 32 }, + { 8, 32 }, + { 32, 32 }, + { 8, 56 }, + { 8, 32 }, + { 8, 32 }, + { 32, 32 }, + { 56, 24 }, + { 32, 24 }, + { 32, 24 }, + { 32, 0 }, + { 56, -24 }, + { 56, 24 }, + { 32, 24 }, + { 32, 0 }, + { 8, 24 }, + { 32, 24 }, + { 32, 24 }, + { 32, 0 }, + { 32, 24 }, + { 32, 24 }, + { 32, 24 }, + { 32, 0 }, + { 24, 0 }, + { 24, 0 }, + { 24, 0 }, + { 0, 0 }, + { 24, -24 }, + { 24, 0 }, + { 24, 0 }, + { 0, 0 }, + { -24, -24 }, + { 24, -24 }, + { 24, 0 }, + { 0, 0 }, + { 24, 24 }, + { 24, 0 }, + { 24, 0 }, + { 0, 0 }, + { 24, 8 }, + { 0, 8 }, + { 0, 8 }, + { 0, 32 }, + { 0, 8 }, + { 0, 8 }, + { 0, 8 }, + { 0, 32 }, + { -24, 8 }, + { 0, 8 }, + { 0, 8 }, + { 0, 32 }, + { -24, 56 }, + { -24, 8 }, + { 0, 8 }, + { 0, 32 }, + }; -// These arrays contain the base minimum and maximum nausea ratings for peeps, based on their nausea tolerance level. -static constexpr RideRating_t kNauseaMinimumThresholds[] = { - 0, - 0, - 200, - 400, -}; + /** rct2: 0x00981F4C, 0x00981F4E */ + static constexpr CoordsXY kWatchingPositionOffsets[] = { + { 7, 5 }, + { 5, 25 }, + { 25, 5 }, + { 5, 7 }, + { 7, 9 }, + { 9, 25 }, + { 25, 9 }, + { 9, 7 }, + { 7, 23 }, + { 23, 25 }, + { 25, 23 }, + { 23, 7 }, + { 7, 27 }, + { 27, 25 }, + { 25, 27 }, + { 27, 7 }, + { 7, 0 }, + { 0, 25 }, + { 25, 0 }, + { 0, 7 }, + { 7, 0 }, + { 0, 25 }, + { 25, 0 }, + { 0, 7 }, + { 7, 0 }, + { 0, 25 }, + { 25, 0 }, + { 0, 7 }, + { 7, 0 }, + { 0, 25 }, + { 25, 0 }, + { 0, 7 }, + }; -static bool GuestHasVoucherForFreeRide(Guest& guest, const Ride& ride); -static void GuestRideIsTooIntense(Guest& guest, Ride& ride, bool peepAtRide); -static void GuestResetRideHeading(Guest& guest); -static void GuestTriedToEnterFullQueue(Guest& guest, Ride& ride); -static int16_t GuestCalculateRideSatisfaction(Guest& guest, const Ride& ride); -static void GuestUpdateFavouriteRide(Guest& guest, const Ride& ride, uint8_t satisfaction); -static int16_t GuestCalculateRideValueSatisfaction(Guest& guest, const Ride& ride); -static int16_t GuestCalculateRideIntensityNauseaSatisfaction(Guest& guest, const Ride& ride); -static void GuestUpdateRideNauseaGrowth(Guest& guest, const Ride& ride); -static bool GuestShouldGoOnRideAgain(Guest& guest, const Ride& ride); -static bool GuestShouldPreferredIntensityIncrease(Guest& guest); -static bool GuestReallyLikedRide(Guest& guest, const Ride& ride); -static PeepThoughtType GuestAssessSurroundings(int16_t centre_x, int16_t centre_y, int16_t centre_z); -static void GuestUpdateHunger(Guest& guest); -static void GuestDecideWhetherToLeavePark(Guest& guest); -static void GuestLeavePark(Guest& guest); -static void GuestHeadForNearestRideWithFlag(Guest& guest, bool considerOnlyCloseRides, RtdFlag rtdFlag); -static void GuestHeadForNearestRideWithSpecialType(Guest& guest, bool considerOnlyCloseRides, RtdSpecialType specialType); -static bool Loc690FD0(Guest& guest, RideId* rideToView, uint8_t* rideSeatToView, TileElement* tileElement); -static void GuestUpdateWalkingBreakScenery(Guest& guest); -static bool GuestFindRideToLookAt(Guest& guest, uint8_t edge, RideId* rideToView, uint8_t* rideSeatToView); -static bool GuestShouldGoToShop(Guest& guest, Ride& ride, bool peepAtShop); -static bool GuestShouldRideWhileRaining(Guest& guest, const Ride& ride); -static void GuestPickRideToGoOn(Guest& guest); -static Ride* GuestFindBestRideToGoOn(Guest& guest); + static constexpr RideRating_t NauseaMaximumThresholds[] = { + 300, + 600, + 800, + 1000, + }; -template<> -bool EntityBase::Is() const -{ - return Type == EntityType::guest; -} + /** rct2: 009823AC */ + static constexpr PeepThoughtType kCrowdedThoughts[] = { + PeepThoughtType::Lost, + PeepThoughtType::Tired, + PeepThoughtType::BadLitter, + PeepThoughtType::Hungry, + PeepThoughtType::Thirsty, + PeepThoughtType::VeryClean, + PeepThoughtType::Crowded, + PeepThoughtType::Scenery, + PeepThoughtType::VeryClean, + PeepThoughtType::Music, + PeepThoughtType::Watched, + PeepThoughtType::NotHungry, + PeepThoughtType::NotThirsty, + PeepThoughtType::Toilet, + PeepThoughtType::None, + PeepThoughtType::None, + }; -static bool IsValidLocation(const CoordsXYZ& coords) -{ - if (coords.x != kLocationNull) + static constexpr const char *gPeepEasterEggNames[] = { + "MICHAEL SCHUMACHER", + "JACQUES VILLENEUVE", + "DAMON HILL", + "MR BEAN", + "CHRIS SAWYER", + "KATIE BRAYSHAW", + "MELANIE WARN", + "SIMON FOSTER", + "JOHN WARDLEY", + "LISA STIRLING", + "DONALD MACRAE", + "KATHERINE MCGOWAN", + "FRANCES MCGOWAN", + "CORINA MASSOURA", + "CAROL YOUNG", + "MIA SHERIDAN", + "KATIE RODGER", + "EMMA GARRELL", + "JOANNE BARTON", + "FELICITY ANDERSON", + "KATIE SMITH", + "EILIDH BELL", + "NANCY STILLWAGON", + "DAVID ELLIS", + }; + // clang-format on + + // Flags used by PeepThoughtToActionMap + enum PeepThoughtToActionFlag : uint8_t { - if (MapIsLocationValid(coords)) - { - return true; - } + PEEP_THOUGHT_ACTION_NO_FLAGS = 0, + PEEP_THOUGHT_ACTION_FLAG_RIDE = (1 << 0), + PEEP_THOUGHT_ACTION_FLAG_SHOP_ITEM_SINGULAR = (1 << 1), + PEEP_THOUGHT_ACTION_FLAG_SHOP_ITEM_INDEFINITE = (1 << 2), + }; + + /** rct2: 0x00981DB0 */ + static struct + { + PeepActionType action; + PeepThoughtToActionFlag flags; + } PeepThoughtToActionMap[] = { + { PeepActionType::shakeHead, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::emptyPockets, PEEP_THOUGHT_ACTION_NO_FLAGS }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_NO_FLAGS }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_NO_FLAGS }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::wow, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_SHOP_ITEM_SINGULAR }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_NO_FLAGS }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_SHOP_ITEM_INDEFINITE }, + { PeepActionType::shakeHead, PEEP_THOUGHT_ACTION_FLAG_SHOP_ITEM_INDEFINITE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_NO_FLAGS }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_NO_FLAGS }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_NO_FLAGS }, + { PeepActionType::wave, PEEP_THOUGHT_ACTION_NO_FLAGS }, + { PeepActionType::joy, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::checkTime, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_NO_FLAGS }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_NO_FLAGS }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_NO_FLAGS }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_NO_FLAGS }, + { PeepActionType::wave, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_NO_FLAGS }, + { PeepActionType::wave, PEEP_THOUGHT_ACTION_NO_FLAGS }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::disgust, PEEP_THOUGHT_ACTION_NO_FLAGS }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_NO_FLAGS }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_NO_FLAGS }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_NO_FLAGS }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_NO_FLAGS }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_NO_FLAGS }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_NO_FLAGS }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_NO_FLAGS }, + { PeepActionType::beingWatched, PEEP_THOUGHT_ACTION_NO_FLAGS }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_NO_FLAGS }, + { PeepActionType::shakeHead, PEEP_THOUGHT_ACTION_NO_FLAGS }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_NO_FLAGS }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_NO_FLAGS }, + { PeepActionType::joy, PEEP_THOUGHT_ACTION_NO_FLAGS }, + { PeepActionType::walking, PEEP_THOUGHT_ACTION_FLAG_RIDE }, + }; + + // These arrays contain the base minimum and maximum nausea ratings for peeps, based on their nausea tolerance level. + static constexpr RideRating_t kNauseaMinimumThresholds[] = { + 0, + 0, + 200, + 400, + }; + + static bool GuestHasVoucherForFreeRide(Guest& guest, const Ride& ride); + static void GuestRideIsTooIntense(Guest& guest, Ride& ride, bool peepAtRide); + static void GuestResetRideHeading(Guest& guest); + static void GuestTriedToEnterFullQueue(Guest& guest, Ride& ride); + static int16_t GuestCalculateRideSatisfaction(Guest& guest, const Ride& ride); + static void GuestUpdateFavouriteRide(Guest& guest, const Ride& ride, uint8_t satisfaction); + static int16_t GuestCalculateRideValueSatisfaction(Guest& guest, const Ride& ride); + static int16_t GuestCalculateRideIntensityNauseaSatisfaction(Guest& guest, const Ride& ride); + static void GuestUpdateRideNauseaGrowth(Guest& guest, const Ride& ride); + static bool GuestShouldGoOnRideAgain(Guest& guest, const Ride& ride); + static bool GuestShouldPreferredIntensityIncrease(Guest& guest); + static bool GuestReallyLikedRide(Guest& guest, const Ride& ride); + static PeepThoughtType GuestAssessSurroundings(int16_t centre_x, int16_t centre_y, int16_t centre_z); + static void GuestUpdateHunger(Guest& guest); + static void GuestDecideWhetherToLeavePark(Guest& guest); + static void GuestLeavePark(Guest& guest); + static void GuestHeadForNearestRideWithFlag(Guest& guest, bool considerOnlyCloseRides, RtdFlag rtdFlag); + static void GuestHeadForNearestRideWithSpecialType(Guest& guest, bool considerOnlyCloseRides, RtdSpecialType specialType); + static bool Loc690FD0(Guest& guest, RideId* rideToView, uint8_t* rideSeatToView, TileElement* tileElement); + static void GuestUpdateWalkingBreakScenery(Guest& guest); + static bool GuestFindRideToLookAt(Guest& guest, uint8_t edge, RideId* rideToView, uint8_t* rideSeatToView); + static bool GuestShouldGoToShop(Guest& guest, Ride& ride, bool peepAtShop); + static bool GuestShouldRideWhileRaining(Guest& guest, const Ride& ride); + static void GuestPickRideToGoOn(Guest& guest); + static Ride* GuestFindBestRideToGoOn(Guest& guest); + + template<> + bool EntityBase::Is() const + { + return Type == EntityType::guest; } - return false; -} - -template -static void ApplyEasterEggToNearbyGuests(Guest& guest) -{ - const auto guestLoc = guest.GetLocation(); - if (!IsValidLocation(guestLoc)) - return; - - for (auto* otherGuest : EntityTileList(guestLoc)) + static bool IsValidLocation(const CoordsXYZ& coords) { - if constexpr (!applyToSelf) + if (coords.x != kLocationNull) { - if (otherGuest == &guest) + if (MapIsLocationValid(coords)) { - // Can not apply effect on self. - continue; + return true; } } - auto zDiff = std::abs(otherGuest->z - guestLoc.z); - if (zDiff <= 32) + + return false; + } + + template + static void ApplyEasterEggToNearbyGuests(Guest& guest) + { + const auto guestLoc = guest.GetLocation(); + if (!IsValidLocation(guestLoc)) + return; + + for (auto* otherGuest : EntityTileList(guestLoc)) { - std::invoke(EasterEggFunc, guest, *otherGuest); + if constexpr (!applyToSelf) + { + if (otherGuest == &guest) + { + // Can not apply effect on self. + continue; + } + } + auto zDiff = std::abs(otherGuest->z - guestLoc.z); + if (zDiff <= 32) + { + std::invoke(EasterEggFunc, guest, *otherGuest); + } } } -} -void Guest::GivePassingGuestPurpleClothes(Guest& passingPeep) -{ - passingPeep.TshirtColour = Drawing::Colour::brightPurple; - passingPeep.TrousersColour = Drawing::Colour::brightPurple; - passingPeep.Invalidate(); -} - -void Guest::GivePassingGuestPizza(Guest& passingPeep) -{ - if (passingPeep.HasItem(ShopItem::pizza)) - return; - - passingPeep.GiveItem(ShopItem::pizza); - - int32_t peepDirection = (Orientation >> 3) ^ 2; - int32_t otherPeepOppositeDirection = passingPeep.Orientation >> 3; - if (peepDirection == otherPeepOppositeDirection) + void Guest::GivePassingGuestPurpleClothes(Guest& passingPeep) { + passingPeep.TshirtColour = Drawing::Colour::brightPurple; + passingPeep.TrousersColour = Drawing::Colour::brightPurple; + passingPeep.Invalidate(); + } + + void Guest::GivePassingGuestPizza(Guest& passingPeep) + { + if (passingPeep.HasItem(ShopItem::pizza)) + return; + + passingPeep.GiveItem(ShopItem::pizza); + + int32_t peepDirection = (Orientation >> 3) ^ 2; + int32_t otherPeepOppositeDirection = passingPeep.Orientation >> 3; + if (peepDirection == otherPeepOppositeDirection) + { + if (passingPeep.IsActionInterruptableSafely()) + { + passingPeep.Action = PeepActionType::wave2; + passingPeep.AnimationFrameNum = 0; + passingPeep.AnimationImageIdOffset = 0; + passingPeep.UpdateCurrentAnimationType(); + } + } + } + + void Guest::MakePassingGuestSick(Guest& passingPeep) + { + if (passingPeep.State != PeepState::walking) + return; + if (passingPeep.IsActionInterruptableSafely()) { - passingPeep.Action = PeepActionType::wave2; + passingPeep.Action = PeepActionType::throwUp; passingPeep.AnimationFrameNum = 0; passingPeep.AnimationImageIdOffset = 0; passingPeep.UpdateCurrentAnimationType(); } } -} -void Guest::MakePassingGuestSick(Guest& passingPeep) -{ - if (passingPeep.State != PeepState::walking) - return; - - if (passingPeep.IsActionInterruptableSafely()) + void Guest::GivePassingPeepsIceCream(Guest& passingPeep) { - passingPeep.Action = PeepActionType::throwUp; - passingPeep.AnimationFrameNum = 0; - passingPeep.AnimationImageIdOffset = 0; - passingPeep.UpdateCurrentAnimationType(); - } -} - -void Guest::GivePassingPeepsIceCream(Guest& passingPeep) -{ - if (passingPeep.HasItem(ShopItem::iceCream)) - return; - - passingPeep.GiveItem(ShopItem::iceCream); - passingPeep.UpdateAnimationGroup(); -} - -/** - * - * rct2: 0x0068FD3A - */ -void Guest::UpdateEasterEggInteractions() -{ - if (PeepFlags & PEEP_FLAGS_PURPLE) - { - ApplyEasterEggToNearbyGuests<&Guest::GivePassingGuestPurpleClothes, true>(*this); - } - - if (PeepFlags & PEEP_FLAGS_PIZZA) - { - ApplyEasterEggToNearbyGuests<&Guest::GivePassingGuestPizza, true>(*this); - } - - if (PeepFlags & PEEP_FLAGS_CONTAGIOUS) - { - ApplyEasterEggToNearbyGuests<&Guest::MakePassingGuestSick, false>(*this); - } - - if (PeepFlags & PEEP_FLAGS_ICE_CREAM) - { - ApplyEasterEggToNearbyGuests<&Guest::GivePassingPeepsIceCream, false>(*this); - } - - if (PeepFlags & PEEP_FLAGS_JOY) - { - if ((ScenarioRand() & 0xFFFF) <= 1456) - { - if (IsActionInterruptableSafely()) - { - Action = PeepActionType::joy; - AnimationFrameNum = 0; - AnimationImageIdOffset = 0; - UpdateCurrentAnimationType(); - } - } - } -} - -int32_t Guest::GetEasterEggNameId() const -{ - char buffer[256]{}; - - Formatter ft; - FormatNameTo(ft); - FormatStringLegacy(buffer, sizeof(buffer), STR_STRINGID, ft.Data()); - - for (uint32_t i = 0; i < std::size(gPeepEasterEggNames); i++) - { - if (String::iequals(buffer, gPeepEasterEggNames[i])) - return static_cast(i); - } - - return -1; -} - -void Guest::HandleEasterEggName() -{ - PeepFlags &= ~PEEP_FLAGS_WAVING; - if (CheckEasterEggName(EASTEREGG_PEEP_NAME_KATIE_BRAYSHAW)) - { - PeepFlags |= PEEP_FLAGS_WAVING; - } - - PeepFlags &= ~PEEP_FLAGS_PHOTO; - if (CheckEasterEggName(EASTEREGG_PEEP_NAME_CHRIS_SAWYER)) - { - PeepFlags |= PEEP_FLAGS_PHOTO; - } - - PeepFlags &= ~PEEP_FLAGS_PAINTING; - if (CheckEasterEggName(EASTEREGG_PEEP_NAME_SIMON_FOSTER)) - { - PeepFlags |= PEEP_FLAGS_PAINTING; - } - - PeepFlags &= ~PEEP_FLAGS_WOW; - if (CheckEasterEggName(EASTEREGG_PEEP_NAME_JOHN_WARDLEY)) - { - PeepFlags |= PEEP_FLAGS_WOW; - } - - if (CheckEasterEggName(EASTEREGG_PEEP_NAME_MELANIE_WARN)) - { - Happiness = 250; - HappinessTarget = 250; - Energy = 127; - EnergyTarget = 127; - Nausea = 0; - NauseaTarget = 0; - } - - PeepFlags &= ~PEEP_FLAGS_LITTER; - if (CheckEasterEggName(EASTEREGG_PEEP_NAME_LISA_STIRLING)) - { - PeepFlags |= PEEP_FLAGS_LITTER; - } - - PeepFlags &= ~PEEP_FLAGS_LOST; - if (CheckEasterEggName(EASTEREGG_PEEP_NAME_DONALD_MACRAE)) - { - PeepFlags |= PEEP_FLAGS_LOST; - } - - PeepFlags &= ~PEEP_FLAGS_HUNGER; - if (CheckEasterEggName(EASTEREGG_PEEP_NAME_KATHERINE_MCGOWAN)) - { - PeepFlags |= PEEP_FLAGS_HUNGER; - } - - PeepFlags &= ~PEEP_FLAGS_TOILET; - if (CheckEasterEggName(EASTEREGG_PEEP_NAME_FRANCES_MCGOWAN)) - { - PeepFlags |= PEEP_FLAGS_TOILET; - } - - PeepFlags &= ~PEEP_FLAGS_CROWDED; - if (CheckEasterEggName(EASTEREGG_PEEP_NAME_CORINA_MASSOURA)) - { - PeepFlags |= PEEP_FLAGS_CROWDED; - } - - PeepFlags &= ~PEEP_FLAGS_HAPPINESS; - if (CheckEasterEggName(EASTEREGG_PEEP_NAME_CAROL_YOUNG)) - { - PeepFlags |= PEEP_FLAGS_HAPPINESS; - } - - PeepFlags &= ~PEEP_FLAGS_NAUSEA; - if (CheckEasterEggName(EASTEREGG_PEEP_NAME_MIA_SHERIDAN)) - { - PeepFlags |= PEEP_FLAGS_NAUSEA; - } - - if (CheckEasterEggName(EASTEREGG_PEEP_NAME_KATIE_RODGER)) - { - PeepFlags |= PEEP_FLAGS_LEAVING_PARK; - PeepFlags &= ~PEEP_FLAGS_PARK_ENTRANCE_CHOSEN; - } - - PeepFlags &= ~PEEP_FLAGS_PURPLE; - if (CheckEasterEggName(EASTEREGG_PEEP_NAME_EMMA_GARRELL)) - { - PeepFlags |= PEEP_FLAGS_PURPLE; - } - - PeepFlags &= ~PEEP_FLAGS_PIZZA; - if (CheckEasterEggName(EASTEREGG_PEEP_NAME_JOANNE_BARTON)) - { - PeepFlags |= PEEP_FLAGS_PIZZA; - } - - PeepFlags &= ~PEEP_FLAGS_CONTAGIOUS; - if (CheckEasterEggName(EASTEREGG_PEEP_NAME_FELICITY_ANDERSON)) - { - PeepFlags |= PEEP_FLAGS_CONTAGIOUS; - } - - PeepFlags &= ~PEEP_FLAGS_JOY; - if (CheckEasterEggName(EASTEREGG_PEEP_NAME_KATIE_SMITH)) - { - PeepFlags |= PEEP_FLAGS_JOY; - } - - PeepFlags &= ~PEEP_FLAGS_ANGRY; - if (CheckEasterEggName(EASTEREGG_PEEP_NAME_EILIDH_BELL)) - { - PeepFlags |= PEEP_FLAGS_ANGRY; - } - - PeepFlags &= ~PEEP_FLAGS_ICE_CREAM; - if (CheckEasterEggName(EASTEREGG_PEEP_NAME_NANCY_STILLWAGON)) - { - PeepFlags |= PEEP_FLAGS_ICE_CREAM; - } - - PeepFlags &= ~PEEP_FLAGS_HERE_WE_ARE; - if (CheckEasterEggName(EASTEREGG_PEEP_NAME_DAVID_ELLIS)) - { - PeepFlags |= PEEP_FLAGS_HERE_WE_ARE; - } -} - -/** - * - * rct2: 0x0069A5A0 - * tests if a peep's name matches a cheat code, normally returns using a register flag - */ -int32_t Guest::CheckEasterEggName(int32_t index) const -{ - char buffer[256]{}; - - Formatter ft; - FormatNameTo(ft); - FormatStringLegacy(buffer, sizeof(buffer), STR_STRINGID, ft.Data()); - - return String::iequals(buffer, gPeepEasterEggNames[index]); -} - -void Guest::UpdateMotivesIdle() -{ - // Idle peep happiness tends towards 127 (50%). - if (HappinessTarget >= 128) - HappinessTarget--; - else - HappinessTarget++; - - NauseaTarget = std::max(NauseaTarget - 2, 0); - - if (Energy <= 50) - { - HappinessTarget = std::max(HappinessTarget - 2, 0); - } - - if (Hunger < 10) - { - HappinessTarget = std::max(HappinessTarget - 1, 0); - } - - if (Thirst < 10) - { - HappinessTarget = std::max(HappinessTarget - 1, 0); - } - - if (Toilet >= 195) - { - HappinessTarget = std::max(HappinessTarget - 1, 0); - } - - if (State == PeepState::walking && NauseaTarget >= 128) - { - if ((ScenarioRand() & 0xFF) <= static_cast((Nausea - 128) / 2)) - { - if (IsActionInterruptableSafely()) - { - Action = PeepActionType::throwUp; - AnimationFrameNum = 0; - AnimationImageIdOffset = 0; - UpdateCurrentAnimationType(); - } - } - } -} - -/* rct2: 0x0068FA89*/ -void Guest::UpdateConsumptionMotives() -{ - if (TimeToConsume == 0 && HasFoodOrDrink()) - { - TimeToConsume += 3; - } - - if (TimeToConsume != 0 && State != PeepState::onRide) - { - TimeToConsume = std::max(TimeToConsume - 3, 0); - - if (HasDrink()) - { - Thirst = std::min(Thirst + 7, 255); - } - else - { - Hunger = std::min(Hunger + 7, 255); - Thirst = std::max(Thirst - 3, 0); - Toilet = std::min(Toilet + 2, 255); - } - - if (TimeToConsume == 0) - { - int32_t chosen_food = Numerics::bitScanForward(GetFoodOrDrinkFlags()); - if (chosen_food != -1) - { - ShopItem food = ShopItem(chosen_food); - RemoveItem(food); - - auto discardContainer = GetShopItemDescriptor(food).DiscardContainer; - if (discardContainer != ShopItem::none) - { - GiveItem(discardContainer); - } - - WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_INVENTORY; - UpdateAnimationGroup(); - } - } - } - - uint8_t newEnergy = Energy; - uint8_t newTargetEnergy = EnergyTarget; - if (newEnergy >= newTargetEnergy) - { - newEnergy -= 2; - if (newEnergy < newTargetEnergy) - newEnergy = newTargetEnergy; - } - else - { - newEnergy = std::min(kPeepMaxEnergyTarget, newEnergy + 4); - if (newEnergy > newTargetEnergy) - newEnergy = newTargetEnergy; - } - - /* Previous code here suggested maximum energy is 128. */ - newEnergy = std::clamp(newEnergy, kPeepMinEnergy, kPeepMaxEnergy); - - if (newEnergy != Energy) - { - Energy = newEnergy; - WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_2; - } - - uint8_t newHappiness = Happiness; - uint8_t newHappinessGrowth = HappinessTarget; - if (newHappiness >= newHappinessGrowth) - { - newHappiness = std::max(newHappiness - 4, 0); - if (newHappiness < newHappinessGrowth) - newHappiness = newHappinessGrowth; - } - else - { - newHappiness = std::min(255, newHappiness + 4); - if (newHappiness > newHappinessGrowth) - newHappiness = newHappinessGrowth; - } - - if (newHappiness != Happiness) - { - Happiness = newHappiness; - WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_2; - } - - uint8_t newNausea = Nausea; - uint8_t newNauseaGrowth = NauseaTarget; - if (newNausea >= newNauseaGrowth) - { - newNausea = std::max(newNausea - 4, 0); - if (newNausea < newNauseaGrowth) - newNausea = newNauseaGrowth; - } - else - { - newNausea = std::min(255, newNausea + 4); - if (newNausea > newNauseaGrowth) - newNausea = newNauseaGrowth; - } - - if (newNausea != Nausea) - { - Nausea = newNausea; - WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_2; - } -} - -void Guest::Tick128UpdateGuest(uint32_t index) -{ - const auto currentTicks = getGameState().currentTicks; - const bool ticksMatchIndex = (index & 0x1FF) != (currentTicks & 0x1FF); - if (ticksMatchIndex && !(PeepFlags & PEEP_FLAGS_POSITION_FROZEN)) - { - UpdateConsumptionMotives(); - return; - } - - /* Effect of masking with 0x1FF here vs mask 0x7F, - * which is the condition for calling this function, is - * to reduce how often the content in this conditional - * is executed to once every four calls. */ - if (PeepFlags & PEEP_FLAGS_CROWDED) - { - PeepThoughtType thought_type = kCrowdedThoughts[ScenarioRand() & 0xF]; - if (thought_type != PeepThoughtType::None) - { - InsertNewThought(thought_type); - } - } - - if (PeepFlags & PEEP_FLAGS_EXPLODE && x != kLocationNull) - { - if (State == PeepState::walking || State == PeepState::sitting) - { - Audio::Play3D(Audio::SoundId::crash, GetLocation()); - - ExplosionCloud::Create({ x, y, z + 16 }); - ExplosionFlare::Create({ x, y, z + 16 }); - - Remove(); + if (passingPeep.HasItem(ShopItem::iceCream)) return; + + passingPeep.GiveItem(ShopItem::iceCream); + passingPeep.UpdateAnimationGroup(); + } + + /** + * + * rct2: 0x0068FD3A + */ + void Guest::UpdateEasterEggInteractions() + { + if (PeepFlags & PEEP_FLAGS_PURPLE) + { + ApplyEasterEggToNearbyGuests<&Guest::GivePassingGuestPurpleClothes, true>(*this); } - PeepFlags &= ~PEEP_FLAGS_EXPLODE; - } - - if (PeepFlags & PEEP_FLAGS_HUNGER) - { - if (Hunger >= 15) - Hunger -= 15; - } - - if (PeepFlags & PEEP_FLAGS_TOILET) - { - if (Toilet <= 180) - Toilet += 50; - } - - if (PeepFlags & PEEP_FLAGS_HAPPINESS) - { - HappinessTarget = 5; - } - - if (PeepFlags & PEEP_FLAGS_NAUSEA) - { - NauseaTarget = 200; - if (Nausea <= 130) - Nausea = 130; - } - - if (Angriness != 0) - Angriness--; - - if (State == PeepState::walking || State == PeepState::sitting) - { - SurroundingsThoughtTimeout++; - if (SurroundingsThoughtTimeout >= 18) + if (PeepFlags & PEEP_FLAGS_PIZZA) { - SurroundingsThoughtTimeout = 0; - if (x != kLocationNull) - { - PeepThoughtType thought_type = GuestAssessSurroundings(x & 0xFFE0, y & 0xFFE0, z); + ApplyEasterEggToNearbyGuests<&Guest::GivePassingGuestPizza, true>(*this); + } - if (thought_type != PeepThoughtType::None) + if (PeepFlags & PEEP_FLAGS_CONTAGIOUS) + { + ApplyEasterEggToNearbyGuests<&Guest::MakePassingGuestSick, false>(*this); + } + + if (PeepFlags & PEEP_FLAGS_ICE_CREAM) + { + ApplyEasterEggToNearbyGuests<&Guest::GivePassingPeepsIceCream, false>(*this); + } + + if (PeepFlags & PEEP_FLAGS_JOY) + { + if ((ScenarioRand() & 0xFFFF) <= 1456) + { + if (IsActionInterruptableSafely()) { - InsertNewThought(thought_type); - HappinessTarget = std::min(kPeepMaxHappiness, HappinessTarget + 45); + Action = PeepActionType::joy; + AnimationFrameNum = 0; + AnimationImageIdOffset = 0; + UpdateCurrentAnimationType(); } } } } - if (!(PeepFlags & PEEP_FLAGS_ANIMATION_FROZEN)) + int32_t Guest::GetEasterEggNameId() const { - UpdateAnimationGroup(); - } + char buffer[256]{}; - if (State == PeepState::onRide || State == PeepState::enteringRide) - { - GuestTimeOnRide = AddClamp(GuestTimeOnRide, 1); + Formatter ft; + FormatNameTo(ft); + FormatStringLegacy(buffer, sizeof(buffer), STR_STRINGID, ft.Data()); - if (PeepFlags & PEEP_FLAGS_WOW) + for (uint32_t i = 0; i < std::size(gPeepEasterEggNames); i++) { - InsertNewThought(PeepThoughtType::Wow2); + if (String::iequals(buffer, gPeepEasterEggNames[i])) + return static_cast(i); } - if (GuestTimeOnRide > 15) + return -1; + } + + void Guest::HandleEasterEggName() + { + PeepFlags &= ~PEEP_FLAGS_WAVING; + if (CheckEasterEggName(EASTEREGG_PEEP_NAME_KATIE_BRAYSHAW)) { - HappinessTarget = std::max(0, HappinessTarget - 5); + PeepFlags |= PEEP_FLAGS_WAVING; + } - if (GuestTimeOnRide > 22) + PeepFlags &= ~PEEP_FLAGS_PHOTO; + if (CheckEasterEggName(EASTEREGG_PEEP_NAME_CHRIS_SAWYER)) + { + PeepFlags |= PEEP_FLAGS_PHOTO; + } + + PeepFlags &= ~PEEP_FLAGS_PAINTING; + if (CheckEasterEggName(EASTEREGG_PEEP_NAME_SIMON_FOSTER)) + { + PeepFlags |= PEEP_FLAGS_PAINTING; + } + + PeepFlags &= ~PEEP_FLAGS_WOW; + if (CheckEasterEggName(EASTEREGG_PEEP_NAME_JOHN_WARDLEY)) + { + PeepFlags |= PEEP_FLAGS_WOW; + } + + if (CheckEasterEggName(EASTEREGG_PEEP_NAME_MELANIE_WARN)) + { + Happiness = 250; + HappinessTarget = 250; + Energy = 127; + EnergyTarget = 127; + Nausea = 0; + NauseaTarget = 0; + } + + PeepFlags &= ~PEEP_FLAGS_LITTER; + if (CheckEasterEggName(EASTEREGG_PEEP_NAME_LISA_STIRLING)) + { + PeepFlags |= PEEP_FLAGS_LITTER; + } + + PeepFlags &= ~PEEP_FLAGS_LOST; + if (CheckEasterEggName(EASTEREGG_PEEP_NAME_DONALD_MACRAE)) + { + PeepFlags |= PEEP_FLAGS_LOST; + } + + PeepFlags &= ~PEEP_FLAGS_HUNGER; + if (CheckEasterEggName(EASTEREGG_PEEP_NAME_KATHERINE_MCGOWAN)) + { + PeepFlags |= PEEP_FLAGS_HUNGER; + } + + PeepFlags &= ~PEEP_FLAGS_TOILET; + if (CheckEasterEggName(EASTEREGG_PEEP_NAME_FRANCES_MCGOWAN)) + { + PeepFlags |= PEEP_FLAGS_TOILET; + } + + PeepFlags &= ~PEEP_FLAGS_CROWDED; + if (CheckEasterEggName(EASTEREGG_PEEP_NAME_CORINA_MASSOURA)) + { + PeepFlags |= PEEP_FLAGS_CROWDED; + } + + PeepFlags &= ~PEEP_FLAGS_HAPPINESS; + if (CheckEasterEggName(EASTEREGG_PEEP_NAME_CAROL_YOUNG)) + { + PeepFlags |= PEEP_FLAGS_HAPPINESS; + } + + PeepFlags &= ~PEEP_FLAGS_NAUSEA; + if (CheckEasterEggName(EASTEREGG_PEEP_NAME_MIA_SHERIDAN)) + { + PeepFlags |= PEEP_FLAGS_NAUSEA; + } + + if (CheckEasterEggName(EASTEREGG_PEEP_NAME_KATIE_RODGER)) + { + PeepFlags |= PEEP_FLAGS_LEAVING_PARK; + PeepFlags &= ~PEEP_FLAGS_PARK_ENTRANCE_CHOSEN; + } + + PeepFlags &= ~PEEP_FLAGS_PURPLE; + if (CheckEasterEggName(EASTEREGG_PEEP_NAME_EMMA_GARRELL)) + { + PeepFlags |= PEEP_FLAGS_PURPLE; + } + + PeepFlags &= ~PEEP_FLAGS_PIZZA; + if (CheckEasterEggName(EASTEREGG_PEEP_NAME_JOANNE_BARTON)) + { + PeepFlags |= PEEP_FLAGS_PIZZA; + } + + PeepFlags &= ~PEEP_FLAGS_CONTAGIOUS; + if (CheckEasterEggName(EASTEREGG_PEEP_NAME_FELICITY_ANDERSON)) + { + PeepFlags |= PEEP_FLAGS_CONTAGIOUS; + } + + PeepFlags &= ~PEEP_FLAGS_JOY; + if (CheckEasterEggName(EASTEREGG_PEEP_NAME_KATIE_SMITH)) + { + PeepFlags |= PEEP_FLAGS_JOY; + } + + PeepFlags &= ~PEEP_FLAGS_ANGRY; + if (CheckEasterEggName(EASTEREGG_PEEP_NAME_EILIDH_BELL)) + { + PeepFlags |= PEEP_FLAGS_ANGRY; + } + + PeepFlags &= ~PEEP_FLAGS_ICE_CREAM; + if (CheckEasterEggName(EASTEREGG_PEEP_NAME_NANCY_STILLWAGON)) + { + PeepFlags |= PEEP_FLAGS_ICE_CREAM; + } + + PeepFlags &= ~PEEP_FLAGS_HERE_WE_ARE; + if (CheckEasterEggName(EASTEREGG_PEEP_NAME_DAVID_ELLIS)) + { + PeepFlags |= PEEP_FLAGS_HERE_WE_ARE; + } + } + + /** + * + * rct2: 0x0069A5A0 + * tests if a peep's name matches a cheat code, normally returns using a register flag + */ + int32_t Guest::CheckEasterEggName(int32_t index) const + { + char buffer[256]{}; + + Formatter ft; + FormatNameTo(ft); + FormatStringLegacy(buffer, sizeof(buffer), STR_STRINGID, ft.Data()); + + return String::iequals(buffer, gPeepEasterEggNames[index]); + } + + void Guest::UpdateMotivesIdle() + { + // Idle peep happiness tends towards 127 (50%). + if (HappinessTarget >= 128) + HappinessTarget--; + else + HappinessTarget++; + + NauseaTarget = std::max(NauseaTarget - 2, 0); + + if (Energy <= 50) + { + HappinessTarget = std::max(HappinessTarget - 2, 0); + } + + if (Hunger < 10) + { + HappinessTarget = std::max(HappinessTarget - 1, 0); + } + + if (Thirst < 10) + { + HappinessTarget = std::max(HappinessTarget - 1, 0); + } + + if (Toilet >= 195) + { + HappinessTarget = std::max(HappinessTarget - 1, 0); + } + + if (State == PeepState::walking && NauseaTarget >= 128) + { + if ((ScenarioRand() & 0xFF) <= static_cast((Nausea - 128) / 2)) { - auto ride = GetRide(CurrentRide); - if (ride != nullptr) + if (IsActionInterruptableSafely()) { - PeepThoughtType thought_type = ride->getRideTypeDescriptor().flags.has(RtdFlag::describeAsInside) - ? PeepThoughtType::GetOut - : PeepThoughtType::GetOff; - - InsertNewThought(thought_type, CurrentRide); + Action = PeepActionType::throwUp; + AnimationFrameNum = 0; + AnimationImageIdOffset = 0; + UpdateCurrentAnimationType(); } } } } - if (PeepFlags & PEEP_FLAGS_POSITION_FROZEN) + /* rct2: 0x0068FA89*/ + void Guest::UpdateConsumptionMotives() { - return; - } - - if (State == PeepState::walking && !OutsideOfPark && !(PeepFlags & PEEP_FLAGS_LEAVING_PARK) && GuestNumRides == 0 - && GuestHeadingToRideId.IsNull()) - { - uint32_t time_duration = currentTicks - ParkEntryTime; - time_duration /= 2048; - - if (time_duration >= 5) + if (TimeToConsume == 0 && HasFoodOrDrink()) { - GuestPickRideToGoOn(*this); - - if (GuestHeadingToRideId.IsNull()) - { - HappinessTarget = std::max(HappinessTarget - 128, 0); - GuestLeavePark(*this); - GuestUpdateHunger(*this); - UpdateMotivesIdle(); - UpdateConsumptionMotives(); - return; - } + TimeToConsume += 3; } - } - if ((ScenarioRand() & 0xFFFF) <= ((HasItem(ShopItem::map)) ? 8192u : 2184u)) - { - GuestPickRideToGoOn(*this); - } - - if ((index & 0x3FF) == (currentTicks & 0x3FF)) - { - /* Effect of masking with 0x3FF here vs mask 0x1FF, - * which is used in the encompassing conditional, is - * to reduce how often the content in this conditional - * is executed to once every second time the encompassing - * conditional executes. */ - - if (!OutsideOfPark && (State == PeepState::walking || State == PeepState::sitting)) + if (TimeToConsume != 0 && State != PeepState::onRide) { - uint8_t num_thoughts = 0; - PeepThoughtType possible_thoughts[5]; + TimeToConsume = std::max(TimeToConsume - 3, 0); - if (PeepFlags & PEEP_FLAGS_LEAVING_PARK) + if (HasDrink()) { - possible_thoughts[num_thoughts++] = PeepThoughtType::GoHome; + Thirst = std::min(Thirst + 7, 255); } else { - if (Energy <= 70 && Happiness < 128) - { - possible_thoughts[num_thoughts++] = PeepThoughtType::Tired; - } - - if (Hunger <= 10 && !HasFoodOrDrink()) - { - possible_thoughts[num_thoughts++] = PeepThoughtType::Hungry; - } - - if (Thirst <= 25 && !HasFoodOrDrink()) - { - possible_thoughts[num_thoughts++] = PeepThoughtType::Thirsty; - } - - if (Toilet >= 160) - { - possible_thoughts[num_thoughts++] = PeepThoughtType::Toilet; - } - - if (!(getGameState().park.flags & PARK_FLAGS_NO_MONEY) && CashInPocket <= 9.00_GBP && Happiness >= 105 - && Energy >= 70) - { - /* The energy check was originally a second check on happiness. - * This was superfluous so should probably check something else. - * Guessed that this should really be checking energy, since - * the addresses for happiness and energy are quite close, - * 70 is also the threshold for tired thoughts (see above) and - * it makes sense that a tired peep might not think about getting - * more money. */ - possible_thoughts[num_thoughts++] = PeepThoughtType::RunningOut; - } + Hunger = std::min(Hunger + 7, 255); + Thirst = std::max(Thirst - 3, 0); + Toilet = std::min(Toilet + 2, 255); } - if (num_thoughts != 0) + if (TimeToConsume == 0) { - PeepThoughtType chosen_thought = possible_thoughts[ScenarioRand() % num_thoughts]; - - InsertNewThought(chosen_thought); - - switch (chosen_thought) + int32_t chosen_food = Numerics::bitScanForward(GetFoodOrDrinkFlags()); + if (chosen_food != -1) { - case PeepThoughtType::Hungry: - GuestHeadForNearestRideWithFlag(*this, false, RtdFlag::sellsFood); - break; - case PeepThoughtType::Thirsty: - GuestHeadForNearestRideWithFlag(*this, false, RtdFlag::sellsDrinks); - break; - case PeepThoughtType::Toilet: - GuestHeadForNearestRideWithSpecialType(*this, false, RtdSpecialType::toilet); - break; - case PeepThoughtType::RunningOut: - GuestHeadForNearestRideWithSpecialType(*this, false, RtdSpecialType::cashMachine); - break; - default: - break; - } - } - } - } - else - { - /* This branch of the conditional is executed on the - * remaining times the encompassing conditional is - * executed (which is also every second time, but - * the alternate time to the true branch). */ - if (Nausea >= 140) - { - PeepThoughtType thought_type = PeepThoughtType::Sick; - if (Nausea >= 200) - { - thought_type = PeepThoughtType::VerySick; - GuestHeadForNearestRideWithSpecialType(*this, true, RtdSpecialType::firstAid); - } - InsertNewThought(thought_type); - } - } + ShopItem food = ShopItem(chosen_food); + RemoveItem(food); - switch (State) - { - case PeepState::walking: - case PeepState::leavingPark: - case PeepState::enteringPark: - GuestDecideWhetherToLeavePark(*this); - GuestUpdateHunger(*this); - break; - - case PeepState::sitting: - if (EnergyTarget <= 135) - EnergyTarget += 5; - - if (Thirst >= 5) - { - Thirst -= 4; - Toilet = std::min(255, Toilet + 3); - } - - if (NauseaTarget >= 50) - NauseaTarget -= 6; - - // In the original this branched differently - // but it would mean setting the peep happiness from - // a thought type entry which i think is incorrect. - GuestUpdateHunger(*this); - break; - - case PeepState::queuing: - if (TimeInQueue >= 2000) - { - /* Peep happiness is affected once the peep has been waiting - * too long in a queue. */ - bool found = false; - for (auto* pathElement : TileElementsView(NextLoc)) - { - if (pathElement->GetBaseZ() != NextLoc.z) - continue; - - // Check if the footpath has a queue line TV monitor on it - if (pathElement->HasAddition() && !pathElement->AdditionIsGhost()) + auto discardContainer = GetShopItemDescriptor(food).DiscardContainer; + if (discardContainer != ShopItem::none) { - auto* pathAddEntry = pathElement->GetAdditionEntry(); - if (pathAddEntry != nullptr && (pathAddEntry->flags & PATH_ADDITION_FLAG_IS_QUEUE_SCREEN)) - { - found = true; - } + GiveItem(discardContainer); } - break; + + WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_INVENTORY; + UpdateAnimationGroup(); } + } + } - if (found) + uint8_t newEnergy = Energy; + uint8_t newTargetEnergy = EnergyTarget; + if (newEnergy >= newTargetEnergy) + { + newEnergy -= 2; + if (newEnergy < newTargetEnergy) + newEnergy = newTargetEnergy; + } + else + { + newEnergy = std::min(kPeepMaxEnergyTarget, newEnergy + 4); + if (newEnergy > newTargetEnergy) + newEnergy = newTargetEnergy; + } + + /* Previous code here suggested maximum energy is 128. */ + newEnergy = std::clamp(newEnergy, kPeepMinEnergy, kPeepMaxEnergy); + + if (newEnergy != Energy) + { + Energy = newEnergy; + WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_2; + } + + uint8_t newHappiness = Happiness; + uint8_t newHappinessGrowth = HappinessTarget; + if (newHappiness >= newHappinessGrowth) + { + newHappiness = std::max(newHappiness - 4, 0); + if (newHappiness < newHappinessGrowth) + newHappiness = newHappinessGrowth; + } + else + { + newHappiness = std::min(255, newHappiness + 4); + if (newHappiness > newHappinessGrowth) + newHappiness = newHappinessGrowth; + } + + if (newHappiness != Happiness) + { + Happiness = newHappiness; + WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_2; + } + + uint8_t newNausea = Nausea; + uint8_t newNauseaGrowth = NauseaTarget; + if (newNausea >= newNauseaGrowth) + { + newNausea = std::max(newNausea - 4, 0); + if (newNausea < newNauseaGrowth) + newNausea = newNauseaGrowth; + } + else + { + newNausea = std::min(255, newNausea + 4); + if (newNausea > newNauseaGrowth) + newNausea = newNauseaGrowth; + } + + if (newNausea != Nausea) + { + Nausea = newNausea; + WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_2; + } + } + + void Guest::Tick128UpdateGuest(uint32_t index) + { + const auto currentTicks = getGameState().currentTicks; + const bool ticksMatchIndex = (index & 0x1FF) != (currentTicks & 0x1FF); + if (ticksMatchIndex && !(PeepFlags & PEEP_FLAGS_POSITION_FROZEN)) + { + UpdateConsumptionMotives(); + return; + } + + /* Effect of masking with 0x1FF here vs mask 0x7F, + * which is the condition for calling this function, is + * to reduce how often the content in this conditional + * is executed to once every four calls. */ + if (PeepFlags & PEEP_FLAGS_CROWDED) + { + PeepThoughtType thought_type = kCrowdedThoughts[ScenarioRand() & 0xF]; + if (thought_type != PeepThoughtType::None) + { + InsertNewThought(thought_type); + } + } + + if (PeepFlags & PEEP_FLAGS_EXPLODE && x != kLocationNull) + { + if (State == PeepState::walking || State == PeepState::sitting) + { + Audio::Play3D(Audio::SoundId::crash, GetLocation()); + + ExplosionCloud::Create({ x, y, z + 16 }); + ExplosionFlare::Create({ x, y, z + 16 }); + + Remove(); + return; + } + + PeepFlags &= ~PEEP_FLAGS_EXPLODE; + } + + if (PeepFlags & PEEP_FLAGS_HUNGER) + { + if (Hunger >= 15) + Hunger -= 15; + } + + if (PeepFlags & PEEP_FLAGS_TOILET) + { + if (Toilet <= 180) + Toilet += 50; + } + + if (PeepFlags & PEEP_FLAGS_HAPPINESS) + { + HappinessTarget = 5; + } + + if (PeepFlags & PEEP_FLAGS_NAUSEA) + { + NauseaTarget = 200; + if (Nausea <= 130) + Nausea = 130; + } + + if (Angriness != 0) + Angriness--; + + if (State == PeepState::walking || State == PeepState::sitting) + { + SurroundingsThoughtTimeout++; + if (SurroundingsThoughtTimeout >= 18) + { + SurroundingsThoughtTimeout = 0; + if (x != kLocationNull) { - /* Queue line TV monitors make the peeps waiting in the queue - * slowly happier, up to a certain level. */ - /* Why don't queue line TV monitors start affecting the peeps - * as soon as they join the queue?? */ - if (HappinessTarget < 90) - HappinessTarget = 90; + PeepThoughtType thought_type = GuestAssessSurroundings(x & 0xFFE0, y & 0xFFE0, z); - // This is +2 as UpdateMotivesIdle (that is called later in the function) - // will -1. We want to gradually increase happiness to 165 - if (HappinessTarget < 165) - HappinessTarget += 2; + if (thought_type != PeepThoughtType::None) + { + InsertNewThought(thought_type); + HappinessTarget = std::min(kPeepMaxHappiness, HappinessTarget + 45); + } + } + } + } + + if (!(PeepFlags & PEEP_FLAGS_ANIMATION_FROZEN)) + { + UpdateAnimationGroup(); + } + + if (State == PeepState::onRide || State == PeepState::enteringRide) + { + GuestTimeOnRide = AddClamp(GuestTimeOnRide, 1); + + if (PeepFlags & PEEP_FLAGS_WOW) + { + InsertNewThought(PeepThoughtType::Wow2); + } + + if (GuestTimeOnRide > 15) + { + HappinessTarget = std::max(0, HappinessTarget - 5); + + if (GuestTimeOnRide > 22) + { + auto ride = GetRide(CurrentRide); + if (ride != nullptr) + { + PeepThoughtType thought_type = ride->getRideTypeDescriptor().flags.has(RtdFlag::describeAsInside) + ? PeepThoughtType::GetOut + : PeepThoughtType::GetOff; + + InsertNewThought(thought_type, CurrentRide); + } + } + } + } + + if (PeepFlags & PEEP_FLAGS_POSITION_FROZEN) + { + return; + } + + if (State == PeepState::walking && !OutsideOfPark && !(PeepFlags & PEEP_FLAGS_LEAVING_PARK) && GuestNumRides == 0 + && GuestHeadingToRideId.IsNull()) + { + uint32_t time_duration = currentTicks - ParkEntryTime; + time_duration /= 2048; + + if (time_duration >= 5) + { + GuestPickRideToGoOn(*this); + + if (GuestHeadingToRideId.IsNull()) + { + HappinessTarget = std::max(HappinessTarget - 128, 0); + GuestLeavePark(*this); + GuestUpdateHunger(*this); + UpdateMotivesIdle(); + UpdateConsumptionMotives(); + return; + } + } + } + + if ((ScenarioRand() & 0xFFFF) <= ((HasItem(ShopItem::map)) ? 8192u : 2184u)) + { + GuestPickRideToGoOn(*this); + } + + if ((index & 0x3FF) == (currentTicks & 0x3FF)) + { + /* Effect of masking with 0x3FF here vs mask 0x1FF, + * which is used in the encompassing conditional, is + * to reduce how often the content in this conditional + * is executed to once every second time the encompassing + * conditional executes. */ + + if (!OutsideOfPark && (State == PeepState::walking || State == PeepState::sitting)) + { + uint8_t num_thoughts = 0; + PeepThoughtType possible_thoughts[5]; + + if (PeepFlags & PEEP_FLAGS_LEAVING_PARK) + { + possible_thoughts[num_thoughts++] = PeepThoughtType::GoHome; } else { - /* Without a queue line TV monitor peeps waiting too long - * in a queue get less happy. */ - HappinessTarget = std::max(HappinessTarget - 4, 0); + if (Energy <= 70 && Happiness < 128) + { + possible_thoughts[num_thoughts++] = PeepThoughtType::Tired; + } + + if (Hunger <= 10 && !HasFoodOrDrink()) + { + possible_thoughts[num_thoughts++] = PeepThoughtType::Hungry; + } + + if (Thirst <= 25 && !HasFoodOrDrink()) + { + possible_thoughts[num_thoughts++] = PeepThoughtType::Thirsty; + } + + if (Toilet >= 160) + { + possible_thoughts[num_thoughts++] = PeepThoughtType::Toilet; + } + + if (!(getGameState().park.flags & PARK_FLAGS_NO_MONEY) && CashInPocket <= 9.00_GBP && Happiness >= 105 + && Energy >= 70) + { + /* The energy check was originally a second check on happiness. + * This was superfluous so should probably check something else. + * Guessed that this should really be checking energy, since + * the addresses for happiness and energy are quite close, + * 70 is also the threshold for tired thoughts (see above) and + * it makes sense that a tired peep might not think about getting + * more money. */ + possible_thoughts[num_thoughts++] = PeepThoughtType::RunningOut; + } + } + + if (num_thoughts != 0) + { + PeepThoughtType chosen_thought = possible_thoughts[ScenarioRand() % num_thoughts]; + + InsertNewThought(chosen_thought); + + switch (chosen_thought) + { + case PeepThoughtType::Hungry: + GuestHeadForNearestRideWithFlag(*this, false, RtdFlag::sellsFood); + break; + case PeepThoughtType::Thirsty: + GuestHeadForNearestRideWithFlag(*this, false, RtdFlag::sellsDrinks); + break; + case PeepThoughtType::Toilet: + GuestHeadForNearestRideWithSpecialType(*this, false, RtdSpecialType::toilet); + break; + case PeepThoughtType::RunningOut: + GuestHeadForNearestRideWithSpecialType(*this, false, RtdSpecialType::cashMachine); + break; + default: + break; + } } } - GuestUpdateHunger(*this); - break; - case PeepState::enteringRide: - if (SubState == 17 || SubState == 15) - { - GuestDecideWhetherToLeavePark(*this); - } - GuestUpdateHunger(*this); - break; - default: - break; - } - - UpdateMotivesIdle(); - UpdateConsumptionMotives(); -} - -/** - * - * rct2: 0x00691677 - */ -static void GuestTryGetUpFromSitting(Guest& guest) -{ - // Eats all food first - if (guest.HasFoodOrDrink()) - return; - - guest.TimeToSitdown--; - if (guest.TimeToSitdown) - return; - - guest.SetState(PeepState::walking); - - // Set destination to the centre of the tile. - const auto destination = guest.GetLocation().ToTileCentre(); - guest.SetDestination(destination, 5); - guest.UpdateCurrentAnimationType(); -} - -/** - * - * rct2: 0x0069152B - */ -void Guest::UpdateSitting() -{ - if (SittingSubState == PeepSittingSubState::tryingToSit) - { - if (!CheckForPath()) - return; - // 691541 - - const auto [pathingResult, _] = PerformNextAction(); - if (!(pathingResult & PATHING_DESTINATION_REACHED)) - return; - - auto loc = GetLocation().ToTileStart() + CoordsXYZ{ BenchUseOffsets[Var37 & 0x7], 0 }; - - MoveTo(loc); - - Orientation = ((Var37 + 2) & 3) * 8; - Action = PeepActionType::idle; - NextAnimationType = PeepAnimationType::sittingIdle; - SwitchNextAnimationType(); - - SittingSubState = PeepSittingSubState::satDown; - - // Sets time to sit on seat - TimeToSitdown = (129 - Energy) * 16 + 50; - } - else if (SittingSubState == PeepSittingSubState::satDown) - { - if (!IsActionInterruptable()) + } + else { - UpdateAction(); - if (!IsActionWalking()) + /* This branch of the conditional is executed on the + * remaining times the encompassing conditional is + * executed (which is also every second time, but + * the alternate time to the true branch). */ + if (Nausea >= 140) + { + PeepThoughtType thought_type = PeepThoughtType::Sick; + if (Nausea >= 200) + { + thought_type = PeepThoughtType::VerySick; + GuestHeadForNearestRideWithSpecialType(*this, true, RtdSpecialType::firstAid); + } + InsertNewThought(thought_type); + } + } + + switch (State) + { + case PeepState::walking: + case PeepState::leavingPark: + case PeepState::enteringPark: + GuestDecideWhetherToLeavePark(*this); + GuestUpdateHunger(*this); + break; + + case PeepState::sitting: + if (EnergyTarget <= 135) + EnergyTarget += 5; + + if (Thirst >= 5) + { + Thirst -= 4; + Toilet = std::min(255, Toilet + 3); + } + + if (NauseaTarget >= 50) + NauseaTarget -= 6; + + // In the original this branched differently + // but it would mean setting the peep happiness from + // a thought type entry which i think is incorrect. + GuestUpdateHunger(*this); + break; + + case PeepState::queuing: + if (TimeInQueue >= 2000) + { + /* Peep happiness is affected once the peep has been waiting + * too long in a queue. */ + bool found = false; + for (auto* pathElement : TileElementsView(NextLoc)) + { + if (pathElement->GetBaseZ() != NextLoc.z) + continue; + + // Check if the footpath has a queue line TV monitor on it + if (pathElement->HasAddition() && !pathElement->AdditionIsGhost()) + { + auto* pathAddEntry = pathElement->GetAdditionEntry(); + if (pathAddEntry != nullptr && (pathAddEntry->flags & PATH_ADDITION_FLAG_IS_QUEUE_SCREEN)) + { + found = true; + } + } + break; + } + + if (found) + { + /* Queue line TV monitors make the peeps waiting in the queue + * slowly happier, up to a certain level. */ + /* Why don't queue line TV monitors start affecting the peeps + * as soon as they join the queue?? */ + if (HappinessTarget < 90) + HappinessTarget = 90; + + // This is +2 as UpdateMotivesIdle (that is called later in the function) + // will -1. We want to gradually increase happiness to 165 + if (HappinessTarget < 165) + HappinessTarget += 2; + } + else + { + /* Without a queue line TV monitor peeps waiting too long + * in a queue get less happy. */ + HappinessTarget = std::max(HappinessTarget - 4, 0); + } + } + GuestUpdateHunger(*this); + break; + case PeepState::enteringRide: + if (SubState == 17 || SubState == 15) + { + GuestDecideWhetherToLeavePark(*this); + } + GuestUpdateHunger(*this); + break; + default: + break; + } + + UpdateMotivesIdle(); + UpdateConsumptionMotives(); + } + + /** + * + * rct2: 0x00691677 + */ + static void GuestTryGetUpFromSitting(Guest& guest) + { + // Eats all food first + if (guest.HasFoodOrDrink()) + return; + + guest.TimeToSitdown--; + if (guest.TimeToSitdown) + return; + + guest.SetState(PeepState::walking); + + // Set destination to the centre of the tile. + const auto destination = guest.GetLocation().ToTileCentre(); + guest.SetDestination(destination, 5); + guest.UpdateCurrentAnimationType(); + } + + /** + * + * rct2: 0x0069152B + */ + void Guest::UpdateSitting() + { + if (SittingSubState == PeepSittingSubState::tryingToSit) + { + if (!CheckForPath()) + return; + // 691541 + + const auto [pathingResult, _] = PerformNextAction(); + if (!(pathingResult & PATHING_DESTINATION_REACHED)) return; + auto loc = GetLocation().ToTileStart() + CoordsXYZ{ BenchUseOffsets[Var37 & 0x7], 0 }; + + MoveTo(loc); + + Orientation = ((Var37 + 2) & 3) * 8; Action = PeepActionType::idle; - GuestTryGetUpFromSitting(*this); - return; + NextAnimationType = PeepAnimationType::sittingIdle; + SwitchNextAnimationType(); + + SittingSubState = PeepSittingSubState::satDown; + + // Sets time to sit on seat + TimeToSitdown = (129 - Energy) * 16 + 50; } - - if ((PeepFlags & PEEP_FLAGS_LEAVING_PARK)) + else if (SittingSubState == PeepSittingSubState::satDown) { - SetState(PeepState::walking); + if (!IsActionInterruptable()) + { + UpdateAction(); + if (!IsActionWalking()) + return; - // Set destination to the centre of the tile - auto destination = GetLocation().ToTileCentre(); - SetDestination(destination, 5); - UpdateCurrentAnimationType(); - return; - } + Action = PeepActionType::idle; + GuestTryGetUpFromSitting(*this); + return; + } - if (AnimationGroup == PeepAnimationGroup::umbrella) - { - GuestTryGetUpFromSitting(*this); - return; - } + if ((PeepFlags & PEEP_FLAGS_LEAVING_PARK)) + { + SetState(PeepState::walking); - if (HasFoodOrDrink()) - { - if ((ScenarioRand() & 0xFFFFu) > 1310u) + // Set destination to the centre of the tile + auto destination = GetLocation().ToTileCentre(); + SetDestination(destination, 5); + UpdateCurrentAnimationType(); + return; + } + + if (AnimationGroup == PeepAnimationGroup::umbrella) { GuestTryGetUpFromSitting(*this); return; } - Action = PeepActionType::sittingEatFood; + + if (HasFoodOrDrink()) + { + if ((ScenarioRand() & 0xFFFFu) > 1310u) + { + GuestTryGetUpFromSitting(*this); + return; + } + Action = PeepActionType::sittingEatFood; + AnimationFrameNum = 0; + AnimationImageIdOffset = 0; + UpdateCurrentAnimationType(); + return; + } + + const auto rand = ScenarioRand(); + if ((rand & 0xFFFFu) > 131u) + { + GuestTryGetUpFromSitting(*this); + return; + } + if (AnimationGroup == PeepAnimationGroup::balloon || AnimationGroup == PeepAnimationGroup::hat) + { + GuestTryGetUpFromSitting(*this); + return; + } + + Action = PeepActionType::sittingLookAroundLeft; + if (rand & 0x80000000u) + { + Action = PeepActionType::sittingLookAroundRight; + } + + if (rand & 0x40000000u) + { + Action = PeepActionType::sittingCheckWatch; + } AnimationFrameNum = 0; AnimationImageIdOffset = 0; UpdateCurrentAnimationType(); - return; } - - const auto rand = ScenarioRand(); - if ((rand & 0xFFFFu) > 131u) - { - GuestTryGetUpFromSitting(*this); - return; - } - if (AnimationGroup == PeepAnimationGroup::balloon || AnimationGroup == PeepAnimationGroup::hat) - { - GuestTryGetUpFromSitting(*this); - return; - } - - Action = PeepActionType::sittingLookAroundLeft; - if (rand & 0x80000000u) - { - Action = PeepActionType::sittingLookAroundRight; - } - - if (rand & 0x40000000u) - { - Action = PeepActionType::sittingCheckWatch; - } - AnimationFrameNum = 0; - AnimationImageIdOffset = 0; - UpdateCurrentAnimationType(); } -} -/** - * To simplify check of 0x36BA3E0 and 0x11FF78 - * returns false on no food. - */ -uint64_t Guest::GetFoodOrDrinkFlags() const -{ - return GetItemFlags() & (ShopItemsGetAllFoods() | ShopItemsGetAllDrinks()); -} - -uint64_t Guest::GetEmptyContainerFlags() const -{ - return GetItemFlags() & ShopItemsGetAllContainers(); -} - -bool Guest::HasFoodOrDrink() const -{ - return GetFoodOrDrinkFlags() != 0; -} - -/** - * To simplify check of NOT(0x12BA3C0 and 0x118F48) - * returns 0 on no food. - */ -bool Guest::HasDrink() const -{ - return GetItemFlags() & ShopItemsGetAllDrinks(); -} - -bool Guest::HasEmptyContainer() const -{ - return GetEmptyContainerFlags() != 0; -} - -/** - * - * rct2: 0x69C308 - * Check if lost. - */ -void Guest::CheckIfLost() -{ - if (!(PeepFlags & PEEP_FLAGS_LOST)) + /** + * To simplify check of 0x36BA3E0 and 0x11FF78 + * returns false on no food. + */ + uint64_t Guest::GetFoodOrDrinkFlags() const { - if (RideGetCount() < 2) - return; - PeepFlags ^= PEEP_FLAGS_21; - - if (!(PeepFlags & PEEP_FLAGS_21)) - return; - - TimeLost++; - if (TimeLost != 254) - return; - TimeLost = 230; + return GetItemFlags() & (ShopItemsGetAllFoods() | ShopItemsGetAllDrinks()); } - InsertNewThought(PeepThoughtType::Lost); - HappinessTarget = std::max(HappinessTarget - 30, 0); -} - -/** - * - * rct2: 0x69C26B - * Check if can't find ride. - */ -void Guest::CheckCantFindRide() -{ - if (GuestHeadingToRideId.IsNull()) - return; - - // Peeps will think "I can't find ride X" twice before giving up completely. - if (GuestIsLostCountdown == 30 || GuestIsLostCountdown == 60) + uint64_t Guest::GetEmptyContainerFlags() const { - InsertNewThought(PeepThoughtType::CantFind, GuestHeadingToRideId); + return GetItemFlags() & ShopItemsGetAllContainers(); + } + + bool Guest::HasFoodOrDrink() const + { + return GetFoodOrDrinkFlags() != 0; + } + + /** + * To simplify check of NOT(0x12BA3C0 and 0x118F48) + * returns 0 on no food. + */ + bool Guest::HasDrink() const + { + return GetItemFlags() & ShopItemsGetAllDrinks(); + } + + bool Guest::HasEmptyContainer() const + { + return GetEmptyContainerFlags() != 0; + } + + /** + * + * rct2: 0x69C308 + * Check if lost. + */ + void Guest::CheckIfLost() + { + if (!(PeepFlags & PEEP_FLAGS_LOST)) + { + if (RideGetCount() < 2) + return; + PeepFlags ^= PEEP_FLAGS_21; + + if (!(PeepFlags & PEEP_FLAGS_21)) + return; + + TimeLost++; + if (TimeLost != 254) + return; + TimeLost = 230; + } + InsertNewThought(PeepThoughtType::Lost); + HappinessTarget = std::max(HappinessTarget - 30, 0); } - GuestIsLostCountdown--; - if (GuestIsLostCountdown != 0) - return; - - GuestHeadingToRideId = RideId::GetNull(); - - auto* windowMgr = Ui::GetWindowManager(); - WindowBase* w = windowMgr->FindByNumber(WindowClass::peep, Id); - - if (w != nullptr) + /** + * + * rct2: 0x69C26B + * Check if can't find ride. + */ + void Guest::CheckCantFindRide() { - w->onPrepareDraw(); - } + if (GuestHeadingToRideId.IsNull()) + return; - windowMgr->InvalidateByNumber(WindowClass::peep, Id); -} - -/** - * - * rct2: 0x69C2D0 - * Check if can't find exit. - */ -void Guest::CheckCantFindExit() -{ - if (!(PeepFlags & PEEP_FLAGS_LEAVING_PARK)) - return; - - // Peeps who can't find the park exit will continue to get less happy until they find it. - if (GuestIsLostCountdown == 1) - { - InsertNewThought(PeepThoughtType::CantFindExit); - HappinessTarget = std::max(HappinessTarget - 30, 0); - } - - if (--GuestIsLostCountdown == 0) - GuestIsLostCountdown = 90; -} - -static money64 getItemValue(const ShopItemDescriptor& shopItemDescriptor) -{ - auto& objManager = GetContext()->GetObjectManager(); - auto* climateObj = objManager.GetLoadedObject(0); - if (climateObj == nullptr) - return shopItemDescriptor.BaseValue; - - const auto& thresholds = climateObj->getItemThresholds(); - const auto& gameState = getGameState(); - - if (gameState.weatherCurrent.temperature >= thresholds.warm) - return shopItemDescriptor.HotValue; - else if (gameState.weatherCurrent.temperature <= thresholds.cold) - return shopItemDescriptor.ColdValue; - else - return shopItemDescriptor.BaseValue; -} - -/** Main logic to decide whether a peep should buy an item in question - * - * Also handles the purchase as well, so once it returns, the peep will have the - * item and the money will have been deducted. - * - * eax: shopItem | (rideIndex << 8) - * ecx: price - * esi: *peep - * - * Returns 0 or 1 depending on if the peep decided to buy the item - * - * rct2: 0x0069AF1E - */ -static bool GuestDecideAndBuyItem(Guest& guest, Ride& ride, const ShopItem shopItem, money64 price) -{ - const bool isPrecipitating = Weather::isPrecipitating(); - const bool isPrecipitatingAndUmbrella = isPrecipitating && (shopItem == ShopItem::umbrella); - - bool hasVoucher = false; - if ((guest.HasItem(ShopItem::voucher)) && (guest.VoucherType == VOUCHER_TYPE_FOOD_OR_DRINK_FREE) - && (guest.VoucherShopItem == shopItem)) - { - hasVoucher = true; - } - - if (guest.HasItem(shopItem)) - { - guest.InsertNewThought(PeepThoughtType::AlreadyGot, shopItem); - return false; - } - - const auto& shopItemDescriptor = GetShopItemDescriptor(shopItem); - if (shopItemDescriptor.IsFoodOrDrink()) - { - int32_t food = Numerics::bitScanForward(guest.GetFoodOrDrinkFlags()); - if (food != -1) + // Peeps will think "I can't find ride X" twice before giving up completely. + if (GuestIsLostCountdown == 30 || GuestIsLostCountdown == 60) { - guest.InsertNewThought(PeepThoughtType::HaventFinished, static_cast(food)); + InsertNewThought(PeepThoughtType::CantFind, GuestHeadingToRideId); + HappinessTarget = std::max(HappinessTarget - 30, 0); + } + + GuestIsLostCountdown--; + if (GuestIsLostCountdown != 0) + return; + + GuestHeadingToRideId = RideId::GetNull(); + + auto* windowMgr = Ui::GetWindowManager(); + WindowBase* w = windowMgr->FindByNumber(WindowClass::peep, Id); + + if (w != nullptr) + { + w->onPrepareDraw(); + } + + windowMgr->InvalidateByNumber(WindowClass::peep, Id); + } + + /** + * + * rct2: 0x69C2D0 + * Check if can't find exit. + */ + void Guest::CheckCantFindExit() + { + if (!(PeepFlags & PEEP_FLAGS_LEAVING_PARK)) + return; + + // Peeps who can't find the park exit will continue to get less happy until they find it. + if (GuestIsLostCountdown == 1) + { + InsertNewThought(PeepThoughtType::CantFindExit); + HappinessTarget = std::max(HappinessTarget - 30, 0); + } + + if (--GuestIsLostCountdown == 0) + GuestIsLostCountdown = 90; + } + + static money64 getItemValue(const ShopItemDescriptor& shopItemDescriptor) + { + auto& objManager = GetContext()->GetObjectManager(); + auto* climateObj = objManager.GetLoadedObject(0); + if (climateObj == nullptr) + return shopItemDescriptor.BaseValue; + + const auto& thresholds = climateObj->getItemThresholds(); + const auto& gameState = getGameState(); + + if (gameState.weatherCurrent.temperature >= thresholds.warm) + return shopItemDescriptor.HotValue; + else if (gameState.weatherCurrent.temperature <= thresholds.cold) + return shopItemDescriptor.ColdValue; + else + return shopItemDescriptor.BaseValue; + } + + /** Main logic to decide whether a peep should buy an item in question + * + * Also handles the purchase as well, so once it returns, the peep will have the + * item and the money will have been deducted. + * + * eax: shopItem | (rideIndex << 8) + * ecx: price + * esi: *peep + * + * Returns 0 or 1 depending on if the peep decided to buy the item + * + * rct2: 0x0069AF1E + */ + static bool GuestDecideAndBuyItem(Guest& guest, Ride& ride, const ShopItem shopItem, money64 price) + { + const bool isPrecipitating = Weather::isPrecipitating(); + const bool isPrecipitatingAndUmbrella = isPrecipitating && (shopItem == ShopItem::umbrella); + + bool hasVoucher = false; + if ((guest.HasItem(ShopItem::voucher)) && (guest.VoucherType == VOUCHER_TYPE_FOOD_OR_DRINK_FREE) + && (guest.VoucherShopItem == shopItem)) + { + hasVoucher = true; + } + + if (guest.HasItem(shopItem)) + { + guest.InsertNewThought(PeepThoughtType::AlreadyGot, shopItem); return false; } - if (guest.Nausea >= 145) - return false; - } - - if ((shopItem == ShopItem::balloon || shopItem == ShopItem::iceCream || shopItem == ShopItem::candyfloss - || shopItem == ShopItem::sunglasses) - && isPrecipitating) - { - return false; - } - - auto& gameState = getGameState(); - if ((shopItem == ShopItem::sunglasses || shopItem == ShopItem::iceCream) && gameState.weatherCurrent.temperature < 12) - { - return false; - } - - if (shopItemDescriptor.IsFood() && (guest.Hunger > 75)) - { - guest.InsertNewThought(PeepThoughtType::NotHungry); - return false; - } - - if (shopItemDescriptor.IsDrink() && (guest.Thirst > 75)) - { - guest.InsertNewThought(PeepThoughtType::NotThirsty); - return false; - } - - if (!isPrecipitatingAndUmbrella && (shopItem != ShopItem::map) && shopItemDescriptor.IsSouvenir() && !hasVoucher) - { - if (((ScenarioRand() & 0x7F) + 0x73) > guest.Happiness || guest.GuestNumRides < 3) - return false; - } - - if (!hasVoucher) - { - if (price != 0 && !(gameState.park.flags & PARK_FLAGS_NO_MONEY)) + const auto& shopItemDescriptor = GetShopItemDescriptor(shopItem); + if (shopItemDescriptor.IsFoodOrDrink()) { - if (guest.CashInPocket == 0) + int32_t food = Numerics::bitScanForward(guest.GetFoodOrDrinkFlags()); + if (food != -1) { - guest.InsertNewThought(PeepThoughtType::SpentMoney); + guest.InsertNewThought(PeepThoughtType::HaventFinished, static_cast(food)); return false; } - if (price > guest.CashInPocket) - { - guest.InsertNewThought(PeepThoughtType::CantAffordItem, shopItem); + + if (guest.Nausea >= 145) return false; - } } - money64 itemValue = getItemValue(shopItemDescriptor); - if (itemValue < price) + if ((shopItem == ShopItem::balloon || shopItem == ShopItem::iceCream || shopItem == ShopItem::candyfloss + || shopItem == ShopItem::sunglasses) + && isPrecipitating) { - itemValue -= price; + return false; + } - if (!isPrecipitatingAndUmbrella) + auto& gameState = getGameState(); + if ((shopItem == ShopItem::sunglasses || shopItem == ShopItem::iceCream) && gameState.weatherCurrent.temperature < 12) + { + return false; + } + + if (shopItemDescriptor.IsFood() && (guest.Hunger > 75)) + { + guest.InsertNewThought(PeepThoughtType::NotHungry); + return false; + } + + if (shopItemDescriptor.IsDrink() && (guest.Thirst > 75)) + { + guest.InsertNewThought(PeepThoughtType::NotThirsty); + return false; + } + + if (!isPrecipitatingAndUmbrella && (shopItem != ShopItem::map) && shopItemDescriptor.IsSouvenir() && !hasVoucher) + { + if (((ScenarioRand() & 0x7F) + 0x73) > guest.Happiness || guest.GuestNumRides < 3) + return false; + } + + if (!hasVoucher) + { + if (price != 0 && !(gameState.park.flags & PARK_FLAGS_NO_MONEY)) { - itemValue = -itemValue; - if (guest.Happiness >= 128) + if (guest.CashInPocket == 0) { - itemValue /= 2; - if (guest.Happiness >= 180) - itemValue /= 2; - } - if (itemValue > (static_cast(ScenarioRand() & 0x07)) && !(gameState.cheats.ignorePrice)) - { - // "I'm not paying that much for x" - guest.InsertNewThought(shopItemDescriptor.TooMuchThought, ride.id); + guest.InsertNewThought(PeepThoughtType::SpentMoney); return false; } + if (price > guest.CashInPocket) + { + guest.InsertNewThought(PeepThoughtType::CantAffordItem, shopItem); + return false; + } + } + + money64 itemValue = getItemValue(shopItemDescriptor); + if (itemValue < price) + { + itemValue -= price; + + if (!isPrecipitatingAndUmbrella) + { + itemValue = -itemValue; + if (guest.Happiness >= 128) + { + itemValue /= 2; + if (guest.Happiness >= 180) + itemValue /= 2; + } + if (itemValue > (static_cast(ScenarioRand() & 0x07)) && !(gameState.cheats.ignorePrice)) + { + // "I'm not paying that much for x" + guest.InsertNewThought(shopItemDescriptor.TooMuchThought, ride.id); + return false; + } + } + } + else + { + itemValue -= price; + itemValue = std::max(0.80_GBP, itemValue); + + if (!(gameState.park.flags & PARK_FLAGS_NO_MONEY)) + { + if (itemValue >= static_cast(ScenarioRand() & 0x07)) + { + // "This x is a really good value" + guest.InsertNewThought(shopItemDescriptor.GoodValueThought, ride.id); + } + } + + int32_t happinessGrowth = itemValue * 4; + guest.HappinessTarget = std::min((guest.HappinessTarget + happinessGrowth), kPeepMaxHappiness); + guest.Happiness = std::min((guest.Happiness + happinessGrowth), kPeepMaxHappiness); + } + + // reset itemValue for satisfaction calculation + itemValue = getItemValue(shopItemDescriptor); + itemValue -= price; + uint8_t satisfaction = 0; + if (itemValue > -8) + { + satisfaction++; + if (itemValue > -3) + { + satisfaction++; + if (itemValue > 3) + satisfaction++; + } + } + ride.updateSatisfaction(satisfaction); + } + + // The peep has now decided to buy the item (or, specifically, has not been + // dissuaded so far). + guest.GiveItem(shopItem); + const auto hasRandomShopColour = ride.flags.has(RideFlag::randomShopColours); + + switch (shopItem) + { + case ShopItem::tShirt: + guest.TshirtColour = hasRandomShopColour + ? static_cast(ScenarioRandMax(Drawing::kColourNumNormal)) + : ride.trackColours[0].main; + break; + case ShopItem::hat: + guest.HatColour = hasRandomShopColour ? static_cast(ScenarioRandMax(Drawing::kColourNumNormal)) + : ride.trackColours[0].main; + break; + case ShopItem::balloon: + guest.BalloonColour = hasRandomShopColour + ? static_cast(ScenarioRandMax(Drawing::kColourNumNormal)) + : ride.trackColours[0].main; + break; + case ShopItem::umbrella: + guest.UmbrellaColour = hasRandomShopColour + ? static_cast(ScenarioRandMax(Drawing::kColourNumNormal)) + : ride.trackColours[0].main; + break; + case ShopItem::map: + guest.ResetPathfindGoal(); + break; + case ShopItem::photo: + guest.Photo1RideRef = ride.id; + break; + case ShopItem::photo2: + guest.Photo2RideRef = ride.id; + break; + case ShopItem::photo3: + guest.Photo3RideRef = ride.id; + break; + case ShopItem::photo4: + guest.Photo4RideRef = ride.id; + break; + default: + break; + } + + guest.WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_INVENTORY; + guest.UpdateAnimationGroup(); + if (guest.PeepFlags & PEEP_FLAGS_TRACKING) + { + auto ft = Formatter(); + guest.FormatNameTo(ft); + ft.Add(shopItemDescriptor.Naming.Indefinite); + if (Config::Get().notifications.guestBoughtItem) + { + News::AddItemToQueue(News::ItemType::peepOnRide, STR_PEEP_TRACKING_NOTIFICATION_BOUGHT_X, guest.Id, ft); + } + } + + money64* expend_type = &guest.PaidOnSouvenirs; + ExpenditureType expenditure = ExpenditureType::shopStock; + + if (shopItemDescriptor.IsFood()) + { + guest.AmountOfFood++; + expend_type = &guest.PaidOnFood; + expenditure = ExpenditureType::foodDrinkStock; + } + else if (shopItemDescriptor.IsDrink()) + { + guest.AmountOfDrinks++; + expend_type = &guest.PaidOnDrink; + expenditure = ExpenditureType::foodDrinkStock; + } + else if (shopItemDescriptor.IsSouvenir()) + { + guest.AmountOfSouvenirs++; + } + + if (!(gameState.park.flags & PARK_FLAGS_NO_MONEY)) + FinancePayment(shopItemDescriptor.Cost, expenditure); + + // Sets the expenditure type to *_FOODDRINK_SALES or *_SHOP_SALES appropriately. + expenditure = static_cast(static_cast(expenditure) - 1); + if (hasVoucher) + { + guest.RemoveItem(ShopItem::voucher); + guest.WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_INVENTORY; + } + else if (!(gameState.park.flags & PARK_FLAGS_NO_MONEY)) + { + guest.SpendMoney(*expend_type, price, expenditure); + } + ride.totalProfit = AddClamp(ride.totalProfit, price - shopItemDescriptor.Cost); + ride.windowInvalidateFlags.set(RideInvalidateFlag::income); + ride.curNumCustomers++; + ride.totalCustomers = AddClamp(ride.totalCustomers, 1u); + ride.windowInvalidateFlags.set(RideInvalidateFlag::customers); + + return true; + } + + /** + * Updates various peep stats upon entering a ride, as well as updating the + * ride's satisfaction value. + * rct2: 0x0069545B + */ + void Guest::OnEnterRide(Ride& ride) + { + // Calculate how satisfying the ride is for the peep. Can range from -140 to +105. + int16_t satisfaction = GuestCalculateRideSatisfaction(*this, ride); + + // Update the satisfaction stat of the ride. + uint8_t rideSatisfaction = 0; + if (satisfaction >= 40) + rideSatisfaction = 3; + else if (satisfaction >= 20) + rideSatisfaction = 2; + else if (satisfaction >= 0) + rideSatisfaction = 1; + + ride.updateSatisfaction(rideSatisfaction); + + // Update various peep stats. + if (GuestNumRides < 255) + GuestNumRides++; + + SetHasRidden(ride); + GuestUpdateFavouriteRide(*this, ride, satisfaction); + HappinessTarget = std::clamp(HappinessTarget + satisfaction, 0, kPeepMaxHappiness); + GuestUpdateRideNauseaGrowth(*this, ride); + } + + /** + * + * rct2: 0x0069576E + */ + void Guest::OnExitRide(Ride& ride) + { + if (PeepFlags & PEEP_FLAGS_RIDE_SHOULD_BE_MARKED_AS_FAVOURITE) + { + PeepFlags &= ~PEEP_FLAGS_RIDE_SHOULD_BE_MARKED_AS_FAVOURITE; + FavouriteRide = ride.id; + // TODO fix this flag name or add another one + WindowInvalidateFlags |= PEEP_INVALIDATE_STAFF_STATS; + } + Happiness = HappinessTarget; + Nausea = NauseaTarget; + WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_STATS; + + if (PeepFlags & PEEP_FLAGS_LEAVING_PARK) + PeepFlags &= ~(PEEP_FLAGS_PARK_ENTRANCE_CHOSEN); + + if (GuestShouldGoOnRideAgain(*this, ride)) + { + GuestHeadingToRideId = ride.id; + GuestIsLostCountdown = 200; + ResetPathfindGoal(); + WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_ACTION; + } + + if (GuestShouldPreferredIntensityIncrease(*this)) + { + if (Intensity.GetMaximum() < 15) + { + Intensity = Intensity.WithMaximum(Intensity.GetMaximum() + 1); + } + } + + if (GuestReallyLikedRide(*this, ride)) + { + InsertNewThought(PeepThoughtType::WasGreat, ride.id); + + static constexpr Audio::SoundId laughs[3] = { + Audio::SoundId::laugh1, + Audio::SoundId::laugh2, + Audio::SoundId::laugh3, + }; + int32_t laughType = ScenarioRand() & 7; + if (laughType < 3) + { + Audio::Play3D(laughs[laughType], GetLocation()); + } + } + + ride.totalCustomers = AddClamp(ride.totalCustomers, 1u); + ride.windowInvalidateFlags.set(RideInvalidateFlag::customers); + } + + /** + * + * rct2: 0x00695DD2 + */ + static void GuestPickRideToGoOn(Guest& guest) + { + if (guest.State != PeepState::walking) + return; + if (!guest.GuestHeadingToRideId.IsNull()) + return; + if (guest.PeepFlags & PEEP_FLAGS_LEAVING_PARK) + return; + if (guest.HasFoodOrDrink()) + return; + if (guest.x == kLocationNull) + return; + + auto* ride = GuestFindBestRideToGoOn(guest); + if (ride != nullptr) + { + // Head to that ride + guest.GuestHeadingToRideId = ride->id; + guest.GuestIsLostCountdown = 200; + guest.ResetPathfindGoal(); + guest.WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_ACTION; + + // Make peep look at their map if they have one + if (guest.HasItem(ShopItem::map)) + { + guest.ReadMap(); + } + } + } + + static OpenRCT2::BitSet GuestFindRidesToGoOn(Guest& guest) + { + OpenRCT2::BitSet rideConsideration; + + // FIX Originally checked for a toy, likely a mistake and should be a map, + // but then again this seems to only allow the peep to go on + // rides they haven't been on before. + if (guest.HasItem(ShopItem::map)) + { + // Consider rides that peep hasn't been on yet + auto& gameState = getGameState(); + for (auto& ride : RideManager(gameState)) + { + if (!guest.HasRidden(ride)) + { + rideConsideration[ride.id.ToUnderlying()] = true; + } } } else { - itemValue -= price; - itemValue = std::max(0.80_GBP, itemValue); - - if (!(gameState.park.flags & PARK_FLAGS_NO_MONEY)) + // Take nearby rides into consideration + constexpr auto radius = 10 * 32; + int32_t cx = Numerics::floor2(guest.x, 32); + int32_t cy = Numerics::floor2(guest.y, 32); + for (int32_t tileX = cx - radius; tileX <= cx + radius; tileX += kCoordsXYStep) { - if (itemValue >= static_cast(ScenarioRand() & 0x07)) + for (int32_t tileY = cy - radius; tileY <= cy + radius; tileY += kCoordsXYStep) { - // "This x is a really good value" - guest.InsertNewThought(shopItemDescriptor.GoodValueThought, ride.id); - } - } + auto location = CoordsXY{ tileX, tileY }; + if (!MapIsLocationValid(location)) + continue; - int32_t happinessGrowth = itemValue * 4; - guest.HappinessTarget = std::min((guest.HappinessTarget + happinessGrowth), kPeepMaxHappiness); - guest.Happiness = std::min((guest.Happiness + happinessGrowth), kPeepMaxHappiness); - } - - // reset itemValue for satisfaction calculation - itemValue = getItemValue(shopItemDescriptor); - itemValue -= price; - uint8_t satisfaction = 0; - if (itemValue > -8) - { - satisfaction++; - if (itemValue > -3) - { - satisfaction++; - if (itemValue > 3) - satisfaction++; - } - } - ride.updateSatisfaction(satisfaction); - } - - // The peep has now decided to buy the item (or, specifically, has not been - // dissuaded so far). - guest.GiveItem(shopItem); - const auto hasRandomShopColour = ride.flags.has(RideFlag::randomShopColours); - - switch (shopItem) - { - case ShopItem::tShirt: - guest.TshirtColour = hasRandomShopColour ? static_cast(ScenarioRandMax(Drawing::kColourNumNormal)) - : ride.trackColours[0].main; - break; - case ShopItem::hat: - guest.HatColour = hasRandomShopColour ? static_cast(ScenarioRandMax(Drawing::kColourNumNormal)) - : ride.trackColours[0].main; - break; - case ShopItem::balloon: - guest.BalloonColour = hasRandomShopColour ? static_cast(ScenarioRandMax(Drawing::kColourNumNormal)) - : ride.trackColours[0].main; - break; - case ShopItem::umbrella: - guest.UmbrellaColour = hasRandomShopColour - ? static_cast(ScenarioRandMax(Drawing::kColourNumNormal)) - : ride.trackColours[0].main; - break; - case ShopItem::map: - guest.ResetPathfindGoal(); - break; - case ShopItem::photo: - guest.Photo1RideRef = ride.id; - break; - case ShopItem::photo2: - guest.Photo2RideRef = ride.id; - break; - case ShopItem::photo3: - guest.Photo3RideRef = ride.id; - break; - case ShopItem::photo4: - guest.Photo4RideRef = ride.id; - break; - default: - break; - } - - guest.WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_INVENTORY; - guest.UpdateAnimationGroup(); - if (guest.PeepFlags & PEEP_FLAGS_TRACKING) - { - auto ft = Formatter(); - guest.FormatNameTo(ft); - ft.Add(shopItemDescriptor.Naming.Indefinite); - if (Config::Get().notifications.guestBoughtItem) - { - News::AddItemToQueue(News::ItemType::peepOnRide, STR_PEEP_TRACKING_NOTIFICATION_BOUGHT_X, guest.Id, ft); - } - } - - money64* expend_type = &guest.PaidOnSouvenirs; - ExpenditureType expenditure = ExpenditureType::shopStock; - - if (shopItemDescriptor.IsFood()) - { - guest.AmountOfFood++; - expend_type = &guest.PaidOnFood; - expenditure = ExpenditureType::foodDrinkStock; - } - else if (shopItemDescriptor.IsDrink()) - { - guest.AmountOfDrinks++; - expend_type = &guest.PaidOnDrink; - expenditure = ExpenditureType::foodDrinkStock; - } - else if (shopItemDescriptor.IsSouvenir()) - { - guest.AmountOfSouvenirs++; - } - - if (!(gameState.park.flags & PARK_FLAGS_NO_MONEY)) - FinancePayment(shopItemDescriptor.Cost, expenditure); - - // Sets the expenditure type to *_FOODDRINK_SALES or *_SHOP_SALES appropriately. - expenditure = static_cast(static_cast(expenditure) - 1); - if (hasVoucher) - { - guest.RemoveItem(ShopItem::voucher); - guest.WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_INVENTORY; - } - else if (!(gameState.park.flags & PARK_FLAGS_NO_MONEY)) - { - guest.SpendMoney(*expend_type, price, expenditure); - } - ride.totalProfit = AddClamp(ride.totalProfit, price - shopItemDescriptor.Cost); - ride.windowInvalidateFlags.set(RideInvalidateFlag::income); - ride.curNumCustomers++; - ride.totalCustomers = AddClamp(ride.totalCustomers, 1u); - ride.windowInvalidateFlags.set(RideInvalidateFlag::customers); - - return true; -} - -/** - * Updates various peep stats upon entering a ride, as well as updating the - * ride's satisfaction value. - * rct2: 0x0069545B - */ -void Guest::OnEnterRide(Ride& ride) -{ - // Calculate how satisfying the ride is for the peep. Can range from -140 to +105. - int16_t satisfaction = GuestCalculateRideSatisfaction(*this, ride); - - // Update the satisfaction stat of the ride. - uint8_t rideSatisfaction = 0; - if (satisfaction >= 40) - rideSatisfaction = 3; - else if (satisfaction >= 20) - rideSatisfaction = 2; - else if (satisfaction >= 0) - rideSatisfaction = 1; - - ride.updateSatisfaction(rideSatisfaction); - - // Update various peep stats. - if (GuestNumRides < 255) - GuestNumRides++; - - SetHasRidden(ride); - GuestUpdateFavouriteRide(*this, ride, satisfaction); - HappinessTarget = std::clamp(HappinessTarget + satisfaction, 0, kPeepMaxHappiness); - GuestUpdateRideNauseaGrowth(*this, ride); -} - -/** - * - * rct2: 0x0069576E - */ -void Guest::OnExitRide(Ride& ride) -{ - if (PeepFlags & PEEP_FLAGS_RIDE_SHOULD_BE_MARKED_AS_FAVOURITE) - { - PeepFlags &= ~PEEP_FLAGS_RIDE_SHOULD_BE_MARKED_AS_FAVOURITE; - FavouriteRide = ride.id; - // TODO fix this flag name or add another one - WindowInvalidateFlags |= PEEP_INVALIDATE_STAFF_STATS; - } - Happiness = HappinessTarget; - Nausea = NauseaTarget; - WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_STATS; - - if (PeepFlags & PEEP_FLAGS_LEAVING_PARK) - PeepFlags &= ~(PEEP_FLAGS_PARK_ENTRANCE_CHOSEN); - - if (GuestShouldGoOnRideAgain(*this, ride)) - { - GuestHeadingToRideId = ride.id; - GuestIsLostCountdown = 200; - ResetPathfindGoal(); - WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_ACTION; - } - - if (GuestShouldPreferredIntensityIncrease(*this)) - { - if (Intensity.GetMaximum() < 15) - { - Intensity = Intensity.WithMaximum(Intensity.GetMaximum() + 1); - } - } - - if (GuestReallyLikedRide(*this, ride)) - { - InsertNewThought(PeepThoughtType::WasGreat, ride.id); - - static constexpr Audio::SoundId laughs[3] = { - Audio::SoundId::laugh1, - Audio::SoundId::laugh2, - Audio::SoundId::laugh3, - }; - int32_t laughType = ScenarioRand() & 7; - if (laughType < 3) - { - Audio::Play3D(laughs[laughType], GetLocation()); - } - } - - ride.totalCustomers = AddClamp(ride.totalCustomers, 1u); - ride.windowInvalidateFlags.set(RideInvalidateFlag::customers); -} - -/** - * - * rct2: 0x00695DD2 - */ -static void GuestPickRideToGoOn(Guest& guest) -{ - if (guest.State != PeepState::walking) - return; - if (!guest.GuestHeadingToRideId.IsNull()) - return; - if (guest.PeepFlags & PEEP_FLAGS_LEAVING_PARK) - return; - if (guest.HasFoodOrDrink()) - return; - if (guest.x == kLocationNull) - return; - - auto* ride = GuestFindBestRideToGoOn(guest); - if (ride != nullptr) - { - // Head to that ride - guest.GuestHeadingToRideId = ride->id; - guest.GuestIsLostCountdown = 200; - guest.ResetPathfindGoal(); - guest.WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_ACTION; - - // Make peep look at their map if they have one - if (guest.HasItem(ShopItem::map)) - { - guest.ReadMap(); - } - } -} - -static OpenRCT2::BitSet GuestFindRidesToGoOn(Guest& guest) -{ - OpenRCT2::BitSet rideConsideration; - - // FIX Originally checked for a toy, likely a mistake and should be a map, - // but then again this seems to only allow the peep to go on - // rides they haven't been on before. - if (guest.HasItem(ShopItem::map)) - { - // Consider rides that peep hasn't been on yet - auto& gameState = getGameState(); - for (auto& ride : RideManager(gameState)) - { - if (!guest.HasRidden(ride)) - { - rideConsideration[ride.id.ToUnderlying()] = true; - } - } - } - else - { - // Take nearby rides into consideration - constexpr auto radius = 10 * 32; - int32_t cx = Numerics::floor2(guest.x, 32); - int32_t cy = Numerics::floor2(guest.y, 32); - for (int32_t tileX = cx - radius; tileX <= cx + radius; tileX += kCoordsXYStep) - { - for (int32_t tileY = cy - radius; tileY <= cy + radius; tileY += kCoordsXYStep) - { - auto location = CoordsXY{ tileX, tileY }; - if (!MapIsLocationValid(location)) - continue; - - for (auto* trackElement : TileElementsView(location)) - { - auto rideIndex = trackElement->GetRideIndex(); - if (!rideIndex.IsNull()) + for (auto* trackElement : TileElementsView(location)) { - rideConsideration[rideIndex.ToUnderlying()] = true; + auto rideIndex = trackElement->GetRideIndex(); + if (!rideIndex.IsNull()) + { + rideConsideration[rideIndex.ToUnderlying()] = true; + } } } } - } - - // Always take the tall rides into consideration (realistic as you can usually see them from anywhere in the park) - auto& gameState = getGameState(); - for (auto& ride : RideManager(gameState)) - { - if (ride.highestDropHeight > 66 || ride.ratings.excitement >= RideRating::make(8, 00)) - { - rideConsideration[ride.id.ToUnderlying()] = true; - } - } - } - - return rideConsideration; -} - -static Ride* GuestFindBestRideToGoOn(Guest& guest) -{ - // Pick the most exciting ride - auto rideConsideration = GuestFindRidesToGoOn(guest); - Ride* mostExcitingRide = nullptr; - - auto& gameState = getGameState(); - for (auto& ride : RideManager(gameState)) - { - const auto rideIndex = ride.id.ToUnderlying(); - if (rideConsideration.size() > rideIndex && rideConsideration[rideIndex]) - { - if (!ride.flags.has(RideFlag::queueFull)) - { - if (guest.ShouldGoOnRide(ride, StationIndex::FromUnderlying(0), false, true) && RideHasRatings(ride)) - { - if (mostExcitingRide == nullptr || ride.ratings.excitement > mostExcitingRide->ratings.excitement) - { - mostExcitingRide = &ride; - } - } - } - } - } - return mostExcitingRide; -} - -/** - * This function is called whenever a peep is deciding whether or not they want - * to go on a ride or visit a shop. They may be physically present at the - * ride/shop, or they may just be thinking about it. - * rct2: 0x006960AB - */ -bool Guest::ShouldGoOnRide(Ride& ride, StationIndex entranceNum, bool atQueue, bool thinking) -{ - // Indicates whether a peep is physically at the ride, or is just thinking about going on the ride. - bool peepAtRide = !thinking; - - if (ride.status == RideStatus::open && !ride.flags.has(RideFlag::brokenDown)) - { - // Peeps that are leaving the park will refuse to go on any rides, with the exception of free transport rides. - assert(ride.type < std::size(kRideTypeDescriptors)); - if (!ride.getRideTypeDescriptor().flags.has(RtdFlag::isTransportRide) || ride.value == kRideValueUndefined - || RideGetPrice(ride) != 0) - { - if (PeepFlags & PEEP_FLAGS_LEAVING_PARK) - { - ChoseNotToGoOnRide(ride, peepAtRide, false); - return false; - } - } - - if (ride.getRideTypeDescriptor().flags.has(RtdFlag::isShopOrFacility)) - { - return GuestShouldGoToShop(*this, ride, peepAtRide); - } - - // This used to check !(flags & 2), but the function is only ever called with flags = 0, 1 or 6. - // This means we can use the existing !(flags & 4) check. - if (peepAtRide) - { - auto& station = ride.getStation(entranceNum); - - // Rides without queues can only have one peep waiting at a time. - if (!atQueue) - { - if (!station.LastPeepInQueue.IsNull()) - { - GuestTriedToEnterFullQueue(*this, ride); - return false; - } - } - else - { - // Check if there's room in the queue for the peep to enter. - Guest* lastPeepInQueue = getGameState().entities.GetEntity(station.LastPeepInQueue); - if (lastPeepInQueue != nullptr && (abs(lastPeepInQueue->z - z) <= 6)) - { - int32_t dx = abs(lastPeepInQueue->x - x); - int32_t dy = abs(lastPeepInQueue->y - y); - int32_t maxD = std::max(dx, dy); - - // Unlike normal paths, peeps cannot overlap when queueing for a ride. - // This check enforces a minimum distance between peeps entering the queue. - if (maxD < 8) - { - GuestTriedToEnterFullQueue(*this, ride); - return false; - } - - // This checks if there's a peep standing still at the very end of the queue. - if (maxD <= 13 && lastPeepInQueue->TimeInQueue > 10) - { - GuestTriedToEnterFullQueue(*this, ride); - return false; - } - } - } - } - - // Assuming the queue conditions are met, peeps will always go on free transport rides. - // Ride ratings, recent crashes and weather will all be ignored. - auto ridePrice = RideGetPrice(ride); - if (!ride.getRideTypeDescriptor().flags.has(RtdFlag::isTransportRide) || ride.value == kRideValueUndefined - || ridePrice != 0) - { - if (PreviousRide == ride.id) - { - ChoseNotToGoOnRide(ride, peepAtRide, false); - return false; - } + // Always take the tall rides into consideration (realistic as you can usually see them from anywhere in the park) auto& gameState = getGameState(); - // Basic price checks - if (ridePrice != 0 && !GuestHasVoucherForFreeRide(*this, ride) && !(gameState.park.flags & PARK_FLAGS_NO_MONEY)) + for (auto& ride : RideManager(gameState)) { - if (ridePrice > CashInPocket) + if (ride.highestDropHeight > 66 || ride.ratings.excitement >= RideRating::make(8, 00)) { - if (peepAtRide) + rideConsideration[ride.id.ToUnderlying()] = true; + } + } + } + + return rideConsideration; + } + + static Ride* GuestFindBestRideToGoOn(Guest& guest) + { + // Pick the most exciting ride + auto rideConsideration = GuestFindRidesToGoOn(guest); + Ride* mostExcitingRide = nullptr; + + auto& gameState = getGameState(); + for (auto& ride : RideManager(gameState)) + { + const auto rideIndex = ride.id.ToUnderlying(); + if (rideConsideration.size() > rideIndex && rideConsideration[rideIndex]) + { + if (!ride.flags.has(RideFlag::queueFull)) + { + if (guest.ShouldGoOnRide(ride, StationIndex::FromUnderlying(0), false, true) && RideHasRatings(ride)) { - if (CashInPocket <= 0) + if (mostExcitingRide == nullptr || ride.ratings.excitement > mostExcitingRide->ratings.excitement) { - InsertNewThought(PeepThoughtType::SpentMoney); - } - else - { - InsertNewThought(PeepThoughtType::CantAffordRide, ride.id); + mostExcitingRide = &ride; } } - ChoseNotToGoOnRide(ride, peepAtRide, true); + } + } + } + return mostExcitingRide; + } + + /** + * This function is called whenever a peep is deciding whether or not they want + * to go on a ride or visit a shop. They may be physically present at the + * ride/shop, or they may just be thinking about it. + * rct2: 0x006960AB + */ + bool Guest::ShouldGoOnRide(Ride& ride, StationIndex entranceNum, bool atQueue, bool thinking) + { + // Indicates whether a peep is physically at the ride, or is just thinking about going on the ride. + bool peepAtRide = !thinking; + + if (ride.status == RideStatus::open && !ride.flags.has(RideFlag::brokenDown)) + { + // Peeps that are leaving the park will refuse to go on any rides, with the exception of free transport rides. + assert(ride.type < std::size(kRideTypeDescriptors)); + if (!ride.getRideTypeDescriptor().flags.has(RtdFlag::isTransportRide) || ride.value == kRideValueUndefined + || RideGetPrice(ride) != 0) + { + if (PeepFlags & PEEP_FLAGS_LEAVING_PARK) + { + ChoseNotToGoOnRide(ride, peepAtRide, false); return false; } } - // If happy enough, peeps will ignore the fact that a ride has recently crashed. - if (ride.lastCrashType != RIDE_CRASH_TYPE_NONE && Happiness < 225) + if (ride.getRideTypeDescriptor().flags.has(RtdFlag::isShopOrFacility)) { - if (peepAtRide) - { - InsertNewThought(PeepThoughtType::NotSafe, ride.id); - if (HappinessTarget >= 64) - { - HappinessTarget -= 8; - } - ride.updatePopularity(0); - } - ChoseNotToGoOnRide(ride, peepAtRide, true); - return false; + return GuestShouldGoToShop(*this, ride, peepAtRide); } - if (RideHasRatings(ride)) + // This used to check !(flags & 2), but the function is only ever called with flags = 0, 1 or 6. + // This means we can use the existing !(flags & 4) check. + if (peepAtRide) { - // If a peep has already decided that they're going to go on a ride, they'll skip the weather and - // excitement check and will only do a basic intensity check when they arrive at the ride itself. - if (ride.id == GuestHeadingToRideId) + auto& station = ride.getStation(entranceNum); + + // Rides without queues can only have one peep waiting at a time. + if (!atQueue) { - if (ride.ratings.intensity > RideRating::make(10, 00) && !gameState.cheats.ignoreRideIntensity) + if (!station.LastPeepInQueue.IsNull()) { - GuestRideIsTooIntense(*this, ride, peepAtRide); + GuestTriedToEnterFullQueue(*this, ride); return false; } } else { - const bool isPrecipitating = Weather::isPrecipitating(); - if (isPrecipitating && !GuestShouldRideWhileRaining(*this, ride)) + // Check if there's room in the queue for the peep to enter. + Guest* lastPeepInQueue = getGameState().entities.GetEntity(station.LastPeepInQueue); + if (lastPeepInQueue != nullptr && (abs(lastPeepInQueue->z - z) <= 6)) { - if (peepAtRide) + int32_t dx = abs(lastPeepInQueue->x - x); + int32_t dy = abs(lastPeepInQueue->y - y); + int32_t maxD = std::max(dx, dy); + + // Unlike normal paths, peeps cannot overlap when queueing for a ride. + // This check enforces a minimum distance between peeps entering the queue. + if (maxD < 8) { - InsertNewThought(PeepThoughtType::NotWhileRaining, ride.id); - if (HappinessTarget >= 64) - { - HappinessTarget -= 8; - } - ride.updatePopularity(0); + GuestTriedToEnterFullQueue(*this, ride); + return false; } - ChoseNotToGoOnRide(ride, peepAtRide, true); - return false; - } - // If it is raining and the ride provides shelter skip the - // ride intensity check and get me on a sheltered ride! - if (!isPrecipitating || !GuestShouldRideWhileRaining(*this, ride)) - { - if (!gameState.cheats.ignoreRideIntensity) + + // This checks if there's a peep standing still at the very end of the queue. + if (maxD <= 13 && lastPeepInQueue->TimeInQueue > 10) { - // Intensity calculations. Even though the max intensity can go up to 15, it's capped - // at 10.0 (before happiness calculations). A full happiness bar will increase the max - // intensity and decrease the min intensity by about 2.5. - RideRating_t maxIntensity = std::min(Intensity.GetMaximum() * 100, 1000) + Happiness; - RideRating_t minIntensity = (Intensity.GetMinimum() * 100) - Happiness; - if (ride.ratings.intensity < minIntensity) - { - if (peepAtRide) - { - InsertNewThought(PeepThoughtType::MoreThrilling, ride.id); - if (HappinessTarget >= 64) - { - HappinessTarget -= 8; - } - ride.updatePopularity(0); - } - ChoseNotToGoOnRide(ride, peepAtRide, true); - return false; - } - if (ride.ratings.intensity > maxIntensity) - { - GuestRideIsTooIntense(*this, ride, peepAtRide); - return false; - } - - // Nausea calculations. - RideRating_t maxNausea = NauseaMaximumThresholds[(EnumValue(NauseaTolerance) & 3)] + Happiness; - - if (ride.ratings.nausea > maxNausea) - { - if (peepAtRide) - { - InsertNewThought(PeepThoughtType::Sickening, ride.id); - if (HappinessTarget >= 64) - { - HappinessTarget -= 8; - } - ride.updatePopularity(0); - } - ChoseNotToGoOnRide(ride, peepAtRide, true); - return false; - } - - // Very nauseous peeps will only go on very gentle rides. - if (ride.ratings.nausea >= RideRating::make(1, 40) && Nausea > 160) - { - ChoseNotToGoOnRide(ride, peepAtRide, false); - return false; - } + GuestTriedToEnterFullQueue(*this, ride); + return false; } } } } - // If the ride has not yet been rated and is capable of having g-forces, - // there's a 90% chance that the peep will ignore it. - if (!RideHasRatings(ride) && ride.getRideTypeDescriptor().flags.has(RtdFlag::checkGForces)) + // Assuming the queue conditions are met, peeps will always go on free transport rides. + // Ride ratings, recent crashes and weather will all be ignored. + auto ridePrice = RideGetPrice(ride); + if (!ride.getRideTypeDescriptor().flags.has(RtdFlag::isTransportRide) || ride.value == kRideValueUndefined + || ridePrice != 0) { - if ((ScenarioRand() & 0xFFFF) > 0x1999u) + if (PreviousRide == ride.id) { ChoseNotToGoOnRide(ride, peepAtRide, false); return false; } - if (!gameState.cheats.ignoreRideIntensity) + auto& gameState = getGameState(); + // Basic price checks + if (ridePrice != 0 && !GuestHasVoucherForFreeRide(*this, ride) && !(gameState.park.flags & PARK_FLAGS_NO_MONEY)) { - if (ride.maxPositiveVerticalG > MakeFixed16_2dp(5, 00) - || ride.maxNegativeVerticalG < MakeFixed16_2dp(-4, 00) || ride.maxLateralG > MakeFixed16_2dp(4, 00)) + if (ridePrice > CashInPocket) { - ChoseNotToGoOnRide(ride, peepAtRide, false); + if (peepAtRide) + { + if (CashInPocket <= 0) + { + InsertNewThought(PeepThoughtType::SpentMoney); + } + else + { + InsertNewThought(PeepThoughtType::CantAffordRide, ride.id); + } + } + ChoseNotToGoOnRide(ride, peepAtRide, true); return false; } } - } - money64 value = ride.value; - - // If the value of the ride hasn't yet been calculated, peeps will be willing to pay any amount for the ride. - if (value != kRideValueUndefined && !GuestHasVoucherForFreeRide(*this, ride) - && !(gameState.park.flags & PARK_FLAGS_NO_MONEY)) - { - // The amount peeps are willing to pay is decreased by 75% if they had to pay to enter the park. - if (PeepFlags & PEEP_FLAGS_HAS_PAID_FOR_PARK_ENTRY) - value /= 4; - - // Peeps won't pay more than twice the value of the ride. - ridePrice = RideGetPrice(ride); - if ((ridePrice > (value * 2)) && !(gameState.cheats.ignorePrice)) + // If happy enough, peeps will ignore the fact that a ride has recently crashed. + if (ride.lastCrashType != RIDE_CRASH_TYPE_NONE && Happiness < 225) { if (peepAtRide) { - InsertNewThought(PeepThoughtType::BadValue, ride.id); - if (HappinessTarget >= 60) + InsertNewThought(PeepThoughtType::NotSafe, ride.id); + if (HappinessTarget >= 64) { - HappinessTarget -= 16; + HappinessTarget -= 8; } ride.updatePopularity(0); } @@ -2229,3779 +2094,1318 @@ bool Guest::ShouldGoOnRide(Ride& ride, StationIndex entranceNum, bool atQueue, b return false; } - // A ride is good value if the price is 50% or less of the ride value and the peep didn't pay to enter the park. - if (ridePrice <= (value / 2) && peepAtRide) + if (RideHasRatings(ride)) { - if (!(gameState.park.flags & PARK_FLAGS_NO_MONEY)) + // If a peep has already decided that they're going to go on a ride, they'll skip the weather and + // excitement check and will only do a basic intensity check when they arrive at the ride itself. + if (ride.id == GuestHeadingToRideId) { - if (!(PeepFlags & PEEP_FLAGS_HAS_PAID_FOR_PARK_ENTRY)) + if (ride.ratings.intensity > RideRating::make(10, 00) && !gameState.cheats.ignoreRideIntensity) { - InsertNewThought(PeepThoughtType::GoodValue, ride.id); + GuestRideIsTooIntense(*this, ride, peepAtRide); + return false; + } + } + else + { + const bool isPrecipitating = Weather::isPrecipitating(); + if (isPrecipitating && !GuestShouldRideWhileRaining(*this, ride)) + { + if (peepAtRide) + { + InsertNewThought(PeepThoughtType::NotWhileRaining, ride.id); + if (HappinessTarget >= 64) + { + HappinessTarget -= 8; + } + ride.updatePopularity(0); + } + ChoseNotToGoOnRide(ride, peepAtRide, true); + return false; + } + // If it is raining and the ride provides shelter skip the + // ride intensity check and get me on a sheltered ride! + if (!isPrecipitating || !GuestShouldRideWhileRaining(*this, ride)) + { + if (!gameState.cheats.ignoreRideIntensity) + { + // Intensity calculations. Even though the max intensity can go up to 15, it's capped + // at 10.0 (before happiness calculations). A full happiness bar will increase the max + // intensity and decrease the min intensity by about 2.5. + RideRating_t maxIntensity = std::min(Intensity.GetMaximum() * 100, 1000) + Happiness; + RideRating_t minIntensity = (Intensity.GetMinimum() * 100) - Happiness; + if (ride.ratings.intensity < minIntensity) + { + if (peepAtRide) + { + InsertNewThought(PeepThoughtType::MoreThrilling, ride.id); + if (HappinessTarget >= 64) + { + HappinessTarget -= 8; + } + ride.updatePopularity(0); + } + ChoseNotToGoOnRide(ride, peepAtRide, true); + return false; + } + if (ride.ratings.intensity > maxIntensity) + { + GuestRideIsTooIntense(*this, ride, peepAtRide); + return false; + } + + // Nausea calculations. + RideRating_t maxNausea = NauseaMaximumThresholds[(EnumValue(NauseaTolerance) & 3)] + Happiness; + + if (ride.ratings.nausea > maxNausea) + { + if (peepAtRide) + { + InsertNewThought(PeepThoughtType::Sickening, ride.id); + if (HappinessTarget >= 64) + { + HappinessTarget -= 8; + } + ride.updatePopularity(0); + } + ChoseNotToGoOnRide(ride, peepAtRide, true); + return false; + } + + // Very nauseous peeps will only go on very gentle rides. + if (ride.ratings.nausea >= RideRating::make(1, 40) && Nausea > 160) + { + ChoseNotToGoOnRide(ride, peepAtRide, false); + return false; + } + } + } + } + } + + // If the ride has not yet been rated and is capable of having g-forces, + // there's a 90% chance that the peep will ignore it. + if (!RideHasRatings(ride) && ride.getRideTypeDescriptor().flags.has(RtdFlag::checkGForces)) + { + if ((ScenarioRand() & 0xFFFF) > 0x1999u) + { + ChoseNotToGoOnRide(ride, peepAtRide, false); + return false; + } + + if (!gameState.cheats.ignoreRideIntensity) + { + if (ride.maxPositiveVerticalG > MakeFixed16_2dp(5, 00) + || ride.maxNegativeVerticalG < MakeFixed16_2dp(-4, 00) || ride.maxLateralG > MakeFixed16_2dp(4, 00)) + { + ChoseNotToGoOnRide(ride, peepAtRide, false); + return false; + } + } + } + + money64 value = ride.value; + + // If the value of the ride hasn't yet been calculated, peeps will be willing to pay any amount for the ride. + if (value != kRideValueUndefined && !GuestHasVoucherForFreeRide(*this, ride) + && !(gameState.park.flags & PARK_FLAGS_NO_MONEY)) + { + // The amount peeps are willing to pay is decreased by 75% if they had to pay to enter the park. + if (PeepFlags & PEEP_FLAGS_HAS_PAID_FOR_PARK_ENTRY) + value /= 4; + + // Peeps won't pay more than twice the value of the ride. + ridePrice = RideGetPrice(ride); + if ((ridePrice > (value * 2)) && !(gameState.cheats.ignorePrice)) + { + if (peepAtRide) + { + InsertNewThought(PeepThoughtType::BadValue, ride.id); + if (HappinessTarget >= 60) + { + HappinessTarget -= 16; + } + ride.updatePopularity(0); + } + ChoseNotToGoOnRide(ride, peepAtRide, true); + return false; + } + + // A ride is good value if the price is 50% or less of the ride value and the peep didn't pay to enter the + // park. + if (ridePrice <= (value / 2) && peepAtRide) + { + if (!(gameState.park.flags & PARK_FLAGS_NO_MONEY)) + { + if (!(PeepFlags & PEEP_FLAGS_HAS_PAID_FOR_PARK_ENTRY)) + { + InsertNewThought(PeepThoughtType::GoodValue, ride.id); + } } } } } + + // At this point, the peep has decided to go on the ride. + if (peepAtRide) + { + ride.updatePopularity(1); + } + + if (ride.id == GuestHeadingToRideId) + { + GuestResetRideHeading(*this); + } + + ride.flags.unset(RideFlag::queueFull); + return true; } - // At this point, the peep has decided to go on the ride. - if (peepAtRide) + ChoseNotToGoOnRide(ride, peepAtRide, false); + return false; + } + + static bool GuestShouldGoToShop(Guest& guest, Ride& ride, bool peepAtShop) + { + // Peeps won't go to the same shop twice in a row. + if (ride.id == guest.PreviousRide) + { + guest.ChoseNotToGoOnRide(ride, peepAtShop, true); + return false; + } + + const auto& rtd = ride.getRideTypeDescriptor(); + if (rtd.specialType == RtdSpecialType::toilet) + { + if (guest.Toilet < 70) + { + guest.ChoseNotToGoOnRide(ride, peepAtShop, true); + return false; + } + + // The amount that peeps are willing to pay to use the Toilets scales with their toilet stat. + // It effectively has a minimum of $0.10 (due to the check above) and a maximum of $0.60. + if ((RideGetPrice(ride) * 40 > guest.Toilet) && !getGameState().cheats.ignorePrice) + { + if (peepAtShop) + { + guest.InsertNewThought(PeepThoughtType::NotPaying, ride.id); + if (guest.HappinessTarget >= 60) + { + guest.HappinessTarget -= 16; + } + ride.updatePopularity(0); + } + guest.ChoseNotToGoOnRide(ride, peepAtShop, true); + return false; + } + } + + if (rtd.specialType == RtdSpecialType::firstAid) + { + if (guest.Nausea < 128) + { + guest.ChoseNotToGoOnRide(ride, peepAtShop, true); + return false; + } + } + + // Basic price checks + auto ridePrice = RideGetPrice(ride); + if (ridePrice != 0 && ridePrice > guest.CashInPocket) + { + if (peepAtShop) + { + if (guest.CashInPocket <= 0) + { + guest.InsertNewThought(PeepThoughtType::SpentMoney); + } + else + { + guest.InsertNewThought(PeepThoughtType::CantAffordRide, ride.id); + } + } + guest.ChoseNotToGoOnRide(ride, peepAtShop, true); + return false; + } + + if (peepAtShop) { ride.updatePopularity(1); + if (ride.id == guest.GuestHeadingToRideId) + { + GuestResetRideHeading(guest); + } + } + return true; + } + + // Used when no logging to an expend type required + void Guest::SpendMoney(money64 amount, ExpenditureType expenditure) + { + money64 unused; + SpendMoney(unused, amount, expenditure); + } + + /** + * + * rct2: 0x0069926C + * Expend type was previously an offset saved in 0x00F1AEC0 + */ + void Guest::SpendMoney(money64& peep_expend_type, money64 amount, ExpenditureType expenditure) + { + assert(!(getGameState().park.flags & PARK_FLAGS_NO_MONEY)); + + CashInPocket = std::max(0.00_GBP, CashInPocket - amount); + CashSpent = AddClamp(CashSpent, amount); + + peep_expend_type = AddClamp(peep_expend_type, amount); + + auto* windowMgr = Ui::GetWindowManager(); + windowMgr->InvalidateByNumber(WindowClass::peep, Id); + + FinancePayment(-amount, expenditure); + + MoneyEffect::CreateAt(amount, GetLocation(), true); + + Audio::Play3D(Audio::SoundId::purchase, GetLocation()); + } + + void Guest::SetHasRidden(const Ride& ride) + { + RideUse::GetHistory().Add(Id, ride.id); + + SetHasRiddenRideType(ride.type); + } + + bool Guest::HasRidden(const Ride& ride) const + { + return RideUse::GetHistory().Contains(Id, ride.id); + } + + void Guest::SetHasRiddenRideType(ride_type_t rideType) + { + RideUse::GetTypeHistory().Add(Id, rideType); + } + + bool Guest::HasRiddenRideType(ride_type_t rideType) const + { + return RideUse::GetTypeHistory().Contains(Id, rideType); + } + + void Guest::SetParkEntryTime(int32_t entryTime) + { + ParkEntryTime = entryTime; + } + + int32_t Guest::GetParkEntryTime() const + { + return ParkEntryTime; + } + + static bool GuestShouldRideWhileRaining(Guest& guest, const Ride& ride) + { + // Peeps will go on rides that are sufficiently undercover while it's raining. + // The threshold is fairly low and only requires about 10-15% of the ride to be undercover. + if (ride.shelteredEighths >= 3) + { + return true; + } + + // Peeps with umbrellas will go on rides where they can use their umbrella on it (like the Maze) 50% of the time + if (guest.HasItem(ShopItem::umbrella) && ride.getRideTypeDescriptor().flags.has(RtdFlag::guestsCanUseUmbrella) + && (ScenarioRand() & 2) == 0) + { + return true; + } + + return false; + } + + void Guest::ChoseNotToGoOnRide(const Ride& ride, bool peepAtRide, bool updateLastRide) + { + if (peepAtRide && updateLastRide) + { + PreviousRide = ride.id; + PreviousRideTimeOut = 0; } if (ride.id == GuestHeadingToRideId) { GuestResetRideHeading(*this); } - - ride.flags.unset(RideFlag::queueFull); - return true; } - ChoseNotToGoOnRide(ride, peepAtRide, false); - return false; -} - -static bool GuestShouldGoToShop(Guest& guest, Ride& ride, bool peepAtShop) -{ - // Peeps won't go to the same shop twice in a row. - if (ride.id == guest.PreviousRide) + void Guest::ReadMap() { - guest.ChoseNotToGoOnRide(ride, peepAtShop, true); - return false; - } - - const auto& rtd = ride.getRideTypeDescriptor(); - if (rtd.specialType == RtdSpecialType::toilet) - { - if (guest.Toilet < 70) + if (IsActionInterruptableSafely()) { - guest.ChoseNotToGoOnRide(ride, peepAtShop, true); - return false; - } - - // The amount that peeps are willing to pay to use the Toilets scales with their toilet stat. - // It effectively has a minimum of $0.10 (due to the check above) and a maximum of $0.60. - if ((RideGetPrice(ride) * 40 > guest.Toilet) && !getGameState().cheats.ignorePrice) - { - if (peepAtShop) - { - guest.InsertNewThought(PeepThoughtType::NotPaying, ride.id); - if (guest.HappinessTarget >= 60) - { - guest.HappinessTarget -= 16; - } - ride.updatePopularity(0); - } - guest.ChoseNotToGoOnRide(ride, peepAtShop, true); - return false; + Action = PeepActionType::readMap; + AnimationFrameNum = 0; + AnimationImageIdOffset = 0; + UpdateCurrentAnimationType(); } } - if (rtd.specialType == RtdSpecialType::firstAid) + static bool GuestHasVoucherForFreeRide(Guest& guest, const Ride& ride) { - if (guest.Nausea < 128) - { - guest.ChoseNotToGoOnRide(ride, peepAtShop, true); - return false; - } + return guest.HasItem(ShopItem::voucher) && guest.VoucherType == VOUCHER_TYPE_RIDE_FREE + && guest.VoucherRideId == ride.id; } - // Basic price checks - auto ridePrice = RideGetPrice(ride); - if (ridePrice != 0 && ridePrice > guest.CashInPocket) + /** + * When the queue is full, peeps will ignore the ride when thinking about what to go on next. + * Does not effect peeps that walk up to the queue entrance. + * This flag is reset the next time a peep successfully joins the queue. + */ + static void GuestTriedToEnterFullQueue(Guest& guest, Ride& ride) { - if (peepAtShop) - { - if (guest.CashInPocket <= 0) - { - guest.InsertNewThought(PeepThoughtType::SpentMoney); - } - else - { - guest.InsertNewThought(PeepThoughtType::CantAffordRide, ride.id); - } - } - guest.ChoseNotToGoOnRide(ride, peepAtShop, true); - return false; - } - - if (peepAtShop) - { - ride.updatePopularity(1); + ride.flags.set(RideFlag::queueFull); + guest.PreviousRide = ride.id; + guest.PreviousRideTimeOut = 0; + // Change status "Heading to" to "Walking" if queue is full if (ride.id == guest.GuestHeadingToRideId) { GuestResetRideHeading(guest); } } - return true; -} -// Used when no logging to an expend type required -void Guest::SpendMoney(money64 amount, ExpenditureType expenditure) -{ - money64 unused; - SpendMoney(unused, amount, expenditure); -} - -/** - * - * rct2: 0x0069926C - * Expend type was previously an offset saved in 0x00F1AEC0 - */ -void Guest::SpendMoney(money64& peep_expend_type, money64 amount, ExpenditureType expenditure) -{ - assert(!(getGameState().park.flags & PARK_FLAGS_NO_MONEY)); - - CashInPocket = std::max(0.00_GBP, CashInPocket - amount); - CashSpent = AddClamp(CashSpent, amount); - - peep_expend_type = AddClamp(peep_expend_type, amount); - - auto* windowMgr = Ui::GetWindowManager(); - windowMgr->InvalidateByNumber(WindowClass::peep, Id); - - FinancePayment(-amount, expenditure); - - MoneyEffect::CreateAt(amount, GetLocation(), true); - - Audio::Play3D(Audio::SoundId::purchase, GetLocation()); -} - -void Guest::SetHasRidden(const Ride& ride) -{ - RideUse::GetHistory().Add(Id, ride.id); - - SetHasRiddenRideType(ride.type); -} - -bool Guest::HasRidden(const Ride& ride) const -{ - return RideUse::GetHistory().Contains(Id, ride.id); -} - -void Guest::SetHasRiddenRideType(ride_type_t rideType) -{ - RideUse::GetTypeHistory().Add(Id, rideType); -} - -bool Guest::HasRiddenRideType(ride_type_t rideType) const -{ - return RideUse::GetTypeHistory().Contains(Id, rideType); -} - -void Guest::SetParkEntryTime(int32_t entryTime) -{ - ParkEntryTime = entryTime; -} - -int32_t Guest::GetParkEntryTime() const -{ - return ParkEntryTime; -} - -static bool GuestShouldRideWhileRaining(Guest& guest, const Ride& ride) -{ - // Peeps will go on rides that are sufficiently undercover while it's raining. - // The threshold is fairly low and only requires about 10-15% of the ride to be undercover. - if (ride.shelteredEighths >= 3) + static void GuestResetRideHeading(Guest& guest) { - return true; - } - - // Peeps with umbrellas will go on rides where they can use their umbrella on it (like the Maze) 50% of the time - if (guest.HasItem(ShopItem::umbrella) && ride.getRideTypeDescriptor().flags.has(RtdFlag::guestsCanUseUmbrella) - && (ScenarioRand() & 2) == 0) - { - return true; - } - - return false; -} - -void Guest::ChoseNotToGoOnRide(const Ride& ride, bool peepAtRide, bool updateLastRide) -{ - if (peepAtRide && updateLastRide) - { - PreviousRide = ride.id; - PreviousRideTimeOut = 0; - } - - if (ride.id == GuestHeadingToRideId) - { - GuestResetRideHeading(*this); - } -} - -void Guest::ReadMap() -{ - if (IsActionInterruptableSafely()) - { - Action = PeepActionType::readMap; - AnimationFrameNum = 0; - AnimationImageIdOffset = 0; - UpdateCurrentAnimationType(); - } -} - -static bool GuestHasVoucherForFreeRide(Guest& guest, const Ride& ride) -{ - return guest.HasItem(ShopItem::voucher) && guest.VoucherType == VOUCHER_TYPE_RIDE_FREE && guest.VoucherRideId == ride.id; -} - -/** - * When the queue is full, peeps will ignore the ride when thinking about what to go on next. - * Does not effect peeps that walk up to the queue entrance. - * This flag is reset the next time a peep successfully joins the queue. - */ -static void GuestTriedToEnterFullQueue(Guest& guest, Ride& ride) -{ - ride.flags.set(RideFlag::queueFull); - guest.PreviousRide = ride.id; - guest.PreviousRideTimeOut = 0; - // Change status "Heading to" to "Walking" if queue is full - if (ride.id == guest.GuestHeadingToRideId) - { - GuestResetRideHeading(guest); - } -} - -static void GuestResetRideHeading(Guest& guest) -{ - guest.GuestHeadingToRideId = RideId::GetNull(); - guest.WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_ACTION; -} - -static void GuestRideIsTooIntense(Guest& guest, Ride& ride, bool peepAtRide) -{ - if (peepAtRide) - { - guest.InsertNewThought(PeepThoughtType::Intense, ride.id); - if (guest.HappinessTarget >= 64) - { - guest.HappinessTarget -= 8; - } - ride.updatePopularity(0); - } - guest.ChoseNotToGoOnRide(ride, peepAtRide, true); -} - -/** - * - * rct2: 0x00691C6E - */ -static Vehicle* PeepChooseCarFromRide(Guest& guest, const Ride& ride, std::span carArray) -{ - uint8_t chosen_car = ScenarioRand(); - if (ride.getRideTypeDescriptor().flags.has(RtdFlag::hasGForces) && ((chosen_car & 0xC) != 0xC)) - { - chosen_car = (ScenarioRand() & 1) ? 0 : static_cast(carArray.size()) - 1; - } - else - { - chosen_car = (chosen_car * static_cast(carArray.size())) >> 8; - } - - guest.CurrentCar = carArray[chosen_car]; - - Vehicle* vehicle = getGameState().entities.GetEntity(ride.vehicles[guest.CurrentTrain]); - if (vehicle == nullptr) - { - return nullptr; - } - return vehicle->GetCar(guest.CurrentCar); -} - -/** - * - * rct2: 0x00691CD1 - */ -static void PeepChooseSeatFromCar(Guest* guest, const Ride& ride, Vehicle* vehicle) -{ - if (vehicle == nullptr) - { - return; - } - uint8_t chosen_seat = vehicle->next_free_seat; - - if (ride.mode == RideMode::forwardRotation || ride.mode == RideMode::backwardRotation) - { - chosen_seat = (((~vehicle->flatRideAnimationFrame + 1) >> 3) & 0xF) * 2; - if (vehicle->next_free_seat & 1) - { - chosen_seat++; - } - } - guest->CurrentSeat = chosen_seat; - vehicle->next_free_seat++; - - vehicle->peep[guest->CurrentSeat] = guest->Id; - vehicle->peep_tshirt_colours[guest->CurrentSeat] = guest->TshirtColour; -} - -/** - * - * rct2: 0x00691D27 - */ -void Guest::GoToRideEntrance(const Ride& ride) -{ - const auto& station = ride.getStation(CurrentRideStation); - if (station.Entrance.IsNull()) - { - RemoveFromQueue(); - return; - } - - auto location = station.Entrance.ToCoordsXYZD().ToTileCentre(); - int16_t x_shift = DirectionOffsets[location.direction].x; - int16_t y_shift = DirectionOffsets[location.direction].y; - - uint8_t shift_multiplier = 21; - const auto* rideEntry = GetRideEntryByIndex(ride.subtype); - if (rideEntry != nullptr) - { - if (rideEntry->Cars[rideEntry->DefaultCar].flags.hasAny( - CarEntryFlag::isMiniGolf, CarEntryFlag::isChairlift, CarEntryFlag::isGoKart)) - { - shift_multiplier = 32; - } - } - - x_shift *= shift_multiplier; - y_shift *= shift_multiplier; - - location.x += x_shift; - location.y += y_shift; - - SetDestination(location, 2); - SetState(PeepState::enteringRide); - RideSubState = PeepRideSubState::inEntrance; - - RejoinQueueTimeout = 0; - GuestTimeOnRide = 0; - - RemoveFromQueue(); -} - -static bool FindVehicleToEnter( - Guest& guest, const Ride& ride, sfl::static_vector& car_array) -{ - uint8_t chosen_train = RideStation::kNoTrain; - - if (ride.mode == RideMode::dodgems || ride.mode == RideMode::race) - { - if (ride.flags.has(RideFlag::passStationNoStopping)) - return false; - - for (int32_t i = 0; i < ride.numTrains; ++i) - { - Vehicle* vehicle = getGameState().entities.GetEntity(ride.vehicles[i]); - if (vehicle == nullptr) - continue; - - if (vehicle->next_free_seat >= vehicle->num_seats) - continue; - - if (vehicle->status != Vehicle::Status::waitingForPassengers) - continue; - chosen_train = i; - break; - } - } - else - { - chosen_train = ride.getStation(guest.CurrentRideStation).TrainAtStation; - } - if (chosen_train >= Limits::kMaxTrainsPerRide) - { - return false; - } - - guest.CurrentTrain = chosen_train; - - int32_t i = 0; - - auto vehicle_id = ride.vehicles[chosen_train]; - for (Vehicle* vehicle = getGameState().entities.GetEntity(vehicle_id); vehicle != nullptr; - vehicle = getGameState().entities.GetEntity(vehicle->next_vehicle_on_train), ++i) - { - uint8_t num_seats = vehicle->num_seats; - if (vehicle->IsUsedInPairs()) - { - if (vehicle->next_free_seat & 1) - { - car_array.clear(); - car_array.push_back(i); - return true; - } - num_seats &= kVehicleSeatNumMask; - } - if (num_seats == vehicle->next_free_seat) - continue; - - if (ride.mode == RideMode::forwardRotation || ride.mode == RideMode::backwardRotation) - { - uint8_t position = (((~vehicle->flatRideAnimationFrame + 1) >> 3) & 0xF) * 2; - if (!vehicle->peep[position].IsNull()) - continue; - } - car_array.push_back(i); - } - - return !car_array.empty(); -} - -static void PeepUpdateRideAtEntranceTryLeave(Guest& guest) -{ - // Destination Tolerance is zero when peep has completely - // entered entrance - if (guest.DestinationTolerance == 0) - { - guest.RemoveFromQueue(); - guest.SetState(PeepState::falling); - } -} - -static bool PeepCheckRidePriceAtEntrance(Guest& guest, const Ride& ride, money64 ridePrice) -{ - if ((guest.HasItem(ShopItem::voucher)) && guest.VoucherType == VOUCHER_TYPE_RIDE_FREE - && guest.VoucherRideId == guest.CurrentRide) - return true; - - if (guest.CashInPocket <= 0 && !(getGameState().park.flags & PARK_FLAGS_NO_MONEY)) - { - guest.InsertNewThought(PeepThoughtType::SpentMoney); - PeepUpdateRideAtEntranceTryLeave(guest); - return false; - } - - if (ridePrice > guest.CashInPocket) - { - // Prevent looping of same thought / animation since Destination Tolerance - // is only 0 exactly at entrance and will immediately change as guest - // tries to leave hereafter - if (guest.DestinationTolerance == 0) - { - guest.InsertNewThought(PeepThoughtType::CantAffordRide, guest.CurrentRide); - } - PeepUpdateRideAtEntranceTryLeave(guest); - return false; - } - - auto value = ride.value; - if (value != kRideValueUndefined) - { - if (((value * 2) < ridePrice) && !(getGameState().cheats.ignorePrice)) - { - guest.InsertNewThought(PeepThoughtType::BadValue, guest.CurrentRide); - PeepUpdateRideAtEntranceTryLeave(guest); - return false; - } - } - return true; -} - -/** - * The satisfaction values calculated here are used to determine how happy the peep is with the ride, - * and also affects the satisfaction stat of the ride itself. The factors that affect satisfaction include: - * - The price of the ride compared to the ride's value - * - How closely the intensity and nausea of the ride matches the peep's preferences - * - How long the peep was waiting in the queue - * - If the peep has been on the ride before, or on another ride of the same type - */ -static int16_t GuestCalculateRideSatisfaction(Guest& guest, const Ride& ride) -{ - int16_t satisfaction = GuestCalculateRideValueSatisfaction(guest, ride); - satisfaction += GuestCalculateRideIntensityNauseaSatisfaction(guest, ride); - - // Calculate satisfaction based on how long the peep has been in the queue for. - // (For comparison: peeps start thinking "I've been queueing for a long time" at 3500 and - // start leaving the queue at 4300.) - if (guest.TimeInQueue >= 4500) - satisfaction -= 35; - else if (guest.TimeInQueue >= 2250) - satisfaction -= 10; - else if (guest.TimeInQueue <= 750) - satisfaction += 10; - - // Peeps get a small boost in satisfaction if they've been on a ride of the same type before, - // and this boost is doubled if they've already been on this particular ride. - if (guest.HasRiddenRideType(ride.type)) - satisfaction += 10; - - if (guest.HasRidden(*GetRide(guest.CurrentRide))) - satisfaction += 10; - - return satisfaction; -} - -/** - * Check to see if the specified ride should become the peep's favourite. - * For this, a "ride rating" is calculated based on the excitement of the ride and the satisfaction of the ride. - * As this value cannot exceed 255, the more satisfied the peep is, the more irrelevant the ride's excitement becomes. - * Due to the minimum happiness requirement, an excitement rating of more than 3.8 has no further effect. - * - * If the ride rating is higher than any ride the peep has already been on and the happiness criteria is met, - * the ride becomes the peep's favourite. (This doesn't happen right away, but will be updated once the peep - * exits the ride.) - */ -static void GuestUpdateFavouriteRide(Guest& guest, const Ride& ride, uint8_t satisfaction) -{ - guest.PeepFlags &= ~PEEP_FLAGS_RIDE_SHOULD_BE_MARKED_AS_FAVOURITE; - uint8_t peepRideRating = std::clamp((ride.ratings.excitement / 4) + satisfaction, 0, kPeepMaxHappiness); - if (peepRideRating >= guest.FavouriteRideRating) - { - if (guest.Happiness >= 160 && guest.HappinessTarget >= 160) - { - guest.FavouriteRideRating = peepRideRating; - guest.PeepFlags |= PEEP_FLAGS_RIDE_SHOULD_BE_MARKED_AS_FAVOURITE; - } - } -} - -/* rct2: 0x00695555 */ -static int16_t GuestCalculateRideValueSatisfaction(Guest& guest, const Ride& ride) -{ - if (getGameState().park.flags & PARK_FLAGS_NO_MONEY) - { - return -30; - } - - if (ride.value == kRideValueUndefined) - { - return -30; - } - - auto ridePrice = RideGetPrice(ride); - if (ride.value >= ridePrice) - { - return -5; - } - - if ((ride.value + ((ride.value * guest.Happiness) / 256)) >= ridePrice) - { - return -30; - } - - return 0; -} - -/** - * Calculate satisfaction based on the intensity and nausea of the ride. - * The best possible score from this section is achieved by having the intensity and nausea - * of the ride fall exactly within the peep's preferences, but lower scores can still be achieved - * if the peep's happiness is enough to offset it. - */ -static int16_t GuestCalculateRideIntensityNauseaSatisfaction(Guest& guest, const Ride& ride) -{ - if (!RideHasRatings(ride)) - { - return 70; - } - - uint8_t intensitySatisfaction = 3; - uint8_t nauseaSatisfaction = 3; - RideRating_t maxIntensity = guest.Intensity.GetMaximum() * 100; - RideRating_t minIntensity = guest.Intensity.GetMinimum() * 100; - if (minIntensity <= ride.ratings.intensity && maxIntensity >= ride.ratings.intensity) - { - intensitySatisfaction--; - } - minIntensity -= guest.Happiness * 2; - maxIntensity += guest.Happiness; - if (minIntensity <= ride.ratings.intensity && maxIntensity >= ride.ratings.intensity) - { - intensitySatisfaction--; - } - minIntensity -= guest.Happiness * 2; - maxIntensity += guest.Happiness; - if (minIntensity <= ride.ratings.intensity && maxIntensity >= ride.ratings.intensity) - { - intensitySatisfaction--; - } - - // Although it's not shown in the interface, a peep with Average or High nausea tolerance - // has a minimum preferred nausea value. (For peeps with None or Low, this is set to zero.) - RideRating_t minNausea = kNauseaMinimumThresholds[(EnumValue(guest.NauseaTolerance) & 3)]; - RideRating_t maxNausea = NauseaMaximumThresholds[(EnumValue(guest.NauseaTolerance) & 3)]; - if (minNausea <= ride.ratings.nausea && maxNausea >= ride.ratings.nausea) - { - nauseaSatisfaction--; - } - minNausea -= guest.Happiness * 2; - maxNausea += guest.Happiness; - if (minNausea <= ride.ratings.nausea && maxNausea >= ride.ratings.nausea) - { - nauseaSatisfaction--; - } - minNausea -= guest.Happiness * 2; - maxNausea += guest.Happiness; - if (minNausea <= ride.ratings.nausea && maxNausea >= ride.ratings.nausea) - { - nauseaSatisfaction--; - } - - uint8_t highestSatisfaction = std::max(intensitySatisfaction, nauseaSatisfaction); - uint8_t lowestSatisfaction = std::min(intensitySatisfaction, nauseaSatisfaction); - - switch (highestSatisfaction) - { - default: - case 0: - return 70; - case 1: - switch (lowestSatisfaction) - { - default: - case 0: - return 50; - case 1: - return 35; - } - case 2: - switch (lowestSatisfaction) - { - default: - case 0: - return 35; - case 1: - return 20; - case 2: - return 10; - } - case 3: - switch (lowestSatisfaction) - { - default: - case 0: - return -35; - case 1: - return -50; - case 2: - return -60; - case 3: - return -60; - } - } -} - -/** - * Update the nausea growth of the peep based on a ride. This is calculated based on: - * - The nausea rating of the ride - * - Their new happiness growth rate (the higher, the less nauseous) - * - How hungry the peep is (+0% nausea at 50% hunger up to +100% nausea at 100% hunger) - * - The peep's nausea tolerance (Final modifier: none: 100%, low: 50%, average: 25%, high: 12.5%) - */ -static void GuestUpdateRideNauseaGrowth(Guest& guest, const Ride& ride) -{ - const auto nauseaMultiplier = std::clamp(256 - guest.HappinessTarget, 64, 200); - const auto rideGeneratedNausea = (ride.ratings.nausea * nauseaMultiplier) / 512; - const auto hungerAdjustedNausea = ((rideGeneratedNausea * std::max(128, guest.Hunger)) / 128) * 2; - const auto nauseaGrowthRateChange = hungerAdjustedNausea >> (EnumValue(guest.NauseaTolerance) & 3); - guest.NauseaTarget = static_cast(std::min(guest.NauseaTarget + nauseaGrowthRateChange, 255)); -} - -static bool GuestShouldGoOnRideAgain(Guest& guest, const Ride& ride) -{ - if (!ride.getRideTypeDescriptor().flags.has(RtdFlag::guestsWillRideAgain)) - return false; - if (!RideHasRatings(ride)) - return false; - if (ride.ratings.intensity > RideRating::make(10, 00) && !getGameState().cheats.ignoreRideIntensity) - return false; - if (guest.Happiness < 180) - return false; - if (guest.Energy < 100) - return false; - if (guest.Nausea > 160) - return false; - if (guest.Hunger < 30) - return false; - if (guest.Thirst < 20) - return false; - if (guest.Toilet > 170) - return false; - - uint8_t r = (ScenarioRand() & 0xFF); - if (r <= 128) - { - if (guest.GuestNumRides > 7) - return false; - if (r > 64) - return false; - } - - return true; -} - -static bool GuestShouldPreferredIntensityIncrease(Guest& guest) -{ - if (getGameState().park.flags & PARK_FLAGS_PREF_LESS_INTENSE_RIDES) - return false; - if (guest.Happiness < 200) - return false; - - return (ScenarioRand() & 0xFF) >= static_cast(guest.Intensity); -} - -static bool GuestReallyLikedRide(Guest& guest, const Ride& ride) -{ - if (guest.Happiness < 215) - return false; - if (guest.Nausea > 120) - return false; - if (!RideHasRatings(ride)) - return false; - if (ride.ratings.intensity > RideRating::make(10, 00) && !getGameState().cheats.ignoreRideIntensity) - return false; - return true; -} - -/** - * - * rct2: 0x0069BC9A - */ -static PeepThoughtType GuestAssessSurroundings(int16_t centre_x, int16_t centre_y, int16_t centre_z) -{ - if ((TileElementHeight({ centre_x, centre_y })) > centre_z) - return PeepThoughtType::None; - - uint16_t num_scenery = 0; - uint16_t num_fountains = 0; - uint16_t nearby_music = 0; - uint16_t num_rubbish = 0; - - // TODO: Refactor this to step as tiles, 160 units is 5 tiles. - int16_t initial_x = std::max(centre_x - 160, 0); - int16_t initial_y = std::max(centre_y - 160, 0); - int16_t final_x = std::min(centre_x + 160, kMaximumMapSizeBig); - int16_t final_y = std::min(centre_y + 160, kMaximumMapSizeBig); - - for (int16_t x = initial_x; x < final_x; x += kCoordsXYStep) - { - for (int16_t y = initial_y; y < final_y; y += kCoordsXYStep) - { - for (auto* tileElement : TileElementsView(CoordsXY{ x, y })) - { - if (tileElement->IsGhost()) - { - continue; - } - - switch (tileElement->GetType()) - { - case TileElementType::Path: - { - if (!tileElement->AsPath()->HasAddition()) - break; - - auto* pathAddEntry = tileElement->AsPath()->GetAdditionEntry(); - if (pathAddEntry == nullptr) - { - return PeepThoughtType::None; - } - if (tileElement->AsPath()->AdditionIsGhost()) - break; - - if (pathAddEntry->flags - & (PATH_ADDITION_FLAG_JUMPING_FOUNTAIN_WATER | PATH_ADDITION_FLAG_JUMPING_FOUNTAIN_SNOW)) - { - num_fountains++; - break; - } - if (tileElement->AsPath()->IsBroken()) - { - num_rubbish++; - } - break; - } - case TileElementType::LargeScenery: - case TileElementType::SmallScenery: - num_scenery++; - break; - case TileElementType::Track: - { - auto* ride = GetRide(tileElement->AsTrack()->GetRideIndex()); - if (ride == nullptr) - break; - - bool isPlayingMusic = ride->flags.has(RideFlag::music) && ride->status != RideStatus::closed - && !ride->flags.hasAny(RideFlag::brokenDown, RideFlag::crashed); - if (!isPlayingMusic) - break; - - const auto* musicObject = ride->getMusicObject(); - if (musicObject == nullptr) - break; - - if (musicObject->GetNiceFactor() == MusicNiceFactor::Nice) - { - nearby_music |= 1; - } - else if (musicObject->GetNiceFactor() == MusicNiceFactor::Overbearing) - { - nearby_music |= 2; - } - - break; - } - default: - break; - } - } - } - } - - for (auto litter : EntityList()) - { - int16_t dist_x = abs(litter->x - centre_x); - int16_t dist_y = abs(litter->y - centre_y); - if (std::max(dist_x, dist_y) <= 160) - { - num_rubbish++; - } - } - - if (num_fountains >= 5 && num_rubbish < 20) - return PeepThoughtType::Fountains; - - if (num_scenery >= 40 && num_rubbish < 8) - return PeepThoughtType::Scenery; - - if (nearby_music == 1 && num_rubbish < 20) - return PeepThoughtType::Music; - - if (num_rubbish < 2 && !getGameState().cheats.disableLittering) - // if disable littering cheat is enabled, peeps will not have the "clean and tidy park" thought - return PeepThoughtType::VeryClean; - - return PeepThoughtType::None; -} - -/** - * - * rct2: 0x0068F9A9 - */ -static void GuestUpdateHunger(Guest& guest) -{ - if (guest.Hunger >= 3) - { - guest.Hunger -= 2; - - guest.EnergyTarget = std::min(guest.EnergyTarget + 2, kPeepMaxEnergyTarget); - guest.Toilet = std::min(guest.Toilet + 1, 255); - } -} - -/** - * Main purpose is to decide when peeps leave the park due to - * low happiness, low energy and (if appropriate) low money. - * - * rct2: 0x0068F8CD - */ -static void GuestDecideWhetherToLeavePark(Guest& guest) -{ - if (guest.EnergyTarget >= 33) - { - guest.EnergyTarget -= 2; - } - - if (getGameState().weatherCurrent.temperature >= 21 && guest.Thirst >= 5) - { - guest.Thirst--; - } - - if (guest.OutsideOfPark) - { - return; - } - - /* Peeps that are happy enough, have enough energy and - * (if appropriate) have enough money will always stay - * in the park. */ - if (!(guest.PeepFlags & PEEP_FLAGS_LEAVING_PARK)) - { - if (getGameState().park.flags & PARK_FLAGS_NO_MONEY) - { - if (guest.Energy >= 70 && guest.Happiness >= 60) - { - return; - } - } - else - { - if (guest.Energy >= 55 && guest.Happiness >= 45 && guest.CashInPocket >= 5.00_GBP) - { - return; - } - } - } - - // Approx 95% chance of staying in the park - if ((ScenarioRand() & 0xFFFF) > 3276) - { - return; - } - - // In the remaining 5% chance the peep leaves the park. - GuestLeavePark(guest); -} - -/** - * - * rct2: 0x0068F93E - */ -static void GuestLeavePark(Guest& guest) -{ - guest.GuestHeadingToRideId = RideId::GetNull(); - if (guest.PeepFlags & PEEP_FLAGS_LEAVING_PARK) - { - if (guest.GuestIsLostCountdown < 60) - { - return; - } - } - else - { - guest.GuestIsLostCountdown = 254; - guest.PeepFlags |= PEEP_FLAGS_LEAVING_PARK; - guest.PeepFlags &= ~PEEP_FLAGS_PARK_ENTRANCE_CHOSEN; - } - - guest.InsertNewThought(PeepThoughtType::GoHome); - - auto* windowMgr = Ui::GetWindowManager(); - WindowBase* w = windowMgr->FindByNumber(WindowClass::peep, guest.Id); - if (w != nullptr) - w->onPrepareDraw(); - windowMgr->InvalidateByNumber(WindowClass::peep, guest.Id); -} - -template -static void PeepHeadForNearestRide(Guest& guest, bool considerOnlyCloseRides, T predicate) -{ - if (guest.State != PeepState::sitting && guest.State != PeepState::watching && guest.State != PeepState::walking) - { - return; - } - if (guest.PeepFlags & PEEP_FLAGS_LEAVING_PARK) - return; - if (guest.x == kLocationNull) - return; - if (!guest.GuestHeadingToRideId.IsNull()) - { - auto ride = GetRide(guest.GuestHeadingToRideId); - if (ride != nullptr && predicate(*ride)) - { - return; - } - } - - OpenRCT2::BitSet rideConsideration; - if (!considerOnlyCloseRides && (guest.HasItem(ShopItem::map))) - { - // Consider all rides in the park - auto& gameState = getGameState(); - for (const auto& ride : RideManager(gameState)) - { - if (predicate(ride)) - { - rideConsideration[ride.id.ToUnderlying()] = true; - } - } - } - else - { - // Take nearby rides into consideration - constexpr auto kSearchRadius = 10 * 32; - int32_t cx = Numerics::floor2(guest.x, 32); - int32_t cy = Numerics::floor2(guest.y, 32); - for (auto x = cx - kSearchRadius; x <= cx + kSearchRadius; x += kCoordsXYStep) - { - for (auto y = cy - kSearchRadius; y <= cy + kSearchRadius; y += kCoordsXYStep) - { - auto location = CoordsXY{ x, y }; - if (!MapIsLocationValid(location)) - continue; - - for (auto* trackElement : TileElementsView(location)) - { - auto rideIndex = trackElement->GetRideIndex(); - auto ride = GetRide(rideIndex); - if (ride == nullptr) - continue; - - if (!predicate(*ride)) - continue; - - rideConsideration[ride->id.ToUnderlying()] = true; - } - } - } - } - - // Filter the considered rides - RideId potentialRides[Limits::kMaxRidesInPark]; - size_t numPotentialRides = 0; - - auto& gameState = getGameState(); - for (auto& ride : RideManager(gameState)) - { - if (rideConsideration[ride.id.ToUnderlying()]) - { - if (!ride.flags.has(RideFlag::queueFull)) - { - if (guest.ShouldGoOnRide(ride, StationIndex::FromUnderlying(0), false, true)) - { - potentialRides[numPotentialRides++] = ride.id; - } - } - } - } - - // Pick the closest ride - Ride* closestRide{}; - auto closestRideDistance = std::numeric_limits::max(); - for (size_t i = 0; i < numPotentialRides; i++) - { - auto ride = GetRide(potentialRides[i]); - if (ride != nullptr) - { - auto rideLocation = ride->getStation().Start; - int32_t distance = abs(rideLocation.x - guest.x) + abs(rideLocation.y - guest.y); - if (distance < closestRideDistance) - { - closestRide = ride; - closestRideDistance = distance; - } - } - } - if (closestRide != nullptr) - { - // Head to that ride - guest.GuestHeadingToRideId = closestRide->id; - guest.GuestIsLostCountdown = 200; - guest.ResetPathfindGoal(); + guest.GuestHeadingToRideId = RideId::GetNull(); guest.WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_ACTION; - guest.TimeLost = 0; } -} -static void GuestHeadForNearestRideWithFlag(Guest& guest, bool considerOnlyCloseRides, RtdFlag rtdFlag) -{ - PeepHeadForNearestRide( - guest, considerOnlyCloseRides, [rtdFlag](const Ride& ride) { return ride.getRideTypeDescriptor().flags.has(rtdFlag); }); -} - -static void GuestHeadForNearestRideWithSpecialType(Guest& guest, bool considerOnlyCloseRides, RtdSpecialType specialType) -{ - if ((specialType == RtdSpecialType::toilet) && guest.HasFoodOrDrink()) + static void GuestRideIsTooIntense(Guest& guest, Ride& ride, bool peepAtRide) { - return; - } - PeepHeadForNearestRide(guest, considerOnlyCloseRides, [specialType](const Ride& ride) { - return ride.getRideTypeDescriptor().specialType == specialType; - }); -} - -/** - * - * rct2: 0x00699FE3 - * Stops peeps that are having thoughts - * such as "I'm hungry" after visiting a food shop. - * Works for Thirst/Hungry/Low Money/Toilet - */ -static void GuestStopPurchaseThought(Guest& guest, ride_type_t rideType) -{ - auto thoughtType = PeepThoughtType::Hungry; - - const auto& rtd = GetRideTypeDescriptor(rideType); - if (!rtd.flags.has(RtdFlag::sellsFood)) - { - thoughtType = PeepThoughtType::Thirsty; - if (!rtd.flags.has(RtdFlag::sellsDrinks)) + if (peepAtRide) { - thoughtType = PeepThoughtType::RunningOut; - if (rtd.specialType != RtdSpecialType::cashMachine) + guest.InsertNewThought(PeepThoughtType::Intense, ride.id); + if (guest.HappinessTarget >= 64) { - thoughtType = PeepThoughtType::Toilet; - if (rtd.specialType != RtdSpecialType::toilet) - { - return; - } + guest.HappinessTarget -= 8; } + ride.updatePopularity(0); } + guest.ChoseNotToGoOnRide(ride, peepAtRide, true); } - // Remove the related thought - for (int32_t i = 0; i < kPeepMaxThoughts; ++i) + /** + * + * rct2: 0x00691C6E + */ + static Vehicle* PeepChooseCarFromRide(Guest& guest, const Ride& ride, std::span carArray) { - PeepThought* thought = &guest.Thoughts[i]; - - if (thought->type == PeepThoughtType::None) - break; - - if (thought->type != thoughtType) - continue; - - if (i < kPeepMaxThoughts - 1) + uint8_t chosen_car = ScenarioRand(); + if (ride.getRideTypeDescriptor().flags.has(RtdFlag::hasGForces) && ((chosen_car & 0xC) != 0xC)) { - memmove(thought, thought + 1, sizeof(PeepThought) * (kPeepMaxThoughts - i - 1)); - } - - guest.Thoughts[kPeepMaxThoughts - 1].type = PeepThoughtType::None; - - guest.WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_THOUGHTS; - i--; - } -} - -/** - * - * rct2: 0x0069AEB7 - */ -static bool PeepShouldUseCashMachine(Guest& guest, RideId rideIndex) -{ - if (getGameState().park.flags & PARK_FLAGS_NO_MONEY) - return false; - if (guest.PeepFlags & PEEP_FLAGS_LEAVING_PARK) - return false; - if (guest.CashInPocket > 20.00_GBP) - return false; - if (115 + (ScenarioRand() % 128) > guest.Happiness) - return false; - if (guest.Energy < 80) - return false; - - auto ride = GetRide(rideIndex); - if (ride != nullptr) - { - ride->updateSatisfaction(guest.Happiness >> 6); - ride->curNumCustomers++; - ride->totalCustomers = AddClamp(ride->totalCustomers, 1u); - ride->windowInvalidateFlags.set(RideInvalidateFlag::customers); - } - return true; -} - -/** - * - * rct2: 0x006912A3 - */ -void Guest::UpdateBuying() -{ - if (!CheckForPath()) - return; - - auto ride = GetRide(CurrentRide); - if (ride == nullptr || ride->status != RideStatus::open) - { - SetState(PeepState::falling); - return; - } - - if (SubState == 1) - { - if (!IsActionWalking()) - { - UpdateAction(); - Invalidate(); - return; - } - - const auto& rtd = GetRideTypeDescriptor(ride->type); - if (rtd.specialType == RtdSpecialType::cashMachine) - { - if (CurrentRide != PreviousRide) - { - CashInPocket += 50.00_GBP; - } - auto* windowMgr = Ui::GetWindowManager(); - windowMgr->InvalidateByNumber(WindowClass::peep, Id); - } - Orientation ^= 0x10; - - auto destination = CoordsXY{ 16, 16 } + NextLoc; - SetDestination(destination); - PeepDirection = DirectionReverse(PeepDirection); - - SetState(PeepState::walking); - return; - } - - bool item_bought = false; - - if (CurrentRide != PreviousRide) - { - const auto& rtd = GetRideTypeDescriptor(ride->type); - if (rtd.specialType == RtdSpecialType::cashMachine) - { - item_bought = PeepShouldUseCashMachine(*this, CurrentRide); - if (!item_bought) - { - PreviousRide = CurrentRide; - PreviousRideTimeOut = 0; - } - else - { - Action = PeepActionType::withdrawMoney; - AnimationFrameNum = 0; - AnimationImageIdOffset = 0; - - UpdateCurrentAnimationType(); - - ride->numPrimaryItemsSold = AddClamp(ride->numPrimaryItemsSold, 1u); - } + chosen_car = (ScenarioRand() & 1) ? 0 : static_cast(carArray.size()) - 1; } else { - const auto* ride_type = GetRideEntryByIndex(ride->subtype); - if (ride_type == nullptr) - { - return; - } - if (ride_type->shop_item[1] != ShopItem::none) - { - auto price = ride->price[1]; - - item_bought = GuestDecideAndBuyItem(*this, *ride, ride_type->shop_item[1], price); - if (item_bought) - { - ride->numSecondaryItemsSold = AddClamp(ride->numSecondaryItemsSold, 1u); - } - } - - if (!item_bought && ride_type->shop_item[0] != ShopItem::none) - { - auto price = ride->price[0]; - - item_bought = GuestDecideAndBuyItem(*this, *ride, ride_type->shop_item[0], price); - if (item_bought) - { - ride->numPrimaryItemsSold = AddClamp(ride->numPrimaryItemsSold, 1u); - } - } + chosen_car = (chosen_car * static_cast(carArray.size())) >> 8; } - } - if (item_bought) - { - ride->updatePopularity(1); + guest.CurrentCar = carArray[chosen_car]; - GuestStopPurchaseThought(*this, ride->type); - } - else - { - ride->updatePopularity(0); - } - SubState = 1; -} - -/** - * - * rct2: 0x00691A3B - */ -void Guest::UpdateRideAtEntrance() -{ - auto ride = GetRide(CurrentRide); - if (ride == nullptr) - return; - - // The peep will keep advancing in the entranceway - // whilst in this state. When it has reached the very - // front of the queue destination tolerance is set to - // zero to indicate it is final decision time (try_leave will pass). - // When a peep has to return to the queue without getting on a ride - // this is the state it will return to. - if (DestinationTolerance != 0) - { - int16_t xy_distance; - if (auto loc = UpdateAction(xy_distance); loc.has_value()) + Vehicle* vehicle = getGameState().entities.GetEntity(ride.vehicles[guest.CurrentTrain]); + if (vehicle == nullptr) { - int16_t actionZ = z; - if (xy_distance < 16) - { - const auto& station = ride->getStation(CurrentRideStation); - auto entrance = station.Entrance.ToCoordsXYZ(); - actionZ = entrance.z + 2; - } - MoveTo({ loc.value(), actionZ }); - } - else - { - DestinationTolerance = 0; - Orientation ^= (1 << 4); - Invalidate(); + return nullptr; } + return vehicle->GetCar(guest.CurrentCar); } - sfl::static_vector carArray; - - if (ride->getRideTypeDescriptor().flags.has(RtdFlag::noVehicles)) + /** + * + * rct2: 0x00691CD1 + */ + static void PeepChooseSeatFromCar(Guest* guest, const Ride& ride, Vehicle* vehicle) { - if (ride->numRiders >= ride->operationOption) - return; - } - else - { - if (!FindVehicleToEnter(*this, *ride, carArray)) - return; - } - - if (ride->status != RideStatus::open || ride->vehicleChangeTimeout != 0) - { - PeepUpdateRideAtEntranceTryLeave(*this); - return; - } - - if (ride->flags.has(RideFlag::brokenDown)) - return; - - auto ridePrice = RideGetPrice(*ride); - if (ridePrice != 0) - { - if (!PeepCheckRidePriceAtEntrance(*this, *ride, ridePrice)) - return; - } - - if (!ride->getRideTypeDescriptor().flags.has(RtdFlag::noVehicles)) - { - Vehicle* vehicle = PeepChooseCarFromRide(*this, *ride, carArray); - PeepChooseSeatFromCar(this, *ride, vehicle); - } - GoToRideEntrance(*ride); -} - -/** rct2: 0x00981FD4, 0x00981FD6 */ -static constexpr CoordsXY kMazeEntranceStart[] = { - { 8, 8 }, - { 8, 24 }, - { 24, 24 }, - { 24, 8 }, -}; - -void PeepUpdateRideLeaveEntranceMaze(Guest& guest, Ride& ride, CoordsXYZD& entrance_loc) -{ - guest.MazeLastEdge = entrance_loc.direction + 1; - - entrance_loc.x += CoordsDirectionDelta[entrance_loc.direction].x; - entrance_loc.y += CoordsDirectionDelta[entrance_loc.direction].y; - - uint8_t direction = entrance_loc.direction * 4 + 11; - if (ScenarioRand() & 0x40) - { - direction += 4; - guest.MazeLastEdge += 2; - } - - direction &= 0xF; - // Direction is 11, 15, 3, or 7 - guest.Var37 = direction; - guest.MazeLastEdge &= 3; - - entrance_loc.x += kMazeEntranceStart[direction / 4].x; - entrance_loc.y += kMazeEntranceStart[direction / 4].y; - - guest.SetDestination(entrance_loc, 3); - - ride.curNumCustomers++; - guest.OnEnterRide(ride); - guest.RideSubState = PeepRideSubState::mazePathfinding; -} - -void PeepUpdateRideLeaveEntranceSpiralSlide(Guest& guest, Ride& ride, CoordsXYZD& entrance_loc) -{ - entrance_loc = { ride.getStation(guest.CurrentRideStation).GetStart(), entrance_loc.direction }; - - TileElement* tile_element = RideGetStationStartTrackElement(ride, guest.CurrentRideStation); - - uint8_t direction_track = (tile_element == nullptr ? 0 : tile_element->GetDirection()); - - guest.Var37 = (entrance_loc.direction << 2) | (direction_track << 4); - - entrance_loc += kSpiralSlideWalkingPath[guest.Var37]; - - guest.SetDestination(entrance_loc); - guest.timesSlidDown = 0; - - ride.curNumCustomers++; - guest.OnEnterRide(ride); - guest.RideSubState = PeepRideSubState::approachSpiralSlide; -} - -void PeepUpdateRideLeaveEntranceDefault(Guest& guest, Ride& ride, CoordsXYZD& entrance_loc) -{ - const auto currentTicks = getGameState().currentTicks; - - // If the ride type was changed guests will become stuck. - // Inform the player about this if its a new issue or hasn't been addressed within 120 seconds. - if ((ride.currentIssues & RIDE_ISSUE_GUESTS_STUCK) == 0 || currentTicks - ride.lastIssueTime > 3000) - { - ride.currentIssues |= RIDE_ISSUE_GUESTS_STUCK; - ride.lastIssueTime = currentTicks; - - auto ft = Formatter(); - ride.formatNameTo(ft); - if (Config::Get().notifications.rideWarnings) - { - News::AddItemToQueue(News::ItemType::ride, STR_GUESTS_GETTING_STUCK_ON_RIDE, guest.CurrentRide.ToUnderlying(), ft); - } - } -} - -uint8_t Guest::GetWaypointedSeatLocation(const Ride& ride, const CarEntry* vehicle_type, uint8_t track_direction) const -{ - // The seatlocation can be split into segments around the ride base - // to decide the segment first split off the segmentable seat location - // from the fixed section - uint8_t seatLocationSegment = CurrentSeat & 0x7; - uint8_t seatLocationFixed = CurrentSeat & 0xF8; - - // Enterprise has more segments (8) compared to the normal (4) - if (ride.getRideTypeDescriptor().specialType != RtdSpecialType::enterprise) - track_direction *= 2; - - // Type 1 loading doesn't do segments and all peeps go to the same - // location on the ride - if (vehicle_type->peep_loading_waypoint_segments == 0) - { - track_direction /= 2; - seatLocationSegment = 0; - seatLocationFixed = 0; - } - seatLocationSegment += track_direction; - seatLocationSegment &= 0x7; - return seatLocationSegment + seatLocationFixed; -} - -void Guest::UpdateRideLeaveEntranceWaypoints(const Ride& ride) -{ - const auto& station = ride.getStation(CurrentRideStation); - if (station.Entrance.IsNull()) - { - return; - } - uint8_t direction_entrance = station.Entrance.direction; - - TileElement* tile_element = RideGetStationStartTrackElement(ride, CurrentRideStation); - - uint8_t direction_track = (tile_element == nullptr ? 0 : tile_element->GetDirection()); - - auto vehicle = getGameState().entities.GetEntity(ride.vehicles[CurrentTrain]); - if (vehicle == nullptr) - { - // TODO: Goto ride exit on failure. - return; - } - const auto* rideEntry = vehicle->GetRideEntry(); - const auto* carEntry = &rideEntry->Cars[vehicle->vehicle_type]; - - Var37 = (direction_entrance | GetWaypointedSeatLocation(ride, carEntry, direction_track) * 4) * 4; - - const auto& rtd = ride.getRideTypeDescriptor(); - CoordsXY waypoint = rtd.GetGuestWaypointLocation(*vehicle, ride, CurrentRideStation); - - const auto waypointIndex = Var37 / 4u; - if (waypointIndex < carEntry->peep_loading_waypoints.size()) - { - Guard::Assert(carEntry->peep_loading_waypoints.size() >= static_cast(waypointIndex)); - waypoint.x += carEntry->peep_loading_waypoints[waypointIndex][0].x; - waypoint.y += carEntry->peep_loading_waypoints[waypointIndex][0].y; - } - - SetDestination(waypoint); - RideSubState = PeepRideSubState::approachVehicleWaypoints; -} - -/** - * - * rct2: 0x006921D3 - */ -void Guest::UpdateRideAdvanceThroughEntrance() -{ - auto ride = GetRide(CurrentRide); - if (ride == nullptr) - return; - - int16_t actionZ, xy_distance; - - const auto* rideEntry = ride->getRideEntry(); - - if (auto loc = UpdateAction(xy_distance); loc.has_value()) - { - uint16_t distanceThreshold = 16; - if (rideEntry != nullptr) - { - uint8_t vehicle = rideEntry->DefaultCar; - if (rideEntry->Cars[vehicle].flags.hasAny( - CarEntryFlag::isMiniGolf, CarEntryFlag::isChairlift, CarEntryFlag::isGoKart)) - { - distanceThreshold = 28; - } - } - - if (RideSubState == PeepRideSubState::inEntrance && xy_distance < distanceThreshold) - { - RideSubState = PeepRideSubState::freeVehicleCheck; - } - - actionZ = ride->getStation(CurrentRideStation).GetBaseZ(); - - distanceThreshold += 4; - if (xy_distance < distanceThreshold) - { - actionZ += ride->getRideTypeDescriptor().Heights.PlatformHeight; - } - - MoveTo({ loc.value(), actionZ }); - return; - } - - if (RideSubState == PeepRideSubState::inEntrance) - { - RideSubState = PeepRideSubState::freeVehicleCheck; - return; - } - - if (ride->getRideTypeDescriptor().flags.has(RtdFlag::noVehicles)) - { - const auto& station = ride->getStation(CurrentRideStation); - auto entranceLocation = station.Entrance.ToCoordsXYZD(); - if (entranceLocation.IsNull()) - { - return; - } - - const auto& rtd = GetRideTypeDescriptor(ride->type); - rtd.UpdateLeaveEntrance(*this, *ride, entranceLocation); - return; - } - - Vehicle* vehicle = getGameState().entities.GetEntity(ride->vehicles[CurrentTrain]); - if (vehicle == nullptr) - { - return; - } - - vehicle = vehicle->GetCar(CurrentCar); - if (vehicle == nullptr) - { - return; - } - - rideEntry = vehicle->GetRideEntry(); - if (rideEntry == nullptr) - { - return; - } - - const auto* vehicle_type = &rideEntry->Cars[vehicle->vehicle_type]; - - if (vehicle_type->flags.has(CarEntryFlag::loadingWaypoints)) - { - UpdateRideLeaveEntranceWaypoints(*ride); - return; - } - - if (vehicle_type->flags.has(CarEntryFlag::useDodgemCarPlacement)) - { - SetDestination(vehicle->GetLocation(), 15); - RideSubState = PeepRideSubState::approachVehicle; - return; - } - - int8_t load_position = 0; - // Safe, in case current seat > number of loading positions - uint16_t numSeatPositions = static_cast(vehicle_type->peep_loading_positions.size()); - if (numSeatPositions != 0) - { - size_t loadPositionIndex = numSeatPositions - 1; - if (CurrentSeat < numSeatPositions) - { - loadPositionIndex = CurrentSeat; - } - load_position = vehicle_type->peep_loading_positions[loadPositionIndex]; - } - - auto destination = GetDestination(); - auto loadPositionWithReversal = (vehicle->flags.has(VehicleFlag::carIsReversed)) ? -load_position : load_position; - switch (vehicle->Orientation / 8) - { - case 0: - destination.x = vehicle->x - loadPositionWithReversal; - break; - case 1: - destination.y = vehicle->y + loadPositionWithReversal; - break; - case 2: - destination.x = vehicle->x + loadPositionWithReversal; - break; - case 3: - destination.y = vehicle->y - loadPositionWithReversal; - break; - } - SetDestination(destination); - - RideSubState = PeepRideSubState::approachVehicle; -} - -/** - * - * rct2: 0x0069321D - */ -static void PeepGoToRideExit(Guest& guest, const Ride& ride, int16_t x, int16_t y, int16_t z, uint8_t exit_direction) -{ - z += ride.getRideTypeDescriptor().Heights.PlatformHeight; - - guest.MoveTo({ x, y, z }); - - Guard::Assert(guest.CurrentRideStation.ToUnderlying() < Limits::kMaxStationsPerRide); - auto exit = ride.getStation(guest.CurrentRideStation).Exit; - x = exit.x; - y = exit.y; - x *= 32; - y *= 32; - x += 16; - y += 16; - - auto [x_shift, y_shift] = [exit_direction]() { - if (exit_direction < DirectionOffsets.size()) - { - return std::pair(DirectionOffsets[exit_direction].x, DirectionOffsets[exit_direction].y); - } - else - { - return std::pair(0, 0); - } - }(); - - int16_t shift_multiplier = 20; - - const auto* rideEntry = GetRideEntryByIndex(ride.subtype); - if (rideEntry != nullptr) - { - const CarEntry& carEntry = rideEntry->Cars[rideEntry->DefaultCar]; - if (carEntry.flags.hasAny(CarEntryFlag::isMiniGolf, CarEntryFlag::isChairlift, CarEntryFlag::isGoKart)) - { - shift_multiplier = 32; - } - } - - x_shift *= shift_multiplier; - y_shift *= shift_multiplier; - - x -= x_shift; - y -= y_shift; - - guest.SetDestination({ x, y }, 2); - - guest.Orientation = exit_direction * 8; - guest.RideSubState = PeepRideSubState::approachExit; -} - -/** - * - * rct2: 0x006920B4 - */ -void Guest::UpdateRideFreeVehicleEnterRide(Ride& ride) -{ - auto ridePrice = RideGetPrice(ride); - if (ridePrice != 0) - { - if ((HasItem(ShopItem::voucher)) && (VoucherType == VOUCHER_TYPE_RIDE_FREE) && (VoucherRideId == CurrentRide)) - { - RemoveItem(ShopItem::voucher); - WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_INVENTORY; - } - else - { - ride.totalProfit = AddClamp(ride.totalProfit, ridePrice); - ride.windowInvalidateFlags.set(RideInvalidateFlag::income); - SpendMoney(PaidOnRides, ridePrice, ExpenditureType::parkRideTickets); - } - } - - RideSubState = PeepRideSubState::leaveEntrance; - uint8_t queueTime = DaysInQueue; - if (queueTime < 253) - queueTime += 3; - - queueTime /= 2; - auto& station = ride.getStation(CurrentRideStation); - if (queueTime != station.QueueTime) - { - station.QueueTime = queueTime; - auto* windowMgr = Ui::GetWindowManager(); - windowMgr->InvalidateByNumber(WindowClass::ride, CurrentRide.ToUnderlying()); - } - - if (PeepFlags & PEEP_FLAGS_TRACKING) - { - auto ft = Formatter(); - FormatNameTo(ft); - ride.formatNameTo(ft); - - StringId msg_string; - if (ride.getRideTypeDescriptor().flags.has(RtdFlag::describeAsInside)) - msg_string = STR_PEEP_TRACKING_PEEP_IS_IN_X; - else - msg_string = STR_PEEP_TRACKING_PEEP_IS_ON_X; - - if (Config::Get().notifications.guestOnRide) - { - News::AddItemToQueue(News::ItemType::peepOnRide, msg_string, Id, ft); - } - } - - const auto& rtd = ride.getRideTypeDescriptor(); - if (rtd.specialType == RtdSpecialType::spiralSlide) - { - SwitchToSpecialSprite(1); - } - - UpdateRideAdvanceThroughEntrance(); -} - -/** - * - * rct2: 0x00691FD4 - */ -static void PeepUpdateRideNoFreeVehicleRejoinQueue(Guest& guest, Ride& ride) -{ - TileCoordsXYZD entranceLocation = ride.getStation(guest.CurrentRideStation).Entrance; - - int32_t x = entranceLocation.x * 32; - int32_t y = entranceLocation.y * 32; - if (entranceLocation.direction < DirectionOffsets.size()) - { - x += 16 - DirectionOffsets[entranceLocation.direction].x * 20; - y += 16 - DirectionOffsets[entranceLocation.direction].y * 20; - } - - guest.SetDestination({ x, y }, 2); - guest.SetState(PeepState::queuingFront); - guest.RideSubState = PeepRideSubState::atEntrance; - - ride.queueInsertGuestAtFront(guest.CurrentRideStation, &guest); -} - -/** - * - * rct2: 0x00691E42 - * Note: Before this was the entry - * point for sub state 1 and 3. The - * check has been removed that would - * branch it out to 1 and 3. Now uses - * separate functions. - */ -void Guest::UpdateRideFreeVehicleCheck() -{ - auto ride = GetRide(CurrentRide); - if (ride == nullptr) - return; - - if (ride->getRideTypeDescriptor().flags.has(RtdFlag::noVehicles)) - { - if (ride->status != RideStatus::open || ride->vehicleChangeTimeout != 0 || (++RejoinQueueTimeout) == 0) - { - PeepUpdateRideNoFreeVehicleRejoinQueue(*this, *ride); - return; - } - - UpdateRideFreeVehicleEnterRide(*ride); - return; - } - - auto& gameState = getGameState(); - Vehicle* vehicle = gameState.entities.GetEntity(ride->vehicles[CurrentTrain]); - if (vehicle == nullptr) - { - // TODO: Leave ride on failure goes for all returns on nullptr in this function - return; - } - vehicle = vehicle->GetCar(CurrentCar); - if (vehicle == nullptr) - return; - - const auto* rideEntry = vehicle->GetRideEntry(); - if (rideEntry == nullptr) - { - return; - } - - if (rideEntry->Cars[0].flags.has(CarEntryFlag::isMiniGolf)) - { - vehicle->miniGolfFlags.unset(MiniGolfFlag::flag5); - - for (size_t i = 0; i < ride->numTrains; ++i) - { - Vehicle* train = gameState.entities.GetEntity(ride->vehicles[i]); - if (train == nullptr) - continue; - - Vehicle* second_vehicle = gameState.entities.GetEntity(train->next_vehicle_on_train); - if (second_vehicle == nullptr) - continue; - - if (second_vehicle->num_peeps == 0) - continue; - - if (second_vehicle->miniGolfFlags.has(MiniGolfFlag::flag5)) - continue; - - return; - } - } - - if (!vehicle->IsUsedInPairs()) - { - UpdateRideFreeVehicleEnterRide(*ride); - return; - } - - if (ride->mode == RideMode::forwardRotation || ride->mode == RideMode::backwardRotation) - { - if (CurrentSeat & 1 || !(vehicle->next_free_seat & 1)) - { - UpdateRideFreeVehicleEnterRide(*ride); - return; - } - } - else - { - uint8_t seat = CurrentSeat | 1; - if (seat < vehicle->next_free_seat) - { - UpdateRideFreeVehicleEnterRide(*ride); - return; - } - } - - Vehicle* currentTrain = gameState.entities.GetEntity(ride->vehicles[CurrentTrain]); - if (currentTrain == nullptr) - { - return; - } - if (ride->status == RideStatus::open && ++RejoinQueueTimeout != 0 && !currentTrain->flags.has(VehicleFlag::readyToDepart)) - { - return; - } - - if (ride->mode != RideMode::forwardRotation && ride->mode != RideMode::backwardRotation) - { - if (vehicle->next_free_seat - 1 != CurrentSeat) - return; - } - - vehicle->next_free_seat--; - vehicle->peep[CurrentSeat] = EntityId::GetNull(); - - PeepUpdateRideNoFreeVehicleRejoinQueue(*this, *ride); -} - -void Guest::UpdateRideApproachVehicle() -{ - if (auto loc = UpdateAction(); loc.has_value()) - { - MoveTo({ loc.value(), z }); - return; - } - RideSubState = PeepRideSubState::enterVehicle; -} - -void Guest::UpdateRideEnterVehicle() -{ - auto& gameState = getGameState(); - auto* ride = GetRide(CurrentRide); - if (ride != nullptr) - { - auto* vehicle = gameState.entities.GetEntity(ride->vehicles[CurrentTrain]); - if (vehicle != nullptr) - { - vehicle = vehicle->GetCar(CurrentCar); - if (vehicle == nullptr) - { - return; - } - - if (ride->mode != RideMode::forwardRotation && ride->mode != RideMode::backwardRotation) - { - if (CurrentSeat != vehicle->num_peeps) - return; - } - - if (vehicle->IsUsedInPairs()) - { - auto* seatedGuest = gameState.entities.GetEntity(vehicle->peep[CurrentSeat ^ 1]); - if (seatedGuest != nullptr) - { - if (seatedGuest->RideSubState != PeepRideSubState::enterVehicle) - return; - - vehicle->num_peeps++; - ride->curNumCustomers++; - - vehicle->ApplyMass(seatedGuest->Mass); - seatedGuest->MoveTo({ kLocationNull, 0, 0 }); - seatedGuest->SetState(PeepState::onRide); - seatedGuest->GuestTimeOnRide = 0; - seatedGuest->RideSubState = PeepRideSubState::onRide; - seatedGuest->OnEnterRide(*ride); - } - } - - vehicle->num_peeps++; - ride->curNumCustomers++; - - vehicle->ApplyMass(Mass); - vehicle->Invalidate(); - - MoveTo({ kLocationNull, 0, 0 }); - - SetState(PeepState::onRide); - - GuestTimeOnRide = 0; - RideSubState = PeepRideSubState::onRide; - OnEnterRide(*ride); - } - } -} - -/** - * - * rct2: 0x00693028 - */ -void Guest::UpdateRideLeaveVehicle() -{ - auto& gameState = getGameState(); - auto ride = GetRide(CurrentRide); - if (ride == nullptr) - return; - - Vehicle* vehicle = gameState.entities.GetEntity(ride->vehicles[CurrentTrain]); - if (vehicle == nullptr) - return; - - StationIndex ride_station = vehicle->current_station; - vehicle = vehicle->GetCar(CurrentCar); - if (vehicle == nullptr) - { - return; - } - - // Check if ride is NOT Ferris Wheel. - if (ride->mode != RideMode::forwardRotation && ride->mode != RideMode::backwardRotation) - { - if (vehicle->num_peeps - 1 != CurrentSeat) - return; - } - - AnimationImageIdOffset++; - if (AnimationImageIdOffset & 3) - return; - - AnimationImageIdOffset = 0; - - vehicle->num_peeps--; - vehicle->ApplyMass(-Mass); - vehicle->Invalidate(); - - if (ride_station.ToUnderlying() >= Limits::kMaxStationsPerRide) - { - // HACK #5658: Some parks have hacked rides which end up in this state - auto bestStationIndex = RideGetFirstValidStationExit(*ride); - if (bestStationIndex.IsNull()) - { - bestStationIndex = StationIndex::FromUnderlying(0); - } - ride_station = bestStationIndex; - } - CurrentRideStation = ride_station; - const auto* rideEntry = vehicle->GetRideEntry(); - if (rideEntry == nullptr) - { - return; - } - - const auto* carEntry = &rideEntry->Cars[vehicle->vehicle_type]; - - assert(CurrentRideStation.ToUnderlying() < Limits::kMaxStationsPerRide); - auto& station = ride->getStation(CurrentRideStation); - - if (!carEntry->flags.has(CarEntryFlag::loadingWaypoints)) - { - TileCoordsXYZD exitLocation = station.Exit; - CoordsXYZD platformLocation; - platformLocation.z = station.GetBaseZ(); - - platformLocation.direction = DirectionReverse(exitLocation.direction); - - if (!ride->getRideTypeDescriptor().flags.has(RtdFlag::vehicleIsIntegral)) - { - for (; vehicle != nullptr && !vehicle->IsHead(); - vehicle = gameState.entities.GetEntity(vehicle->prev_vehicle_on_ride)) - { - auto trackType = vehicle->GetTrackType(); - if (trackType == TrackElemType::flat || trackType > TrackElemType::middleStation) - continue; - - bool foundStation = false; - for (auto* trackElement : TileElementsView(vehicle->TrackLocation)) - { - if (trackElement->GetBaseZ() != vehicle->TrackLocation.z) - continue; - - if (trackElement->GetStationIndex() != CurrentRideStation) - continue; - - foundStation = true; - break; - } - - if (foundStation) - break; - } - - if (vehicle == nullptr) - { - return; - } - uint8_t shiftMultiplier = 12; - uint8_t specialDirection = platformLocation.direction; - - rideEntry = GetRideEntryByIndex(ride->subtype); - - if (rideEntry != nullptr) - { - carEntry = &rideEntry->Cars[rideEntry->DefaultCar]; - - if (carEntry->flags.has(CarEntryFlag::isGoKart)) - { - shiftMultiplier = 9; - } - - if (carEntry->flags.hasAny(CarEntryFlag::isChairlift, CarEntryFlag::isGoKart)) - { - specialDirection = ((vehicle->Orientation + 3) / 8) + 1; - specialDirection &= 3; - - if (vehicle->TrackSubposition == VehicleTrackSubposition::GoKartsRightLane) - specialDirection = DirectionReverse(specialDirection); - } - } - - auto [xShift, yShift] = [specialDirection]() { - if (specialDirection < DirectionOffsets.size()) - { - return std::pair(DirectionOffsets[specialDirection].x, DirectionOffsets[specialDirection].y); - } - else - { - return std::pair(0, 0); - } - }(); - - platformLocation.x = vehicle->x + xShift * shiftMultiplier; - platformLocation.y = vehicle->y + yShift * shiftMultiplier; - - PeepGoToRideExit( - *this, *ride, platformLocation.x, platformLocation.y, platformLocation.z, platformLocation.direction); - return; - } - - platformLocation.x = vehicle->x + DirectionOffsets[platformLocation.direction].x * 12; - platformLocation.y = vehicle->y + DirectionOffsets[platformLocation.direction].y * 12; - - // This can evaluate to false with buggy custom rides. - if (CurrentSeat < carEntry->peep_loading_positions.size()) - { - int8_t loadPosition = carEntry->peep_loading_positions[CurrentSeat]; - - switch (vehicle->Orientation / 8) - { - case 0: - platformLocation.x -= loadPosition; - break; - case 1: - platformLocation.y += loadPosition; - break; - case 2: - platformLocation.x += loadPosition; - break; - case 3: - platformLocation.y -= loadPosition; - break; - } - } - else - { - LOG_VERBOSE( - "CurrentSeat %d is too large! (Vehicle entry has room for %d.)", CurrentSeat, - carEntry->peep_loading_positions.size()); - } - - platformLocation.z = station.GetBaseZ(); - - PeepGoToRideExit(*this, *ride, platformLocation.x, platformLocation.y, platformLocation.z, platformLocation.direction); - return; - } - - auto exitLocation = station.Exit.ToCoordsXYZD(); - if (exitLocation.IsNull()) - { - return; - } - - TileElement* trackElement = RideGetStationStartTrackElement(*ride, CurrentRideStation); - - Direction station_direction = (trackElement == nullptr ? 0 : trackElement->GetDirection()); - - vehicle = gameState.entities.GetEntity(ride->vehicles[CurrentTrain]); - if (vehicle == nullptr) - { - return; - } - - const auto& rtd = ride->getRideTypeDescriptor(); - CoordsXYZ waypointLoc = { rtd.GetGuestWaypointLocation(*vehicle, *ride, CurrentRideStation), - exitLocation.z + ride->getRideTypeDescriptor().Heights.PlatformHeight }; - - rideEntry = vehicle->GetRideEntry(); - carEntry = &rideEntry->Cars[vehicle->vehicle_type]; - if (carEntry == nullptr) - return; - - Var37 = ((exitLocation.direction | GetWaypointedSeatLocation(*ride, carEntry, station_direction) * 4) * 4) | 1; - - CoordsXYZ exitWaypointLoc = waypointLoc; - - const auto waypointIndex = Var37 / 4u; - if (waypointIndex < carEntry->peep_loading_waypoints.size()) - { - exitWaypointLoc.x += carEntry->peep_loading_waypoints[waypointIndex][2].x; - exitWaypointLoc.y += carEntry->peep_loading_waypoints[waypointIndex][2].y; - } - - if (ride->getRideTypeDescriptor().specialType == RtdSpecialType::motionSimulator) - exitWaypointLoc.z += 15; - - MoveTo(exitWaypointLoc); - - if (waypointIndex < carEntry->peep_loading_waypoints.size()) - { - waypointLoc.x += carEntry->peep_loading_waypoints[waypointIndex][1].x; - waypointLoc.y += carEntry->peep_loading_waypoints[waypointIndex][1].y; - } - - SetDestination(waypointLoc, 2); - RideSubState = PeepRideSubState::approachExitWaypoints; -} - -/** - * - * rct2: 0x0069376A - */ -void Guest::UpdateRidePrepareForExit() -{ - const auto* ride = GetRide(CurrentRide); - if (ride == nullptr || CurrentRideStation.ToUnderlying() >= std::size(ride->getStations())) - return; - - auto exit = ride->getStation(CurrentRideStation).Exit; - auto newDestination = exit.ToCoordsXY().ToTileCentre(); - - auto [xShift, yShift] = [exit]() { - if (exit.direction < DirectionOffsets.size()) - { - return std::pair(DirectionOffsets[exit.direction].x, DirectionOffsets[exit.direction].y); - } - else - { - return std::pair(0, 0); - } - }(); - - int16_t shiftMultiplier = 20; - - const auto* rideEntry = ride->getRideEntry(); - if (rideEntry != nullptr) - { - const auto& carEntry = rideEntry->Cars[rideEntry->DefaultCar]; - if (carEntry.flags.hasAny(CarEntryFlag::isChairlift, CarEntryFlag::isGoKart)) - { - shiftMultiplier = 32; - } - } - - xShift *= shiftMultiplier; - yShift *= shiftMultiplier; - - newDestination.x -= xShift; - newDestination.y -= yShift; - - SetDestination(newDestination, 2); - RideSubState = PeepRideSubState::inExit; -} - -/** - * - * rct2: 0x0069374F - */ -void Guest::UpdateRideApproachExit() -{ - if (auto loc = UpdateAction(); loc.has_value()) - { - MoveTo({ loc.value(), z }); - return; - } - - UpdateRidePrepareForExit(); -} - -/** - * - * rct2: 0x0069382E - */ -void Guest::UpdateRideInExit() -{ - auto ride = GetRide(CurrentRide); - if (ride == nullptr) - return; - - int16_t xy_distance; - - if (auto loc = UpdateAction(xy_distance); loc.has_value()) - { - if (xy_distance >= 16) - { - int16_t actionZ = ride->getStation(CurrentRideStation).GetBaseZ(); - - actionZ += ride->getRideTypeDescriptor().Heights.PlatformHeight; - MoveTo({ loc.value(), actionZ }); - return; - } - - SwitchToSpecialSprite(0); - MoveTo({ loc.value(), z }); - } - - if (ride->flags.has(RideFlag::onRidePhoto)) - { - ShopItem secondaryItem = ride->getRideTypeDescriptor().PhotoItem; - if (GuestDecideAndBuyItem(*this, *ride, secondaryItem, ride->price[1])) - { - ride->numSecondaryItemsSold = AddClamp(ride->numSecondaryItemsSold, 1u); - } - } - RideSubState = PeepRideSubState::leaveExit; -} -#pragma warning(default : 6011) - -CoordsXY GetGuestWaypointLocationDefault(const Vehicle& vehicle, const Ride& ride, const StationIndex& CurrentRideStation) -{ - return ride.getStation(CurrentRideStation).Start.ToTileCentre(); -} - -CoordsXY GetGuestWaypointLocationEnterprise(const Vehicle& vehicle, const Ride& ride, const StationIndex& CurrentRideStation) -{ - return { vehicle.x, vehicle.y }; -} - -/** - * - * rct2: 0x006926AD - */ -void Guest::UpdateRideApproachVehicleWaypoints() -{ - auto ride = GetRide(CurrentRide); - if (ride == nullptr) - return; - - int16_t xy_distance; - uint8_t waypoint = Var37 & 3; - - const auto& rtd = ride->getRideTypeDescriptor(); - if (auto loc = UpdateAction(xy_distance); loc.has_value()) - { - rtd.UpdateRideApproachVehicleWaypoints(*this, loc.value(), xy_distance); - return; - } - - if (waypoint == 2) - { - RideSubState = PeepRideSubState::enterVehicle; - return; - } - - waypoint++; - // This is incrementing the actual peep waypoint - Var37++; - - Vehicle* vehicle = getGameState().entities.GetEntity(ride->vehicles[CurrentTrain]); - if (vehicle == nullptr) - { - return; - } - - CoordsXY targetLoc = rtd.GetGuestWaypointLocation(*vehicle, *ride, CurrentRideStation); - - const auto* rideEntry = vehicle->GetRideEntry(); - if (rideEntry == nullptr) - { - return; - } - - const auto& vehicle_type = rideEntry->Cars[vehicle->vehicle_type]; - const auto waypointIndex = Var37 / 4u; - if (waypointIndex < vehicle_type.peep_loading_waypoints.size()) - { - Guard::Assert(waypoint < 3); - targetLoc.x += vehicle_type.peep_loading_waypoints[waypointIndex][waypoint].x; - targetLoc.y += vehicle_type.peep_loading_waypoints[waypointIndex][waypoint].y; - } - - SetDestination(targetLoc); -} - -void UpdateRideApproachVehicleWaypointsMotionSimulator(Guest& guest, const CoordsXY& loc, int16_t& xy_distance) -{ - auto ride = GetRide(guest.CurrentRide); - // Motion simulators have steps. This moves the peeps up the steps. - int16_t actionZ = ride->getStation(guest.CurrentRideStation).GetBaseZ() + 2; - - uint8_t waypoint = guest.Var37 & 3; - if (waypoint == 2) - { - xy_distance -= 12; - if (xy_distance < 0) - xy_distance = 0; - - if (xy_distance <= 15) - { - actionZ += 15 - xy_distance; - } - } - guest.MoveTo({ loc, actionZ }); -} - -void UpdateRideApproachVehicleWaypointsDefault(Guest& guest, const CoordsXY& loc, int16_t& xy_distance) -{ - guest.MoveTo({ loc, guest.z }); -} - -/** - * - * rct2: 0x0069357D - */ -void Guest::UpdateRideApproachExitWaypoints() -{ - auto ride = GetRide(CurrentRide); - if (ride == nullptr) - return; - - int16_t xy_distance; - - if (auto loc = UpdateAction(xy_distance); loc.has_value()) - { - int16_t actionZ; - - if (ride->getRideTypeDescriptor().specialType == RtdSpecialType::motionSimulator) - { - actionZ = ride->getStation(CurrentRideStation).GetBaseZ() + 2; - - if ((Var37 & 3) == 1) - { - if (xy_distance > 15) - xy_distance = 15; - - actionZ += xy_distance; - } - } - else - { - actionZ = z; - } - MoveTo({ loc.value(), actionZ }); - return; - } - - if ((Var37 & 3) != 0) - { - if ((Var37 & 3) == 3) - { - UpdateRidePrepareForExit(); - return; - } - - Var37--; - Vehicle* vehicle = getGameState().entities.GetEntity(ride->vehicles[CurrentTrain]); if (vehicle == nullptr) { return; } + uint8_t chosen_seat = vehicle->next_free_seat; - const auto* rideEntry = vehicle->GetRideEntry(); - if (rideEntry == nullptr) - return; - - if (vehicle->vehicle_type >= std::size(rideEntry->Cars)) - return; - - const CarEntry& carEntry = rideEntry->Cars[vehicle->vehicle_type]; - - const size_t carPosition = Var37 / 4; - if (carPosition >= carEntry.peep_loading_waypoints.size()) - return; - - const auto waypoint = Var37 & 3; - Guard::Assert(waypoint < 3); - - const auto& rtd = ride->getRideTypeDescriptor(); - - CoordsXY targetLoc = rtd.GetGuestWaypointLocation(*vehicle, *ride, CurrentRideStation); - targetLoc += carEntry.peep_loading_waypoints[carPosition][waypoint]; - SetDestination(targetLoc); - return; - } - - Var37 |= 3; - - auto targetLoc = ride->getStation(CurrentRideStation).Exit.ToCoordsXYZD().ToTileCentre(); - uint8_t exit_direction = DirectionReverse(targetLoc.direction); - - int16_t x_shift = DirectionOffsets[exit_direction].x; - int16_t y_shift = DirectionOffsets[exit_direction].y; - - int16_t shift_multiplier = 20; - - auto rideEntry = GetRideEntryByIndex(ride->subtype); - if (rideEntry != nullptr) - { - auto carEntry = &rideEntry->Cars[rideEntry->DefaultCar]; - if (carEntry->flags.hasAny(CarEntryFlag::isChairlift, CarEntryFlag::isGoKart)) + if (ride.mode == RideMode::forwardRotation || ride.mode == RideMode::backwardRotation) { - shift_multiplier = 32; - } - } - - x_shift *= shift_multiplier; - y_shift *= shift_multiplier; - - targetLoc.x -= x_shift; - targetLoc.y -= y_shift; - - SetDestination(targetLoc); -} - -/** - * - * rct2: 0x006927B3 - */ -void Guest::UpdateRideApproachSpiralSlide() -{ - auto ride = GetRide(CurrentRide); - if (ride == nullptr) - return; - - if (auto loc = UpdateAction(); loc.has_value()) - { - MoveTo({ loc.value(), z }); - return; - } - - uint8_t waypoint = Var37 & 3; - - if (waypoint == 3) - { - SubState = 15; - spiralSlideSubstate = PeepSpiralSlideSubState::goingUp; - spiralSlideGoingUpTimer = 0; - Var37 = (Var37 / 4) & 0xC; - MoveTo({ kLocationNull, y, z }); - return; - } - - [[maybe_unused]] const auto& rtd = ride->getRideTypeDescriptor(); - if (waypoint == 2) - { - bool lastRide = false; - if (ride->status != RideStatus::open) - lastRide = true; - else if (timesSlidDown++ != 0) - { - if (ride->mode == RideMode::singleRidePerAdmission) - lastRide = true; - if (static_cast(timesSlidDown - 1) > (ScenarioRand() & 0xF)) - lastRide = true; - } - - if (lastRide) - { - auto exit = ride->getStation(CurrentRideStation).Exit; - waypoint = 1; - auto directionTemp = exit.direction; - if (exit.direction == kInvalidDirection) + chosen_seat = (((~vehicle->flatRideAnimationFrame + 1) >> 3) & 0xF) * 2; + if (vehicle->next_free_seat & 1) { - directionTemp = 0; - } - Var37 = (directionTemp * 4) | (Var37 & 0x30) | waypoint; - CoordsXY targetLoc = ride->getStation(CurrentRideStation).Start; - - assert(rtd.specialType == RtdSpecialType::spiralSlide); - targetLoc += kSpiralSlideWalkingPath[Var37]; - - SetDestination(targetLoc); - RideSubState = PeepRideSubState::leaveSpiralSlide; - return; - } - } - waypoint++; - // Actually increment the real peep waypoint - Var37++; - - CoordsXY targetLoc = ride->getStation(CurrentRideStation).Start; - - assert(rtd.specialType == RtdSpecialType::spiralSlide); - targetLoc += kSpiralSlideWalkingPath[Var37]; - - SetDestination(targetLoc); -} - -/** rct2: 0x00981F0C, 0x00981F0E */ -static constexpr CoordsXY kSpiralSlideEnd[] = { - { 25, 56 }, - { 56, 7 }, - { 7, -24 }, - { -24, 25 }, -}; - -/** rct2: 0x00981F1C, 0x00981F1E */ -static constexpr CoordsXY kSpiralSlideEndWaypoint[] = { - { 8, 56 }, - { 56, 24 }, - { 24, -24 }, - { -24, 8 }, -}; - -/** - * - * rct2: 0x00692D83 - */ -void Guest::UpdateRideOnSpiralSlide() -{ - auto ride = GetRide(CurrentRide); - - if (ride == nullptr) - return; - - const auto& rtd = ride->getRideTypeDescriptor(); - if (rtd.specialType != RtdSpecialType::spiralSlide) - return; - - if ((Var37 & 3) == 0) - { - switch (spiralSlideSubstate) - { - case PeepSpiralSlideSubState::goingUp: - spiralSlideGoingUpTimer++; - if (spiralSlideGoingUpTimer >= kTicksToGoUpSpiralSlide) - spiralSlideSubstate = PeepSpiralSlideSubState::prepareToSlide; - - return; - case PeepSpiralSlideSubState::prepareToSlide: - if (ride->slideInUse || ride->flags.has(RideFlag::brokenDown)) - return; - - ride->slideInUse = 1; - ride->slidePeep = Id; - ride->slidePeepTShirtColour = TshirtColour; - ride->spiralSlideProgress = 0; - spiralSlideSubstate = PeepSpiralSlideSubState::slidingDown; - - return; - case PeepSpiralSlideSubState::finishedSliding: - { - auto newLocation = ride->getStation(CurrentRideStation).Start; - uint8_t dir = (Var37 / 4) & 3; - - // Set the location that the guest walks to go on slide again - auto destination = newLocation + kSpiralSlideEndWaypoint[dir]; - SetDestination(destination); - - // Move the guest sprite to just at the end of the slide - newLocation.x += kSpiralSlideEnd[dir].x; - newLocation.y += kSpiralSlideEnd[dir].y; - - MoveTo({ newLocation, z }); - - Orientation = (Var37 & 0xC) * 2; - - Var37++; - return; - } - case PeepSpiralSlideSubState::slidingDown: // Handled by updateSpiralSlide in Ride.cpp - default: - return; - } - } - - if (auto loc = UpdateAction(); loc.has_value()) - { - MoveTo({ loc.value(), z }); - return; - } - - uint8_t waypoint = 2; - Var37 = (Var37 * 4 & 0x30) + waypoint; - - CoordsXY targetLoc = ride->getStation(CurrentRideStation).Start; - - targetLoc += kSpiralSlideWalkingPath[Var37]; - - SetDestination(targetLoc); - RideSubState = PeepRideSubState::approachSpiralSlide; -} - -/** - * - * rct2: 0x00692C6B - */ -void Guest::UpdateRideLeaveSpiralSlide() -{ - // Iterates through the spiral slide waypoints until it reaches - // waypoint 0. Then it readies to leave the ride by the entrance. - if (auto loc = UpdateAction(); loc.has_value()) - { - MoveTo({ loc.value(), z }); - return; - } - - auto ride = GetRide(CurrentRide); - if (ride == nullptr) - return; - - uint8_t waypoint = Var37 & 3; - - if (waypoint != 0) - { - if (waypoint == 3) - { - UpdateRidePrepareForExit(); - return; - } - - waypoint--; - // Actually decrement the peep waypoint - Var37--; - CoordsXY targetLoc = ride->getStation(CurrentRideStation).Start; - - [[maybe_unused]] const auto& rtd = ride->getRideTypeDescriptor(); - assert(rtd.specialType == RtdSpecialType::spiralSlide); - targetLoc += kSpiralSlideWalkingPath[Var37]; - - SetDestination(targetLoc); - return; - } - - // Actually force the final waypoint - Var37 |= 3; - - auto targetLoc = ride->getStation(CurrentRideStation).Exit.ToCoordsXYZD().ToTileCentre(); - - int16_t xShift = DirectionOffsets[DirectionReverse(targetLoc.direction)].x; - int16_t yShift = DirectionOffsets[DirectionReverse(targetLoc.direction)].y; - - int16_t shiftMultiplier = 20; - - xShift *= shiftMultiplier; - yShift *= shiftMultiplier; - - targetLoc.x -= xShift; - targetLoc.y -= yShift; - - SetDestination(targetLoc); -} - -/** rct2: 0x00981FE4 */ -static constexpr uint8_t kMazeGetNewDirectionFromEdge[][4] = { - { 15, 7, 15, 7 }, - { 11, 3, 11, 3 }, - { 7, 15, 7, 15 }, - { 3, 11, 3, 11 }, -}; - -/** rct2: 0x00981FF4 */ -static constexpr uint8_t kMazeCurrentDirectionToOpenHedge[][4] = { - { 1, 2, 14, 0 }, - { 4, 5, 6, 2 }, - { 6, 8, 9, 10 }, - { 14, 10, 12, 13 }, -}; - -/** - * - * rct2: 0x00692A83 - */ -void Guest::UpdateRideMazePathfinding() -{ - if (auto loc = UpdateAction(); loc.has_value()) - { - MoveTo({ loc.value(), z }); - return; - } - - auto ride = GetRide(CurrentRide); - if (ride == nullptr) - return; - - if (Var37 == 16) - { - UpdateRidePrepareForExit(); - return; - } - - if (IsActionInterruptable()) - { - if (Energy > 80 && !(PeepFlags & PEEP_FLAGS_SLOW_WALK) && !Weather::isPrecipitating() - && (ScenarioRand() & 0xFFFF) <= 2427) - { - Action = PeepActionType::jump; - AnimationFrameNum = 0; - AnimationImageIdOffset = 0; - UpdateCurrentAnimationType(); - } - } - - auto targetLoc = GetDestination().ToTileStart(); - - auto stationBaseZ = ride->getStation().GetBaseZ(); - - // Find the station track element - auto trackElement = MapGetTrackElementAt({ targetLoc, stationBaseZ }); - if (trackElement == nullptr) - { - return; - } - - uint16_t mazeEntry = trackElement->GetMazeEntry(); - // Var37 is 3, 7, 11 or 15 - uint8_t hedges[4]{ 0xFF, 0xFF, 0xFF, 0xFF }; - uint8_t openCount = 0; - uint8_t mazeReverseLastEdge = DirectionReverse(MazeLastEdge); - for (uint8_t i = 0; i < kNumOrthogonalDirections; ++i) - { - if (!(mazeEntry & (1 << kMazeCurrentDirectionToOpenHedge[Var37 / 4][i])) && i != mazeReverseLastEdge) - { - hedges[openCount++] = i; - } - } - - if (openCount == 0) - { - if ((mazeEntry & (1 << kMazeCurrentDirectionToOpenHedge[Var37 / 4][mazeReverseLastEdge]))) - { - return; - } - hedges[openCount++] = mazeReverseLastEdge; - } - - uint8_t chosenEdge = hedges[ScenarioRand() % openCount]; - assert(chosenEdge != 0xFF); - - targetLoc = GetDestination() + CoordsDirectionDelta[chosenEdge] / 2; - - enum class maze_type - { - invalid, - hedge, - entrance_or_exit - }; - maze_type mazeType = maze_type::invalid; - - auto tileElement = MapGetFirstElementAt(targetLoc); - if (tileElement == nullptr) - return; - do - { - if (stationBaseZ != tileElement->GetBaseZ()) - continue; - - if (tileElement->GetType() == TileElementType::Track) - { - mazeType = maze_type::hedge; - break; - } - - if (tileElement->GetType() == TileElementType::Entrance - && tileElement->AsEntrance()->GetEntranceType() == ENTRANCE_TYPE_RIDE_EXIT) - { - mazeType = maze_type::entrance_or_exit; - break; - } - } while (!(tileElement++)->IsLastForTile()); - - switch (mazeType) - { - case maze_type::invalid: - MazeLastEdge++; - MazeLastEdge &= 3; - return; - case maze_type::hedge: - SetDestination(targetLoc); - Var37 = kMazeGetNewDirectionFromEdge[Var37 / 4][chosenEdge]; - MazeLastEdge = chosenEdge; - break; - case maze_type::entrance_or_exit: - targetLoc = GetDestination(); - if (chosenEdge & 1) - { - targetLoc.x = targetLoc.ToTileCentre().x; - } - else - { - targetLoc.y = targetLoc.ToTileCentre().y; - } - SetDestination(targetLoc); - Var37 = 16; - MazeLastEdge = chosenEdge; - break; - } - - if (auto loc = UpdateAction(); loc.has_value()) - { - MoveTo({ loc.value(), z }); - } -} - -/** - * - * rct2: 0x006938D2 - */ -void Guest::UpdateRideLeaveExit() -{ - auto ride = GetRide(CurrentRide); - - if (auto loc = UpdateAction(); loc.has_value()) - { - if (ride != nullptr) - { - MoveTo({ loc.value(), ride->getStation(CurrentRideStation).GetBaseZ() }); - } - return; - } - - if (ride != nullptr) - { - OnExitRide(*ride); - - if (PeepFlags & PEEP_FLAGS_TRACKING) - { - auto ft = Formatter(); - FormatNameTo(ft); - ride->formatNameTo(ft); - - if (Config::Get().notifications.guestLeftRide) - { - News::AddItemToQueue(News::ItemType::peepOnRide, STR_PEEP_TRACKING_LEFT_RIDE_X, Id, ft); + chosen_seat++; } } + guest->CurrentSeat = chosen_seat; + vehicle->next_free_seat++; + + vehicle->peep[guest->CurrentSeat] = guest->Id; + vehicle->peep_tshirt_colours[guest->CurrentSeat] = guest->TshirtColour; } - InteractionRideIndex = RideId::GetNull(); - SetState(PeepState::falling); - - CoordsXY targetLoc = { x, y }; - - // Find the station track element - for (auto* pathElement : TileElementsView(targetLoc)) + /** + * + * rct2: 0x00691D27 + */ + void Guest::GoToRideEntrance(const Ride& ride) { - int16_t height = MapHeightFromSlope(targetLoc, pathElement->GetSlopeDirection(), pathElement->IsSloped()); - height += pathElement->GetBaseZ(); - - int16_t z_diff = z - height; - if (z_diff > 0 || z_diff < -16) - continue; - - MoveTo({ x, y, height }); - return; - } -} - -/** - * - * rct2: 0x0069299C - */ -void Guest::UpdateRideShopApproach() -{ - if (auto loc = UpdateAction(); loc.has_value()) - { - MoveTo({ loc.value(), z }); - return; - } - - RideSubState = PeepRideSubState::interactShop; -} - -/** - * - * rct2: 0x006929BB - */ -void Guest::UpdateRideShopInteract() -{ - auto ride = GetRide(CurrentRide); - if (ride == nullptr) - return; - - const int16_t tileCentreX = NextLoc.x + 16; - const int16_t tileCentreY = NextLoc.y + 16; - - const auto& rtd = ride->getRideTypeDescriptor(); - if (rtd.specialType == RtdSpecialType::firstAid) - { - if (Nausea <= 35) + const auto& station = ride.getStation(CurrentRideStation); + if (station.Entrance.IsNull()) { - RideSubState = PeepRideSubState::leaveShop; + RemoveFromQueue(); + return; + } - SetDestination({ tileCentreX, tileCentreY }, 3); - HappinessTarget = std::min(HappinessTarget + 30, kPeepMaxHappiness); - Happiness = HappinessTarget; + auto location = station.Entrance.ToCoordsXYZD().ToTileCentre(); + int16_t x_shift = DirectionOffsets[location.direction].x; + int16_t y_shift = DirectionOffsets[location.direction].y; + + uint8_t shift_multiplier = 21; + const auto* rideEntry = GetRideEntryByIndex(ride.subtype); + if (rideEntry != nullptr) + { + if (rideEntry->Cars[rideEntry->DefaultCar].flags.hasAny( + CarEntryFlag::isMiniGolf, CarEntryFlag::isChairlift, CarEntryFlag::isGoKart)) + { + shift_multiplier = 32; + } + } + + x_shift *= shift_multiplier; + y_shift *= shift_multiplier; + + location.x += x_shift; + location.y += y_shift; + + SetDestination(location, 2); + SetState(PeepState::enteringRide); + RideSubState = PeepRideSubState::inEntrance; + + RejoinQueueTimeout = 0; + GuestTimeOnRide = 0; + + RemoveFromQueue(); + } + + static bool FindVehicleToEnter( + Guest& guest, const Ride& ride, sfl::static_vector& car_array) + { + uint8_t chosen_train = RideStation::kNoTrain; + + if (ride.mode == RideMode::dodgems || ride.mode == RideMode::race) + { + if (ride.flags.has(RideFlag::passStationNoStopping)) + return false; + + for (int32_t i = 0; i < ride.numTrains; ++i) + { + Vehicle* vehicle = getGameState().entities.GetEntity(ride.vehicles[i]); + if (vehicle == nullptr) + continue; + + if (vehicle->next_free_seat >= vehicle->num_seats) + continue; + + if (vehicle->status != Vehicle::Status::waitingForPassengers) + continue; + chosen_train = i; + break; + } } else { - Nausea--; - NauseaTarget = Nausea; + chosen_train = ride.getStation(guest.CurrentRideStation).TrainAtStation; } - return; - } - - if (Toilet != 0) - { - Toilet--; - return; - } - - // Do not play toilet flush sound on title screen as it's considered loud and annoying - if (gLegacyScene != LegacyScene::titleSequence) - { - Audio::Play3D(Audio::SoundId::toiletFlush, GetLocation()); - } - - RideSubState = PeepRideSubState::leaveShop; - - SetDestination({ tileCentreX, tileCentreY }, 3); - - HappinessTarget = std::min(HappinessTarget + 30, kPeepMaxHappiness); - Happiness = HappinessTarget; - GuestStopPurchaseThought(*this, ride->type); -} - -/** - * - * rct2: 0x00692935 - */ -void Guest::UpdateRideShopLeave() -{ - if (auto loc = UpdateAction(); loc.has_value()) - { - const auto curLoc = GetLocation(); - MoveTo({ loc.value(), curLoc.z }); - - const auto newLoc = GetLocation().ToTileStart(); - if (newLoc.x != NextLoc.x) - return; - if (newLoc.y != NextLoc.y) - return; - } - - // #11758 Previously SetState(PeepState::walking) caused Peeps to double-back to exit point of shop - SetState(PeepState::falling); - - auto ride = GetRide(CurrentRide); - if (ride != nullptr) - { - ride->totalCustomers = AddClamp(ride->totalCustomers, 1u); - ride->windowInvalidateFlags.set(RideInvalidateFlag::customers); - ride->updateSatisfaction(Happiness / 64); - } -} - -/* From peep_update */ -static void GuestUpdateThoughts(Guest& guest) -{ - // Thoughts must always have a gap of at least - // 220 ticks in age between them. In order to - // allow this when a thought is new it enters - // a holding zone. Before it becomes fresh. - int32_t add_fresh = 1; - int32_t fresh_thought = -1; - for (int32_t i = 0; i < kPeepMaxThoughts; i++) - { - if (guest.Thoughts[i].type == PeepThoughtType::None) - break; - - if (guest.Thoughts[i].freshness == 1) + if (chosen_train >= Limits::kMaxTrainsPerRide) { - add_fresh = 0; - // If thought is fresh we wait 220 ticks - // before allowing a new thought to become fresh. - if (++guest.Thoughts[i].fresh_timeout >= 220) + return false; + } + + guest.CurrentTrain = chosen_train; + + int32_t i = 0; + + auto vehicle_id = ride.vehicles[chosen_train]; + for (Vehicle* vehicle = getGameState().entities.GetEntity(vehicle_id); vehicle != nullptr; + vehicle = getGameState().entities.GetEntity(vehicle->next_vehicle_on_train), ++i) + { + uint8_t num_seats = vehicle->num_seats; + if (vehicle->IsUsedInPairs()) { - guest.Thoughts[i].fresh_timeout = 0; - // Thought is no longer fresh - guest.Thoughts[i].freshness++; - add_fresh = 1; + if (vehicle->next_free_seat & 1) + { + car_array.clear(); + car_array.push_back(i); + return true; + } + num_seats &= kVehicleSeatNumMask; + } + if (num_seats == vehicle->next_free_seat) + continue; + + if (ride.mode == RideMode::forwardRotation || ride.mode == RideMode::backwardRotation) + { + uint8_t position = (((~vehicle->flatRideAnimationFrame + 1) >> 3) & 0xF) * 2; + if (!vehicle->peep[position].IsNull()) + continue; + } + car_array.push_back(i); + } + + return !car_array.empty(); + } + + static void PeepUpdateRideAtEntranceTryLeave(Guest& guest) + { + // Destination Tolerance is zero when peep has completely + // entered entrance + if (guest.DestinationTolerance == 0) + { + guest.RemoveFromQueue(); + guest.SetState(PeepState::falling); + } + } + + static bool PeepCheckRidePriceAtEntrance(Guest& guest, const Ride& ride, money64 ridePrice) + { + if ((guest.HasItem(ShopItem::voucher)) && guest.VoucherType == VOUCHER_TYPE_RIDE_FREE + && guest.VoucherRideId == guest.CurrentRide) + return true; + + if (guest.CashInPocket <= 0 && !(getGameState().park.flags & PARK_FLAGS_NO_MONEY)) + { + guest.InsertNewThought(PeepThoughtType::SpentMoney); + PeepUpdateRideAtEntranceTryLeave(guest); + return false; + } + + if (ridePrice > guest.CashInPocket) + { + // Prevent looping of same thought / animation since Destination Tolerance + // is only 0 exactly at entrance and will immediately change as guest + // tries to leave hereafter + if (guest.DestinationTolerance == 0) + { + guest.InsertNewThought(PeepThoughtType::CantAffordRide, guest.CurrentRide); + } + PeepUpdateRideAtEntranceTryLeave(guest); + return false; + } + + auto value = ride.value; + if (value != kRideValueUndefined) + { + if (((value * 2) < ridePrice) && !(getGameState().cheats.ignorePrice)) + { + guest.InsertNewThought(PeepThoughtType::BadValue, guest.CurrentRide); + PeepUpdateRideAtEntranceTryLeave(guest); + return false; } } - else if (guest.Thoughts[i].freshness > 1) - { - if (++guest.Thoughts[i].fresh_timeout == 0) - { - // When thought is older than ~6900 ticks remove it - if (++guest.Thoughts[i].freshness >= 28) - { - guest.WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_THOUGHTS; + return true; + } - // Clear top thought, push others up - if (i < kPeepMaxThoughts - 2) + /** + * The satisfaction values calculated here are used to determine how happy the peep is with the ride, + * and also affects the satisfaction stat of the ride itself. The factors that affect satisfaction include: + * - The price of the ride compared to the ride's value + * - How closely the intensity and nausea of the ride matches the peep's preferences + * - How long the peep was waiting in the queue + * - If the peep has been on the ride before, or on another ride of the same type + */ + static int16_t GuestCalculateRideSatisfaction(Guest& guest, const Ride& ride) + { + int16_t satisfaction = GuestCalculateRideValueSatisfaction(guest, ride); + satisfaction += GuestCalculateRideIntensityNauseaSatisfaction(guest, ride); + + // Calculate satisfaction based on how long the peep has been in the queue for. + // (For comparison: peeps start thinking "I've been queueing for a long time" at 3500 and + // start leaving the queue at 4300.) + if (guest.TimeInQueue >= 4500) + satisfaction -= 35; + else if (guest.TimeInQueue >= 2250) + satisfaction -= 10; + else if (guest.TimeInQueue <= 750) + satisfaction += 10; + + // Peeps get a small boost in satisfaction if they've been on a ride of the same type before, + // and this boost is doubled if they've already been on this particular ride. + if (guest.HasRiddenRideType(ride.type)) + satisfaction += 10; + + if (guest.HasRidden(*GetRide(guest.CurrentRide))) + satisfaction += 10; + + return satisfaction; + } + + /** + * Check to see if the specified ride should become the peep's favourite. + * For this, a "ride rating" is calculated based on the excitement of the ride and the satisfaction of the ride. + * As this value cannot exceed 255, the more satisfied the peep is, the more irrelevant the ride's excitement becomes. + * Due to the minimum happiness requirement, an excitement rating of more than 3.8 has no further effect. + * + * If the ride rating is higher than any ride the peep has already been on and the happiness criteria is met, + * the ride becomes the peep's favourite. (This doesn't happen right away, but will be updated once the peep + * exits the ride.) + */ + static void GuestUpdateFavouriteRide(Guest& guest, const Ride& ride, uint8_t satisfaction) + { + guest.PeepFlags &= ~PEEP_FLAGS_RIDE_SHOULD_BE_MARKED_AS_FAVOURITE; + uint8_t peepRideRating = std::clamp((ride.ratings.excitement / 4) + satisfaction, 0, kPeepMaxHappiness); + if (peepRideRating >= guest.FavouriteRideRating) + { + if (guest.Happiness >= 160 && guest.HappinessTarget >= 160) + { + guest.FavouriteRideRating = peepRideRating; + guest.PeepFlags |= PEEP_FLAGS_RIDE_SHOULD_BE_MARKED_AS_FAVOURITE; + } + } + } + + /* rct2: 0x00695555 */ + static int16_t GuestCalculateRideValueSatisfaction(Guest& guest, const Ride& ride) + { + if (getGameState().park.flags & PARK_FLAGS_NO_MONEY) + { + return -30; + } + + if (ride.value == kRideValueUndefined) + { + return -30; + } + + auto ridePrice = RideGetPrice(ride); + if (ride.value >= ridePrice) + { + return -5; + } + + if ((ride.value + ((ride.value * guest.Happiness) / 256)) >= ridePrice) + { + return -30; + } + + return 0; + } + + /** + * Calculate satisfaction based on the intensity and nausea of the ride. + * The best possible score from this section is achieved by having the intensity and nausea + * of the ride fall exactly within the peep's preferences, but lower scores can still be achieved + * if the peep's happiness is enough to offset it. + */ + static int16_t GuestCalculateRideIntensityNauseaSatisfaction(Guest& guest, const Ride& ride) + { + if (!RideHasRatings(ride)) + { + return 70; + } + + uint8_t intensitySatisfaction = 3; + uint8_t nauseaSatisfaction = 3; + RideRating_t maxIntensity = guest.Intensity.GetMaximum() * 100; + RideRating_t minIntensity = guest.Intensity.GetMinimum() * 100; + if (minIntensity <= ride.ratings.intensity && maxIntensity >= ride.ratings.intensity) + { + intensitySatisfaction--; + } + minIntensity -= guest.Happiness * 2; + maxIntensity += guest.Happiness; + if (minIntensity <= ride.ratings.intensity && maxIntensity >= ride.ratings.intensity) + { + intensitySatisfaction--; + } + minIntensity -= guest.Happiness * 2; + maxIntensity += guest.Happiness; + if (minIntensity <= ride.ratings.intensity && maxIntensity >= ride.ratings.intensity) + { + intensitySatisfaction--; + } + + // Although it's not shown in the interface, a peep with Average or High nausea tolerance + // has a minimum preferred nausea value. (For peeps with None or Low, this is set to zero.) + RideRating_t minNausea = kNauseaMinimumThresholds[(EnumValue(guest.NauseaTolerance) & 3)]; + RideRating_t maxNausea = NauseaMaximumThresholds[(EnumValue(guest.NauseaTolerance) & 3)]; + if (minNausea <= ride.ratings.nausea && maxNausea >= ride.ratings.nausea) + { + nauseaSatisfaction--; + } + minNausea -= guest.Happiness * 2; + maxNausea += guest.Happiness; + if (minNausea <= ride.ratings.nausea && maxNausea >= ride.ratings.nausea) + { + nauseaSatisfaction--; + } + minNausea -= guest.Happiness * 2; + maxNausea += guest.Happiness; + if (minNausea <= ride.ratings.nausea && maxNausea >= ride.ratings.nausea) + { + nauseaSatisfaction--; + } + + uint8_t highestSatisfaction = std::max(intensitySatisfaction, nauseaSatisfaction); + uint8_t lowestSatisfaction = std::min(intensitySatisfaction, nauseaSatisfaction); + + switch (highestSatisfaction) + { + default: + case 0: + return 70; + case 1: + switch (lowestSatisfaction) + { + default: + case 0: + return 50; + case 1: + return 35; + } + case 2: + switch (lowestSatisfaction) + { + default: + case 0: + return 35; + case 1: + return 20; + case 2: + return 10; + } + case 3: + switch (lowestSatisfaction) + { + default: + case 0: + return -35; + case 1: + return -50; + case 2: + return -60; + case 3: + return -60; + } + } + } + + /** + * Update the nausea growth of the peep based on a ride. This is calculated based on: + * - The nausea rating of the ride + * - Their new happiness growth rate (the higher, the less nauseous) + * - How hungry the peep is (+0% nausea at 50% hunger up to +100% nausea at 100% hunger) + * - The peep's nausea tolerance (Final modifier: none: 100%, low: 50%, average: 25%, high: 12.5%) + */ + static void GuestUpdateRideNauseaGrowth(Guest& guest, const Ride& ride) + { + const auto nauseaMultiplier = std::clamp(256 - guest.HappinessTarget, 64, 200); + const auto rideGeneratedNausea = (ride.ratings.nausea * nauseaMultiplier) / 512; + const auto hungerAdjustedNausea = ((rideGeneratedNausea * std::max(128, guest.Hunger)) / 128) * 2; + const auto nauseaGrowthRateChange = hungerAdjustedNausea >> (EnumValue(guest.NauseaTolerance) & 3); + guest.NauseaTarget = static_cast(std::min(guest.NauseaTarget + nauseaGrowthRateChange, 255)); + } + + static bool GuestShouldGoOnRideAgain(Guest& guest, const Ride& ride) + { + if (!ride.getRideTypeDescriptor().flags.has(RtdFlag::guestsWillRideAgain)) + return false; + if (!RideHasRatings(ride)) + return false; + if (ride.ratings.intensity > RideRating::make(10, 00) && !getGameState().cheats.ignoreRideIntensity) + return false; + if (guest.Happiness < 180) + return false; + if (guest.Energy < 100) + return false; + if (guest.Nausea > 160) + return false; + if (guest.Hunger < 30) + return false; + if (guest.Thirst < 20) + return false; + if (guest.Toilet > 170) + return false; + + uint8_t r = (ScenarioRand() & 0xFF); + if (r <= 128) + { + if (guest.GuestNumRides > 7) + return false; + if (r > 64) + return false; + } + + return true; + } + + static bool GuestShouldPreferredIntensityIncrease(Guest& guest) + { + if (getGameState().park.flags & PARK_FLAGS_PREF_LESS_INTENSE_RIDES) + return false; + if (guest.Happiness < 200) + return false; + + return (ScenarioRand() & 0xFF) >= static_cast(guest.Intensity); + } + + static bool GuestReallyLikedRide(Guest& guest, const Ride& ride) + { + if (guest.Happiness < 215) + return false; + if (guest.Nausea > 120) + return false; + if (!RideHasRatings(ride)) + return false; + if (ride.ratings.intensity > RideRating::make(10, 00) && !getGameState().cheats.ignoreRideIntensity) + return false; + return true; + } + + /** + * + * rct2: 0x0069BC9A + */ + static PeepThoughtType GuestAssessSurroundings(int16_t centre_x, int16_t centre_y, int16_t centre_z) + { + if ((TileElementHeight({ centre_x, centre_y })) > centre_z) + return PeepThoughtType::None; + + uint16_t num_scenery = 0; + uint16_t num_fountains = 0; + uint16_t nearby_music = 0; + uint16_t num_rubbish = 0; + + // TODO: Refactor this to step as tiles, 160 units is 5 tiles. + int16_t initial_x = std::max(centre_x - 160, 0); + int16_t initial_y = std::max(centre_y - 160, 0); + int16_t final_x = std::min(centre_x + 160, kMaximumMapSizeBig); + int16_t final_y = std::min(centre_y + 160, kMaximumMapSizeBig); + + for (int16_t x = initial_x; x < final_x; x += kCoordsXYStep) + { + for (int16_t y = initial_y; y < final_y; y += kCoordsXYStep) + { + for (auto* tileElement : TileElementsView(CoordsXY{ x, y })) + { + if (tileElement->IsGhost()) { - memmove(&guest.Thoughts[i], &guest.Thoughts[i + 1], sizeof(PeepThought) * (kPeepMaxThoughts - i - 1)); + continue; } - guest.Thoughts[kPeepMaxThoughts - 1].type = PeepThoughtType::None; + + switch (tileElement->GetType()) + { + case TileElementType::Path: + { + if (!tileElement->AsPath()->HasAddition()) + break; + + auto* pathAddEntry = tileElement->AsPath()->GetAdditionEntry(); + if (pathAddEntry == nullptr) + { + return PeepThoughtType::None; + } + if (tileElement->AsPath()->AdditionIsGhost()) + break; + + if (pathAddEntry->flags + & (PATH_ADDITION_FLAG_JUMPING_FOUNTAIN_WATER | PATH_ADDITION_FLAG_JUMPING_FOUNTAIN_SNOW)) + { + num_fountains++; + break; + } + if (tileElement->AsPath()->IsBroken()) + { + num_rubbish++; + } + break; + } + case TileElementType::LargeScenery: + case TileElementType::SmallScenery: + num_scenery++; + break; + case TileElementType::Track: + { + auto* ride = GetRide(tileElement->AsTrack()->GetRideIndex()); + if (ride == nullptr) + break; + + bool isPlayingMusic = ride->flags.has(RideFlag::music) && ride->status != RideStatus::closed + && !ride->flags.hasAny(RideFlag::brokenDown, RideFlag::crashed); + if (!isPlayingMusic) + break; + + const auto* musicObject = ride->getMusicObject(); + if (musicObject == nullptr) + break; + + if (musicObject->GetNiceFactor() == MusicNiceFactor::Nice) + { + nearby_music |= 1; + } + else if (musicObject->GetNiceFactor() == MusicNiceFactor::Overbearing) + { + nearby_music |= 2; + } + + break; + } + default: + break; + } + } + } + } + + for (auto litter : EntityList()) + { + int16_t dist_x = abs(litter->x - centre_x); + int16_t dist_y = abs(litter->y - centre_y); + if (std::max(dist_x, dist_y) <= 160) + { + num_rubbish++; + } + } + + if (num_fountains >= 5 && num_rubbish < 20) + return PeepThoughtType::Fountains; + + if (num_scenery >= 40 && num_rubbish < 8) + return PeepThoughtType::Scenery; + + if (nearby_music == 1 && num_rubbish < 20) + return PeepThoughtType::Music; + + if (num_rubbish < 2 && !getGameState().cheats.disableLittering) + // if disable littering cheat is enabled, peeps will not have the "clean and tidy park" thought + return PeepThoughtType::VeryClean; + + return PeepThoughtType::None; + } + + /** + * + * rct2: 0x0068F9A9 + */ + static void GuestUpdateHunger(Guest& guest) + { + if (guest.Hunger >= 3) + { + guest.Hunger -= 2; + + guest.EnergyTarget = std::min(guest.EnergyTarget + 2, kPeepMaxEnergyTarget); + guest.Toilet = std::min(guest.Toilet + 1, 255); + } + } + + /** + * Main purpose is to decide when peeps leave the park due to + * low happiness, low energy and (if appropriate) low money. + * + * rct2: 0x0068F8CD + */ + static void GuestDecideWhetherToLeavePark(Guest& guest) + { + if (guest.EnergyTarget >= 33) + { + guest.EnergyTarget -= 2; + } + + if (getGameState().weatherCurrent.temperature >= 21 && guest.Thirst >= 5) + { + guest.Thirst--; + } + + if (guest.OutsideOfPark) + { + return; + } + + /* Peeps that are happy enough, have enough energy and + * (if appropriate) have enough money will always stay + * in the park. */ + if (!(guest.PeepFlags & PEEP_FLAGS_LEAVING_PARK)) + { + if (getGameState().park.flags & PARK_FLAGS_NO_MONEY) + { + if (guest.Energy >= 70 && guest.Happiness >= 60) + { + return; + } + } + else + { + if (guest.Energy >= 55 && guest.Happiness >= 45 && guest.CashInPocket >= 5.00_GBP) + { + return; + } + } + } + + // Approx 95% chance of staying in the park + if ((ScenarioRand() & 0xFFFF) > 3276) + { + return; + } + + // In the remaining 5% chance the peep leaves the park. + GuestLeavePark(guest); + } + + /** + * + * rct2: 0x0068F93E + */ + static void GuestLeavePark(Guest& guest) + { + guest.GuestHeadingToRideId = RideId::GetNull(); + if (guest.PeepFlags & PEEP_FLAGS_LEAVING_PARK) + { + if (guest.GuestIsLostCountdown < 60) + { + return; + } + } + else + { + guest.GuestIsLostCountdown = 254; + guest.PeepFlags |= PEEP_FLAGS_LEAVING_PARK; + guest.PeepFlags &= ~PEEP_FLAGS_PARK_ENTRANCE_CHOSEN; + } + + guest.InsertNewThought(PeepThoughtType::GoHome); + + auto* windowMgr = Ui::GetWindowManager(); + WindowBase* w = windowMgr->FindByNumber(WindowClass::peep, guest.Id); + if (w != nullptr) + w->onPrepareDraw(); + windowMgr->InvalidateByNumber(WindowClass::peep, guest.Id); + } + + template + static void PeepHeadForNearestRide(Guest& guest, bool considerOnlyCloseRides, T predicate) + { + if (guest.State != PeepState::sitting && guest.State != PeepState::watching && guest.State != PeepState::walking) + { + return; + } + if (guest.PeepFlags & PEEP_FLAGS_LEAVING_PARK) + return; + if (guest.x == kLocationNull) + return; + if (!guest.GuestHeadingToRideId.IsNull()) + { + auto ride = GetRide(guest.GuestHeadingToRideId); + if (ride != nullptr && predicate(*ride)) + { + return; + } + } + + OpenRCT2::BitSet rideConsideration; + if (!considerOnlyCloseRides && (guest.HasItem(ShopItem::map))) + { + // Consider all rides in the park + auto& gameState = getGameState(); + for (const auto& ride : RideManager(gameState)) + { + if (predicate(ride)) + { + rideConsideration[ride.id.ToUnderlying()] = true; } } } else { - fresh_thought = i; - } - } - // If there are no fresh thoughts - // a previously new thought can become - // fresh. - if (add_fresh && fresh_thought != -1) - { - guest.Thoughts[fresh_thought].freshness = 1; - guest.WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_THOUGHTS; - } -} - -void Guest::Update() -{ - if (PeepFlags & PEEP_FLAGS_POSITION_FROZEN) - { - if (!(PeepFlags & PEEP_FLAGS_ANIMATION_FROZEN)) - { - // This is circumventing other logic, so only update every few ticks - if ((getGameState().currentTicks & 3) == 0) + // Take nearby rides into consideration + constexpr auto kSearchRadius = 10 * 32; + int32_t cx = Numerics::floor2(guest.x, 32); + int32_t cy = Numerics::floor2(guest.y, 32); + for (auto x = cx - kSearchRadius; x <= cx + kSearchRadius; x += kCoordsXYStep) { - if (IsActionWalking()) - UpdateWalkingAnimation(); - else - UpdateActionAnimation(); - Invalidate(); + for (auto y = cy - kSearchRadius; y <= cy + kSearchRadius; y += kCoordsXYStep) + { + auto location = CoordsXY{ x, y }; + if (!MapIsLocationValid(location)) + continue; + + for (auto* trackElement : TileElementsView(location)) + { + auto rideIndex = trackElement->GetRideIndex(); + auto ride = GetRide(rideIndex); + if (ride == nullptr) + continue; + + if (!predicate(*ride)) + continue; + + rideConsideration[ride->id.ToUnderlying()] = true; + } + } } } - return; - } - else if (PeepFlags & PEEP_FLAGS_ANIMATION_FROZEN) - { - // Animation is frozen while position is not. This allows a peep to walk - // around without its sprite being updated, which looks very glitchy. - // We'll just remove the flag and continue as normal, in this case. - PeepFlags &= ~PEEP_FLAGS_ANIMATION_FROZEN; - } - if (!PreviousRide.IsNull()) - { - if (++PreviousRideTimeOut >= 720) + // Filter the considered rides + RideId potentialRides[Limits::kMaxRidesInPark]; + size_t numPotentialRides = 0; + + auto& gameState = getGameState(); + for (auto& ride : RideManager(gameState)) { - PreviousRide = RideId::GetNull(); - } - } - - GuestUpdateThoughts(*this); - - // Walking speed logic - const auto stepsToTake = GetStepsToTake(); - const auto carryCheck = StepProgress + stepsToTake; - StepProgress = carryCheck; - - if (carryCheck <= 255) - { - UpdateEasterEggInteractions(); - } - else - { - // Loc68FD2F - switch (State) - { - case PeepState::falling: - UpdateFalling(); - break; - case PeepState::one: - Update1(); - break; - case PeepState::onRide: - // No action - break; - case PeepState::picked: - UpdatePicked(); - break; - case PeepState::queuingFront: - UpdateRide(); - break; - case PeepState::leavingRide: - UpdateRide(); - break; - case PeepState::walking: - UpdateWalking(); - break; - case PeepState::queuing: - UpdateQueuing(); - break; - case PeepState::enteringRide: - UpdateRide(); - break; - case PeepState::sitting: - UpdateSitting(); - break; - case PeepState::enteringPark: - UpdateEnteringPark(); - break; - case PeepState::leavingPark: - UpdateLeavingPark(); - break; - case PeepState::buying: - UpdateBuying(); - break; - case PeepState::watching: - UpdateWatching(); - break; - case PeepState::usingBin: - UpdateUsingBin(); - break; - default: - // TODO reset to default state - assert(false); - break; - } - } -} - -/** - * - * rct2: 0x691A30 - * Used by entering_ride and queueing_front */ -void Guest::UpdateRide() -{ - NextFlags &= ~PEEP_NEXT_FLAG_IS_SLOPED; - - switch (RideSubState) - { - case PeepRideSubState::atEntrance: - UpdateRideAtEntrance(); - break; - case PeepRideSubState::inEntrance: - UpdateRideAdvanceThroughEntrance(); - break; - case PeepRideSubState::freeVehicleCheck: - UpdateRideFreeVehicleCheck(); - break; - case PeepRideSubState::leaveEntrance: - UpdateRideAdvanceThroughEntrance(); - break; - case PeepRideSubState::approachVehicle: - UpdateRideApproachVehicle(); - break; - case PeepRideSubState::enterVehicle: - UpdateRideEnterVehicle(); - break; - case PeepRideSubState::onRide: - // No action, on ride. - break; - case PeepRideSubState::leaveVehicle: - UpdateRideLeaveVehicle(); - break; - case PeepRideSubState::approachExit: - UpdateRideApproachExit(); - break; - case PeepRideSubState::inExit: - UpdateRideInExit(); - break; - case PeepRideSubState::approachVehicleWaypoints: - UpdateRideApproachVehicleWaypoints(); - break; - case PeepRideSubState::approachExitWaypoints: - UpdateRideApproachExitWaypoints(); - break; - case PeepRideSubState::approachSpiralSlide: - UpdateRideApproachSpiralSlide(); - break; - case PeepRideSubState::onSpiralSlide: - UpdateRideOnSpiralSlide(); - break; - case PeepRideSubState::leaveSpiralSlide: - UpdateRideLeaveSpiralSlide(); - break; - case PeepRideSubState::mazePathfinding: - UpdateRideMazePathfinding(); - break; - case PeepRideSubState::leaveExit: - UpdateRideLeaveExit(); - break; - case PeepRideSubState::approachShop: - UpdateRideShopApproach(); - break; - case PeepRideSubState::interactShop: - UpdateRideShopInteract(); - break; - case PeepRideSubState::leaveShop: - UpdateRideShopLeave(); - break; - default: - // Invalid peep sub-state - assert(false); - break; - } -} - -/** - * - * rct2: 0x0069030A - */ -void Guest::UpdateWalking() -{ - if (!CheckForPath()) - return; - - const auto currentTicks = getGameState().currentTicks; - - if (IsActionInterruptableSafely()) - { - PeepActionType NewAction = Action; - - if (PeepFlags & PEEP_FLAGS_WAVING && (0xFFFF & ScenarioRand()) < 936) - NewAction = PeepActionType::wave2; - else if (PeepFlags & PEEP_FLAGS_PHOTO && (0xFFFF & ScenarioRand()) < 936) - NewAction = PeepActionType::takePhoto; - else if (PeepFlags & PEEP_FLAGS_PAINTING && (0xFFFF & ScenarioRand()) < 936) - NewAction = PeepActionType::drawPicture; - - if (NewAction != Action) - { - Action = NewAction; - AnimationFrameNum = 0; - AnimationImageIdOffset = 0; - UpdateCurrentAnimationType(); - } - } - - if (PeepFlags & PEEP_FLAGS_LITTER) - { - if (!GetNextIsSurface()) - { - if ((0xFFFF & ScenarioRand()) <= 4096) + if (rideConsideration[ride.id.ToUnderlying()]) { - static constexpr Litter::Type litter_types[] = { - Litter::Type::emptyCan, - Litter::Type::rubbish, - Litter::Type::burgerBox, - Litter::Type::emptyCup, - }; - auto litterType = litter_types[ScenarioRand() & 0x3]; - const auto loc = GetLocation(); - int32_t litterX = loc.x + (ScenarioRand() & 0x7) - 3; - int32_t litterY = loc.y + (ScenarioRand() & 0x7) - 3; - Direction litterDirection = (ScenarioRand() & 0x3); - - Litter::Create({ litterX, litterY, loc.z, litterDirection }, litterType); + if (!ride.flags.has(RideFlag::queueFull)) + { + if (guest.ShouldGoOnRide(ride, StationIndex::FromUnderlying(0), false, true)) + { + potentialRides[numPotentialRides++] = ride.id; + } + } } } - } - else if (HasEmptyContainer()) - { - if ((!GetNextIsSurface()) && (static_cast(Id.ToUnderlying() & 0x1FF) == (currentTicks & 0x1FF)) - && ((0xFFFF & ScenarioRand()) <= 4096)) + + // Pick the closest ride + Ride* closestRide{}; + auto closestRideDistance = std::numeric_limits::max(); + for (size_t i = 0; i < numPotentialRides; i++) { - int32_t container = Numerics::bitScanForward(GetEmptyContainerFlags()); - auto litterType = Litter::Type::vomit; - - if (container != -1) + auto ride = GetRide(potentialRides[i]); + if (ride != nullptr) { - auto item = static_cast(container); - RemoveItem(item); - litterType = Litter::Type(GetShopItemDescriptor(item).Type); - } - - WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_INVENTORY; - UpdateAnimationGroup(); - - const auto loc = GetLocation(); - int32_t litterX = loc.x + (ScenarioRand() & 0x7) - 3; - int32_t litterY = loc.y + (ScenarioRand() & 0x7) - 3; - Direction litterDirection = (ScenarioRand() & 0x3); - - Litter::Create({ litterX, litterY, loc.z, litterDirection }, litterType); - } - } - - if (ShouldWaitForLevelCrossing()) - { - // Wait for vehicle to pass - UpdateWaitingAtCrossing(); - - return; - } - - const auto [pathingResult, _] = PerformNextAction(); - if (!(pathingResult & PATHING_DESTINATION_REACHED)) - return; - - if (GetNextIsSurface()) - { - auto surfaceElement = MapGetSurfaceElementAt(NextLoc); - - if (surfaceElement != nullptr) - { - int32_t water_height = surfaceElement->GetWaterHeight(); - if (water_height > 0) - { - MoveTo({ x, y, water_height }); - SetState(PeepState::falling); - return; + auto rideLocation = ride->getStation().Start; + int32_t distance = abs(rideLocation.x - guest.x) + abs(rideLocation.y - guest.y); + if (distance < closestRideDistance) + { + closestRide = ride; + closestRideDistance = distance; + } } } + if (closestRide != nullptr) + { + // Head to that ride + guest.GuestHeadingToRideId = closestRide->id; + guest.GuestIsLostCountdown = 200; + guest.ResetPathfindGoal(); + guest.WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_ACTION; + guest.TimeLost = 0; + } } - CheckIfLost(); - CheckCantFindRide(); - CheckCantFindExit(); - - if (UpdateWalkingFindBench()) - return; - - if (UpdateWalkingFindBin()) - return; - - GuestUpdateWalkingBreakScenery(*this); - - if (State != PeepState::walking) - return; - - if (PeepFlags & PEEP_FLAGS_LEAVING_PARK) - return; - - if (Nausea > 140) - return; - - if (Happiness < 120) - return; - - if (Toilet > 140) - return; - - uint16_t chance = HasFoodOrDrink() ? 13107 : 2849; - - if ((ScenarioRand() & 0xFFFF) > chance) - return; - - if (GetNextIsSurface() || GetNextIsSloped()) - return; - - TileElement* tileElement = MapGetFirstElementAt(NextLoc); - if (tileElement == nullptr) - return; - - for (;; tileElement++) + static void GuestHeadForNearestRideWithFlag(Guest& guest, bool considerOnlyCloseRides, RtdFlag rtdFlag) { - if (tileElement->GetType() == TileElementType::Path) - { - if (NextLoc.z == tileElement->GetBaseZ()) - break; - } - if (tileElement->IsLastForTile()) + PeepHeadForNearestRide(guest, considerOnlyCloseRides, [rtdFlag](const Ride& ride) { + return ride.getRideTypeDescriptor().flags.has(rtdFlag); + }); + } + + static void GuestHeadForNearestRideWithSpecialType(Guest& guest, bool considerOnlyCloseRides, RtdSpecialType specialType) + { + if ((specialType == RtdSpecialType::toilet) && guest.HasFoodOrDrink()) { return; } + PeepHeadForNearestRide(guest, considerOnlyCloseRides, [specialType](const Ride& ride) { + return ride.getRideTypeDescriptor().specialType == specialType; + }); } - int32_t positions_free = 15; - - if (tileElement->AsPath()->HasAddition()) + /** + * + * rct2: 0x00699FE3 + * Stops peeps that are having thoughts + * such as "I'm hungry" after visiting a food shop. + * Works for Thirst/Hungry/Low Money/Toilet + */ + static void GuestStopPurchaseThought(Guest& guest, ride_type_t rideType) { - if (!tileElement->AsPath()->AdditionIsGhost()) + auto thoughtType = PeepThoughtType::Hungry; + + const auto& rtd = GetRideTypeDescriptor(rideType); + if (!rtd.flags.has(RtdFlag::sellsFood)) { - auto* pathAddEntry = tileElement->AsPath()->GetAdditionEntry(); - if (pathAddEntry == nullptr) + thoughtType = PeepThoughtType::Thirsty; + if (!rtd.flags.has(RtdFlag::sellsDrinks)) { - return; - } - - if (!(pathAddEntry->flags & PATH_ADDITION_FLAG_IS_BENCH)) - positions_free = 9; - } - } - - int32_t edges = (tileElement->AsPath()->GetEdges()) ^ 0xF; - if (edges == 0) - return; - - uint8_t chosen_edge = ScenarioRand() & 0x3; - - while (!(edges & (1 << chosen_edge))) - chosen_edge = (chosen_edge + 1) & 3; - - RideId ride_to_view; - uint8_t ride_seat_to_view; - if (IsOnLevelCrossing() || !GuestFindRideToLookAt(*this, chosen_edge, &ride_to_view, &ride_seat_to_view)) - return; - - // Check if there is a peep watching (and if there is place for us) - for (auto peep : EntityTileList({ x, y })) - { - if (peep->State != PeepState::watching) - continue; - - if (z != peep->z) - continue; - - if ((peep->Var37 & 0x3) != chosen_edge) - continue; - - positions_free &= ~(1 << ((peep->Var37 & 0x1C) >> 2)); - } - - if (!positions_free) - return; - - uint8_t chosen_position = ScenarioRand() & 0x3; - - while (!(positions_free & (1 << chosen_position))) - chosen_position = (chosen_position + 1) & 3; - - CurrentRide = ride_to_view; - CurrentSeat = ride_seat_to_view; - Var37 = chosen_edge | (chosen_position << 2); - - SetState(PeepState::watching); - SubState = 0; - - int32_t destX = (x & 0xFFE0) + kWatchingPositionOffsets[Var37 & 0x1F].x; - int32_t destY = (y & 0xFFE0) + kWatchingPositionOffsets[Var37 & 0x1F].y; - - SetDestination({ destX, destY }, 3); - - if (CurrentSeat & 1) - { - InsertNewThought(PeepThoughtType::NewRide); - } - if (CurrentRide.IsNull()) - { - InsertNewThought(PeepThoughtType::Scenery); - } -} - -/** - * - * rct2: 0x69185D - */ -void Guest::UpdateQueuing() -{ - if (!CheckForPath()) - { - RemoveFromQueue(); - return; - } - auto ride = GetRide(CurrentRide); - if (ride == nullptr || ride->status != RideStatus::open) - { - RemoveFromQueue(); - SetState(PeepState::one); - return; - } - - // If not in the queue then at front of queue - if (RideSubState != PeepRideSubState::inQueue) - { - bool is_front = true; - // Fix #4819: Occasionally the peep->GuestNextInQueue is incorrectly set - // to prevent this from causing the peeps to enter a loop - // first check if the next in queue is actually nearby - // if they are not then it's safe to assume that this is - // the front of the queue. - Peep* nextGuest = getGameState().entities.GetEntity(GuestNextInQueue); - if (nextGuest != nullptr) - { - if (abs(nextGuest->x - x) < 32 && abs(nextGuest->y - y) < 32) - { - is_front = false; + thoughtType = PeepThoughtType::RunningOut; + if (rtd.specialType != RtdSpecialType::cashMachine) + { + thoughtType = PeepThoughtType::Toilet; + if (rtd.specialType != RtdSpecialType::toilet) + { + return; + } + } } } - if (is_front) + // Remove the related thought + for (int32_t i = 0; i < kPeepMaxThoughts; ++i) { - // Happens every time peep goes onto ride. - DestinationTolerance = 0; - SetState(PeepState::queuingFront); - RideSubState = PeepRideSubState::atEntrance; - } + PeepThought* thought = &guest.Thoughts[i]; - return; - } + if (thought->type == PeepThoughtType::None) + break; - PerformNextAction(); - if (!IsActionInterruptable()) - return; - if (AnimationGroup == PeepAnimationGroup::normal) - { - if (TimeInQueue >= 2000 && (0xFFFF & ScenarioRand()) <= 119) - { - // Eat Food/Look at watch - Action = PeepActionType::eatFood; - AnimationFrameNum = 0; - AnimationImageIdOffset = 0; - UpdateCurrentAnimationType(); - } - if (TimeInQueue >= 3500 && (0xFFFF & ScenarioRand()) <= 93) - { - // Create the I have been waiting in line ages thought - InsertNewThought(PeepThoughtType::QueuingAges, CurrentRide); - } - } - else - { - if (!(TimeInQueue & 0x3F) && IsActionIdle() && NextAnimationType == PeepAnimationType::watchRide) - { - switch (AnimationGroup) + if (thought->type != thoughtType) + continue; + + if (i < kPeepMaxThoughts - 1) { - case PeepAnimationGroup::iceCream: - case PeepAnimationGroup::chips: - case PeepAnimationGroup::burger: - case PeepAnimationGroup::drink: - case PeepAnimationGroup::candyfloss: - case PeepAnimationGroup::pizza: - case PeepAnimationGroup::popcorn: - case PeepAnimationGroup::hotDog: - case PeepAnimationGroup::tentacle: - case PeepAnimationGroup::toffeeApple: - case PeepAnimationGroup::doughnut: - case PeepAnimationGroup::coffee: - case PeepAnimationGroup::chicken: - case PeepAnimationGroup::lemonade: - case PeepAnimationGroup::pretzel: - case PeepAnimationGroup::sujeonggwa: - case PeepAnimationGroup::juice: - case PeepAnimationGroup::funnelCake: - case PeepAnimationGroup::noodles: - case PeepAnimationGroup::sausage: - case PeepAnimationGroup::soup: - case PeepAnimationGroup::sandwich: - // Eat food - Action = PeepActionType::eatFood; - AnimationFrameNum = 0; - AnimationImageIdOffset = 0; - UpdateCurrentAnimationType(); - break; - default: - break; + memmove(thought, thought + 1, sizeof(PeepThought) * (kPeepMaxThoughts - i - 1)); } + + guest.Thoughts[kPeepMaxThoughts - 1].type = PeepThoughtType::None; + + guest.WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_THOUGHTS; + i--; } } - if (TimeInQueue < 4300) - return; - if (Happiness <= 65 && (0xFFFF & ScenarioRand()) < 2184) + /** + * + * rct2: 0x0069AEB7 + */ + static bool PeepShouldUseCashMachine(Guest& guest, RideId rideIndex) { - // Give up queueing for the ride - Orientation ^= (1 << 4); - Invalidate(); - RemoveFromQueue(); - SetState(PeepState::one); - } -} + if (getGameState().park.flags & PARK_FLAGS_NO_MONEY) + return false; + if (guest.PeepFlags & PEEP_FLAGS_LEAVING_PARK) + return false; + if (guest.CashInPocket > 20.00_GBP) + return false; + if (115 + (ScenarioRand() % 128) > guest.Happiness) + return false; + if (guest.Energy < 80) + return false; -/** - * rct2: 0x691451 - */ -void Guest::UpdateEnteringPark() -{ - if (Var37 != 1) - { - const auto [pathingResult, _] = PerformNextAction(); - if ((pathingResult & PATHING_OUTSIDE_PARK)) + auto ride = GetRide(rideIndex); + if (ride != nullptr) { - DecrementGuestsHeadingForPark(); - PeepEntityRemove(this); + ride->updateSatisfaction(guest.Happiness >> 6); + ride->curNumCustomers++; + ride->totalCustomers = AddClamp(ride->totalCustomers, 1u); + ride->windowInvalidateFlags.set(RideInvalidateFlag::customers); } - return; - } - if (auto loc = UpdateAction(); loc.has_value()) - { - MoveTo({ loc.value(), z }); - return; - } - SetState(PeepState::falling); - - OutsideOfPark = false; - ParkEntryTime = getGameState().currentTicks; - IncrementGuestsInPark(); - DecrementGuestsHeadingForPark(); - auto intent = Intent(INTENT_ACTION_UPDATE_GUEST_COUNT); - ContextBroadcastIntent(&intent); -} - -/** - * - * rct2: 0x6914CD - */ -void Guest::UpdateLeavingPark() -{ - if (Var37 != 0) - { - const auto [pathingResult, _] = PerformNextAction(); - if (!(pathingResult & PATHING_OUTSIDE_PARK)) - return; - PeepEntityRemove(this); - return; + return true; } - if (auto loc = UpdateAction(); loc.has_value()) - { - MoveTo({ loc.value(), z }); - return; - } - - OutsideOfPark = true; - DestinationTolerance = 5; - DecrementGuestsInPark(); - auto intent = Intent(INTENT_ACTION_UPDATE_GUEST_COUNT); - ContextBroadcastIntent(&intent); - Var37 = 1; - - auto* windowMgr = Ui::GetWindowManager(); - windowMgr->InvalidateByClass(WindowClass::guestList); - - const auto [pathingResult, _] = PerformNextAction(); - if (!(pathingResult & PATHING_OUTSIDE_PARK)) - return; - Remove(); -} - -/** - * - * rct2: 0x6916D6 - */ -void Guest::UpdateWatching() -{ - if (SubState == 0) + /** + * + * rct2: 0x006912A3 + */ + void Guest::UpdateBuying() { if (!CheckForPath()) return; - const auto [pathingResult, _] = PerformNextAction(); - if (!(pathingResult & PATHING_DESTINATION_REACHED)) + auto ride = GetRide(CurrentRide); + if (ride == nullptr || ride->status != RideStatus::open) + { + SetState(PeepState::falling); return; - - SetDestination(GetLocation()); - - Orientation = (Var37 & 3) * 8; - - Action = PeepActionType::idle; - NextAnimationType = PeepAnimationType::watchRide; - - SwitchNextAnimationType(); - - SubState++; - - TimeToStand = std::clamp(((129 - Energy) * 16 + 50) / 2, 0, 255); - UpdateAnimationGroup(); - } - else if (SubState == 1) - { - if (!IsActionInterruptable()) - { - // 6917F6 - UpdateAction(); - Invalidate(); - if (!IsActionWalking()) - return; - Action = PeepActionType::idle; - } - else - { - if (HasFoodOrDrink()) - { - if ((ScenarioRand() & 0xFFFF) <= 1310) - { - Action = PeepActionType::eatFood; - AnimationFrameNum = 0; - AnimationImageIdOffset = 0; - UpdateCurrentAnimationType(); - return; - } - } - - if ((ScenarioRand() & 0xFFFF) <= 655) - { - Action = PeepActionType::takePhoto; - AnimationFrameNum = 0; - AnimationImageIdOffset = 0; - UpdateCurrentAnimationType(); - return; - } - - if ((StandingFlags & 1)) - { - if ((ScenarioRand() & 0xFFFF) <= 655) - { - Action = PeepActionType::wave; - AnimationFrameNum = 0; - AnimationImageIdOffset = 0; - UpdateCurrentAnimationType(); - return; - } - } } - StandingFlags ^= (1 << 7); - if (!(StandingFlags & (1 << 7))) - return; - - TimeToStand--; - if (TimeToStand != 0) - return; - - SetState(PeepState::walking); - UpdateAnimationGroup(); - // Send peep to the centre of current tile. - - auto destination = GetLocation().ToTileCentre(); - SetDestination(destination, 5); - UpdateCurrentAnimationType(); - } -} - -/** - * - * rct2: 0x00691089 - */ -void Guest::UpdateUsingBin() -{ - switch (UsingBinSubState) - { - case PeepUsingBinSubState::walkingToBin: - { - if (!CheckForPath()) - return; - - const auto [pathingResult, _] = PerformNextAction(); - if (pathingResult & PATHING_DESTINATION_REACHED) - { - UsingBinSubState = PeepUsingBinSubState::goingBack; - } - break; - } - case PeepUsingBinSubState::goingBack: + if (SubState == 1) { if (!IsActionWalking()) { @@ -6010,1847 +3414,4454 @@ void Guest::UpdateUsingBin() return; } - PathElement* foundElement = nullptr; - for (auto* pathElement : TileElementsView(NextLoc)) + const auto& rtd = GetRideTypeDescriptor(ride->type); + if (rtd.specialType == RtdSpecialType::cashMachine) { - if (pathElement->GetBaseZ() != NextLoc.z) - continue; + if (CurrentRide != PreviousRide) + { + CashInPocket += 50.00_GBP; + } + auto* windowMgr = Ui::GetWindowManager(); + windowMgr->InvalidateByNumber(WindowClass::peep, Id); + } + Orientation ^= 0x10; - if (!pathElement->HasAddition()) - break; + auto destination = CoordsXY{ 16, 16 } + NextLoc; + SetDestination(destination); + PeepDirection = DirectionReverse(PeepDirection); - auto* pathAddEntry = pathElement->GetAdditionEntry(); - if (!(pathAddEntry->flags & PATH_ADDITION_FLAG_IS_BIN)) - break; + SetState(PeepState::walking); + return; + } - if (pathElement->IsBroken()) - break; + bool item_bought = false; - if (pathElement->AdditionIsGhost()) - break; + if (CurrentRide != PreviousRide) + { + const auto& rtd = GetRideTypeDescriptor(ride->type); + if (rtd.specialType == RtdSpecialType::cashMachine) + { + item_bought = PeepShouldUseCashMachine(*this, CurrentRide); + if (!item_bought) + { + PreviousRide = CurrentRide; + PreviousRideTimeOut = 0; + } + else + { + Action = PeepActionType::withdrawMoney; + AnimationFrameNum = 0; + AnimationImageIdOffset = 0; - foundElement = pathElement; - break; + UpdateCurrentAnimationType(); + + ride->numPrimaryItemsSold = AddClamp(ride->numPrimaryItemsSold, 1u); + } + } + else + { + const auto* ride_type = GetRideEntryByIndex(ride->subtype); + if (ride_type == nullptr) + { + return; + } + if (ride_type->shop_item[1] != ShopItem::none) + { + auto price = ride->price[1]; + + item_bought = GuestDecideAndBuyItem(*this, *ride, ride_type->shop_item[1], price); + if (item_bought) + { + ride->numSecondaryItemsSold = AddClamp(ride->numSecondaryItemsSold, 1u); + } + } + + if (!item_bought && ride_type->shop_item[0] != ShopItem::none) + { + auto price = ride->price[0]; + + item_bought = GuestDecideAndBuyItem(*this, *ride, ride_type->shop_item[0], price); + if (item_bought) + { + ride->numPrimaryItemsSold = AddClamp(ride->numPrimaryItemsSold, 1u); + } + } + } + } + + if (item_bought) + { + ride->updatePopularity(1); + + GuestStopPurchaseThought(*this, ride->type); + } + else + { + ride->updatePopularity(0); + } + SubState = 1; + } + + /** + * + * rct2: 0x00691A3B + */ + void Guest::UpdateRideAtEntrance() + { + auto ride = GetRide(CurrentRide); + if (ride == nullptr) + return; + + // The peep will keep advancing in the entranceway + // whilst in this state. When it has reached the very + // front of the queue destination tolerance is set to + // zero to indicate it is final decision time (try_leave will pass). + // When a peep has to return to the queue without getting on a ride + // this is the state it will return to. + if (DestinationTolerance != 0) + { + int16_t xy_distance; + if (auto loc = UpdateAction(xy_distance); loc.has_value()) + { + int16_t actionZ = z; + if (xy_distance < 16) + { + const auto& station = ride->getStation(CurrentRideStation); + auto entrance = station.Entrance.ToCoordsXYZ(); + actionZ = entrance.z + 2; + } + MoveTo({ loc.value(), actionZ }); + } + else + { + DestinationTolerance = 0; + Orientation ^= (1 << 4); + Invalidate(); + } + } + + sfl::static_vector carArray; + + if (ride->getRideTypeDescriptor().flags.has(RtdFlag::noVehicles)) + { + if (ride->numRiders >= ride->operationOption) + return; + } + else + { + if (!FindVehicleToEnter(*this, *ride, carArray)) + return; + } + + if (ride->status != RideStatus::open || ride->vehicleChangeTimeout != 0) + { + PeepUpdateRideAtEntranceTryLeave(*this); + return; + } + + if (ride->flags.has(RideFlag::brokenDown)) + return; + + auto ridePrice = RideGetPrice(*ride); + if (ridePrice != 0) + { + if (!PeepCheckRidePriceAtEntrance(*this, *ride, ridePrice)) + return; + } + + if (!ride->getRideTypeDescriptor().flags.has(RtdFlag::noVehicles)) + { + Vehicle* vehicle = PeepChooseCarFromRide(*this, *ride, carArray); + PeepChooseSeatFromCar(this, *ride, vehicle); + } + GoToRideEntrance(*ride); + } + + /** rct2: 0x00981FD4, 0x00981FD6 */ + static constexpr CoordsXY kMazeEntranceStart[] = { + { 8, 8 }, + { 8, 24 }, + { 24, 24 }, + { 24, 8 }, + }; + + void PeepUpdateRideLeaveEntranceMaze(Guest& guest, Ride& ride, CoordsXYZD& entrance_loc) + { + guest.MazeLastEdge = entrance_loc.direction + 1; + + entrance_loc.x += CoordsDirectionDelta[entrance_loc.direction].x; + entrance_loc.y += CoordsDirectionDelta[entrance_loc.direction].y; + + uint8_t direction = entrance_loc.direction * 4 + 11; + if (ScenarioRand() & 0x40) + { + direction += 4; + guest.MazeLastEdge += 2; + } + + direction &= 0xF; + // Direction is 11, 15, 3, or 7 + guest.Var37 = direction; + guest.MazeLastEdge &= 3; + + entrance_loc.x += kMazeEntranceStart[direction / 4].x; + entrance_loc.y += kMazeEntranceStart[direction / 4].y; + + guest.SetDestination(entrance_loc, 3); + + ride.curNumCustomers++; + guest.OnEnterRide(ride); + guest.RideSubState = PeepRideSubState::mazePathfinding; + } + + void PeepUpdateRideLeaveEntranceSpiralSlide(Guest& guest, Ride& ride, CoordsXYZD& entrance_loc) + { + entrance_loc = { ride.getStation(guest.CurrentRideStation).GetStart(), entrance_loc.direction }; + + TileElement* tile_element = RideGetStationStartTrackElement(ride, guest.CurrentRideStation); + + uint8_t direction_track = (tile_element == nullptr ? 0 : tile_element->GetDirection()); + + guest.Var37 = (entrance_loc.direction << 2) | (direction_track << 4); + + entrance_loc += kSpiralSlideWalkingPath[guest.Var37]; + + guest.SetDestination(entrance_loc); + guest.timesSlidDown = 0; + + ride.curNumCustomers++; + guest.OnEnterRide(ride); + guest.RideSubState = PeepRideSubState::approachSpiralSlide; + } + + void PeepUpdateRideLeaveEntranceDefault(Guest& guest, Ride& ride, CoordsXYZD& entrance_loc) + { + const auto currentTicks = getGameState().currentTicks; + + // If the ride type was changed guests will become stuck. + // Inform the player about this if its a new issue or hasn't been addressed within 120 seconds. + if ((ride.currentIssues & RIDE_ISSUE_GUESTS_STUCK) == 0 || currentTicks - ride.lastIssueTime > 3000) + { + ride.currentIssues |= RIDE_ISSUE_GUESTS_STUCK; + ride.lastIssueTime = currentTicks; + + auto ft = Formatter(); + ride.formatNameTo(ft); + if (Config::Get().notifications.rideWarnings) + { + News::AddItemToQueue( + News::ItemType::ride, STR_GUESTS_GETTING_STUCK_ON_RIDE, guest.CurrentRide.ToUnderlying(), ft); + } + } + } + + uint8_t Guest::GetWaypointedSeatLocation(const Ride& ride, const CarEntry* vehicle_type, uint8_t track_direction) const + { + // The seatlocation can be split into segments around the ride base + // to decide the segment first split off the segmentable seat location + // from the fixed section + uint8_t seatLocationSegment = CurrentSeat & 0x7; + uint8_t seatLocationFixed = CurrentSeat & 0xF8; + + // Enterprise has more segments (8) compared to the normal (4) + if (ride.getRideTypeDescriptor().specialType != RtdSpecialType::enterprise) + track_direction *= 2; + + // Type 1 loading doesn't do segments and all peeps go to the same + // location on the ride + if (vehicle_type->peep_loading_waypoint_segments == 0) + { + track_direction /= 2; + seatLocationSegment = 0; + seatLocationFixed = 0; + } + seatLocationSegment += track_direction; + seatLocationSegment &= 0x7; + return seatLocationSegment + seatLocationFixed; + } + + void Guest::UpdateRideLeaveEntranceWaypoints(const Ride& ride) + { + const auto& station = ride.getStation(CurrentRideStation); + if (station.Entrance.IsNull()) + { + return; + } + uint8_t direction_entrance = station.Entrance.direction; + + TileElement* tile_element = RideGetStationStartTrackElement(ride, CurrentRideStation); + + uint8_t direction_track = (tile_element == nullptr ? 0 : tile_element->GetDirection()); + + auto vehicle = getGameState().entities.GetEntity(ride.vehicles[CurrentTrain]); + if (vehicle == nullptr) + { + // TODO: Goto ride exit on failure. + return; + } + const auto* rideEntry = vehicle->GetRideEntry(); + const auto* carEntry = &rideEntry->Cars[vehicle->vehicle_type]; + + Var37 = (direction_entrance | GetWaypointedSeatLocation(ride, carEntry, direction_track) * 4) * 4; + + const auto& rtd = ride.getRideTypeDescriptor(); + CoordsXY waypoint = rtd.GetGuestWaypointLocation(*vehicle, ride, CurrentRideStation); + + const auto waypointIndex = Var37 / 4u; + if (waypointIndex < carEntry->peep_loading_waypoints.size()) + { + Guard::Assert(carEntry->peep_loading_waypoints.size() >= static_cast(waypointIndex)); + waypoint.x += carEntry->peep_loading_waypoints[waypointIndex][0].x; + waypoint.y += carEntry->peep_loading_waypoints[waypointIndex][0].y; + } + + SetDestination(waypoint); + RideSubState = PeepRideSubState::approachVehicleWaypoints; + } + + /** + * + * rct2: 0x006921D3 + */ + void Guest::UpdateRideAdvanceThroughEntrance() + { + auto ride = GetRide(CurrentRide); + if (ride == nullptr) + return; + + int16_t actionZ, xy_distance; + + const auto* rideEntry = ride->getRideEntry(); + + if (auto loc = UpdateAction(xy_distance); loc.has_value()) + { + uint16_t distanceThreshold = 16; + if (rideEntry != nullptr) + { + uint8_t vehicle = rideEntry->DefaultCar; + if (rideEntry->Cars[vehicle].flags.hasAny( + CarEntryFlag::isMiniGolf, CarEntryFlag::isChairlift, CarEntryFlag::isGoKart)) + { + distanceThreshold = 28; + } } - if (foundElement == nullptr) + if (RideSubState == PeepRideSubState::inEntrance && xy_distance < distanceThreshold) + { + RideSubState = PeepRideSubState::freeVehicleCheck; + } + + actionZ = ride->getStation(CurrentRideStation).GetBaseZ(); + + distanceThreshold += 4; + if (xy_distance < distanceThreshold) + { + actionZ += ride->getRideTypeDescriptor().Heights.PlatformHeight; + } + + MoveTo({ loc.value(), actionZ }); + return; + } + + if (RideSubState == PeepRideSubState::inEntrance) + { + RideSubState = PeepRideSubState::freeVehicleCheck; + return; + } + + if (ride->getRideTypeDescriptor().flags.has(RtdFlag::noVehicles)) + { + const auto& station = ride->getStation(CurrentRideStation); + auto entranceLocation = station.Entrance.ToCoordsXYZD(); + if (entranceLocation.IsNull()) { - StateReset(); return; } - // Bin selection is one of 4 corners - uint8_t selectedBin = Var37 * 2; - - // This counts down 2 = No rubbish, 0 = full - uint8_t spaceLeftInBin = 0x3 & (foundElement->GetAdditionStatus() >> selectedBin); - uint64_t emptyContainers = GetEmptyContainerFlags(); - - for (uint8_t curContainer = 0; curContainer < 64; curContainer++) - { - if (!(emptyContainers & (1uLL << curContainer))) - continue; - - auto item = ShopItem(curContainer); - if (spaceLeftInBin != 0) - { - // OpenRCT2 modification: This previously used - // the tick count as a simple random function - // switched to scenario_rand as it is more reliable - if ((ScenarioRand() & 7) == 0) - spaceLeftInBin--; - RemoveItem(item); - WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_INVENTORY; - UpdateAnimationGroup(); - continue; - } - - auto litterType = Litter::Type(GetShopItemDescriptor(item).Type); - - int32_t litterX = x + (ScenarioRand() & 7) - 3; - int32_t litterY = y + (ScenarioRand() & 7) - 3; - - Litter::Create({ litterX, litterY, z, static_cast(ScenarioRand() & 3) }, litterType); - RemoveItem(item); - WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_INVENTORY; - - UpdateAnimationGroup(); - } - - uint8_t additionStatus = foundElement->GetAdditionStatus(); - // Place new amount in bin by first clearing the value - additionStatus &= ~(3 << selectedBin); - // Then placing the new value. - additionStatus |= spaceLeftInBin << selectedBin; - foundElement->SetAdditionStatus(additionStatus); - - MapInvalidateTileZoom0({ NextLoc, foundElement->GetBaseZ(), foundElement->GetClearanceZ() }); - StateReset(); - break; + const auto& rtd = GetRideTypeDescriptor(ride->type); + rtd.UpdateLeaveEntrance(*this, *ride, entranceLocation); + return; } - default: - Guard::Assert(false, "Invalid sub state"); - break; - } -} -/* Simplifies 0x690582. Returns true if should find bench*/ -bool Guest::ShouldFindBench() -{ - if (PeepFlags & PEEP_FLAGS_LEAVING_PARK) - { - return false; - } - - if (HasFoodOrDrink()) - { - if (Hunger < 128 || Happiness < 128) + Vehicle* vehicle = getGameState().entities.GetEntity(ride->vehicles[CurrentTrain]); + if (vehicle == nullptr) { - if (!GetNextIsSurface() && !GetNextIsSloped()) - { - return true; - } + return; } - } - if (Nausea <= 170 && Energy > 50) - { - return false; - } - - return !GetNextIsSurface() && !GetNextIsSloped(); -} - -static PathElement* FindBench(const CoordsXYZ& loc) -{ - for (auto* pathElement : TileElementsView(loc)) - { - if (pathElement->GetBaseZ() != loc.z) - continue; - - if (!pathElement->HasAddition()) - continue; - - auto* pathAddEntry = pathElement->GetAdditionEntry(); - if (pathAddEntry == nullptr || !(pathAddEntry->flags & PATH_ADDITION_FLAG_IS_BENCH)) - continue; - - if (pathElement->IsBroken()) - continue; - - if (pathElement->AdditionIsGhost()) - continue; - - return pathElement; - } - - return nullptr; -} - -/** - * - * rct2: 0x00690582 - * Returns true when the guest wants to sit down and has found a bench to sit on - */ -bool Guest::UpdateWalkingFindBench() -{ - if (!ShouldFindBench()) - return false; - - auto* pathElement = FindBench(NextLoc); - if (pathElement == nullptr) - return false; - - int32_t edges = pathElement->GetEdges() ^ 0xF; - if (edges == 0) - return false; - uint8_t chosen_edge = ScenarioRand() & 0x3; - - while (!(edges & (1 << chosen_edge))) - chosen_edge = (chosen_edge + 1) & 0x3; - - uint8_t free_edge = 3; - - // Check if there is no peep sitting in chosen_edge - for (auto peep : EntityTileList({ x, y })) - { - if (peep->State != PeepState::sitting) - continue; - - if (z != peep->z) - continue; - - if ((peep->Var37 & 0x3) != chosen_edge) - continue; - - free_edge &= ~(1 << ((peep->Var37 & 0x4) >> 2)); - } - - if (!free_edge) - return false; - - free_edge ^= 0x3; - if (!free_edge) - { - if (ScenarioRand() & 0x8000000) - free_edge = 1; - } - - Var37 = ((free_edge & 1) << 2) | chosen_edge; - - SetState(PeepState::sitting); - - SittingSubState = PeepSittingSubState::tryingToSit; - - int32_t benchX = (x & 0xFFE0) + BenchUseOffsets[Var37 & 0x7].x; - int32_t benchY = (y & 0xFFE0) + BenchUseOffsets[Var37 & 0x7].y; - - SetDestination({ benchX, benchY }, 3); - - return true; -} - -static PathElement* FindBin(const CoordsXYZ& loc) -{ - for (auto* pathElement : TileElementsView(loc)) - { - if (pathElement->GetBaseZ() != loc.z) - continue; - - if (!pathElement->HasAddition()) - continue; - - auto* pathAddEntry = pathElement->GetAdditionEntry(); - if (pathAddEntry == nullptr || !(pathAddEntry->flags & PATH_ADDITION_FLAG_IS_BIN)) - continue; - - if (pathElement->IsBroken()) - continue; - - if (pathElement->AdditionIsGhost()) - continue; - - return pathElement; - } - - return nullptr; -} - -bool Guest::UpdateWalkingFindBin() -{ - auto peep = this; - if (!peep->HasEmptyContainer()) - return false; - - if (peep->GetNextIsSurface()) - return false; - - auto* pathElement = FindBin(peep->NextLoc); - if (pathElement == nullptr) - return false; - - int32_t edges = (pathElement->GetEdges()) ^ 0xF; - if (edges == 0) - return false; - - uint8_t chosen_edge = ScenarioRand() & 0x3; - - // Note: Bin quantity is inverted 0 = full, 3 = empty - uint8_t bin_quantities = pathElement->GetAdditionStatus(); - - // Rotate the bin to the correct edge. Makes it easier for next calc. - bin_quantities = Numerics::ror8(Numerics::ror8(bin_quantities, chosen_edge), chosen_edge); - - for (uint8_t free_edge = 4; free_edge != 0; free_edge--) - { - // If not full - if (bin_quantities & 0x3) + vehicle = vehicle->GetCar(CurrentCar); + if (vehicle == nullptr) { - if (edges & (1 << chosen_edge)) + return; + } + + rideEntry = vehicle->GetRideEntry(); + if (rideEntry == nullptr) + { + return; + } + + const auto* vehicle_type = &rideEntry->Cars[vehicle->vehicle_type]; + + if (vehicle_type->flags.has(CarEntryFlag::loadingWaypoints)) + { + UpdateRideLeaveEntranceWaypoints(*ride); + return; + } + + if (vehicle_type->flags.has(CarEntryFlag::useDodgemCarPlacement)) + { + SetDestination(vehicle->GetLocation(), 15); + RideSubState = PeepRideSubState::approachVehicle; + return; + } + + int8_t load_position = 0; + // Safe, in case current seat > number of loading positions + uint16_t numSeatPositions = static_cast(vehicle_type->peep_loading_positions.size()); + if (numSeatPositions != 0) + { + size_t loadPositionIndex = numSeatPositions - 1; + if (CurrentSeat < numSeatPositions) + { + loadPositionIndex = CurrentSeat; + } + load_position = vehicle_type->peep_loading_positions[loadPositionIndex]; + } + + auto destination = GetDestination(); + auto loadPositionWithReversal = (vehicle->flags.has(VehicleFlag::carIsReversed)) ? -load_position : load_position; + switch (vehicle->Orientation / 8) + { + case 0: + destination.x = vehicle->x - loadPositionWithReversal; + break; + case 1: + destination.y = vehicle->y + loadPositionWithReversal; + break; + case 2: + destination.x = vehicle->x + loadPositionWithReversal; + break; + case 3: + destination.y = vehicle->y - loadPositionWithReversal; break; } - chosen_edge = (chosen_edge + 1) & 0x3; - bin_quantities = Numerics::ror8(bin_quantities, 2); - if ((free_edge - 1) == 0) - return false; + SetDestination(destination); + + RideSubState = PeepRideSubState::approachVehicle; } - peep->Var37 = chosen_edge; - - peep->SetState(PeepState::usingBin); - peep->UsingBinSubState = PeepUsingBinSubState::walkingToBin; - - int32_t binX = (peep->x & 0xFFE0) + BinUseOffsets[peep->Var37 & 0x3].x; - int32_t binY = (peep->y & 0xFFE0) + BinUseOffsets[peep->Var37 & 0x3].y; - - peep->SetDestination({ binX, binY }, 3); - - return true; -} - -static PathElement* FindBreakableElement(const CoordsXYZ& loc) -{ - for (auto* pathElement : TileElementsView(loc)) + /** + * + * rct2: 0x0069321D + */ + static void PeepGoToRideExit(Guest& guest, const Ride& ride, int16_t x, int16_t y, int16_t z, uint8_t exit_direction) { - if (pathElement->GetBaseZ() != loc.z) - continue; + z += ride.getRideTypeDescriptor().Heights.PlatformHeight; - if (!pathElement->HasAddition()) - continue; + guest.MoveTo({ x, y, z }); - auto* pathAddEntry = pathElement->GetAdditionEntry(); - if (pathAddEntry == nullptr || !(pathAddEntry->flags & PATH_ADDITION_FLAG_BREAKABLE)) - continue; + Guard::Assert(guest.CurrentRideStation.ToUnderlying() < Limits::kMaxStationsPerRide); + auto exit = ride.getStation(guest.CurrentRideStation).Exit; + x = exit.x; + y = exit.y; + x *= 32; + y *= 32; + x += 16; + y += 16; - if (pathElement->IsBroken()) - continue; + auto [x_shift, y_shift] = [exit_direction]() { + if (exit_direction < DirectionOffsets.size()) + { + return std::pair(DirectionOffsets[exit_direction].x, DirectionOffsets[exit_direction].y); + } + else + { + return std::pair(0, 0); + } + }(); - if (pathElement->AdditionIsGhost()) - continue; + int16_t shift_multiplier = 20; - return pathElement; + const auto* rideEntry = GetRideEntryByIndex(ride.subtype); + if (rideEntry != nullptr) + { + const CarEntry& carEntry = rideEntry->Cars[rideEntry->DefaultCar]; + if (carEntry.flags.hasAny(CarEntryFlag::isMiniGolf, CarEntryFlag::isChairlift, CarEntryFlag::isGoKart)) + { + shift_multiplier = 32; + } + } + + x_shift *= shift_multiplier; + y_shift *= shift_multiplier; + + x -= x_shift; + y -= y_shift; + + guest.SetDestination({ x, y }, 2); + + guest.Orientation = exit_direction * 8; + guest.RideSubState = PeepRideSubState::approachExit; } - return nullptr; -} - -/** - * - * rct2: 0x00690848 - */ -static void GuestUpdateWalkingBreakScenery(Guest& guest) -{ - if (getGameState().cheats.disableVandalism) - return; - - if (!(guest.PeepFlags & PEEP_FLAGS_ANGRY)) + /** + * + * rct2: 0x006920B4 + */ + void Guest::UpdateRideFreeVehicleEnterRide(Ride& ride) { - if (guest.Happiness >= 48) - return; - if (guest.Energy < 85) - return; - if (guest.State != PeepState::walking) + auto ridePrice = RideGetPrice(ride); + if (ridePrice != 0) + { + if ((HasItem(ShopItem::voucher)) && (VoucherType == VOUCHER_TYPE_RIDE_FREE) && (VoucherRideId == CurrentRide)) + { + RemoveItem(ShopItem::voucher); + WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_INVENTORY; + } + else + { + ride.totalProfit = AddClamp(ride.totalProfit, ridePrice); + ride.windowInvalidateFlags.set(RideInvalidateFlag::income); + SpendMoney(PaidOnRides, ridePrice, ExpenditureType::parkRideTickets); + } + } + + RideSubState = PeepRideSubState::leaveEntrance; + uint8_t queueTime = DaysInQueue; + if (queueTime < 253) + queueTime += 3; + + queueTime /= 2; + auto& station = ride.getStation(CurrentRideStation); + if (queueTime != station.QueueTime) + { + station.QueueTime = queueTime; + auto* windowMgr = Ui::GetWindowManager(); + windowMgr->InvalidateByNumber(WindowClass::ride, CurrentRide.ToUnderlying()); + } + + if (PeepFlags & PEEP_FLAGS_TRACKING) + { + auto ft = Formatter(); + FormatNameTo(ft); + ride.formatNameTo(ft); + + StringId msg_string; + if (ride.getRideTypeDescriptor().flags.has(RtdFlag::describeAsInside)) + msg_string = STR_PEEP_TRACKING_PEEP_IS_IN_X; + else + msg_string = STR_PEEP_TRACKING_PEEP_IS_ON_X; + + if (Config::Get().notifications.guestOnRide) + { + News::AddItemToQueue(News::ItemType::peepOnRide, msg_string, Id, ft); + } + } + + const auto& rtd = ride.getRideTypeDescriptor(); + if (rtd.specialType == RtdSpecialType::spiralSlide) + { + SwitchToSpecialSprite(1); + } + + UpdateRideAdvanceThroughEntrance(); + } + + /** + * + * rct2: 0x00691FD4 + */ + static void PeepUpdateRideNoFreeVehicleRejoinQueue(Guest& guest, Ride& ride) + { + TileCoordsXYZD entranceLocation = ride.getStation(guest.CurrentRideStation).Entrance; + + int32_t x = entranceLocation.x * 32; + int32_t y = entranceLocation.y * 32; + if (entranceLocation.direction < DirectionOffsets.size()) + { + x += 16 - DirectionOffsets[entranceLocation.direction].x * 20; + y += 16 - DirectionOffsets[entranceLocation.direction].y * 20; + } + + guest.SetDestination({ x, y }, 2); + guest.SetState(PeepState::queuingFront); + guest.RideSubState = PeepRideSubState::atEntrance; + + ride.queueInsertGuestAtFront(guest.CurrentRideStation, &guest); + } + + /** + * + * rct2: 0x00691E42 + * Note: Before this was the entry + * point for sub state 1 and 3. The + * check has been removed that would + * branch it out to 1 and 3. Now uses + * separate functions. + */ + void Guest::UpdateRideFreeVehicleCheck() + { + auto ride = GetRide(CurrentRide); + if (ride == nullptr) return; - if ((guest.LitterCount & 0xC0) != 0xC0 && (guest.DisgustingCount & 0xC0) != 0xC0) - return; - - if ((ScenarioRand() & 0xFFFF) > 3276) - return; - } - - if (guest.GetNextIsSurface()) - return; - - auto* tileElement = FindBreakableElement(guest.NextLoc); - if (tileElement == nullptr) - return; - - int32_t edges = tileElement->GetEdges(); - if (edges == 0xF) - return; - - // Check if a peep is already sitting on the bench. If so, do not vandalise it. - for (auto* otherGuest : EntityTileList({ guest.x, guest.y })) - { - if ((otherGuest->State != PeepState::sitting) || (guest.z != otherGuest->z)) + if (ride->getRideTypeDescriptor().flags.has(RtdFlag::noVehicles)) { - continue; - } + if (ride->status != RideStatus::open || ride->vehicleChangeTimeout != 0 || (++RejoinQueueTimeout) == 0) + { + PeepUpdateRideNoFreeVehicleRejoinQueue(*this, *ride); + return; + } - return; - } - - for (auto innerPeep : EntityList()) - { - if (innerPeep->AssignedStaffType != StaffType::security || innerPeep->x == kLocationNull) - continue; - - int32_t xDist = abs(innerPeep->x - guest.x); - int32_t yDist = abs(innerPeep->y - guest.y); - - if (std::max(xDist, yDist) < 224) - { - innerPeep->StaffVandalsStopped = AddClamp(innerPeep->StaffVandalsStopped, 1u); - innerPeep->WindowInvalidateFlags |= PEEP_INVALIDATE_STAFF_STATS; + UpdateRideFreeVehicleEnterRide(*ride); return; } - } - tileElement->SetIsBroken(true); - - MapInvalidateTileZoom1({ guest.NextLoc, tileElement->GetBaseZ(), tileElement->GetBaseZ() + 32 }); - - guest.Angriness = 16; -} - -/** - * rct2: 0x0069101A - * - * @return (CF) - */ -static bool PeepShouldWatchRide(TileElement* tileElement) -{ - // Ghosts are purely this-client-side and should not cause any interaction, - // as that may lead to a desync. - if (Network::GetMode() != Network::Mode::none) - { - if (tileElement->IsGhost()) - return false; - } - - auto ride = GetRide(tileElement->AsTrack()->GetRideIndex()); - if (ride == nullptr || !ride->isRide()) - { - return false; - } - - // This is most likely to have peeps watch new rides - if (ride->ratings.isNull()) - { - return true; - } - - if (ride->ratings.excitement >= RideRating::make(4, 70)) - { - return true; - } - - if (ride->ratings.intensity >= RideRating::make(4, 50)) - { - return true; - } - - if (ride->getRideTypeDescriptor().flags.has(RtdFlag::interestingToLookAt)) - { - if ((ScenarioRand() & 0xFFFF) > 0x3333) + auto& gameState = getGameState(); + Vehicle* vehicle = gameState.entities.GetEntity(ride->vehicles[CurrentTrain]); + if (vehicle == nullptr) { - return false; - } - } - else if (ride->getRideTypeDescriptor().flags.has(RtdFlag::slightlyInterestingToLookAt)) - { - if ((ScenarioRand() & 0xFFFF) > 0x1000) - { - return false; - } - } - else - { - return false; - } - - return true; -} - -bool Loc690FD0(Guest& guest, RideId* rideToView, uint8_t* rideSeatToView, TileElement* tileElement) -{ - auto ride = GetRide(tileElement->AsTrack()->GetRideIndex()); - if (ride == nullptr) - return false; - - *rideToView = ride->id; - if (ride->ratings.isNull()) - { - *rideSeatToView = 1; - if (ride->status != RideStatus::open) - { - if (tileElement->GetClearanceZ() > guest.NextLoc.z + (8 * kCoordsZStep)) - { - *rideSeatToView |= (1 << 1); - } - - return true; - } - } - else - { - *rideSeatToView = 0; - if (ride->status == RideStatus::open && !ride->flags.has(RideFlag::brokenDown)) - { - if (tileElement->GetClearanceZ() > guest.NextLoc.z + (8 * kCoordsZStep)) - { - *rideSeatToView = 0x02; - } - - return true; - } - } - - return false; -} - -/** - * - * rct2: 0x00690B99 - * - * @param edge (eax) - * @param peep (esi) - * @param[out] rideToView (cl) - * @param[out] rideSeatToView (ch) - * @return !CF - */ -static bool GuestFindRideToLookAt(Guest& guest, uint8_t edge, RideId* rideToView, uint8_t* rideSeatToView) -{ - auto surfaceElement = MapGetSurfaceElementAt(guest.NextLoc); - TileElement* tileElement = reinterpret_cast(surfaceElement); - if (tileElement == nullptr) - { - return false; - } - - do - { - // Ghosts are purely this-client-side and should not cause any interaction, - // as that may lead to a desync. - if (Network::GetMode() != Network::Mode::none) - { - if (tileElement->IsGhost()) - continue; - } - if (tileElement->GetType() != TileElementType::Wall) - continue; - if (tileElement->GetDirection() != edge) - continue; - auto wallEntry = tileElement->AsWall()->GetEntry(); - if (wallEntry == nullptr || (wallEntry->flags2 & WALL_SCENERY_2_IS_OPAQUE)) - continue; - if (guest.NextLoc.z + (4 * kCoordsZStep) <= tileElement->GetBaseZ()) - continue; - if (guest.NextLoc.z + (1 * kCoordsZStep) >= tileElement->GetClearanceZ()) - continue; - - return false; - } while (!(tileElement++)->IsLastForTile()); - - uint16_t x = guest.NextLoc.x + CoordsDirectionDelta[edge].x; - uint16_t y = guest.NextLoc.y + CoordsDirectionDelta[edge].y; - if (!MapIsLocationValid(CoordsXY{ x, y })) - { - return false; - } - - surfaceElement = MapGetSurfaceElementAt(CoordsXY{ x, y }); - - tileElement = reinterpret_cast(surfaceElement); - if (tileElement == nullptr) - { - return false; - } - - do - { - // Ghosts are purely this-client-side and should not cause any interaction, - // as that may lead to a desync. - if (Network::GetMode() != Network::Mode::none) - { - if (tileElement->IsGhost()) - continue; - } - if (tileElement->GetType() != TileElementType::Wall) - continue; - if (DirectionReverse(tileElement->GetDirection()) != edge) - continue; - auto wallEntry = tileElement->AsWall()->GetEntry(); - if (wallEntry == nullptr || (wallEntry->flags2 & WALL_SCENERY_2_IS_OPAQUE)) - continue; - // TODO: Check whether this shouldn't be <=, as the other loops use. If so, also extract as loop A. - if (guest.NextLoc.z + (4 * kCoordsZStep) >= tileElement->GetBaseZ()) - continue; - if (guest.NextLoc.z + (1 * kCoordsZStep) >= tileElement->GetClearanceZ()) - continue; - - return false; - } while (!(tileElement++)->IsLastForTile()); - - // TODO: Extract loop B - tileElement = reinterpret_cast(surfaceElement); - do - { - // Ghosts are purely this-client-side and should not cause any interaction, - // as that may lead to a desync. - if (Network::GetMode() != Network::Mode::none) - { - if (tileElement->IsGhost()) - continue; - } - - if (tileElement->GetClearanceZ() + (1 * kCoordsZStep) < guest.NextLoc.z) - continue; - if (guest.NextLoc.z + (6 * kCoordsZStep) < tileElement->GetBaseZ()) - continue; - - if (tileElement->GetType() == TileElementType::Track) - { - if (PeepShouldWatchRide(tileElement)) - { - return Loc690FD0(guest, rideToView, rideSeatToView, tileElement); - } - } - - if (tileElement->GetType() == TileElementType::LargeScenery) - { - const auto* sceneryEntry = tileElement->AsLargeScenery()->GetEntry(); - if (sceneryEntry == nullptr || !sceneryEntry->flags.has(LargeSceneryFlag::isPhotogenic)) - { - continue; - } - - *rideSeatToView = 0; - if (tileElement->GetClearanceZ() >= guest.NextLoc.z + (8 * kCoordsZStep)) - { - *rideSeatToView = 0x02; - } - - *rideToView = RideId::GetNull(); - - return true; - } - } while (!(tileElement++)->IsLastForTile()); - - // TODO: Extract loop C - tileElement = reinterpret_cast(surfaceElement); - do - { - // Ghosts are purely this-client-side and should not cause any interaction, - // as that may lead to a desync. - if (Network::GetMode() != Network::Mode::none) - { - if (tileElement->IsGhost()) - continue; - } - if (tileElement->GetClearanceZ() + (1 * kCoordsZStep) < guest.NextLoc.z) - continue; - if (guest.NextLoc.z + (6 * kCoordsZStep) < tileElement->GetBaseZ()) - continue; - if (tileElement->GetType() == TileElementType::Surface) - continue; - if (tileElement->GetType() == TileElementType::Path) - continue; - - if (tileElement->GetType() == TileElementType::Wall) - { - auto wallEntry = tileElement->AsWall()->GetEntry(); - if (wallEntry == nullptr || (wallEntry->flags2 & WALL_SCENERY_2_IS_OPAQUE)) - { - continue; - } - } - - return false; - } while (!(tileElement++)->IsLastForTile()); - - x += CoordsDirectionDelta[edge].x; - y += CoordsDirectionDelta[edge].y; - if (!MapIsLocationValid(CoordsXY{ x, y })) - { - return false; - } - - surfaceElement = MapGetSurfaceElementAt(CoordsXY{ x, y }); - - // TODO: extract loop A - tileElement = reinterpret_cast(surfaceElement); - - if (tileElement == nullptr) - { - return false; - } - - do - { - // Ghosts are purely this-client-side and should not cause any interaction, - // as that may lead to a desync. - if (Network::GetMode() != Network::Mode::none) - { - if (tileElement->IsGhost()) - continue; - } - if (tileElement->GetType() != TileElementType::Wall) - continue; - if (DirectionReverse(tileElement->GetDirection()) != edge) - continue; - auto wallEntry = tileElement->AsWall()->GetEntry(); - if (wallEntry == nullptr || (wallEntry->flags2 & WALL_SCENERY_2_IS_OPAQUE)) - continue; - if (guest.NextLoc.z + (6 * kCoordsZStep) <= tileElement->GetBaseZ()) - continue; - if (guest.NextLoc.z >= tileElement->GetClearanceZ()) - continue; - - return false; - } while (!(tileElement++)->IsLastForTile()); - - // TODO: Extract loop B - tileElement = reinterpret_cast(surfaceElement); - do - { - // Ghosts are purely this-client-side and should not cause any interaction, - // as that may lead to a desync. - if (Network::GetMode() != Network::Mode::none) - { - if (tileElement->IsGhost()) - continue; - } - if (tileElement->GetClearanceZ() + (1 * kCoordsZStep) < guest.NextLoc.z) - continue; - if (guest.NextLoc.z + (8 * kCoordsZStep) < tileElement->GetBaseZ()) - continue; - - if (tileElement->GetType() == TileElementType::Track) - { - if (PeepShouldWatchRide(tileElement)) - { - return Loc690FD0(guest, rideToView, rideSeatToView, tileElement); - } - } - - if (tileElement->GetType() == TileElementType::LargeScenery) - { - auto* sceneryEntry = tileElement->AsLargeScenery()->GetEntry(); - if (!(sceneryEntry == nullptr || sceneryEntry->flags.has(LargeSceneryFlag::isPhotogenic))) - { - continue; - } - - *rideSeatToView = 0; - if (tileElement->GetClearanceZ() >= guest.NextLoc.z + (8 * kCoordsZStep)) - { - *rideSeatToView = 0x02; - } - - *rideToView = RideId::GetNull(); - - return true; - } - } while (!(tileElement++)->IsLastForTile()); - - // TODO: Extract loop C - tileElement = reinterpret_cast(surfaceElement); - do - { - // Ghosts are purely this-client-side and should not cause any interaction, - // as that may lead to a desync. - if (Network::GetMode() != Network::Mode::none) - { - if (tileElement->IsGhost()) - continue; - } - if (tileElement->GetClearanceZ() + (1 * kCoordsZStep) < guest.NextLoc.z) - continue; - if (guest.NextLoc.z + (8 * kCoordsZStep) < tileElement->GetBaseZ()) - continue; - if (tileElement->GetType() == TileElementType::Surface) - continue; - if (tileElement->GetType() == TileElementType::Path) - continue; - - if (tileElement->GetType() == TileElementType::Wall) - { - auto wallEntry = tileElement->AsWall()->GetEntry(); - if (wallEntry == nullptr || (wallEntry->flags2 & WALL_SCENERY_2_IS_OPAQUE)) - { - continue; - } - } - - return false; - } while (!(tileElement++)->IsLastForTile()); - - x += CoordsDirectionDelta[edge].x; - y += CoordsDirectionDelta[edge].y; - if (!MapIsLocationValid(CoordsXY{ x, y })) - { - return false; - } - - surfaceElement = MapGetSurfaceElementAt(CoordsXY{ x, y }); - - // TODO: extract loop A - tileElement = reinterpret_cast(surfaceElement); - if (tileElement == nullptr) - { - return false; - } - - do - { - // Ghosts are purely this-client-side and should not cause any interaction, - // as that may lead to a desync. - if (Network::GetMode() != Network::Mode::none) - { - if (tileElement->IsGhost()) - continue; - } - if (tileElement->GetType() != TileElementType::Wall) - continue; - if (DirectionReverse(tileElement->GetDirection()) != edge) - continue; - auto wallEntry = tileElement->AsWall()->GetEntry(); - if (wallEntry == nullptr || (wallEntry->flags2 & WALL_SCENERY_2_IS_OPAQUE)) - continue; - if (guest.NextLoc.z + (8 * kCoordsZStep) <= tileElement->GetBaseZ()) - continue; - if (guest.NextLoc.z >= tileElement->GetClearanceZ()) - continue; - - return false; - } while (!(tileElement++)->IsLastForTile()); - - // TODO: Extract loop B - tileElement = reinterpret_cast(surfaceElement); - do - { - // Ghosts are purely this-client-side and should not cause any interaction, - // as that may lead to a desync. - if (Network::GetMode() != Network::Mode::none) - { - if (tileElement->IsGhost()) - continue; - } - if (tileElement->GetClearanceZ() + (1 * kCoordsZStep) < guest.NextLoc.z) - continue; - if (guest.NextLoc.z + (10 * kCoordsZStep) < tileElement->GetBaseZ()) - continue; - - if (tileElement->GetType() == TileElementType::Track) - { - if (PeepShouldWatchRide(tileElement)) - { - return Loc690FD0(guest, rideToView, rideSeatToView, tileElement); - } - } - - if (tileElement->GetType() == TileElementType::LargeScenery) - { - const auto* sceneryEntry = tileElement->AsLargeScenery()->GetEntry(); - if (sceneryEntry == nullptr || !sceneryEntry->flags.has(LargeSceneryFlag::isPhotogenic)) - { - continue; - } - - *rideSeatToView = 0; - if (tileElement->GetClearanceZ() >= guest.NextLoc.z + (8 * kCoordsZStep)) - { - *rideSeatToView = 0x02; - } - - *rideToView = RideId::GetNull(); - - return true; - } - } while (!(tileElement++)->IsLastForTile()); - - return false; -} - -/* Part of 0x0069B8CC rct2: 0x0069BC31 */ -void Guest::SetAnimationGroup(PeepAnimationGroup new_sprite_type) -{ - if (AnimationGroup == new_sprite_type) - return; - - AnimationGroup = new_sprite_type; - AnimationImageIdOffset = 0; - WalkingAnimationFrameNum = 0; - - if (IsActionInterruptable()) - Action = PeepActionType::walking; - - auto& objManager = GetContext()->GetObjectManager(); - auto* animObj = objManager.GetLoadedObject(AnimationObjectIndex); - - PeepFlags &= ~PEEP_FLAGS_SLOW_WALK; - if (animObj->IsSlowWalking(new_sprite_type)) - { - PeepFlags |= PEEP_FLAGS_SLOW_WALK; - } - - AnimationType = PeepAnimationType::invalid; - UpdateCurrentAnimationType(); - - if (State == PeepState::sitting) - { - Action = PeepActionType::idle; - NextAnimationType = PeepAnimationType::sittingIdle; - SwitchNextAnimationType(); - } - if (State == PeepState::watching) - { - Action = PeepActionType::idle; - NextAnimationType = PeepAnimationType::watchRide; - SwitchNextAnimationType(); - } -} - -struct ItemPref -{ - ShopItem item; - PeepAnimationGroup sprite_type; -}; - -// clang-format off -static ItemPref item_order_preference[] = { - { ShopItem::iceCream, PeepAnimationGroup::iceCream }, - { ShopItem::chips, PeepAnimationGroup::chips }, - { ShopItem::pizza, PeepAnimationGroup::pizza }, - { ShopItem::burger, PeepAnimationGroup::burger }, - { ShopItem::drink, PeepAnimationGroup::drink }, - { ShopItem::coffee, PeepAnimationGroup::coffee }, - { ShopItem::chicken, PeepAnimationGroup::chicken }, - { ShopItem::lemonade, PeepAnimationGroup::lemonade }, - { ShopItem::candyfloss, PeepAnimationGroup::candyfloss }, - { ShopItem::popcorn, PeepAnimationGroup::popcorn }, - { ShopItem::hotDog, PeepAnimationGroup::hotDog }, - { ShopItem::tentacle, PeepAnimationGroup::tentacle }, - { ShopItem::toffeeApple, PeepAnimationGroup::toffeeApple }, - { ShopItem::doughnut, PeepAnimationGroup::doughnut }, - { ShopItem::pretzel, PeepAnimationGroup::pretzel }, - { ShopItem::cookie, PeepAnimationGroup::pretzel }, - { ShopItem::chocolate, PeepAnimationGroup::coffee }, - { ShopItem::icedTea, PeepAnimationGroup::coffee }, - { ShopItem::funnelCake, PeepAnimationGroup::funnelCake }, - { ShopItem::beefNoodles, PeepAnimationGroup::noodles }, - { ShopItem::friedRiceNoodles, PeepAnimationGroup::noodles }, - { ShopItem::wontonSoup, PeepAnimationGroup::soup }, - { ShopItem::meatballSoup, PeepAnimationGroup::soup }, - { ShopItem::fruitJuice, PeepAnimationGroup::juice }, - { ShopItem::soybeanMilk, PeepAnimationGroup::sujeonggwa }, - { ShopItem::sujeonggwa, PeepAnimationGroup::sujeonggwa }, - { ShopItem::subSandwich, PeepAnimationGroup::sandwich }, - { ShopItem::roastSausage, PeepAnimationGroup::sausage }, - { ShopItem::balloon, PeepAnimationGroup::balloon }, - { ShopItem::hat, PeepAnimationGroup::hat }, - { ShopItem::sunglasses, PeepAnimationGroup::sunglasses }, -}; -// clang-format on - -/** - * - * rct2: 0x0069B8CC - */ -void Guest::UpdateAnimationGroup() -{ - if (AnimationGroup == PeepAnimationGroup::balloon && (ScenarioRand() & 0xFFFF) <= 327) - { - bool isBalloonPopped = false; - if (x != kLocationNull) - { - if ((ScenarioRand() & 0xFFFF) <= 13107) - { - isBalloonPopped = true; - Audio::Play3D(Audio::SoundId::balloonPop, { x, y, z }); - } - Balloon::Create({ x, y, z + 9 }, BalloonColour, isBalloonPopped); - } - RemoveItem(ShopItem::balloon); - WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_INVENTORY; - } - - if (Weather::isPrecipitating() && (HasItem(ShopItem::umbrella)) && x != kLocationNull) - { - CoordsXY loc = { x, y }; - if (MapIsLocationValid(loc.ToTileStart())) - { - TileElement* tileElement = MapGetFirstElementAt(loc); - while (true) - { - if (tileElement == nullptr) - break; - if (z < tileElement->GetBaseZ()) - break; - - if (tileElement->IsLastForTile()) - { - SetAnimationGroup(PeepAnimationGroup::umbrella); - return; - } - tileElement++; - } - } - } - - for (auto& itemPref : item_order_preference) - { - if (HasItem(itemPref.item)) - { - SetAnimationGroup(itemPref.sprite_type); + // TODO: Leave ride on failure goes for all returns on nullptr in this function return; } + vehicle = vehicle->GetCar(CurrentCar); + if (vehicle == nullptr) + return; + + const auto* rideEntry = vehicle->GetRideEntry(); + if (rideEntry == nullptr) + { + return; + } + + if (rideEntry->Cars[0].flags.has(CarEntryFlag::isMiniGolf)) + { + vehicle->miniGolfFlags.unset(MiniGolfFlag::flag5); + + for (size_t i = 0; i < ride->numTrains; ++i) + { + Vehicle* train = gameState.entities.GetEntity(ride->vehicles[i]); + if (train == nullptr) + continue; + + Vehicle* second_vehicle = gameState.entities.GetEntity(train->next_vehicle_on_train); + if (second_vehicle == nullptr) + continue; + + if (second_vehicle->num_peeps == 0) + continue; + + if (second_vehicle->miniGolfFlags.has(MiniGolfFlag::flag5)) + continue; + + return; + } + } + + if (!vehicle->IsUsedInPairs()) + { + UpdateRideFreeVehicleEnterRide(*ride); + return; + } + + if (ride->mode == RideMode::forwardRotation || ride->mode == RideMode::backwardRotation) + { + if (CurrentSeat & 1 || !(vehicle->next_free_seat & 1)) + { + UpdateRideFreeVehicleEnterRide(*ride); + return; + } + } + else + { + uint8_t seat = CurrentSeat | 1; + if (seat < vehicle->next_free_seat) + { + UpdateRideFreeVehicleEnterRide(*ride); + return; + } + } + + Vehicle* currentTrain = gameState.entities.GetEntity(ride->vehicles[CurrentTrain]); + if (currentTrain == nullptr) + { + return; + } + if (ride->status == RideStatus::open && ++RejoinQueueTimeout != 0 + && !currentTrain->flags.has(VehicleFlag::readyToDepart)) + { + return; + } + + if (ride->mode != RideMode::forwardRotation && ride->mode != RideMode::backwardRotation) + { + if (vehicle->next_free_seat - 1 != CurrentSeat) + return; + } + + vehicle->next_free_seat--; + vehicle->peep[CurrentSeat] = EntityId::GetNull(); + + PeepUpdateRideNoFreeVehicleRejoinQueue(*this, *ride); } - if (State == PeepState::watching && StandingFlags & (1 << 1)) + void Guest::UpdateRideApproachVehicle() { - SetAnimationGroup(PeepAnimationGroup::watching); - return; + if (auto loc = UpdateAction(); loc.has_value()) + { + MoveTo({ loc.value(), z }); + return; + } + RideSubState = PeepRideSubState::enterVehicle; } - if (Nausea > 170) + void Guest::UpdateRideEnterVehicle() { - SetAnimationGroup(PeepAnimationGroup::veryNauseous); - return; - } - - if (Nausea > 140) - { - SetAnimationGroup(PeepAnimationGroup::nauseous); - return; - } - - if (Energy <= 64 && Happiness < 128) - { - SetAnimationGroup(PeepAnimationGroup::headDown); - return; - } - - if (Energy <= 80 && Happiness < 128) - { - SetAnimationGroup(PeepAnimationGroup::armsCrossed); - return; - } - - if (Toilet > 220) - { - SetAnimationGroup(PeepAnimationGroup::requireToilet); - return; - } - - SetAnimationGroup(PeepAnimationGroup::normal); -} - -bool Guest::HeadingForRideOrParkExit() const -{ - return (PeepFlags & PEEP_FLAGS_LEAVING_PARK) || !GuestHeadingToRideId.IsNull(); -} - -/** - * rct2: 0x00698342 - * thought.item (eax) - * thought.type (ebx) - * argument_1 (esi & ebx) - * argument_2 (esi+2) - */ -void PeepThoughtSetFormatArgs(const PeepThought* thought, Formatter& ft) -{ - ft.Add(kPeepThoughtIds[EnumValue(thought->type)]); - - PeepThoughtToActionFlag flags = PeepThoughtToActionMap[EnumValue(thought->type)].flags; - if (flags & PEEP_THOUGHT_ACTION_FLAG_RIDE) - { - auto ride = GetRide(thought->rideId); + auto& gameState = getGameState(); + auto* ride = GetRide(CurrentRide); if (ride != nullptr) { - ride->formatNameTo(ft); - } - else - { - ft.Add(kStringIdNone); - } - } - else if (flags & PEEP_THOUGHT_ACTION_FLAG_SHOP_ITEM_SINGULAR) - { - ft.Add(GetShopItemDescriptor(thought->shopItem).Naming.Singular); - } - else if (flags & PEEP_THOUGHT_ACTION_FLAG_SHOP_ITEM_INDEFINITE) - { - ft.Add(GetShopItemDescriptor(thought->shopItem).Naming.Indefinite); - } -} - -void Guest::InsertNewThought(PeepThoughtType thought_type) -{ - InsertNewThought(thought_type, kPeepThoughtItemNone); -} - -void Guest::InsertNewThought(PeepThoughtType thought_type, ShopItem shopItem) -{ - InsertNewThought(thought_type, static_cast(shopItem)); -} - -void Guest::InsertNewThought(PeepThoughtType thought_type, RideId rideId) -{ - InsertNewThought(thought_type, rideId.ToUnderlying()); -} -/** - * - * rct2: 0x699F5A - * al:thoughtType - * ah:thoughtArguments - * esi: peep - */ -void Guest::InsertNewThought(PeepThoughtType thoughtType, uint16_t thoughtArguments) -{ - PeepActionType newAction = PeepThoughtToActionMap[EnumValue(thoughtType)].action; - if (newAction != PeepActionType::walking && IsActionInterruptableSafely()) - { - Action = newAction; - AnimationFrameNum = 0; - AnimationImageIdOffset = 0; - UpdateCurrentAnimationType(); - } - - for (int32_t i = 0; i < kPeepMaxThoughts; ++i) - { - PeepThought* thought = &Thoughts[i]; - // Remove the oldest thought by setting it to NONE. - if (thought->type == PeepThoughtType::None) - break; - - if (thought->type == thoughtType && thought->item == thoughtArguments) - { - // If the thought type has not changed then we need to move - // it to the top of the thought list. This is done by first removing the - // existing thought and placing it at the top. - if (i < kPeepMaxThoughts - 2) + auto* vehicle = gameState.entities.GetEntity(ride->vehicles[CurrentTrain]); + if (vehicle != nullptr) { - memmove(thought, thought + 1, sizeof(PeepThought) * (kPeepMaxThoughts - i - 1)); + vehicle = vehicle->GetCar(CurrentCar); + if (vehicle == nullptr) + { + return; + } + + if (ride->mode != RideMode::forwardRotation && ride->mode != RideMode::backwardRotation) + { + if (CurrentSeat != vehicle->num_peeps) + return; + } + + if (vehicle->IsUsedInPairs()) + { + auto* seatedGuest = gameState.entities.GetEntity(vehicle->peep[CurrentSeat ^ 1]); + if (seatedGuest != nullptr) + { + if (seatedGuest->RideSubState != PeepRideSubState::enterVehicle) + return; + + vehicle->num_peeps++; + ride->curNumCustomers++; + + vehicle->ApplyMass(seatedGuest->Mass); + seatedGuest->MoveTo({ kLocationNull, 0, 0 }); + seatedGuest->SetState(PeepState::onRide); + seatedGuest->GuestTimeOnRide = 0; + seatedGuest->RideSubState = PeepRideSubState::onRide; + seatedGuest->OnEnterRide(*ride); + } + } + + vehicle->num_peeps++; + ride->curNumCustomers++; + + vehicle->ApplyMass(Mass); + vehicle->Invalidate(); + + MoveTo({ kLocationNull, 0, 0 }); + + SetState(PeepState::onRide); + + GuestTimeOnRide = 0; + RideSubState = PeepRideSubState::onRide; + OnEnterRide(*ride); } - break; } } - memmove(&std::get<1>(Thoughts), &std::get<0>(Thoughts), sizeof(PeepThought) * (kPeepMaxThoughts - 1)); - - auto& thought = std::get<0>(Thoughts); - thought.type = thoughtType; - thought.item = thoughtArguments; - thought.freshness = 0; - thought.fresh_timeout = 0; - - WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_THOUGHTS; -} - -// clang-format off -/** rct2: 0x009823A0 */ -static constexpr PeepNauseaTolerance nausea_tolerance_distribution[] = { - PeepNauseaTolerance::None, - PeepNauseaTolerance::Low, PeepNauseaTolerance::Low, - PeepNauseaTolerance::Average, PeepNauseaTolerance::Average, PeepNauseaTolerance::Average, - PeepNauseaTolerance::High, PeepNauseaTolerance::High, PeepNauseaTolerance::High, PeepNauseaTolerance::High, PeepNauseaTolerance::High, PeepNauseaTolerance::High, -}; - -/** rct2: 0x009823BC */ -static constexpr Drawing::Colour kTrouserColours[] = { - Drawing::Colour::black, - Drawing::Colour::grey, - Drawing::Colour::lightBrown, - Drawing::Colour::saturatedBrown, - Drawing::Colour::darkBrown, - Drawing::Colour::salmonPink, - Drawing::Colour::black, - Drawing::Colour::grey, - Drawing::Colour::lightBrown, - Drawing::Colour::saturatedBrown, - Drawing::Colour::darkBrown, - Drawing::Colour::salmonPink, - Drawing::Colour::black, - Drawing::Colour::grey, - Drawing::Colour::lightBrown, - Drawing::Colour::saturatedBrown, - Drawing::Colour::darkBrown, - Drawing::Colour::salmonPink, - Drawing::Colour::darkPurple, - Drawing::Colour::lightPurple, - Drawing::Colour::darkBlue, - Drawing::Colour::saturatedGreen, - Drawing::Colour::saturatedRed, - Drawing::Colour::darkOrange, - Drawing::Colour::bordeauxRed, - Drawing::Colour::armyGreen, - Drawing::Colour::hunterGreen, - Drawing::Colour::deepWater, - Drawing::Colour::umber, -}; - -/** rct2: 0x009823D5 */ -static constexpr Drawing::Colour kTshirtColours[] = { - Drawing::Colour::black, - Drawing::Colour::grey, - Drawing::Colour::lightBrown, - Drawing::Colour::saturatedBrown, - Drawing::Colour::darkBrown, - Drawing::Colour::salmonPink, - Drawing::Colour::black, - Drawing::Colour::grey, - Drawing::Colour::lightBrown, - Drawing::Colour::saturatedBrown, - Drawing::Colour::darkBrown, - Drawing::Colour::salmonPink, - Drawing::Colour::darkPurple, - Drawing::Colour::lightPurple, - Drawing::Colour::darkBlue, - Drawing::Colour::saturatedGreen, - Drawing::Colour::saturatedRed, - Drawing::Colour::darkOrange, - Drawing::Colour::bordeauxRed, - Drawing::Colour::white, - Drawing::Colour::brightPurple, - Drawing::Colour::lightBlue, - Drawing::Colour::darkWater, - Drawing::Colour::darkGreen, - Drawing::Colour::mossGreen, - Drawing::Colour::brightGreen, - Drawing::Colour::oliveGreen, - Drawing::Colour::darkOliveGreen, - Drawing::Colour::yellow, - Drawing::Colour::lightOrange, - Drawing::Colour::brightRed, - Drawing::Colour::darkPink, - Drawing::Colour::brightPink, - Drawing::Colour::armyGreen, - Drawing::Colour::honeyDew, - Drawing::Colour::tan, - Drawing::Colour::maroon, - Drawing::Colour::coralPink, - Drawing::Colour::forestGreen, - Drawing::Colour::chartreuse, - Drawing::Colour::hunterGreen, - Drawing::Colour::celadon, - Drawing::Colour::limeGreen, - Drawing::Colour::sepia, - Drawing::Colour::peach, - Drawing::Colour::periwinkle, - Drawing::Colour::viridian, - Drawing::Colour::seafoamGreen, - Drawing::Colour::violet, - Drawing::Colour::lavender, - Drawing::Colour::pastelOrange, - Drawing::Colour::deepWater, - Drawing::Colour::pastelPink, - Drawing::Colour::umber, - Drawing::Colour::beige, -}; -// clang-format on - -/** - * - * rct2: 0x0069A05D - */ -Guest* Guest::Generate(const CoordsXYZ& coords) -{ - auto& gameState = getGameState(); - if (gameState.entities.GetNumFreeEntities() < 400) - return nullptr; - - Guest* peep = gameState.entities.CreateEntity(); - - peep->AnimationObjectIndex = findPeepAnimationsIndexForType(AnimationPeepType::guest); - peep->AnimationGroup = PeepAnimationGroup::normal; - peep->OutsideOfPark = true; - peep->State = PeepState::falling; - peep->Action = PeepActionType::walking; - peep->SpecialSprite = 0; - peep->AnimationImageIdOffset = 0; - peep->WalkingAnimationFrameNum = 0; - peep->AnimationType = PeepAnimationType::walking; - peep->PeepFlags = 0; - peep->FavouriteRide = RideId::GetNull(); - peep->FavouriteRideRating = 0; - - auto& objManager = GetContext()->GetObjectManager(); - auto* animObj = objManager.GetLoadedObject(peep->AnimationObjectIndex); - - const auto& spriteBounds = animObj->GetSpriteBounds(peep->AnimationGroup, peep->AnimationType); - peep->SpriteData.Width = spriteBounds.spriteWidth; - peep->SpriteData.HeightMin = spriteBounds.spriteHeightNegative; - peep->SpriteData.HeightMax = spriteBounds.spriteHeightPositive; - peep->Orientation = 0; - - peep->MoveTo(coords); - peep->Mass = (ScenarioRand() & 0x1F) + 45; - peep->PathCheckOptimisation = 0; - peep->InteractionRideIndex = RideId::GetNull(); - peep->PreviousRide = RideId::GetNull(); - std::get<0>(peep->Thoughts).type = PeepThoughtType::None; - peep->WindowInvalidateFlags = 0; - - uint8_t intensityHighest = (ScenarioRand() & 0x7) + 3; - uint8_t intensityLowest = std::min(intensityHighest, static_cast(7)) - 3; - - if (intensityHighest >= 7) - intensityHighest = 15; - - /* Check which intensity boxes are enabled - * and apply the appropriate intensity settings. */ - if (gameState.park.flags & PARK_FLAGS_PREF_LESS_INTENSE_RIDES) + /** + * + * rct2: 0x00693028 + */ + void Guest::UpdateRideLeaveVehicle() { - if (gameState.park.flags & PARK_FLAGS_PREF_MORE_INTENSE_RIDES) + auto& gameState = getGameState(); + auto ride = GetRide(CurrentRide); + if (ride == nullptr) + return; + + Vehicle* vehicle = gameState.entities.GetEntity(ride->vehicles[CurrentTrain]); + if (vehicle == nullptr) + return; + + StationIndex ride_station = vehicle->current_station; + vehicle = vehicle->GetCar(CurrentCar); + if (vehicle == nullptr) { - intensityLowest = 0; - intensityHighest = 15; + return; + } + + // Check if ride is NOT Ferris Wheel. + if (ride->mode != RideMode::forwardRotation && ride->mode != RideMode::backwardRotation) + { + if (vehicle->num_peeps - 1 != CurrentSeat) + return; + } + + AnimationImageIdOffset++; + if (AnimationImageIdOffset & 3) + return; + + AnimationImageIdOffset = 0; + + vehicle->num_peeps--; + vehicle->ApplyMass(-Mass); + vehicle->Invalidate(); + + if (ride_station.ToUnderlying() >= Limits::kMaxStationsPerRide) + { + // HACK #5658: Some parks have hacked rides which end up in this state + auto bestStationIndex = RideGetFirstValidStationExit(*ride); + if (bestStationIndex.IsNull()) + { + bestStationIndex = StationIndex::FromUnderlying(0); + } + ride_station = bestStationIndex; + } + CurrentRideStation = ride_station; + const auto* rideEntry = vehicle->GetRideEntry(); + if (rideEntry == nullptr) + { + return; + } + + const auto* carEntry = &rideEntry->Cars[vehicle->vehicle_type]; + + assert(CurrentRideStation.ToUnderlying() < Limits::kMaxStationsPerRide); + auto& station = ride->getStation(CurrentRideStation); + + if (!carEntry->flags.has(CarEntryFlag::loadingWaypoints)) + { + TileCoordsXYZD exitLocation = station.Exit; + CoordsXYZD platformLocation; + platformLocation.z = station.GetBaseZ(); + + platformLocation.direction = DirectionReverse(exitLocation.direction); + + if (!ride->getRideTypeDescriptor().flags.has(RtdFlag::vehicleIsIntegral)) + { + for (; vehicle != nullptr && !vehicle->IsHead(); + vehicle = gameState.entities.GetEntity(vehicle->prev_vehicle_on_ride)) + { + auto trackType = vehicle->GetTrackType(); + if (trackType == TrackElemType::flat || trackType > TrackElemType::middleStation) + continue; + + bool foundStation = false; + for (auto* trackElement : TileElementsView(vehicle->TrackLocation)) + { + if (trackElement->GetBaseZ() != vehicle->TrackLocation.z) + continue; + + if (trackElement->GetStationIndex() != CurrentRideStation) + continue; + + foundStation = true; + break; + } + + if (foundStation) + break; + } + + if (vehicle == nullptr) + { + return; + } + uint8_t shiftMultiplier = 12; + uint8_t specialDirection = platformLocation.direction; + + rideEntry = GetRideEntryByIndex(ride->subtype); + + if (rideEntry != nullptr) + { + carEntry = &rideEntry->Cars[rideEntry->DefaultCar]; + + if (carEntry->flags.has(CarEntryFlag::isGoKart)) + { + shiftMultiplier = 9; + } + + if (carEntry->flags.hasAny(CarEntryFlag::isChairlift, CarEntryFlag::isGoKart)) + { + specialDirection = ((vehicle->Orientation + 3) / 8) + 1; + specialDirection &= 3; + + if (vehicle->TrackSubposition == VehicleTrackSubposition::GoKartsRightLane) + specialDirection = DirectionReverse(specialDirection); + } + } + + auto [xShift, yShift] = [specialDirection]() { + if (specialDirection < DirectionOffsets.size()) + { + return std::pair(DirectionOffsets[specialDirection].x, DirectionOffsets[specialDirection].y); + } + else + { + return std::pair(0, 0); + } + }(); + + platformLocation.x = vehicle->x + xShift * shiftMultiplier; + platformLocation.y = vehicle->y + yShift * shiftMultiplier; + + PeepGoToRideExit( + *this, *ride, platformLocation.x, platformLocation.y, platformLocation.z, platformLocation.direction); + return; + } + + platformLocation.x = vehicle->x + DirectionOffsets[platformLocation.direction].x * 12; + platformLocation.y = vehicle->y + DirectionOffsets[platformLocation.direction].y * 12; + + // This can evaluate to false with buggy custom rides. + if (CurrentSeat < carEntry->peep_loading_positions.size()) + { + int8_t loadPosition = carEntry->peep_loading_positions[CurrentSeat]; + + switch (vehicle->Orientation / 8) + { + case 0: + platformLocation.x -= loadPosition; + break; + case 1: + platformLocation.y += loadPosition; + break; + case 2: + platformLocation.x += loadPosition; + break; + case 3: + platformLocation.y -= loadPosition; + break; + } + } + else + { + LOG_VERBOSE( + "CurrentSeat %d is too large! (Vehicle entry has room for %d.)", CurrentSeat, + carEntry->peep_loading_positions.size()); + } + + platformLocation.z = station.GetBaseZ(); + + PeepGoToRideExit( + *this, *ride, platformLocation.x, platformLocation.y, platformLocation.z, platformLocation.direction); + return; + } + + auto exitLocation = station.Exit.ToCoordsXYZD(); + if (exitLocation.IsNull()) + { + return; + } + + TileElement* trackElement = RideGetStationStartTrackElement(*ride, CurrentRideStation); + + Direction station_direction = (trackElement == nullptr ? 0 : trackElement->GetDirection()); + + vehicle = gameState.entities.GetEntity(ride->vehicles[CurrentTrain]); + if (vehicle == nullptr) + { + return; + } + + const auto& rtd = ride->getRideTypeDescriptor(); + CoordsXYZ waypointLoc = { rtd.GetGuestWaypointLocation(*vehicle, *ride, CurrentRideStation), + exitLocation.z + ride->getRideTypeDescriptor().Heights.PlatformHeight }; + + rideEntry = vehicle->GetRideEntry(); + carEntry = &rideEntry->Cars[vehicle->vehicle_type]; + if (carEntry == nullptr) + return; + + Var37 = ((exitLocation.direction | GetWaypointedSeatLocation(*ride, carEntry, station_direction) * 4) * 4) | 1; + + CoordsXYZ exitWaypointLoc = waypointLoc; + + const auto waypointIndex = Var37 / 4u; + if (waypointIndex < carEntry->peep_loading_waypoints.size()) + { + exitWaypointLoc.x += carEntry->peep_loading_waypoints[waypointIndex][2].x; + exitWaypointLoc.y += carEntry->peep_loading_waypoints[waypointIndex][2].y; + } + + if (ride->getRideTypeDescriptor().specialType == RtdSpecialType::motionSimulator) + exitWaypointLoc.z += 15; + + MoveTo(exitWaypointLoc); + + if (waypointIndex < carEntry->peep_loading_waypoints.size()) + { + waypointLoc.x += carEntry->peep_loading_waypoints[waypointIndex][1].x; + waypointLoc.y += carEntry->peep_loading_waypoints[waypointIndex][1].y; + } + + SetDestination(waypointLoc, 2); + RideSubState = PeepRideSubState::approachExitWaypoints; + } + + /** + * + * rct2: 0x0069376A + */ + void Guest::UpdateRidePrepareForExit() + { + const auto* ride = GetRide(CurrentRide); + if (ride == nullptr || CurrentRideStation.ToUnderlying() >= std::size(ride->getStations())) + return; + + auto exit = ride->getStation(CurrentRideStation).Exit; + auto newDestination = exit.ToCoordsXY().ToTileCentre(); + + auto [xShift, yShift] = [exit]() { + if (exit.direction < DirectionOffsets.size()) + { + return std::pair(DirectionOffsets[exit.direction].x, DirectionOffsets[exit.direction].y); + } + else + { + return std::pair(0, 0); + } + }(); + + int16_t shiftMultiplier = 20; + + const auto* rideEntry = ride->getRideEntry(); + if (rideEntry != nullptr) + { + const auto& carEntry = rideEntry->Cars[rideEntry->DefaultCar]; + if (carEntry.flags.hasAny(CarEntryFlag::isChairlift, CarEntryFlag::isGoKart)) + { + shiftMultiplier = 32; + } + } + + xShift *= shiftMultiplier; + yShift *= shiftMultiplier; + + newDestination.x -= xShift; + newDestination.y -= yShift; + + SetDestination(newDestination, 2); + RideSubState = PeepRideSubState::inExit; + } + + /** + * + * rct2: 0x0069374F + */ + void Guest::UpdateRideApproachExit() + { + if (auto loc = UpdateAction(); loc.has_value()) + { + MoveTo({ loc.value(), z }); + return; + } + + UpdateRidePrepareForExit(); + } + + /** + * + * rct2: 0x0069382E + */ + void Guest::UpdateRideInExit() + { + auto ride = GetRide(CurrentRide); + if (ride == nullptr) + return; + + int16_t xy_distance; + + if (auto loc = UpdateAction(xy_distance); loc.has_value()) + { + if (xy_distance >= 16) + { + int16_t actionZ = ride->getStation(CurrentRideStation).GetBaseZ(); + + actionZ += ride->getRideTypeDescriptor().Heights.PlatformHeight; + MoveTo({ loc.value(), actionZ }); + return; + } + + SwitchToSpecialSprite(0); + MoveTo({ loc.value(), z }); + } + + if (ride->flags.has(RideFlag::onRidePhoto)) + { + ShopItem secondaryItem = ride->getRideTypeDescriptor().PhotoItem; + if (GuestDecideAndBuyItem(*this, *ride, secondaryItem, ride->price[1])) + { + ride->numSecondaryItemsSold = AddClamp(ride->numSecondaryItemsSold, 1u); + } + } + RideSubState = PeepRideSubState::leaveExit; + } +#pragma warning(default : 6011) + + CoordsXY GetGuestWaypointLocationDefault(const Vehicle& vehicle, const Ride& ride, const StationIndex& CurrentRideStation) + { + return ride.getStation(CurrentRideStation).Start.ToTileCentre(); + } + + CoordsXY GetGuestWaypointLocationEnterprise( + const Vehicle& vehicle, const Ride& ride, const StationIndex& CurrentRideStation) + { + return { vehicle.x, vehicle.y }; + } + + /** + * + * rct2: 0x006926AD + */ + void Guest::UpdateRideApproachVehicleWaypoints() + { + auto ride = GetRide(CurrentRide); + if (ride == nullptr) + return; + + int16_t xy_distance; + uint8_t waypoint = Var37 & 3; + + const auto& rtd = ride->getRideTypeDescriptor(); + if (auto loc = UpdateAction(xy_distance); loc.has_value()) + { + rtd.UpdateRideApproachVehicleWaypoints(*this, loc.value(), xy_distance); + return; + } + + if (waypoint == 2) + { + RideSubState = PeepRideSubState::enterVehicle; + return; + } + + waypoint++; + // This is incrementing the actual peep waypoint + Var37++; + + Vehicle* vehicle = getGameState().entities.GetEntity(ride->vehicles[CurrentTrain]); + if (vehicle == nullptr) + { + return; + } + + CoordsXY targetLoc = rtd.GetGuestWaypointLocation(*vehicle, *ride, CurrentRideStation); + + const auto* rideEntry = vehicle->GetRideEntry(); + if (rideEntry == nullptr) + { + return; + } + + const auto& vehicle_type = rideEntry->Cars[vehicle->vehicle_type]; + const auto waypointIndex = Var37 / 4u; + if (waypointIndex < vehicle_type.peep_loading_waypoints.size()) + { + Guard::Assert(waypoint < 3); + targetLoc.x += vehicle_type.peep_loading_waypoints[waypointIndex][waypoint].x; + targetLoc.y += vehicle_type.peep_loading_waypoints[waypointIndex][waypoint].y; + } + + SetDestination(targetLoc); + } + + void UpdateRideApproachVehicleWaypointsMotionSimulator(Guest& guest, const CoordsXY& loc, int16_t& xy_distance) + { + auto ride = GetRide(guest.CurrentRide); + // Motion simulators have steps. This moves the peeps up the steps. + int16_t actionZ = ride->getStation(guest.CurrentRideStation).GetBaseZ() + 2; + + uint8_t waypoint = guest.Var37 & 3; + if (waypoint == 2) + { + xy_distance -= 12; + if (xy_distance < 0) + xy_distance = 0; + + if (xy_distance <= 15) + { + actionZ += 15 - xy_distance; + } + } + guest.MoveTo({ loc, actionZ }); + } + + void UpdateRideApproachVehicleWaypointsDefault(Guest& guest, const CoordsXY& loc, int16_t& xy_distance) + { + guest.MoveTo({ loc, guest.z }); + } + + /** + * + * rct2: 0x0069357D + */ + void Guest::UpdateRideApproachExitWaypoints() + { + auto ride = GetRide(CurrentRide); + if (ride == nullptr) + return; + + int16_t xy_distance; + + if (auto loc = UpdateAction(xy_distance); loc.has_value()) + { + int16_t actionZ; + + if (ride->getRideTypeDescriptor().specialType == RtdSpecialType::motionSimulator) + { + actionZ = ride->getStation(CurrentRideStation).GetBaseZ() + 2; + + if ((Var37 & 3) == 1) + { + if (xy_distance > 15) + xy_distance = 15; + + actionZ += xy_distance; + } + } + else + { + actionZ = z; + } + MoveTo({ loc.value(), actionZ }); + return; + } + + if ((Var37 & 3) != 0) + { + if ((Var37 & 3) == 3) + { + UpdateRidePrepareForExit(); + return; + } + + Var37--; + Vehicle* vehicle = getGameState().entities.GetEntity(ride->vehicles[CurrentTrain]); + if (vehicle == nullptr) + { + return; + } + + const auto* rideEntry = vehicle->GetRideEntry(); + if (rideEntry == nullptr) + return; + + if (vehicle->vehicle_type >= std::size(rideEntry->Cars)) + return; + + const CarEntry& carEntry = rideEntry->Cars[vehicle->vehicle_type]; + + const size_t carPosition = Var37 / 4; + if (carPosition >= carEntry.peep_loading_waypoints.size()) + return; + + const auto waypoint = Var37 & 3; + Guard::Assert(waypoint < 3); + + const auto& rtd = ride->getRideTypeDescriptor(); + + CoordsXY targetLoc = rtd.GetGuestWaypointLocation(*vehicle, *ride, CurrentRideStation); + targetLoc += carEntry.peep_loading_waypoints[carPosition][waypoint]; + SetDestination(targetLoc); + return; + } + + Var37 |= 3; + + auto targetLoc = ride->getStation(CurrentRideStation).Exit.ToCoordsXYZD().ToTileCentre(); + uint8_t exit_direction = DirectionReverse(targetLoc.direction); + + int16_t x_shift = DirectionOffsets[exit_direction].x; + int16_t y_shift = DirectionOffsets[exit_direction].y; + + int16_t shift_multiplier = 20; + + auto rideEntry = GetRideEntryByIndex(ride->subtype); + if (rideEntry != nullptr) + { + auto carEntry = &rideEntry->Cars[rideEntry->DefaultCar]; + if (carEntry->flags.hasAny(CarEntryFlag::isChairlift, CarEntryFlag::isGoKart)) + { + shift_multiplier = 32; + } + } + + x_shift *= shift_multiplier; + y_shift *= shift_multiplier; + + targetLoc.x -= x_shift; + targetLoc.y -= y_shift; + + SetDestination(targetLoc); + } + + /** + * + * rct2: 0x006927B3 + */ + void Guest::UpdateRideApproachSpiralSlide() + { + auto ride = GetRide(CurrentRide); + if (ride == nullptr) + return; + + if (auto loc = UpdateAction(); loc.has_value()) + { + MoveTo({ loc.value(), z }); + return; + } + + uint8_t waypoint = Var37 & 3; + + if (waypoint == 3) + { + SubState = 15; + spiralSlideSubstate = PeepSpiralSlideSubState::goingUp; + spiralSlideGoingUpTimer = 0; + Var37 = (Var37 / 4) & 0xC; + MoveTo({ kLocationNull, y, z }); + return; + } + + [[maybe_unused]] const auto& rtd = ride->getRideTypeDescriptor(); + if (waypoint == 2) + { + bool lastRide = false; + if (ride->status != RideStatus::open) + lastRide = true; + else if (timesSlidDown++ != 0) + { + if (ride->mode == RideMode::singleRidePerAdmission) + lastRide = true; + if (static_cast(timesSlidDown - 1) > (ScenarioRand() & 0xF)) + lastRide = true; + } + + if (lastRide) + { + auto exit = ride->getStation(CurrentRideStation).Exit; + waypoint = 1; + auto directionTemp = exit.direction; + if (exit.direction == kInvalidDirection) + { + directionTemp = 0; + } + Var37 = (directionTemp * 4) | (Var37 & 0x30) | waypoint; + CoordsXY targetLoc = ride->getStation(CurrentRideStation).Start; + + assert(rtd.specialType == RtdSpecialType::spiralSlide); + targetLoc += kSpiralSlideWalkingPath[Var37]; + + SetDestination(targetLoc); + RideSubState = PeepRideSubState::leaveSpiralSlide; + return; + } + } + waypoint++; + // Actually increment the real peep waypoint + Var37++; + + CoordsXY targetLoc = ride->getStation(CurrentRideStation).Start; + + assert(rtd.specialType == RtdSpecialType::spiralSlide); + targetLoc += kSpiralSlideWalkingPath[Var37]; + + SetDestination(targetLoc); + } + + /** rct2: 0x00981F0C, 0x00981F0E */ + static constexpr CoordsXY kSpiralSlideEnd[] = { + { 25, 56 }, + { 56, 7 }, + { 7, -24 }, + { -24, 25 }, + }; + + /** rct2: 0x00981F1C, 0x00981F1E */ + static constexpr CoordsXY kSpiralSlideEndWaypoint[] = { + { 8, 56 }, + { 56, 24 }, + { 24, -24 }, + { -24, 8 }, + }; + + /** + * + * rct2: 0x00692D83 + */ + void Guest::UpdateRideOnSpiralSlide() + { + auto ride = GetRide(CurrentRide); + + if (ride == nullptr) + return; + + const auto& rtd = ride->getRideTypeDescriptor(); + if (rtd.specialType != RtdSpecialType::spiralSlide) + return; + + if ((Var37 & 3) == 0) + { + switch (spiralSlideSubstate) + { + case PeepSpiralSlideSubState::goingUp: + spiralSlideGoingUpTimer++; + if (spiralSlideGoingUpTimer >= kTicksToGoUpSpiralSlide) + spiralSlideSubstate = PeepSpiralSlideSubState::prepareToSlide; + + return; + case PeepSpiralSlideSubState::prepareToSlide: + if (ride->slideInUse || ride->flags.has(RideFlag::brokenDown)) + return; + + ride->slideInUse = 1; + ride->slidePeep = Id; + ride->slidePeepTShirtColour = TshirtColour; + ride->spiralSlideProgress = 0; + spiralSlideSubstate = PeepSpiralSlideSubState::slidingDown; + + return; + case PeepSpiralSlideSubState::finishedSliding: + { + auto newLocation = ride->getStation(CurrentRideStation).Start; + uint8_t dir = (Var37 / 4) & 3; + + // Set the location that the guest walks to go on slide again + auto destination = newLocation + kSpiralSlideEndWaypoint[dir]; + SetDestination(destination); + + // Move the guest sprite to just at the end of the slide + newLocation.x += kSpiralSlideEnd[dir].x; + newLocation.y += kSpiralSlideEnd[dir].y; + + MoveTo({ newLocation, z }); + + Orientation = (Var37 & 0xC) * 2; + + Var37++; + return; + } + case PeepSpiralSlideSubState::slidingDown: // Handled by updateSpiralSlide in Ride.cpp + default: + return; + } + } + + if (auto loc = UpdateAction(); loc.has_value()) + { + MoveTo({ loc.value(), z }); + return; + } + + uint8_t waypoint = 2; + Var37 = (Var37 * 4 & 0x30) + waypoint; + + CoordsXY targetLoc = ride->getStation(CurrentRideStation).Start; + + targetLoc += kSpiralSlideWalkingPath[Var37]; + + SetDestination(targetLoc); + RideSubState = PeepRideSubState::approachSpiralSlide; + } + + /** + * + * rct2: 0x00692C6B + */ + void Guest::UpdateRideLeaveSpiralSlide() + { + // Iterates through the spiral slide waypoints until it reaches + // waypoint 0. Then it readies to leave the ride by the entrance. + if (auto loc = UpdateAction(); loc.has_value()) + { + MoveTo({ loc.value(), z }); + return; + } + + auto ride = GetRide(CurrentRide); + if (ride == nullptr) + return; + + uint8_t waypoint = Var37 & 3; + + if (waypoint != 0) + { + if (waypoint == 3) + { + UpdateRidePrepareForExit(); + return; + } + + waypoint--; + // Actually decrement the peep waypoint + Var37--; + CoordsXY targetLoc = ride->getStation(CurrentRideStation).Start; + + [[maybe_unused]] const auto& rtd = ride->getRideTypeDescriptor(); + assert(rtd.specialType == RtdSpecialType::spiralSlide); + targetLoc += kSpiralSlideWalkingPath[Var37]; + + SetDestination(targetLoc); + return; + } + + // Actually force the final waypoint + Var37 |= 3; + + auto targetLoc = ride->getStation(CurrentRideStation).Exit.ToCoordsXYZD().ToTileCentre(); + + int16_t xShift = DirectionOffsets[DirectionReverse(targetLoc.direction)].x; + int16_t yShift = DirectionOffsets[DirectionReverse(targetLoc.direction)].y; + + int16_t shiftMultiplier = 20; + + xShift *= shiftMultiplier; + yShift *= shiftMultiplier; + + targetLoc.x -= xShift; + targetLoc.y -= yShift; + + SetDestination(targetLoc); + } + + /** rct2: 0x00981FE4 */ + static constexpr uint8_t kMazeGetNewDirectionFromEdge[][4] = { + { 15, 7, 15, 7 }, + { 11, 3, 11, 3 }, + { 7, 15, 7, 15 }, + { 3, 11, 3, 11 }, + }; + + /** rct2: 0x00981FF4 */ + static constexpr uint8_t kMazeCurrentDirectionToOpenHedge[][4] = { + { 1, 2, 14, 0 }, + { 4, 5, 6, 2 }, + { 6, 8, 9, 10 }, + { 14, 10, 12, 13 }, + }; + + /** + * + * rct2: 0x00692A83 + */ + void Guest::UpdateRideMazePathfinding() + { + if (auto loc = UpdateAction(); loc.has_value()) + { + MoveTo({ loc.value(), z }); + return; + } + + auto ride = GetRide(CurrentRide); + if (ride == nullptr) + return; + + if (Var37 == 16) + { + UpdateRidePrepareForExit(); + return; + } + + if (IsActionInterruptable()) + { + if (Energy > 80 && !(PeepFlags & PEEP_FLAGS_SLOW_WALK) && !Weather::isPrecipitating() + && (ScenarioRand() & 0xFFFF) <= 2427) + { + Action = PeepActionType::jump; + AnimationFrameNum = 0; + AnimationImageIdOffset = 0; + UpdateCurrentAnimationType(); + } + } + + auto targetLoc = GetDestination().ToTileStart(); + + auto stationBaseZ = ride->getStation().GetBaseZ(); + + // Find the station track element + auto trackElement = MapGetTrackElementAt({ targetLoc, stationBaseZ }); + if (trackElement == nullptr) + { + return; + } + + uint16_t mazeEntry = trackElement->GetMazeEntry(); + // Var37 is 3, 7, 11 or 15 + uint8_t hedges[4]{ 0xFF, 0xFF, 0xFF, 0xFF }; + uint8_t openCount = 0; + uint8_t mazeReverseLastEdge = DirectionReverse(MazeLastEdge); + for (uint8_t i = 0; i < kNumOrthogonalDirections; ++i) + { + if (!(mazeEntry & (1 << kMazeCurrentDirectionToOpenHedge[Var37 / 4][i])) && i != mazeReverseLastEdge) + { + hedges[openCount++] = i; + } + } + + if (openCount == 0) + { + if ((mazeEntry & (1 << kMazeCurrentDirectionToOpenHedge[Var37 / 4][mazeReverseLastEdge]))) + { + return; + } + hedges[openCount++] = mazeReverseLastEdge; + } + + uint8_t chosenEdge = hedges[ScenarioRand() % openCount]; + assert(chosenEdge != 0xFF); + + targetLoc = GetDestination() + CoordsDirectionDelta[chosenEdge] / 2; + + enum class maze_type + { + invalid, + hedge, + entrance_or_exit + }; + maze_type mazeType = maze_type::invalid; + + auto tileElement = MapGetFirstElementAt(targetLoc); + if (tileElement == nullptr) + return; + do + { + if (stationBaseZ != tileElement->GetBaseZ()) + continue; + + if (tileElement->GetType() == TileElementType::Track) + { + mazeType = maze_type::hedge; + break; + } + + if (tileElement->GetType() == TileElementType::Entrance + && tileElement->AsEntrance()->GetEntranceType() == ENTRANCE_TYPE_RIDE_EXIT) + { + mazeType = maze_type::entrance_or_exit; + break; + } + } while (!(tileElement++)->IsLastForTile()); + + switch (mazeType) + { + case maze_type::invalid: + MazeLastEdge++; + MazeLastEdge &= 3; + return; + case maze_type::hedge: + SetDestination(targetLoc); + Var37 = kMazeGetNewDirectionFromEdge[Var37 / 4][chosenEdge]; + MazeLastEdge = chosenEdge; + break; + case maze_type::entrance_or_exit: + targetLoc = GetDestination(); + if (chosenEdge & 1) + { + targetLoc.x = targetLoc.ToTileCentre().x; + } + else + { + targetLoc.y = targetLoc.ToTileCentre().y; + } + SetDestination(targetLoc); + Var37 = 16; + MazeLastEdge = chosenEdge; + break; + } + + if (auto loc = UpdateAction(); loc.has_value()) + { + MoveTo({ loc.value(), z }); + } + } + + /** + * + * rct2: 0x006938D2 + */ + void Guest::UpdateRideLeaveExit() + { + auto ride = GetRide(CurrentRide); + + if (auto loc = UpdateAction(); loc.has_value()) + { + if (ride != nullptr) + { + MoveTo({ loc.value(), ride->getStation(CurrentRideStation).GetBaseZ() }); + } + return; + } + + if (ride != nullptr) + { + OnExitRide(*ride); + + if (PeepFlags & PEEP_FLAGS_TRACKING) + { + auto ft = Formatter(); + FormatNameTo(ft); + ride->formatNameTo(ft); + + if (Config::Get().notifications.guestLeftRide) + { + News::AddItemToQueue(News::ItemType::peepOnRide, STR_PEEP_TRACKING_LEFT_RIDE_X, Id, ft); + } + } + } + + InteractionRideIndex = RideId::GetNull(); + SetState(PeepState::falling); + + CoordsXY targetLoc = { x, y }; + + // Find the station track element + for (auto* pathElement : TileElementsView(targetLoc)) + { + int16_t height = MapHeightFromSlope(targetLoc, pathElement->GetSlopeDirection(), pathElement->IsSloped()); + height += pathElement->GetBaseZ(); + + int16_t z_diff = z - height; + if (z_diff > 0 || z_diff < -16) + continue; + + MoveTo({ x, y, height }); + return; + } + } + + /** + * + * rct2: 0x0069299C + */ + void Guest::UpdateRideShopApproach() + { + if (auto loc = UpdateAction(); loc.has_value()) + { + MoveTo({ loc.value(), z }); + return; + } + + RideSubState = PeepRideSubState::interactShop; + } + + /** + * + * rct2: 0x006929BB + */ + void Guest::UpdateRideShopInteract() + { + auto ride = GetRide(CurrentRide); + if (ride == nullptr) + return; + + const int16_t tileCentreX = NextLoc.x + 16; + const int16_t tileCentreY = NextLoc.y + 16; + + const auto& rtd = ride->getRideTypeDescriptor(); + if (rtd.specialType == RtdSpecialType::firstAid) + { + if (Nausea <= 35) + { + RideSubState = PeepRideSubState::leaveShop; + + SetDestination({ tileCentreX, tileCentreY }, 3); + HappinessTarget = std::min(HappinessTarget + 30, kPeepMaxHappiness); + Happiness = HappinessTarget; + } + else + { + Nausea--; + NauseaTarget = Nausea; + } + return; + } + + if (Toilet != 0) + { + Toilet--; + return; + } + + // Do not play toilet flush sound on title screen as it's considered loud and annoying + if (gLegacyScene != LegacyScene::titleSequence) + { + Audio::Play3D(Audio::SoundId::toiletFlush, GetLocation()); + } + + RideSubState = PeepRideSubState::leaveShop; + + SetDestination({ tileCentreX, tileCentreY }, 3); + + HappinessTarget = std::min(HappinessTarget + 30, kPeepMaxHappiness); + Happiness = HappinessTarget; + GuestStopPurchaseThought(*this, ride->type); + } + + /** + * + * rct2: 0x00692935 + */ + void Guest::UpdateRideShopLeave() + { + if (auto loc = UpdateAction(); loc.has_value()) + { + const auto curLoc = GetLocation(); + MoveTo({ loc.value(), curLoc.z }); + + const auto newLoc = GetLocation().ToTileStart(); + if (newLoc.x != NextLoc.x) + return; + if (newLoc.y != NextLoc.y) + return; + } + + // #11758 Previously SetState(PeepState::walking) caused Peeps to double-back to exit point of shop + SetState(PeepState::falling); + + auto ride = GetRide(CurrentRide); + if (ride != nullptr) + { + ride->totalCustomers = AddClamp(ride->totalCustomers, 1u); + ride->windowInvalidateFlags.set(RideInvalidateFlag::customers); + ride->updateSatisfaction(Happiness / 64); + } + } + + /* From peep_update */ + static void GuestUpdateThoughts(Guest& guest) + { + // Thoughts must always have a gap of at least + // 220 ticks in age between them. In order to + // allow this when a thought is new it enters + // a holding zone. Before it becomes fresh. + int32_t add_fresh = 1; + int32_t fresh_thought = -1; + for (int32_t i = 0; i < kPeepMaxThoughts; i++) + { + if (guest.Thoughts[i].type == PeepThoughtType::None) + break; + + if (guest.Thoughts[i].freshness == 1) + { + add_fresh = 0; + // If thought is fresh we wait 220 ticks + // before allowing a new thought to become fresh. + if (++guest.Thoughts[i].fresh_timeout >= 220) + { + guest.Thoughts[i].fresh_timeout = 0; + // Thought is no longer fresh + guest.Thoughts[i].freshness++; + add_fresh = 1; + } + } + else if (guest.Thoughts[i].freshness > 1) + { + if (++guest.Thoughts[i].fresh_timeout == 0) + { + // When thought is older than ~6900 ticks remove it + if (++guest.Thoughts[i].freshness >= 28) + { + guest.WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_THOUGHTS; + + // Clear top thought, push others up + if (i < kPeepMaxThoughts - 2) + { + memmove( + &guest.Thoughts[i], &guest.Thoughts[i + 1], sizeof(PeepThought) * (kPeepMaxThoughts - i - 1)); + } + guest.Thoughts[kPeepMaxThoughts - 1].type = PeepThoughtType::None; + } + } + } + else + { + fresh_thought = i; + } + } + // If there are no fresh thoughts + // a previously new thought can become + // fresh. + if (add_fresh && fresh_thought != -1) + { + guest.Thoughts[fresh_thought].freshness = 1; + guest.WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_THOUGHTS; + } + } + + void Guest::Update() + { + if (PeepFlags & PEEP_FLAGS_POSITION_FROZEN) + { + if (!(PeepFlags & PEEP_FLAGS_ANIMATION_FROZEN)) + { + // This is circumventing other logic, so only update every few ticks + if ((getGameState().currentTicks & 3) == 0) + { + if (IsActionWalking()) + UpdateWalkingAnimation(); + else + UpdateActionAnimation(); + Invalidate(); + } + } + return; + } + else if (PeepFlags & PEEP_FLAGS_ANIMATION_FROZEN) + { + // Animation is frozen while position is not. This allows a peep to walk + // around without its sprite being updated, which looks very glitchy. + // We'll just remove the flag and continue as normal, in this case. + PeepFlags &= ~PEEP_FLAGS_ANIMATION_FROZEN; + } + + if (!PreviousRide.IsNull()) + { + if (++PreviousRideTimeOut >= 720) + { + PreviousRide = RideId::GetNull(); + } + } + + GuestUpdateThoughts(*this); + + // Walking speed logic + const auto stepsToTake = GetStepsToTake(); + const auto carryCheck = StepProgress + stepsToTake; + StepProgress = carryCheck; + + if (carryCheck <= 255) + { + UpdateEasterEggInteractions(); } else { - intensityLowest = 0; - intensityHighest = 4; + // Loc68FD2F + switch (State) + { + case PeepState::falling: + UpdateFalling(); + break; + case PeepState::one: + Update1(); + break; + case PeepState::onRide: + // No action + break; + case PeepState::picked: + UpdatePicked(); + break; + case PeepState::queuingFront: + UpdateRide(); + break; + case PeepState::leavingRide: + UpdateRide(); + break; + case PeepState::walking: + UpdateWalking(); + break; + case PeepState::queuing: + UpdateQueuing(); + break; + case PeepState::enteringRide: + UpdateRide(); + break; + case PeepState::sitting: + UpdateSitting(); + break; + case PeepState::enteringPark: + UpdateEnteringPark(); + break; + case PeepState::leavingPark: + UpdateLeavingPark(); + break; + case PeepState::buying: + UpdateBuying(); + break; + case PeepState::watching: + UpdateWatching(); + break; + case PeepState::usingBin: + UpdateUsingBin(); + break; + default: + // TODO reset to default state + assert(false); + break; + } } } - else if (gameState.park.flags & PARK_FLAGS_PREF_MORE_INTENSE_RIDES) + + /** + * + * rct2: 0x691A30 + * Used by entering_ride and queueing_front */ + void Guest::UpdateRide() { - intensityLowest = 9; - intensityHighest = 15; - } + NextFlags &= ~PEEP_NEXT_FLAG_IS_SLOPED; - peep->Intensity = IntensityRange(intensityLowest, intensityHighest); - - uint8_t nauseaTolerance = ScenarioRand() & 0x7; - if (gameState.park.flags & PARK_FLAGS_PREF_MORE_INTENSE_RIDES) - { - nauseaTolerance += 4; - } - - peep->NauseaTolerance = nausea_tolerance_distribution[nauseaTolerance]; - - /* Scenario editor limits initial guest happiness to between 37..253. - * To be on the safe side, assume the value could have been hacked - * to any value 0..255. */ - peep->Happiness = gameState.scenarioOptions.guestInitialHappiness; - /* Assume a default initial happiness of 0 is wrong and set - * to 128 (50%) instead. */ - if (gameState.scenarioOptions.guestInitialHappiness == 0) - peep->Happiness = 128; - /* Initial value will vary by -15..16 */ - int8_t happinessDelta = (ScenarioRand() & 0x1F) - 15; - /* Adjust by the delta, clamping at min=0 and max=255. */ - peep->Happiness = std::clamp(peep->Happiness + happinessDelta, 0, kPeepMaxHappiness); - peep->HappinessTarget = peep->Happiness; - peep->Nausea = 0; - peep->NauseaTarget = 0; - - /* Scenario editor limits initial guest hunger to between 37..253. - * To be on the safe side, assume the value could have been hacked - * to any value 0..255. */ - peep->Hunger = gameState.scenarioOptions.guestInitialHunger; - /* Initial value will vary by -15..16 */ - int8_t hungerDelta = (ScenarioRand() & 0x1F) - 15; - /* Adjust by the delta, clamping at min=0 and max=255. */ - peep->Hunger = std::clamp(peep->Hunger + hungerDelta, 0, kPeepMaxHunger); - - /* Scenario editor limits initial guest thirst to between 37..253. - * To be on the safe side, assume the value could have been hacked - * to any value 0..255. */ - peep->Thirst = gameState.scenarioOptions.guestInitialThirst; - /* Initial value will vary by -15..16 */ - int8_t thirstDelta = (ScenarioRand() & 0x1F) - 15; - /* Adjust by the delta, clamping at min=0 and max=255. */ - peep->Thirst = std::clamp(peep->Thirst + thirstDelta, 0, kPeepMaxThirst); - - peep->Toilet = 0; - peep->TimeToConsume = 0; - - peep->GuestNumRides = 0; - peep->PeepId = gameState.nextGuestNumber++; - peep->Name = nullptr; - - money64 cash = (static_cast(ScenarioRand() & 0x3) * 100) - 100 + gameState.scenarioOptions.guestInitialCash; - if (cash < 0) - cash = 0; - - if (gameState.scenarioOptions.guestInitialCash == 0.00_GBP) - { - cash = 500; - } - - if (gameState.park.flags & PARK_FLAGS_NO_MONEY) - { - cash = 0; - } - - if (gameState.scenarioOptions.guestInitialCash == kMoney64Undefined) - { - cash = 0; - } - - peep->CashInPocket = cash; - peep->CashSpent = 0; - peep->ParkEntryTime = -1; - peep->ResetPathfindGoal(); - peep->RemoveAllItems(); - peep->GuestHeadingToRideId = RideId::GetNull(); - peep->GuestNextInQueue = EntityId::GetNull(); - peep->LitterCount = 0; - peep->DisgustingCount = 0; - peep->VandalismSeen = 0; - peep->PaidToEnter = 0; - peep->PaidOnRides = 0; - peep->PaidOnFood = 0; - peep->PaidOnDrink = 0; - peep->PaidOnSouvenirs = 0; - peep->AmountOfFood = 0; - peep->AmountOfDrinks = 0; - peep->AmountOfSouvenirs = 0; - peep->SurroundingsThoughtTimeout = 0; - peep->Angriness = 0; - peep->TimeLost = 0; - - uint8_t tshirtColour = static_cast(ScenarioRand() % std::size(kTshirtColours)); - peep->TshirtColour = kTshirtColours[tshirtColour]; - - uint8_t trousersColour = static_cast(ScenarioRand() % std::size(kTrouserColours)); - peep->TrousersColour = kTrouserColours[trousersColour]; - - /* Minimum energy is capped at 32 and maximum at 128, so this initialises - * a peep with approx 34%-100% energy. (65 - 32) / (128 - 32) ≈ 34% */ - uint8_t energy = (ScenarioRand() % 64) + 65; - peep->Energy = energy; - peep->EnergyTarget = energy; - - IncrementGuestsHeadingForPark(); - -#ifdef ENABLE_SCRIPTING - auto& hookEngine = GetContext()->GetScriptEngine().GetHookEngine(); - if (hookEngine.HasSubscriptions(Scripting::HookType::guestGeneration)) - { - auto ctx = GetContext()->GetScriptEngine().GetContext(); - - // Create event args object - auto obj = Scripting::DukObject(ctx); - obj.Set("id", peep->Id.ToUnderlying()); - - // Call the subscriptions - auto e = obj.Take(); - hookEngine.Call(Scripting::HookType::guestGeneration, e, true); - } -#endif - - return peep; -} - -enum -{ - PEEP_FACE_OFFSET_ANGRY = 0, - PEEP_FACE_OFFSET_VERY_VERY_SICK, - PEEP_FACE_OFFSET_VERY_SICK, - PEEP_FACE_OFFSET_SICK, - PEEP_FACE_OFFSET_VERY_TIRED, - PEEP_FACE_OFFSET_TIRED, - PEEP_FACE_OFFSET_VERY_VERY_UNHAPPY, - PEEP_FACE_OFFSET_VERY_UNHAPPY, - PEEP_FACE_OFFSET_UNHAPPY, - PEEP_FACE_OFFSET_NORMAL, - PEEP_FACE_OFFSET_HAPPY, - PEEP_FACE_OFFSET_VERY_HAPPY, - PEEP_FACE_OFFSET_VERY_VERY_HAPPY, -}; - -static constexpr int32_t kFaceSpriteSmall[] = { - SPR_PEEP_SMALL_FACE_ANGRY, - SPR_PEEP_SMALL_FACE_VERY_VERY_SICK, - SPR_PEEP_SMALL_FACE_VERY_SICK, - SPR_PEEP_SMALL_FACE_SICK, - SPR_PEEP_SMALL_FACE_VERY_TIRED, - SPR_PEEP_SMALL_FACE_TIRED, - SPR_PEEP_SMALL_FACE_VERY_VERY_UNHAPPY, - SPR_PEEP_SMALL_FACE_VERY_UNHAPPY, - SPR_PEEP_SMALL_FACE_UNHAPPY, - SPR_PEEP_SMALL_FACE_NORMAL, - SPR_PEEP_SMALL_FACE_HAPPY, - SPR_PEEP_SMALL_FACE_VERY_HAPPY, - SPR_PEEP_SMALL_FACE_VERY_VERY_HAPPY, -}; - -static constexpr int32_t kFaceSpriteLarge[] = { - SPR_PEEP_LARGE_FACE_ANGRY_0, - SPR_PEEP_LARGE_FACE_VERY_VERY_SICK_0, - SPR_PEEP_LARGE_FACE_VERY_SICK_0, - SPR_PEEP_LARGE_FACE_SICK, - SPR_PEEP_LARGE_FACE_VERY_TIRED, - SPR_PEEP_LARGE_FACE_TIRED, - SPR_PEEP_LARGE_FACE_VERY_VERY_UNHAPPY, - SPR_PEEP_LARGE_FACE_VERY_UNHAPPY, - SPR_PEEP_LARGE_FACE_UNHAPPY, - SPR_PEEP_LARGE_FACE_NORMAL, - SPR_PEEP_LARGE_FACE_HAPPY, - SPR_PEEP_LARGE_FACE_VERY_HAPPY, - SPR_PEEP_LARGE_FACE_VERY_VERY_HAPPY, -}; - -static int32_t GetFaceSpriteOffset(Guest* peep) -{ - // ANGRY - if (peep->Angriness > 0) - return PEEP_FACE_OFFSET_ANGRY; - - // VERY_VERY_SICK - if (peep->Nausea > 200) - return PEEP_FACE_OFFSET_VERY_VERY_SICK; - - // VERY_SICK - if (peep->Nausea > 170) - return PEEP_FACE_OFFSET_VERY_SICK; - - // SICK - if (peep->Nausea > 140) - return PEEP_FACE_OFFSET_SICK; - - // VERY_TIRED - if (peep->Energy < 46) - return PEEP_FACE_OFFSET_VERY_TIRED; - - // TIRED - if (peep->Energy < 70) - return PEEP_FACE_OFFSET_TIRED; - - int32_t offset = PEEP_FACE_OFFSET_VERY_VERY_UNHAPPY; - // There are 7 different happiness based faces - for (int32_t i = 37; peep->Happiness >= i; i += 37) - { - offset++; - } - - return offset; -} - -/** - * Function split into large and small sprite - * rct2: 0x00698721 - */ -int32_t GetPeepFaceSpriteSmall(Guest* peep) -{ - return kFaceSpriteSmall[GetFaceSpriteOffset(peep)]; -} - -/** - * Function split into large and small sprite - * rct2: 0x00698721 - */ -int32_t GetPeepFaceSpriteLarge(Guest* peep) -{ - return kFaceSpriteLarge[GetFaceSpriteOffset(peep)]; -} - -/** - * - * rct2: 0x00693CBB - */ -bool Guest::UpdateQueuePosition(PeepActionType previous_action) -{ - TimeInQueue = AddClamp(TimeInQueue, 1); - - auto* guestNext = getGameState().entities.GetEntity(GuestNextInQueue); - if (guestNext == nullptr) - { - return false; - } - - int16_t x_diff = abs(guestNext->x - x); - int16_t y_diff = abs(guestNext->y - y); - int16_t z_diff = abs(guestNext->z - z); - - if (z_diff > 10) - return false; - - if (x_diff < y_diff) - { - int16_t temp_x = x_diff; - x_diff = y_diff; - y_diff = temp_x; - } - - x_diff += y_diff / 2; - if (x_diff > 7) - { - if (x_diff > 13) + switch (RideSubState) { - if ((x & 0xFFE0) != (guestNext->x & 0xFFE0) || (y & 0xFFE0) != (guestNext->y & 0xFFE0)) + case PeepRideSubState::atEntrance: + UpdateRideAtEntrance(); + break; + case PeepRideSubState::inEntrance: + UpdateRideAdvanceThroughEntrance(); + break; + case PeepRideSubState::freeVehicleCheck: + UpdateRideFreeVehicleCheck(); + break; + case PeepRideSubState::leaveEntrance: + UpdateRideAdvanceThroughEntrance(); + break; + case PeepRideSubState::approachVehicle: + UpdateRideApproachVehicle(); + break; + case PeepRideSubState::enterVehicle: + UpdateRideEnterVehicle(); + break; + case PeepRideSubState::onRide: + // No action, on ride. + break; + case PeepRideSubState::leaveVehicle: + UpdateRideLeaveVehicle(); + break; + case PeepRideSubState::approachExit: + UpdateRideApproachExit(); + break; + case PeepRideSubState::inExit: + UpdateRideInExit(); + break; + case PeepRideSubState::approachVehicleWaypoints: + UpdateRideApproachVehicleWaypoints(); + break; + case PeepRideSubState::approachExitWaypoints: + UpdateRideApproachExitWaypoints(); + break; + case PeepRideSubState::approachSpiralSlide: + UpdateRideApproachSpiralSlide(); + break; + case PeepRideSubState::onSpiralSlide: + UpdateRideOnSpiralSlide(); + break; + case PeepRideSubState::leaveSpiralSlide: + UpdateRideLeaveSpiralSlide(); + break; + case PeepRideSubState::mazePathfinding: + UpdateRideMazePathfinding(); + break; + case PeepRideSubState::leaveExit: + UpdateRideLeaveExit(); + break; + case PeepRideSubState::approachShop: + UpdateRideShopApproach(); + break; + case PeepRideSubState::interactShop: + UpdateRideShopInteract(); + break; + case PeepRideSubState::leaveShop: + UpdateRideShopLeave(); + break; + default: + // Invalid peep sub-state + assert(false); + break; + } + } + + /** + * + * rct2: 0x0069030A + */ + void Guest::UpdateWalking() + { + if (!CheckForPath()) + return; + + const auto currentTicks = getGameState().currentTicks; + + if (IsActionInterruptableSafely()) + { + PeepActionType NewAction = Action; + + if (PeepFlags & PEEP_FLAGS_WAVING && (0xFFFF & ScenarioRand()) < 936) + NewAction = PeepActionType::wave2; + else if (PeepFlags & PEEP_FLAGS_PHOTO && (0xFFFF & ScenarioRand()) < 936) + NewAction = PeepActionType::takePhoto; + else if (PeepFlags & PEEP_FLAGS_PAINTING && (0xFFFF & ScenarioRand()) < 936) + NewAction = PeepActionType::drawPicture; + + if (NewAction != Action) + { + Action = NewAction; + AnimationFrameNum = 0; + AnimationImageIdOffset = 0; + UpdateCurrentAnimationType(); + } + } + + if (PeepFlags & PEEP_FLAGS_LITTER) + { + if (!GetNextIsSurface()) + { + if ((0xFFFF & ScenarioRand()) <= 4096) + { + static constexpr Litter::Type litter_types[] = { + Litter::Type::emptyCan, + Litter::Type::rubbish, + Litter::Type::burgerBox, + Litter::Type::emptyCup, + }; + auto litterType = litter_types[ScenarioRand() & 0x3]; + const auto loc = GetLocation(); + int32_t litterX = loc.x + (ScenarioRand() & 0x7) - 3; + int32_t litterY = loc.y + (ScenarioRand() & 0x7) - 3; + Direction litterDirection = (ScenarioRand() & 0x3); + + Litter::Create({ litterX, litterY, loc.z, litterDirection }, litterType); + } + } + } + else if (HasEmptyContainer()) + { + if ((!GetNextIsSurface()) && (static_cast(Id.ToUnderlying() & 0x1FF) == (currentTicks & 0x1FF)) + && ((0xFFFF & ScenarioRand()) <= 4096)) + { + int32_t container = Numerics::bitScanForward(GetEmptyContainerFlags()); + auto litterType = Litter::Type::vomit; + + if (container != -1) + { + auto item = static_cast(container); + RemoveItem(item); + litterType = Litter::Type(GetShopItemDescriptor(item).Type); + } + + WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_INVENTORY; + UpdateAnimationGroup(); + + const auto loc = GetLocation(); + int32_t litterX = loc.x + (ScenarioRand() & 0x7) - 3; + int32_t litterY = loc.y + (ScenarioRand() & 0x7) - 3; + Direction litterDirection = (ScenarioRand() & 0x3); + + Litter::Create({ litterX, litterY, loc.z, litterDirection }, litterType); + } + } + + if (ShouldWaitForLevelCrossing()) + { + // Wait for vehicle to pass + UpdateWaitingAtCrossing(); + + return; + } + + const auto [pathingResult, _] = PerformNextAction(); + if (!(pathingResult & PATHING_DESTINATION_REACHED)) + return; + + if (GetNextIsSurface()) + { + auto surfaceElement = MapGetSurfaceElementAt(NextLoc); + + if (surfaceElement != nullptr) + { + int32_t water_height = surfaceElement->GetWaterHeight(); + if (water_height > 0) + { + MoveTo({ x, y, water_height }); + SetState(PeepState::falling); + return; + } + } + } + + CheckIfLost(); + CheckCantFindRide(); + CheckCantFindExit(); + + if (UpdateWalkingFindBench()) + return; + + if (UpdateWalkingFindBin()) + return; + + GuestUpdateWalkingBreakScenery(*this); + + if (State != PeepState::walking) + return; + + if (PeepFlags & PEEP_FLAGS_LEAVING_PARK) + return; + + if (Nausea > 140) + return; + + if (Happiness < 120) + return; + + if (Toilet > 140) + return; + + uint16_t chance = HasFoodOrDrink() ? 13107 : 2849; + + if ((ScenarioRand() & 0xFFFF) > chance) + return; + + if (GetNextIsSurface() || GetNextIsSloped()) + return; + + TileElement* tileElement = MapGetFirstElementAt(NextLoc); + if (tileElement == nullptr) + return; + + for (;; tileElement++) + { + if (tileElement->GetType() == TileElementType::Path) + { + if (NextLoc.z == tileElement->GetBaseZ()) + break; + } + if (tileElement->IsLastForTile()) + { + return; + } + } + + int32_t positions_free = 15; + + if (tileElement->AsPath()->HasAddition()) + { + if (!tileElement->AsPath()->AdditionIsGhost()) + { + auto* pathAddEntry = tileElement->AsPath()->GetAdditionEntry(); + if (pathAddEntry == nullptr) + { + return; + } + + if (!(pathAddEntry->flags & PATH_ADDITION_FLAG_IS_BENCH)) + positions_free = 9; + } + } + + int32_t edges = (tileElement->AsPath()->GetEdges()) ^ 0xF; + if (edges == 0) + return; + + uint8_t chosen_edge = ScenarioRand() & 0x3; + + while (!(edges & (1 << chosen_edge))) + chosen_edge = (chosen_edge + 1) & 3; + + RideId ride_to_view; + uint8_t ride_seat_to_view; + if (IsOnLevelCrossing() || !GuestFindRideToLookAt(*this, chosen_edge, &ride_to_view, &ride_seat_to_view)) + return; + + // Check if there is a peep watching (and if there is place for us) + for (auto peep : EntityTileList({ x, y })) + { + if (peep->State != PeepState::watching) + continue; + + if (z != peep->z) + continue; + + if ((peep->Var37 & 0x3) != chosen_edge) + continue; + + positions_free &= ~(1 << ((peep->Var37 & 0x1C) >> 2)); + } + + if (!positions_free) + return; + + uint8_t chosen_position = ScenarioRand() & 0x3; + + while (!(positions_free & (1 << chosen_position))) + chosen_position = (chosen_position + 1) & 3; + + CurrentRide = ride_to_view; + CurrentSeat = ride_seat_to_view; + Var37 = chosen_edge | (chosen_position << 2); + + SetState(PeepState::watching); + SubState = 0; + + int32_t destX = (x & 0xFFE0) + kWatchingPositionOffsets[Var37 & 0x1F].x; + int32_t destY = (y & 0xFFE0) + kWatchingPositionOffsets[Var37 & 0x1F].y; + + SetDestination({ destX, destY }, 3); + + if (CurrentSeat & 1) + { + InsertNewThought(PeepThoughtType::NewRide); + } + if (CurrentRide.IsNull()) + { + InsertNewThought(PeepThoughtType::Scenery); + } + } + + /** + * + * rct2: 0x69185D + */ + void Guest::UpdateQueuing() + { + if (!CheckForPath()) + { + RemoveFromQueue(); + return; + } + auto ride = GetRide(CurrentRide); + if (ride == nullptr || ride->status != RideStatus::open) + { + RemoveFromQueue(); + SetState(PeepState::one); + return; + } + + // If not in the queue then at front of queue + if (RideSubState != PeepRideSubState::inQueue) + { + bool is_front = true; + // Fix #4819: Occasionally the peep->GuestNextInQueue is incorrectly set + // to prevent this from causing the peeps to enter a loop + // first check if the next in queue is actually nearby + // if they are not then it's safe to assume that this is + // the front of the queue. + Peep* nextGuest = getGameState().entities.GetEntity(GuestNextInQueue); + if (nextGuest != nullptr) + { + if (abs(nextGuest->x - x) < 32 && abs(nextGuest->y - y) < 32) + { + is_front = false; + } + } + + if (is_front) + { + // Happens every time peep goes onto ride. + DestinationTolerance = 0; + SetState(PeepState::queuingFront); + RideSubState = PeepRideSubState::atEntrance; + } + + return; + } + + PerformNextAction(); + if (!IsActionInterruptable()) + return; + if (AnimationGroup == PeepAnimationGroup::normal) + { + if (TimeInQueue >= 2000 && (0xFFFF & ScenarioRand()) <= 119) + { + // Eat Food/Look at watch + Action = PeepActionType::eatFood; + AnimationFrameNum = 0; + AnimationImageIdOffset = 0; + UpdateCurrentAnimationType(); + } + if (TimeInQueue >= 3500 && (0xFFFF & ScenarioRand()) <= 93) + { + // Create the I have been waiting in line ages thought + InsertNewThought(PeepThoughtType::QueuingAges, CurrentRide); + } + } + else + { + if (!(TimeInQueue & 0x3F) && IsActionIdle() && NextAnimationType == PeepAnimationType::watchRide) + { + switch (AnimationGroup) + { + case PeepAnimationGroup::iceCream: + case PeepAnimationGroup::chips: + case PeepAnimationGroup::burger: + case PeepAnimationGroup::drink: + case PeepAnimationGroup::candyfloss: + case PeepAnimationGroup::pizza: + case PeepAnimationGroup::popcorn: + case PeepAnimationGroup::hotDog: + case PeepAnimationGroup::tentacle: + case PeepAnimationGroup::toffeeApple: + case PeepAnimationGroup::doughnut: + case PeepAnimationGroup::coffee: + case PeepAnimationGroup::chicken: + case PeepAnimationGroup::lemonade: + case PeepAnimationGroup::pretzel: + case PeepAnimationGroup::sujeonggwa: + case PeepAnimationGroup::juice: + case PeepAnimationGroup::funnelCake: + case PeepAnimationGroup::noodles: + case PeepAnimationGroup::sausage: + case PeepAnimationGroup::soup: + case PeepAnimationGroup::sandwich: + // Eat food + Action = PeepActionType::eatFood; + AnimationFrameNum = 0; + AnimationImageIdOffset = 0; + UpdateCurrentAnimationType(); + break; + default: + break; + } + } + } + if (TimeInQueue < 4300) + return; + + if (Happiness <= 65 && (0xFFFF & ScenarioRand()) < 2184) + { + // Give up queueing for the ride + Orientation ^= (1 << 4); + Invalidate(); + RemoveFromQueue(); + SetState(PeepState::one); + } + } + + /** + * rct2: 0x691451 + */ + void Guest::UpdateEnteringPark() + { + if (Var37 != 1) + { + const auto [pathingResult, _] = PerformNextAction(); + if ((pathingResult & PATHING_OUTSIDE_PARK)) + { + DecrementGuestsHeadingForPark(); + PeepEntityRemove(this); + } + return; + } + if (auto loc = UpdateAction(); loc.has_value()) + { + MoveTo({ loc.value(), z }); + return; + } + SetState(PeepState::falling); + + OutsideOfPark = false; + ParkEntryTime = getGameState().currentTicks; + IncrementGuestsInPark(); + DecrementGuestsHeadingForPark(); + auto intent = Intent(INTENT_ACTION_UPDATE_GUEST_COUNT); + ContextBroadcastIntent(&intent); + } + + /** + * + * rct2: 0x6914CD + */ + void Guest::UpdateLeavingPark() + { + if (Var37 != 0) + { + const auto [pathingResult, _] = PerformNextAction(); + if (!(pathingResult & PATHING_OUTSIDE_PARK)) + return; + PeepEntityRemove(this); + return; + } + + if (auto loc = UpdateAction(); loc.has_value()) + { + MoveTo({ loc.value(), z }); + return; + } + + OutsideOfPark = true; + DestinationTolerance = 5; + DecrementGuestsInPark(); + auto intent = Intent(INTENT_ACTION_UPDATE_GUEST_COUNT); + ContextBroadcastIntent(&intent); + Var37 = 1; + + auto* windowMgr = Ui::GetWindowManager(); + windowMgr->InvalidateByClass(WindowClass::guestList); + + const auto [pathingResult, _] = PerformNextAction(); + if (!(pathingResult & PATHING_OUTSIDE_PARK)) + return; + Remove(); + } + + /** + * + * rct2: 0x6916D6 + */ + void Guest::UpdateWatching() + { + if (SubState == 0) + { + if (!CheckForPath()) + return; + + const auto [pathingResult, _] = PerformNextAction(); + if (!(pathingResult & PATHING_DESTINATION_REACHED)) + return; + + SetDestination(GetLocation()); + + Orientation = (Var37 & 3) * 8; + + Action = PeepActionType::idle; + NextAnimationType = PeepAnimationType::watchRide; + + SwitchNextAnimationType(); + + SubState++; + + TimeToStand = std::clamp(((129 - Energy) * 16 + 50) / 2, 0, 255); + UpdateAnimationGroup(); + } + else if (SubState == 1) + { + if (!IsActionInterruptable()) + { + // 6917F6 + UpdateAction(); + Invalidate(); + if (!IsActionWalking()) + return; + Action = PeepActionType::idle; + } + else + { + if (HasFoodOrDrink()) + { + if ((ScenarioRand() & 0xFFFF) <= 1310) + { + Action = PeepActionType::eatFood; + AnimationFrameNum = 0; + AnimationImageIdOffset = 0; + UpdateCurrentAnimationType(); + return; + } + } + + if ((ScenarioRand() & 0xFFFF) <= 655) + { + Action = PeepActionType::takePhoto; + AnimationFrameNum = 0; + AnimationImageIdOffset = 0; + UpdateCurrentAnimationType(); + return; + } + + if ((StandingFlags & 1)) + { + if ((ScenarioRand() & 0xFFFF) <= 655) + { + Action = PeepActionType::wave; + AnimationFrameNum = 0; + AnimationImageIdOffset = 0; + UpdateCurrentAnimationType(); + return; + } + } + } + + StandingFlags ^= (1 << 7); + if (!(StandingFlags & (1 << 7))) + return; + + TimeToStand--; + if (TimeToStand != 0) + return; + + SetState(PeepState::walking); + UpdateAnimationGroup(); + // Send peep to the centre of current tile. + + auto destination = GetLocation().ToTileCentre(); + SetDestination(destination, 5); + UpdateCurrentAnimationType(); + } + } + + /** + * + * rct2: 0x00691089 + */ + void Guest::UpdateUsingBin() + { + switch (UsingBinSubState) + { + case PeepUsingBinSubState::walkingToBin: + { + if (!CheckForPath()) + return; + + const auto [pathingResult, _] = PerformNextAction(); + if (pathingResult & PATHING_DESTINATION_REACHED) + { + UsingBinSubState = PeepUsingBinSubState::goingBack; + } + break; + } + case PeepUsingBinSubState::goingBack: + { + if (!IsActionWalking()) + { + UpdateAction(); + Invalidate(); + return; + } + + PathElement* foundElement = nullptr; + for (auto* pathElement : TileElementsView(NextLoc)) + { + if (pathElement->GetBaseZ() != NextLoc.z) + continue; + + if (!pathElement->HasAddition()) + break; + + auto* pathAddEntry = pathElement->GetAdditionEntry(); + if (!(pathAddEntry->flags & PATH_ADDITION_FLAG_IS_BIN)) + break; + + if (pathElement->IsBroken()) + break; + + if (pathElement->AdditionIsGhost()) + break; + + foundElement = pathElement; + break; + } + + if (foundElement == nullptr) + { + StateReset(); + return; + } + + // Bin selection is one of 4 corners + uint8_t selectedBin = Var37 * 2; + + // This counts down 2 = No rubbish, 0 = full + uint8_t spaceLeftInBin = 0x3 & (foundElement->GetAdditionStatus() >> selectedBin); + uint64_t emptyContainers = GetEmptyContainerFlags(); + + for (uint8_t curContainer = 0; curContainer < 64; curContainer++) + { + if (!(emptyContainers & (1uLL << curContainer))) + continue; + + auto item = ShopItem(curContainer); + if (spaceLeftInBin != 0) + { + // OpenRCT2 modification: This previously used + // the tick count as a simple random function + // switched to scenario_rand as it is more reliable + if ((ScenarioRand() & 7) == 0) + spaceLeftInBin--; + RemoveItem(item); + WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_INVENTORY; + UpdateAnimationGroup(); + continue; + } + + auto litterType = Litter::Type(GetShopItemDescriptor(item).Type); + + int32_t litterX = x + (ScenarioRand() & 7) - 3; + int32_t litterY = y + (ScenarioRand() & 7) - 3; + + Litter::Create({ litterX, litterY, z, static_cast(ScenarioRand() & 3) }, litterType); + RemoveItem(item); + WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_INVENTORY; + + UpdateAnimationGroup(); + } + + uint8_t additionStatus = foundElement->GetAdditionStatus(); + // Place new amount in bin by first clearing the value + additionStatus &= ~(3 << selectedBin); + // Then placing the new value. + additionStatus |= spaceLeftInBin << selectedBin; + foundElement->SetAdditionStatus(additionStatus); + + MapInvalidateTileZoom0({ NextLoc, foundElement->GetBaseZ(), foundElement->GetClearanceZ() }); + StateReset(); + break; + } + default: + Guard::Assert(false, "Invalid sub state"); + break; + } + } + + /* Simplifies 0x690582. Returns true if should find bench*/ + bool Guest::ShouldFindBench() + { + if (PeepFlags & PEEP_FLAGS_LEAVING_PARK) + { + return false; + } + + if (HasFoodOrDrink()) + { + if (Hunger < 128 || Happiness < 128) + { + if (!GetNextIsSurface() && !GetNextIsSloped()) + { + return true; + } + } + } + + if (Nausea <= 170 && Energy > 50) + { + return false; + } + + return !GetNextIsSurface() && !GetNextIsSloped(); + } + + static PathElement* FindBench(const CoordsXYZ& loc) + { + for (auto* pathElement : TileElementsView(loc)) + { + if (pathElement->GetBaseZ() != loc.z) + continue; + + if (!pathElement->HasAddition()) + continue; + + auto* pathAddEntry = pathElement->GetAdditionEntry(); + if (pathAddEntry == nullptr || !(pathAddEntry->flags & PATH_ADDITION_FLAG_IS_BENCH)) + continue; + + if (pathElement->IsBroken()) + continue; + + if (pathElement->AdditionIsGhost()) + continue; + + return pathElement; + } + + return nullptr; + } + + /** + * + * rct2: 0x00690582 + * Returns true when the guest wants to sit down and has found a bench to sit on + */ + bool Guest::UpdateWalkingFindBench() + { + if (!ShouldFindBench()) + return false; + + auto* pathElement = FindBench(NextLoc); + if (pathElement == nullptr) + return false; + + int32_t edges = pathElement->GetEdges() ^ 0xF; + if (edges == 0) + return false; + uint8_t chosen_edge = ScenarioRand() & 0x3; + + while (!(edges & (1 << chosen_edge))) + chosen_edge = (chosen_edge + 1) & 0x3; + + uint8_t free_edge = 3; + + // Check if there is no peep sitting in chosen_edge + for (auto peep : EntityTileList({ x, y })) + { + if (peep->State != PeepState::sitting) + continue; + + if (z != peep->z) + continue; + + if ((peep->Var37 & 0x3) != chosen_edge) + continue; + + free_edge &= ~(1 << ((peep->Var37 & 0x4) >> 2)); + } + + if (!free_edge) + return false; + + free_edge ^= 0x3; + if (!free_edge) + { + if (ScenarioRand() & 0x8000000) + free_edge = 1; + } + + Var37 = ((free_edge & 1) << 2) | chosen_edge; + + SetState(PeepState::sitting); + + SittingSubState = PeepSittingSubState::tryingToSit; + + int32_t benchX = (x & 0xFFE0) + BenchUseOffsets[Var37 & 0x7].x; + int32_t benchY = (y & 0xFFE0) + BenchUseOffsets[Var37 & 0x7].y; + + SetDestination({ benchX, benchY }, 3); + + return true; + } + + static PathElement* FindBin(const CoordsXYZ& loc) + { + for (auto* pathElement : TileElementsView(loc)) + { + if (pathElement->GetBaseZ() != loc.z) + continue; + + if (!pathElement->HasAddition()) + continue; + + auto* pathAddEntry = pathElement->GetAdditionEntry(); + if (pathAddEntry == nullptr || !(pathAddEntry->flags & PATH_ADDITION_FLAG_IS_BIN)) + continue; + + if (pathElement->IsBroken()) + continue; + + if (pathElement->AdditionIsGhost()) + continue; + + return pathElement; + } + + return nullptr; + } + + bool Guest::UpdateWalkingFindBin() + { + auto peep = this; + if (!peep->HasEmptyContainer()) + return false; + + if (peep->GetNextIsSurface()) + return false; + + auto* pathElement = FindBin(peep->NextLoc); + if (pathElement == nullptr) + return false; + + int32_t edges = (pathElement->GetEdges()) ^ 0xF; + if (edges == 0) + return false; + + uint8_t chosen_edge = ScenarioRand() & 0x3; + + // Note: Bin quantity is inverted 0 = full, 3 = empty + uint8_t bin_quantities = pathElement->GetAdditionStatus(); + + // Rotate the bin to the correct edge. Makes it easier for next calc. + bin_quantities = Numerics::ror8(Numerics::ror8(bin_quantities, chosen_edge), chosen_edge); + + for (uint8_t free_edge = 4; free_edge != 0; free_edge--) + { + // If not full + if (bin_quantities & 0x3) + { + if (edges & (1 << chosen_edge)) + break; + } + chosen_edge = (chosen_edge + 1) & 0x3; + bin_quantities = Numerics::ror8(bin_quantities, 2); + if ((free_edge - 1) == 0) return false; } - if (PeepDirection != guestNext->PeepDirection) - return false; + peep->Var37 = chosen_edge; - switch (guestNext->PeepDirection) - { - case 0: - if (x >= guestNext->x) - return false; - break; - case 1: - if (y <= guestNext->y) - return false; - break; - case 2: - if (x <= guestNext->x) - return false; - break; - case 3: - if (y >= guestNext->y) - return false; - break; - } - } + peep->SetState(PeepState::usingBin); + peep->UsingBinSubState = PeepUsingBinSubState::walkingToBin; - if (!IsActionInterruptable()) - UpdateAction(); + int32_t binX = (peep->x & 0xFFE0) + BinUseOffsets[peep->Var37 & 0x3].x; + int32_t binY = (peep->y & 0xFFE0) + BinUseOffsets[peep->Var37 & 0x3].y; + + peep->SetDestination({ binX, binY }, 3); - if (!IsActionWalking()) return true; - - Action = PeepActionType::idle; - NextAnimationType = PeepAnimationType::watchRide; - if (previous_action != PeepActionType::idle) - Invalidate(); - return true; -} - -/** - * - * rct2: 0x006966A9 - */ -void Guest::RemoveFromQueue() -{ - auto ride = GetRide(CurrentRide); - if (ride == nullptr) - return; - - auto& station = ride->getStation(CurrentRideStation); - // Make sure we don't underflow, building while paused might reset it to 0 where peeps have - // not yet left the queue. - if (station.QueueLength > 0) - { - station.QueueLength--; } - if (Id == station.LastPeepInQueue) + static PathElement* FindBreakableElement(const CoordsXYZ& loc) { - station.LastPeepInQueue = GuestNextInQueue; - return; - } - - auto& gameState = getGameState(); - auto* otherGuest = gameState.entities.GetEntity(station.LastPeepInQueue); - if (otherGuest == nullptr) - { - LOG_ERROR("Invalid Guest Queue list!"); - return; - } - for (; otherGuest != nullptr; otherGuest = gameState.entities.GetEntity(otherGuest->GuestNextInQueue)) - { - if (Id == otherGuest->GuestNextInQueue) + for (auto* pathElement : TileElementsView(loc)) { - otherGuest->GuestNextInQueue = GuestNextInQueue; + if (pathElement->GetBaseZ() != loc.z) + continue; + + if (!pathElement->HasAddition()) + continue; + + auto* pathAddEntry = pathElement->GetAdditionEntry(); + if (pathAddEntry == nullptr || !(pathAddEntry->flags & PATH_ADDITION_FLAG_BREAKABLE)) + continue; + + if (pathElement->IsBroken()) + continue; + + if (pathElement->AdditionIsGhost()) + continue; + + return pathElement; + } + + return nullptr; + } + + /** + * + * rct2: 0x00690848 + */ + static void GuestUpdateWalkingBreakScenery(Guest& guest) + { + if (getGameState().cheats.disableVandalism) + return; + + if (!(guest.PeepFlags & PEEP_FLAGS_ANGRY)) + { + if (guest.Happiness >= 48) + return; + if (guest.Energy < 85) + return; + if (guest.State != PeepState::walking) + return; + + if ((guest.LitterCount & 0xC0) != 0xC0 && (guest.DisgustingCount & 0xC0) != 0xC0) + return; + + if ((ScenarioRand() & 0xFFFF) > 3276) + return; + } + + if (guest.GetNextIsSurface()) + return; + + auto* tileElement = FindBreakableElement(guest.NextLoc); + if (tileElement == nullptr) + return; + + int32_t edges = tileElement->GetEdges(); + if (edges == 0xF) + return; + + // Check if a peep is already sitting on the bench. If so, do not vandalise it. + for (auto* otherGuest : EntityTileList({ guest.x, guest.y })) + { + if ((otherGuest->State != PeepState::sitting) || (guest.z != otherGuest->z)) + { + continue; + } + return; } - } -} -uint64_t Guest::GetItemFlags() const -{ - return ItemFlags; -} - -void Guest::SetItemFlags(uint64_t itemFlags) -{ - ItemFlags = itemFlags; -} - -void Guest::RemoveAllItems() -{ - ItemFlags = 0; - TimeToConsume = 0; -} - -void Guest::RemoveItem(ShopItem item) -{ - ItemFlags &= ~EnumToFlag(item); - TimeToConsume = 0; -} - -void Guest::GiveItem(ShopItem item) -{ - ItemFlags |= EnumToFlag(item); - - const auto& shopItemDescriptor = GetShopItemDescriptor(item); - uint16_t consumptionTime = shopItemDescriptor.ConsumptionTime; - TimeToConsume = std::min((TimeToConsume + consumptionTime), 255); -} - -bool Guest::HasItem(ShopItem peepItem) const -{ - return GetItemFlags() & EnumToFlag(peepItem); -} - -static bool IsThoughtShopItemRelated(const PeepThoughtType type) -{ - switch (type) - { - case PeepThoughtType::AlreadyGot: - case PeepThoughtType::HaventFinished: - case PeepThoughtType::CantAffordItem: - return true; - default: - break; - } - return false; -} - -void Guest::RemoveRideFromMemory(RideId rideId) -{ - if (State == PeepState::watching) - { - if (CurrentRide == rideId) + for (auto innerPeep : EntityList()) { - CurrentRide = RideId::GetNull(); - if (TimeToStand >= 50) + if (innerPeep->AssignedStaffType != StaffType::security || innerPeep->x == kLocationNull) + continue; + + int32_t xDist = abs(innerPeep->x - guest.x); + int32_t yDist = abs(innerPeep->y - guest.y); + + if (std::max(xDist, yDist) < 224) { - // make peep stop watching the ride - TimeToStand = 50; + innerPeep->StaffVandalsStopped = AddClamp(innerPeep->StaffVandalsStopped, 1u); + innerPeep->WindowInvalidateFlags |= PEEP_INVALIDATE_STAFF_STATS; + return; + } + } + + tileElement->SetIsBroken(true); + + MapInvalidateTileZoom1({ guest.NextLoc, tileElement->GetBaseZ(), tileElement->GetBaseZ() + 32 }); + + guest.Angriness = 16; + } + + /** + * rct2: 0x0069101A + * + * @return (CF) + */ + static bool PeepShouldWatchRide(TileElement* tileElement) + { + // Ghosts are purely this-client-side and should not cause any interaction, + // as that may lead to a desync. + if (Network::GetMode() != Network::Mode::none) + { + if (tileElement->IsGhost()) + return false; + } + + auto ride = GetRide(tileElement->AsTrack()->GetRideIndex()); + if (ride == nullptr || !ride->isRide()) + { + return false; + } + + // This is most likely to have peeps watch new rides + if (ride->ratings.isNull()) + { + return true; + } + + if (ride->ratings.excitement >= RideRating::make(4, 70)) + { + return true; + } + + if (ride->ratings.intensity >= RideRating::make(4, 50)) + { + return true; + } + + if (ride->getRideTypeDescriptor().flags.has(RtdFlag::interestingToLookAt)) + { + if ((ScenarioRand() & 0xFFFF) > 0x3333) + { + return false; + } + } + else if (ride->getRideTypeDescriptor().flags.has(RtdFlag::slightlyInterestingToLookAt)) + { + if ((ScenarioRand() & 0xFFFF) > 0x1000) + { + return false; + } + } + else + { + return false; + } + + return true; + } + + bool Loc690FD0(Guest& guest, RideId* rideToView, uint8_t* rideSeatToView, TileElement* tileElement) + { + auto ride = GetRide(tileElement->AsTrack()->GetRideIndex()); + if (ride == nullptr) + return false; + + *rideToView = ride->id; + if (ride->ratings.isNull()) + { + *rideSeatToView = 1; + if (ride->status != RideStatus::open) + { + if (tileElement->GetClearanceZ() > guest.NextLoc.z + (8 * kCoordsZStep)) + { + *rideSeatToView |= (1 << 1); + } + + return true; + } + } + else + { + *rideSeatToView = 0; + if (ride->status == RideStatus::open && !ride->flags.has(RideFlag::brokenDown)) + { + if (tileElement->GetClearanceZ() > guest.NextLoc.z + (8 * kCoordsZStep)) + { + *rideSeatToView = 0x02; + } + + return true; + } + } + + return false; + } + + /** + * + * rct2: 0x00690B99 + * + * @param edge (eax) + * @param peep (esi) + * @param[out] rideToView (cl) + * @param[out] rideSeatToView (ch) + * @return !CF + */ + static bool GuestFindRideToLookAt(Guest& guest, uint8_t edge, RideId* rideToView, uint8_t* rideSeatToView) + { + auto surfaceElement = MapGetSurfaceElementAt(guest.NextLoc); + TileElement* tileElement = reinterpret_cast(surfaceElement); + if (tileElement == nullptr) + { + return false; + } + + do + { + // Ghosts are purely this-client-side and should not cause any interaction, + // as that may lead to a desync. + if (Network::GetMode() != Network::Mode::none) + { + if (tileElement->IsGhost()) + continue; + } + if (tileElement->GetType() != TileElementType::Wall) + continue; + if (tileElement->GetDirection() != edge) + continue; + auto wallEntry = tileElement->AsWall()->GetEntry(); + if (wallEntry == nullptr || (wallEntry->flags2 & WALL_SCENERY_2_IS_OPAQUE)) + continue; + if (guest.NextLoc.z + (4 * kCoordsZStep) <= tileElement->GetBaseZ()) + continue; + if (guest.NextLoc.z + (1 * kCoordsZStep) >= tileElement->GetClearanceZ()) + continue; + + return false; + } while (!(tileElement++)->IsLastForTile()); + + uint16_t x = guest.NextLoc.x + CoordsDirectionDelta[edge].x; + uint16_t y = guest.NextLoc.y + CoordsDirectionDelta[edge].y; + if (!MapIsLocationValid(CoordsXY{ x, y })) + { + return false; + } + + surfaceElement = MapGetSurfaceElementAt(CoordsXY{ x, y }); + + tileElement = reinterpret_cast(surfaceElement); + if (tileElement == nullptr) + { + return false; + } + + do + { + // Ghosts are purely this-client-side and should not cause any interaction, + // as that may lead to a desync. + if (Network::GetMode() != Network::Mode::none) + { + if (tileElement->IsGhost()) + continue; + } + if (tileElement->GetType() != TileElementType::Wall) + continue; + if (DirectionReverse(tileElement->GetDirection()) != edge) + continue; + auto wallEntry = tileElement->AsWall()->GetEntry(); + if (wallEntry == nullptr || (wallEntry->flags2 & WALL_SCENERY_2_IS_OPAQUE)) + continue; + // TODO: Check whether this shouldn't be <=, as the other loops use. If so, also extract as loop A. + if (guest.NextLoc.z + (4 * kCoordsZStep) >= tileElement->GetBaseZ()) + continue; + if (guest.NextLoc.z + (1 * kCoordsZStep) >= tileElement->GetClearanceZ()) + continue; + + return false; + } while (!(tileElement++)->IsLastForTile()); + + // TODO: Extract loop B + tileElement = reinterpret_cast(surfaceElement); + do + { + // Ghosts are purely this-client-side and should not cause any interaction, + // as that may lead to a desync. + if (Network::GetMode() != Network::Mode::none) + { + if (tileElement->IsGhost()) + continue; + } + + if (tileElement->GetClearanceZ() + (1 * kCoordsZStep) < guest.NextLoc.z) + continue; + if (guest.NextLoc.z + (6 * kCoordsZStep) < tileElement->GetBaseZ()) + continue; + + if (tileElement->GetType() == TileElementType::Track) + { + if (PeepShouldWatchRide(tileElement)) + { + return Loc690FD0(guest, rideToView, rideSeatToView, tileElement); + } + } + + if (tileElement->GetType() == TileElementType::LargeScenery) + { + const auto* sceneryEntry = tileElement->AsLargeScenery()->GetEntry(); + if (sceneryEntry == nullptr || !sceneryEntry->flags.has(LargeSceneryFlag::isPhotogenic)) + { + continue; + } + + *rideSeatToView = 0; + if (tileElement->GetClearanceZ() >= guest.NextLoc.z + (8 * kCoordsZStep)) + { + *rideSeatToView = 0x02; + } + + *rideToView = RideId::GetNull(); + + return true; + } + } while (!(tileElement++)->IsLastForTile()); + + // TODO: Extract loop C + tileElement = reinterpret_cast(surfaceElement); + do + { + // Ghosts are purely this-client-side and should not cause any interaction, + // as that may lead to a desync. + if (Network::GetMode() != Network::Mode::none) + { + if (tileElement->IsGhost()) + continue; + } + if (tileElement->GetClearanceZ() + (1 * kCoordsZStep) < guest.NextLoc.z) + continue; + if (guest.NextLoc.z + (6 * kCoordsZStep) < tileElement->GetBaseZ()) + continue; + if (tileElement->GetType() == TileElementType::Surface) + continue; + if (tileElement->GetType() == TileElementType::Path) + continue; + + if (tileElement->GetType() == TileElementType::Wall) + { + auto wallEntry = tileElement->AsWall()->GetEntry(); + if (wallEntry == nullptr || (wallEntry->flags2 & WALL_SCENERY_2_IS_OPAQUE)) + { + continue; + } + } + + return false; + } while (!(tileElement++)->IsLastForTile()); + + x += CoordsDirectionDelta[edge].x; + y += CoordsDirectionDelta[edge].y; + if (!MapIsLocationValid(CoordsXY{ x, y })) + { + return false; + } + + surfaceElement = MapGetSurfaceElementAt(CoordsXY{ x, y }); + + // TODO: extract loop A + tileElement = reinterpret_cast(surfaceElement); + + if (tileElement == nullptr) + { + return false; + } + + do + { + // Ghosts are purely this-client-side and should not cause any interaction, + // as that may lead to a desync. + if (Network::GetMode() != Network::Mode::none) + { + if (tileElement->IsGhost()) + continue; + } + if (tileElement->GetType() != TileElementType::Wall) + continue; + if (DirectionReverse(tileElement->GetDirection()) != edge) + continue; + auto wallEntry = tileElement->AsWall()->GetEntry(); + if (wallEntry == nullptr || (wallEntry->flags2 & WALL_SCENERY_2_IS_OPAQUE)) + continue; + if (guest.NextLoc.z + (6 * kCoordsZStep) <= tileElement->GetBaseZ()) + continue; + if (guest.NextLoc.z >= tileElement->GetClearanceZ()) + continue; + + return false; + } while (!(tileElement++)->IsLastForTile()); + + // TODO: Extract loop B + tileElement = reinterpret_cast(surfaceElement); + do + { + // Ghosts are purely this-client-side and should not cause any interaction, + // as that may lead to a desync. + if (Network::GetMode() != Network::Mode::none) + { + if (tileElement->IsGhost()) + continue; + } + if (tileElement->GetClearanceZ() + (1 * kCoordsZStep) < guest.NextLoc.z) + continue; + if (guest.NextLoc.z + (8 * kCoordsZStep) < tileElement->GetBaseZ()) + continue; + + if (tileElement->GetType() == TileElementType::Track) + { + if (PeepShouldWatchRide(tileElement)) + { + return Loc690FD0(guest, rideToView, rideSeatToView, tileElement); + } + } + + if (tileElement->GetType() == TileElementType::LargeScenery) + { + auto* sceneryEntry = tileElement->AsLargeScenery()->GetEntry(); + if (!(sceneryEntry == nullptr || sceneryEntry->flags.has(LargeSceneryFlag::isPhotogenic))) + { + continue; + } + + *rideSeatToView = 0; + if (tileElement->GetClearanceZ() >= guest.NextLoc.z + (8 * kCoordsZStep)) + { + *rideSeatToView = 0x02; + } + + *rideToView = RideId::GetNull(); + + return true; + } + } while (!(tileElement++)->IsLastForTile()); + + // TODO: Extract loop C + tileElement = reinterpret_cast(surfaceElement); + do + { + // Ghosts are purely this-client-side and should not cause any interaction, + // as that may lead to a desync. + if (Network::GetMode() != Network::Mode::none) + { + if (tileElement->IsGhost()) + continue; + } + if (tileElement->GetClearanceZ() + (1 * kCoordsZStep) < guest.NextLoc.z) + continue; + if (guest.NextLoc.z + (8 * kCoordsZStep) < tileElement->GetBaseZ()) + continue; + if (tileElement->GetType() == TileElementType::Surface) + continue; + if (tileElement->GetType() == TileElementType::Path) + continue; + + if (tileElement->GetType() == TileElementType::Wall) + { + auto wallEntry = tileElement->AsWall()->GetEntry(); + if (wallEntry == nullptr || (wallEntry->flags2 & WALL_SCENERY_2_IS_OPAQUE)) + { + continue; + } + } + + return false; + } while (!(tileElement++)->IsLastForTile()); + + x += CoordsDirectionDelta[edge].x; + y += CoordsDirectionDelta[edge].y; + if (!MapIsLocationValid(CoordsXY{ x, y })) + { + return false; + } + + surfaceElement = MapGetSurfaceElementAt(CoordsXY{ x, y }); + + // TODO: extract loop A + tileElement = reinterpret_cast(surfaceElement); + if (tileElement == nullptr) + { + return false; + } + + do + { + // Ghosts are purely this-client-side and should not cause any interaction, + // as that may lead to a desync. + if (Network::GetMode() != Network::Mode::none) + { + if (tileElement->IsGhost()) + continue; + } + if (tileElement->GetType() != TileElementType::Wall) + continue; + if (DirectionReverse(tileElement->GetDirection()) != edge) + continue; + auto wallEntry = tileElement->AsWall()->GetEntry(); + if (wallEntry == nullptr || (wallEntry->flags2 & WALL_SCENERY_2_IS_OPAQUE)) + continue; + if (guest.NextLoc.z + (8 * kCoordsZStep) <= tileElement->GetBaseZ()) + continue; + if (guest.NextLoc.z >= tileElement->GetClearanceZ()) + continue; + + return false; + } while (!(tileElement++)->IsLastForTile()); + + // TODO: Extract loop B + tileElement = reinterpret_cast(surfaceElement); + do + { + // Ghosts are purely this-client-side and should not cause any interaction, + // as that may lead to a desync. + if (Network::GetMode() != Network::Mode::none) + { + if (tileElement->IsGhost()) + continue; + } + if (tileElement->GetClearanceZ() + (1 * kCoordsZStep) < guest.NextLoc.z) + continue; + if (guest.NextLoc.z + (10 * kCoordsZStep) < tileElement->GetBaseZ()) + continue; + + if (tileElement->GetType() == TileElementType::Track) + { + if (PeepShouldWatchRide(tileElement)) + { + return Loc690FD0(guest, rideToView, rideSeatToView, tileElement); + } + } + + if (tileElement->GetType() == TileElementType::LargeScenery) + { + const auto* sceneryEntry = tileElement->AsLargeScenery()->GetEntry(); + if (sceneryEntry == nullptr || !sceneryEntry->flags.has(LargeSceneryFlag::isPhotogenic)) + { + continue; + } + + *rideSeatToView = 0; + if (tileElement->GetClearanceZ() >= guest.NextLoc.z + (8 * kCoordsZStep)) + { + *rideSeatToView = 0x02; + } + + *rideToView = RideId::GetNull(); + + return true; + } + } while (!(tileElement++)->IsLastForTile()); + + return false; + } + + /* Part of 0x0069B8CC rct2: 0x0069BC31 */ + void Guest::SetAnimationGroup(PeepAnimationGroup new_sprite_type) + { + if (AnimationGroup == new_sprite_type) + return; + + AnimationGroup = new_sprite_type; + AnimationImageIdOffset = 0; + WalkingAnimationFrameNum = 0; + + if (IsActionInterruptable()) + Action = PeepActionType::walking; + + auto& objManager = GetContext()->GetObjectManager(); + auto* animObj = objManager.GetLoadedObject(AnimationObjectIndex); + + PeepFlags &= ~PEEP_FLAGS_SLOW_WALK; + if (animObj->IsSlowWalking(new_sprite_type)) + { + PeepFlags |= PEEP_FLAGS_SLOW_WALK; + } + + AnimationType = PeepAnimationType::invalid; + UpdateCurrentAnimationType(); + + if (State == PeepState::sitting) + { + Action = PeepActionType::idle; + NextAnimationType = PeepAnimationType::sittingIdle; + SwitchNextAnimationType(); + } + if (State == PeepState::watching) + { + Action = PeepActionType::idle; + NextAnimationType = PeepAnimationType::watchRide; + SwitchNextAnimationType(); + } + } + + struct ItemPref + { + ShopItem item; + PeepAnimationGroup sprite_type; + }; + + // clang-format off + static ItemPref item_order_preference[] = { + { ShopItem::iceCream, PeepAnimationGroup::iceCream }, + { ShopItem::chips, PeepAnimationGroup::chips }, + { ShopItem::pizza, PeepAnimationGroup::pizza }, + { ShopItem::burger, PeepAnimationGroup::burger }, + { ShopItem::drink, PeepAnimationGroup::drink }, + { ShopItem::coffee, PeepAnimationGroup::coffee }, + { ShopItem::chicken, PeepAnimationGroup::chicken }, + { ShopItem::lemonade, PeepAnimationGroup::lemonade }, + { ShopItem::candyfloss, PeepAnimationGroup::candyfloss }, + { ShopItem::popcorn, PeepAnimationGroup::popcorn }, + { ShopItem::hotDog, PeepAnimationGroup::hotDog }, + { ShopItem::tentacle, PeepAnimationGroup::tentacle }, + { ShopItem::toffeeApple, PeepAnimationGroup::toffeeApple }, + { ShopItem::doughnut, PeepAnimationGroup::doughnut }, + { ShopItem::pretzel, PeepAnimationGroup::pretzel }, + { ShopItem::cookie, PeepAnimationGroup::pretzel }, + { ShopItem::chocolate, PeepAnimationGroup::coffee }, + { ShopItem::icedTea, PeepAnimationGroup::coffee }, + { ShopItem::funnelCake, PeepAnimationGroup::funnelCake }, + { ShopItem::beefNoodles, PeepAnimationGroup::noodles }, + { ShopItem::friedRiceNoodles, PeepAnimationGroup::noodles }, + { ShopItem::wontonSoup, PeepAnimationGroup::soup }, + { ShopItem::meatballSoup, PeepAnimationGroup::soup }, + { ShopItem::fruitJuice, PeepAnimationGroup::juice }, + { ShopItem::soybeanMilk, PeepAnimationGroup::sujeonggwa }, + { ShopItem::sujeonggwa, PeepAnimationGroup::sujeonggwa }, + { ShopItem::subSandwich, PeepAnimationGroup::sandwich }, + { ShopItem::roastSausage, PeepAnimationGroup::sausage }, + { ShopItem::balloon, PeepAnimationGroup::balloon }, + { ShopItem::hat, PeepAnimationGroup::hat }, + { ShopItem::sunglasses, PeepAnimationGroup::sunglasses }, + }; + // clang-format on + + /** + * + * rct2: 0x0069B8CC + */ + void Guest::UpdateAnimationGroup() + { + if (AnimationGroup == PeepAnimationGroup::balloon && (ScenarioRand() & 0xFFFF) <= 327) + { + bool isBalloonPopped = false; + if (x != kLocationNull) + { + if ((ScenarioRand() & 0xFFFF) <= 13107) + { + isBalloonPopped = true; + Audio::Play3D(Audio::SoundId::balloonPop, { x, y, z }); + } + Balloon::Create({ x, y, z + 9 }, BalloonColour, isBalloonPopped); + } + RemoveItem(ShopItem::balloon); + WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_INVENTORY; + } + + if (Weather::isPrecipitating() && (HasItem(ShopItem::umbrella)) && x != kLocationNull) + { + CoordsXY loc = { x, y }; + if (MapIsLocationValid(loc.ToTileStart())) + { + TileElement* tileElement = MapGetFirstElementAt(loc); + while (true) + { + if (tileElement == nullptr) + break; + if (z < tileElement->GetBaseZ()) + break; + + if (tileElement->IsLastForTile()) + { + SetAnimationGroup(PeepAnimationGroup::umbrella); + return; + } + tileElement++; + } + } + } + + for (auto& itemPref : item_order_preference) + { + if (HasItem(itemPref.item)) + { + SetAnimationGroup(itemPref.sprite_type); + return; + } + } + + if (State == PeepState::watching && StandingFlags & (1 << 1)) + { + SetAnimationGroup(PeepAnimationGroup::watching); + return; + } + + if (Nausea > 170) + { + SetAnimationGroup(PeepAnimationGroup::veryNauseous); + return; + } + + if (Nausea > 140) + { + SetAnimationGroup(PeepAnimationGroup::nauseous); + return; + } + + if (Energy <= 64 && Happiness < 128) + { + SetAnimationGroup(PeepAnimationGroup::headDown); + return; + } + + if (Energy <= 80 && Happiness < 128) + { + SetAnimationGroup(PeepAnimationGroup::armsCrossed); + return; + } + + if (Toilet > 220) + { + SetAnimationGroup(PeepAnimationGroup::requireToilet); + return; + } + + SetAnimationGroup(PeepAnimationGroup::normal); + } + + bool Guest::HeadingForRideOrParkExit() const + { + return (PeepFlags & PEEP_FLAGS_LEAVING_PARK) || !GuestHeadingToRideId.IsNull(); + } + + /** + * rct2: 0x00698342 + * thought.item (eax) + * thought.type (ebx) + * argument_1 (esi & ebx) + * argument_2 (esi+2) + */ + void PeepThoughtSetFormatArgs(const PeepThought* thought, Formatter& ft) + { + ft.Add(kPeepThoughtIds[EnumValue(thought->type)]); + + PeepThoughtToActionFlag flags = PeepThoughtToActionMap[EnumValue(thought->type)].flags; + if (flags & PEEP_THOUGHT_ACTION_FLAG_RIDE) + { + auto ride = GetRide(thought->rideId); + if (ride != nullptr) + { + ride->formatNameTo(ft); + } + else + { + ft.Add(kStringIdNone); + } + } + else if (flags & PEEP_THOUGHT_ACTION_FLAG_SHOP_ITEM_SINGULAR) + { + ft.Add(GetShopItemDescriptor(thought->shopItem).Naming.Singular); + } + else if (flags & PEEP_THOUGHT_ACTION_FLAG_SHOP_ITEM_INDEFINITE) + { + ft.Add(GetShopItemDescriptor(thought->shopItem).Naming.Indefinite); + } + } + + void Guest::InsertNewThought(PeepThoughtType thought_type) + { + InsertNewThought(thought_type, kPeepThoughtItemNone); + } + + void Guest::InsertNewThought(PeepThoughtType thought_type, ShopItem shopItem) + { + InsertNewThought(thought_type, static_cast(shopItem)); + } + + void Guest::InsertNewThought(PeepThoughtType thought_type, RideId rideId) + { + InsertNewThought(thought_type, rideId.ToUnderlying()); + } + /** + * + * rct2: 0x699F5A + * al:thoughtType + * ah:thoughtArguments + * esi: peep + */ + void Guest::InsertNewThought(PeepThoughtType thoughtType, uint16_t thoughtArguments) + { + PeepActionType newAction = PeepThoughtToActionMap[EnumValue(thoughtType)].action; + if (newAction != PeepActionType::walking && IsActionInterruptableSafely()) + { + Action = newAction; + AnimationFrameNum = 0; + AnimationImageIdOffset = 0; + UpdateCurrentAnimationType(); + } + + for (int32_t i = 0; i < kPeepMaxThoughts; ++i) + { + PeepThought* thought = &Thoughts[i]; + // Remove the oldest thought by setting it to NONE. + if (thought->type == PeepThoughtType::None) + break; + + if (thought->type == thoughtType && thought->item == thoughtArguments) + { + // If the thought type has not changed then we need to move + // it to the top of the thought list. This is done by first removing the + // existing thought and placing it at the top. + if (i < kPeepMaxThoughts - 2) + { + memmove(thought, thought + 1, sizeof(PeepThought) * (kPeepMaxThoughts - i - 1)); + } + break; + } + } + + memmove(&std::get<1>(Thoughts), &std::get<0>(Thoughts), sizeof(PeepThought) * (kPeepMaxThoughts - 1)); + + auto& thought = std::get<0>(Thoughts); + thought.type = thoughtType; + thought.item = thoughtArguments; + thought.freshness = 0; + thought.fresh_timeout = 0; + + WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_THOUGHTS; + } + + // clang-format off + /** rct2: 0x009823A0 */ + static constexpr PeepNauseaTolerance nausea_tolerance_distribution[] = { + PeepNauseaTolerance::None, + PeepNauseaTolerance::Low, PeepNauseaTolerance::Low, + PeepNauseaTolerance::Average, PeepNauseaTolerance::Average, PeepNauseaTolerance::Average, + PeepNauseaTolerance::High, PeepNauseaTolerance::High, PeepNauseaTolerance::High, PeepNauseaTolerance::High, PeepNauseaTolerance::High, PeepNauseaTolerance::High, + }; + + /** rct2: 0x009823BC */ + static constexpr Drawing::Colour kTrouserColours[] = { + Drawing::Colour::black, + Drawing::Colour::grey, + Drawing::Colour::lightBrown, + Drawing::Colour::saturatedBrown, + Drawing::Colour::darkBrown, + Drawing::Colour::salmonPink, + Drawing::Colour::black, + Drawing::Colour::grey, + Drawing::Colour::lightBrown, + Drawing::Colour::saturatedBrown, + Drawing::Colour::darkBrown, + Drawing::Colour::salmonPink, + Drawing::Colour::black, + Drawing::Colour::grey, + Drawing::Colour::lightBrown, + Drawing::Colour::saturatedBrown, + Drawing::Colour::darkBrown, + Drawing::Colour::salmonPink, + Drawing::Colour::darkPurple, + Drawing::Colour::lightPurple, + Drawing::Colour::darkBlue, + Drawing::Colour::saturatedGreen, + Drawing::Colour::saturatedRed, + Drawing::Colour::darkOrange, + Drawing::Colour::bordeauxRed, + Drawing::Colour::armyGreen, + Drawing::Colour::hunterGreen, + Drawing::Colour::deepWater, + Drawing::Colour::umber, + }; + + /** rct2: 0x009823D5 */ + static constexpr Drawing::Colour kTshirtColours[] = { + Drawing::Colour::black, + Drawing::Colour::grey, + Drawing::Colour::lightBrown, + Drawing::Colour::saturatedBrown, + Drawing::Colour::darkBrown, + Drawing::Colour::salmonPink, + Drawing::Colour::black, + Drawing::Colour::grey, + Drawing::Colour::lightBrown, + Drawing::Colour::saturatedBrown, + Drawing::Colour::darkBrown, + Drawing::Colour::salmonPink, + Drawing::Colour::darkPurple, + Drawing::Colour::lightPurple, + Drawing::Colour::darkBlue, + Drawing::Colour::saturatedGreen, + Drawing::Colour::saturatedRed, + Drawing::Colour::darkOrange, + Drawing::Colour::bordeauxRed, + Drawing::Colour::white, + Drawing::Colour::brightPurple, + Drawing::Colour::lightBlue, + Drawing::Colour::darkWater, + Drawing::Colour::darkGreen, + Drawing::Colour::mossGreen, + Drawing::Colour::brightGreen, + Drawing::Colour::oliveGreen, + Drawing::Colour::darkOliveGreen, + Drawing::Colour::yellow, + Drawing::Colour::lightOrange, + Drawing::Colour::brightRed, + Drawing::Colour::darkPink, + Drawing::Colour::brightPink, + Drawing::Colour::armyGreen, + Drawing::Colour::honeyDew, + Drawing::Colour::tan, + Drawing::Colour::maroon, + Drawing::Colour::coralPink, + Drawing::Colour::forestGreen, + Drawing::Colour::chartreuse, + Drawing::Colour::hunterGreen, + Drawing::Colour::celadon, + Drawing::Colour::limeGreen, + Drawing::Colour::sepia, + Drawing::Colour::peach, + Drawing::Colour::periwinkle, + Drawing::Colour::viridian, + Drawing::Colour::seafoamGreen, + Drawing::Colour::violet, + Drawing::Colour::lavender, + Drawing::Colour::pastelOrange, + Drawing::Colour::deepWater, + Drawing::Colour::pastelPink, + Drawing::Colour::umber, + Drawing::Colour::beige, + }; + // clang-format on + + /** + * + * rct2: 0x0069A05D + */ + Guest* Guest::Generate(const CoordsXYZ& coords) + { + auto& gameState = getGameState(); + if (gameState.entities.GetNumFreeEntities() < 400) + return nullptr; + + Guest* peep = gameState.entities.CreateEntity(); + + peep->AnimationObjectIndex = findPeepAnimationsIndexForType(AnimationPeepType::guest); + peep->AnimationGroup = PeepAnimationGroup::normal; + peep->OutsideOfPark = true; + peep->State = PeepState::falling; + peep->Action = PeepActionType::walking; + peep->SpecialSprite = 0; + peep->AnimationImageIdOffset = 0; + peep->WalkingAnimationFrameNum = 0; + peep->AnimationType = PeepAnimationType::walking; + peep->PeepFlags = 0; + peep->FavouriteRide = RideId::GetNull(); + peep->FavouriteRideRating = 0; + + auto& objManager = GetContext()->GetObjectManager(); + auto* animObj = objManager.GetLoadedObject(peep->AnimationObjectIndex); + + const auto& spriteBounds = animObj->GetSpriteBounds(peep->AnimationGroup, peep->AnimationType); + peep->SpriteData.Width = spriteBounds.spriteWidth; + peep->SpriteData.HeightMin = spriteBounds.spriteHeightNegative; + peep->SpriteData.HeightMax = spriteBounds.spriteHeightPositive; + peep->Orientation = 0; + + peep->MoveTo(coords); + peep->Mass = (ScenarioRand() & 0x1F) + 45; + peep->PathCheckOptimisation = 0; + peep->InteractionRideIndex = RideId::GetNull(); + peep->PreviousRide = RideId::GetNull(); + std::get<0>(peep->Thoughts).type = PeepThoughtType::None; + peep->WindowInvalidateFlags = 0; + + uint8_t intensityHighest = (ScenarioRand() & 0x7) + 3; + uint8_t intensityLowest = std::min(intensityHighest, static_cast(7)) - 3; + + if (intensityHighest >= 7) + intensityHighest = 15; + + /* Check which intensity boxes are enabled + * and apply the appropriate intensity settings. */ + if (gameState.park.flags & PARK_FLAGS_PREF_LESS_INTENSE_RIDES) + { + if (gameState.park.flags & PARK_FLAGS_PREF_MORE_INTENSE_RIDES) + { + intensityLowest = 0; + intensityHighest = 15; + } + else + { + intensityLowest = 0; + intensityHighest = 4; + } + } + else if (gameState.park.flags & PARK_FLAGS_PREF_MORE_INTENSE_RIDES) + { + intensityLowest = 9; + intensityHighest = 15; + } + + peep->Intensity = IntensityRange(intensityLowest, intensityHighest); + + uint8_t nauseaTolerance = ScenarioRand() & 0x7; + if (gameState.park.flags & PARK_FLAGS_PREF_MORE_INTENSE_RIDES) + { + nauseaTolerance += 4; + } + + peep->NauseaTolerance = nausea_tolerance_distribution[nauseaTolerance]; + + /* Scenario editor limits initial guest happiness to between 37..253. + * To be on the safe side, assume the value could have been hacked + * to any value 0..255. */ + peep->Happiness = gameState.scenarioOptions.guestInitialHappiness; + /* Assume a default initial happiness of 0 is wrong and set + * to 128 (50%) instead. */ + if (gameState.scenarioOptions.guestInitialHappiness == 0) + peep->Happiness = 128; + /* Initial value will vary by -15..16 */ + int8_t happinessDelta = (ScenarioRand() & 0x1F) - 15; + /* Adjust by the delta, clamping at min=0 and max=255. */ + peep->Happiness = std::clamp(peep->Happiness + happinessDelta, 0, kPeepMaxHappiness); + peep->HappinessTarget = peep->Happiness; + peep->Nausea = 0; + peep->NauseaTarget = 0; + + /* Scenario editor limits initial guest hunger to between 37..253. + * To be on the safe side, assume the value could have been hacked + * to any value 0..255. */ + peep->Hunger = gameState.scenarioOptions.guestInitialHunger; + /* Initial value will vary by -15..16 */ + int8_t hungerDelta = (ScenarioRand() & 0x1F) - 15; + /* Adjust by the delta, clamping at min=0 and max=255. */ + peep->Hunger = std::clamp(peep->Hunger + hungerDelta, 0, kPeepMaxHunger); + + /* Scenario editor limits initial guest thirst to between 37..253. + * To be on the safe side, assume the value could have been hacked + * to any value 0..255. */ + peep->Thirst = gameState.scenarioOptions.guestInitialThirst; + /* Initial value will vary by -15..16 */ + int8_t thirstDelta = (ScenarioRand() & 0x1F) - 15; + /* Adjust by the delta, clamping at min=0 and max=255. */ + peep->Thirst = std::clamp(peep->Thirst + thirstDelta, 0, kPeepMaxThirst); + + peep->Toilet = 0; + peep->TimeToConsume = 0; + + peep->GuestNumRides = 0; + peep->PeepId = gameState.nextGuestNumber++; + peep->Name = nullptr; + + money64 cash = (static_cast(ScenarioRand() & 0x3) * 100) - 100 + gameState.scenarioOptions.guestInitialCash; + if (cash < 0) + cash = 0; + + if (gameState.scenarioOptions.guestInitialCash == 0.00_GBP) + { + cash = 500; + } + + if (gameState.park.flags & PARK_FLAGS_NO_MONEY) + { + cash = 0; + } + + if (gameState.scenarioOptions.guestInitialCash == kMoney64Undefined) + { + cash = 0; + } + + peep->CashInPocket = cash; + peep->CashSpent = 0; + peep->ParkEntryTime = -1; + peep->ResetPathfindGoal(); + peep->RemoveAllItems(); + peep->GuestHeadingToRideId = RideId::GetNull(); + peep->GuestNextInQueue = EntityId::GetNull(); + peep->LitterCount = 0; + peep->DisgustingCount = 0; + peep->VandalismSeen = 0; + peep->PaidToEnter = 0; + peep->PaidOnRides = 0; + peep->PaidOnFood = 0; + peep->PaidOnDrink = 0; + peep->PaidOnSouvenirs = 0; + peep->AmountOfFood = 0; + peep->AmountOfDrinks = 0; + peep->AmountOfSouvenirs = 0; + peep->SurroundingsThoughtTimeout = 0; + peep->Angriness = 0; + peep->TimeLost = 0; + + uint8_t tshirtColour = static_cast(ScenarioRand() % std::size(kTshirtColours)); + peep->TshirtColour = kTshirtColours[tshirtColour]; + + uint8_t trousersColour = static_cast(ScenarioRand() % std::size(kTrouserColours)); + peep->TrousersColour = kTrouserColours[trousersColour]; + + /* Minimum energy is capped at 32 and maximum at 128, so this initialises + * a peep with approx 34%-100% energy. (65 - 32) / (128 - 32) ≈ 34% */ + uint8_t energy = (ScenarioRand() % 64) + 65; + peep->Energy = energy; + peep->EnergyTarget = energy; + + IncrementGuestsHeadingForPark(); + +#ifdef ENABLE_SCRIPTING + auto& hookEngine = GetContext()->GetScriptEngine().GetHookEngine(); + if (hookEngine.HasSubscriptions(Scripting::HookType::guestGeneration)) + { + auto ctx = GetContext()->GetScriptEngine().GetContext(); + + // Create event args object + auto obj = Scripting::DukObject(ctx); + obj.Set("id", peep->Id.ToUnderlying()); + + // Call the subscriptions + auto e = obj.Take(); + hookEngine.Call(Scripting::HookType::guestGeneration, e, true); + } +#endif + + return peep; + } + + enum + { + PEEP_FACE_OFFSET_ANGRY = 0, + PEEP_FACE_OFFSET_VERY_VERY_SICK, + PEEP_FACE_OFFSET_VERY_SICK, + PEEP_FACE_OFFSET_SICK, + PEEP_FACE_OFFSET_VERY_TIRED, + PEEP_FACE_OFFSET_TIRED, + PEEP_FACE_OFFSET_VERY_VERY_UNHAPPY, + PEEP_FACE_OFFSET_VERY_UNHAPPY, + PEEP_FACE_OFFSET_UNHAPPY, + PEEP_FACE_OFFSET_NORMAL, + PEEP_FACE_OFFSET_HAPPY, + PEEP_FACE_OFFSET_VERY_HAPPY, + PEEP_FACE_OFFSET_VERY_VERY_HAPPY, + }; + + static constexpr int32_t kFaceSpriteSmall[] = { + SPR_PEEP_SMALL_FACE_ANGRY, + SPR_PEEP_SMALL_FACE_VERY_VERY_SICK, + SPR_PEEP_SMALL_FACE_VERY_SICK, + SPR_PEEP_SMALL_FACE_SICK, + SPR_PEEP_SMALL_FACE_VERY_TIRED, + SPR_PEEP_SMALL_FACE_TIRED, + SPR_PEEP_SMALL_FACE_VERY_VERY_UNHAPPY, + SPR_PEEP_SMALL_FACE_VERY_UNHAPPY, + SPR_PEEP_SMALL_FACE_UNHAPPY, + SPR_PEEP_SMALL_FACE_NORMAL, + SPR_PEEP_SMALL_FACE_HAPPY, + SPR_PEEP_SMALL_FACE_VERY_HAPPY, + SPR_PEEP_SMALL_FACE_VERY_VERY_HAPPY, + }; + + static constexpr int32_t kFaceSpriteLarge[] = { + SPR_PEEP_LARGE_FACE_ANGRY_0, + SPR_PEEP_LARGE_FACE_VERY_VERY_SICK_0, + SPR_PEEP_LARGE_FACE_VERY_SICK_0, + SPR_PEEP_LARGE_FACE_SICK, + SPR_PEEP_LARGE_FACE_VERY_TIRED, + SPR_PEEP_LARGE_FACE_TIRED, + SPR_PEEP_LARGE_FACE_VERY_VERY_UNHAPPY, + SPR_PEEP_LARGE_FACE_VERY_UNHAPPY, + SPR_PEEP_LARGE_FACE_UNHAPPY, + SPR_PEEP_LARGE_FACE_NORMAL, + SPR_PEEP_LARGE_FACE_HAPPY, + SPR_PEEP_LARGE_FACE_VERY_HAPPY, + SPR_PEEP_LARGE_FACE_VERY_VERY_HAPPY, + }; + + static int32_t GetFaceSpriteOffset(Guest* peep) + { + // ANGRY + if (peep->Angriness > 0) + return PEEP_FACE_OFFSET_ANGRY; + + // VERY_VERY_SICK + if (peep->Nausea > 200) + return PEEP_FACE_OFFSET_VERY_VERY_SICK; + + // VERY_SICK + if (peep->Nausea > 170) + return PEEP_FACE_OFFSET_VERY_SICK; + + // SICK + if (peep->Nausea > 140) + return PEEP_FACE_OFFSET_SICK; + + // VERY_TIRED + if (peep->Energy < 46) + return PEEP_FACE_OFFSET_VERY_TIRED; + + // TIRED + if (peep->Energy < 70) + return PEEP_FACE_OFFSET_TIRED; + + int32_t offset = PEEP_FACE_OFFSET_VERY_VERY_UNHAPPY; + // There are 7 different happiness based faces + for (int32_t i = 37; peep->Happiness >= i; i += 37) + { + offset++; + } + + return offset; + } + + /** + * Function split into large and small sprite + * rct2: 0x00698721 + */ + int32_t GetPeepFaceSpriteSmall(Guest* peep) + { + return kFaceSpriteSmall[GetFaceSpriteOffset(peep)]; + } + + /** + * Function split into large and small sprite + * rct2: 0x00698721 + */ + int32_t GetPeepFaceSpriteLarge(Guest* peep) + { + return kFaceSpriteLarge[GetFaceSpriteOffset(peep)]; + } + + /** + * + * rct2: 0x00693CBB + */ + bool Guest::UpdateQueuePosition(PeepActionType previous_action) + { + TimeInQueue = AddClamp(TimeInQueue, 1); + + auto* guestNext = getGameState().entities.GetEntity(GuestNextInQueue); + if (guestNext == nullptr) + { + return false; + } + + int16_t x_diff = abs(guestNext->x - x); + int16_t y_diff = abs(guestNext->y - y); + int16_t z_diff = abs(guestNext->z - z); + + if (z_diff > 10) + return false; + + if (x_diff < y_diff) + { + int16_t temp_x = x_diff; + x_diff = y_diff; + y_diff = temp_x; + } + + x_diff += y_diff / 2; + if (x_diff > 7) + { + if (x_diff > 13) + { + if ((x & 0xFFE0) != (guestNext->x & 0xFFE0) || (y & 0xFFE0) != (guestNext->y & 0xFFE0)) + return false; + } + + if (PeepDirection != guestNext->PeepDirection) + return false; + + switch (guestNext->PeepDirection) + { + case 0: + if (x >= guestNext->x) + return false; + break; + case 1: + if (y <= guestNext->y) + return false; + break; + case 2: + if (x <= guestNext->x) + return false; + break; + case 3: + if (y >= guestNext->y) + return false; + break; + } + } + + if (!IsActionInterruptable()) + UpdateAction(); + + if (!IsActionWalking()) + return true; + + Action = PeepActionType::idle; + NextAnimationType = PeepAnimationType::watchRide; + if (previous_action != PeepActionType::idle) + Invalidate(); + return true; + } + + /** + * + * rct2: 0x006966A9 + */ + void Guest::RemoveFromQueue() + { + auto ride = GetRide(CurrentRide); + if (ride == nullptr) + return; + + auto& station = ride->getStation(CurrentRideStation); + // Make sure we don't underflow, building while paused might reset it to 0 where peeps have + // not yet left the queue. + if (station.QueueLength > 0) + { + station.QueueLength--; + } + + if (Id == station.LastPeepInQueue) + { + station.LastPeepInQueue = GuestNextInQueue; + return; + } + + auto& gameState = getGameState(); + auto* otherGuest = gameState.entities.GetEntity(station.LastPeepInQueue); + if (otherGuest == nullptr) + { + LOG_ERROR("Invalid Guest Queue list!"); + return; + } + for (; otherGuest != nullptr; otherGuest = gameState.entities.GetEntity(otherGuest->GuestNextInQueue)) + { + if (Id == otherGuest->GuestNextInQueue) + { + otherGuest->GuestNextInQueue = GuestNextInQueue; + return; } } } - // remove any free voucher for this ride from peep - if (HasItem(ShopItem::voucher)) + uint64_t Guest::GetItemFlags() const { - if (VoucherType == VOUCHER_TYPE_RIDE_FREE && VoucherRideId == rideId) + return ItemFlags; + } + + void Guest::SetItemFlags(uint64_t itemFlags) + { + ItemFlags = itemFlags; + } + + void Guest::RemoveAllItems() + { + ItemFlags = 0; + TimeToConsume = 0; + } + + void Guest::RemoveItem(ShopItem item) + { + ItemFlags &= ~EnumToFlag(item); + TimeToConsume = 0; + } + + void Guest::GiveItem(ShopItem item) + { + ItemFlags |= EnumToFlag(item); + + const auto& shopItemDescriptor = GetShopItemDescriptor(item); + uint16_t consumptionTime = shopItemDescriptor.ConsumptionTime; + TimeToConsume = std::min((TimeToConsume + consumptionTime), 255); + } + + bool Guest::HasItem(ShopItem peepItem) const + { + return GetItemFlags() & EnumToFlag(peepItem); + } + + static bool IsThoughtShopItemRelated(const PeepThoughtType type) + { + switch (type) { - RemoveItem(ShopItem::voucher); + case PeepThoughtType::AlreadyGot: + case PeepThoughtType::HaventFinished: + case PeepThoughtType::CantAffordItem: + return true; + default: + break; + } + return false; + } + + void Guest::RemoveRideFromMemory(RideId rideId) + { + if (State == PeepState::watching) + { + if (CurrentRide == rideId) + { + CurrentRide = RideId::GetNull(); + if (TimeToStand >= 50) + { + // make peep stop watching the ride + TimeToStand = 50; + } + } + } + + // remove any free voucher for this ride from peep + if (HasItem(ShopItem::voucher)) + { + if (VoucherType == VOUCHER_TYPE_RIDE_FREE && VoucherRideId == rideId) + { + RemoveItem(ShopItem::voucher); + } + } + + // remove any photos of this ride from peep + if (HasItem(ShopItem::photo)) + { + if (Photo1RideRef == rideId) + { + RemoveItem(ShopItem::photo); + } + } + if (HasItem(ShopItem::photo2)) + { + if (Photo2RideRef == rideId) + { + RemoveItem(ShopItem::photo2); + } + } + if (HasItem(ShopItem::photo3)) + { + if (Photo3RideRef == rideId) + { + RemoveItem(ShopItem::photo3); + } + } + if (HasItem(ShopItem::photo4)) + { + if (Photo4RideRef == rideId) + { + RemoveItem(ShopItem::photo4); + } + } + + if (GuestHeadingToRideId == rideId) + { + GuestHeadingToRideId = RideId::GetNull(); + } + if (FavouriteRide == rideId) + { + FavouriteRide = RideId::GetNull(); + } + + // Erase all thoughts that contain the ride. + for (auto it = std::begin(Thoughts); it != std::end(Thoughts);) + { + const auto& entry = *it; + if (entry.type == PeepThoughtType::None) + break; + + // Ride ids and shop item ids might have the same value, look only for ride thoughts. + if (IsThoughtShopItemRelated(entry.type) || entry.rideId != rideId) + { + it++; + continue; + } + + if (auto itNext = std::next(it); itNext != std::end(Thoughts)) + { + // Overwrite this entry by shifting all entries that follow. + std::rotate(it, itNext, std::end(Thoughts)); + } + + // Last slot is now free. + auto& lastEntry = Thoughts.back(); + lastEntry.type = PeepThoughtType::None; + lastEntry.item = kPeepThoughtItemNone; } } - // remove any photos of this ride from peep - if (HasItem(ShopItem::photo)) + void Guest::ThrowUp() { - if (Photo1RideRef == rideId) - { - RemoveItem(ShopItem::photo); - } - } - if (HasItem(ShopItem::photo2)) - { - if (Photo2RideRef == rideId) - { - RemoveItem(ShopItem::photo2); - } - } - if (HasItem(ShopItem::photo3)) - { - if (Photo3RideRef == rideId) - { - RemoveItem(ShopItem::photo3); - } - } - if (HasItem(ShopItem::photo4)) - { - if (Photo4RideRef == rideId) - { - RemoveItem(ShopItem::photo4); - } + Hunger /= 2; + NauseaTarget /= 2; + + if (Nausea < 30) + Nausea = 0; + else + Nausea -= 30; + + WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_2; + + const auto curLoc = GetLocation(); + Litter::Create({ curLoc, Orientation }, (Id.ToUnderlying() & 1) ? Litter::Type::vomitAlt : Litter::Type::vomit); + + static constexpr Audio::SoundId coughs[4] = { + Audio::SoundId::cough1, + Audio::SoundId::cough2, + Audio::SoundId::cough3, + Audio::SoundId::cough4, + }; + auto soundId = coughs[ScenarioRand() & 3]; + Audio::Play3D(soundId, curLoc); } - if (GuestHeadingToRideId == rideId) + void Guest::Serialise(DataSerialiser& stream) { - GuestHeadingToRideId = RideId::GetNull(); + Peep::Serialise(stream); + stream << GuestNumRides; + stream << GuestNextInQueue; + stream << ParkEntryTime; + stream << GuestHeadingToRideId; + stream << GuestIsLostCountdown; + stream << GuestTimeOnRide; + stream << PaidToEnter; + stream << PaidOnRides; + stream << PaidOnFood; + stream << PaidOnDrink; + stream << PaidOnSouvenirs; + stream << OutsideOfPark; + stream << Happiness; + stream << HappinessTarget; + stream << Nausea; + stream << NauseaTarget; + stream << Hunger; + stream << Thirst; + stream << Toilet; + stream << TimeToConsume; + stream << Intensity; + stream << NauseaTolerance; + stream << TimeInQueue; + stream << CashInPocket; + stream << CashSpent; + stream << Photo1RideRef; + stream << Photo2RideRef; + stream << Photo3RideRef; + stream << Photo4RideRef; + stream << RejoinQueueTimeout; + stream << PreviousRide; + stream << PreviousRideTimeOut; + stream << Thoughts; + stream << LitterCount; + stream << DisgustingCount; + stream << AmountOfFood; + stream << AmountOfDrinks; + stream << AmountOfSouvenirs; + stream << VandalismSeen; + stream << VoucherType; + stream << VoucherRideId; + stream << SurroundingsThoughtTimeout; + stream << Angriness; + stream << TimeLost; + stream << DaysInQueue; + stream << BalloonColour; + stream << UmbrellaColour; + stream << HatColour; + stream << FavouriteRide; + stream << FavouriteRideRating; + stream << ItemFlags; } - if (FavouriteRide == rideId) - { - FavouriteRide = RideId::GetNull(); - } - - // Erase all thoughts that contain the ride. - for (auto it = std::begin(Thoughts); it != std::end(Thoughts);) - { - const auto& entry = *it; - if (entry.type == PeepThoughtType::None) - break; - - // Ride ids and shop item ids might have the same value, look only for ride thoughts. - if (IsThoughtShopItemRelated(entry.type) || entry.rideId != rideId) - { - it++; - continue; - } - - if (auto itNext = std::next(it); itNext != std::end(Thoughts)) - { - // Overwrite this entry by shifting all entries that follow. - std::rotate(it, itNext, std::end(Thoughts)); - } - - // Last slot is now free. - auto& lastEntry = Thoughts.back(); - lastEntry.type = PeepThoughtType::None; - lastEntry.item = kPeepThoughtItemNone; - } -} - -void Guest::ThrowUp() -{ - Hunger /= 2; - NauseaTarget /= 2; - - if (Nausea < 30) - Nausea = 0; - else - Nausea -= 30; - - WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_2; - - const auto curLoc = GetLocation(); - Litter::Create({ curLoc, Orientation }, (Id.ToUnderlying() & 1) ? Litter::Type::vomitAlt : Litter::Type::vomit); - - static constexpr Audio::SoundId coughs[4] = { - Audio::SoundId::cough1, - Audio::SoundId::cough2, - Audio::SoundId::cough3, - Audio::SoundId::cough4, - }; - auto soundId = coughs[ScenarioRand() & 3]; - Audio::Play3D(soundId, curLoc); -} - -void Guest::Serialise(DataSerialiser& stream) -{ - Peep::Serialise(stream); - stream << GuestNumRides; - stream << GuestNextInQueue; - stream << ParkEntryTime; - stream << GuestHeadingToRideId; - stream << GuestIsLostCountdown; - stream << GuestTimeOnRide; - stream << PaidToEnter; - stream << PaidOnRides; - stream << PaidOnFood; - stream << PaidOnDrink; - stream << PaidOnSouvenirs; - stream << OutsideOfPark; - stream << Happiness; - stream << HappinessTarget; - stream << Nausea; - stream << NauseaTarget; - stream << Hunger; - stream << Thirst; - stream << Toilet; - stream << TimeToConsume; - stream << Intensity; - stream << NauseaTolerance; - stream << TimeInQueue; - stream << CashInPocket; - stream << CashSpent; - stream << Photo1RideRef; - stream << Photo2RideRef; - stream << Photo3RideRef; - stream << Photo4RideRef; - stream << RejoinQueueTimeout; - stream << PreviousRide; - stream << PreviousRideTimeOut; - stream << Thoughts; - stream << LitterCount; - stream << DisgustingCount; - stream << AmountOfFood; - stream << AmountOfDrinks; - stream << AmountOfSouvenirs; - stream << VandalismSeen; - stream << VoucherType; - stream << VoucherRideId; - stream << SurroundingsThoughtTimeout; - stream << Angriness; - stream << TimeLost; - stream << DaysInQueue; - stream << BalloonColour; - stream << UmbrellaColour; - stream << HatColour; - stream << FavouriteRide; - stream << FavouriteRideRating; - stream << ItemFlags; -} +} // namespace OpenRCT2 diff --git a/src/openrct2/entity/Guest.h b/src/openrct2/entity/Guest.h index f8abaacab5..a984104355 100644 --- a/src/openrct2/entity/Guest.h +++ b/src/openrct2/entity/Guest.h @@ -15,452 +15,457 @@ #include "../ride/ShopItem.h" #include "Peep.h" -constexpr int8_t kPeepMaxThoughts = 5; - -constexpr int8_t kPeepHungerWarningThreshold = 25; -constexpr int8_t kPeepThirstWarningThreshold = 25; -constexpr int8_t kPeepToiletWarningThreshold = 28; -constexpr int8_t kPeepLitterWarningThreshold = 23; -constexpr int8_t kPeepDisgustWarningThreshold = 22; -constexpr int8_t kPeepVandalismWarningThreshold = 15; -constexpr int8_t kPeepNoExitWarningThreshold = 8; -constexpr int8_t kPeepLostWarningThreshold = 8; -constexpr int8_t kPeepTooLongQueueThreshold = 25; - -constexpr int kPeepMaxHappiness = 255; -constexpr int kPeepMaxHunger = 255; -constexpr int16_t kPeepMaxToilet = 255; -constexpr int16_t kPeepMaxNausea = 255; -constexpr int kPeepMaxThirst = 255; - -enum class PeepThoughtType : uint8_t -{ - CantAffordRide = 0, // "I can't afford" - SpentMoney = 1, // "I've spent all my money" - Sick = 2, // "I feel sick" - VerySick = 3, // "I feel very sick" - MoreThrilling = 4, // "I want to go on something more thrilling than X" - Intense = 5, // "X looks too intense for me" - HaventFinished = 6, // "I haven't finished my X yet" - Sickening = 7, // "Just looking at X makes me feel sick" - BadValue = 8, // "I'm not paying that much to go on X" - GoHome = 9, // "I want to go home" - GoodValue = 10, // "X is really good value" - AlreadyGot = 11, // "I've already got" - CantAffordItem = 12, // "I can't afford" - NotHungry = 13, // "I'm not hungry" - NotThirsty = 14, // "I'm not thirsty" - Drowning = 15, // "Help! I'm drowning!" - Lost = 16, // "I'm lost!" - WasGreat = 17, // "X was great" - QueuingAges = 18, // "I've been queuing for X for ages" - Tired = 19, // "I'm tired" - Hungry = 20, // "I'm hungry" - Thirsty = 21, // "I'm thirsty" - Toilet = 22, // "I need to go to the toilet" - CantFind = 23, // "I can't find X" - NotPaying = 24, // "I'm not paying that much to use X" - NotWhileRaining = 25, // "I'm not going on X while it's raining" - BadLitter = 26, // "The litter here is really bad" - CantFindExit = 27, // "I can't find the exit" - GetOff = 28, // "I want to get off X" - GetOut = 29, // "I want to get out of X" - NotSafe = 30, // "I'm not going on X - it isn't safe" - PathDisgusting = 31, // "This path is disgusting" - Crowded = 32, // "It's too crowded here" - Vandalism = 33, // "The vandalism here is really bad" - Scenery = 34, // "Great scenery!" - VeryClean = 35, // "This park is very clean and tidy" - Fountains = 36, // "The jumping fountains are great" - Music = 37, // "The music is nice here" - Balloon = 38, // "This balloon from X is really good value" - Toy = 39, // "This cuddly toy from X is really good value" - Map = 40, - Photo = 41, // "This on ride photo from X is really good value" - Umbrella = 42, - Drink = 43, - Burger = 44, - Chips = 45, - IceCream = 46, - Candyfloss = 47, - - Pizza = 51, - - Popcorn = 53, - HotDog = 54, - Tentacle = 55, - Hat = 56, - ToffeeApple = 57, - Tshirt = 58, - Doughnut = 59, - Coffee = 60, - - Chicken = 62, - Lemonade = 63, - - Wow = 67, // "Wow!" - - Wow2 = 70, // "Wow!" - Watched = 71, // "I have the strangest feeling someone is watching me" - BalloonMuch = 72, // "I'm not paying that much to get a balloon from X" - ToyMuch = 73, - MapMuch = 74, - PhotoMuch = 75, - UmbrellaMuch = 76, - DrinkMuch = 77, - BurgerMuch = 78, - ChipsMuch = 79, - IceCreamMuch = 80, - CandyflossMuch = 81, - - PizzaMuch = 85, - - PopcornMuch = 87, - HotDogMuch = 88, - TentacleMuch = 89, - HatMuch = 90, - ToffeeAppleMuch = 91, - TshirtMuch = 92, - DoughnutMuch = 93, - CoffeeMuch = 94, - - ChickenMuch = 96, - LemonadeMuch = 97, - - Photo2 = 104, // "This on-ride photo from X is really good value" - Photo3 = 105, - Photo4 = 106, - Pretzel = 107, - HotChocolate = 108, - IcedTea = 109, - FunnelCake = 110, - Sunglasses = 111, - BeefNoodles = 112, - FriedRiceNoodles = 113, - WontonSoup = 114, - MeatballSoup = 115, - FruitJuice = 116, - SoybeanMilk = 117, - Sujongkwa = 118, - SubSandwich = 119, - Cookie = 120, - - RoastSausage = 124, - - Photo2Much = 136, - Photo3Much = 137, - Photo4Much = 138, - PretzelMuch = 139, - HotChocolateMuch = 140, - IcedTeaMuch = 141, - FunnelCakeMuch = 142, - SunglassesMuch = 143, - BeefNoodlesMuch = 144, - FriedRiceNoodlesMuch = 145, - WontonSoupMuch = 146, - MeatballSoupMuch = 147, - FruitJuiceMuch = 148, - SoybeanMilkMuch = 149, - SujongkwaMuch = 150, - SubSandwichMuch = 151, - CookieMuch = 152, - - RoastSausageMuch = 156, - - Help = 168, // "Help! Put me down!" - RunningOut = 169, // "I'm running out of cash!" - NewRide = 170, // "Wow! A new ride being built!" - NiceRideDeprecated = 171, // "Nice ride! But not as good as the Phoenix..." - ExcitedDeprecated = 172, // "I'm so excited - It's an Intamin ride!" - HereWeAre = 173, // "...and here we are on X!" - - None = 255 -}; - -enum class PeepNauseaTolerance : uint8_t -{ - None, - Low, - Average, - High -}; - -static constexpr uint16_t kPeepThoughtItemNone = std::numeric_limits::max(); - -struct PeepThought -{ - PeepThoughtType type; - union - { - RideId rideId; - ShopItem shopItem; - uint16_t item; - }; - uint8_t freshness; // larger is less fresh - uint8_t fresh_timeout; // updates every tick -}; - -struct Guest; -struct Staff; struct CarEntry; -struct IntensityRange +namespace OpenRCT2 { -private: - uint8_t _value{}; + constexpr int8_t kPeepMaxThoughts = 5; -public: - explicit IntensityRange(uint8_t value) - : _value(value) + constexpr int8_t kPeepHungerWarningThreshold = 25; + constexpr int8_t kPeepThirstWarningThreshold = 25; + constexpr int8_t kPeepToiletWarningThreshold = 28; + constexpr int8_t kPeepLitterWarningThreshold = 23; + constexpr int8_t kPeepDisgustWarningThreshold = 22; + constexpr int8_t kPeepVandalismWarningThreshold = 15; + constexpr int8_t kPeepNoExitWarningThreshold = 8; + constexpr int8_t kPeepLostWarningThreshold = 8; + constexpr int8_t kPeepTooLongQueueThreshold = 25; + + constexpr int kPeepMaxHappiness = 255; + constexpr int kPeepMaxHunger = 255; + constexpr int16_t kPeepMaxToilet = 255; + constexpr int16_t kPeepMaxNausea = 255; + constexpr int kPeepMaxThirst = 255; + + enum class PeepThoughtType : uint8_t { - } + CantAffordRide = 0, // "I can't afford" + SpentMoney = 1, // "I've spent all my money" + Sick = 2, // "I feel sick" + VerySick = 3, // "I feel very sick" + MoreThrilling = 4, // "I want to go on something more thrilling than X" + Intense = 5, // "X looks too intense for me" + HaventFinished = 6, // "I haven't finished my X yet" + Sickening = 7, // "Just looking at X makes me feel sick" + BadValue = 8, // "I'm not paying that much to go on X" + GoHome = 9, // "I want to go home" + GoodValue = 10, // "X is really good value" + AlreadyGot = 11, // "I've already got" + CantAffordItem = 12, // "I can't afford" + NotHungry = 13, // "I'm not hungry" + NotThirsty = 14, // "I'm not thirsty" + Drowning = 15, // "Help! I'm drowning!" + Lost = 16, // "I'm lost!" + WasGreat = 17, // "X was great" + QueuingAges = 18, // "I've been queuing for X for ages" + Tired = 19, // "I'm tired" + Hungry = 20, // "I'm hungry" + Thirsty = 21, // "I'm thirsty" + Toilet = 22, // "I need to go to the toilet" + CantFind = 23, // "I can't find X" + NotPaying = 24, // "I'm not paying that much to use X" + NotWhileRaining = 25, // "I'm not going on X while it's raining" + BadLitter = 26, // "The litter here is really bad" + CantFindExit = 27, // "I can't find the exit" + GetOff = 28, // "I want to get off X" + GetOut = 29, // "I want to get out of X" + NotSafe = 30, // "I'm not going on X - it isn't safe" + PathDisgusting = 31, // "This path is disgusting" + Crowded = 32, // "It's too crowded here" + Vandalism = 33, // "The vandalism here is really bad" + Scenery = 34, // "Great scenery!" + VeryClean = 35, // "This park is very clean and tidy" + Fountains = 36, // "The jumping fountains are great" + Music = 37, // "The music is nice here" + Balloon = 38, // "This balloon from X is really good value" + Toy = 39, // "This cuddly toy from X is really good value" + Map = 40, + Photo = 41, // "This on ride photo from X is really good value" + Umbrella = 42, + Drink = 43, + Burger = 44, + Chips = 45, + IceCream = 46, + Candyfloss = 47, - IntensityRange(uint8_t min, uint8_t max) - : _value(std::min(min, 15) | (std::min(max, 15) << 4)) - { - } + Pizza = 51, - uint8_t GetMinimum() const - { - return _value & 0x0F; - } + Popcorn = 53, + HotDog = 54, + Tentacle = 55, + Hat = 56, + ToffeeApple = 57, + Tshirt = 58, + Doughnut = 59, + Coffee = 60, - uint8_t GetMaximum() const - { - return _value >> 4; - } + Chicken = 62, + Lemonade = 63, - IntensityRange WithMinimum(uint8_t value) const - { - return IntensityRange(value, GetMaximum()); - } + Wow = 67, // "Wow!" - IntensityRange WithMaximum(uint8_t value) const - { - return IntensityRange(GetMinimum(), value); - } + Wow2 = 70, // "Wow!" + Watched = 71, // "I have the strangest feeling someone is watching me" + BalloonMuch = 72, // "I'm not paying that much to get a balloon from X" + ToyMuch = 73, + MapMuch = 74, + PhotoMuch = 75, + UmbrellaMuch = 76, + DrinkMuch = 77, + BurgerMuch = 78, + ChipsMuch = 79, + IceCreamMuch = 80, + CandyflossMuch = 81, - explicit operator uint8_t() const - { - return _value; - } + PizzaMuch = 85, - friend bool operator==(const IntensityRange& lhs, const IntensityRange& rhs) - { - return lhs._value == rhs._value; - } + PopcornMuch = 87, + HotDogMuch = 88, + TentacleMuch = 89, + HatMuch = 90, + ToffeeAppleMuch = 91, + TshirtMuch = 92, + DoughnutMuch = 93, + CoffeeMuch = 94, - friend bool operator!=(const IntensityRange& lhs, const IntensityRange& rhs) - { - return lhs._value != rhs._value; - } -}; + ChickenMuch = 96, + LemonadeMuch = 97, -struct Guest : Peep -{ - static constexpr auto cEntityType = EntityType::guest; + Photo2 = 104, // "This on-ride photo from X is really good value" + Photo3 = 105, + Photo4 = 106, + Pretzel = 107, + HotChocolate = 108, + IcedTea = 109, + FunnelCake = 110, + Sunglasses = 111, + BeefNoodles = 112, + FriedRiceNoodles = 113, + WontonSoup = 114, + MeatballSoup = 115, + FruitJuice = 116, + SoybeanMilk = 117, + Sujongkwa = 118, + SubSandwich = 119, + Cookie = 120, -public: - uint8_t GuestNumRides; - EntityId GuestNextInQueue; - int32_t ParkEntryTime; - RideId GuestHeadingToRideId; - uint8_t GuestIsLostCountdown; - uint8_t GuestTimeOnRide; - money64 PaidToEnter; - money64 PaidOnRides; - money64 PaidOnFood; - money64 PaidOnDrink; - money64 PaidOnSouvenirs; - bool OutsideOfPark; - uint8_t Happiness; - uint8_t HappinessTarget; - uint8_t Nausea; - uint8_t NauseaTarget; - uint8_t Hunger; - uint8_t Thirst; - uint8_t Toilet; - uint8_t TimeToConsume; - IntensityRange Intensity{ 0 }; - PeepNauseaTolerance NauseaTolerance; - uint16_t TimeInQueue; - money64 CashInPocket; - money64 CashSpent; - RideId Photo1RideRef; - RideId Photo2RideRef; - RideId Photo3RideRef; - RideId Photo4RideRef; + RoastSausage = 124, - int8_t RejoinQueueTimeout; // whilst waiting for a free vehicle (or pair) in the entrance - RideId PreviousRide; - uint16_t PreviousRideTimeOut; - std::array Thoughts; - // 0x3F Litter Count split into lots of 3 with time, 0xC0 Time since last recalc - uint8_t LitterCount; - // 0x3F Sick Count split into lots of 3 with time, 0xC0 Time since last recalc - uint8_t DisgustingCount; - uint8_t AmountOfFood; - uint8_t AmountOfDrinks; - uint8_t AmountOfSouvenirs; - uint8_t VandalismSeen; // 0xC0 vandalism thought timeout, 0x3F vandalism tiles seen - uint8_t VoucherType; - union - { - RideId VoucherRideId; - ShopItemIndex VoucherShopItem; + Photo2Much = 136, + Photo3Much = 137, + Photo4Much = 138, + PretzelMuch = 139, + HotChocolateMuch = 140, + IcedTeaMuch = 141, + FunnelCakeMuch = 142, + SunglassesMuch = 143, + BeefNoodlesMuch = 144, + FriedRiceNoodlesMuch = 145, + WontonSoupMuch = 146, + MeatballSoupMuch = 147, + FruitJuiceMuch = 148, + SoybeanMilkMuch = 149, + SujongkwaMuch = 150, + SubSandwichMuch = 151, + CookieMuch = 152, + + RoastSausageMuch = 156, + + Help = 168, // "Help! Put me down!" + RunningOut = 169, // "I'm running out of cash!" + NewRide = 170, // "Wow! A new ride being built!" + NiceRideDeprecated = 171, // "Nice ride! But not as good as the Phoenix..." + ExcitedDeprecated = 172, // "I'm so excited - It's an Intamin ride!" + HereWeAre = 173, // "...and here we are on X!" + + None = 255 }; - uint8_t SurroundingsThoughtTimeout; - uint8_t Angriness; - uint8_t TimeLost; // the time the peep has been lost when it reaches 254 generates the lost thought - uint8_t DaysInQueue; - OpenRCT2::Drawing::Colour BalloonColour; - OpenRCT2::Drawing::Colour UmbrellaColour; - OpenRCT2::Drawing::Colour HatColour; - RideId FavouriteRide; - uint8_t FavouriteRideRating; - uint64_t ItemFlags; - void Update(); - void Tick128UpdateGuest(uint32_t index); - uint64_t GetFoodOrDrinkFlags() const; - uint64_t GetEmptyContainerFlags() const; - bool HasDrink() const; - bool HasFoodOrDrink() const; - bool HasEmptyContainer() const; - void UpdateAnimationGroup(); - bool HeadingForRideOrParkExit() const; - void ReadMap(); - bool ShouldGoOnRide(Ride& ride, StationIndex entranceNum, bool atQueue, bool thinking); - void SpendMoney(money64& peep_expend_type, money64 amount, ExpenditureType type); - void SpendMoney(money64 amount, ExpenditureType type); - void SetHasRidden(const Ride& ride); - bool HasRidden(const Ride& ride) const; - void SetHasRiddenRideType(ride_type_t rideType); - bool HasRiddenRideType(ride_type_t rideType) const; - void SetParkEntryTime(int32_t entryTime); - int32_t GetParkEntryTime() const; - void CheckIfLost(); - void CheckCantFindRide(); - void CheckCantFindExit(); - void SetAnimationGroup(PeepAnimationGroup new_sprite_type); - int32_t GetEasterEggNameId() const; - void UpdateEasterEggInteractions(); - void InsertNewThought(PeepThoughtType thought_type); - void InsertNewThought(PeepThoughtType thought_type, ShopItem thought_arguments); - void InsertNewThought(PeepThoughtType thought_type, RideId rideId); - void InsertNewThought(PeepThoughtType thought_type, uint16_t thought_arguments); - static Guest* Generate(const CoordsXYZ& coords); - bool UpdateQueuePosition(PeepActionType previous_action); - void RemoveFromQueue(); + enum class PeepNauseaTolerance : uint8_t + { + None, + Low, + Average, + High + }; - uint64_t GetItemFlags() const; - void SetItemFlags(uint64_t itemFlags); - void RemoveAllItems(); - void RemoveItem(ShopItem item); - void GiveItem(ShopItem item); - bool HasItem(ShopItem peepItem) const; - void Serialise(OpenRCT2::DataSerialiser& stream); + static constexpr uint16_t kPeepThoughtItemNone = std::numeric_limits::max(); - // Removes the ride from the guests memory, this includes - // the history, thoughts, etc. - void RemoveRideFromMemory(RideId rideId); - void HandleEasterEggName(); - void ChoseNotToGoOnRide(const Ride& ride, bool peepAtRide, bool updateLastRide); - void OnEnterRide(Ride& ride); - void OnExitRide(Ride& ride); - void ThrowUp(); + struct PeepThought + { + PeepThoughtType type; + union + { + RideId rideId; + ShopItem shopItem; + uint16_t item; + }; + uint8_t freshness; // larger is less fresh + uint8_t fresh_timeout; // updates every tick + }; -private: - bool ShouldFindBench(); - bool UpdateWalkingFindBin(); - bool UpdateWalkingFindBench(); - void UpdateRide(); - void UpdateOnRide() {}; // TODO - void UpdateWalking(); - void UpdateQueuing(); - void UpdateSitting(); - void UpdateEnteringPark(); - void UpdateLeavingPark(); - void UpdateBuying(); - void UpdateWatching(); - void UpdateUsingBin(); - void UpdateRideAtEntrance(); - void UpdateRideAdvanceThroughEntrance(); - void UpdateRideLeaveEntranceWaypoints(const Ride& ride); - uint8_t GetWaypointedSeatLocation(const Ride& ride, const CarEntry* vehicle_type, uint8_t track_direction) const; - void UpdateRideFreeVehicleCheck(); - void UpdateRideFreeVehicleEnterRide(Ride& ride); - void UpdateRideApproachVehicle(); - void UpdateRideEnterVehicle(); - void UpdateRideLeaveVehicle(); - void UpdateRideApproachExit(); - void UpdateRideInExit(); + struct Guest; + struct Staff; - void UpdateRideApproachVehicleWaypoints(); + struct IntensityRange + { + private: + uint8_t _value{}; - void UpdateRideApproachExitWaypoints(); - void UpdateRideApproachSpiralSlide(); - void UpdateRideOnSpiralSlide(); - void UpdateRideLeaveSpiralSlide(); - void UpdateRideMazePathfinding(); - void UpdateRideLeaveExit(); - void UpdateRideShopApproach(); - void UpdateRideShopInteract(); - void UpdateRideShopLeave(); - void UpdateRidePrepareForExit(); - void UpdateMotivesIdle(); - void UpdateConsumptionMotives(); - int32_t CheckEasterEggName(int32_t index) const; - void GivePassingGuestPurpleClothes(Guest& passingPeep); - void GivePassingGuestPizza(Guest& passingPeep); - void MakePassingGuestSick(Guest& passingPeep); - void GivePassingPeepsIceCream(Guest& passingPeep); - void GoToRideEntrance(const Ride& ride); -}; + public: + explicit IntensityRange(uint8_t value) + : _value(value) + { + } -void UpdateRideApproachVehicleWaypointsMotionSimulator(Guest&, const CoordsXY&, int16_t&); -void UpdateRideApproachVehicleWaypointsDefault(Guest&, const CoordsXY&, int16_t&); + IntensityRange(uint8_t min, uint8_t max) + : _value(std::min(min, 15) | (std::min(max, 15) << 4)) + { + } -static_assert(sizeof(Guest) <= 512); + uint8_t GetMinimum() const + { + return _value & 0x0F; + } -enum -{ - EASTEREGG_PEEP_NAME_MICHAEL_SCHUMACHER, - EASTEREGG_PEEP_NAME_JACQUES_VILLENEUVE, - EASTEREGG_PEEP_NAME_DAMON_HILL, - EASTEREGG_PEEP_NAME_MR_BEAN, - EASTEREGG_PEEP_NAME_CHRIS_SAWYER, - EASTEREGG_PEEP_NAME_KATIE_BRAYSHAW, - EASTEREGG_PEEP_NAME_MELANIE_WARN, - EASTEREGG_PEEP_NAME_SIMON_FOSTER, - EASTEREGG_PEEP_NAME_JOHN_WARDLEY, - EASTEREGG_PEEP_NAME_LISA_STIRLING, - EASTEREGG_PEEP_NAME_DONALD_MACRAE, - EASTEREGG_PEEP_NAME_KATHERINE_MCGOWAN, - EASTEREGG_PEEP_NAME_FRANCES_MCGOWAN, - EASTEREGG_PEEP_NAME_CORINA_MASSOURA, - EASTEREGG_PEEP_NAME_CAROL_YOUNG, - EASTEREGG_PEEP_NAME_MIA_SHERIDAN, - EASTEREGG_PEEP_NAME_KATIE_RODGER, - EASTEREGG_PEEP_NAME_EMMA_GARRELL, - EASTEREGG_PEEP_NAME_JOANNE_BARTON, - EASTEREGG_PEEP_NAME_FELICITY_ANDERSON, - EASTEREGG_PEEP_NAME_KATIE_SMITH, - EASTEREGG_PEEP_NAME_EILIDH_BELL, - EASTEREGG_PEEP_NAME_NANCY_STILLWAGON, - EASTEREGG_PEEP_NAME_DAVID_ELLIS -}; + uint8_t GetMaximum() const + { + return _value >> 4; + } -void PeepThoughtSetFormatArgs(const PeepThought* thought, OpenRCT2::Formatter& ft); + IntensityRange WithMinimum(uint8_t value) const + { + return IntensityRange(value, GetMaximum()); + } -void IncrementGuestsInPark(); -void IncrementGuestsHeadingForPark(); -void DecrementGuestsInPark(); -void DecrementGuestsHeadingForPark(); + IntensityRange WithMaximum(uint8_t value) const + { + return IntensityRange(GetMinimum(), value); + } -void PeepUpdateRideLeaveEntranceMaze(Guest& peep, Ride& ride, CoordsXYZD& entrance_loc); -void PeepUpdateRideLeaveEntranceSpiralSlide(Guest& peep, Ride& ride, CoordsXYZD& entrance_loc); -void PeepUpdateRideLeaveEntranceDefault(Guest& peep, Ride& ride, CoordsXYZD& entrance_loc); + explicit operator uint8_t() const + { + return _value; + } -CoordsXY GetGuestWaypointLocationDefault(const Vehicle& vehicle, const Ride& ride, const StationIndex& CurrentRideStation); -CoordsXY GetGuestWaypointLocationEnterprise(const Vehicle& vehicle, const Ride& ride, const StationIndex& CurrentRideStation); + friend bool operator==(const IntensityRange& lhs, const IntensityRange& rhs) + { + return lhs._value == rhs._value; + } + + friend bool operator!=(const IntensityRange& lhs, const IntensityRange& rhs) + { + return lhs._value != rhs._value; + } + }; + + struct Guest : Peep + { + static constexpr auto cEntityType = EntityType::guest; + + public: + uint8_t GuestNumRides; + EntityId GuestNextInQueue; + int32_t ParkEntryTime; + RideId GuestHeadingToRideId; + uint8_t GuestIsLostCountdown; + uint8_t GuestTimeOnRide; + money64 PaidToEnter; + money64 PaidOnRides; + money64 PaidOnFood; + money64 PaidOnDrink; + money64 PaidOnSouvenirs; + bool OutsideOfPark; + uint8_t Happiness; + uint8_t HappinessTarget; + uint8_t Nausea; + uint8_t NauseaTarget; + uint8_t Hunger; + uint8_t Thirst; + uint8_t Toilet; + uint8_t TimeToConsume; + IntensityRange Intensity{ 0 }; + PeepNauseaTolerance NauseaTolerance; + uint16_t TimeInQueue; + money64 CashInPocket; + money64 CashSpent; + RideId Photo1RideRef; + RideId Photo2RideRef; + RideId Photo3RideRef; + RideId Photo4RideRef; + + int8_t RejoinQueueTimeout; // whilst waiting for a free vehicle (or pair) in the entrance + RideId PreviousRide; + uint16_t PreviousRideTimeOut; + std::array Thoughts; + // 0x3F Litter Count split into lots of 3 with time, 0xC0 Time since last recalc + uint8_t LitterCount; + // 0x3F Sick Count split into lots of 3 with time, 0xC0 Time since last recalc + uint8_t DisgustingCount; + uint8_t AmountOfFood; + uint8_t AmountOfDrinks; + uint8_t AmountOfSouvenirs; + uint8_t VandalismSeen; // 0xC0 vandalism thought timeout, 0x3F vandalism tiles seen + uint8_t VoucherType; + union + { + RideId VoucherRideId; + ShopItemIndex VoucherShopItem; + }; + uint8_t SurroundingsThoughtTimeout; + uint8_t Angriness; + uint8_t TimeLost; // the time the peep has been lost when it reaches 254 generates the lost thought + uint8_t DaysInQueue; + Drawing::Colour BalloonColour; + Drawing::Colour UmbrellaColour; + Drawing::Colour HatColour; + RideId FavouriteRide; + uint8_t FavouriteRideRating; + uint64_t ItemFlags; + + void Update(); + void Tick128UpdateGuest(uint32_t index); + uint64_t GetFoodOrDrinkFlags() const; + uint64_t GetEmptyContainerFlags() const; + bool HasDrink() const; + bool HasFoodOrDrink() const; + bool HasEmptyContainer() const; + void UpdateAnimationGroup(); + bool HeadingForRideOrParkExit() const; + void ReadMap(); + bool ShouldGoOnRide(Ride& ride, StationIndex entranceNum, bool atQueue, bool thinking); + void SpendMoney(money64& peep_expend_type, money64 amount, ExpenditureType type); + void SpendMoney(money64 amount, ExpenditureType type); + void SetHasRidden(const Ride& ride); + bool HasRidden(const Ride& ride) const; + void SetHasRiddenRideType(ride_type_t rideType); + bool HasRiddenRideType(ride_type_t rideType) const; + void SetParkEntryTime(int32_t entryTime); + int32_t GetParkEntryTime() const; + void CheckIfLost(); + void CheckCantFindRide(); + void CheckCantFindExit(); + void SetAnimationGroup(PeepAnimationGroup new_sprite_type); + int32_t GetEasterEggNameId() const; + void UpdateEasterEggInteractions(); + void InsertNewThought(PeepThoughtType thought_type); + void InsertNewThought(PeepThoughtType thought_type, ShopItem thought_arguments); + void InsertNewThought(PeepThoughtType thought_type, RideId rideId); + void InsertNewThought(PeepThoughtType thought_type, uint16_t thought_arguments); + static Guest* Generate(const CoordsXYZ& coords); + bool UpdateQueuePosition(PeepActionType previous_action); + void RemoveFromQueue(); + + uint64_t GetItemFlags() const; + void SetItemFlags(uint64_t itemFlags); + void RemoveAllItems(); + void RemoveItem(ShopItem item); + void GiveItem(ShopItem item); + bool HasItem(ShopItem peepItem) const; + void Serialise(DataSerialiser& stream); + + // Removes the ride from the guests memory, this includes + // the history, thoughts, etc. + void RemoveRideFromMemory(RideId rideId); + void HandleEasterEggName(); + void ChoseNotToGoOnRide(const Ride& ride, bool peepAtRide, bool updateLastRide); + void OnEnterRide(Ride& ride); + void OnExitRide(Ride& ride); + void ThrowUp(); + + private: + bool ShouldFindBench(); + bool UpdateWalkingFindBin(); + bool UpdateWalkingFindBench(); + void UpdateRide(); + void UpdateOnRide() {}; // TODO + void UpdateWalking(); + void UpdateQueuing(); + void UpdateSitting(); + void UpdateEnteringPark(); + void UpdateLeavingPark(); + void UpdateBuying(); + void UpdateWatching(); + void UpdateUsingBin(); + void UpdateRideAtEntrance(); + void UpdateRideAdvanceThroughEntrance(); + void UpdateRideLeaveEntranceWaypoints(const Ride& ride); + uint8_t GetWaypointedSeatLocation(const Ride& ride, const CarEntry* vehicle_type, uint8_t track_direction) const; + void UpdateRideFreeVehicleCheck(); + void UpdateRideFreeVehicleEnterRide(Ride& ride); + void UpdateRideApproachVehicle(); + void UpdateRideEnterVehicle(); + void UpdateRideLeaveVehicle(); + void UpdateRideApproachExit(); + void UpdateRideInExit(); + + void UpdateRideApproachVehicleWaypoints(); + + void UpdateRideApproachExitWaypoints(); + void UpdateRideApproachSpiralSlide(); + void UpdateRideOnSpiralSlide(); + void UpdateRideLeaveSpiralSlide(); + void UpdateRideMazePathfinding(); + void UpdateRideLeaveExit(); + void UpdateRideShopApproach(); + void UpdateRideShopInteract(); + void UpdateRideShopLeave(); + void UpdateRidePrepareForExit(); + void UpdateMotivesIdle(); + void UpdateConsumptionMotives(); + int32_t CheckEasterEggName(int32_t index) const; + void GivePassingGuestPurpleClothes(Guest& passingPeep); + void GivePassingGuestPizza(Guest& passingPeep); + void MakePassingGuestSick(Guest& passingPeep); + void GivePassingPeepsIceCream(Guest& passingPeep); + void GoToRideEntrance(const Ride& ride); + }; + + void UpdateRideApproachVehicleWaypointsMotionSimulator(Guest&, const CoordsXY&, int16_t&); + void UpdateRideApproachVehicleWaypointsDefault(Guest&, const CoordsXY&, int16_t&); + + static_assert(sizeof(Guest) <= 512); + + enum + { + EASTEREGG_PEEP_NAME_MICHAEL_SCHUMACHER, + EASTEREGG_PEEP_NAME_JACQUES_VILLENEUVE, + EASTEREGG_PEEP_NAME_DAMON_HILL, + EASTEREGG_PEEP_NAME_MR_BEAN, + EASTEREGG_PEEP_NAME_CHRIS_SAWYER, + EASTEREGG_PEEP_NAME_KATIE_BRAYSHAW, + EASTEREGG_PEEP_NAME_MELANIE_WARN, + EASTEREGG_PEEP_NAME_SIMON_FOSTER, + EASTEREGG_PEEP_NAME_JOHN_WARDLEY, + EASTEREGG_PEEP_NAME_LISA_STIRLING, + EASTEREGG_PEEP_NAME_DONALD_MACRAE, + EASTEREGG_PEEP_NAME_KATHERINE_MCGOWAN, + EASTEREGG_PEEP_NAME_FRANCES_MCGOWAN, + EASTEREGG_PEEP_NAME_CORINA_MASSOURA, + EASTEREGG_PEEP_NAME_CAROL_YOUNG, + EASTEREGG_PEEP_NAME_MIA_SHERIDAN, + EASTEREGG_PEEP_NAME_KATIE_RODGER, + EASTEREGG_PEEP_NAME_EMMA_GARRELL, + EASTEREGG_PEEP_NAME_JOANNE_BARTON, + EASTEREGG_PEEP_NAME_FELICITY_ANDERSON, + EASTEREGG_PEEP_NAME_KATIE_SMITH, + EASTEREGG_PEEP_NAME_EILIDH_BELL, + EASTEREGG_PEEP_NAME_NANCY_STILLWAGON, + EASTEREGG_PEEP_NAME_DAVID_ELLIS + }; + + void PeepThoughtSetFormatArgs(const PeepThought* thought, Formatter& ft); + + void IncrementGuestsInPark(); + void IncrementGuestsHeadingForPark(); + void DecrementGuestsInPark(); + void DecrementGuestsHeadingForPark(); + + void PeepUpdateRideLeaveEntranceMaze(Guest& peep, Ride& ride, CoordsXYZD& entrance_loc); + void PeepUpdateRideLeaveEntranceSpiralSlide(Guest& peep, Ride& ride, CoordsXYZD& entrance_loc); + void PeepUpdateRideLeaveEntranceDefault(Guest& peep, Ride& ride, CoordsXYZD& entrance_loc); + + CoordsXY GetGuestWaypointLocationDefault(const Vehicle& vehicle, const Ride& ride, const StationIndex& CurrentRideStation); + CoordsXY GetGuestWaypointLocationEnterprise( + const Vehicle& vehicle, const Ride& ride, const StationIndex& CurrentRideStation); +} // namespace OpenRCT2 diff --git a/src/openrct2/entity/Litter.cpp b/src/openrct2/entity/Litter.cpp index fb445f3a8b..f8ee4f208d 100644 --- a/src/openrct2/entity/Litter.cpp +++ b/src/openrct2/entity/Litter.cpp @@ -15,186 +15,187 @@ #include -using namespace OpenRCT2; - -template<> -bool EntityBase::Is() const +namespace OpenRCT2 { - return Type == EntityType::litter; -} - -static bool IsLocationLitterable(const CoordsXYZ& mapPos) -{ - if (!MapIsLocationOwned(mapPos)) - return false; - - TileElement* tileElement = MapGetFirstElementAt(mapPos); - if (tileElement == nullptr) - return false; - do + template<> + bool EntityBase::Is() const { - if (tileElement->GetType() != TileElementType::Path) - continue; + return Type == EntityType::litter; + } - int32_t pathZ = tileElement->GetBaseZ(); - if (pathZ < mapPos.z || pathZ >= mapPos.z + kPathClearance) - continue; - - return !TileElementIsUnderground(tileElement); - } while (!(tileElement++)->IsLastForTile()); - return false; -} - -/** - * - * rct2: 0x0067375D - */ -void Litter::Create(const CoordsXYZD& litterPos, Type type) -{ - auto& gameState = getGameState(); - if (gameState.cheats.disableLittering) - return; - - auto offsetLitterPos = litterPos - + CoordsXY{ CoordsDirectionDelta[litterPos.direction >> 3].x / 8, - CoordsDirectionDelta[litterPos.direction >> 3].y / 8 }; - - if (!IsLocationLitterable(offsetLitterPos)) - return; - - if (gameState.entities.GetEntityListCount(EntityType::litter) >= 500) + static bool IsLocationLitterable(const CoordsXYZ& mapPos) { - Litter* newestLitter = nullptr; - uint32_t newestLitterCreationTick = 0; - for (auto litter : EntityList()) + if (!MapIsLocationOwned(mapPos)) + return false; + + TileElement* tileElement = MapGetFirstElementAt(mapPos); + if (tileElement == nullptr) + return false; + do { - if (newestLitterCreationTick <= litter->creationTick) + if (tileElement->GetType() != TileElementType::Path) + continue; + + int32_t pathZ = tileElement->GetBaseZ(); + if (pathZ < mapPos.z || pathZ >= mapPos.z + kPathClearance) + continue; + + return !TileElementIsUnderground(tileElement); + } while (!(tileElement++)->IsLastForTile()); + return false; + } + + /** + * + * rct2: 0x0067375D + */ + void Litter::Create(const CoordsXYZD& litterPos, Type type) + { + auto& gameState = getGameState(); + if (gameState.cheats.disableLittering) + return; + + auto offsetLitterPos = litterPos + + CoordsXY{ CoordsDirectionDelta[litterPos.direction >> 3].x / 8, + CoordsDirectionDelta[litterPos.direction >> 3].y / 8 }; + + if (!IsLocationLitterable(offsetLitterPos)) + return; + + if (gameState.entities.GetEntityListCount(EntityType::litter) >= 500) + { + Litter* newestLitter = nullptr; + uint32_t newestLitterCreationTick = 0; + for (auto litter : EntityList()) { - newestLitterCreationTick = litter->creationTick; - newestLitter = litter; + if (newestLitterCreationTick <= litter->creationTick) + { + newestLitterCreationTick = litter->creationTick; + newestLitter = litter; + } + } + + if (newestLitter != nullptr) + { + newestLitter->Invalidate(); + gameState.entities.EntityRemove(newestLitter); } } - if (newestLitter != nullptr) - { - newestLitter->Invalidate(); - gameState.entities.EntityRemove(newestLitter); - } + Litter* litter = gameState.entities.CreateEntity(); + if (litter == nullptr) + return; + + litter->Orientation = offsetLitterPos.direction; + litter->SpriteData.Width = 6; + litter->SpriteData.HeightMin = 6; + litter->SpriteData.HeightMax = 3; + litter->SubType = type; + litter->MoveTo(offsetLitterPos); + litter->creationTick = gameState.currentTicks; } - Litter* litter = gameState.entities.CreateEntity(); - if (litter == nullptr) - return; - - litter->Orientation = offsetLitterPos.direction; - litter->SpriteData.Width = 6; - litter->SpriteData.HeightMin = 6; - litter->SpriteData.HeightMax = 3; - litter->SubType = type; - litter->MoveTo(offsetLitterPos); - litter->creationTick = gameState.currentTicks; -} - -/** - * - * rct2: 0x006738E1 - */ -void Litter::RemoveAt(const CoordsXYZ& litterPos) -{ - // There can be a lot of litter entities on the same tile, avoid heap allocations - // by having the first 512 stored in a small_vector which is on the stack. - sfl::small_vector removals; - for (auto litter : EntityTileList(litterPos)) + /** + * + * rct2: 0x006738E1 + */ + void Litter::RemoveAt(const CoordsXYZ& litterPos) { - if (abs(litter->z - litterPos.z) <= 16) + // There can be a lot of litter entities on the same tile, avoid heap allocations + // by having the first 512 stored in a small_vector which is on the stack. + sfl::small_vector removals; + for (auto litter : EntityTileList(litterPos)) { - if (abs(litter->x - litterPos.x) <= 8 && abs(litter->y - litterPos.y) <= 8) + if (abs(litter->z - litterPos.z) <= 16) { - removals.push_back(litter); + if (abs(litter->x - litterPos.x) <= 8 && abs(litter->y - litterPos.y) <= 8) + { + removals.push_back(litter); + } } } + for (auto* litter : removals) + { + litter->Invalidate(); + getGameState().entities.EntityRemove(litter); + } } - for (auto* litter : removals) + + static const StringId litterNames[12] = { + STR_LITTER_VOMIT, + STR_LITTER_VOMIT, + STR_SHOP_ITEM_SINGULAR_EMPTY_CAN, + STR_SHOP_ITEM_SINGULAR_RUBBISH, + STR_SHOP_ITEM_SINGULAR_EMPTY_BURGER_BOX, + STR_SHOP_ITEM_SINGULAR_EMPTY_CUP, + STR_SHOP_ITEM_SINGULAR_EMPTY_BOX, + STR_SHOP_ITEM_SINGULAR_EMPTY_BOTTLE, + STR_SHOP_ITEM_SINGULAR_EMPTY_BOWL_RED, + STR_SHOP_ITEM_SINGULAR_EMPTY_DRINK_CARTON, + STR_SHOP_ITEM_SINGULAR_EMPTY_JUICE_CUP, + STR_SHOP_ITEM_SINGULAR_EMPTY_BOWL_BLUE, + }; + + StringId Litter::GetName() const { - litter->Invalidate(); - getGameState().entities.EntityRemove(litter); + if (EnumValue(SubType) >= std::size(litterNames)) + return kStringIdNone; + return litterNames[EnumValue(SubType)]; } -} -static const StringId litterNames[12] = { - STR_LITTER_VOMIT, - STR_LITTER_VOMIT, - STR_SHOP_ITEM_SINGULAR_EMPTY_CAN, - STR_SHOP_ITEM_SINGULAR_RUBBISH, - STR_SHOP_ITEM_SINGULAR_EMPTY_BURGER_BOX, - STR_SHOP_ITEM_SINGULAR_EMPTY_CUP, - STR_SHOP_ITEM_SINGULAR_EMPTY_BOX, - STR_SHOP_ITEM_SINGULAR_EMPTY_BOTTLE, - STR_SHOP_ITEM_SINGULAR_EMPTY_BOWL_RED, - STR_SHOP_ITEM_SINGULAR_EMPTY_DRINK_CARTON, - STR_SHOP_ITEM_SINGULAR_EMPTY_JUICE_CUP, - STR_SHOP_ITEM_SINGULAR_EMPTY_BOWL_BLUE, -}; + uint32_t Litter::GetAge() const + { + return getGameState().currentTicks - creationTick; + } -StringId Litter::GetName() const -{ - if (EnumValue(SubType) >= std::size(litterNames)) - return kStringIdNone; - return litterNames[EnumValue(SubType)]; -} + void Litter::Serialise(DataSerialiser& stream) + { + EntityBase::Serialise(stream); -uint32_t Litter::GetAge() const -{ - return getGameState().currentTicks - creationTick; -} + stream << SubType; + stream << creationTick; + } -void Litter::Serialise(DataSerialiser& stream) -{ - EntityBase::Serialise(stream); + struct LitterSprite + { + uint16_t base_id; + uint8_t direction_mask; + }; - stream << SubType; - stream << creationTick; -} + /** rct2: 0x0097EF6C */ + static constexpr LitterSprite kLitterSprites[] = { + { SPR_LITTER_SICK, 0x1 }, + { SPR_LITTER_SICK_ALT, 0x1 }, + { SPR_LITTER_EMPTY_CAN, 0x1 }, + { SPR_LITTER_RUBBISH, 0x1 }, + { SPR_LITTER_EMPTY_BURGER_BOX, 0x1 }, + { SPR_LITTER_EMPTY_CUP, 0x1 }, + { SPR_LITTER_EMPTY_BOX, 0x1 }, + { SPR_LITTER_EMPTY_BOTTLE, 0x1 }, + { SPR_LITTER_EMPTY_BOWL_RED, 0x3 }, + { SPR_LITTER_EMPTY_DRINK_CART, 0x3 }, + { SPR_LITTER_EMPTY_JUICE_CUP, 0x3 }, + { SPR_LITTER_EMPTY_BOWL_BLUE, 0x3 }, + }; -struct LitterSprite -{ - uint16_t base_id; - uint8_t direction_mask; -}; + void Litter::Paint(PaintSession& session, int32_t imageDirection) const + { + PROFILED_FUNCTION(); -/** rct2: 0x0097EF6C */ -static constexpr LitterSprite kLitterSprites[] = { - { SPR_LITTER_SICK, 0x1 }, - { SPR_LITTER_SICK_ALT, 0x1 }, - { SPR_LITTER_EMPTY_CAN, 0x1 }, - { SPR_LITTER_RUBBISH, 0x1 }, - { SPR_LITTER_EMPTY_BURGER_BOX, 0x1 }, - { SPR_LITTER_EMPTY_CUP, 0x1 }, - { SPR_LITTER_EMPTY_BOX, 0x1 }, - { SPR_LITTER_EMPTY_BOTTLE, 0x1 }, - { SPR_LITTER_EMPTY_BOWL_RED, 0x3 }, - { SPR_LITTER_EMPTY_DRINK_CART, 0x3 }, - { SPR_LITTER_EMPTY_JUICE_CUP, 0x3 }, - { SPR_LITTER_EMPTY_BOWL_BLUE, 0x3 }, -}; + auto& rt = session.rt; + if (rt.zoom_level > ZoomLevel{ 0 }) + return; // If zoomed at all no litter drawn -void Litter::Paint(PaintSession& session, int32_t imageDirection) const -{ - PROFILED_FUNCTION(); + // litter has no sprite direction so remove that + imageDirection >>= 3; + // Some litter types have only 1 direction so remove + // anything that isn't required. + imageDirection &= kLitterSprites[EnumValue(SubType)].direction_mask; - auto& rt = session.rt; - if (rt.zoom_level > ZoomLevel{ 0 }) - return; // If zoomed at all no litter drawn + uint32_t image_id = imageDirection + kLitterSprites[EnumValue(SubType)].base_id; - // litter has no sprite direction so remove that - imageDirection >>= 3; - // Some litter types have only 1 direction so remove - // anything that isn't required. - imageDirection &= kLitterSprites[EnumValue(SubType)].direction_mask; - - uint32_t image_id = imageDirection + kLitterSprites[EnumValue(SubType)].base_id; - - // In the following call to PaintAddImageAsParent, we add 4 (instead of 2) to the - // bound_box_offset_z to make sure litter is drawn on top of railways - PaintAddImageAsParent(session, ImageId(image_id), { 0, 0, z }, { { -4, -4, z + 4 }, { 5, 5, -1 } }); -} + // In the following call to PaintAddImageAsParent, we add 4 (instead of 2) to the + // bound_box_offset_z to make sure litter is drawn on top of railways + PaintAddImageAsParent(session, ImageId(image_id), { 0, 0, z }, { { -4, -4, z + 4 }, { 5, 5, -1 } }); + } +} // namespace OpenRCT2 diff --git a/src/openrct2/entity/Litter.h b/src/openrct2/entity/Litter.h index 3c035e8075..bd06631f61 100644 --- a/src/openrct2/entity/Litter.h +++ b/src/openrct2/entity/Litter.h @@ -19,33 +19,33 @@ struct PaintSession; namespace OpenRCT2 { class DataSerialiser; -} -struct Litter : EntityBase -{ - enum class Type : uint8_t + struct Litter : EntityBase { - vomit, - vomitAlt, - emptyCan, - rubbish, - burgerBox, - emptyCup, - emptyBox, - emptyBottle, - emptyBowlRed, - emptyDrinkCarton, - emptyJuiceCup, - emptyBowlBlue, - }; + enum class Type : uint8_t + { + vomit, + vomitAlt, + emptyCan, + rubbish, + burgerBox, + emptyCup, + emptyBox, + emptyBottle, + emptyBowlRed, + emptyDrinkCarton, + emptyJuiceCup, + emptyBowlBlue, + }; - static constexpr auto cEntityType = EntityType::litter; - Type SubType; - uint32_t creationTick; - static void Create(const CoordsXYZD& litterPos, Type type); - static void RemoveAt(const CoordsXYZ& litterPos); - void Serialise(OpenRCT2::DataSerialiser& stream); - StringId GetName() const; - uint32_t GetAge() const; - void Paint(PaintSession& session, int32_t imageDirection) const; -}; + static constexpr auto cEntityType = EntityType::litter; + Type SubType; + uint32_t creationTick; + static void Create(const CoordsXYZD& litterPos, Type type); + static void RemoveAt(const CoordsXYZ& litterPos); + void Serialise(DataSerialiser& stream); + StringId GetName() const; + uint32_t GetAge() const; + void Paint(PaintSession& session, int32_t imageDirection) const; + }; +} // namespace OpenRCT2 diff --git a/src/openrct2/entity/MoneyEffect.cpp b/src/openrct2/entity/MoneyEffect.cpp index e19ab7115c..d8129cd112 100644 --- a/src/openrct2/entity/MoneyEffect.cpp +++ b/src/openrct2/entity/MoneyEffect.cpp @@ -24,193 +24,194 @@ #include "../world/Map.h" #include "EntityRegistry.h" -using namespace OpenRCT2; - -static constexpr CoordsXY kMoneyEffectMoveOffset[] = { - { 1, -1 }, - { 1, 1 }, - { -1, 1 }, - { -1, -1 }, -}; - -template<> -bool EntityBase::Is() const +namespace OpenRCT2 { - return Type == EntityType::moneyEffect; -} + static constexpr CoordsXY kMoneyEffectMoveOffset[] = { + { 1, -1 }, + { 1, 1 }, + { -1, 1 }, + { -1, -1 }, + }; -/** - * - * rct2: 0x0067351F - */ -void MoneyEffect::CreateAt(money64 value, const CoordsXYZ& effectPos, bool guestPurchase) -{ - if (value == 0.00_GBP) - return; - - MoneyEffect* moneyEffect = getGameState().entities.CreateEntity(); - if (moneyEffect == nullptr) - return; - - moneyEffect->GuestPurchase = (guestPurchase ? 1 : 0); - moneyEffect->MoveTo(effectPos); - moneyEffect->SetValue(value); -} - -/** - * - * rct2: 0x0069C5D0 - */ -void MoneyEffect::Create(money64 value, const CoordsXYZ& loc) -{ - auto offsetLoc = loc; - if (loc.IsNull()) + template<> + bool EntityBase::Is() const { - // If game actions return no valid location of the action we can not use the screen - // coordinates as every client will have different ones. - if (Network::GetMode() != Network::Mode::none) + return Type == EntityType::moneyEffect; + } + + /** + * + * rct2: 0x0067351F + */ + void MoneyEffect::CreateAt(money64 value, const CoordsXYZ& effectPos, bool guestPurchase) + { + if (value == 0.00_GBP) + return; + + MoneyEffect* moneyEffect = getGameState().entities.CreateEntity(); + if (moneyEffect == nullptr) + return; + + moneyEffect->GuestPurchase = (guestPurchase ? 1 : 0); + moneyEffect->MoveTo(effectPos); + moneyEffect->SetValue(value); + } + + /** + * + * rct2: 0x0069C5D0 + */ + void MoneyEffect::Create(money64 value, const CoordsXYZ& loc) + { + auto offsetLoc = loc; + if (loc.IsNull()) { - LOG_WARNING("Attempted to create money effect without a valid location in multiplayer"); - return; + // If game actions return no valid location of the action we can not use the screen + // coordinates as every client will have different ones. + if (Network::GetMode() != Network::Mode::none) + { + LOG_WARNING("Attempted to create money effect without a valid location in multiplayer"); + return; + } + + WindowBase* mainWindow = WindowGetMain(); + if (mainWindow == nullptr) + return; + + Viewport* mainViewport = WindowGetViewport(mainWindow); + auto mapPositionXY = ScreenGetMapXY( + { mainViewport->pos.x + (mainViewport->width / 2), mainViewport->pos.y + (mainViewport->height / 2) }, nullptr); + if (!mapPositionXY.has_value()) + return; + + offsetLoc = { mapPositionXY.value(), TileElementHeight(*mapPositionXY) }; } - - WindowBase* mainWindow = WindowGetMain(); - if (mainWindow == nullptr) - return; - - Viewport* mainViewport = WindowGetViewport(mainWindow); - auto mapPositionXY = ScreenGetMapXY( - { mainViewport->pos.x + (mainViewport->width / 2), mainViewport->pos.y + (mainViewport->height / 2) }, nullptr); - if (!mapPositionXY.has_value()) - return; - - offsetLoc = { mapPositionXY.value(), TileElementHeight(*mapPositionXY) }; + offsetLoc.z += 10; + CreateAt(-value, offsetLoc, false); } - offsetLoc.z += 10; - CreateAt(-value, offsetLoc, false); -} -/** - * Set the value of the money effect - */ -void MoneyEffect::SetValue(money64 value) -{ - Value = value; - SpriteData.Width = 64; - SpriteData.HeightMin = 20; - SpriteData.HeightMax = 30; - MoveDelay = 0; - NumMovements = 0; - - int16_t offsetX = 0; - if (!gOpenRCT2NoGraphics) + /** + * Set the value of the money effect + */ + void MoneyEffect::SetValue(money64 value) { - auto [stringId, newValue] = GetStringId(); - char buffer[128]; - FormatStringLegacy(buffer, 128, stringId, &newValue); - offsetX = -(GfxGetStringWidth(buffer, FontStyle::medium) / 2); - } - OffsetX = offsetX; - Wiggle = 0; -} + Value = value; + SpriteData.Width = 64; + SpriteData.HeightMin = 20; + SpriteData.HeightMax = 30; + MoveDelay = 0; + NumMovements = 0; -/** - * - * rct2: 0x00673232 - */ -void MoneyEffect::Update() -{ - Wiggle++; - if (Wiggle >= 22) - { + int16_t offsetX = 0; + if (!gOpenRCT2NoGraphics) + { + auto [stringId, newValue] = GetStringId(); + char buffer[128]; + FormatStringLegacy(buffer, 128, stringId, &newValue); + offsetX = -(GfxGetStringWidth(buffer, FontStyle::medium) / 2); + } + OffsetX = offsetX; Wiggle = 0; } - MoveDelay++; - if (MoveDelay < 2) + /** + * + * rct2: 0x00673232 + */ + void MoneyEffect::Update() { - return; + Wiggle++; + if (Wiggle >= 22) + { + Wiggle = 0; + } + + MoveDelay++; + if (MoveDelay < 2) + { + return; + } + + int32_t newX = x; + int32_t newY = y; + int32_t newZ = z; + MoveDelay = 0; + + if (GuestPurchase) + { + newZ += 1; + } + newY += kMoneyEffectMoveOffset[GetCurrentRotation()].y; + newX += kMoneyEffectMoveOffset[GetCurrentRotation()].x; + + MoveTo({ newX, newY, newZ }); + + NumMovements++; + if (NumMovements < 55) + { + return; + } + + getGameState().entities.EntityRemove(this); } - int32_t newX = x; - int32_t newY = y; - int32_t newZ = z; - MoveDelay = 0; - - if (GuestPurchase) + std::pair MoneyEffect::GetStringId() const { - newZ += 1; - } - newY += kMoneyEffectMoveOffset[GetCurrentRotation()].y; - newX += kMoneyEffectMoveOffset[GetCurrentRotation()].x; + StringId spentStringId = GuestPurchase ? STR_MONEY_EFFECT_SPEND_HIGHP : STR_MONEY_EFFECT_SPEND; + StringId receiveStringId = GuestPurchase ? STR_MONEY_EFFECT_RECEIVE_HIGHP : STR_MONEY_EFFECT_RECEIVE; + StringId stringId = receiveStringId; + money64 outValue = Value; + if (Value < 0) + { + outValue *= -1; + stringId = spentStringId; + } - MoveTo({ newX, newY, newZ }); - - NumMovements++; - if (NumMovements < 55) - { - return; + return std::make_pair(stringId, outValue); } - getGameState().entities.EntityRemove(this); -} - -std::pair MoneyEffect::GetStringId() const -{ - StringId spentStringId = GuestPurchase ? STR_MONEY_EFFECT_SPEND_HIGHP : STR_MONEY_EFFECT_SPEND; - StringId receiveStringId = GuestPurchase ? STR_MONEY_EFFECT_RECEIVE_HIGHP : STR_MONEY_EFFECT_RECEIVE; - StringId stringId = receiveStringId; - money64 outValue = Value; - if (Value < 0) + void MoneyEffect::Serialise(DataSerialiser& stream) { - outValue *= -1; - stringId = spentStringId; + EntityBase::Serialise(stream); + stream << frame; + stream << MoveDelay; + stream << NumMovements; + stream << GuestPurchase; + stream << Value; + stream << OffsetX; + stream << Wiggle; } - return std::make_pair(stringId, outValue); -} - -void MoneyEffect::Serialise(DataSerialiser& stream) -{ - EntityBase::Serialise(stream); - stream << frame; - stream << MoveDelay; - stream << NumMovements; - stream << GuestPurchase; - stream << Value; - stream << OffsetX; - stream << Wiggle; -} - -void MoneyEffect::Paint(PaintSession& session, int32_t imageDirection) const -{ - PROFILED_FUNCTION(); - - if (gLegacyScene == LegacyScene::titleSequence) + void MoneyEffect::Paint(PaintSession& session, int32_t imageDirection) const { - // Don't render any money in the title screen. - return; + PROFILED_FUNCTION(); + + if (gLegacyScene == LegacyScene::titleSequence) + { + // Don't render any money in the title screen. + return; + } + + if (GuestPurchase && !Config::Get().general.showGuestPurchases) + { + // Don't show the money effect for guest purchases when the option is disabled. + return; + } + + auto& rt = session.rt; + if (rt.zoom_level > ZoomLevel{ 0 }) + { + return; + } + + /** rct2: 0x0097EDA4 */ + static constexpr int8_t waveOffset[] = { + 0, 1, 2, 2, 3, 3, 3, 3, 2, 2, 1, 0, -1, -2, -2, -3, -3, -3, -3, -2, -2, -1, + 0, 1, 2, 2, 3, 3, 3, 3, 2, 2, 1, 0, -1, -2, -2, -3, -3, -3, -3, -2, -2, -1, + }; + + auto [stringId, value] = GetStringId(); + PaintFloatingMoneyEffect( + session, value, stringId, y, z, const_cast(&waveOffset[Wiggle % 22]), OffsetX, session.CurrentRotation); } - - if (GuestPurchase && !Config::Get().general.showGuestPurchases) - { - // Don't show the money effect for guest purchases when the option is disabled. - return; - } - - auto& rt = session.rt; - if (rt.zoom_level > ZoomLevel{ 0 }) - { - return; - } - - /** rct2: 0x0097EDA4 */ - static constexpr int8_t waveOffset[] = { - 0, 1, 2, 2, 3, 3, 3, 3, 2, 2, 1, 0, -1, -2, -2, -3, -3, -3, -3, -2, -2, -1, - 0, 1, 2, 2, 3, 3, 3, 3, 2, 2, 1, 0, -1, -2, -2, -3, -3, -3, -3, -2, -2, -1, - }; - - auto [stringId, value] = GetStringId(); - PaintFloatingMoneyEffect( - session, value, stringId, y, z, const_cast(&waveOffset[Wiggle % 22]), OffsetX, session.CurrentRotation); -} +} // namespace OpenRCT2 diff --git a/src/openrct2/entity/MoneyEffect.h b/src/openrct2/entity/MoneyEffect.h index f8b27e3900..0dbd3d1254 100644 --- a/src/openrct2/entity/MoneyEffect.h +++ b/src/openrct2/entity/MoneyEffect.h @@ -21,25 +21,25 @@ struct PaintSession; namespace OpenRCT2 { class DataSerialiser; -} -struct MoneyEffect : EntityBase -{ - static constexpr auto cEntityType = EntityType::moneyEffect; + struct MoneyEffect : EntityBase + { + static constexpr auto cEntityType = EntityType::moneyEffect; - uint16_t frame; - uint16_t MoveDelay; - uint8_t NumMovements; - uint8_t GuestPurchase; - money64 Value; - int16_t OffsetX; - uint16_t Wiggle; + uint16_t frame; + uint16_t MoveDelay; + uint8_t NumMovements; + uint8_t GuestPurchase; + money64 Value; + int16_t OffsetX; + uint16_t Wiggle; - static void CreateAt(money64 value, const CoordsXYZ& effectPos, bool guestPurchase); - static void Create(money64 value, const CoordsXYZ& loc); - void SetValue(money64 value); - void Update(); - std::pair GetStringId() const; - void Serialise(OpenRCT2::DataSerialiser& stream); - void Paint(PaintSession& session, int32_t imageDirection) const; -}; + static void CreateAt(money64 value, const CoordsXYZ& effectPos, bool guestPurchase); + static void Create(money64 value, const CoordsXYZ& loc); + void SetValue(money64 value); + void Update(); + std::pair GetStringId() const; + void Serialise(DataSerialiser& stream); + void Paint(PaintSession& session, int32_t imageDirection) const; + }; +} // namespace OpenRCT2 diff --git a/src/openrct2/entity/Particle.cpp b/src/openrct2/entity/Particle.cpp index 6db88b209f..5260e2c468 100644 --- a/src/openrct2/entity/Particle.cpp +++ b/src/openrct2/entity/Particle.cpp @@ -22,360 +22,361 @@ #include -using namespace OpenRCT2; - -static constexpr uint32_t kVehicleCrashParticleSprites[kCrashedVehicleParticleNumberTypes] = { - SPR_VEHICLE_CRASH_PARTICLE_1, SPR_VEHICLE_CRASH_PARTICLE_2, SPR_VEHICLE_CRASH_PARTICLE_3, - SPR_VEHICLE_CRASH_PARTICLE_4, SPR_VEHICLE_CRASH_PARTICLE_5, -}; - -template<> -bool EntityBase::Is() const +namespace OpenRCT2 { - return Type == EntityType::steamParticle; -} + static constexpr uint32_t kVehicleCrashParticleSprites[kCrashedVehicleParticleNumberTypes] = { + SPR_VEHICLE_CRASH_PARTICLE_1, SPR_VEHICLE_CRASH_PARTICLE_2, SPR_VEHICLE_CRASH_PARTICLE_3, + SPR_VEHICLE_CRASH_PARTICLE_4, SPR_VEHICLE_CRASH_PARTICLE_5, + }; -template<> -bool EntityBase::Is() const -{ - return Type == EntityType::explosionFlare; -} - -template<> -bool EntityBase::Is() const -{ - return Type == EntityType::explosionCloud; -} - -template<> -bool EntityBase::Is() const -{ - return Type == EntityType::crashedVehicleParticle; -} - -template<> -bool EntityBase::Is() const -{ - return Type == EntityType::crashSplash; -} - -void VehicleCrashParticle::SetSpriteData() -{ - SpriteData.Width = 8; - SpriteData.HeightMin = 8; - SpriteData.HeightMax = 8; -} - -void VehicleCrashParticle::Launch() -{ - frame = (ScenarioRand() & 0xFF) * kCrashedVehicleParticleNumberSprites; - time_to_live = (ScenarioRand() & 0x7F) + 140; - crashed_sprite_base = ScenarioRandMax(kCrashedVehicleParticleNumberTypes); - acceleration_x = (static_cast(ScenarioRand() & 0xFFFF)) * 4; - acceleration_y = (static_cast(ScenarioRand() & 0xFFFF)) * 4; - acceleration_z = (ScenarioRand() & 0xFFFF) * 4 + 0x10000; - velocity_x = 0; - velocity_y = 0; - velocity_z = 0; -} - -/** - * - * rct2: 0x006735A1 - */ -void VehicleCrashParticle::Create(VehicleColour& colours, const CoordsXYZ& vehiclePos) -{ - VehicleCrashParticle* sprite = getGameState().entities.CreateEntity(); - if (sprite != nullptr) + template<> + bool EntityBase::Is() const { - sprite->MoveTo(vehiclePos); - sprite->colour[0] = colours.Body; - sprite->colour[1] = colours.Trim; - sprite->SetSpriteData(); - sprite->Launch(); - } -} - -/** - * - * rct2: 0x00673298 - */ -void VehicleCrashParticle::Update() -{ - Invalidate(); - time_to_live--; - if (time_to_live == 0) - { - getGameState().entities.EntityRemove(this); - return; + return Type == EntityType::steamParticle; } - // Apply gravity - acceleration_z -= 5041; - - // Apply air resistance - acceleration_x -= (acceleration_x / 256); - acceleration_y -= (acceleration_y / 256); - acceleration_z -= (acceleration_z / 256); - - // Update velocity and position - int32_t vx = velocity_x + acceleration_x; - int32_t vy = velocity_y + acceleration_y; - int32_t vz = velocity_z + acceleration_z; - - CoordsXYZ newLoc = { x + (vx >> 16), y + (vy >> 16), z + (vz >> 16) }; - - velocity_x = vx & 0xFFFF; - velocity_y = vy & 0xFFFF; - velocity_z = vz & 0xFFFF; - - // Check collision with land / water - int16_t landZ = TileElementHeight(newLoc); - int16_t waterZ = TileElementWaterHeight(newLoc); - - if (waterZ != 0 && z >= waterZ && newLoc.z <= waterZ) + template<> + bool EntityBase::Is() const { - // Splash - Audio::Play3D(Audio::SoundId::water2, { x, y, waterZ }); - CrashSplashParticle::Create({ x, y, waterZ }); - getGameState().entities.EntityRemove(this); - return; + return Type == EntityType::explosionFlare; } - if (z >= landZ && newLoc.z <= landZ) + template<> + bool EntityBase::Is() const { - // Bounce - acceleration_z *= -1; - newLoc.z = landZ; - } - MoveTo(newLoc); - - frame += kCrashedVehicleParticleFrameIncrement; - if (frame >= (kCrashedVehicleParticleNumberSprites * kCrashedVehicleParticleFrameToSprite)) - { - frame = 0; - } -} - -void VehicleCrashParticle::Serialise(DataSerialiser& stream) -{ - EntityBase::Serialise(stream); - stream << frame; - stream << time_to_live; - stream << colour; - stream << crashed_sprite_base; - stream << velocity_x; - stream << velocity_y; - stream << velocity_z; - stream << acceleration_x; - stream << acceleration_y; - stream << acceleration_z; -} - -void VehicleCrashParticle::Paint(PaintSession& session, int32_t imageDirection) const -{ - PROFILED_FUNCTION(); - - auto& rt = session.rt; - if (rt.zoom_level > ZoomLevel{ 0 }) - { - return; + return Type == EntityType::explosionCloud; } - uint32_t imageId = kVehicleCrashParticleSprites[crashed_sprite_base] + frame / 256; - auto image = ImageId(imageId, colour[0], colour[1]); - PaintAddImageAsParent(session, image, { 0, 0, z }, { 1, 1, 0 }); -} - -/** - * - * rct2: 0x00673699 - */ -void CrashSplashParticle::Create(const CoordsXYZ& splashPos) -{ - auto* sprite = getGameState().entities.CreateEntity(); - if (sprite != nullptr) + template<> + bool EntityBase::Is() const { - sprite->SpriteData.Width = 33; - sprite->SpriteData.HeightMin = 51; - sprite->SpriteData.HeightMax = 16; - sprite->MoveTo(splashPos + CoordsXYZ{ 0, 0, 3 }); - sprite->frame = 0; + return Type == EntityType::crashedVehicleParticle; } -} -/** - * - * rct2: 0x0067339D - */ -void CrashSplashParticle::Update() -{ - Invalidate(); - frame += 85; - if (frame >= 7168) + template<> + bool EntityBase::Is() const { - getGameState().entities.EntityRemove(this); + return Type == EntityType::crashSplash; } -} -void CrashSplashParticle::Serialise(DataSerialiser& stream) -{ - EntityBase::Serialise(stream); - stream << frame; -} - -void CrashSplashParticle::Paint(PaintSession& session, int32_t imageDirection) const -{ - PROFILED_FUNCTION(); - - uint32_t imageId = SPR_CRASH_SPLASH_PARTICLE + (frame / 256); - PaintAddImageAsParent(session, ImageId(imageId), { 0, 0, z }, { 1, 1, 0 }); -} - -/** - * - * rct2: 0x006734B2 - */ -void SteamParticle::Create(const CoordsXYZ& coords) -{ - auto surfaceElement = MapGetSurfaceElementAt(coords); - if (surfaceElement != nullptr && coords.z > surfaceElement->GetBaseZ()) + void VehicleCrashParticle::SetSpriteData() { - SteamParticle* steam = getGameState().entities.CreateEntity(); - if (steam == nullptr) + SpriteData.Width = 8; + SpriteData.HeightMin = 8; + SpriteData.HeightMax = 8; + } + + void VehicleCrashParticle::Launch() + { + frame = (ScenarioRand() & 0xFF) * kCrashedVehicleParticleNumberSprites; + time_to_live = (ScenarioRand() & 0x7F) + 140; + crashed_sprite_base = ScenarioRandMax(kCrashedVehicleParticleNumberTypes); + acceleration_x = (static_cast(ScenarioRand() & 0xFFFF)) * 4; + acceleration_y = (static_cast(ScenarioRand() & 0xFFFF)) * 4; + acceleration_z = (ScenarioRand() & 0xFFFF) * 4 + 0x10000; + velocity_x = 0; + velocity_y = 0; + velocity_z = 0; + } + + /** + * + * rct2: 0x006735A1 + */ + void VehicleCrashParticle::Create(VehicleColour& colours, const CoordsXYZ& vehiclePos) + { + VehicleCrashParticle* sprite = getGameState().entities.CreateEntity(); + if (sprite != nullptr) + { + sprite->MoveTo(vehiclePos); + sprite->colour[0] = colours.Body; + sprite->colour[1] = colours.Trim; + sprite->SetSpriteData(); + sprite->Launch(); + } + } + + /** + * + * rct2: 0x00673298 + */ + void VehicleCrashParticle::Update() + { + Invalidate(); + time_to_live--; + if (time_to_live == 0) + { + getGameState().entities.EntityRemove(this); return; + } - steam->SpriteData.Width = 20; - steam->SpriteData.HeightMin = 18; - steam->SpriteData.HeightMax = 16; - steam->frame = 256; - steam->time_to_move = 0; - steam->MoveTo(coords); + // Apply gravity + acceleration_z -= 5041; + + // Apply air resistance + acceleration_x -= (acceleration_x / 256); + acceleration_y -= (acceleration_y / 256); + acceleration_z -= (acceleration_z / 256); + + // Update velocity and position + int32_t vx = velocity_x + acceleration_x; + int32_t vy = velocity_y + acceleration_y; + int32_t vz = velocity_z + acceleration_z; + + CoordsXYZ newLoc = { x + (vx >> 16), y + (vy >> 16), z + (vz >> 16) }; + + velocity_x = vx & 0xFFFF; + velocity_y = vy & 0xFFFF; + velocity_z = vz & 0xFFFF; + + // Check collision with land / water + int16_t landZ = TileElementHeight(newLoc); + int16_t waterZ = TileElementWaterHeight(newLoc); + + if (waterZ != 0 && z >= waterZ && newLoc.z <= waterZ) + { + // Splash + Audio::Play3D(Audio::SoundId::water2, { x, y, waterZ }); + CrashSplashParticle::Create({ x, y, waterZ }); + getGameState().entities.EntityRemove(this); + return; + } + + if (z >= landZ && newLoc.z <= landZ) + { + // Bounce + acceleration_z *= -1; + newLoc.z = landZ; + } + MoveTo(newLoc); + + frame += kCrashedVehicleParticleFrameIncrement; + if (frame >= (kCrashedVehicleParticleNumberSprites * kCrashedVehicleParticleFrameToSprite)) + { + frame = 0; + } } -} -/** - * - * rct2: 0x00673200 - */ -void SteamParticle::Update() -{ - // Move up 1 z every 3 ticks (Starts after 4 ticks) - Invalidate(); - time_to_move++; - if (time_to_move >= 4) + void VehicleCrashParticle::Serialise(DataSerialiser& stream) { - time_to_move = 1; - MoveTo({ x, y, z + 1 }); + EntityBase::Serialise(stream); + stream << frame; + stream << time_to_live; + stream << colour; + stream << crashed_sprite_base; + stream << velocity_x; + stream << velocity_y; + stream << velocity_z; + stream << acceleration_x; + stream << acceleration_y; + stream << acceleration_z; } - frame += 64; - if (frame >= (56 * 64)) + + void VehicleCrashParticle::Paint(PaintSession& session, int32_t imageDirection) const { - getGameState().entities.EntityRemove(this); + PROFILED_FUNCTION(); + + auto& rt = session.rt; + if (rt.zoom_level > ZoomLevel{ 0 }) + { + return; + } + + uint32_t imageId = kVehicleCrashParticleSprites[crashed_sprite_base] + frame / 256; + auto image = ImageId(imageId, colour[0], colour[1]); + PaintAddImageAsParent(session, image, { 0, 0, z }, { 1, 1, 0 }); } -} -void SteamParticle::Serialise(DataSerialiser& stream) -{ - EntityBase::Serialise(stream); - stream << frame; - stream << time_to_move; -} - -void SteamParticle::Paint(PaintSession& session, int32_t imageDirection) const -{ - PROFILED_FUNCTION(); - - uint32_t imageId = SPR_STEAM_PARTICLE + (frame / 256); - PaintAddImageAsParent(session, ImageId(imageId), { 0, 0, z }, { 1, 1, 0 }); -} - -/** - * - * rct2: 0x0067363D - */ -void ExplosionCloud::Create(const CoordsXYZ& cloudPos) -{ - auto* entity = getGameState().entities.CreateEntity(); - if (entity != nullptr) + /** + * + * rct2: 0x00673699 + */ + void CrashSplashParticle::Create(const CoordsXYZ& splashPos) { - entity->SpriteData.Width = 44; - entity->SpriteData.HeightMin = 32; - entity->SpriteData.HeightMax = 34; - entity->MoveTo(cloudPos + CoordsXYZ{ 0, 0, 4 }); - entity->frame = 0; + auto* sprite = getGameState().entities.CreateEntity(); + if (sprite != nullptr) + { + sprite->SpriteData.Width = 33; + sprite->SpriteData.HeightMin = 51; + sprite->SpriteData.HeightMax = 16; + sprite->MoveTo(splashPos + CoordsXYZ{ 0, 0, 3 }); + sprite->frame = 0; + } } -} -/** - * - * rct2: 0x00673385 - */ -void ExplosionCloud::Update() -{ - Invalidate(); - frame += 128; - if (frame >= (36 * 128)) + /** + * + * rct2: 0x0067339D + */ + void CrashSplashParticle::Update() { - getGameState().entities.EntityRemove(this); + Invalidate(); + frame += 85; + if (frame >= 7168) + { + getGameState().entities.EntityRemove(this); + } } -} -void ExplosionCloud::Serialise(DataSerialiser& stream) -{ - EntityBase::Serialise(stream); - stream << frame; -} - -void ExplosionCloud::Paint(PaintSession& session, int32_t imageDirection) const -{ - PROFILED_FUNCTION(); - - uint32_t imageId = SPR_EXPLOSION_CLOUD + (frame / 256); - PaintAddImageAsParent(session, ImageId(imageId), { 0, 0, z }, { 1, 1, 0 }); -} - -/** - * - * rct2: 0x0067366B - */ -void ExplosionFlare::Create(const CoordsXYZ& flarePos) -{ - auto* entity = getGameState().entities.CreateEntity(); - if (entity != nullptr) + void CrashSplashParticle::Serialise(DataSerialiser& stream) { - entity->SpriteData.Width = 25; - entity->SpriteData.HeightMin = 85; - entity->SpriteData.HeightMax = 8; - entity->MoveTo(flarePos + CoordsXYZ{ 0, 0, 4 }); - entity->frame = 0; + EntityBase::Serialise(stream); + stream << frame; } -} -/** - * - * rct2: 0x006733B4 - */ -void ExplosionFlare::Update() -{ - Invalidate(); - frame += 64; - if (frame >= (124 * 64)) + void CrashSplashParticle::Paint(PaintSession& session, int32_t imageDirection) const { - getGameState().entities.EntityRemove(this); + PROFILED_FUNCTION(); + + uint32_t imageId = SPR_CRASH_SPLASH_PARTICLE + (frame / 256); + PaintAddImageAsParent(session, ImageId(imageId), { 0, 0, z }, { 1, 1, 0 }); } -} -void ExplosionFlare::Serialise(DataSerialiser& stream) -{ - EntityBase::Serialise(stream); - stream << frame; -} + /** + * + * rct2: 0x006734B2 + */ + void SteamParticle::Create(const CoordsXYZ& coords) + { + auto surfaceElement = MapGetSurfaceElementAt(coords); + if (surfaceElement != nullptr && coords.z > surfaceElement->GetBaseZ()) + { + SteamParticle* steam = getGameState().entities.CreateEntity(); + if (steam == nullptr) + return; -void ExplosionFlare::Paint(PaintSession& session, int32_t imageDirection) const -{ - PROFILED_FUNCTION(); + steam->SpriteData.Width = 20; + steam->SpriteData.HeightMin = 18; + steam->SpriteData.HeightMax = 16; + steam->frame = 256; + steam->time_to_move = 0; + steam->MoveTo(coords); + } + } - uint32_t imageId = SPR_EXPLOSION_FLARE + (frame / 256); - PaintAddImageAsParent(session, ImageId(imageId), { 0, 0, z }, { 1, 1, 0 }); -} + /** + * + * rct2: 0x00673200 + */ + void SteamParticle::Update() + { + // Move up 1 z every 3 ticks (Starts after 4 ticks) + Invalidate(); + time_to_move++; + if (time_to_move >= 4) + { + time_to_move = 1; + MoveTo({ x, y, z + 1 }); + } + frame += 64; + if (frame >= (56 * 64)) + { + getGameState().entities.EntityRemove(this); + } + } + + void SteamParticle::Serialise(DataSerialiser& stream) + { + EntityBase::Serialise(stream); + stream << frame; + stream << time_to_move; + } + + void SteamParticle::Paint(PaintSession& session, int32_t imageDirection) const + { + PROFILED_FUNCTION(); + + uint32_t imageId = SPR_STEAM_PARTICLE + (frame / 256); + PaintAddImageAsParent(session, ImageId(imageId), { 0, 0, z }, { 1, 1, 0 }); + } + + /** + * + * rct2: 0x0067363D + */ + void ExplosionCloud::Create(const CoordsXYZ& cloudPos) + { + auto* entity = getGameState().entities.CreateEntity(); + if (entity != nullptr) + { + entity->SpriteData.Width = 44; + entity->SpriteData.HeightMin = 32; + entity->SpriteData.HeightMax = 34; + entity->MoveTo(cloudPos + CoordsXYZ{ 0, 0, 4 }); + entity->frame = 0; + } + } + + /** + * + * rct2: 0x00673385 + */ + void ExplosionCloud::Update() + { + Invalidate(); + frame += 128; + if (frame >= (36 * 128)) + { + getGameState().entities.EntityRemove(this); + } + } + + void ExplosionCloud::Serialise(DataSerialiser& stream) + { + EntityBase::Serialise(stream); + stream << frame; + } + + void ExplosionCloud::Paint(PaintSession& session, int32_t imageDirection) const + { + PROFILED_FUNCTION(); + + uint32_t imageId = SPR_EXPLOSION_CLOUD + (frame / 256); + PaintAddImageAsParent(session, ImageId(imageId), { 0, 0, z }, { 1, 1, 0 }); + } + + /** + * + * rct2: 0x0067366B + */ + void ExplosionFlare::Create(const CoordsXYZ& flarePos) + { + auto* entity = getGameState().entities.CreateEntity(); + if (entity != nullptr) + { + entity->SpriteData.Width = 25; + entity->SpriteData.HeightMin = 85; + entity->SpriteData.HeightMax = 8; + entity->MoveTo(flarePos + CoordsXYZ{ 0, 0, 4 }); + entity->frame = 0; + } + } + + /** + * + * rct2: 0x006733B4 + */ + void ExplosionFlare::Update() + { + Invalidate(); + frame += 64; + if (frame >= (124 * 64)) + { + getGameState().entities.EntityRemove(this); + } + } + + void ExplosionFlare::Serialise(DataSerialiser& stream) + { + EntityBase::Serialise(stream); + stream << frame; + } + + void ExplosionFlare::Paint(PaintSession& session, int32_t imageDirection) const + { + PROFILED_FUNCTION(); + + uint32_t imageId = SPR_EXPLOSION_FLARE + (frame / 256); + PaintAddImageAsParent(session, ImageId(imageId), { 0, 0, z }, { 1, 1, 0 }); + } +} // namespace OpenRCT2 diff --git a/src/openrct2/entity/Particle.h b/src/openrct2/entity/Particle.h index ab947e6a97..e0d5f6c633 100644 --- a/src/openrct2/entity/Particle.h +++ b/src/openrct2/entity/Particle.h @@ -15,80 +15,80 @@ struct CoordsXYZ; struct PaintSession; struct VehicleColour; -namespace OpenRCT2 -{ - class DataSerialiser; -} - namespace OpenRCT2::Drawing { enum class Colour : uint8_t; } -constexpr int32_t kCrashedVehicleParticleFrameToSprite = 256; -constexpr int32_t kCrashedVehicleParticleNumberSprites = 12; -constexpr int32_t kCrashedVehicleParticleNumberTypes = 5; -constexpr int32_t kCrashedVehicleParticleFrameIncrement = 85; // 1/3 of 256, rounded up - -struct VehicleCrashParticle : EntityBase +namespace OpenRCT2 { - static constexpr auto cEntityType = EntityType::crashedVehicleParticle; - uint16_t frame; - uint16_t time_to_live; - OpenRCT2::Drawing::Colour colour[2]; - uint16_t crashed_sprite_base; - int16_t velocity_x; - int16_t velocity_y; - int16_t velocity_z; - int32_t acceleration_x; - int32_t acceleration_y; - int32_t acceleration_z; - static void Create(VehicleColour& colours, const CoordsXYZ& vehiclePos); - void SetSpriteData(); - void Launch(); - void Update(); - void Serialise(OpenRCT2::DataSerialiser& stream); - void Paint(PaintSession& session, int32_t imageDirection) const; -}; + class DataSerialiser; -struct CrashSplashParticle : EntityBase -{ - static constexpr auto cEntityType = EntityType::crashSplash; - uint16_t frame; - static void Create(const CoordsXYZ& splashPos); - void Update(); - void Serialise(OpenRCT2::DataSerialiser& stream); - void Paint(PaintSession& session, int32_t imageDirection) const; -}; + constexpr int32_t kCrashedVehicleParticleFrameToSprite = 256; + constexpr int32_t kCrashedVehicleParticleNumberSprites = 12; + constexpr int32_t kCrashedVehicleParticleNumberTypes = 5; + constexpr int32_t kCrashedVehicleParticleFrameIncrement = 85; // 1/3 of 256, rounded up -struct ExplosionFlare : EntityBase -{ - static constexpr auto cEntityType = EntityType::explosionFlare; - uint16_t frame; - static void Create(const CoordsXYZ& flarePos); - void Update(); - void Serialise(OpenRCT2::DataSerialiser& stream); - void Paint(PaintSession& session, int32_t imageDirection) const; -}; + struct VehicleCrashParticle : EntityBase + { + static constexpr auto cEntityType = EntityType::crashedVehicleParticle; + uint16_t frame; + uint16_t time_to_live; + Drawing::Colour colour[2]; + uint16_t crashed_sprite_base; + int16_t velocity_x; + int16_t velocity_y; + int16_t velocity_z; + int32_t acceleration_x; + int32_t acceleration_y; + int32_t acceleration_z; + static void Create(VehicleColour& colours, const CoordsXYZ& vehiclePos); + void SetSpriteData(); + void Launch(); + void Update(); + void Serialise(DataSerialiser& stream); + void Paint(PaintSession& session, int32_t imageDirection) const; + }; -struct ExplosionCloud : EntityBase -{ - static constexpr auto cEntityType = EntityType::explosionCloud; - uint16_t frame; - static void Create(const CoordsXYZ& cloudPos); - void Update(); - void Serialise(OpenRCT2::DataSerialiser& stream); - void Paint(PaintSession& session, int32_t imageDirection) const; -}; + struct CrashSplashParticle : EntityBase + { + static constexpr auto cEntityType = EntityType::crashSplash; + uint16_t frame; + static void Create(const CoordsXYZ& splashPos); + void Update(); + void Serialise(DataSerialiser& stream); + void Paint(PaintSession& session, int32_t imageDirection) const; + }; -struct SteamParticle : EntityBase -{ - static constexpr auto cEntityType = EntityType::steamParticle; - uint16_t frame; - uint16_t time_to_move; + struct ExplosionFlare : EntityBase + { + static constexpr auto cEntityType = EntityType::explosionFlare; + uint16_t frame; + static void Create(const CoordsXYZ& flarePos); + void Update(); + void Serialise(DataSerialiser& stream); + void Paint(PaintSession& session, int32_t imageDirection) const; + }; - static void Create(const CoordsXYZ& coords); - void Update(); - void Serialise(OpenRCT2::DataSerialiser& stream); - void Paint(PaintSession& session, int32_t imageDirection) const; -}; + struct ExplosionCloud : EntityBase + { + static constexpr auto cEntityType = EntityType::explosionCloud; + uint16_t frame; + static void Create(const CoordsXYZ& cloudPos); + void Update(); + void Serialise(DataSerialiser& stream); + void Paint(PaintSession& session, int32_t imageDirection) const; + }; + + struct SteamParticle : EntityBase + { + static constexpr auto cEntityType = EntityType::steamParticle; + uint16_t frame; + uint16_t time_to_move; + + static void Create(const CoordsXYZ& coords); + void Update(); + void Serialise(DataSerialiser& stream); + void Paint(PaintSession& session, int32_t imageDirection) const; + }; +} // namespace OpenRCT2 diff --git a/src/openrct2/entity/PatrolArea.cpp b/src/openrct2/entity/PatrolArea.cpp index eabe83e1a2..b44154f6d5 100644 --- a/src/openrct2/entity/PatrolArea.cpp +++ b/src/openrct2/entity/PatrolArea.cpp @@ -15,169 +15,171 @@ #include -using namespace OpenRCT2; -using namespace OpenRCT2::Core; - -static PatrolArea _consolidatedPatrolArea[EnumValue(StaffType::count)]; -static std::variant _patrolAreaToRender; - -static bool CompareTileCoordsXY(const TileCoordsXY& lhs, const TileCoordsXY& rhs) +namespace OpenRCT2 { - if (lhs.y == rhs.y) - return lhs.x < rhs.x; - return lhs.y < rhs.y; -} + using namespace OpenRCT2::Core; -const PatrolArea::Cell* PatrolArea::GetCell(const TileCoordsXY& pos) const -{ - return const_cast(this)->GetCell(pos); -} + static PatrolArea _consolidatedPatrolArea[EnumValue(StaffType::count)]; + static std::variant _patrolAreaToRender; -PatrolArea::Cell* PatrolArea::GetCell(const TileCoordsXY& pos) -{ - auto areaPos = TileCoordsXY(pos.x / Cell::Width, pos.y / Cell::Height); - if (areaPos.x < 0 || areaPos.x >= CellColumns || areaPos.y < 0 || areaPos.y >= CellRows) - return nullptr; - - auto& area = Areas[(areaPos.y * CellColumns) + areaPos.x]; - return &area; -} - -bool PatrolArea::IsEmpty() const -{ - return TileCount == 0; -} - -void PatrolArea::Clear() -{ - for (auto& area : Areas) + static bool CompareTileCoordsXY(const TileCoordsXY& lhs, const TileCoordsXY& rhs) { - area.SortedTiles.clear(); + if (lhs.y == rhs.y) + return lhs.x < rhs.x; + return lhs.y < rhs.y; } -} -bool PatrolArea::Get(const TileCoordsXY& pos) const -{ - auto* area = GetCell(pos); - if (area == nullptr) - return false; - - auto it = Algorithm::binaryFind(area->SortedTiles.begin(), area->SortedTiles.end(), pos, CompareTileCoordsXY); - auto found = it != area->SortedTiles.end(); - return found; -} - -bool PatrolArea::Get(const CoordsXY& pos) const -{ - return Get(TileCoordsXY(pos)); -} - -void PatrolArea::Set(const TileCoordsXY& pos, bool value) -{ - auto* area = GetCell(pos); - if (area == nullptr) - return; - - auto it = std::lower_bound(area->SortedTiles.begin(), area->SortedTiles.end(), pos, CompareTileCoordsXY); - auto found = it != area->SortedTiles.end() && *it == pos; - - if (!found && value) + const PatrolArea::Cell* PatrolArea::GetCell(const TileCoordsXY& pos) const { - area->SortedTiles.insert(it, pos); - TileCount++; + return const_cast(this)->GetCell(pos); } - else if (found && !value) + + PatrolArea::Cell* PatrolArea::GetCell(const TileCoordsXY& pos) { - area->SortedTiles.erase(it); - assert(TileCount != 0); - TileCount--; + auto areaPos = TileCoordsXY(pos.x / Cell::Width, pos.y / Cell::Height); + if (areaPos.x < 0 || areaPos.x >= CellColumns || areaPos.y < 0 || areaPos.y >= CellRows) + return nullptr; + + auto& area = Areas[(areaPos.y * CellColumns) + areaPos.x]; + return &area; } -} -void PatrolArea::Set(const CoordsXY& pos, bool value) -{ - Set(TileCoordsXY(pos), value); -} - -void PatrolArea::Union(const PatrolArea& other) -{ - for (size_t i = 0; i < Areas.size(); i++) + bool PatrolArea::IsEmpty() const { - for (const auto& pos : other.Areas[i].SortedTiles) + return TileCount == 0; + } + + void PatrolArea::Clear() + { + for (auto& area : Areas) + { + area.SortedTiles.clear(); + } + } + + bool PatrolArea::Get(const TileCoordsXY& pos) const + { + auto* area = GetCell(pos); + if (area == nullptr) + return false; + + auto it = Algorithm::binaryFind(area->SortedTiles.begin(), area->SortedTiles.end(), pos, CompareTileCoordsXY); + auto found = it != area->SortedTiles.end(); + return found; + } + + bool PatrolArea::Get(const CoordsXY& pos) const + { + return Get(TileCoordsXY(pos)); + } + + void PatrolArea::Set(const TileCoordsXY& pos, bool value) + { + auto* area = GetCell(pos); + if (area == nullptr) + return; + + auto it = std::lower_bound(area->SortedTiles.begin(), area->SortedTiles.end(), pos, CompareTileCoordsXY); + auto found = it != area->SortedTiles.end() && *it == pos; + + if (!found && value) + { + area->SortedTiles.insert(it, pos); + TileCount++; + } + else if (found && !value) + { + area->SortedTiles.erase(it); + assert(TileCount != 0); + TileCount--; + } + } + + void PatrolArea::Set(const CoordsXY& pos, bool value) + { + Set(TileCoordsXY(pos), value); + } + + void PatrolArea::Union(const PatrolArea& other) + { + for (size_t i = 0; i < Areas.size(); i++) + { + for (const auto& pos : other.Areas[i].SortedTiles) + { + Set(pos, true); + } + } + } + + void PatrolArea::Union(const std::vector& other) + { + for (const auto& pos : other) { Set(pos, true); } } -} -void PatrolArea::Union(const std::vector& other) -{ - for (const auto& pos : other) + std::vector PatrolArea::ToVector() const { - Set(pos, true); - } -} - -std::vector PatrolArea::ToVector() const -{ - std::vector result; - for (const auto& area : Areas) - { - for (const auto& pos : area.SortedTiles) + std::vector result; + for (const auto& area : Areas) { - result.push_back(pos); + for (const auto& pos : area.SortedTiles) + { + result.push_back(pos); + } + } + return result; + } + + const PatrolArea& GetMergedPatrolArea(const StaffType type) + { + return _consolidatedPatrolArea[EnumValue(type)]; + } + + void UpdateConsolidatedPatrolAreas() + { + for (int32_t staffType = 0; staffType < EnumValue(StaffType::count); ++staffType) + { + // Reset all of the merged data for the type. + auto& mergedArea = _consolidatedPatrolArea[staffType]; + mergedArea.Clear(); + + for (auto staff : EntityList()) + { + if (EnumValue(staff->AssignedStaffType) != staffType) + continue; + + if (staff->PatrolInfo == nullptr) + continue; + + mergedArea.Union(*staff->PatrolInfo); + } } } - return result; -} -const PatrolArea& GetMergedPatrolArea(const StaffType type) -{ - return _consolidatedPatrolArea[EnumValue(type)]; -} - -void UpdateConsolidatedPatrolAreas() -{ - for (int32_t staffType = 0; staffType < EnumValue(StaffType::count); ++staffType) + bool IsPatrolAreaSetForStaffType(StaffType type, const CoordsXY& coords) { - // Reset all of the merged data for the type. - auto& mergedArea = _consolidatedPatrolArea[staffType]; - mergedArea.Clear(); - - for (auto staff : EntityList()) - { - if (EnumValue(staff->AssignedStaffType) != staffType) - continue; - - if (staff->PatrolInfo == nullptr) - continue; - - mergedArea.Union(*staff->PatrolInfo); - } + return _consolidatedPatrolArea[EnumValue(type)].Get(coords); } -} -bool IsPatrolAreaSetForStaffType(StaffType type, const CoordsXY& coords) -{ - return _consolidatedPatrolArea[EnumValue(type)].Get(coords); -} + std::variant GetPatrolAreaToRender() + { + return _patrolAreaToRender; + } -std::variant GetPatrolAreaToRender() -{ - return _patrolAreaToRender; -} + void ClearPatrolAreaToRender() + { + SetPatrolAreaToRender(EntityId::GetNull()); + } -void ClearPatrolAreaToRender() -{ - SetPatrolAreaToRender(EntityId::GetNull()); -} + void SetPatrolAreaToRender(EntityId staffId) + { + _patrolAreaToRender = staffId; + } -void SetPatrolAreaToRender(EntityId staffId) -{ - _patrolAreaToRender = staffId; -} - -void SetPatrolAreaToRender(StaffType staffType) -{ - _patrolAreaToRender = staffType; -} + void SetPatrolAreaToRender(StaffType staffType) + { + _patrolAreaToRender = staffType; + } +} // namespace OpenRCT2 diff --git a/src/openrct2/entity/PatrolArea.h b/src/openrct2/entity/PatrolArea.h index 3c88facbf2..efbd8c760a 100644 --- a/src/openrct2/entity/PatrolArea.h +++ b/src/openrct2/entity/PatrolArea.h @@ -15,49 +15,52 @@ #include #include -// The number of elements in the GameState_t.StaffPatrolAreas array per staff member. Every bit in the array represents a 4x4 -// square. Right now, it's a 32-bit array like in RCT2. 32 * 128 = 4096 bits, which is also the number of 4x4 squares on a -// 256x256 map. -constexpr size_t kStaffPatrolAreaBlocksPerLine = kMaximumMapSizeTechnical / 4; -constexpr size_t kStaffPatrolAreaSize = (kStaffPatrolAreaBlocksPerLine * kStaffPatrolAreaBlocksPerLine) / 32; - -class PatrolArea +namespace OpenRCT2 { -private: - struct Cell - { - static constexpr auto Width = 64; - static constexpr auto Height = 64; - static constexpr auto NumTiles = Width * Height; + // The number of elements in the GameState_t.StaffPatrolAreas array per staff member. Every bit in the array represents a + // 4x4 square. Right now, it's a 32-bit array like in RCT2. 32 * 128 = 4096 bits, which is also the number of 4x4 squares on + // a 256x256 map. + constexpr size_t kStaffPatrolAreaBlocksPerLine = kMaximumMapSizeTechnical / 4; + constexpr size_t kStaffPatrolAreaSize = (kStaffPatrolAreaBlocksPerLine * kStaffPatrolAreaBlocksPerLine) / 32; - std::vector SortedTiles; + class PatrolArea + { + private: + struct Cell + { + static constexpr auto Width = 64; + static constexpr auto Height = 64; + static constexpr auto NumTiles = Width * Height; + + std::vector SortedTiles; + }; + + static constexpr auto CellColumns = (kMaximumMapSizeTechnical + (Cell::Width - 1)) / Cell::Width; + static constexpr auto CellRows = (kMaximumMapSizeTechnical + (Cell::Height - 1)) / Cell::Height; + static constexpr auto NumCells = CellColumns * CellRows; + + std::array Areas; + size_t TileCount{}; + + const Cell* GetCell(const TileCoordsXY& pos) const; + Cell* GetCell(const TileCoordsXY& pos); + + public: + bool IsEmpty() const; + void Clear(); + bool Get(const TileCoordsXY& pos) const; + bool Get(const CoordsXY& pos) const; + void Set(const TileCoordsXY& pos, bool value); + void Set(const CoordsXY& pos, bool value); + void Union(const PatrolArea& other); + void Union(const std::vector& other); + std::vector ToVector() const; }; - static constexpr auto CellColumns = (kMaximumMapSizeTechnical + (Cell::Width - 1)) / Cell::Width; - static constexpr auto CellRows = (kMaximumMapSizeTechnical + (Cell::Height - 1)) / Cell::Height; - static constexpr auto NumCells = CellColumns * CellRows; - - std::array Areas; - size_t TileCount{}; - - const Cell* GetCell(const TileCoordsXY& pos) const; - Cell* GetCell(const TileCoordsXY& pos); - -public: - bool IsEmpty() const; - void Clear(); - bool Get(const TileCoordsXY& pos) const; - bool Get(const CoordsXY& pos) const; - void Set(const TileCoordsXY& pos, bool value); - void Set(const CoordsXY& pos, bool value); - void Union(const PatrolArea& other); - void Union(const std::vector& other); - std::vector ToVector() const; -}; - -void UpdateConsolidatedPatrolAreas(); -bool IsPatrolAreaSetForStaffType(StaffType type, const CoordsXY& coords); -std::variant GetPatrolAreaToRender(); -void ClearPatrolAreaToRender(); -void SetPatrolAreaToRender(EntityId staffId); -void SetPatrolAreaToRender(StaffType staffType); + void UpdateConsolidatedPatrolAreas(); + bool IsPatrolAreaSetForStaffType(StaffType type, const CoordsXY& coords); + std::variant GetPatrolAreaToRender(); + void ClearPatrolAreaToRender(); + void SetPatrolAreaToRender(EntityId staffId); + void SetPatrolAreaToRender(StaffType staffType); +} // namespace OpenRCT2 diff --git a/src/openrct2/entity/Peep.cpp b/src/openrct2/entity/Peep.cpp index a48eb62ffd..914b97c3e5 100644 --- a/src/openrct2/entity/Peep.cpp +++ b/src/openrct2/entity/Peep.cpp @@ -73,1339 +73,1250 @@ #include #include -using namespace OpenRCT2; -using namespace OpenRCT2::Audio; -using namespace OpenRCT2::Drawing; - -static uint8_t _backupAnimationImageIdOffset; -static TileElement* _peepRideEntranceExitElement; - -static std::shared_ptr _crowdSoundChannel = nullptr; - -static void GuestReleaseBalloon(Guest* peep, int16_t spawn_height); - -static PeepAnimationType PeepSpecialSpriteToAnimationGroupMap[] = { - PeepAnimationType::walking, - PeepAnimationType::holdMat, - PeepAnimationType::staffMower, -}; - -static PeepAnimationType PeepActionToAnimationGroupMap[] = { - PeepAnimationType::checkTime, - PeepAnimationType::eatFood, - PeepAnimationType::shakeHead, - PeepAnimationType::emptyPockets, - PeepAnimationType::sittingEatFood, - PeepAnimationType::sittingLookAroundLeft, - PeepAnimationType::sittingLookAroundRight, - PeepAnimationType::wow, - PeepAnimationType::throwUp, - PeepAnimationType::jump, - PeepAnimationType::staffSweep, - PeepAnimationType::drowning, - PeepAnimationType::staffAnswerCall, - PeepAnimationType::staffAnswerCall2, - PeepAnimationType::staffCheckBoard, - PeepAnimationType::staffFix, - PeepAnimationType::staffFix2, - PeepAnimationType::staffFixGround, - PeepAnimationType::staffFix3, - PeepAnimationType::staffWatering, - PeepAnimationType::joy, - PeepAnimationType::readMap, - PeepAnimationType::wave, - PeepAnimationType::staffEmptyBin, - PeepAnimationType::wave2, - PeepAnimationType::takePhoto, - PeepAnimationType::clap, - PeepAnimationType::disgust, - PeepAnimationType::drawPicture, - PeepAnimationType::beingWatched, - PeepAnimationType::withdrawMoney, -}; - -template<> -bool EntityBase::Is() const +namespace OpenRCT2 { - return Type == EntityType::guest || Type == EntityType::staff; -} + using namespace OpenRCT2::Audio; + using namespace OpenRCT2::Drawing; -uint8_t Peep::GetNextDirection() const -{ - return NextFlags & PEEP_NEXT_FLAG_DIRECTION_MASK; -} + static uint8_t _backupAnimationImageIdOffset; + static TileElement* _peepRideEntranceExitElement; -bool Peep::GetNextIsSloped() const -{ - return NextFlags & PEEP_NEXT_FLAG_IS_SLOPED; -} + static std::shared_ptr _crowdSoundChannel = nullptr; -bool Peep::GetNextIsSurface() const -{ - return NextFlags & PEEP_NEXT_FLAG_IS_SURFACE; -} + static void GuestReleaseBalloon(Guest* peep, int16_t spawn_height); -void Peep::SetNextFlags(uint8_t next_direction, bool is_sloped, bool is_surface) -{ - NextFlags = next_direction & PEEP_NEXT_FLAG_DIRECTION_MASK; - NextFlags |= is_sloped ? PEEP_NEXT_FLAG_IS_SLOPED : 0; - NextFlags |= is_surface ? PEEP_NEXT_FLAG_IS_SURFACE : 0; -} + static PeepAnimationType PeepSpecialSpriteToAnimationGroupMap[] = { + PeepAnimationType::walking, + PeepAnimationType::holdMat, + PeepAnimationType::staffMower, + }; -bool Peep::CanBePickedUp() const -{ - switch (State) + static PeepAnimationType PeepActionToAnimationGroupMap[] = { + PeepAnimationType::checkTime, + PeepAnimationType::eatFood, + PeepAnimationType::shakeHead, + PeepAnimationType::emptyPockets, + PeepAnimationType::sittingEatFood, + PeepAnimationType::sittingLookAroundLeft, + PeepAnimationType::sittingLookAroundRight, + PeepAnimationType::wow, + PeepAnimationType::throwUp, + PeepAnimationType::jump, + PeepAnimationType::staffSweep, + PeepAnimationType::drowning, + PeepAnimationType::staffAnswerCall, + PeepAnimationType::staffAnswerCall2, + PeepAnimationType::staffCheckBoard, + PeepAnimationType::staffFix, + PeepAnimationType::staffFix2, + PeepAnimationType::staffFixGround, + PeepAnimationType::staffFix3, + PeepAnimationType::staffWatering, + PeepAnimationType::joy, + PeepAnimationType::readMap, + PeepAnimationType::wave, + PeepAnimationType::staffEmptyBin, + PeepAnimationType::wave2, + PeepAnimationType::takePhoto, + PeepAnimationType::clap, + PeepAnimationType::disgust, + PeepAnimationType::drawPicture, + PeepAnimationType::beingWatched, + PeepAnimationType::withdrawMoney, + }; + + template<> + bool EntityBase::Is() const { - case PeepState::one: - case PeepState::queuingFront: - case PeepState::onRide: - case PeepState::enteringRide: - case PeepState::leavingRide: - case PeepState::enteringPark: - case PeepState::leavingPark: - case PeepState::fixing: - case PeepState::buying: - case PeepState::inspecting: - return false; - case PeepState::falling: - case PeepState::walking: - case PeepState::queuing: - case PeepState::sitting: - case PeepState::picked: - case PeepState::patrolling: - case PeepState::mowing: - case PeepState::sweeping: - case PeepState::answering: - case PeepState::watching: - case PeepState::emptyingBin: - case PeepState::usingBin: - case PeepState::watering: - case PeepState::headingToInspection: - return true; + return Type == EntityType::guest || Type == EntityType::staff; } - return false; -} -int32_t PeepGetStaffCount() -{ - return getGameState().entities.GetEntityListCount(EntityType::staff); -} - -/** - * - * rct2: 0x0068F0A9 - */ -void PeepUpdateAll() -{ - PROFILED_FUNCTION(); - - if (isInEditorMode()) - return; - - const auto currentTicks = getGameState().currentTicks; - - constexpr auto kTicks128Mask = 128u - 1u; - const auto currentTicksMasked = currentTicks & kTicks128Mask; - - uint32_t index = 0; - - for (auto peep : EntityList()) + uint8_t Peep::GetNextDirection() const { - if ((index & kTicks128Mask) == currentTicksMasked) + return NextFlags & PEEP_NEXT_FLAG_DIRECTION_MASK; + } + + bool Peep::GetNextIsSloped() const + { + return NextFlags & PEEP_NEXT_FLAG_IS_SLOPED; + } + + bool Peep::GetNextIsSurface() const + { + return NextFlags & PEEP_NEXT_FLAG_IS_SURFACE; + } + + void Peep::SetNextFlags(uint8_t next_direction, bool is_sloped, bool is_surface) + { + NextFlags = next_direction & PEEP_NEXT_FLAG_DIRECTION_MASK; + NextFlags |= is_sloped ? PEEP_NEXT_FLAG_IS_SLOPED : 0; + NextFlags |= is_surface ? PEEP_NEXT_FLAG_IS_SURFACE : 0; + } + + bool Peep::CanBePickedUp() const + { + switch (State) { - peep->Tick128UpdateGuest(index); + case PeepState::one: + case PeepState::queuingFront: + case PeepState::onRide: + case PeepState::enteringRide: + case PeepState::leavingRide: + case PeepState::enteringPark: + case PeepState::leavingPark: + case PeepState::fixing: + case PeepState::buying: + case PeepState::inspecting: + return false; + case PeepState::falling: + case PeepState::walking: + case PeepState::queuing: + case PeepState::sitting: + case PeepState::picked: + case PeepState::patrolling: + case PeepState::mowing: + case PeepState::sweeping: + case PeepState::answering: + case PeepState::watching: + case PeepState::emptyingBin: + case PeepState::usingBin: + case PeepState::watering: + case PeepState::headingToInspection: + return true; } - - peep->Update(); - - index++; + return false; } - for (auto staff : EntityList()) + int32_t PeepGetStaffCount() { - if ((index & kTicks128Mask) == currentTicksMasked) - { - staff->Tick128UpdateStaff(); - } - - staff->Update(); - - index++; - } -} - -void PeepUpdateAllBoundingBoxes() -{ - for (auto* peep : EntityList()) - { - peep->UpdateSpriteBoundingBox(); + return getGameState().entities.GetEntityListCount(EntityType::staff); } - for (auto* peep : EntityList()) + /** + * + * rct2: 0x0068F0A9 + */ + void PeepUpdateAll() { - peep->UpdateSpriteBoundingBox(); - } -} + PROFILED_FUNCTION(); -void Peep::UpdateWaitingAtCrossing() -{ - if (!IsActionInterruptable()) - { - UpdateAction(); - Invalidate(); - if (!IsActionWalking()) + if (isInEditorMode()) return; + + const auto currentTicks = getGameState().currentTicks; + + constexpr auto kTicks128Mask = 128u - 1u; + const auto currentTicksMasked = currentTicks & kTicks128Mask; + + uint32_t index = 0; + + for (auto peep : EntityList()) + { + if ((index & kTicks128Mask) == currentTicksMasked) + { + peep->Tick128UpdateGuest(index); + } + + peep->Update(); + + index++; + } + + for (auto staff : EntityList()) + { + if ((index & kTicks128Mask) == currentTicksMasked) + { + staff->Tick128UpdateStaff(); + } + + staff->Update(); + + index++; + } } - Action = PeepActionType::idle; - NextAnimationType = PeepAnimationType::watchRide; - SwitchNextAnimationType(); - - auto* guest = As(); - if (guest != nullptr) + void PeepUpdateAllBoundingBoxes() { - if (guest->IsActionInterruptable()) + for (auto* peep : EntityList()) { - if (guest->HasFoodOrDrink()) + peep->UpdateSpriteBoundingBox(); + } + + for (auto* peep : EntityList()) + { + peep->UpdateSpriteBoundingBox(); + } + } + + void Peep::UpdateWaitingAtCrossing() + { + if (!IsActionInterruptable()) + { + UpdateAction(); + Invalidate(); + if (!IsActionWalking()) + return; + } + + Action = PeepActionType::idle; + NextAnimationType = PeepAnimationType::watchRide; + SwitchNextAnimationType(); + + auto* guest = As(); + if (guest != nullptr) + { + if (guest->IsActionInterruptable()) { - if ((ScenarioRand() & 0xFFFF) <= 1310) + if (guest->HasFoodOrDrink()) { - Action = PeepActionType::eatFood; + if ((ScenarioRand() & 0xFFFF) <= 1310) + { + Action = PeepActionType::eatFood; + AnimationFrameNum = 0; + AnimationImageIdOffset = 0; + } + } + else if ((ScenarioRand() & 0xFFFF) <= 64) + { + Action = PeepActionType::wave2; AnimationFrameNum = 0; AnimationImageIdOffset = 0; } } - else if ((ScenarioRand() & 0xFFFF) <= 64) - { - Action = PeepActionType::wave2; - AnimationFrameNum = 0; - AnimationImageIdOffset = 0; - } } + + UpdateCurrentAnimationType(); } - UpdateCurrentAnimationType(); -} - -/* - * rct2: 0x68F3AE - * Set peep state to falling if path below has gone missing, return true if current path is valid, false if peep starts falling. - */ -bool Peep::CheckForPath() -{ - PROFILED_FUNCTION(); - - PathCheckOptimisation++; - if ((PathCheckOptimisation & 0xF) != (Id.ToUnderlying() & 0xF)) + /* + * rct2: 0x68F3AE + * Set peep state to falling if path below has gone missing, return true if current path is valid, false if peep starts + * falling. + */ + bool Peep::CheckForPath() { - // This condition makes the check happen less often - // As a side effect peeps hover for a short, - // random time when a path below them has been deleted - return true; - } + PROFILED_FUNCTION(); - TileElement* tile_element = MapGetFirstElementAt(NextLoc); - - auto mapType = TileElementType::Path; - if (GetNextIsSurface()) - { - mapType = TileElementType::Surface; - } - - do - { - if (tile_element == nullptr) - break; - if (tile_element->GetType() == mapType) + PathCheckOptimisation++; + if ((PathCheckOptimisation & 0xF) != (Id.ToUnderlying() & 0xF)) { - if (NextLoc.z == tile_element->GetBaseZ()) - { - // Found a suitable path or surface - return true; - } + // This condition makes the check happen less often + // As a side effect peeps hover for a short, + // random time when a path below them has been deleted + return true; } - } while (!(tile_element++)->IsLastForTile()); - // Found no suitable path - SetState(PeepState::falling); - return false; -} + TileElement* tile_element = MapGetFirstElementAt(NextLoc); -bool Peep::ShouldWaitForLevelCrossing() const -{ - if (IsOnPathBlockedByVehicle()) - { - // Try to get out of the way + auto mapType = TileElementType::Path; + if (GetNextIsSurface()) + { + mapType = TileElementType::Surface; + } + + do + { + if (tile_element == nullptr) + break; + if (tile_element->GetType() == mapType) + { + if (NextLoc.z == tile_element->GetBaseZ()) + { + // Found a suitable path or surface + return true; + } + } + } while (!(tile_element++)->IsLastForTile()); + + // Found no suitable path + SetState(PeepState::falling); return false; } - auto curPos = TileCoordsXYZ(GetLocation()); - auto dstPos = TileCoordsXYZ(CoordsXYZ{ GetDestination(), NextLoc.z }); - if ((curPos.x != dstPos.x || curPos.y != dstPos.y) && FootpathIsBlockedByVehicle(dstPos)) + bool Peep::ShouldWaitForLevelCrossing() const { - return true; + if (IsOnPathBlockedByVehicle()) + { + // Try to get out of the way + return false; + } + + auto curPos = TileCoordsXYZ(GetLocation()); + auto dstPos = TileCoordsXYZ(CoordsXYZ{ GetDestination(), NextLoc.z }); + if ((curPos.x != dstPos.x || curPos.y != dstPos.y) && FootpathIsBlockedByVehicle(dstPos)) + { + return true; + } + + return false; } - return false; -} - -bool Peep::IsOnLevelCrossing() const -{ - auto loc = GetLocation(); - auto pathElement = MapGetFootpathElement(loc); - if (pathElement != nullptr) + bool Peep::IsOnLevelCrossing() const { - return pathElement->AsPath()->IsLevelCrossing(loc); - } - return false; -} - -bool Peep::IsOnPathBlockedByVehicle() const -{ - auto curPos = TileCoordsXYZ(GetLocation()); - return FootpathIsBlockedByVehicle(curPos); -} - -PeepAnimationType Peep::GetAnimationType() -{ - if (IsActionInterruptable()) - { // PeepActionType::none1 or PeepActionType::none2 - return PeepSpecialSpriteToAnimationGroupMap[SpecialSprite]; + auto loc = GetLocation(); + auto pathElement = MapGetFootpathElement(loc); + if (pathElement != nullptr) + { + return pathElement->AsPath()->IsLevelCrossing(loc); + } + return false; } - if (EnumValue(Action) < std::size(PeepActionToAnimationGroupMap)) + bool Peep::IsOnPathBlockedByVehicle() const { - return PeepActionToAnimationGroupMap[EnumValue(Action)]; + auto curPos = TileCoordsXYZ(GetLocation()); + return FootpathIsBlockedByVehicle(curPos); } - Guard::Assert( - EnumValue(Action) >= std::size(PeepActionToAnimationGroupMap) && Action < PeepActionType::idle, - "Invalid peep action %u", EnumValue(Action)); - return PeepAnimationType::walking; -} - -/* - * rct2: 0x00693B58 - */ -void Peep::UpdateCurrentAnimationType() -{ - PeepAnimationType newAnimationType = GetAnimationType(); - if (AnimationType == newAnimationType) + PeepAnimationType Peep::GetAnimationType() { - return; + if (IsActionInterruptable()) + { // PeepActionType::none1 or PeepActionType::none2 + return PeepSpecialSpriteToAnimationGroupMap[SpecialSprite]; + } + + if (EnumValue(Action) < std::size(PeepActionToAnimationGroupMap)) + { + return PeepActionToAnimationGroupMap[EnumValue(Action)]; + } + + Guard::Assert( + EnumValue(Action) >= std::size(PeepActionToAnimationGroupMap) && Action < PeepActionType::idle, + "Invalid peep action %u", EnumValue(Action)); + return PeepAnimationType::walking; } - AnimationType = newAnimationType; - - Invalidate(); - UpdateSpriteBoundingBox(); - Invalidate(); -} - -void Peep::UpdateSpriteBoundingBox() -{ - auto& objManager = GetContext()->GetObjectManager(); - auto* animObj = objManager.GetLoadedObject(AnimationObjectIndex); - - const auto& spriteBounds = animObj->GetSpriteBounds(AnimationGroup, AnimationType); - SpriteData.Width = spriteBounds.spriteWidth; - SpriteData.HeightMin = spriteBounds.spriteHeightNegative; - SpriteData.HeightMax = spriteBounds.spriteHeightPositive; -} - -/* rct2: 0x00693BE5 */ -void Peep::SwitchToSpecialSprite(uint8_t special_sprite_id) -{ - if (special_sprite_id == SpecialSprite) - return; - - SpecialSprite = special_sprite_id; - - if (IsActionInterruptable()) + /* + * rct2: 0x00693B58 + */ + void Peep::UpdateCurrentAnimationType() { - AnimationImageIdOffset = 0; - } - UpdateCurrentAnimationType(); -} + PeepAnimationType newAnimationType = GetAnimationType(); + if (AnimationType == newAnimationType) + { + return; + } -void Peep::StateReset() -{ - SetState(PeepState::one); - SwitchToSpecialSprite(0); -} + AnimationType = newAnimationType; -/** rct2: 0x00981D7C, 0x00981D7E */ -static constexpr CoordsXY kWalkingOffsetByDirection[kNumOrthogonalDirections] = { - { -2, 0 }, - { 0, 2 }, - { 2, 0 }, - { 0, -2 }, -}; - -std::optional Peep::UpdateAction() -{ - int16_t xy_distance; - return UpdateAction(xy_distance); -} - -/** - * - * rct2: 0x6939EB - * Also used to move peeps to the correct position to - * start an action. Returns true if the correct destination - * has not yet been reached. xy_distance is how close the - * peep is to the target. - */ -std::optional Peep::UpdateAction(int16_t& xy_distance) -{ - PROFILED_FUNCTION(); - - _backupAnimationImageIdOffset = AnimationImageIdOffset; - if (Action == PeepActionType::idle) - { - Action = PeepActionType::walking; + Invalidate(); + UpdateSpriteBoundingBox(); + Invalidate(); } - CoordsXY differenceLoc = GetLocation(); - differenceLoc -= GetDestination(); - - int32_t x_delta = abs(differenceLoc.x); - int32_t y_delta = abs(differenceLoc.y); - - xy_distance = x_delta + y_delta; - - // We're taking an easier route if we're just walking - if (IsActionWalking()) + void Peep::UpdateSpriteBoundingBox() { - return UpdateWalkingAction(differenceLoc, xy_distance); + auto& objManager = GetContext()->GetObjectManager(); + auto* animObj = objManager.GetLoadedObject(AnimationObjectIndex); + + const auto& spriteBounds = animObj->GetSpriteBounds(AnimationGroup, AnimationType); + SpriteData.Width = spriteBounds.spriteWidth; + SpriteData.HeightMin = spriteBounds.spriteHeightNegative; + SpriteData.HeightMax = spriteBounds.spriteHeightPositive; } - if (!UpdateActionAnimation()) + /* rct2: 0x00693BE5 */ + void Peep::SwitchToSpecialSprite(uint8_t special_sprite_id) { - AnimationImageIdOffset = 0; - Action = PeepActionType::walking; + if (special_sprite_id == SpecialSprite) + return; + + SpecialSprite = special_sprite_id; + + if (IsActionInterruptable()) + { + AnimationImageIdOffset = 0; + } UpdateCurrentAnimationType(); + } + + void Peep::StateReset() + { + SetState(PeepState::one); + SwitchToSpecialSprite(0); + } + + /** rct2: 0x00981D7C, 0x00981D7E */ + static constexpr CoordsXY kWalkingOffsetByDirection[kNumOrthogonalDirections] = { + { -2, 0 }, + { 0, 2 }, + { 2, 0 }, + { 0, -2 }, + }; + + std::optional Peep::UpdateAction() + { + int16_t xy_distance; + return UpdateAction(xy_distance); + } + + /** + * + * rct2: 0x6939EB + * Also used to move peeps to the correct position to + * start an action. Returns true if the correct destination + * has not yet been reached. xy_distance is how close the + * peep is to the target. + */ + std::optional Peep::UpdateAction(int16_t& xy_distance) + { + PROFILED_FUNCTION(); + + _backupAnimationImageIdOffset = AnimationImageIdOffset; + if (Action == PeepActionType::idle) + { + Action = PeepActionType::walking; + } + + CoordsXY differenceLoc = GetLocation(); + differenceLoc -= GetDestination(); + + int32_t x_delta = abs(differenceLoc.x); + int32_t y_delta = abs(differenceLoc.y); + + xy_distance = x_delta + y_delta; + + // We're taking an easier route if we're just walking + if (IsActionWalking()) + { + return UpdateWalkingAction(differenceLoc, xy_distance); + } + + if (!UpdateActionAnimation()) + { + AnimationImageIdOffset = 0; + Action = PeepActionType::walking; + UpdateCurrentAnimationType(); + return { { x, y } }; + } + + // Should we throw up, and are we at the frame where sick appears? + if (auto* guest = As(); guest != nullptr) + { + if (Action == PeepActionType::throwUp && AnimationFrameNum == 15) + { + guest->ThrowUp(); + } + } + return { { x, y } }; } - // Should we throw up, and are we at the frame where sick appears? - if (auto* guest = As(); guest != nullptr) + bool Peep::UpdateActionAnimation() { - if (Action == PeepActionType::throwUp && AnimationFrameNum == 15) + auto& objManager = GetContext()->GetObjectManager(); + auto* animObj = objManager.GetLoadedObject(AnimationObjectIndex); + + const PeepAnimation& peepAnimation = animObj->GetPeepAnimation(AnimationGroup, AnimationType); + AnimationFrameNum++; + + // If last frame of action + if (AnimationFrameNum >= peepAnimation.frameOffsets.size()) { - guest->ThrowUp(); + return false; } + + AnimationImageIdOffset = peepAnimation.frameOffsets[AnimationFrameNum]; + return true; } - return { { x, y } }; -} - -bool Peep::UpdateActionAnimation() -{ - auto& objManager = GetContext()->GetObjectManager(); - auto* animObj = objManager.GetLoadedObject(AnimationObjectIndex); - - const PeepAnimation& peepAnimation = animObj->GetPeepAnimation(AnimationGroup, AnimationType); - AnimationFrameNum++; - - // If last frame of action - if (AnimationFrameNum >= peepAnimation.frameOffsets.size()) + std::optional Peep::UpdateWalkingAction(const CoordsXY& differenceLoc, int16_t& xy_distance) { - return false; - } - - AnimationImageIdOffset = peepAnimation.frameOffsets[AnimationFrameNum]; - return true; -} - -std::optional Peep::UpdateWalkingAction(const CoordsXY& differenceLoc, int16_t& xy_distance) -{ - if (!IsActionWalking()) - { - return std::nullopt; - } - - if (xy_distance <= DestinationTolerance) - { - return std::nullopt; - } - - int32_t x_delta = abs(differenceLoc.x); - int32_t y_delta = abs(differenceLoc.y); - - int32_t nextDirection = 0; - if (x_delta < y_delta) - { - nextDirection = 1; - if (differenceLoc.y >= 0) + if (!IsActionWalking()) { - nextDirection = 3; + return std::nullopt; } - } - else - { - nextDirection = 2; - if (differenceLoc.x >= 0) + + if (xy_distance <= DestinationTolerance) { - nextDirection = 0; + return std::nullopt; } - } - Orientation = nextDirection * 8; + int32_t x_delta = abs(differenceLoc.x); + int32_t y_delta = abs(differenceLoc.y); - CoordsXY loc = { x, y }; - loc += kWalkingOffsetByDirection[nextDirection]; - - UpdateWalkingAnimation(); - - return loc; -} - -void Peep::UpdateWalkingAnimation() -{ - auto& objManager = GetContext()->GetObjectManager(); - auto* animObj = objManager.GetLoadedObject(AnimationObjectIndex); - - WalkingAnimationFrameNum++; - const PeepAnimation& peepAnimation = animObj->GetPeepAnimation(AnimationGroup, AnimationType); - if (WalkingAnimationFrameNum >= peepAnimation.frameOffsets.size()) - { - WalkingAnimationFrameNum = 0; - } - AnimationImageIdOffset = peepAnimation.frameOffsets[WalkingAnimationFrameNum]; -} - -/** - * rct2: 0x0069A409 - * Decreases rider count if on/entering a ride. - */ -void PeepDecrementNumRiders(Peep* peep) -{ - if (peep->State == PeepState::onRide || peep->State == PeepState::enteringRide) - { - auto ride = GetRide(peep->CurrentRide); - if (ride != nullptr) + int32_t nextDirection = 0; + if (x_delta < y_delta) { - ride->numRiders = std::max(0, ride->numRiders - 1); - ride->windowInvalidateFlags.set(RideInvalidateFlag::main, RideInvalidateFlag::list); + nextDirection = 1; + if (differenceLoc.y >= 0) + { + nextDirection = 3; + } } + else + { + nextDirection = 2; + if (differenceLoc.x >= 0) + { + nextDirection = 0; + } + } + + Orientation = nextDirection * 8; + + CoordsXY loc = { x, y }; + loc += kWalkingOffsetByDirection[nextDirection]; + + UpdateWalkingAnimation(); + + return loc; } -} -/** - * Call after changing a peeps state to insure that all relevant windows update. - * Note also increase ride count if on/entering a ride. - * rct2: 0x0069A42F - */ -void PeepWindowStateUpdate(Peep* peep) -{ - auto* windowMgr = Ui::GetWindowManager(); - WindowBase* w = windowMgr->FindByNumber(WindowClass::peep, peep->Id.ToUnderlying()); - if (w != nullptr) - w->onPrepareDraw(); + void Peep::UpdateWalkingAnimation() + { + auto& objManager = GetContext()->GetObjectManager(); + auto* animObj = objManager.GetLoadedObject(AnimationObjectIndex); - if (peep->Is()) + WalkingAnimationFrameNum++; + const PeepAnimation& peepAnimation = animObj->GetPeepAnimation(AnimationGroup, AnimationType); + if (WalkingAnimationFrameNum >= peepAnimation.frameOffsets.size()) + { + WalkingAnimationFrameNum = 0; + } + AnimationImageIdOffset = peepAnimation.frameOffsets[WalkingAnimationFrameNum]; + } + + /** + * rct2: 0x0069A409 + * Decreases rider count if on/entering a ride. + */ + void PeepDecrementNumRiders(Peep* peep) { if (peep->State == PeepState::onRide || peep->State == PeepState::enteringRide) { auto ride = GetRide(peep->CurrentRide); if (ride != nullptr) { - ride->numRiders++; + ride->numRiders = std::max(0, ride->numRiders - 1); ride->windowInvalidateFlags.set(RideInvalidateFlag::main, RideInvalidateFlag::list); } } - - windowMgr->InvalidateByNumber(WindowClass::peep, peep->Id); - windowMgr->InvalidateByClass(WindowClass::guestList); - } - else - { - windowMgr->InvalidateByNumber(WindowClass::peep, peep->Id); - windowMgr->InvalidateByClass(WindowClass::staffList); - } -} - -void Peep::Pickup() -{ - if (auto* guest = As(); guest != nullptr) - { - guest->RemoveFromRide(); - } - MoveTo({ kLocationNull, y, z }); - SetState(PeepState::picked); - SubState = 0; -} - -void Peep::PickupAbort(int32_t old_x) -{ - if (State != PeepState::picked) - return; - - MoveTo({ old_x, y, z + 8 }); - - if (x != kLocationNull) - { - SetState(PeepState::falling); - Action = PeepActionType::walking; - SpecialSprite = 0; - AnimationImageIdOffset = 0; - AnimationType = PeepAnimationType::walking; - PathCheckOptimisation = 0; } - gPickupPeepImage = ImageId(); -} - -// Returns GameActions::Status::ok when a peep can be dropped at the given location. When apply is set to true the peep gets -// dropped. -GameActions::Result Peep::Place(const TileCoordsXYZ& location, bool apply) -{ - auto* pathElement = MapGetPathElementAt(location); - TileElement* tileElement = reinterpret_cast(pathElement); - if (pathElement == nullptr) + /** + * Call after changing a peeps state to insure that all relevant windows update. + * Note also increase ride count if on/entering a ride. + * rct2: 0x0069A42F + */ + void PeepWindowStateUpdate(Peep* peep) { - tileElement = reinterpret_cast(MapGetSurfaceElementAt(location)); - } - if (tileElement == nullptr) - { - return GameActions::Result(GameActions::Status::invalidParameters, STR_ERR_CANT_PLACE_PERSON_HERE, kStringIdNone); - } + auto* windowMgr = Ui::GetWindowManager(); + WindowBase* w = windowMgr->FindByNumber(WindowClass::peep, peep->Id.ToUnderlying()); + if (w != nullptr) + w->onPrepareDraw(); - // Set the coordinate of destination to be exactly - // in the middle of a tile. - CoordsXYZ destination = { location.ToCoordsXY().ToTileCentre(), tileElement->GetBaseZ() + 16 }; - - if (!MapIsLocationOwned(destination)) - { - return GameActions::Result(GameActions::Status::notOwned, STR_ERR_CANT_PLACE_PERSON_HERE, STR_LAND_NOT_OWNED_BY_PARK); - } - - if (auto res = MapCanConstructAt({ destination, destination.z, destination.z + (1 * 8) }, { 0b1111, 0 }); - res.error != GameActions::Status::ok) - { - const auto stringId = std::get(res.errorMessage); - if (stringId != STR_RAISE_OR_LOWER_LAND_FIRST && stringId != STR_FOOTPATH_IN_THE_WAY) + if (peep->Is()) { - return GameActions::Result( - GameActions::Status::noClearance, STR_ERR_CANT_PLACE_PERSON_HERE, stringId, res.errorMessageArgs.data()); + if (peep->State == PeepState::onRide || peep->State == PeepState::enteringRide) + { + auto ride = GetRide(peep->CurrentRide); + if (ride != nullptr) + { + ride->numRiders++; + ride->windowInvalidateFlags.set(RideInvalidateFlag::main, RideInvalidateFlag::list); + } + } + + windowMgr->InvalidateByNumber(WindowClass::peep, peep->Id); + windowMgr->InvalidateByClass(WindowClass::guestList); + } + else + { + windowMgr->InvalidateByNumber(WindowClass::peep, peep->Id); + windowMgr->InvalidateByClass(WindowClass::staffList); } } - if (apply) + void Peep::Pickup() { - MoveTo(destination); - SetState(PeepState::falling); - Action = PeepActionType::walking; - SpecialSprite = 0; - AnimationImageIdOffset = 0; - AnimationType = PeepAnimationType::walking; - PathCheckOptimisation = 0; - EntityTweener::Get().Reset(); if (auto* guest = As(); guest != nullptr) { - AnimationType = PeepAnimationType::invalid; - guest->HappinessTarget = std::max(guest->HappinessTarget - 10, 0); - UpdateCurrentAnimationType(); + guest->RemoveFromRide(); } + MoveTo({ kLocationNull, y, z }); + SetState(PeepState::picked); + SubState = 0; } - return GameActions::Result(); -} - -/** - * - * rct2: 0x0069A535 - */ -void PeepEntityRemove(Peep* peep) -{ - auto* guest = peep->As(); - if (guest != nullptr) + void Peep::PickupAbort(int32_t old_x) { - guest->RemoveFromRide(); - } - peep->Invalidate(); - - auto* windowMgr = Ui::GetWindowManager(); - windowMgr->CloseByNumber(WindowClass::peep, peep->Id); - windowMgr->CloseByNumber(WindowClass::firePrompt, EnumValue(peep->Type)); - - auto* staff = peep->As(); - // Needed for invalidations after sprite removal - bool wasGuest = staff == nullptr; - if (wasGuest) - { - News::DisableNewsItems(News::ItemType::peepOnRide, peep->Id.ToUnderlying()); - } - else - { - staff->ClearPatrolArea(); - UpdateConsolidatedPatrolAreas(); - - News::DisableNewsItems(News::ItemType::peep, staff->Id.ToUnderlying()); - } - getGameState().entities.EntityRemove(peep); - - auto intent = Intent(wasGuest ? INTENT_ACTION_REFRESH_GUEST_LIST : INTENT_ACTION_REFRESH_STAFF_LIST); - ContextBroadcastIntent(&intent); -} - -/** - * New function removes peep from park existence. Works with staff. - */ -void Peep::Remove() -{ - auto* guest = As(); - if (guest != nullptr) - { - if (!guest->OutsideOfPark) - { - DecrementGuestsInPark(); - auto intent = Intent(INTENT_ACTION_UPDATE_GUEST_COUNT); - ContextBroadcastIntent(&intent); - } - if (State == PeepState::enteringPark) - { - DecrementGuestsHeadingForPark(); - } - } - PeepEntityRemove(this); -} - -/** - * Falling and its subset drowning - * rct2: 0x690028 - */ -void Peep::UpdateFalling() -{ - if (Action == PeepActionType::drowning) - { - // Check to see if we are ready to drown. - UpdateAction(); - Invalidate(); - if (Action == PeepActionType::drowning) + if (State != PeepState::picked) return; - if (Config::Get().notifications.guestDied) + MoveTo({ old_x, y, z + 8 }); + + if (x != kLocationNull) { - auto ft = Formatter(); - FormatNameTo(ft); - News::AddItemToQueue(News::ItemType::blank, STR_NEWS_ITEM_GUEST_DROWNED, x | (y << 16), ft); + SetState(PeepState::falling); + Action = PeepActionType::walking; + SpecialSprite = 0; + AnimationImageIdOffset = 0; + AnimationType = PeepAnimationType::walking; + PathCheckOptimisation = 0; } - auto& gameState = getGameState(); - gameState.park.ratingCasualtyPenalty = std::min(gameState.park.ratingCasualtyPenalty + 25, 1000); - Remove(); - return; + gPickupPeepImage = ImageId(); } - // If not drowning then falling. Note: peeps 'fall' after leaving a ride/enter the park. - TileElement* tile_element = MapGetFirstElementAt(CoordsXY{ x, y }); - TileElement* saved_map = nullptr; - int32_t saved_height = 0; - - if (tile_element != nullptr) + // Returns GameActions::Status::ok when a peep can be dropped at the given location. When apply is set to true the peep gets + // dropped. + GameActions::Result Peep::Place(const TileCoordsXYZ& location, bool apply) { - do + auto* pathElement = MapGetPathElementAt(location); + TileElement* tileElement = reinterpret_cast(pathElement); + if (pathElement == nullptr) { - // If a path check if we are on it - if (tile_element->GetType() == TileElementType::Path) + tileElement = reinterpret_cast(MapGetSurfaceElementAt(location)); + } + if (tileElement == nullptr) + { + return GameActions::Result(GameActions::Status::invalidParameters, STR_ERR_CANT_PLACE_PERSON_HERE, kStringIdNone); + } + + // Set the coordinate of destination to be exactly + // in the middle of a tile. + CoordsXYZ destination = { location.ToCoordsXY().ToTileCentre(), tileElement->GetBaseZ() + 16 }; + + if (!MapIsLocationOwned(destination)) + { + return GameActions::Result( + GameActions::Status::notOwned, STR_ERR_CANT_PLACE_PERSON_HERE, STR_LAND_NOT_OWNED_BY_PARK); + } + + if (auto res = MapCanConstructAt({ destination, destination.z, destination.z + (1 * 8) }, { 0b1111, 0 }); + res.error != GameActions::Status::ok) + { + const auto stringId = std::get(res.errorMessage); + if (stringId != STR_RAISE_OR_LOWER_LAND_FIRST && stringId != STR_FOOTPATH_IN_THE_WAY) { - int32_t height = MapHeightFromSlope( - { x, y }, tile_element->AsPath()->GetSlopeDirection(), tile_element->AsPath()->IsSloped()) - + tile_element->GetBaseZ(); + return GameActions::Result( + GameActions::Status::noClearance, STR_ERR_CANT_PLACE_PERSON_HERE, stringId, res.errorMessageArgs.data()); + } + } - if (height < z - 1 || height > z + 8) - continue; - - saved_height = height; - saved_map = tile_element; - break; - } // If a surface get the height and see if we are on it - else if (tile_element->GetType() == TileElementType::Surface) + if (apply) + { + MoveTo(destination); + SetState(PeepState::falling); + Action = PeepActionType::walking; + SpecialSprite = 0; + AnimationImageIdOffset = 0; + AnimationType = PeepAnimationType::walking; + PathCheckOptimisation = 0; + EntityTweener::Get().Reset(); + if (auto* guest = As(); guest != nullptr) { - // If the surface is water check to see if we could be drowning - if (tile_element->AsSurface()->GetWaterHeight() > 0) - { - int32_t height = tile_element->AsSurface()->GetWaterHeight(); + AnimationType = PeepAnimationType::invalid; + guest->HappinessTarget = std::max(guest->HappinessTarget - 10, 0); + UpdateCurrentAnimationType(); + } + } - if (height - 4 >= z && height < z + 20) - { - // Looks like we are drowning! - MoveTo({ x, y, height }); - - if (auto* guest = As(); guest != nullptr) - { - // Drop balloon if held - GuestReleaseBalloon(guest, height); - guest->InsertNewThought(PeepThoughtType::Drowning); - } - - Action = PeepActionType::drowning; - AnimationFrameNum = 0; - AnimationImageIdOffset = 0; - - UpdateCurrentAnimationType(); - PeepWindowStateUpdate(this); - return; - } - } - int32_t map_height = TileElementHeight({ x, y }); - if (map_height < z || map_height - 4 > z) - continue; - saved_height = map_height; - saved_map = tile_element; - } // If not a path or surface go see next element - } while (!(tile_element++)->IsLastForTile()); + return GameActions::Result(); } - // This will be null if peep is falling - if (saved_map == nullptr) + /** + * + * rct2: 0x0069A535 + */ + void PeepEntityRemove(Peep* peep) { - if (z <= 1) + auto* guest = peep->As(); + if (guest != nullptr) { - // Remove peep if it has gone to the void + guest->RemoveFromRide(); + } + peep->Invalidate(); + + auto* windowMgr = Ui::GetWindowManager(); + windowMgr->CloseByNumber(WindowClass::peep, peep->Id); + windowMgr->CloseByNumber(WindowClass::firePrompt, EnumValue(peep->Type)); + + auto* staff = peep->As(); + // Needed for invalidations after sprite removal + bool wasGuest = staff == nullptr; + if (wasGuest) + { + News::DisableNewsItems(News::ItemType::peepOnRide, peep->Id.ToUnderlying()); + } + else + { + staff->ClearPatrolArea(); + UpdateConsolidatedPatrolAreas(); + + News::DisableNewsItems(News::ItemType::peep, staff->Id.ToUnderlying()); + } + getGameState().entities.EntityRemove(peep); + + auto intent = Intent(wasGuest ? INTENT_ACTION_REFRESH_GUEST_LIST : INTENT_ACTION_REFRESH_STAFF_LIST); + ContextBroadcastIntent(&intent); + } + + /** + * New function removes peep from park existence. Works with staff. + */ + void Peep::Remove() + { + auto* guest = As(); + if (guest != nullptr) + { + if (!guest->OutsideOfPark) + { + DecrementGuestsInPark(); + auto intent = Intent(INTENT_ACTION_UPDATE_GUEST_COUNT); + ContextBroadcastIntent(&intent); + } + if (State == PeepState::enteringPark) + { + DecrementGuestsHeadingForPark(); + } + } + PeepEntityRemove(this); + } + + /** + * Falling and its subset drowning + * rct2: 0x690028 + */ + void Peep::UpdateFalling() + { + if (Action == PeepActionType::drowning) + { + // Check to see if we are ready to drown. + UpdateAction(); + Invalidate(); + if (Action == PeepActionType::drowning) + return; + + if (Config::Get().notifications.guestDied) + { + auto ft = Formatter(); + FormatNameTo(ft); + News::AddItemToQueue(News::ItemType::blank, STR_NEWS_ITEM_GUEST_DROWNED, x | (y << 16), ft); + } + + auto& gameState = getGameState(); + gameState.park.ratingCasualtyPenalty = std::min(gameState.park.ratingCasualtyPenalty + 25, 1000); Remove(); return; } - MoveTo({ x, y, z - 2 }); - return; - } - MoveTo({ x, y, saved_height }); + // If not drowning then falling. Note: peeps 'fall' after leaving a ride/enter the park. + TileElement* tile_element = MapGetFirstElementAt(CoordsXY{ x, y }); + TileElement* saved_map = nullptr; + int32_t saved_height = 0; - NextLoc = { CoordsXY{ x, y }.ToTileStart(), saved_map->GetBaseZ() }; - - if (saved_map->GetType() != TileElementType::Path) - { - SetNextFlags(0, false, true); - } - else - { - SetNextFlags(saved_map->AsPath()->GetSlopeDirection(), saved_map->AsPath()->IsSloped(), false); - } - SetState(PeepState::one); -} - -/** - * - * rct2: 0x6902A2 - */ -void Peep::Update1() -{ - if (!CheckForPath()) - return; - - if (Is()) - { - SetState(PeepState::walking); - } - else - { - SetState(PeepState::patrolling); - } - - SetDestination(GetLocation(), 10); - PeepDirection = Orientation >> 3; -} - -void Peep::SetState(PeepState new_state) -{ - PeepDecrementNumRiders(this); - State = new_state; - PeepWindowStateUpdate(this); -} - -/** - * - * rct2: 0x690009 - */ -void Peep::UpdatePicked() -{ - if (getGameState().currentTicks & 0x1F) - return; - SubState++; - auto* guest = As(); - if (SubState == 13 && guest != nullptr) - { - guest->InsertNewThought(PeepThoughtType::Help); - } -} - -uint32_t Peep::GetStepsToTake() const -{ - uint32_t stepsToTake = Energy; - if (stepsToTake < 95 && State == PeepState::queuing) - stepsToTake = 95; - if ((PeepFlags & PEEP_FLAGS_SLOW_WALK) && State != PeepState::queuing) - stepsToTake /= 2; - if (IsActionWalking() && GetNextIsSloped()) - { - stepsToTake /= 2; - if (State == PeepState::queuing) - stepsToTake += stepsToTake / 2; - } - // Ensure guests make it across a level crossing in time - constexpr auto minStepsForCrossing = 55; - if (stepsToTake < minStepsForCrossing && IsOnPathBlockedByVehicle()) - stepsToTake = minStepsForCrossing; - - return stepsToTake; -} - -/** - * - * rct2: 0x0069BF41 - */ -void PeepProblemWarningsUpdate() -{ - auto& gameState = getGameState(); - - Ride* ride; - uint32_t hungerCounter = 0, lostCounter = 0, noexitCounter = 0, thirstCounter = 0, litterCounter = 0, disgustCounter = 0, - toiletCounter = 0, vandalismCounter = 0; - uint8_t* warningThrottle = gameState.park.peepWarningThrottle; - - int32_t inQueueCounter = 0; - int32_t tooLongQueueCounter = 0; - std::map queueComplainingGuestsMap; - - for (auto peep : EntityList()) - { - if (peep->OutsideOfPark) - continue; - - if (peep->State == PeepState::queuing || peep->State == PeepState::queuingFront) - inQueueCounter++; - - if (peep->Thoughts[0].freshness > 5) - continue; - - switch (peep->Thoughts[0].type) + if (tile_element != nullptr) { - case PeepThoughtType::Lost: // 0x10 - lostCounter++; - break; - - case PeepThoughtType::Hungry: // 0x14 - if (peep->GuestHeadingToRideId.IsNull()) + do + { + // If a path check if we are on it + if (tile_element->GetType() == TileElementType::Path) { - hungerCounter++; - break; - } - ride = GetRide(peep->GuestHeadingToRideId); - if (ride != nullptr && !ride->getRideTypeDescriptor().flags.has(RtdFlag::sellsFood)) - hungerCounter++; - break; + int32_t height = MapHeightFromSlope( + { x, y }, tile_element->AsPath()->GetSlopeDirection(), + tile_element->AsPath()->IsSloped()) + + tile_element->GetBaseZ(); - case PeepThoughtType::Thirsty: - if (peep->GuestHeadingToRideId.IsNull()) + if (height < z - 1 || height > z + 8) + continue; + + saved_height = height; + saved_map = tile_element; + break; + } // If a surface get the height and see if we are on it + else if (tile_element->GetType() == TileElementType::Surface) { - thirstCounter++; + // If the surface is water check to see if we could be drowning + if (tile_element->AsSurface()->GetWaterHeight() > 0) + { + int32_t height = tile_element->AsSurface()->GetWaterHeight(); + + if (height - 4 >= z && height < z + 20) + { + // Looks like we are drowning! + MoveTo({ x, y, height }); + + if (auto* guest = As(); guest != nullptr) + { + // Drop balloon if held + GuestReleaseBalloon(guest, height); + guest->InsertNewThought(PeepThoughtType::Drowning); + } + + Action = PeepActionType::drowning; + AnimationFrameNum = 0; + AnimationImageIdOffset = 0; + + UpdateCurrentAnimationType(); + PeepWindowStateUpdate(this); + return; + } + } + int32_t map_height = TileElementHeight({ x, y }); + if (map_height < z || map_height - 4 > z) + continue; + saved_height = map_height; + saved_map = tile_element; + } // If not a path or surface go see next element + } while (!(tile_element++)->IsLastForTile()); + } + + // This will be null if peep is falling + if (saved_map == nullptr) + { + if (z <= 1) + { + // Remove peep if it has gone to the void + Remove(); + return; + } + MoveTo({ x, y, z - 2 }); + return; + } + + MoveTo({ x, y, saved_height }); + + NextLoc = { CoordsXY{ x, y }.ToTileStart(), saved_map->GetBaseZ() }; + + if (saved_map->GetType() != TileElementType::Path) + { + SetNextFlags(0, false, true); + } + else + { + SetNextFlags(saved_map->AsPath()->GetSlopeDirection(), saved_map->AsPath()->IsSloped(), false); + } + SetState(PeepState::one); + } + + /** + * + * rct2: 0x6902A2 + */ + void Peep::Update1() + { + if (!CheckForPath()) + return; + + if (Is()) + { + SetState(PeepState::walking); + } + else + { + SetState(PeepState::patrolling); + } + + SetDestination(GetLocation(), 10); + PeepDirection = Orientation >> 3; + } + + void Peep::SetState(PeepState new_state) + { + PeepDecrementNumRiders(this); + State = new_state; + PeepWindowStateUpdate(this); + } + + /** + * + * rct2: 0x690009 + */ + void Peep::UpdatePicked() + { + if (getGameState().currentTicks & 0x1F) + return; + SubState++; + auto* guest = As(); + if (SubState == 13 && guest != nullptr) + { + guest->InsertNewThought(PeepThoughtType::Help); + } + } + + uint32_t Peep::GetStepsToTake() const + { + uint32_t stepsToTake = Energy; + if (stepsToTake < 95 && State == PeepState::queuing) + stepsToTake = 95; + if ((PeepFlags & PEEP_FLAGS_SLOW_WALK) && State != PeepState::queuing) + stepsToTake /= 2; + if (IsActionWalking() && GetNextIsSloped()) + { + stepsToTake /= 2; + if (State == PeepState::queuing) + stepsToTake += stepsToTake / 2; + } + // Ensure guests make it across a level crossing in time + constexpr auto minStepsForCrossing = 55; + if (stepsToTake < minStepsForCrossing && IsOnPathBlockedByVehicle()) + stepsToTake = minStepsForCrossing; + + return stepsToTake; + } + + /** + * + * rct2: 0x0069BF41 + */ + void PeepProblemWarningsUpdate() + { + auto& gameState = getGameState(); + + Ride* ride; + uint32_t hungerCounter = 0, lostCounter = 0, noexitCounter = 0, thirstCounter = 0, litterCounter = 0, + disgustCounter = 0, toiletCounter = 0, vandalismCounter = 0; + uint8_t* warningThrottle = gameState.park.peepWarningThrottle; + + int32_t inQueueCounter = 0; + int32_t tooLongQueueCounter = 0; + std::map queueComplainingGuestsMap; + + for (auto peep : EntityList()) + { + if (peep->OutsideOfPark) + continue; + + if (peep->State == PeepState::queuing || peep->State == PeepState::queuingFront) + inQueueCounter++; + + if (peep->Thoughts[0].freshness > 5) + continue; + + switch (peep->Thoughts[0].type) + { + case PeepThoughtType::Lost: // 0x10 + lostCounter++; break; - } - ride = GetRide(peep->GuestHeadingToRideId); - if (ride != nullptr && !ride->getRideTypeDescriptor().flags.has(RtdFlag::sellsDrinks)) - thirstCounter++; - break; - case PeepThoughtType::Toilet: - if (peep->GuestHeadingToRideId.IsNull()) - { - toiletCounter++; + case PeepThoughtType::Hungry: // 0x14 + if (peep->GuestHeadingToRideId.IsNull()) + { + hungerCounter++; + break; + } + ride = GetRide(peep->GuestHeadingToRideId); + if (ride != nullptr && !ride->getRideTypeDescriptor().flags.has(RtdFlag::sellsFood)) + hungerCounter++; break; - } - ride = GetRide(peep->GuestHeadingToRideId); - if (ride != nullptr && ride->getRideTypeDescriptor().specialType != RtdSpecialType::toilet) - toiletCounter++; - break; - case PeepThoughtType::BadLitter: // 0x1a - litterCounter++; - break; - case PeepThoughtType::CantFindExit: // 0x1b - noexitCounter++; - break; - case PeepThoughtType::PathDisgusting: // 0x1f - disgustCounter++; - break; - case PeepThoughtType::Vandalism: // 0x21 - vandalismCounter++; - break; - case PeepThoughtType::QueuingAges: - tooLongQueueCounter++; - queueComplainingGuestsMap[peep->Thoughts[0].rideId]++; - break; - default: - break; + case PeepThoughtType::Thirsty: + if (peep->GuestHeadingToRideId.IsNull()) + { + thirstCounter++; + break; + } + ride = GetRide(peep->GuestHeadingToRideId); + if (ride != nullptr && !ride->getRideTypeDescriptor().flags.has(RtdFlag::sellsDrinks)) + thirstCounter++; + break; + + case PeepThoughtType::Toilet: + if (peep->GuestHeadingToRideId.IsNull()) + { + toiletCounter++; + break; + } + ride = GetRide(peep->GuestHeadingToRideId); + if (ride != nullptr && ride->getRideTypeDescriptor().specialType != RtdSpecialType::toilet) + toiletCounter++; + break; + + case PeepThoughtType::BadLitter: // 0x1a + litterCounter++; + break; + case PeepThoughtType::CantFindExit: // 0x1b + noexitCounter++; + break; + case PeepThoughtType::PathDisgusting: // 0x1f + disgustCounter++; + break; + case PeepThoughtType::Vandalism: // 0x21 + vandalismCounter++; + break; + case PeepThoughtType::QueuingAges: + tooLongQueueCounter++; + queueComplainingGuestsMap[peep->Thoughts[0].rideId]++; + break; + default: + break; + } } - } - // could maybe be packed into a loop, would lose a lot of clarity though - if (warningThrottle[0]) - --warningThrottle[0]; - else if (hungerCounter >= kPeepHungerWarningThreshold && hungerCounter >= gameState.park.numGuestsInPark / 16) - { - warningThrottle[0] = 4; - if (Config::Get().notifications.guestWarnings) + // could maybe be packed into a loop, would lose a lot of clarity though + if (warningThrottle[0]) + --warningThrottle[0]; + else if (hungerCounter >= kPeepHungerWarningThreshold && hungerCounter >= gameState.park.numGuestsInPark / 16) { - constexpr auto thoughtId = static_cast(PeepThoughtType::Hungry); - News::AddItemToQueue(News::ItemType::peeps, STR_PEEPS_ARE_HUNGRY, thoughtId, {}); + warningThrottle[0] = 4; + if (Config::Get().notifications.guestWarnings) + { + constexpr auto thoughtId = static_cast(PeepThoughtType::Hungry); + News::AddItemToQueue(News::ItemType::peeps, STR_PEEPS_ARE_HUNGRY, thoughtId, {}); + } } - } - if (warningThrottle[1]) - --warningThrottle[1]; - else if (thirstCounter >= kPeepThirstWarningThreshold && thirstCounter >= gameState.park.numGuestsInPark / 16) - { - warningThrottle[1] = 4; - if (Config::Get().notifications.guestWarnings) + if (warningThrottle[1]) + --warningThrottle[1]; + else if (thirstCounter >= kPeepThirstWarningThreshold && thirstCounter >= gameState.park.numGuestsInPark / 16) { - constexpr auto thoughtId = static_cast(PeepThoughtType::Thirsty); - News::AddItemToQueue(News::ItemType::peeps, STR_PEEPS_ARE_THIRSTY, thoughtId, {}); + warningThrottle[1] = 4; + if (Config::Get().notifications.guestWarnings) + { + constexpr auto thoughtId = static_cast(PeepThoughtType::Thirsty); + News::AddItemToQueue(News::ItemType::peeps, STR_PEEPS_ARE_THIRSTY, thoughtId, {}); + } } - } - if (warningThrottle[2]) - --warningThrottle[2]; - else if (toiletCounter >= kPeepToiletWarningThreshold && toiletCounter >= gameState.park.numGuestsInPark / 16) - { - warningThrottle[2] = 4; - if (Config::Get().notifications.guestWarnings) + if (warningThrottle[2]) + --warningThrottle[2]; + else if (toiletCounter >= kPeepToiletWarningThreshold && toiletCounter >= gameState.park.numGuestsInPark / 16) { - constexpr auto thoughtId = static_cast(PeepThoughtType::Toilet); - News::AddItemToQueue(News::ItemType::peeps, STR_PEEPS_CANT_FIND_TOILET, thoughtId, {}); + warningThrottle[2] = 4; + if (Config::Get().notifications.guestWarnings) + { + constexpr auto thoughtId = static_cast(PeepThoughtType::Toilet); + News::AddItemToQueue(News::ItemType::peeps, STR_PEEPS_CANT_FIND_TOILET, thoughtId, {}); + } } - } - if (warningThrottle[3]) - --warningThrottle[3]; - else if (litterCounter >= kPeepLitterWarningThreshold && litterCounter >= gameState.park.numGuestsInPark / 32) - { - warningThrottle[3] = 4; - if (Config::Get().notifications.guestWarnings) + if (warningThrottle[3]) + --warningThrottle[3]; + else if (litterCounter >= kPeepLitterWarningThreshold && litterCounter >= gameState.park.numGuestsInPark / 32) { - constexpr auto thoughtId = static_cast(PeepThoughtType::BadLitter); - News::AddItemToQueue(News::ItemType::peeps, STR_PEEPS_DISLIKE_LITTER, thoughtId, {}); + warningThrottle[3] = 4; + if (Config::Get().notifications.guestWarnings) + { + constexpr auto thoughtId = static_cast(PeepThoughtType::BadLitter); + News::AddItemToQueue(News::ItemType::peeps, STR_PEEPS_DISLIKE_LITTER, thoughtId, {}); + } } - } - if (warningThrottle[4]) - --warningThrottle[4]; - else if (disgustCounter >= kPeepDisgustWarningThreshold && disgustCounter >= gameState.park.numGuestsInPark / 32) - { - warningThrottle[4] = 4; - if (Config::Get().notifications.guestWarnings) + if (warningThrottle[4]) + --warningThrottle[4]; + else if (disgustCounter >= kPeepDisgustWarningThreshold && disgustCounter >= gameState.park.numGuestsInPark / 32) { - constexpr auto thoughtId = static_cast(PeepThoughtType::PathDisgusting); - News::AddItemToQueue(News::ItemType::peeps, STR_PEEPS_DISGUSTED_BY_PATHS, thoughtId, {}); + warningThrottle[4] = 4; + if (Config::Get().notifications.guestWarnings) + { + constexpr auto thoughtId = static_cast(PeepThoughtType::PathDisgusting); + News::AddItemToQueue(News::ItemType::peeps, STR_PEEPS_DISGUSTED_BY_PATHS, thoughtId, {}); + } } - } - if (warningThrottle[5]) - --warningThrottle[5]; - else if (vandalismCounter >= kPeepVandalismWarningThreshold && vandalismCounter >= gameState.park.numGuestsInPark / 32) - { - warningThrottle[5] = 4; - if (Config::Get().notifications.guestWarnings) + if (warningThrottle[5]) + --warningThrottle[5]; + else if (vandalismCounter >= kPeepVandalismWarningThreshold && vandalismCounter >= gameState.park.numGuestsInPark / 32) { - constexpr auto thoughtId = static_cast(PeepThoughtType::Vandalism); - News::AddItemToQueue(News::ItemType::peeps, STR_PEEPS_DISLIKE_VANDALISM, thoughtId, {}); + warningThrottle[5] = 4; + if (Config::Get().notifications.guestWarnings) + { + constexpr auto thoughtId = static_cast(PeepThoughtType::Vandalism); + News::AddItemToQueue(News::ItemType::peeps, STR_PEEPS_DISLIKE_VANDALISM, thoughtId, {}); + } } - } - if (warningThrottle[6]) - --warningThrottle[6]; - else if (noexitCounter >= kPeepNoExitWarningThreshold) - { - warningThrottle[6] = 4; - if (Config::Get().notifications.guestWarnings) + if (warningThrottle[6]) + --warningThrottle[6]; + else if (noexitCounter >= kPeepNoExitWarningThreshold) { - constexpr auto thoughtId = static_cast(PeepThoughtType::CantFindExit); - News::AddItemToQueue(News::ItemType::peeps, STR_PEEPS_GETTING_LOST_OR_STUCK, thoughtId, {}); + warningThrottle[6] = 4; + if (Config::Get().notifications.guestWarnings) + { + constexpr auto thoughtId = static_cast(PeepThoughtType::CantFindExit); + News::AddItemToQueue(News::ItemType::peeps, STR_PEEPS_GETTING_LOST_OR_STUCK, thoughtId, {}); + } } - } - else if (lostCounter >= kPeepLostWarningThreshold) - { - warningThrottle[6] = 4; - if (Config::Get().notifications.guestWarnings) + else if (lostCounter >= kPeepLostWarningThreshold) { - constexpr auto thoughtId = static_cast(PeepThoughtType::Lost); - News::AddItemToQueue(News::ItemType::peeps, STR_PEEPS_GETTING_LOST_OR_STUCK, thoughtId, {}); + warningThrottle[6] = 4; + if (Config::Get().notifications.guestWarnings) + { + constexpr auto thoughtId = static_cast(PeepThoughtType::Lost); + News::AddItemToQueue(News::ItemType::peeps, STR_PEEPS_GETTING_LOST_OR_STUCK, thoughtId, {}); + } + } + + if (warningThrottle[7]) + --warningThrottle[7]; + else if (tooLongQueueCounter > kPeepTooLongQueueThreshold && tooLongQueueCounter > inQueueCounter / 20) + { // The amount of guests complaining about queue duration is at least 5% of the amount of queuing guests. + // This includes guests who are no longer queuing. + warningThrottle[7] = 4; + if (Config::Get().notifications.guestWarnings) + { + auto rideWithMostQueueComplaints = std::max_element( + queueComplainingGuestsMap.begin(), queueComplainingGuestsMap.end(), + [](auto& lhs, auto& rhs) { return lhs.second < rhs.second; }); + auto rideId = rideWithMostQueueComplaints->first.ToUnderlying(); + News::AddItemToQueue(News::ItemType::ride, STR_PEEPS_COMPLAINING_ABOUT_QUEUE_LENGTH_WARNING, rideId, {}); + } } } - if (warningThrottle[7]) - --warningThrottle[7]; - else if (tooLongQueueCounter > kPeepTooLongQueueThreshold && tooLongQueueCounter > inQueueCounter / 20) - { // The amount of guests complaining about queue duration is at least 5% of the amount of queuing guests. - // This includes guests who are no longer queuing. - warningThrottle[7] = 4; - if (Config::Get().notifications.guestWarnings) - { - auto rideWithMostQueueComplaints = std::max_element( - queueComplainingGuestsMap.begin(), queueComplainingGuestsMap.end(), - [](auto& lhs, auto& rhs) { return lhs.second < rhs.second; }); - auto rideId = rideWithMostQueueComplaints->first.ToUnderlying(); - News::AddItemToQueue(News::ItemType::ride, STR_PEEPS_COMPLAINING_ABOUT_QUEUE_LENGTH_WARNING, rideId, {}); - } - } -} - -void PeepStopCrowdNoise() -{ - if (_crowdSoundChannel != nullptr) + void PeepStopCrowdNoise() { - _crowdSoundChannel->Stop(); - _crowdSoundChannel = nullptr; - } -} - -/** - * - * rct2: 0x006BD18A - */ -void PeepUpdateCrowdNoise() -{ - PROFILED_FUNCTION(); - - if (gGameSoundsOff) - return; - - if (!Config::Get().sound.soundEnabled) - return; - - if (gLegacyScene == LegacyScene::scenarioEditor) - return; - - auto viewport = gMusicTrackingViewport; - if (viewport == nullptr) - return; - - // Count the number of peeps visible - auto visiblePeeps = 0; - - for (auto peep : EntityList()) - { - if (peep->x == kLocationNull) - continue; - if (viewport->viewPos.x > peep->SpriteData.SpriteRect.GetRight()) - continue; - if (viewport->viewPos.x + viewport->ViewWidth() < peep->SpriteData.SpriteRect.GetLeft()) - continue; - if (viewport->viewPos.y > peep->SpriteData.SpriteRect.GetBottom()) - continue; - if (viewport->viewPos.y + viewport->ViewHeight() < peep->SpriteData.SpriteRect.GetTop()) - continue; - - visiblePeeps += peep->State == PeepState::queuing ? 1 : 2; - } - - // This function doesn't account for the fact that the screen might be so big that 100 peeps could potentially be very - // spread out and therefore not produce any crowd noise. Perhaps a more sophisticated solution would check how many peeps - // were in close proximity to each other. - - // Allows queuing peeps to make half as much noise, and at least 6 peeps must be visible for any crowd noise - visiblePeeps = (visiblePeeps / 2) - 6; - if (visiblePeeps < 0) - { - // Mute crowd noise if (_crowdSoundChannel != nullptr) { - _crowdSoundChannel->SetVolume(0); + _crowdSoundChannel->Stop(); + _crowdSoundChannel = nullptr; } } - else - { - // Formula to scale peeps to dB where peeps [0, 120] scales approximately logarithmically to [-3314, -150] dB/100 - // 207360000 maybe related to DSBVOLUME_MIN which is -10,000 (dB/100) - int32_t volume = 120 - std::min(visiblePeeps, 120); - volume = volume * volume * volume * volume; - volume = (viewport->zoom.ApplyInversedTo(207360000 - volume) - 207360000) / 65536 - 150; - // Load and play crowd noise if needed and set volume - if (_crowdSoundChannel == nullptr || _crowdSoundChannel->IsDone()) + /** + * + * rct2: 0x006BD18A + */ + void PeepUpdateCrowdNoise() + { + PROFILED_FUNCTION(); + + if (gGameSoundsOff) + return; + + if (!Config::Get().sound.soundEnabled) + return; + + if (gLegacyScene == LegacyScene::scenarioEditor) + return; + + auto viewport = gMusicTrackingViewport; + if (viewport == nullptr) + return; + + // Count the number of peeps visible + auto visiblePeeps = 0; + + for (auto peep : EntityList()) { - _crowdSoundChannel = CreateAudioChannel(SoundId::crowdAmbience, true, 0); + if (peep->x == kLocationNull) + continue; + if (viewport->viewPos.x > peep->SpriteData.SpriteRect.GetRight()) + continue; + if (viewport->viewPos.x + viewport->ViewWidth() < peep->SpriteData.SpriteRect.GetLeft()) + continue; + if (viewport->viewPos.y > peep->SpriteData.SpriteRect.GetBottom()) + continue; + if (viewport->viewPos.y + viewport->ViewHeight() < peep->SpriteData.SpriteRect.GetTop()) + continue; + + visiblePeeps += peep->State == PeepState::queuing ? 1 : 2; + } + + // This function doesn't account for the fact that the screen might be so big that 100 peeps could potentially be very + // spread out and therefore not produce any crowd noise. Perhaps a more sophisticated solution would check how many + // peeps were in close proximity to each other. + + // Allows queuing peeps to make half as much noise, and at least 6 peeps must be visible for any crowd noise + visiblePeeps = (visiblePeeps / 2) - 6; + if (visiblePeeps < 0) + { + // Mute crowd noise if (_crowdSoundChannel != nullptr) { - _crowdSoundChannel->SetGroup(MixerGroup::Sound); + _crowdSoundChannel->SetVolume(0); } } - if (_crowdSoundChannel != nullptr) + else { - _crowdSoundChannel->SetVolume(DStoMixerVolume(volume)); - } - } -} + // Formula to scale peeps to dB where peeps [0, 120] scales approximately logarithmically to [-3314, -150] dB/100 + // 207360000 maybe related to DSBVOLUME_MIN which is -10,000 (dB/100) + int32_t volume = 120 - std::min(visiblePeeps, 120); + volume = volume * volume * volume * volume; + volume = (viewport->zoom.ApplyInversedTo(207360000 - volume) - 207360000) / 65536 - 150; -/** - * - * rct2: 0x0069BE9B - */ -void PeepApplause() -{ - for (auto peep : EntityList()) - { - if (peep->OutsideOfPark || peep->PeepFlags & PEEP_FLAGS_POSITION_FROZEN - || peep->PeepFlags & PEEP_FLAGS_ANIMATION_FROZEN) - continue; - - // Release balloon - GuestReleaseBalloon(peep, peep->z + 9); - - // Clap - if ((peep->State == PeepState::walking || peep->State == PeepState::queuing) && peep->IsActionInterruptableSafely()) - { - peep->Action = PeepActionType::clap; - peep->AnimationFrameNum = 0; - peep->AnimationImageIdOffset = 0; - peep->UpdateCurrentAnimationType(); - } - } - - // Play applause noise - Play(SoundId::applause, 0, ContextGetWidth() / 2); -} - -/** - * - * rct2: 0x0069C35E - */ -void PeepUpdateDaysInQueue() -{ - for (auto peep : EntityList()) - { - if (!peep->OutsideOfPark && (peep->State == PeepState::queuing)) - { - peep->DaysInQueue = AddClamp(peep->DaysInQueue, 1); - } - } -} - -void Peep::FormatActionTo(Formatter& ft) const -{ - switch (State) - { - case PeepState::falling: - ft.Add(Action == PeepActionType::drowning ? STR_DROWNING : STR_WALKING); - break; - case PeepState::one: - ft.Add(STR_WALKING); - break; - case PeepState::onRide: - case PeepState::leavingRide: - case PeepState::enteringRide: - { - auto ride = GetRide(CurrentRide); - if (ride != nullptr) + // Load and play crowd noise if needed and set volume + if (_crowdSoundChannel == nullptr || _crowdSoundChannel->IsDone()) { - ft.Add( - ride->getRideTypeDescriptor().flags.has(RtdFlag::describeAsInside) ? STR_IN_RIDE : STR_ON_RIDE); - ride->formatNameTo(ft); - } - else - { - ft.Add(STR_ON_RIDE).Add(kStringIdNone); - } - break; - } - case PeepState::buying: - { - ft.Add(STR_AT_RIDE); - auto ride = GetRide(CurrentRide); - if (ride != nullptr) - { - ride->formatNameTo(ft); - } - else - { - ft.Add(kStringIdNone); - } - break; - } - case PeepState::walking: - case PeepState::usingBin: - { - if (auto* guest = As(); guest != nullptr) - { - if (!guest->GuestHeadingToRideId.IsNull()) + _crowdSoundChannel = CreateAudioChannel(SoundId::crowdAmbience, true, 0); + if (_crowdSoundChannel != nullptr) { - auto ride = GetRide(guest->GuestHeadingToRideId); - if (ride != nullptr) - { - ft.Add(STR_HEADING_FOR); - ride->formatNameTo(ft); - } - } - else - { - ft.Add((PeepFlags & PEEP_FLAGS_LEAVING_PARK) ? STR_LEAVING_PARK : STR_WALKING); + _crowdSoundChannel->SetGroup(MixerGroup::Sound); } } - break; - } - case PeepState::queuingFront: - case PeepState::queuing: - { - auto ride = GetRide(CurrentRide); - if (ride != nullptr) + if (_crowdSoundChannel != nullptr) { - ft.Add(STR_QUEUING_FOR); - ride->formatNameTo(ft); + _crowdSoundChannel->SetVolume(DStoMixerVolume(volume)); } - break; } - case PeepState::sitting: - ft.Add(STR_SITTING); - break; - case PeepState::watching: - if (!CurrentRide.IsNull()) + } + + /** + * + * rct2: 0x0069BE9B + */ + void PeepApplause() + { + for (auto peep : EntityList()) + { + if (peep->OutsideOfPark || peep->PeepFlags & PEEP_FLAGS_POSITION_FROZEN + || peep->PeepFlags & PEEP_FLAGS_ANIMATION_FROZEN) + continue; + + // Release balloon + GuestReleaseBalloon(peep, peep->z + 9); + + // Clap + if ((peep->State == PeepState::walking || peep->State == PeepState::queuing) && peep->IsActionInterruptableSafely()) + { + peep->Action = PeepActionType::clap; + peep->AnimationFrameNum = 0; + peep->AnimationImageIdOffset = 0; + peep->UpdateCurrentAnimationType(); + } + } + + // Play applause noise + Play(SoundId::applause, 0, ContextGetWidth() / 2); + } + + /** + * + * rct2: 0x0069C35E + */ + void PeepUpdateDaysInQueue() + { + for (auto peep : EntityList()) + { + if (!peep->OutsideOfPark && (peep->State == PeepState::queuing)) + { + peep->DaysInQueue = AddClamp(peep->DaysInQueue, 1); + } + } + } + + void Peep::FormatActionTo(Formatter& ft) const + { + switch (State) + { + case PeepState::falling: + ft.Add(Action == PeepActionType::drowning ? STR_DROWNING : STR_WALKING); + break; + case PeepState::one: + ft.Add(STR_WALKING); + break; + case PeepState::onRide: + case PeepState::leavingRide: + case PeepState::enteringRide: { auto ride = GetRide(CurrentRide); if (ride != nullptr) { - ft.Add((StandingFlags & 0x1) ? STR_WATCHING_CONSTRUCTION_OF : STR_WATCHING_RIDE); + ft.Add( + ride->getRideTypeDescriptor().flags.has(RtdFlag::describeAsInside) ? STR_IN_RIDE : STR_ON_RIDE); ride->formatNameTo(ft); } + else + { + ft.Add(STR_ON_RIDE).Add(kStringIdNone); + } + break; } - else + case PeepState::buying: { - ft.Add((StandingFlags & 0x1) ? STR_WATCHING_NEW_RIDE_BEING_CONSTRUCTED : STR_LOOKING_AT_SCENERY); - } - break; - case PeepState::picked: - ft.Add(STR_SELECT_LOCATION); - break; - case PeepState::patrolling: - case PeepState::enteringPark: - case PeepState::leavingPark: - ft.Add(STR_WALKING); - break; - case PeepState::mowing: - ft.Add(STR_MOWING_GRASS); - break; - case PeepState::sweeping: - ft.Add(STR_SWEEPING_FOOTPATH); - break; - case PeepState::watering: - ft.Add(STR_WATERING_GARDENS); - break; - case PeepState::emptyingBin: - ft.Add(STR_EMPTYING_LITTER_BIN); - break; - case PeepState::answering: - if (SubState == 0) - { - ft.Add(STR_WALKING); - } - else if (SubState == 1) - { - ft.Add(STR_ANSWERING_RADIO_CALL); - } - else - { - ft.Add(STR_RESPONDING_TO_RIDE_BREAKDOWN_CALL); + ft.Add(STR_AT_RIDE); auto ride = GetRide(CurrentRide); if (ride != nullptr) { @@ -1415,493 +1326,495 @@ void Peep::FormatActionTo(Formatter& ft) const { ft.Add(kStringIdNone); } + break; } - break; - case PeepState::fixing: - { - ft.Add(STR_FIXING_RIDE); - auto ride = GetRide(CurrentRide); - if (ride != nullptr) + case PeepState::walking: + case PeepState::usingBin: { - ride->formatNameTo(ft); + if (auto* guest = As(); guest != nullptr) + { + if (!guest->GuestHeadingToRideId.IsNull()) + { + auto ride = GetRide(guest->GuestHeadingToRideId); + if (ride != nullptr) + { + ft.Add(STR_HEADING_FOR); + ride->formatNameTo(ft); + } + } + else + { + ft.Add((PeepFlags & PEEP_FLAGS_LEAVING_PARK) ? STR_LEAVING_PARK : STR_WALKING); + } + } + break; } - else + case PeepState::queuingFront: + case PeepState::queuing: { - ft.Add(kStringIdNone); + auto ride = GetRide(CurrentRide); + if (ride != nullptr) + { + ft.Add(STR_QUEUING_FOR); + ride->formatNameTo(ft); + } + break; } - break; - } - case PeepState::headingToInspection: - { - ft.Add(STR_HEADING_TO_RIDE_FOR_INSPECTION); - auto ride = GetRide(CurrentRide); - if (ride != nullptr) + case PeepState::sitting: + ft.Add(STR_SITTING); + break; + case PeepState::watching: + if (!CurrentRide.IsNull()) + { + auto ride = GetRide(CurrentRide); + if (ride != nullptr) + { + ft.Add((StandingFlags & 0x1) ? STR_WATCHING_CONSTRUCTION_OF : STR_WATCHING_RIDE); + ride->formatNameTo(ft); + } + } + else + { + ft.Add((StandingFlags & 0x1) ? STR_WATCHING_NEW_RIDE_BEING_CONSTRUCTED : STR_LOOKING_AT_SCENERY); + } + break; + case PeepState::picked: + ft.Add(STR_SELECT_LOCATION); + break; + case PeepState::patrolling: + case PeepState::enteringPark: + case PeepState::leavingPark: + ft.Add(STR_WALKING); + break; + case PeepState::mowing: + ft.Add(STR_MOWING_GRASS); + break; + case PeepState::sweeping: + ft.Add(STR_SWEEPING_FOOTPATH); + break; + case PeepState::watering: + ft.Add(STR_WATERING_GARDENS); + break; + case PeepState::emptyingBin: + ft.Add(STR_EMPTYING_LITTER_BIN); + break; + case PeepState::answering: + if (SubState == 0) + { + ft.Add(STR_WALKING); + } + else if (SubState == 1) + { + ft.Add(STR_ANSWERING_RADIO_CALL); + } + else + { + ft.Add(STR_RESPONDING_TO_RIDE_BREAKDOWN_CALL); + auto ride = GetRide(CurrentRide); + if (ride != nullptr) + { + ride->formatNameTo(ft); + } + else + { + ft.Add(kStringIdNone); + } + } + break; + case PeepState::fixing: { - ride->formatNameTo(ft); + ft.Add(STR_FIXING_RIDE); + auto ride = GetRide(CurrentRide); + if (ride != nullptr) + { + ride->formatNameTo(ft); + } + else + { + ft.Add(kStringIdNone); + } + break; } - else + case PeepState::headingToInspection: { - ft.Add(kStringIdNone); + ft.Add(STR_HEADING_TO_RIDE_FOR_INSPECTION); + auto ride = GetRide(CurrentRide); + if (ride != nullptr) + { + ride->formatNameTo(ft); + } + else + { + ft.Add(kStringIdNone); + } + break; } - break; - } - case PeepState::inspecting: - { - ft.Add(STR_INSPECTING_RIDE); - auto ride = GetRide(CurrentRide); - if (ride != nullptr) + case PeepState::inspecting: { - ride->formatNameTo(ft); + ft.Add(STR_INSPECTING_RIDE); + auto ride = GetRide(CurrentRide); + if (ride != nullptr) + { + ride->formatNameTo(ft); + } + else + { + ft.Add(kStringIdNone); + } + break; } - else - { - ft.Add(kStringIdNone); - } - break; } } -} -static constexpr StringId kStaffNames[] = { - STR_HANDYMAN_X, - STR_MECHANIC_X, - STR_SECURITY_GUARD_X, - STR_ENTERTAINER_X, -}; + static constexpr StringId kStaffNames[] = { + STR_HANDYMAN_X, + STR_MECHANIC_X, + STR_SECURITY_GUARD_X, + STR_ENTERTAINER_X, + }; -void Peep::FormatNameTo(Formatter& ft) const -{ - if (Name == nullptr) + void Peep::FormatNameTo(Formatter& ft) const { - auto& gameState = getGameState(); - const bool showGuestNames = gameState.park.flags & PARK_FLAGS_SHOW_REAL_GUEST_NAMES; - const bool showStaffNames = gameState.park.flags & PARK_FLAGS_SHOW_REAL_STAFF_NAMES; - - auto* staff = As(); - const bool isStaff = staff != nullptr; - - if ((!isStaff && showGuestNames) || (isStaff && showStaffNames)) + if (Name == nullptr) { - auto nameId = PeepId; - if (isStaff) - { - // Prevent staff from getting the same names by offsetting the name table based on staff type. - nameId *= 256 * EnumValue(staff->AssignedStaffType) + 1; - } + auto& gameState = getGameState(); + const bool showGuestNames = gameState.park.flags & PARK_FLAGS_SHOW_REAL_GUEST_NAMES; + const bool showStaffNames = gameState.park.flags & PARK_FLAGS_SHOW_REAL_STAFF_NAMES; - auto realNameStringId = GetRealNameStringIDFromPeepID(nameId); - ft.Add(realNameStringId); - } - else if (isStaff) - { - auto staffNameIndex = static_cast(staff->AssignedStaffType); - if (staffNameIndex >= std::size(kStaffNames)) - { - staffNameIndex = 0; - } + auto* staff = As(); + const bool isStaff = staff != nullptr; - ft.Add(kStaffNames[staffNameIndex]); - ft.Add(PeepId); + if ((!isStaff && showGuestNames) || (isStaff && showStaffNames)) + { + auto nameId = PeepId; + if (isStaff) + { + // Prevent staff from getting the same names by offsetting the name table based on staff type. + nameId *= 256 * EnumValue(staff->AssignedStaffType) + 1; + } + + auto realNameStringId = GetRealNameStringIDFromPeepID(nameId); + ft.Add(realNameStringId); + } + else if (isStaff) + { + auto staffNameIndex = static_cast(staff->AssignedStaffType); + if (staffNameIndex >= std::size(kStaffNames)) + { + staffNameIndex = 0; + } + + ft.Add(kStaffNames[staffNameIndex]); + ft.Add(PeepId); + } + else + { + ft.Add(STR_GUEST_X).Add(PeepId); + } } else { - ft.Add(STR_GUEST_X).Add(PeepId); + ft.Add(STR_STRING).Add(Name); } } - else - { - ft.Add(STR_STRING).Add(Name); - } -} -std::string Peep::GetName() const -{ - Formatter ft; - FormatNameTo(ft); - return FormatStringIDLegacy(STR_STRINGID, ft.Data()); -} - -bool Peep::SetName(std::string_view value) -{ - if (value.empty()) + std::string Peep::GetName() const { - std::free(Name); - Name = nullptr; - return true; + Formatter ft; + FormatNameTo(ft); + return FormatStringIDLegacy(STR_STRINGID, ft.Data()); } - auto newNameMemory = static_cast(std::malloc(value.size() + 1)); - if (newNameMemory != nullptr) + bool Peep::SetName(std::string_view value) { - std::memcpy(newNameMemory, value.data(), value.size()); - newNameMemory[value.size()] = '\0'; - std::free(Name); - Name = newNameMemory; - return true; - } - return false; -} - -bool Peep::IsActionWalking() const -{ - return Action == PeepActionType::walking; -} - -bool Peep::IsActionIdle() const -{ - return Action == PeepActionType::idle; -} - -bool Peep::IsActionInterruptable() const -{ - return IsActionIdle() || IsActionWalking(); -} - -/** - * Used to avoid peep action and animation triggers that cause them to stop moving and might put them at risk - * of getting run over at level crossings, such as guests reading the map and entertainers performing. - */ -bool Peep::IsActionInterruptableSafely() const -{ - return IsActionInterruptable() && !IsOnLevelCrossing(); -} - -void PeepSetMapTooltip(Peep* peep) -{ - auto ft = Formatter(); - if (auto* guest = peep->As(); guest != nullptr) - { - ft.Add((peep->PeepFlags & PEEP_FLAGS_TRACKING) ? STR_TRACKED_GUEST_MAP_TIP : STR_GUEST_MAP_TIP); - ft.Add(GetPeepFaceSpriteSmall(guest)); - guest->FormatNameTo(ft); - guest->FormatActionTo(ft); - } - else - { - ft.Add(STR_STAFF_MAP_TIP); - peep->FormatNameTo(ft); - peep->FormatActionTo(ft); - } - - auto intent = Intent(INTENT_ACTION_SET_MAP_TOOLTIP); - intent.PutExtra(INTENT_EXTRA_FORMATTER, &ft); - ContextBroadcastIntent(&intent); -} - -/** - * rct2: 0x00693BAB - */ -void Peep::SwitchNextAnimationType() -{ - // TBD: Add nextAnimationType as function parameter and make peep->NextAnimationType obsolete? - if (NextAnimationType != AnimationType) - { - Invalidate(); - AnimationType = NextAnimationType; - - auto& objManager = GetContext()->GetObjectManager(); - auto* animObj = objManager.GetLoadedObject(AnimationObjectIndex); - - const auto& spriteBounds = animObj->GetSpriteBounds(AnimationGroup, NextAnimationType); - SpriteData.Width = spriteBounds.spriteWidth; - SpriteData.HeightMin = spriteBounds.spriteHeightNegative; - SpriteData.HeightMax = spriteBounds.spriteHeightPositive; - Invalidate(); - } -} - -/** - * - * rct2: 0x00693EF2 - */ -static void PeepReturnToCentreOfTile(Peep* peep) -{ - peep->PeepDirection = DirectionReverse(peep->PeepDirection); - auto destination = peep->GetLocation().ToTileCentre(); - peep->SetDestination(destination, 5); -} - -/** - * - * rct2: 0x00693f2C - */ -static bool PeepInteractWithEntrance(Peep* peep, const CoordsXYE& coords, uint8_t& pathing_result) -{ - auto tile_element = coords.element; - uint8_t entranceType = tile_element->AsEntrance()->GetEntranceType(); - auto rideIndex = tile_element->AsEntrance()->GetRideIndex(); - - if ((entranceType == ENTRANCE_TYPE_RIDE_ENTRANCE) || (entranceType == ENTRANCE_TYPE_RIDE_EXIT)) - { - // If an entrance or exit that doesn't belong to the ride we are queuing for ignore the entrance/exit - // This can happen when paths clip through entrance/exits - if (peep->State == PeepState::queuing && peep->CurrentRide != rideIndex) + if (value.empty()) { - return false; + std::free(Name); + Name = nullptr; + return true; + } + + auto newNameMemory = static_cast(std::malloc(value.size() + 1)); + if (newNameMemory != nullptr) + { + std::memcpy(newNameMemory, value.data(), value.size()); + newNameMemory[value.size()] = '\0'; + std::free(Name); + Name = newNameMemory; + return true; + } + return false; + } + + bool Peep::IsActionWalking() const + { + return Action == PeepActionType::walking; + } + + bool Peep::IsActionIdle() const + { + return Action == PeepActionType::idle; + } + + bool Peep::IsActionInterruptable() const + { + return IsActionIdle() || IsActionWalking(); + } + + /** + * Used to avoid peep action and animation triggers that cause them to stop moving and might put them at risk + * of getting run over at level crossings, such as guests reading the map and entertainers performing. + */ + bool Peep::IsActionInterruptableSafely() const + { + return IsActionInterruptable() && !IsOnLevelCrossing(); + } + + void PeepSetMapTooltip(Peep* peep) + { + auto ft = Formatter(); + if (auto* guest = peep->As(); guest != nullptr) + { + ft.Add((peep->PeepFlags & PEEP_FLAGS_TRACKING) ? STR_TRACKED_GUEST_MAP_TIP : STR_GUEST_MAP_TIP); + ft.Add(GetPeepFaceSpriteSmall(guest)); + guest->FormatNameTo(ft); + guest->FormatActionTo(ft); + } + else + { + ft.Add(STR_STAFF_MAP_TIP); + peep->FormatNameTo(ft); + peep->FormatActionTo(ft); + } + + auto intent = Intent(INTENT_ACTION_SET_MAP_TOOLTIP); + intent.PutExtra(INTENT_EXTRA_FORMATTER, &ft); + ContextBroadcastIntent(&intent); + } + + /** + * rct2: 0x00693BAB + */ + void Peep::SwitchNextAnimationType() + { + // TBD: Add nextAnimationType as function parameter and make peep->NextAnimationType obsolete? + if (NextAnimationType != AnimationType) + { + Invalidate(); + AnimationType = NextAnimationType; + + auto& objManager = GetContext()->GetObjectManager(); + auto* animObj = objManager.GetLoadedObject(AnimationObjectIndex); + + const auto& spriteBounds = animObj->GetSpriteBounds(AnimationGroup, NextAnimationType); + SpriteData.Width = spriteBounds.spriteWidth; + SpriteData.HeightMin = spriteBounds.spriteHeightNegative; + SpriteData.HeightMax = spriteBounds.spriteHeightPositive; + Invalidate(); } } - // Store some details to determine when to override the default - // behaviour (defined below) for when staff attempt to enter a ride - // to fix/inspect it. - if (entranceType == ENTRANCE_TYPE_RIDE_EXIT) + + /** + * + * rct2: 0x00693EF2 + */ + static void PeepReturnToCentreOfTile(Peep* peep) { - pathing_result |= PATHING_RIDE_EXIT; - _peepRideEntranceExitElement = tile_element; - } - else if (entranceType == ENTRANCE_TYPE_RIDE_ENTRANCE) - { - pathing_result |= PATHING_RIDE_ENTRANCE; - _peepRideEntranceExitElement = tile_element; + peep->PeepDirection = DirectionReverse(peep->PeepDirection); + auto destination = peep->GetLocation().ToTileCentre(); + peep->SetDestination(destination, 5); } - if (entranceType == ENTRANCE_TYPE_RIDE_EXIT) + /** + * + * rct2: 0x00693f2C + */ + static bool PeepInteractWithEntrance(Peep* peep, const CoordsXYE& coords, uint8_t& pathing_result) { - // Default guest/staff behaviour attempting to enter a - // ride exit is to turn around. - peep->InteractionRideIndex = RideId::GetNull(); - PeepReturnToCentreOfTile(peep); - return true; - } + auto tile_element = coords.element; + uint8_t entranceType = tile_element->AsEntrance()->GetEntranceType(); + auto rideIndex = tile_element->AsEntrance()->GetRideIndex(); - if (entranceType == ENTRANCE_TYPE_RIDE_ENTRANCE) - { - auto ride = GetRide(rideIndex); - if (ride == nullptr) - return false; - - auto* guest = peep->As(); - if (guest == nullptr) + if ((entranceType == ENTRANCE_TYPE_RIDE_ENTRANCE) || (entranceType == ENTRANCE_TYPE_RIDE_EXIT)) { - // Default staff behaviour attempting to enter a - // ride entrance is to turn around. + // If an entrance or exit that doesn't belong to the ride we are queuing for ignore the entrance/exit + // This can happen when paths clip through entrance/exits + if (peep->State == PeepState::queuing && peep->CurrentRide != rideIndex) + { + return false; + } + } + // Store some details to determine when to override the default + // behaviour (defined below) for when staff attempt to enter a ride + // to fix/inspect it. + if (entranceType == ENTRANCE_TYPE_RIDE_EXIT) + { + pathing_result |= PATHING_RIDE_EXIT; + _peepRideEntranceExitElement = tile_element; + } + else if (entranceType == ENTRANCE_TYPE_RIDE_ENTRANCE) + { + pathing_result |= PATHING_RIDE_ENTRANCE; + _peepRideEntranceExitElement = tile_element; + } + + if (entranceType == ENTRANCE_TYPE_RIDE_EXIT) + { + // Default guest/staff behaviour attempting to enter a + // ride exit is to turn around. peep->InteractionRideIndex = RideId::GetNull(); PeepReturnToCentreOfTile(peep); return true; } - if (guest->State == PeepState::queuing) + if (entranceType == ENTRANCE_TYPE_RIDE_ENTRANCE) { - // Guest is in the ride queue. - guest->RideSubState = PeepRideSubState::atQueueFront; + auto ride = GetRide(rideIndex); + if (ride == nullptr) + return false; + + auto* guest = peep->As(); + if (guest == nullptr) + { + // Default staff behaviour attempting to enter a + // ride entrance is to turn around. + peep->InteractionRideIndex = RideId::GetNull(); + PeepReturnToCentreOfTile(peep); + return true; + } + + if (guest->State == PeepState::queuing) + { + // Guest is in the ride queue. + guest->RideSubState = PeepRideSubState::atQueueFront; + guest->AnimationImageIdOffset = _backupAnimationImageIdOffset; + return true; + } + + // Guest is on a normal path, i.e. ride has no queue. + if (guest->InteractionRideIndex == rideIndex) + { + // Peep is retrying the ride entrance without leaving + // the path tile and without trying any other ride + // attached to this path tile. i.e. stick with the + // peeps previous decision not to go on the ride. + PeepReturnToCentreOfTile(guest); + return true; + } + + guest->TimeLost = 0; + auto stationNum = tile_element->AsEntrance()->GetStationIndex(); + // Guest walks up to the ride for the first time since entering + // the path tile or since considering another ride attached to + // the path tile. + if (!guest->ShouldGoOnRide(*ride, stationNum, false, false)) + { + // Peep remembers that this is the last ride they + // considered while on this path tile. + guest->InteractionRideIndex = rideIndex; + PeepReturnToCentreOfTile(guest); + return true; + } + + // Guest has decided to go on the ride. guest->AnimationImageIdOffset = _backupAnimationImageIdOffset; - return true; - } - - // Guest is on a normal path, i.e. ride has no queue. - if (guest->InteractionRideIndex == rideIndex) - { - // Peep is retrying the ride entrance without leaving - // the path tile and without trying any other ride - // attached to this path tile. i.e. stick with the - // peeps previous decision not to go on the ride. - PeepReturnToCentreOfTile(guest); - return true; - } - - guest->TimeLost = 0; - auto stationNum = tile_element->AsEntrance()->GetStationIndex(); - // Guest walks up to the ride for the first time since entering - // the path tile or since considering another ride attached to - // the path tile. - if (!guest->ShouldGoOnRide(*ride, stationNum, false, false)) - { - // Peep remembers that this is the last ride they - // considered while on this path tile. guest->InteractionRideIndex = rideIndex; - PeepReturnToCentreOfTile(guest); - return true; - } - // Guest has decided to go on the ride. - guest->AnimationImageIdOffset = _backupAnimationImageIdOffset; - guest->InteractionRideIndex = rideIndex; + auto& station = ride->getStation(stationNum); + auto previous_last = station.LastPeepInQueue; + station.LastPeepInQueue = guest->Id; + guest->GuestNextInQueue = previous_last; + station.QueueLength++; - auto& station = ride->getStation(stationNum); - auto previous_last = station.LastPeepInQueue; - station.LastPeepInQueue = guest->Id; - guest->GuestNextInQueue = previous_last; - station.QueueLength++; - - guest->CurrentRide = rideIndex; - guest->CurrentRideStation = stationNum; - guest->DaysInQueue = 0; - guest->SetState(PeepState::queuing); - guest->RideSubState = PeepRideSubState::atQueueFront; - guest->TimeInQueue = 0; - if (guest->PeepFlags & PEEP_FLAGS_TRACKING) - { - auto ft = Formatter(); - guest->FormatNameTo(ft); - ride->formatNameTo(ft); - if (Config::Get().notifications.guestQueuingForRide) - { - News::AddItemToQueue(News::ItemType::peepOnRide, STR_PEEP_TRACKING_PEEP_JOINED_QUEUE_FOR_X, guest->Id, ft); - } - } - } - else - { - // PARK_ENTRANCE - auto* guest = peep->As(); - if (guest == nullptr) - { - // Staff cannot leave the park, so go back. - PeepReturnToCentreOfTile(peep); - return true; - } - - // If not the centre of the entrance arch - if (tile_element->AsEntrance()->GetSequenceIndex() != 0) - { - PeepReturnToCentreOfTile(guest); - return true; - } - - auto& gameState = getGameState(); - uint8_t entranceDirection = tile_element->GetDirection(); - if (entranceDirection != guest->PeepDirection) - { - if (DirectionReverse(entranceDirection) != guest->PeepDirection) - { - PeepReturnToCentreOfTile(guest); - return true; - } - - // Peep is leaving the park. - if (guest->State != PeepState::walking) - { - PeepReturnToCentreOfTile(guest); - return true; - } - - if (!(guest->PeepFlags & PEEP_FLAGS_LEAVING_PARK)) - { - // If the park is open and leaving flag isn't set return to centre - if (gameState.park.flags & PARK_FLAGS_PARK_OPEN) - { - PeepReturnToCentreOfTile(guest); - return true; - } - } - - auto destination = guest->GetDestination() + CoordsDirectionDelta[guest->PeepDirection]; - guest->SetDestination(destination, 9); - guest->MoveTo({ coords, guest->z }); - guest->SetState(PeepState::leavingPark); - - guest->Var37 = 0; + guest->CurrentRide = rideIndex; + guest->CurrentRideStation = stationNum; + guest->DaysInQueue = 0; + guest->SetState(PeepState::queuing); + guest->RideSubState = PeepRideSubState::atQueueFront; + guest->TimeInQueue = 0; if (guest->PeepFlags & PEEP_FLAGS_TRACKING) { auto ft = Formatter(); guest->FormatNameTo(ft); - if (Config::Get().notifications.guestLeftPark) + ride->formatNameTo(ft); + if (Config::Get().notifications.guestQueuingForRide) { - News::AddItemToQueue(News::ItemType::peepOnRide, STR_PEEP_TRACKING_LEFT_PARK, guest->Id, ft); + News::AddItemToQueue(News::ItemType::peepOnRide, STR_PEEP_TRACKING_PEEP_JOINED_QUEUE_FOR_X, guest->Id, ft); } } - return true; } - - // Peep is entering the park. - - if (guest->State != PeepState::enteringPark) + else { - PeepReturnToCentreOfTile(guest); - return true; - } - - if (!(gameState.park.flags & PARK_FLAGS_PARK_OPEN)) - { - guest->State = PeepState::leavingPark; - guest->Var37 = 1; - DecrementGuestsHeadingForPark(); - PeepWindowStateUpdate(guest); - PeepReturnToCentreOfTile(guest); - return true; - } - - bool found = false; - auto entrance = std::find_if(gameState.park.entrances.begin(), gameState.park.entrances.end(), [coords](const auto& e) { - return coords.ToTileStart() == e; - }); - if (entrance != gameState.park.entrances.end()) - { - int16_t z = entrance->z / 8; - entranceDirection = entrance->direction; - auto nextLoc = coords.ToTileStart() + CoordsDirectionDelta[entranceDirection]; - - // Make sure there is a path right behind the entrance, otherwise turn around - TileElement* nextTileElement = MapGetFirstElementAt(nextLoc); - do + // PARK_ENTRANCE + auto* guest = peep->As(); + if (guest == nullptr) { - if (nextTileElement == nullptr) - break; - if (nextTileElement->GetType() != TileElementType::Path) - continue; + // Staff cannot leave the park, so go back. + PeepReturnToCentreOfTile(peep); + return true; + } - if (nextTileElement->AsPath()->IsQueue()) - continue; + // If not the centre of the entrance arch + if (tile_element->AsEntrance()->GetSequenceIndex() != 0) + { + PeepReturnToCentreOfTile(guest); + return true; + } - if (nextTileElement->AsPath()->IsSloped()) + auto& gameState = getGameState(); + uint8_t entranceDirection = tile_element->GetDirection(); + if (entranceDirection != guest->PeepDirection) + { + if (DirectionReverse(entranceDirection) != guest->PeepDirection) { - uint8_t slopeDirection = nextTileElement->AsPath()->GetSlopeDirection(); - if (slopeDirection == entranceDirection) + PeepReturnToCentreOfTile(guest); + return true; + } + + // Peep is leaving the park. + if (guest->State != PeepState::walking) + { + PeepReturnToCentreOfTile(guest); + return true; + } + + if (!(guest->PeepFlags & PEEP_FLAGS_LEAVING_PARK)) + { + // If the park is open and leaving flag isn't set return to centre + if (gameState.park.flags & PARK_FLAGS_PARK_OPEN) { - if (z != nextTileElement->BaseHeight) - { - continue; - } - found = true; - break; + PeepReturnToCentreOfTile(guest); + return true; } - - if (DirectionReverse(slopeDirection) != entranceDirection) - continue; - - if (z - 2 != nextTileElement->BaseHeight) - continue; - found = true; - break; } - if (z != nextTileElement->BaseHeight) + auto destination = guest->GetDestination() + CoordsDirectionDelta[guest->PeepDirection]; + guest->SetDestination(destination, 9); + guest->MoveTo({ coords, guest->z }); + guest->SetState(PeepState::leavingPark); + + guest->Var37 = 0; + if (guest->PeepFlags & PEEP_FLAGS_TRACKING) { - continue; - } - found = true; - break; - } while (!(nextTileElement++)->IsLastForTile()); - } - - if (!found) - { - guest->State = PeepState::leavingPark; - guest->Var37 = 1; - DecrementGuestsHeadingForPark(); - PeepWindowStateUpdate(guest); - PeepReturnToCentreOfTile(guest); - return true; - } - - auto entranceFee = Park::GetEntranceFee(); - if (entranceFee != 0) - { - if (guest->HasItem(ShopItem::voucher)) - { - if (guest->VoucherType == VOUCHER_TYPE_PARK_ENTRY_HALF_PRICE) - { - entranceFee /= 2; - guest->RemoveItem(ShopItem::voucher); - guest->WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_INVENTORY; - } - else if (guest->VoucherType == VOUCHER_TYPE_PARK_ENTRY_FREE) - { - entranceFee = 0; - guest->RemoveItem(ShopItem::voucher); - guest->WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_INVENTORY; + auto ft = Formatter(); + guest->FormatNameTo(ft); + if (Config::Get().notifications.guestLeftPark) + { + News::AddItemToQueue(News::ItemType::peepOnRide, STR_PEEP_TRACKING_LEFT_PARK, guest->Id, ft); + } } + return true; } - if (entranceFee > guest->CashInPocket) + + // Peep is entering the park. + + if (guest->State != PeepState::enteringPark) + { + PeepReturnToCentreOfTile(guest); + return true; + } + + if (!(gameState.park.flags & PARK_FLAGS_PARK_OPEN)) { guest->State = PeepState::leavingPark; guest->Var37 = 1; @@ -1911,840 +1824,933 @@ static bool PeepInteractWithEntrance(Peep* peep, const CoordsXYE& coords, uint8_ return true; } - gameState.park.totalIncomeFromAdmissions = AddClamp(gameState.park.totalIncomeFromAdmissions, entranceFee); - guest->SpendMoney(guest->PaidToEnter, entranceFee, ExpenditureType::parkEntranceTickets); - guest->PeepFlags |= PEEP_FLAGS_HAS_PAID_FOR_PARK_ENTRY; - } - - auto& park = getGameState().park; - park.totalAdmissions = AddClamp(park.totalAdmissions, 1); - - auto* windowMgr = Ui::GetWindowManager(); - windowMgr->InvalidateByNumber(WindowClass::parkInformation, 0); - - guest->Var37 = 1; - auto destination = guest->GetDestination(); - destination += CoordsDirectionDelta[guest->PeepDirection]; - guest->SetDestination(destination, 7); - guest->MoveTo({ coords, guest->z }); - } - return true; -} - -/** - * - * rct2: 0x006946D8 - */ -static void PeepFootpathMoveForward(Peep* peep, const CoordsXYE& coords, bool vandalism) -{ - const auto* pathElement = coords.element->AsPath(); - assert(pathElement != nullptr); - - peep->NextLoc = { coords.ToTileStart(), pathElement->GetBaseZ() }; - peep->SetNextFlags(pathElement->GetSlopeDirection(), pathElement->IsSloped(), false); - - int16_t z = peep->GetZOnSlope(coords.x, coords.y); - - auto* guest = peep->As(); - if (guest == nullptr) - { - peep->MoveTo({ coords, z }); - return; - } - - uint8_t vandalThoughtTimeout = (guest->VandalismSeen & 0xC0) >> 6; - // Advance the vandalised tiles by 1 - uint8_t vandalisedTiles = (guest->VandalismSeen * 2) & 0x3F; - - if (vandalism) - { - // Add one more to the vandalised tiles - vandalisedTiles |= 1; - // If there has been 2 vandalised tiles in the last 6 - if (vandalisedTiles & 0x3E && (vandalThoughtTimeout == 0)) - { - if ((ScenarioRand() & 0xFFFF) <= 10922) + bool found = false; + auto entrance = std::find_if( + gameState.park.entrances.begin(), gameState.park.entrances.end(), + [coords](const auto& e) { return coords.ToTileStart() == e; }); + if (entrance != gameState.park.entrances.end()) { - guest->InsertNewThought(PeepThoughtType::Vandalism); - guest->HappinessTarget = std::max(0, guest->HappinessTarget - 17); + int16_t z = entrance->z / 8; + entranceDirection = entrance->direction; + auto nextLoc = coords.ToTileStart() + CoordsDirectionDelta[entranceDirection]; + + // Make sure there is a path right behind the entrance, otherwise turn around + TileElement* nextTileElement = MapGetFirstElementAt(nextLoc); + do + { + if (nextTileElement == nullptr) + break; + if (nextTileElement->GetType() != TileElementType::Path) + continue; + + if (nextTileElement->AsPath()->IsQueue()) + continue; + + if (nextTileElement->AsPath()->IsSloped()) + { + uint8_t slopeDirection = nextTileElement->AsPath()->GetSlopeDirection(); + if (slopeDirection == entranceDirection) + { + if (z != nextTileElement->BaseHeight) + { + continue; + } + found = true; + break; + } + + if (DirectionReverse(slopeDirection) != entranceDirection) + continue; + + if (z - 2 != nextTileElement->BaseHeight) + continue; + found = true; + break; + } + + if (z != nextTileElement->BaseHeight) + { + continue; + } + found = true; + break; + } while (!(nextTileElement++)->IsLastForTile()); } - vandalThoughtTimeout = 3; + + if (!found) + { + guest->State = PeepState::leavingPark; + guest->Var37 = 1; + DecrementGuestsHeadingForPark(); + PeepWindowStateUpdate(guest); + PeepReturnToCentreOfTile(guest); + return true; + } + + auto entranceFee = Park::GetEntranceFee(); + if (entranceFee != 0) + { + if (guest->HasItem(ShopItem::voucher)) + { + if (guest->VoucherType == VOUCHER_TYPE_PARK_ENTRY_HALF_PRICE) + { + entranceFee /= 2; + guest->RemoveItem(ShopItem::voucher); + guest->WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_INVENTORY; + } + else if (guest->VoucherType == VOUCHER_TYPE_PARK_ENTRY_FREE) + { + entranceFee = 0; + guest->RemoveItem(ShopItem::voucher); + guest->WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_INVENTORY; + } + } + if (entranceFee > guest->CashInPocket) + { + guest->State = PeepState::leavingPark; + guest->Var37 = 1; + DecrementGuestsHeadingForPark(); + PeepWindowStateUpdate(guest); + PeepReturnToCentreOfTile(guest); + return true; + } + + gameState.park.totalIncomeFromAdmissions = AddClamp(gameState.park.totalIncomeFromAdmissions, entranceFee); + guest->SpendMoney(guest->PaidToEnter, entranceFee, ExpenditureType::parkEntranceTickets); + guest->PeepFlags |= PEEP_FLAGS_HAS_PAID_FOR_PARK_ENTRY; + } + + auto& park = getGameState().park; + park.totalAdmissions = AddClamp(park.totalAdmissions, 1); + + auto* windowMgr = Ui::GetWindowManager(); + windowMgr->InvalidateByNumber(WindowClass::parkInformation, 0); + + guest->Var37 = 1; + auto destination = guest->GetDestination(); + destination += CoordsDirectionDelta[guest->PeepDirection]; + guest->SetDestination(destination, 7); + guest->MoveTo({ coords, guest->z }); } + return true; } - if (vandalThoughtTimeout && (ScenarioRand() & 0xFFFF) <= 4369) + /** + * + * rct2: 0x006946D8 + */ + static void PeepFootpathMoveForward(Peep* peep, const CoordsXYE& coords, bool vandalism) { - vandalThoughtTimeout--; - } + const auto* pathElement = coords.element->AsPath(); + assert(pathElement != nullptr); - guest->VandalismSeen = (vandalThoughtTimeout << 6) | vandalisedTiles; + peep->NextLoc = { coords.ToTileStart(), pathElement->GetBaseZ() }; + peep->SetNextFlags(pathElement->GetSlopeDirection(), pathElement->IsSloped(), false); - constexpr uint16_t kThresholdCrowdCount = 10; - constexpr uint8_t kThresholdLitterCount = 3; - constexpr uint8_t kThresholdVomitCount = 3; + int16_t z = peep->GetZOnSlope(coords.x, coords.y); - // Don't allow this loop to become too expensive, lets just have enough to potentially satisfy - // all the conditions. - constexpr uint32_t kMaxIterations = kThresholdCrowdCount + kThresholdLitterCount + kThresholdVomitCount; - - uint16_t crowdCount = 0; - uint8_t litterCount = 0; - uint8_t vomitCount = 0; - uint32_t iterations = 0; - - auto quad = EntityTileList(coords); - for (auto* otherEnt : quad) - { - if (iterations++ >= kMaxIterations) + auto* guest = peep->As(); + if (guest == nullptr) { - break; + peep->MoveTo({ coords, z }); + return; } - if (std::abs(otherEnt->z - guest->NextLoc.z) > 16) - continue; + uint8_t vandalThoughtTimeout = (guest->VandalismSeen & 0xC0) >> 6; + // Advance the vandalised tiles by 1 + uint8_t vandalisedTiles = (guest->VandalismSeen * 2) & 0x3F; - if (const auto* otherPeep = otherEnt->As(); otherPeep != nullptr) + if (vandalism) { - if (otherPeep->State != PeepState::walking) + // Add one more to the vandalised tiles + vandalisedTiles |= 1; + // If there has been 2 vandalised tiles in the last 6 + if (vandalisedTiles & 0x3E && (vandalThoughtTimeout == 0)) + { + if ((ScenarioRand() & 0xFFFF) <= 10922) + { + guest->InsertNewThought(PeepThoughtType::Vandalism); + guest->HappinessTarget = std::max(0, guest->HappinessTarget - 17); + } + vandalThoughtTimeout = 3; + } + } + + if (vandalThoughtTimeout && (ScenarioRand() & 0xFFFF) <= 4369) + { + vandalThoughtTimeout--; + } + + guest->VandalismSeen = (vandalThoughtTimeout << 6) | vandalisedTiles; + + constexpr uint16_t kThresholdCrowdCount = 10; + constexpr uint8_t kThresholdLitterCount = 3; + constexpr uint8_t kThresholdVomitCount = 3; + + // Don't allow this loop to become too expensive, lets just have enough to potentially satisfy + // all the conditions. + constexpr uint32_t kMaxIterations = kThresholdCrowdCount + kThresholdLitterCount + kThresholdVomitCount; + + uint16_t crowdCount = 0; + uint8_t litterCount = 0; + uint8_t vomitCount = 0; + uint32_t iterations = 0; + + auto quad = EntityTileList(coords); + for (auto* otherEnt : quad) + { + if (iterations++ >= kMaxIterations) + { + break; + } + + if (std::abs(otherEnt->z - guest->NextLoc.z) > 16) continue; - crowdCount++; - continue; - } + if (const auto* otherPeep = otherEnt->As(); otherPeep != nullptr) + { + if (otherPeep->State != PeepState::walking) + continue; - if (const auto* litter = otherEnt->As(); litter != nullptr) - { - if (litter->SubType != Litter::Type::vomit && litter->SubType != Litter::Type::vomitAlt) - { - litterCount++; + crowdCount++; + continue; } - else + + if (const auto* litter = otherEnt->As(); litter != nullptr) { - vomitCount++; + if (litter->SubType != Litter::Type::vomit && litter->SubType != Litter::Type::vomitAlt) + { + litterCount++; + } + else + { + vomitCount++; + } } } - } - if (crowdCount >= kThresholdCrowdCount && guest->State == PeepState::walking && (ScenarioRand() & 0xFFFF) <= 21845) - { - guest->InsertNewThought(PeepThoughtType::Crowded); - guest->HappinessTarget = std::max(0, guest->HappinessTarget - 14); - } - - litterCount = std::min(kThresholdLitterCount, litterCount); - vomitCount = std::min(kThresholdVomitCount, vomitCount); - - uint8_t disgustingTime = guest->DisgustingCount & 0xC0; - uint8_t disgustingCount = ((guest->DisgustingCount & 0xF) << 2) | vomitCount; - guest->DisgustingCount = disgustingCount | disgustingTime; - - if (disgustingTime & 0xC0 && (ScenarioRand() & 0xFFFF) <= 4369) - { - // Reduce the disgusting time - guest->DisgustingCount -= 0x40; - } - else - { - uint8_t totalDisgustingCount = 0; - for (uint8_t time = 0; time < 3; time++) + if (crowdCount >= kThresholdCrowdCount && guest->State == PeepState::walking && (ScenarioRand() & 0xFFFF) <= 21845) { - totalDisgustingCount += (disgustingCount >> (2 * time)) & 0x3; + guest->InsertNewThought(PeepThoughtType::Crowded); + guest->HappinessTarget = std::max(0, guest->HappinessTarget - 14); } - if (totalDisgustingCount >= kThresholdVomitCount && (ScenarioRand() & 0xFFFF) <= 10922) + litterCount = std::min(kThresholdLitterCount, litterCount); + vomitCount = std::min(kThresholdVomitCount, vomitCount); + + uint8_t disgustingTime = guest->DisgustingCount & 0xC0; + uint8_t disgustingCount = ((guest->DisgustingCount & 0xF) << 2) | vomitCount; + guest->DisgustingCount = disgustingCount | disgustingTime; + + if (disgustingTime & 0xC0 && (ScenarioRand() & 0xFFFF) <= 4369) { - guest->InsertNewThought(PeepThoughtType::PathDisgusting); - guest->HappinessTarget = std::max(0, guest->HappinessTarget - 17); - // Reset disgusting time - guest->DisgustingCount |= 0xC0; + // Reduce the disgusting time + guest->DisgustingCount -= 0x40; } - } - - uint8_t litterTime = guest->LitterCount & 0xC0; - litterCount = ((guest->LitterCount & 0xF) << 2) | litterCount; - guest->LitterCount = litterCount | litterTime; - - if (litterTime & 0xC0 && (ScenarioRand() & 0xFFFF) <= 4369) - { - // Reduce the litter time - guest->LitterCount -= 0x40; - } - else - { - uint8_t totalLitter = 0; - for (uint8_t time = 0; time < 3; time++) + else { - totalLitter += (litterCount >> (2 * time)) & 0x3; - } - - if (totalLitter >= kThresholdLitterCount && (ScenarioRand() & 0xFFFF) <= 10922) - { - guest->InsertNewThought(PeepThoughtType::BadLitter); - guest->HappinessTarget = std::max(0, guest->HappinessTarget - 17); - // Reset litter time - guest->LitterCount |= 0xC0; - } - } - - guest->MoveTo({ coords, z }); -} - -/** - * - * rct2: 0x0069455E - */ -static void PeepInteractWithPath(Peep* peep, const CoordsXYE& coords) -{ - // 0x00F1AEE2 - const auto* pathElement = coords.element->AsPath(); - assert(pathElement != nullptr); - - bool vandalismPresent = false; - if (pathElement->HasAddition() && pathElement->IsBroken() && (pathElement->GetEdges()) != 0xF) - { - vandalismPresent = true; - } - - int16_t z = pathElement->GetBaseZ(); - auto* guest = peep->As(); - if (MapIsLocationOwned({ coords, z })) - { - if (guest != nullptr && guest->OutsideOfPark) - { - PeepReturnToCentreOfTile(guest); - return; - } - } - else - { - if (guest == nullptr || !guest->OutsideOfPark) - { - PeepReturnToCentreOfTile(peep); - return; - } - } - - if (guest != nullptr && pathElement->IsQueue()) - { - auto rideIndex = pathElement->GetRideIndex(); - if (guest->State == PeepState::queuing) - { - // Check if this queue is connected to the ride the - // peep is queuing for, i.e. the player hasn't edited - // the queue, rebuilt the ride, etc. - if (guest->CurrentRide == rideIndex) + uint8_t totalDisgustingCount = 0; + for (uint8_t time = 0; time < 3; time++) { - PeepFootpathMoveForward(guest, coords, vandalismPresent); + totalDisgustingCount += (disgustingCount >> (2 * time)) & 0x3; } - else + + if (totalDisgustingCount >= kThresholdVomitCount && (ScenarioRand() & 0xFFFF) <= 10922) { - // Queue got disconnected from the original ride. - guest->InteractionRideIndex = RideId::GetNull(); - guest->RemoveFromQueue(); - guest->SetState(PeepState::one); - PeepFootpathMoveForward(guest, coords, vandalismPresent); + guest->InsertNewThought(PeepThoughtType::PathDisgusting); + guest->HappinessTarget = std::max(0, guest->HappinessTarget - 17); + // Reset disgusting time + guest->DisgustingCount |= 0xC0; + } + } + + uint8_t litterTime = guest->LitterCount & 0xC0; + litterCount = ((guest->LitterCount & 0xF) << 2) | litterCount; + guest->LitterCount = litterCount | litterTime; + + if (litterTime & 0xC0 && (ScenarioRand() & 0xFFFF) <= 4369) + { + // Reduce the litter time + guest->LitterCount -= 0x40; + } + else + { + uint8_t totalLitter = 0; + for (uint8_t time = 0; time < 3; time++) + { + totalLitter += (litterCount >> (2 * time)) & 0x3; + } + + if (totalLitter >= kThresholdLitterCount && (ScenarioRand() & 0xFFFF) <= 10922) + { + guest->InsertNewThought(PeepThoughtType::BadLitter); + guest->HappinessTarget = std::max(0, guest->HappinessTarget - 17); + // Reset litter time + guest->LitterCount |= 0xC0; + } + } + + guest->MoveTo({ coords, z }); + } + + /** + * + * rct2: 0x0069455E + */ + static void PeepInteractWithPath(Peep* peep, const CoordsXYE& coords) + { + // 0x00F1AEE2 + const auto* pathElement = coords.element->AsPath(); + assert(pathElement != nullptr); + + bool vandalismPresent = false; + if (pathElement->HasAddition() && pathElement->IsBroken() && (pathElement->GetEdges()) != 0xF) + { + vandalismPresent = true; + } + + int16_t z = pathElement->GetBaseZ(); + auto* guest = peep->As(); + if (MapIsLocationOwned({ coords, z })) + { + if (guest != nullptr && guest->OutsideOfPark) + { + PeepReturnToCentreOfTile(guest); + return; } } else { - // Peep is not queuing. - guest->TimeLost = 0; - auto stationNum = pathElement->GetStationIndex(); - - if (pathElement->HasQueueBanner() - && pathElement->GetQueueBannerDirection() - == DirectionReverse(guest->PeepDirection) // Ride sign is facing the direction the peep is walking - ) + if (guest == nullptr || !guest->OutsideOfPark) { - /* Peep is approaching the entrance of a ride queue. - * Decide whether to go on the ride. */ - auto* ride = GetRide(rideIndex); - if (ride != nullptr && guest->ShouldGoOnRide(*ride, stationNum, true, false)) + PeepReturnToCentreOfTile(peep); + return; + } + } + + if (guest != nullptr && pathElement->IsQueue()) + { + auto rideIndex = pathElement->GetRideIndex(); + if (guest->State == PeepState::queuing) + { + // Check if this queue is connected to the ride the + // peep is queuing for, i.e. the player hasn't edited + // the queue, rebuilt the ride, etc. + if (guest->CurrentRide == rideIndex) { - // Peep has decided to go on the ride at the queue. - guest->InteractionRideIndex = rideIndex; - - // Add the peep to the ride queue. - auto& station = ride->getStation(stationNum); - auto old_last_peep = station.LastPeepInQueue; - station.LastPeepInQueue = guest->Id; - guest->GuestNextInQueue = old_last_peep; - station.QueueLength++; - - PeepDecrementNumRiders(guest); - guest->CurrentRide = rideIndex; - guest->CurrentRideStation = stationNum; - guest->State = PeepState::queuing; - guest->DaysInQueue = 0; - PeepWindowStateUpdate(guest); - - guest->RideSubState = PeepRideSubState::inQueue; - guest->DestinationTolerance = 2; - guest->TimeInQueue = 0; - if (guest->PeepFlags & PEEP_FLAGS_TRACKING) - { - auto ft = Formatter(); - guest->FormatNameTo(ft); - ride->formatNameTo(ft); - if (Config::Get().notifications.guestQueuingForRide) - { - News::AddItemToQueue( - News::ItemType::peepOnRide, STR_PEEP_TRACKING_PEEP_JOINED_QUEUE_FOR_X, guest->Id, ft); - } - } - - // Force set centre of tile to prevent issues with guests accidentally skipping the queue - auto queueTileCentre = CoordsXY{ CoordsXY{ guest->NextLoc } + CoordsDirectionDelta[guest->PeepDirection] } - .ToTileCentre(); - guest->SetDestination(queueTileCentre); - PeepFootpathMoveForward(guest, coords, vandalismPresent); } else { - // Peep has decided not to go on the ride. - PeepReturnToCentreOfTile(guest); + // Queue got disconnected from the original ride. + guest->InteractionRideIndex = RideId::GetNull(); + guest->RemoveFromQueue(); + guest->SetState(PeepState::one); + PeepFootpathMoveForward(guest, coords, vandalismPresent); } } else { - /* Peep is approaching a queue tile without a ride - * sign facing the peep. */ - PeepFootpathMoveForward(guest, coords, vandalismPresent); + // Peep is not queuing. + guest->TimeLost = 0; + auto stationNum = pathElement->GetStationIndex(); + + if (pathElement->HasQueueBanner() + && pathElement->GetQueueBannerDirection() + == DirectionReverse(guest->PeepDirection) // Ride sign is facing the direction the peep is walking + ) + { + /* Peep is approaching the entrance of a ride queue. + * Decide whether to go on the ride. */ + auto* ride = GetRide(rideIndex); + if (ride != nullptr && guest->ShouldGoOnRide(*ride, stationNum, true, false)) + { + // Peep has decided to go on the ride at the queue. + guest->InteractionRideIndex = rideIndex; + + // Add the peep to the ride queue. + auto& station = ride->getStation(stationNum); + auto old_last_peep = station.LastPeepInQueue; + station.LastPeepInQueue = guest->Id; + guest->GuestNextInQueue = old_last_peep; + station.QueueLength++; + + PeepDecrementNumRiders(guest); + guest->CurrentRide = rideIndex; + guest->CurrentRideStation = stationNum; + guest->State = PeepState::queuing; + guest->DaysInQueue = 0; + PeepWindowStateUpdate(guest); + + guest->RideSubState = PeepRideSubState::inQueue; + guest->DestinationTolerance = 2; + guest->TimeInQueue = 0; + if (guest->PeepFlags & PEEP_FLAGS_TRACKING) + { + auto ft = Formatter(); + guest->FormatNameTo(ft); + ride->formatNameTo(ft); + if (Config::Get().notifications.guestQueuingForRide) + { + News::AddItemToQueue( + News::ItemType::peepOnRide, STR_PEEP_TRACKING_PEEP_JOINED_QUEUE_FOR_X, guest->Id, ft); + } + } + + // Force set centre of tile to prevent issues with guests accidentally skipping the queue + auto queueTileCentre = CoordsXY{ CoordsXY{ guest->NextLoc } + + CoordsDirectionDelta[guest->PeepDirection] } + .ToTileCentre(); + guest->SetDestination(queueTileCentre); + + PeepFootpathMoveForward(guest, coords, vandalismPresent); + } + else + { + // Peep has decided not to go on the ride. + PeepReturnToCentreOfTile(guest); + } + } + else + { + /* Peep is approaching a queue tile without a ride + * sign facing the peep. */ + PeepFootpathMoveForward(guest, coords, vandalismPresent); + } } } - } - else - { - peep->InteractionRideIndex = RideId::GetNull(); - if (guest != nullptr && peep->State == PeepState::queuing) + else { - guest->RemoveFromQueue(); - guest->SetState(PeepState::one); + peep->InteractionRideIndex = RideId::GetNull(); + if (guest != nullptr && peep->State == PeepState::queuing) + { + guest->RemoveFromQueue(); + guest->SetState(PeepState::one); + } + PeepFootpathMoveForward(peep, coords, vandalismPresent); } - PeepFootpathMoveForward(peep, coords, vandalismPresent); - } -} - -/** - * - * rct2: 0x00693F70 - */ -static bool PeepInteractWithShop(Peep* peep, const CoordsXYE& coords) -{ - RideId rideIndex = coords.element->AsTrack()->GetRideIndex(); - auto ride = GetRide(rideIndex); - if (ride == nullptr || !ride->getRideTypeDescriptor().flags.has(RtdFlag::isShopOrFacility)) - return false; - - auto* guest = peep->As(); - if (guest == nullptr) - { - PeepReturnToCentreOfTile(peep); - return true; } - // If we are queuing ignore the 'shop' - // This can happen when paths clip through track - if (guest->State == PeepState::queuing) + /** + * + * rct2: 0x00693F70 + */ + static bool PeepInteractWithShop(Peep* peep, const CoordsXYE& coords) { - return false; - } + RideId rideIndex = coords.element->AsTrack()->GetRideIndex(); + auto ride = GetRide(rideIndex); + if (ride == nullptr || !ride->getRideTypeDescriptor().flags.has(RtdFlag::isShopOrFacility)) + return false; - guest->TimeLost = 0; + auto* guest = peep->As(); + if (guest == nullptr) + { + PeepReturnToCentreOfTile(peep); + return true; + } - if (ride->status != RideStatus::open) - { - PeepReturnToCentreOfTile(guest); - return true; - } + // If we are queuing ignore the 'shop' + // This can happen when paths clip through track + if (guest->State == PeepState::queuing) + { + return false; + } - if (guest->InteractionRideIndex == rideIndex) - { - PeepReturnToCentreOfTile(guest); - return true; - } - - if (guest->PeepFlags & PEEP_FLAGS_LEAVING_PARK) - { - PeepReturnToCentreOfTile(guest); - return true; - } - - if (ride->getRideTypeDescriptor().flags.has(RtdFlag::guestsShouldGoInsideFacility)) - { guest->TimeLost = 0; - if (!guest->ShouldGoOnRide(*ride, StationIndex::FromUnderlying(0), false, false)) + + if (ride->status != RideStatus::open) { PeepReturnToCentreOfTile(guest); return true; } - auto cost = ride->price[0]; - if (cost != 0 && !(getGameState().park.flags & PARK_FLAGS_NO_MONEY)) + if (guest->InteractionRideIndex == rideIndex) { - ride->totalProfit = AddClamp(ride->totalProfit, cost); - ride->windowInvalidateFlags.set(RideInvalidateFlag::income); - guest->SpendMoney(cost, ExpenditureType::shopSales); + PeepReturnToCentreOfTile(guest); + return true; } - auto coordsCentre = coords.ToTileCentre(); - guest->SetDestination(coordsCentre, 3); - guest->CurrentRide = rideIndex; - guest->SetState(PeepState::enteringRide); - guest->RideSubState = PeepRideSubState::approachShop; - - guest->GuestTimeOnRide = 0; - ride->curNumCustomers++; - if (guest->PeepFlags & PEEP_FLAGS_TRACKING) + if (guest->PeepFlags & PEEP_FLAGS_LEAVING_PARK) { - auto ft = Formatter(); - guest->FormatNameTo(ft); - ride->formatNameTo(ft); - StringId string_id = ride->getRideTypeDescriptor().flags.has(RtdFlag::describeAsInside) - ? STR_PEEP_TRACKING_PEEP_IS_IN_X - : STR_PEEP_TRACKING_PEEP_IS_ON_X; - if (Config::Get().notifications.guestUsedFacility) + PeepReturnToCentreOfTile(guest); + return true; + } + + if (ride->getRideTypeDescriptor().flags.has(RtdFlag::guestsShouldGoInsideFacility)) + { + guest->TimeLost = 0; + if (!guest->ShouldGoOnRide(*ride, StationIndex::FromUnderlying(0), false, false)) { - News::AddItemToQueue(News::ItemType::peepOnRide, string_id, guest->Id, ft); + PeepReturnToCentreOfTile(guest); + return true; } - } - } - else - { - if (guest->GuestHeadingToRideId == rideIndex) - guest->GuestHeadingToRideId = RideId::GetNull(); - guest->AnimationImageIdOffset = _backupAnimationImageIdOffset; - guest->SetState(PeepState::buying); - guest->CurrentRide = rideIndex; - guest->SubState = 0; - } - return true; -} + auto cost = ride->price[0]; + if (cost != 0 && !(getGameState().park.flags & PARK_FLAGS_NO_MONEY)) + { + ride->totalProfit = AddClamp(ride->totalProfit, cost); + ride->windowInvalidateFlags.set(RideInvalidateFlag::income); + guest->SpendMoney(cost, ExpenditureType::shopSales); + } -/** - * - * rct2: 0x00693C9E - */ -std::pair Peep::PerformNextAction() -{ - uint8_t pathingResult = 0; - TileElement* tileResult = nullptr; + auto coordsCentre = coords.ToTileCentre(); + guest->SetDestination(coordsCentre, 3); + guest->CurrentRide = rideIndex; + guest->SetState(PeepState::enteringRide); + guest->RideSubState = PeepRideSubState::approachShop; - PeepActionType previousAction = Action; - - if (Action == PeepActionType::idle) - Action = PeepActionType::walking; - - auto* guest = As(); - if (State == PeepState::queuing && guest != nullptr) - { - if (guest->UpdateQueuePosition(previousAction)) - { - return { pathingResult, tileResult }; - } - } - - std::optional loc; - if (loc = UpdateAction(); !loc.has_value()) - { - pathingResult |= PATHING_DESTINATION_REACHED; - uint8_t result = 0; - - if (guest != nullptr) - { - result = PathFinding::CalculateNextDestination(*guest); + guest->GuestTimeOnRide = 0; + ride->curNumCustomers++; + if (guest->PeepFlags & PEEP_FLAGS_TRACKING) + { + auto ft = Formatter(); + guest->FormatNameTo(ft); + ride->formatNameTo(ft); + StringId string_id = ride->getRideTypeDescriptor().flags.has(RtdFlag::describeAsInside) + ? STR_PEEP_TRACKING_PEEP_IS_IN_X + : STR_PEEP_TRACKING_PEEP_IS_ON_X; + if (Config::Get().notifications.guestUsedFacility) + { + News::AddItemToQueue(News::ItemType::peepOnRide, string_id, guest->Id, ft); + } + } } else { - auto* staff = As(); - result = staff->DoPathFinding(); + if (guest->GuestHeadingToRideId == rideIndex) + guest->GuestHeadingToRideId = RideId::GetNull(); + guest->AnimationImageIdOffset = _backupAnimationImageIdOffset; + guest->SetState(PeepState::buying); + guest->CurrentRide = rideIndex; + guest->SubState = 0; } - if (result != 0) - return { pathingResult, tileResult }; - - if (loc = UpdateAction(); !loc.has_value()) - return { pathingResult, tileResult }; + return true; } - auto newLoc = *loc; - CoordsXY truncatedNewLoc = newLoc.ToTileStart(); - if (truncatedNewLoc == CoordsXY{ NextLoc }) + /** + * + * rct2: 0x00693C9E + */ + std::pair Peep::PerformNextAction() { - int16_t height = GetZOnSlope(newLoc.x, newLoc.y); - MoveTo({ newLoc.x, newLoc.y, height }); - return { pathingResult, tileResult }; - } + uint8_t pathingResult = 0; + TileElement* tileResult = nullptr; - if (MapIsEdge(newLoc)) - { - if (guest != nullptr && guest->OutsideOfPark) + PeepActionType previousAction = Action; + + if (Action == PeepActionType::idle) + Action = PeepActionType::walking; + + auto* guest = As(); + if (State == PeepState::queuing && guest != nullptr) { - pathingResult |= PATHING_OUTSIDE_PARK; + if (guest->UpdateQueuePosition(previousAction)) + { + return { pathingResult, tileResult }; + } } + + std::optional loc; + if (loc = UpdateAction(); !loc.has_value()) + { + pathingResult |= PATHING_DESTINATION_REACHED; + uint8_t result = 0; + + if (guest != nullptr) + { + result = PathFinding::CalculateNextDestination(*guest); + } + else + { + auto* staff = As(); + result = staff->DoPathFinding(); + } + + if (result != 0) + return { pathingResult, tileResult }; + + if (loc = UpdateAction(); !loc.has_value()) + return { pathingResult, tileResult }; + } + + auto newLoc = *loc; + CoordsXY truncatedNewLoc = newLoc.ToTileStart(); + if (truncatedNewLoc == CoordsXY{ NextLoc }) + { + int16_t height = GetZOnSlope(newLoc.x, newLoc.y); + MoveTo({ newLoc.x, newLoc.y, height }); + return { pathingResult, tileResult }; + } + + if (MapIsEdge(newLoc)) + { + if (guest != nullptr && guest->OutsideOfPark) + { + pathingResult |= PATHING_OUTSIDE_PARK; + } + PeepReturnToCentreOfTile(this); + return { pathingResult, tileResult }; + } + + TileElement* tileElement = MapGetFirstElementAt(newLoc); + if (tileElement == nullptr) + return { pathingResult, tileResult }; + + int16_t base_z = std::max(0, (z / 8) - 2); + int16_t top_z = (z / 8) + 1; + + do + { + if (base_z > tileElement->BaseHeight) + continue; + if (top_z < tileElement->BaseHeight) + continue; + if (tileElement->IsGhost()) + continue; + + if (tileElement->GetType() == TileElementType::Path) + { + PeepInteractWithPath(this, { newLoc, tileElement }); + tileResult = tileElement; + + return { pathingResult, tileResult }; + } + + if (tileElement->GetType() == TileElementType::Track) + { + if (PeepInteractWithShop(this, { newLoc, tileElement })) + { + tileResult = tileElement; + return { pathingResult, tileResult }; + } + } + else if (tileElement->GetType() == TileElementType::Entrance) + { + if (PeepInteractWithEntrance(this, { newLoc, tileElement }, pathingResult)) + { + tileResult = tileElement; + return { pathingResult, tileResult }; + } + } + } while (!(tileElement++)->IsLastForTile()); + + if (Is() || (GetNextIsSurface())) + { + int16_t height = abs(TileElementHeight(newLoc) - z); + if (height <= 3 || (Is() && height <= 32)) + { + InteractionRideIndex = RideId::GetNull(); + if (guest != nullptr && State == PeepState::queuing) + { + guest->RemoveFromQueue(); + SetState(PeepState::one); + } + + if (!MapIsLocationInPark(newLoc)) + { + PeepReturnToCentreOfTile(this); + return { pathingResult, tileResult }; + } + + auto surfaceElement = MapGetSurfaceElementAt(newLoc); + if (surfaceElement == nullptr) + { + PeepReturnToCentreOfTile(this); + return { pathingResult, tileResult }; + } + + int16_t water_height = surfaceElement->GetWaterHeight(); + if (water_height > 0) + { + PeepReturnToCentreOfTile(this); + return { pathingResult, tileResult }; + } + + auto* staff = As(); + if (staff != nullptr && !GetNextIsSurface()) + { + // Prevent staff from leaving the path on their own unless they're allowed to mow. + if (!((staff->StaffOrders & STAFF_ORDERS_MOWING) && staff->StaffMowingTimeout >= 12)) + { + PeepReturnToCentreOfTile(staff); + return { pathingResult, tileResult }; + } + } + + // The peep is on a surface and not on a path + NextLoc = { truncatedNewLoc, surfaceElement->GetBaseZ() }; + SetNextFlags(0, false, true); + + height = GetZOnSlope(newLoc.x, newLoc.y); + MoveTo({ newLoc.x, newLoc.y, height }); + return { pathingResult, tileResult }; + } + } + PeepReturnToCentreOfTile(this); return { pathingResult, tileResult }; } - TileElement* tileElement = MapGetFirstElementAt(newLoc); - if (tileElement == nullptr) - return { pathingResult, tileResult }; - - int16_t base_z = std::max(0, (z / 8) - 2); - int16_t top_z = (z / 8) + 1; - - do + /** + * Gets the height including the bit depending on how far up the slope the peep + * is. + * rct2: 0x00694921 + */ + int32_t Peep::GetZOnSlope(int32_t tile_x, int32_t tile_y) { - if (base_z > tileElement->BaseHeight) - continue; - if (top_z < tileElement->BaseHeight) - continue; - if (tileElement->IsGhost()) - continue; + if (tile_x == kLocationNull) + return 0; - if (tileElement->GetType() == TileElementType::Path) + if (GetNextIsSurface()) { - PeepInteractWithPath(this, { newLoc, tileElement }); - tileResult = tileElement; - - return { pathingResult, tileResult }; + return TileElementHeight({ tile_x, tile_y }); } - if (tileElement->GetType() == TileElementType::Track) + uint8_t slope = GetNextDirection(); + return NextLoc.z + MapHeightFromSlope({ tile_x, tile_y }, slope, GetNextIsSloped()); + } + + StringId GetRealNameStringIDFromPeepID(uint32_t id) + { + // Generate a name_string_idx from the peep Id using bit twiddling + uint16_t ax = static_cast(id + 0xF0B); + uint16_t dx = 0; + static constexpr uint16_t twiddlingBitOrder[] = { + 4, 9, 3, 7, 5, 8, 2, 1, 6, 0, 12, 11, 13, 10, + }; + for (size_t i = 0; i < std::size(twiddlingBitOrder); i++) { - if (PeepInteractWithShop(this, { newLoc, tileElement })) + dx |= (ax & (1 << twiddlingBitOrder[i]) ? 1 : 0) << i; + } + ax = dx & 0xF; + dx *= 4; + ax *= 4096; + dx += ax; + if (dx < ax) + { + dx += 0x1000; + } + dx /= 4; + dx += kRealNameStart; + return dx; + } + + int32_t PeepCompare(const EntityId sprite_index_a, const EntityId sprite_index_b) + { + Peep const* peep_a = getGameState().entities.GetEntity(sprite_index_a); + Peep const* peep_b = getGameState().entities.GetEntity(sprite_index_b); + if (peep_a == nullptr || peep_b == nullptr) + { + return 0; + } + + // Compare types + if (peep_a->Type != peep_b->Type) + { + return static_cast(peep_a->Type) - static_cast(peep_b->Type); + } + + if (peep_a->Name == nullptr && peep_b->Name == nullptr) + { + if (getGameState().park.flags & PARK_FLAGS_SHOW_REAL_GUEST_NAMES) { - tileResult = tileElement; - return { pathingResult, tileResult }; + // Potentially could find a more optional way of sorting dynamic real names + } + else + { + // Simple ID comparison for when both peeps use a number or a generated name + return peep_a->PeepId - peep_b->PeepId; } } - else if (tileElement->GetType() == TileElementType::Entrance) + + // Compare their names as strings + char nameA[256]{}; + Formatter ft; + peep_a->FormatNameTo(ft); + FormatStringLegacy(nameA, sizeof(nameA), STR_STRINGID, ft.Data()); + + char nameB[256]{}; + ft.Rewind(); + peep_b->FormatNameTo(ft); + FormatStringLegacy(nameB, sizeof(nameB), STR_STRINGID, ft.Data()); + return String::logicalCmp(nameA, nameB); + } + + /** + * + * rct2: 0x0069926C + */ + void PeepUpdateNames() + { + auto& gameState = getGameState(); + auto& config = Config::Get().general; + + if (config.showRealNamesOfGuests) + gameState.park.flags |= PARK_FLAGS_SHOW_REAL_GUEST_NAMES; + else + gameState.park.flags &= ~PARK_FLAGS_SHOW_REAL_GUEST_NAMES; + + if (config.showRealNamesOfStaff) + gameState.park.flags |= PARK_FLAGS_SHOW_REAL_STAFF_NAMES; + else + gameState.park.flags &= ~PARK_FLAGS_SHOW_REAL_STAFF_NAMES; + + auto intent = Intent(INTENT_ACTION_REFRESH_GUEST_LIST); + ContextBroadcastIntent(&intent); + GfxInvalidateScreen(); + } + + void IncrementGuestsInPark() + { + auto& gameState = getGameState(); + if (gameState.park.numGuestsInPark < UINT32_MAX) { - if (PeepInteractWithEntrance(this, { newLoc, tileElement }, pathingResult)) - { - tileResult = tileElement; - return { pathingResult, tileResult }; - } - } - } while (!(tileElement++)->IsLastForTile()); - - if (Is() || (GetNextIsSurface())) - { - int16_t height = abs(TileElementHeight(newLoc) - z); - if (height <= 3 || (Is() && height <= 32)) - { - InteractionRideIndex = RideId::GetNull(); - if (guest != nullptr && State == PeepState::queuing) - { - guest->RemoveFromQueue(); - SetState(PeepState::one); - } - - if (!MapIsLocationInPark(newLoc)) - { - PeepReturnToCentreOfTile(this); - return { pathingResult, tileResult }; - } - - auto surfaceElement = MapGetSurfaceElementAt(newLoc); - if (surfaceElement == nullptr) - { - PeepReturnToCentreOfTile(this); - return { pathingResult, tileResult }; - } - - int16_t water_height = surfaceElement->GetWaterHeight(); - if (water_height > 0) - { - PeepReturnToCentreOfTile(this); - return { pathingResult, tileResult }; - } - - auto* staff = As(); - if (staff != nullptr && !GetNextIsSurface()) - { - // Prevent staff from leaving the path on their own unless they're allowed to mow. - if (!((staff->StaffOrders & STAFF_ORDERS_MOWING) && staff->StaffMowingTimeout >= 12)) - { - PeepReturnToCentreOfTile(staff); - return { pathingResult, tileResult }; - } - } - - // The peep is on a surface and not on a path - NextLoc = { truncatedNewLoc, surfaceElement->GetBaseZ() }; - SetNextFlags(0, false, true); - - height = GetZOnSlope(newLoc.x, newLoc.y); - MoveTo({ newLoc.x, newLoc.y, height }); - return { pathingResult, tileResult }; - } - } - - PeepReturnToCentreOfTile(this); - return { pathingResult, tileResult }; -} - -/** - * Gets the height including the bit depending on how far up the slope the peep - * is. - * rct2: 0x00694921 - */ -int32_t Peep::GetZOnSlope(int32_t tile_x, int32_t tile_y) -{ - if (tile_x == kLocationNull) - return 0; - - if (GetNextIsSurface()) - { - return TileElementHeight({ tile_x, tile_y }); - } - - uint8_t slope = GetNextDirection(); - return NextLoc.z + MapHeightFromSlope({ tile_x, tile_y }, slope, GetNextIsSloped()); -} - -StringId GetRealNameStringIDFromPeepID(uint32_t id) -{ - // Generate a name_string_idx from the peep Id using bit twiddling - uint16_t ax = static_cast(id + 0xF0B); - uint16_t dx = 0; - static constexpr uint16_t twiddlingBitOrder[] = { - 4, 9, 3, 7, 5, 8, 2, 1, 6, 0, 12, 11, 13, 10, - }; - for (size_t i = 0; i < std::size(twiddlingBitOrder); i++) - { - dx |= (ax & (1 << twiddlingBitOrder[i]) ? 1 : 0) << i; - } - ax = dx & 0xF; - dx *= 4; - ax *= 4096; - dx += ax; - if (dx < ax) - { - dx += 0x1000; - } - dx /= 4; - dx += kRealNameStart; - return dx; -} - -int32_t PeepCompare(const EntityId sprite_index_a, const EntityId sprite_index_b) -{ - Peep const* peep_a = getGameState().entities.GetEntity(sprite_index_a); - Peep const* peep_b = getGameState().entities.GetEntity(sprite_index_b); - if (peep_a == nullptr || peep_b == nullptr) - { - return 0; - } - - // Compare types - if (peep_a->Type != peep_b->Type) - { - return static_cast(peep_a->Type) - static_cast(peep_b->Type); - } - - if (peep_a->Name == nullptr && peep_b->Name == nullptr) - { - if (getGameState().park.flags & PARK_FLAGS_SHOW_REAL_GUEST_NAMES) - { - // Potentially could find a more optional way of sorting dynamic real names + gameState.park.numGuestsInPark++; } else { - // Simple ID comparison for when both peeps use a number or a generated name - return peep_a->PeepId - peep_b->PeepId; + Guard::Fail("Attempt to increment guests in park above max value (65535)."); } } - // Compare their names as strings - char nameA[256]{}; - Formatter ft; - peep_a->FormatNameTo(ft); - FormatStringLegacy(nameA, sizeof(nameA), STR_STRINGID, ft.Data()); - - char nameB[256]{}; - ft.Rewind(); - peep_b->FormatNameTo(ft); - FormatStringLegacy(nameB, sizeof(nameB), STR_STRINGID, ft.Data()); - return String::logicalCmp(nameA, nameB); -} - -/** - * - * rct2: 0x0069926C - */ -void PeepUpdateNames() -{ - auto& gameState = getGameState(); - auto& config = Config::Get().general; - - if (config.showRealNamesOfGuests) - gameState.park.flags |= PARK_FLAGS_SHOW_REAL_GUEST_NAMES; - else - gameState.park.flags &= ~PARK_FLAGS_SHOW_REAL_GUEST_NAMES; - - if (config.showRealNamesOfStaff) - gameState.park.flags |= PARK_FLAGS_SHOW_REAL_STAFF_NAMES; - else - gameState.park.flags &= ~PARK_FLAGS_SHOW_REAL_STAFF_NAMES; - - auto intent = Intent(INTENT_ACTION_REFRESH_GUEST_LIST); - ContextBroadcastIntent(&intent); - GfxInvalidateScreen(); -} - -void IncrementGuestsInPark() -{ - auto& gameState = getGameState(); - if (gameState.park.numGuestsInPark < UINT32_MAX) + void IncrementGuestsHeadingForPark() { - gameState.park.numGuestsInPark++; - } - else - { - Guard::Fail("Attempt to increment guests in park above max value (65535)."); - } -} - -void IncrementGuestsHeadingForPark() -{ - auto& gameState = getGameState(); - if (gameState.park.numGuestsHeadingForPark < UINT32_MAX) - { - gameState.park.numGuestsHeadingForPark++; - } - else - { - Guard::Fail("Attempt to increment guests heading for park above max value (65535)."); - } -} - -void DecrementGuestsInPark() -{ - auto& gameState = getGameState(); - if (gameState.park.numGuestsInPark > 0) - { - gameState.park.numGuestsInPark--; - } - else - { - LOG_ERROR("Attempt to decrement guests in park below zero."); - } -} - -void DecrementGuestsHeadingForPark() -{ - auto& gameState = getGameState(); - - if (gameState.park.numGuestsHeadingForPark > 0) - { - gameState.park.numGuestsHeadingForPark--; - } - else - { - LOG_ERROR("Attempt to decrement guests heading for park below zero."); - } -} - -static void GuestReleaseBalloon(Guest* peep, int16_t spawn_height) -{ - if (peep->HasItem(ShopItem::balloon)) - { - peep->RemoveItem(ShopItem::balloon); - - if (peep->AnimationGroup == PeepAnimationGroup::balloon && peep->x != kLocationNull) + auto& gameState = getGameState(); + if (gameState.park.numGuestsHeadingForPark < UINT32_MAX) { - Balloon::Create({ peep->x, peep->y, spawn_height }, peep->BalloonColour, false); - peep->WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_INVENTORY; - peep->UpdateAnimationGroup(); + gameState.park.numGuestsHeadingForPark++; + } + else + { + Guard::Fail("Attempt to increment guests heading for park above max value (65535)."); } } -} -/** - * - * rct2: 0x0069A512 - */ -void Peep::RemoveFromRide() -{ - auto* guest = As(); - if (guest != nullptr && State == PeepState::queuing) + void DecrementGuestsInPark() { - guest->RemoveFromQueue(); + auto& gameState = getGameState(); + if (gameState.park.numGuestsInPark > 0) + { + gameState.park.numGuestsInPark--; + } + else + { + LOG_ERROR("Attempt to decrement guests in park below zero."); + } } - StateReset(); -} -void Peep::SetDestination(const CoordsXY& coords) -{ - DestinationX = static_cast(coords.x); - DestinationY = static_cast(coords.y); -} - -void Peep::SetDestination(const CoordsXY& coords, int32_t tolerance) -{ - SetDestination(coords); - DestinationTolerance = tolerance; -} - -CoordsXY Peep::GetDestination() const -{ - return CoordsXY{ DestinationX, DestinationY }; -} - -void Peep::Serialise(DataSerialiser& stream) -{ - EntityBase::Serialise(stream); - if (stream.IsLoading()) + void DecrementGuestsHeadingForPark() { - Name = nullptr; - } - stream << NextLoc; - stream << NextFlags; - stream << State; - stream << SubState; - stream << AnimationGroup; - stream << TshirtColour; - stream << TrousersColour; - stream << DestinationX; - stream << DestinationY; - stream << DestinationTolerance; - stream << Var37; - stream << Energy; - stream << EnergyTarget; - stream << Mass; - // stream << base.WindowInvalidateFlags; - stream << CurrentRide; - stream << CurrentRideStation; - stream << CurrentTrain; - stream << CurrentCar; - stream << CurrentSeat; - stream << SpecialSprite; - stream << AnimationType; - stream << NextAnimationType; - stream << AnimationImageIdOffset; - stream << Action; - stream << AnimationFrameNum; - stream << StepProgress; - stream << PeepDirection; - stream << InteractionRideIndex; - stream << PeepId; - stream << PathCheckOptimisation; - stream << PathfindGoal; - stream << PathfindHistory; - stream << WalkingAnimationFrameNum; - stream << PeepFlags; -} + auto& gameState = getGameState(); -/** - * - * rct2: 0x0069A98C - */ -void Peep::ResetPathfindGoal() -{ - PathfindGoal.SetNull(); - PathfindGoal.direction = kInvalidDirection; -} + if (gameState.park.numGuestsHeadingForPark > 0) + { + gameState.park.numGuestsHeadingForPark--; + } + else + { + LOG_ERROR("Attempt to decrement guests heading for park below zero."); + } + } + + static void GuestReleaseBalloon(Guest* peep, int16_t spawn_height) + { + if (peep->HasItem(ShopItem::balloon)) + { + peep->RemoveItem(ShopItem::balloon); + + if (peep->AnimationGroup == PeepAnimationGroup::balloon && peep->x != kLocationNull) + { + Balloon::Create({ peep->x, peep->y, spawn_height }, peep->BalloonColour, false); + peep->WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_INVENTORY; + peep->UpdateAnimationGroup(); + } + } + } + + /** + * + * rct2: 0x0069A512 + */ + void Peep::RemoveFromRide() + { + auto* guest = As(); + if (guest != nullptr && State == PeepState::queuing) + { + guest->RemoveFromQueue(); + } + StateReset(); + } + + void Peep::SetDestination(const CoordsXY& coords) + { + DestinationX = static_cast(coords.x); + DestinationY = static_cast(coords.y); + } + + void Peep::SetDestination(const CoordsXY& coords, int32_t tolerance) + { + SetDestination(coords); + DestinationTolerance = tolerance; + } + + CoordsXY Peep::GetDestination() const + { + return CoordsXY{ DestinationX, DestinationY }; + } + + void Peep::Serialise(DataSerialiser& stream) + { + EntityBase::Serialise(stream); + if (stream.IsLoading()) + { + Name = nullptr; + } + stream << NextLoc; + stream << NextFlags; + stream << State; + stream << SubState; + stream << AnimationGroup; + stream << TshirtColour; + stream << TrousersColour; + stream << DestinationX; + stream << DestinationY; + stream << DestinationTolerance; + stream << Var37; + stream << Energy; + stream << EnergyTarget; + stream << Mass; + // stream << base.WindowInvalidateFlags; + stream << CurrentRide; + stream << CurrentRideStation; + stream << CurrentTrain; + stream << CurrentCar; + stream << CurrentSeat; + stream << SpecialSprite; + stream << AnimationType; + stream << NextAnimationType; + stream << AnimationImageIdOffset; + stream << Action; + stream << AnimationFrameNum; + stream << StepProgress; + stream << PeepDirection; + stream << InteractionRideIndex; + stream << PeepId; + stream << PathCheckOptimisation; + stream << PathfindGoal; + stream << PathfindHistory; + stream << WalkingAnimationFrameNum; + stream << PeepFlags; + } + + /** + * + * rct2: 0x0069A98C + */ + void Peep::ResetPathfindGoal() + { + PathfindGoal.SetNull(); + PathfindGoal.direction = kInvalidDirection; + } +} // namespace OpenRCT2 diff --git a/src/openrct2/entity/Peep.h b/src/openrct2/entity/Peep.h index 84e52a5e82..2fc73ee568 100644 --- a/src/openrct2/entity/Peep.h +++ b/src/openrct2/entity/Peep.h @@ -22,19 +22,6 @@ #include #include -constexpr uint8_t kPeepMinEnergy = 32; -constexpr uint8_t kPeepMaxEnergy = 128; -constexpr uint8_t kPeepMaxEnergyTarget = 255; // Oddly, this differs from max energy! - -constexpr auto kPeepClearanceHeight = 4 * kCoordsZStep; - -namespace OpenRCT2 -{ - class DataSerialiser; - class Formatter; - struct TileElement; -} // namespace OpenRCT2 - namespace OpenRCT2::GameActions { class Result; @@ -45,427 +32,440 @@ namespace OpenRCT2::Drawing enum class Colour : uint8_t; } -enum class PeepState : uint8_t +namespace OpenRCT2 { - falling = 0, // Drowning is part of falling - one = 1, // was PEEP_STATE_1 - queuingFront = 2, - onRide = 3, - leavingRide = 4, - walking = 5, - queuing = 6, - enteringRide = 7, - sitting = 8, - picked = 9, - patrolling = 10, // Not sure - mowing = 11, - sweeping = 12, - enteringPark = 13, - leavingPark = 14, - answering = 15, - fixing = 16, - buying = 17, - watching = 18, - emptyingBin = 19, - usingBin = 20, - watering = 21, - headingToInspection = 22, - inspecting = 23, -}; + class DataSerialiser; + class Formatter; + struct TileElement; -enum class PeepSittingSubState : uint8_t -{ - tryingToSit, // was = 0 - satDown // was unassigned -}; + constexpr uint8_t kPeepMinEnergy = 32; + constexpr uint8_t kPeepMaxEnergy = 128; + constexpr uint8_t kPeepMaxEnergyTarget = 255; // Oddly, this differs from max energy! -enum class PeepRideSubState : uint8_t -{ - atEntrance = 0, - inEntrance = 1, - freeVehicleCheck = 2, // Spend money on ride - leaveEntrance = 3, // Calculate what direction and where to go after committing to entering vehicle - approachVehicle = 4, - enterVehicle = 5, - onRide = 6, - leaveVehicle = 7, - approachExit = 8, - inExit = 9, - inQueue = 10, - atQueueFront = 11, - approachVehicleWaypoints = 12, - approachExitWaypoints = 13, - approachSpiralSlide = 14, - onSpiralSlide = 15, - leaveSpiralSlide = 16, - mazePathfinding = 17, - leaveExit = 18, - approachShop = 19, - interactShop = 20, - leaveShop = 21, -}; + constexpr auto kPeepClearanceHeight = 4 * kCoordsZStep; -// Substates for guests that are inside the Spiral Slide. Declared as uint16_t to match DestinationX. -enum class PeepSpiralSlideSubState : uint16_t -{ - goingUp = 0, - prepareToSlide = 1, - slidingDown = 2, - finishedSliding = 3 -}; - -enum class PeepUsingBinSubState : uint8_t -{ - walkingToBin = 0, - goingBack, -}; - -enum class PeepActionType : uint8_t -{ - checkTime = 0, - // If no food then check watch - eatFood = 1, - shakeHead = 2, - emptyPockets = 3, - sittingEatFood = 4, - sittingCheckWatch = 4, - sittingLookAroundLeft = 5, - sittingLookAroundRight = 6, - wow = 7, - throwUp = 8, - jump = 9, - staffSweep = 10, - drowning = 11, - staffAnswerCall = 12, - staffAnswerCall2 = 13, - staffCheckBoard = 14, - staffFix = 15, - staffFix2 = 16, - staffFixGround = 17, - staffFix3 = 18, - staffWatering = 19, - joy = 20, - readMap = 21, - wave = 22, - staffEmptyBin = 23, - wave2 = 24, - takePhoto = 25, - clap = 26, - disgust = 27, - drawPicture = 28, - beingWatched = 29, - withdrawMoney = 30, - - idle = 254, - walking = 255, -}; - -enum class PeepAnimationType : uint8_t -{ - walking = 0, - checkTime = 1, - watchRide = 2, - eatFood = 3, - shakeHead = 4, - emptyPockets = 5, - holdMat = 6, - sittingIdle = 7, - sittingEatFood = 8, - sittingLookAroundLeft = 9, - sittingLookAroundRight = 10, - hanging = 11, - staffMower = 12, - wow = 13, - throwUp = 14, - jump = 15, - staffSweep = 16, - drowning = 17, - staffAnswerCall = 18, - staffAnswerCall2 = 19, - staffCheckBoard = 20, - staffFix = 21, - staffFix2 = 22, - staffFixGround = 23, - staffFix3 = 24, - staffWatering = 25, - joy = 26, - readMap = 27, - wave = 28, - staffEmptyBin = 29, - wave2 = 30, - takePhoto = 31, - clap = 32, - disgust = 33, - drawPicture = 34, - beingWatched = 35, - withdrawMoney = 36, - - invalid = 255 -}; - -enum PeepFlags : uint32_t -{ - PEEP_FLAGS_LEAVING_PARK = (1 << 0), - PEEP_FLAGS_SLOW_WALK = (1 << 1), - PEEP_FLAGS_DEBUG_PATHFINDING = (1 << 2), // Enables debug logging for path finding - PEEP_FLAGS_TRACKING = (1 << 3), - PEEP_FLAGS_WAVING = (1 << 4), // Makes the peep wave - PEEP_FLAGS_HAS_PAID_FOR_PARK_ENTRY = (1 << 5), // Set on paying to enter park - PEEP_FLAGS_PHOTO = (1 << 6), // Makes the peep take a picture - PEEP_FLAGS_PAINTING = (1 << 7), - PEEP_FLAGS_WOW = (1 << 8), // Makes a peep WOW2 - PEEP_FLAGS_LITTER = (1 << 9), // Makes the peep throw litter - PEEP_FLAGS_LOST = (1 << 10), // Makes the peep feel lost (animation triggered) - PEEP_FLAGS_HUNGER = (1 << 11), // Makes the peep become hungry quicker - PEEP_FLAGS_TOILET = (1 << 12), // Makes the peep want to go to the toilet - PEEP_FLAGS_CROWDED = (1 << 13), // The peep will start feeling crowded - PEEP_FLAGS_HAPPINESS = (1 << 14), // The peep will start increasing happiness - PEEP_FLAGS_NAUSEA = (1 << 15), // Makes the peep feel sick (e.g. after an extreme ride) - PEEP_FLAGS_PURPLE = (1 << 16), // Makes surrounding peeps purple - PEEP_FLAGS_PIZZA = (1 << 17), // Gives passing peeps pizza - PEEP_FLAGS_EXPLODE = (1 << 18), - PEEP_FLAGS_RIDE_SHOULD_BE_MARKED_AS_FAVOURITE = (1 << 19), - PEEP_FLAGS_PARK_ENTRANCE_CHOSEN = (1 << 20), // Set when the nearest park entrance has been chosen - PEEP_FLAGS_21 = (1 << 21), - PEEP_FLAGS_CONTAGIOUS = (1 << 22), // Makes any peeps in surrounding tiles sick - PEEP_FLAGS_JOY = (1 << 23), // Makes the peep jump in joy - PEEP_FLAGS_ANGRY = (1 << 24), - PEEP_FLAGS_ICE_CREAM = (1 << 25), // Gives passing peeps ice cream and they wave back - PEEP_FLAGS_NICE_RIDE_DEPRECATED = (1 << 26), // Used to make the peep think "Nice ride! But not as good as the Phoenix..." - // on exiting a ride - PEEP_FLAGS_INTAMIN_DEPRECATED = (1 << 27), // Used to make the peep think "I'm so excited - It's an Intamin ride!" while - // riding on a Intamin ride. - PEEP_FLAGS_HERE_WE_ARE = (1 << 28), // Makes the peep think "...and here we are on X!" while riding a ride - PEEP_FLAGS_POSITION_FROZEN = (1 << 29), // Prevents the peep from moving around, thus keeping them in place - PEEP_FLAGS_ANIMATION_FROZEN = (1 << 30), // Prevents the peep sprite from updating - PEEP_FLAGS_TWITCH_DEPRECATED = (1u << 31), // Formerly used for twitch integration -}; - -enum PeepNextFlags -{ - PEEP_NEXT_FLAG_DIRECTION_MASK = 0x3, - PEEP_NEXT_FLAG_IS_SLOPED = (1 << 2), - PEEP_NEXT_FLAG_IS_SURFACE = (1 << 3), - PEEP_NEXT_FLAG_UNUSED = (1 << 4), -}; - -enum class PeepAnimationGroup : uint8_t -{ - normal = 0, - - // Security staff - alternate = 1, - - // Guest variations - iceCream = 1, - chips = 2, - burger = 3, - drink = 4, - balloon = 5, - candyfloss = 6, - umbrella = 7, - pizza = 8, - popcorn = 9, - armsCrossed = 10, - headDown = 11, - nauseous = 12, - veryNauseous = 13, - requireToilet = 14, - hat = 15, - hotDog = 16, - tentacle = 17, - toffeeApple = 18, - doughnut = 19, - coffee = 20, - chicken = 21, - lemonade = 22, - watching = 23, - pretzel = 24, - sunglasses = 25, - sujeonggwa = 26, - juice = 27, - funnelCake = 28, - noodles = 29, - sausage = 30, - soup = 31, - sandwich = 32, - - invalid = 255 -}; - -// Flags used by peep->WindowInvalidateFlags -enum PeepInvalidate -{ - PEEP_INVALIDATE_PEEP_THOUGHTS = 1, - PEEP_INVALIDATE_PEEP_STATS = 1 << 1, - PEEP_INVALIDATE_PEEP_2 = 1 << 2, - PEEP_INVALIDATE_PEEP_INVENTORY = 1 << 3, - PEEP_INVALIDATE_STAFF_STATS = 1 << 4, - PEEP_INVALIDATE_PEEP_ACTION = 1 << 5, // Currently set only when GuestHeadingToRideId is changed -}; - -struct Guest; -struct Staff; - -struct Peep : EntityBase -{ - char* Name; - CoordsXYZ NextLoc; - uint8_t NextFlags; - PeepState State; - union + enum class PeepState : uint8_t { - uint8_t SubState; - PeepSittingSubState SittingSubState; - PeepRideSubState RideSubState; - PeepUsingBinSubState UsingBinSubState; + falling = 0, // Drowning is part of falling + one = 1, // was PEEP_STATE_1 + queuingFront = 2, + onRide = 3, + leavingRide = 4, + walking = 5, + queuing = 6, + enteringRide = 7, + sitting = 8, + picked = 9, + patrolling = 10, // Not sure + mowing = 11, + sweeping = 12, + enteringPark = 13, + leavingPark = 14, + answering = 15, + fixing = 16, + buying = 17, + watching = 18, + emptyingBin = 19, + usingBin = 20, + watering = 21, + headingToInspection = 22, + inspecting = 23, }; - OpenRCT2::ObjectEntryIndex AnimationObjectIndex; - PeepAnimationGroup AnimationGroup; - OpenRCT2::Drawing::Colour TshirtColour; - OpenRCT2::Drawing::Colour TrousersColour; - union + + enum class PeepSittingSubState : uint8_t { - uint16_t DestinationX; - PeepSpiralSlideSubState spiralSlideSubstate; + tryingToSit, // was = 0 + satDown // was unassigned }; - union + + enum class PeepRideSubState : uint8_t { - uint16_t DestinationY; - uint16_t spiralSlideGoingUpTimer; + atEntrance = 0, + inEntrance = 1, + freeVehicleCheck = 2, // Spend money on ride + leaveEntrance = 3, // Calculate what direction and where to go after committing to entering vehicle + approachVehicle = 4, + enterVehicle = 5, + onRide = 6, + leaveVehicle = 7, + approachExit = 8, + inExit = 9, + inQueue = 10, + atQueueFront = 11, + approachVehicleWaypoints = 12, + approachExitWaypoints = 13, + approachSpiralSlide = 14, + onSpiralSlide = 15, + leaveSpiralSlide = 16, + mazePathfinding = 17, + leaveExit = 18, + approachShop = 19, + interactShop = 20, + leaveShop = 21, }; - uint8_t DestinationTolerance; // How close to destination before next action/state 0 = exact - uint8_t Var37; - uint8_t Energy; - uint8_t EnergyTarget; - uint8_t Mass; - uint8_t WindowInvalidateFlags; - RideId CurrentRide; - StationIndex CurrentRideStation; - uint8_t CurrentTrain; - union + + // Substates for guests that are inside the Spiral Slide. Declared as uint16_t to match DestinationX. + enum class PeepSpiralSlideSubState : uint16_t { - struct + goingUp = 0, + prepareToSlide = 1, + slidingDown = 2, + finishedSliding = 3 + }; + + enum class PeepUsingBinSubState : uint8_t + { + walkingToBin = 0, + goingBack, + }; + + enum class PeepActionType : uint8_t + { + checkTime = 0, + // If no food then check watch + eatFood = 1, + shakeHead = 2, + emptyPockets = 3, + sittingEatFood = 4, + sittingCheckWatch = 4, + sittingLookAroundLeft = 5, + sittingLookAroundRight = 6, + wow = 7, + throwUp = 8, + jump = 9, + staffSweep = 10, + drowning = 11, + staffAnswerCall = 12, + staffAnswerCall2 = 13, + staffCheckBoard = 14, + staffFix = 15, + staffFix2 = 16, + staffFixGround = 17, + staffFix3 = 18, + staffWatering = 19, + joy = 20, + readMap = 21, + wave = 22, + staffEmptyBin = 23, + wave2 = 24, + takePhoto = 25, + clap = 26, + disgust = 27, + drawPicture = 28, + beingWatched = 29, + withdrawMoney = 30, + + idle = 254, + walking = 255, + }; + + enum class PeepAnimationType : uint8_t + { + walking = 0, + checkTime = 1, + watchRide = 2, + eatFood = 3, + shakeHead = 4, + emptyPockets = 5, + holdMat = 6, + sittingIdle = 7, + sittingEatFood = 8, + sittingLookAroundLeft = 9, + sittingLookAroundRight = 10, + hanging = 11, + staffMower = 12, + wow = 13, + throwUp = 14, + jump = 15, + staffSweep = 16, + drowning = 17, + staffAnswerCall = 18, + staffAnswerCall2 = 19, + staffCheckBoard = 20, + staffFix = 21, + staffFix2 = 22, + staffFixGround = 23, + staffFix3 = 24, + staffWatering = 25, + joy = 26, + readMap = 27, + wave = 28, + staffEmptyBin = 29, + wave2 = 30, + takePhoto = 31, + clap = 32, + disgust = 33, + drawPicture = 34, + beingWatched = 35, + withdrawMoney = 36, + + invalid = 255 + }; + + enum PeepFlags : uint32_t + { + PEEP_FLAGS_LEAVING_PARK = (1 << 0), + PEEP_FLAGS_SLOW_WALK = (1 << 1), + PEEP_FLAGS_DEBUG_PATHFINDING = (1 << 2), // Enables debug logging for path finding + PEEP_FLAGS_TRACKING = (1 << 3), + PEEP_FLAGS_WAVING = (1 << 4), // Makes the peep wave + PEEP_FLAGS_HAS_PAID_FOR_PARK_ENTRY = (1 << 5), // Set on paying to enter park + PEEP_FLAGS_PHOTO = (1 << 6), // Makes the peep take a picture + PEEP_FLAGS_PAINTING = (1 << 7), + PEEP_FLAGS_WOW = (1 << 8), // Makes a peep WOW2 + PEEP_FLAGS_LITTER = (1 << 9), // Makes the peep throw litter + PEEP_FLAGS_LOST = (1 << 10), // Makes the peep feel lost (animation triggered) + PEEP_FLAGS_HUNGER = (1 << 11), // Makes the peep become hungry quicker + PEEP_FLAGS_TOILET = (1 << 12), // Makes the peep want to go to the toilet + PEEP_FLAGS_CROWDED = (1 << 13), // The peep will start feeling crowded + PEEP_FLAGS_HAPPINESS = (1 << 14), // The peep will start increasing happiness + PEEP_FLAGS_NAUSEA = (1 << 15), // Makes the peep feel sick (e.g. after an extreme ride) + PEEP_FLAGS_PURPLE = (1 << 16), // Makes surrounding peeps purple + PEEP_FLAGS_PIZZA = (1 << 17), // Gives passing peeps pizza + PEEP_FLAGS_EXPLODE = (1 << 18), + PEEP_FLAGS_RIDE_SHOULD_BE_MARKED_AS_FAVOURITE = (1 << 19), + PEEP_FLAGS_PARK_ENTRANCE_CHOSEN = (1 << 20), // Set when the nearest park entrance has been chosen + PEEP_FLAGS_21 = (1 << 21), + PEEP_FLAGS_CONTAGIOUS = (1 << 22), // Makes any peeps in surrounding tiles sick + PEEP_FLAGS_JOY = (1 << 23), // Makes the peep jump in joy + PEEP_FLAGS_ANGRY = (1 << 24), + PEEP_FLAGS_ICE_CREAM = (1 << 25), // Gives passing peeps ice cream and they wave back + PEEP_FLAGS_NICE_RIDE_DEPRECATED = (1 << 26), // Used to make the peep think "Nice ride! But not as good as the + // Phoenix..." on exiting a ride + PEEP_FLAGS_INTAMIN_DEPRECATED = (1 << 27), // Used to make the peep think "I'm so excited - It's an Intamin ride!" while + // riding on a Intamin ride. + PEEP_FLAGS_HERE_WE_ARE = (1 << 28), // Makes the peep think "...and here we are on X!" while riding a ride + PEEP_FLAGS_POSITION_FROZEN = (1 << 29), // Prevents the peep from moving around, thus keeping them in place + PEEP_FLAGS_ANIMATION_FROZEN = (1 << 30), // Prevents the peep sprite from updating + PEEP_FLAGS_TWITCH_DEPRECATED = (1u << 31), // Formerly used for twitch integration + }; + + enum PeepNextFlags + { + PEEP_NEXT_FLAG_DIRECTION_MASK = 0x3, + PEEP_NEXT_FLAG_IS_SLOPED = (1 << 2), + PEEP_NEXT_FLAG_IS_SURFACE = (1 << 3), + PEEP_NEXT_FLAG_UNUSED = (1 << 4), + }; + + enum class PeepAnimationGroup : uint8_t + { + normal = 0, + + // Security staff + alternate = 1, + + // Guest variations + iceCream = 1, + chips = 2, + burger = 3, + drink = 4, + balloon = 5, + candyfloss = 6, + umbrella = 7, + pizza = 8, + popcorn = 9, + armsCrossed = 10, + headDown = 11, + nauseous = 12, + veryNauseous = 13, + requireToilet = 14, + hat = 15, + hotDog = 16, + tentacle = 17, + toffeeApple = 18, + doughnut = 19, + coffee = 20, + chicken = 21, + lemonade = 22, + watching = 23, + pretzel = 24, + sunglasses = 25, + sujeonggwa = 26, + juice = 27, + funnelCake = 28, + noodles = 29, + sausage = 30, + soup = 31, + sandwich = 32, + + invalid = 255 + }; + + // Flags used by peep->WindowInvalidateFlags + enum PeepInvalidate + { + PEEP_INVALIDATE_PEEP_THOUGHTS = 1, + PEEP_INVALIDATE_PEEP_STATS = 1 << 1, + PEEP_INVALIDATE_PEEP_2 = 1 << 2, + PEEP_INVALIDATE_PEEP_INVENTORY = 1 << 3, + PEEP_INVALIDATE_STAFF_STATS = 1 << 4, + PEEP_INVALIDATE_PEEP_ACTION = 1 << 5, // Currently set only when GuestHeadingToRideId is changed + }; + + struct Guest; + struct Staff; + + struct Peep : EntityBase + { + char* Name; + CoordsXYZ NextLoc; + uint8_t NextFlags; + PeepState State; + union { - uint8_t CurrentCar; - uint8_t CurrentSeat; + uint8_t SubState; + PeepSittingSubState SittingSubState; + PeepRideSubState RideSubState; + PeepUsingBinSubState UsingBinSubState; }; - uint16_t TimeToSitdown; - struct + ObjectEntryIndex AnimationObjectIndex; + PeepAnimationGroup AnimationGroup; + Drawing::Colour TshirtColour; + Drawing::Colour TrousersColour; + union { - uint8_t TimeToStand; - uint8_t StandingFlags; + uint16_t DestinationX; + PeepSpiralSlideSubState spiralSlideSubstate; }; - uint8_t timesSlidDown; + union + { + uint16_t DestinationY; + uint16_t spiralSlideGoingUpTimer; + }; + uint8_t DestinationTolerance; // How close to destination before next action/state 0 = exact + uint8_t Var37; + uint8_t Energy; + uint8_t EnergyTarget; + uint8_t Mass; + uint8_t WindowInvalidateFlags; + RideId CurrentRide; + StationIndex CurrentRideStation; + uint8_t CurrentTrain; + union + { + struct + { + uint8_t CurrentCar; + uint8_t CurrentSeat; + }; + uint16_t TimeToSitdown; + struct + { + uint8_t TimeToStand; + uint8_t StandingFlags; + }; + uint8_t timesSlidDown; + }; + // Normally 0, 1 for carrying sliding board on spiral slide ride, 2 for carrying lawn mower + uint8_t SpecialSprite; + PeepAnimationType AnimationType; + // Seems to be used like a local variable, as it's always set before calling SwitchNextAnimationType, which + // reads this again + PeepAnimationType NextAnimationType; + uint8_t AnimationImageIdOffset; + PeepActionType Action; + uint8_t AnimationFrameNum; + uint8_t StepProgress; + union + { + uint8_t MazeLastEdge; + ::Direction PeepDirection; // Direction ? + }; + RideId InteractionRideIndex; + uint32_t PeepId; + uint8_t PathCheckOptimisation; // see peep.checkForPath + TileCoordsXYZD PathfindGoal; + std::array PathfindHistory; + uint8_t WalkingAnimationFrameNum; + uint32_t PeepFlags; + + public: // Peep + std::optional UpdateAction(int16_t& xy_distance); + std::optional UpdateAction(); + bool UpdateActionAnimation(); + std::optional UpdateWalkingAction(const CoordsXY& differenceLoc, int16_t& xy_distance); + void UpdateWalkingAnimation(); + void SetState(PeepState new_state); + void Remove(); + void UpdateCurrentAnimationType(); + void UpdateSpriteBoundingBox(); + void SwitchToSpecialSprite(uint8_t special_sprite_id); + void StateReset(); + [[nodiscard]] uint8_t GetNextDirection() const; + bool GetNextIsSloped() const; + bool GetNextIsSurface() const; + void SetNextFlags(uint8_t next_direction, bool is_sloped, bool is_surface); + bool CanBePickedUp() const; + void Pickup(); + void PickupAbort(int32_t old_x); + [[nodiscard]] GameActions::Result Place(const TileCoordsXYZ& location, bool apply); + void RemoveFromRide(); + void FormatActionTo(Formatter&) const; + void FormatNameTo(Formatter&) const; + [[nodiscard]] std::string GetName() const; + bool SetName(std::string_view value); + bool IsActionWalking() const; + bool IsActionIdle() const; + bool IsActionInterruptable() const; + bool IsActionInterruptableSafely() const; + + // Reset the peep's stored goal, which means they will forget any stored pathfinding history + // on the next GuestPathfinding::ChooseDirection call. + void ResetPathfindGoal(); + + void SetDestination(const CoordsXY& coords); + void SetDestination(const CoordsXY& coords, int32_t tolerance); + [[nodiscard]] CoordsXY GetDestination() const; + + void Serialise(class DataSerialiser& stream); + + // TODO: Make these private again when done refactoring + public: // Peep + [[nodiscard]] bool CheckForPath(); + std::pair PerformNextAction(); + [[nodiscard]] int32_t GetZOnSlope(int32_t tile_x, int32_t tile_y); + void SwitchNextAnimationType(); + [[nodiscard]] PeepAnimationType GetAnimationType(); + + protected: + bool ShouldWaitForLevelCrossing() const; + bool IsOnLevelCrossing() const; + bool IsOnPathBlockedByVehicle() const; + void UpdateWaitingAtCrossing(); + void UpdateFalling(); + void Update1(); + void UpdatePicked(); + uint32_t GetStepsToTake() const; }; - // Normally 0, 1 for carrying sliding board on spiral slide ride, 2 for carrying lawn mower - uint8_t SpecialSprite; - PeepAnimationType AnimationType; - // Seems to be used like a local variable, as it's always set before calling SwitchNextAnimationType, which - // reads this again - PeepAnimationType NextAnimationType; - uint8_t AnimationImageIdOffset; - PeepActionType Action; - uint8_t AnimationFrameNum; - uint8_t StepProgress; - union + + enum { - uint8_t MazeLastEdge; - ::Direction PeepDirection; // Direction ? + PATHING_DESTINATION_REACHED = 1 << 0, + PATHING_OUTSIDE_PARK = 1 << 1, + PATHING_RIDE_EXIT = 1 << 2, + PATHING_RIDE_ENTRANCE = 1 << 3, }; - RideId InteractionRideIndex; - uint32_t PeepId; - uint8_t PathCheckOptimisation; // see peep.checkForPath - TileCoordsXYZD PathfindGoal; - std::array PathfindHistory; - uint8_t WalkingAnimationFrameNum; - uint32_t PeepFlags; -public: // Peep - std::optional UpdateAction(int16_t& xy_distance); - std::optional UpdateAction(); - bool UpdateActionAnimation(); - std::optional UpdateWalkingAction(const CoordsXY& differenceLoc, int16_t& xy_distance); - void UpdateWalkingAnimation(); - void SetState(PeepState new_state); - void Remove(); - void UpdateCurrentAnimationType(); - void UpdateSpriteBoundingBox(); - void SwitchToSpecialSprite(uint8_t special_sprite_id); - void StateReset(); - [[nodiscard]] uint8_t GetNextDirection() const; - bool GetNextIsSloped() const; - bool GetNextIsSurface() const; - void SetNextFlags(uint8_t next_direction, bool is_sloped, bool is_surface); - bool CanBePickedUp() const; - void Pickup(); - void PickupAbort(int32_t old_x); - [[nodiscard]] OpenRCT2::GameActions::Result Place(const TileCoordsXYZ& location, bool apply); - void RemoveFromRide(); - void FormatActionTo(OpenRCT2::Formatter&) const; - void FormatNameTo(OpenRCT2::Formatter&) const; - [[nodiscard]] std::string GetName() const; - bool SetName(std::string_view value); - bool IsActionWalking() const; - bool IsActionIdle() const; - bool IsActionInterruptable() const; - bool IsActionInterruptableSafely() const; + int32_t PeepGetStaffCount(); + void PeepUpdateAll(); + void PeepUpdateAllBoundingBoxes(); + void PeepProblemWarningsUpdate(); + void PeepStopCrowdNoise(); + void PeepUpdateCrowdNoise(); + void PeepUpdateDaysInQueue(); + void PeepApplause(); + int32_t GetPeepFaceSpriteSmall(Guest* peep); + int32_t GetPeepFaceSpriteLarge(Guest* peep); + void PeepEntityRemove(Peep* peep); - // Reset the peep's stored goal, which means they will forget any stored pathfinding history - // on the next GuestPathfinding::ChooseDirection call. - void ResetPathfindGoal(); + void PeepWindowStateUpdate(Peep* peep); + void PeepDecrementNumRiders(Peep* peep); - void SetDestination(const CoordsXY& coords); - void SetDestination(const CoordsXY& coords, int32_t tolerance); - [[nodiscard]] CoordsXY GetDestination() const; + void PeepSetMapTooltip(Peep* peep); + int32_t PeepCompare(EntityId sprite_index_a, EntityId sprite_index_b); - void Serialise(class OpenRCT2::DataSerialiser& stream); + void PeepUpdateNames(); - // TODO: Make these private again when done refactoring -public: // Peep - [[nodiscard]] bool CheckForPath(); - std::pair PerformNextAction(); - [[nodiscard]] int32_t GetZOnSlope(int32_t tile_x, int32_t tile_y); - void SwitchNextAnimationType(); - [[nodiscard]] PeepAnimationType GetAnimationType(); - -protected: - bool ShouldWaitForLevelCrossing() const; - bool IsOnLevelCrossing() const; - bool IsOnPathBlockedByVehicle() const; - void UpdateWaitingAtCrossing(); - void UpdateFalling(); - void Update1(); - void UpdatePicked(); - uint32_t GetStepsToTake() const; -}; - -enum -{ - PATHING_DESTINATION_REACHED = 1 << 0, - PATHING_OUTSIDE_PARK = 1 << 1, - PATHING_RIDE_EXIT = 1 << 2, - PATHING_RIDE_ENTRANCE = 1 << 3, -}; - -int32_t PeepGetStaffCount(); -void PeepUpdateAll(); -void PeepUpdateAllBoundingBoxes(); -void PeepProblemWarningsUpdate(); -void PeepStopCrowdNoise(); -void PeepUpdateCrowdNoise(); -void PeepUpdateDaysInQueue(); -void PeepApplause(); -int32_t GetPeepFaceSpriteSmall(Guest* peep); -int32_t GetPeepFaceSpriteLarge(Guest* peep); -void PeepEntityRemove(Peep* peep); - -void PeepWindowStateUpdate(Peep* peep); -void PeepDecrementNumRiders(Peep* peep); - -void PeepSetMapTooltip(Peep* peep); -int32_t PeepCompare(EntityId sprite_index_a, EntityId sprite_index_b); - -void PeepUpdateNames(); - -StringId GetRealNameStringIDFromPeepID(uint32_t id); + StringId GetRealNameStringIDFromPeepID(uint32_t id); +} // namespace OpenRCT2 diff --git a/src/openrct2/entity/Staff.cpp b/src/openrct2/entity/Staff.cpp index 52a6ae2e5c..cd94e5f4b6 100644 --- a/src/openrct2/entity/Staff.cpp +++ b/src/openrct2/entity/Staff.cpp @@ -48,2589 +48,2593 @@ #include #include -using namespace OpenRCT2; - -template<> -bool EntityBase::Is() const +namespace OpenRCT2 { - return Type == EntityType::staff; -} - -/** - * - * rct2: 0x006C0905 - */ -bool Staff::IsLocationInPatrol(const CoordsXY& loc) const -{ - // Check if location is in the park - if (!MapIsLocationOwnedOrHasRights(loc)) - return false; - - // Check if staff has patrol area - if (!HasPatrolArea()) - return true; - - return IsPatrolAreaSet(loc); -} - -// Check whether the location x,y is inside and on the edge of the -// patrol zone for mechanic. -bool Staff::IsLocationOnPatrolEdge(const CoordsXY& loc) const -{ - bool onZoneEdge = false; - for (uint8_t neighbourDir = 0; !onZoneEdge && neighbourDir <= 7; neighbourDir++) + template<> + bool EntityBase::Is() const { - auto neighbourPos = loc + CoordsDirectionDelta[neighbourDir]; - onZoneEdge = !IsLocationInPatrol(neighbourPos); - } - return onZoneEdge; -} - -bool Staff::CanIgnoreWideFlag(const CoordsXYZ& staffPos, TileElement* path) const -{ - /* Wide flags can potentially wall off parts of a staff patrol zone - * for the heuristic search. - * This function provide doors through such "walls" by defining - * the conditions under which staff can ignore the wide path flag. */ - /* Staff can ignore the wide flag on a path on the edge of the patrol - * zone based on its adjacent tiles that are also in the patrol zone - * but not on the patrol zone edge: - * Basic points of interest are: - * - how many such tiles there are; - * - whether there are connected paths on those tiles; - * - whether the connected paths have the wide flag set. - * If there are no such tiles, the path is a concave corner of - * the patrol zone and the wide flag can be ignored. - * If there is one such tile, the path is on a straight side of the - * patrol zone. If this one tile is either a connected wide path or - * not a connected path, the wide flag can be ignored. - * If there are two such tiles, the path is a convex corner of the - * patrol zone. If at most one of these tiles is a connected path or - * both of these tiles are connected wide paths, the wide flag can be - * ignored. */ - - if (!IsLocationOnPatrolEdge(staffPos)) - { - return false; + return Type == EntityType::staff; } - /* Check the connected adjacent paths that are also inside the patrol - * zone but are not on the patrol zone edge have the wide flag set. */ - uint8_t total = 0; - uint8_t pathcount = 0; - uint8_t widecount = 0; - for (Direction adjac_dir : kAllDirections) + /** + * + * rct2: 0x006C0905 + */ + bool Staff::IsLocationInPatrol(const CoordsXY& loc) const { - auto adjacPos = staffPos + CoordsXYZ{ CoordsDirectionDelta[adjac_dir].x, CoordsDirectionDelta[adjac_dir].y, 0 }; + // Check if location is in the park + if (!MapIsLocationOwnedOrHasRights(loc)) + return false; - /* Ignore adjacent tiles outside the patrol zone. */ - if (!IsLocationInPatrol(adjacPos)) - continue; + // Check if staff has patrol area + if (!HasPatrolArea()) + return true; - /* Ignore adjacent tiles on the patrol zone edge. */ - if (IsLocationOnPatrolEdge(adjacPos)) - continue; + return IsPatrolAreaSet(loc); + } - /* Adjacent tile is inside the patrol zone but not on the - * patrol zone edge. */ - total++; - - /* Check if path has an edge in adjac_dir */ - if (!(path->AsPath()->GetEdges() & (1u << adjac_dir))) + // Check whether the location x,y is inside and on the edge of the + // patrol zone for mechanic. + bool Staff::IsLocationOnPatrolEdge(const CoordsXY& loc) const + { + bool onZoneEdge = false; + for (uint8_t neighbourDir = 0; !onZoneEdge && neighbourDir <= 7; neighbourDir++) { - continue; + auto neighbourPos = loc + CoordsDirectionDelta[neighbourDir]; + onZoneEdge = !IsLocationInPatrol(neighbourPos); + } + return onZoneEdge; + } + + bool Staff::CanIgnoreWideFlag(const CoordsXYZ& staffPos, TileElement* path) const + { + /* Wide flags can potentially wall off parts of a staff patrol zone + * for the heuristic search. + * This function provide doors through such "walls" by defining + * the conditions under which staff can ignore the wide path flag. */ + /* Staff can ignore the wide flag on a path on the edge of the patrol + * zone based on its adjacent tiles that are also in the patrol zone + * but not on the patrol zone edge: + * Basic points of interest are: + * - how many such tiles there are; + * - whether there are connected paths on those tiles; + * - whether the connected paths have the wide flag set. + * If there are no such tiles, the path is a concave corner of + * the patrol zone and the wide flag can be ignored. + * If there is one such tile, the path is on a straight side of the + * patrol zone. If this one tile is either a connected wide path or + * not a connected path, the wide flag can be ignored. + * If there are two such tiles, the path is a convex corner of the + * patrol zone. If at most one of these tiles is a connected path or + * both of these tiles are connected wide paths, the wide flag can be + * ignored. */ + + if (!IsLocationOnPatrolEdge(staffPos)) + { + return false; } - if (path->AsPath()->IsSloped()) + /* Check the connected adjacent paths that are also inside the patrol + * zone but are not on the patrol zone edge have the wide flag set. */ + uint8_t total = 0; + uint8_t pathcount = 0; + uint8_t widecount = 0; + for (Direction adjac_dir : kAllDirections) { - if (path->AsPath()->GetSlopeDirection() == adjac_dir) + auto adjacPos = staffPos + CoordsXYZ{ CoordsDirectionDelta[adjac_dir].x, CoordsDirectionDelta[adjac_dir].y, 0 }; + + /* Ignore adjacent tiles outside the patrol zone. */ + if (!IsLocationInPatrol(adjacPos)) + continue; + + /* Ignore adjacent tiles on the patrol zone edge. */ + if (IsLocationOnPatrolEdge(adjacPos)) + continue; + + /* Adjacent tile is inside the patrol zone but not on the + * patrol zone edge. */ + total++; + + /* Check if path has an edge in adjac_dir */ + if (!(path->AsPath()->GetEdges() & (1u << adjac_dir))) { - adjacPos.z += kPathHeightStep; + continue; + } + + if (path->AsPath()->IsSloped()) + { + if (path->AsPath()->GetSlopeDirection() == adjac_dir) + { + adjacPos.z += kPathHeightStep; + } + } + + /* Search through all adjacent map elements */ + TileElement* test_element = MapGetFirstElementAt(adjacPos); + if (test_element == nullptr) + return false; + bool pathfound = false; + bool widefound = false; + do + { + if (test_element->GetType() != TileElementType::Path) + { + continue; + } + + /* test_element is a path */ + const auto* adjacentPathElement = test_element->AsPath(); + if (!FootpathIsZAndDirectionValid(*adjacentPathElement, adjacPos.z / kCoordsZStep, adjac_dir)) + continue; + + /* test_element is a connected path */ + if (!pathfound) + { + pathfound = true; + pathcount++; + } + + if (adjacentPathElement->IsWide()) + { + if (!widefound) + { + widefound = true; + widecount++; + } + } + } while (!(test_element++)->IsLastForTile()); + } + + switch (total) + { + case 0: /* Concave corner */ + return true; + case 1: /* Straight side */ + case 2: /* Convex corner */ + if (pathcount <= total - 1 || widecount == total) + { + return true; + } + } + + return false; + } + + /** + * + * rct2: 0x006C095B + * returns 0xF if not in a valid patrol area + */ + uint8_t Staff::GetValidPatrolDirections(const CoordsXY& loc) const + { + uint8_t directions = 0; + + if (IsLocationInPatrol({ loc.x - kCoordsXYStep, loc.y })) + { + directions |= (1 << 0); + } + + if (IsLocationInPatrol({ loc.x, loc.y + kCoordsXYStep })) + { + directions |= (1 << 1); + } + + if (IsLocationInPatrol({ loc.x + kCoordsXYStep, loc.y })) + { + directions |= (1 << 2); + } + + if (IsLocationInPatrol({ loc.x, loc.y - kCoordsXYStep })) + { + directions |= (1 << 3); + } + + if (directions == 0) + { + directions = 0xF; + } + + return directions; + } + + /** + * + * rct2: 0x006C1955 + */ + void Staff::ResetStats() + { + for (auto peep : EntityList()) + { + peep->SetHireDate(GetDate().GetMonthsElapsed()); + peep->StaffLawnsMown = 0; + peep->StaffRidesFixed = 0; + peep->StaffGardensWatered = 0; + peep->StaffRidesInspected = 0; + peep->StaffLitterSwept = 0; + peep->StaffVandalsStopped = 0; + peep->StaffBinsEmptied = 0; + } + } + + bool Staff::IsPatrolAreaSet(const CoordsXY& coords) const + { + if (PatrolInfo != nullptr) + { + return PatrolInfo->Get(coords); + } + return false; + } + + void Staff::SetPatrolArea(const CoordsXY& coords, bool value) + { + if (PatrolInfo == nullptr) + { + if (value) + { + PatrolInfo = new PatrolArea(); + } + else + { + return; } } - /* Search through all adjacent map elements */ - TileElement* test_element = MapGetFirstElementAt(adjacPos); - if (test_element == nullptr) - return false; - bool pathfound = false; - bool widefound = false; + PatrolInfo->Set(coords, value); + } + + void Staff::SetPatrolArea(const MapRange& range, bool value) + { + for (int32_t yy = range.GetY1(); yy <= range.GetY2(); yy += kCoordsXYStep) + { + for (int32_t xx = range.GetX1(); xx <= range.GetX2(); xx += kCoordsXYStep) + { + SetPatrolArea({ xx, yy }, value); + } + } + } + + void Staff::ClearPatrolArea() + { + delete PatrolInfo; + PatrolInfo = nullptr; + } + + bool Staff::HasPatrolArea() const + { + return PatrolInfo == nullptr ? false : !PatrolInfo->IsEmpty(); + } + + /** + * + * rct2: 0x006BFBE8 + * + * Returns kInvalidDirection when no nearby litter or unpathable litter + */ + Direction Staff::HandymanDirectionToNearestLitter() const + { + // Maximum manhattan distance that litter can be for a handyman to seek to it + constexpr auto kTileRadius = 3; + constexpr auto kLookupRadius = kCoordsXYStep * kTileRadius; + + auto nearestLitterDist = std::numeric_limits::max(); + Litter* nearestLitter = nullptr; + + for (int32_t tileX = x - kLookupRadius; tileX <= x + kLookupRadius; tileX += kCoordsXYStep) + { + for (int32_t tileY = y - kLookupRadius; tileY <= y + kLookupRadius; tileY += kCoordsXYStep) + { + for (auto* litter : EntityTileList({ tileX, tileY })) + { + // Calculate Manhattan distance with z-weighting + uint16_t distance = std::abs(litter->x - x) + std::abs(litter->y - y) + std::abs(litter->z - z) * 4; + + if (distance < nearestLitterDist) + { + nearestLitterDist = distance; + nearestLitter = litter; + } + } + } + } + + if (nearestLitterDist > kLookupRadius || nearestLitter == nullptr) + { + return kInvalidDirection; + } + + auto litterTile = CoordsXY{ nearestLitter->x, nearestLitter->y }.ToTileStart(); + + if (!IsLocationInPatrol(litterTile)) + { + return kInvalidDirection; + } + + Direction nextDirection = DirectionFromTo(CoordsXY(x, y), litterTile.ToTileCentre()); + + CoordsXY nextTile = litterTile.ToTileStart() - CoordsDirectionDelta[nextDirection]; + + int16_t nextZ = ((z + kCoordsZStep) & 0xFFF0) / kCoordsZStep; + + TileElement* tileElement = MapGetFirstElementAt(nextTile); + if (tileElement == nullptr) + return kInvalidDirection; do { - if (test_element->GetType() != TileElementType::Path) - { + if (tileElement->BaseHeight != nextZ) continue; + if (tileElement->GetType() == TileElementType::Entrance || tileElement->GetType() == TileElementType::Track) + { + return kInvalidDirection; } + } while (!(tileElement++)->IsLastForTile()); - /* test_element is a path */ - const auto* adjacentPathElement = test_element->AsPath(); - if (!FootpathIsZAndDirectionValid(*adjacentPathElement, adjacPos.z / kCoordsZStep, adjac_dir)) + nextTile = CoordsXY(x, y).ToTileStart() + CoordsDirectionDelta[nextDirection]; + + tileElement = MapGetFirstElementAt(nextTile); + if (tileElement == nullptr) + return kInvalidDirection; + + do + { + if (tileElement->BaseHeight != nextZ) continue; - - /* test_element is a connected path */ - if (!pathfound) + if (tileElement->GetType() == TileElementType::Entrance || tileElement->GetType() == TileElementType::Track) { - pathfound = true; - pathcount++; + return kInvalidDirection; } + } while (!(tileElement++)->IsLastForTile()); - if (adjacentPathElement->IsWide()) + return nextDirection; + } + + /** + * + * rct2: 0x006BF931 + */ + uint8_t Staff::HandymanDirectionToUncutGrass(uint8_t valid_directions) const + { + if (!(GetNextIsSurface())) + { + auto surfaceElement = MapGetSurfaceElementAt(NextLoc); + if (surfaceElement == nullptr) + return kInvalidDirection; + + if (NextLoc.z != surfaceElement->GetBaseZ()) + return kInvalidDirection; + + if (GetNextIsSloped()) { - if (!widefound) - { - widefound = true; - widecount++; - } + if (surfaceElement->GetSlope() != kPathSlopeToLandSlope[GetNextDirection()]) + return kInvalidDirection; } - } while (!(test_element++)->IsLastForTile()); - } - - switch (total) - { - case 0: /* Concave corner */ - return true; - case 1: /* Straight side */ - case 2: /* Convex corner */ - if (pathcount <= total - 1 || widecount == total) - { - return true; - } - } - - return false; -} - -/** - * - * rct2: 0x006C095B - * returns 0xF if not in a valid patrol area - */ -uint8_t Staff::GetValidPatrolDirections(const CoordsXY& loc) const -{ - uint8_t directions = 0; - - if (IsLocationInPatrol({ loc.x - kCoordsXYStep, loc.y })) - { - directions |= (1 << 0); - } - - if (IsLocationInPatrol({ loc.x, loc.y + kCoordsXYStep })) - { - directions |= (1 << 1); - } - - if (IsLocationInPatrol({ loc.x + kCoordsXYStep, loc.y })) - { - directions |= (1 << 2); - } - - if (IsLocationInPatrol({ loc.x, loc.y - kCoordsXYStep })) - { - directions |= (1 << 3); - } - - if (directions == 0) - { - directions = 0xF; - } - - return directions; -} - -/** - * - * rct2: 0x006C1955 - */ -void Staff::ResetStats() -{ - for (auto peep : EntityList()) - { - peep->SetHireDate(GetDate().GetMonthsElapsed()); - peep->StaffLawnsMown = 0; - peep->StaffRidesFixed = 0; - peep->StaffGardensWatered = 0; - peep->StaffRidesInspected = 0; - peep->StaffLitterSwept = 0; - peep->StaffVandalsStopped = 0; - peep->StaffBinsEmptied = 0; - } -} - -bool Staff::IsPatrolAreaSet(const CoordsXY& coords) const -{ - if (PatrolInfo != nullptr) - { - return PatrolInfo->Get(coords); - } - return false; -} - -void Staff::SetPatrolArea(const CoordsXY& coords, bool value) -{ - if (PatrolInfo == nullptr) - { - if (value) - { - PatrolInfo = new PatrolArea(); - } - else - { - return; - } - } - - PatrolInfo->Set(coords, value); -} - -void Staff::SetPatrolArea(const MapRange& range, bool value) -{ - for (int32_t yy = range.GetY1(); yy <= range.GetY2(); yy += kCoordsXYStep) - { - for (int32_t xx = range.GetX1(); xx <= range.GetX2(); xx += kCoordsXYStep) - { - SetPatrolArea({ xx, yy }, value); - } - } -} - -void Staff::ClearPatrolArea() -{ - delete PatrolInfo; - PatrolInfo = nullptr; -} - -bool Staff::HasPatrolArea() const -{ - return PatrolInfo == nullptr ? false : !PatrolInfo->IsEmpty(); -} - -/** - * - * rct2: 0x006BFBE8 - * - * Returns kInvalidDirection when no nearby litter or unpathable litter - */ -Direction Staff::HandymanDirectionToNearestLitter() const -{ - // Maximum manhattan distance that litter can be for a handyman to seek to it - constexpr auto kTileRadius = 3; - constexpr auto kLookupRadius = kCoordsXYStep * kTileRadius; - - auto nearestLitterDist = std::numeric_limits::max(); - Litter* nearestLitter = nullptr; - - for (int32_t tileX = x - kLookupRadius; tileX <= x + kLookupRadius; tileX += kCoordsXYStep) - { - for (int32_t tileY = y - kLookupRadius; tileY <= y + kLookupRadius; tileY += kCoordsXYStep) - { - for (auto* litter : EntityTileList({ tileX, tileY })) - { - // Calculate Manhattan distance with z-weighting - uint16_t distance = std::abs(litter->x - x) + std::abs(litter->y - y) + std::abs(litter->z - z) * 4; - - if (distance < nearestLitterDist) - { - nearestLitterDist = distance; - nearestLitter = litter; - } - } - } - } - - if (nearestLitterDist > kLookupRadius || nearestLitter == nullptr) - { - return kInvalidDirection; - } - - auto litterTile = CoordsXY{ nearestLitter->x, nearestLitter->y }.ToTileStart(); - - if (!IsLocationInPatrol(litterTile)) - { - return kInvalidDirection; - } - - Direction nextDirection = DirectionFromTo(CoordsXY(x, y), litterTile.ToTileCentre()); - - CoordsXY nextTile = litterTile.ToTileStart() - CoordsDirectionDelta[nextDirection]; - - int16_t nextZ = ((z + kCoordsZStep) & 0xFFF0) / kCoordsZStep; - - TileElement* tileElement = MapGetFirstElementAt(nextTile); - if (tileElement == nullptr) - return kInvalidDirection; - do - { - if (tileElement->BaseHeight != nextZ) - continue; - if (tileElement->GetType() == TileElementType::Entrance || tileElement->GetType() == TileElementType::Track) - { - return kInvalidDirection; - } - } while (!(tileElement++)->IsLastForTile()); - - nextTile = CoordsXY(x, y).ToTileStart() + CoordsDirectionDelta[nextDirection]; - - tileElement = MapGetFirstElementAt(nextTile); - if (tileElement == nullptr) - return kInvalidDirection; - - do - { - if (tileElement->BaseHeight != nextZ) - continue; - if (tileElement->GetType() == TileElementType::Entrance || tileElement->GetType() == TileElementType::Track) - { - return kInvalidDirection; - } - } while (!(tileElement++)->IsLastForTile()); - - return nextDirection; -} - -/** - * - * rct2: 0x006BF931 - */ -uint8_t Staff::HandymanDirectionToUncutGrass(uint8_t valid_directions) const -{ - if (!(GetNextIsSurface())) - { - auto surfaceElement = MapGetSurfaceElementAt(NextLoc); - if (surfaceElement == nullptr) - return kInvalidDirection; - - if (NextLoc.z != surfaceElement->GetBaseZ()) - return kInvalidDirection; - - if (GetNextIsSloped()) - { - if (surfaceElement->GetSlope() != kPathSlopeToLandSlope[GetNextDirection()]) + else if (surfaceElement->GetSlope() != kTileSlopeFlat) return kInvalidDirection; } - else if (surfaceElement->GetSlope() != kTileSlopeFlat) - return kInvalidDirection; - } - uint8_t chosenDirection = ScenarioRand() & 0x3; - for (uint8_t i = 0; i < 4; ++i, ++chosenDirection) - { - chosenDirection &= 0x3; - - if (!(valid_directions & (1 << chosenDirection))) + uint8_t chosenDirection = ScenarioRand() & 0x3; + for (uint8_t i = 0; i < 4; ++i, ++chosenDirection) { - continue; - } + chosenDirection &= 0x3; - CoordsXY chosenTile = CoordsXY{ NextLoc } + CoordsDirectionDelta[chosenDirection]; - - if (!MapIsLocationValid(chosenTile)) - continue; - - auto surfaceElement = MapGetSurfaceElementAt(chosenTile); - if (surfaceElement != nullptr) - { - if (std::abs(surfaceElement->GetBaseZ() - NextLoc.z) <= 2 * kCoordsZStep) + if (!(valid_directions & (1 << chosenDirection))) { - if (surfaceElement->CanGrassGrow() && (surfaceElement->GetGrassLength() & 0x7) >= GRASS_LENGTH_CLEAR_1) + continue; + } + + CoordsXY chosenTile = CoordsXY{ NextLoc } + CoordsDirectionDelta[chosenDirection]; + + if (!MapIsLocationValid(chosenTile)) + continue; + + auto surfaceElement = MapGetSurfaceElementAt(chosenTile); + if (surfaceElement != nullptr) + { + if (std::abs(surfaceElement->GetBaseZ() - NextLoc.z) <= 2 * kCoordsZStep) { - return chosenDirection; + if (surfaceElement->CanGrassGrow() && (surfaceElement->GetGrassLength() & 0x7) >= GRASS_LENGTH_CLEAR_1) + { + return chosenDirection; + } } } } - } - return kInvalidDirection; -} - -/** - * - * rct2: 0x006BFD9C - */ -Direction Staff::HandymanDirectionRandSurface(uint8_t validDirections) const -{ - Direction newDirection = ScenarioRand() % kNumOrthogonalDirections; - for (int32_t i = 0; i < kNumOrthogonalDirections; ++i, ++newDirection) - { - newDirection %= kNumOrthogonalDirections; - if (!(validDirections & (1 << newDirection))) - continue; - - CoordsXY chosenTile = CoordsXY{ NextLoc } + CoordsDirectionDelta[newDirection]; - - if (MapSurfaceIsBlocked(chosenTile)) - continue; - - break; - } - // If it tries all directions this is required - // to make it back to the first direction and - // override validDirections - newDirection %= kNumOrthogonalDirections; - return newDirection; -} - -/** - * - * rct2: 0x006BFBA8 - */ -bool Staff::DoHandymanPathFinding() -{ - StaffMowingTimeout++; - - Direction litterDirection = kInvalidDirection; - uint8_t validDirections = GetValidPatrolDirections(NextLoc); - - if ((StaffOrders & STAFF_ORDERS_SWEEPING) && ((getGameState().currentTicks + Id.ToUnderlying()) & 0xFFF) > 110) - { - litterDirection = HandymanDirectionToNearestLitter(); + return kInvalidDirection; } - Direction newDirection = kInvalidDirection; - if (litterDirection == kInvalidDirection && (StaffOrders & STAFF_ORDERS_MOWING) && StaffMowingTimeout >= 12) + /** + * + * rct2: 0x006BFD9C + */ + Direction Staff::HandymanDirectionRandSurface(uint8_t validDirections) const { - newDirection = HandymanDirectionToUncutGrass(validDirections); - } - - if (newDirection == kInvalidDirection) - { - if (GetNextIsSurface()) + Direction newDirection = ScenarioRand() % kNumOrthogonalDirections; + for (int32_t i = 0; i < kNumOrthogonalDirections; ++i, ++newDirection) { - newDirection = HandymanDirectionRandSurface(validDirections); + newDirection %= kNumOrthogonalDirections; + if (!(validDirections & (1 << newDirection))) + continue; + + CoordsXY chosenTile = CoordsXY{ NextLoc } + CoordsDirectionDelta[newDirection]; + + if (MapSurfaceIsBlocked(chosenTile)) + continue; + + break; } - else + // If it tries all directions this is required + // to make it back to the first direction and + // override validDirections + newDirection %= kNumOrthogonalDirections; + return newDirection; + } + + /** + * + * rct2: 0x006BFBA8 + */ + bool Staff::DoHandymanPathFinding() + { + StaffMowingTimeout++; + + Direction litterDirection = kInvalidDirection; + uint8_t validDirections = GetValidPatrolDirections(NextLoc); + + if ((StaffOrders & STAFF_ORDERS_SWEEPING) && ((getGameState().currentTicks + Id.ToUnderlying()) & 0xFFF) > 110) { - auto* pathElement = MapGetPathElementAt(TileCoordsXYZ{ NextLoc }); + litterDirection = HandymanDirectionToNearestLitter(); + } - if (pathElement == nullptr) - return true; + Direction newDirection = kInvalidDirection; + if (litterDirection == kInvalidDirection && (StaffOrders & STAFF_ORDERS_MOWING) && StaffMowingTimeout >= 12) + { + newDirection = HandymanDirectionToUncutGrass(validDirections); + } - uint8_t pathDirections = (pathElement->GetEdges() & validDirections) & 0xF; - if (pathDirections == 0) + if (newDirection == kInvalidDirection) + { + if (GetNextIsSurface()) { newDirection = HandymanDirectionRandSurface(validDirections); } else { - bool chooseRandom = true; - if (litterDirection != kInvalidDirection && pathDirections & (1 << litterDirection)) + auto* pathElement = MapGetPathElementAt(TileCoordsXYZ{ NextLoc }); + + if (pathElement == nullptr) + return true; + + uint8_t pathDirections = (pathElement->GetEdges() & validDirections) & 0xF; + if (pathDirections == 0) { - // Check whether path is a queue path and connected to a ride - bool connectedQueue = (pathElement->IsQueue() && !pathElement->GetRideIndex().IsNull()); - // When in a queue path make the probability of following litter much lower (10% instead of 90%) - // as handymen often get stuck when there is litter on a normal path next to a queue they are in - uint32_t chooseRandomProbability = connectedQueue ? 0xE666 : 0x1999; - if ((ScenarioRand() & 0xFFFF) >= chooseRandomProbability) - { - chooseRandom = false; - newDirection = litterDirection; - } + newDirection = HandymanDirectionRandSurface(validDirections); } else { - pathDirections &= ~(1 << DirectionReverse(PeepDirection)); - if (pathDirections == 0) + bool chooseRandom = true; + if (litterDirection != kInvalidDirection && pathDirections & (1 << litterDirection)) { - pathDirections |= 1 << DirectionReverse(PeepDirection); + // Check whether path is a queue path and connected to a ride + bool connectedQueue = (pathElement->IsQueue() && !pathElement->GetRideIndex().IsNull()); + // When in a queue path make the probability of following litter much lower (10% instead of 90%) + // as handymen often get stuck when there is litter on a normal path next to a queue they are in + uint32_t chooseRandomProbability = connectedQueue ? 0xE666 : 0x1999; + if ((ScenarioRand() & 0xFFFF) >= chooseRandomProbability) + { + chooseRandom = false; + newDirection = litterDirection; + } + } + else + { + pathDirections &= ~(1 << DirectionReverse(PeepDirection)); + if (pathDirections == 0) + { + pathDirections |= 1 << DirectionReverse(PeepDirection); + } + } + + if (chooseRandom) + { + do + { + newDirection = ScenarioRand() & 3; + } while ((pathDirections & (1 << newDirection)) == 0); } } - - if (chooseRandom) - { - do - { - newDirection = ScenarioRand() & 3; - } while ((pathDirections & (1 << newDirection)) == 0); - } } } - } - // newDirection can only contain a cardinal direction at this point, no diagonals - assert(DirectionValid(newDirection)); + // newDirection can only contain a cardinal direction at this point, no diagonals + assert(DirectionValid(newDirection)); - CoordsXY chosenTile = CoordsXY{ NextLoc } + CoordsDirectionDelta[newDirection]; + CoordsXY chosenTile = CoordsXY{ NextLoc } + CoordsDirectionDelta[newDirection]; - while (!MapIsLocationValid(chosenTile)) - { - newDirection = HandymanDirectionRandSurface(validDirections); - chosenTile = CoordsXY{ NextLoc } + CoordsDirectionDelta[newDirection]; - } - - PeepDirection = newDirection; - SetDestination(chosenTile + CoordsXY{ 16, 16 }, 3); - if (State == PeepState::queuing) - { - DestinationTolerance = (ScenarioRand() & 7) + 2; - } - return false; -} - -Direction Staff::DirectionSurface(Direction initialDirection) const -{ - uint8_t direction = initialDirection; - for (int32_t i = 0; i < 3; ++i) - { - // Looks left and right from initial direction - switch (i) + while (!MapIsLocationValid(chosenTile)) { - case 1: - direction++; - if (ScenarioRand() & 1) - { + newDirection = HandymanDirectionRandSurface(validDirections); + chosenTile = CoordsXY{ NextLoc } + CoordsDirectionDelta[newDirection]; + } + + PeepDirection = newDirection; + SetDestination(chosenTile + CoordsXY{ 16, 16 }, 3); + if (State == PeepState::queuing) + { + DestinationTolerance = (ScenarioRand() & 7) + 2; + } + return false; + } + + Direction Staff::DirectionSurface(Direction initialDirection) const + { + uint8_t direction = initialDirection; + for (int32_t i = 0; i < 3; ++i) + { + // Looks left and right from initial direction + switch (i) + { + case 1: + direction++; + if (ScenarioRand() & 1) + { + direction -= 2; + } + break; + case 2: direction -= 2; - } - break; - case 2: - direction -= 2; - break; + break; + } + + direction &= 3; + + if (WallInTheWay({ NextLoc, NextLoc.z, NextLoc.z + kPeepClearanceHeight }, direction)) + continue; + + if (WallInTheWay({ NextLoc, NextLoc.z, NextLoc.z + kPeepClearanceHeight }, DirectionReverse(direction))) + continue; + + CoordsXY chosenTile = CoordsXY{ NextLoc } + CoordsDirectionDelta[direction]; + + if (!MapSurfaceIsBlocked(chosenTile)) + { + return direction; + } } + return initialDirection; + } - direction &= 3; + /** + * + * rct2: 0x006BFF45 + */ + Direction Staff::MechanicDirectionSurface() const + { + Direction direction = ScenarioRand() & 3; - if (WallInTheWay({ NextLoc, NextLoc.z, NextLoc.z + kPeepClearanceHeight }, direction)) - continue; - - if (WallInTheWay({ NextLoc, NextLoc.z, NextLoc.z + kPeepClearanceHeight }, DirectionReverse(direction))) - continue; - - CoordsXY chosenTile = CoordsXY{ NextLoc } + CoordsDirectionDelta[direction]; - - if (!MapSurfaceIsBlocked(chosenTile)) + auto ride = GetRide(CurrentRide); + if (ride != nullptr && (State == PeepState::answering || State == PeepState::headingToInspection) + && (ScenarioRand() & 1)) { - return direction; - } - } - return initialDirection; -} - -/** - * - * rct2: 0x006BFF45 - */ -Direction Staff::MechanicDirectionSurface() const -{ - Direction direction = ScenarioRand() & 3; - - auto ride = GetRide(CurrentRide); - if (ride != nullptr && (State == PeepState::answering || State == PeepState::headingToInspection) && (ScenarioRand() & 1)) - { - auto location = ride->getStation(CurrentRideStation).Exit; - if (location.IsNull()) - { - location = ride->getStation(CurrentRideStation).Entrance; - } - - direction = DirectionFromTo(CoordsXY(x, y), location.ToCoordsXY()); - } - - return DirectionSurface(direction); -} - -/** - * - * rct2: 0x006C02D1 - */ -Direction Staff::MechanicDirectionPathRand(uint8_t pathDirections) const -{ - if (ScenarioRand() & 1) - { - if (pathDirections & (1 << PeepDirection)) - return PeepDirection; - } - - // Modified from original to spam scenario_rand less - uint8_t direction = ScenarioRand() & 3; - for (int32_t i = 0; i < 4; ++i, ++direction) - { - direction &= 3; - if (pathDirections & (1 << direction)) - return direction; - } - // This will never happen as pathDirections always has a bit set. - return PeepDirection; -} - -/** - * - * rct2: 0x006C0121 - */ -Direction Staff::MechanicDirectionPath(uint8_t validDirections, PathElement* pathElement) -{ - uint32_t pathDirections = pathElement->GetEdges(); - pathDirections &= validDirections; - - if (pathDirections == 0) - { - return MechanicDirectionSurface(); - } - - // Check if this is dead end - i.e. only way out is the reverse direction. - pathDirections &= ~(1 << DirectionReverse(PeepDirection)); - if (pathDirections == 0) - { - pathDirections |= (1 << DirectionReverse(PeepDirection)); - } - - Direction direction = Numerics::bitScanForward(pathDirections); - pathDirections &= ~(1 << direction); - if (pathDirections == 0) - { - if (State != PeepState::answering && State != PeepState::headingToInspection) - { - return direction; - } - - if (SubState != 2) - { - return direction; - } - SubState = 3; - } - - pathDirections |= (1 << direction); - - // Mechanic is heading to ride (either broken down or for inspection). - auto ride = GetRide(CurrentRide); - if (ride != nullptr && (State == PeepState::answering || State == PeepState::headingToInspection)) - { - /* Find location of the exit for the target ride station - * or if the ride has no exit, the entrance. */ - TileCoordsXYZD location = ride->getStation(CurrentRideStation).Exit; - if (location.IsNull()) - { - location = ride->getStation(CurrentRideStation).Entrance; - - // If no entrance is present either. This is an incorrect state. + auto location = ride->getStation(CurrentRideStation).Exit; if (location.IsNull()) { + location = ride->getStation(CurrentRideStation).Entrance; + } + + direction = DirectionFromTo(CoordsXY(x, y), location.ToCoordsXY()); + } + + return DirectionSurface(direction); + } + + /** + * + * rct2: 0x006C02D1 + */ + Direction Staff::MechanicDirectionPathRand(uint8_t pathDirections) const + { + if (ScenarioRand() & 1) + { + if (pathDirections & (1 << PeepDirection)) + return PeepDirection; + } + + // Modified from original to spam scenario_rand less + uint8_t direction = ScenarioRand() & 3; + for (int32_t i = 0; i < 4; ++i, ++direction) + { + direction &= 3; + if (pathDirections & (1 << direction)) + return direction; + } + // This will never happen as pathDirections always has a bit set. + return PeepDirection; + } + + /** + * + * rct2: 0x006C0121 + */ + Direction Staff::MechanicDirectionPath(uint8_t validDirections, PathElement* pathElement) + { + uint32_t pathDirections = pathElement->GetEdges(); + pathDirections &= validDirections; + + if (pathDirections == 0) + { + return MechanicDirectionSurface(); + } + + // Check if this is dead end - i.e. only way out is the reverse direction. + pathDirections &= ~(1 << DirectionReverse(PeepDirection)); + if (pathDirections == 0) + { + pathDirections |= (1 << DirectionReverse(PeepDirection)); + } + + Direction direction = Numerics::bitScanForward(pathDirections); + pathDirections &= ~(1 << direction); + if (pathDirections == 0) + { + if (State != PeepState::answering && State != PeepState::headingToInspection) + { + return direction; + } + + if (SubState != 2) + { + return direction; + } + SubState = 3; + } + + pathDirections |= (1 << direction); + + // Mechanic is heading to ride (either broken down or for inspection). + auto ride = GetRide(CurrentRide); + if (ride != nullptr && (State == PeepState::answering || State == PeepState::headingToInspection)) + { + /* Find location of the exit for the target ride station + * or if the ride has no exit, the entrance. */ + TileCoordsXYZD location = ride->getStation(CurrentRideStation).Exit; + if (location.IsNull()) + { + location = ride->getStation(CurrentRideStation).Entrance; + + // If no entrance is present either. This is an incorrect state. + if (location.IsNull()) + { + return MechanicDirectionPathRand(pathDirections); + } + } + + const auto goalPos = TileCoordsXYZ{ location }; + Direction pathfindDirection = PathFinding::ChooseDirection( + TileCoordsXYZ{ NextLoc }, goalPos, *this, false, RideId::GetNull()); + if (pathfindDirection == kInvalidDirection) + { + /* Heuristic search failed for all directions. + * Reset the PathfindGoal - this means that the PathfindHistory + * will be reset in the next call to GuestPathfinding::ChooseDirection(). + * This lets the heuristic search "try again" in case the player has + * edited the path layout or the mechanic was already stuck in the + * save game (e.g. with a worse version of the pathfinding). */ + ResetPathfindGoal(); return MechanicDirectionPathRand(pathDirections); } - } - const auto goalPos = TileCoordsXYZ{ location }; - Direction pathfindDirection = PathFinding::ChooseDirection( - TileCoordsXYZ{ NextLoc }, goalPos, *this, false, RideId::GetNull()); - if (pathfindDirection == kInvalidDirection) + return pathfindDirection; + } + return MechanicDirectionPathRand(pathDirections); + } + + /** + * + * rct2: 0x006BFF2C + */ + bool Staff::DoMechanicPathFinding() + { + uint8_t validDirections = GetValidPatrolDirections(NextLoc); + Direction newDirection = kInvalidDirection; + if (GetNextIsSurface()) { - /* Heuristic search failed for all directions. - * Reset the PathfindGoal - this means that the PathfindHistory - * will be reset in the next call to GuestPathfinding::ChooseDirection(). - * This lets the heuristic search "try again" in case the player has - * edited the path layout or the mechanic was already stuck in the - * save game (e.g. with a worse version of the pathfinding). */ - ResetPathfindGoal(); - return MechanicDirectionPathRand(pathDirections); + newDirection = MechanicDirectionSurface(); + } + else + { + auto* pathElement = MapGetPathElementAt(TileCoordsXYZ{ NextLoc }); + if (pathElement == nullptr) + return true; + + newDirection = MechanicDirectionPath(validDirections, pathElement); } - return pathfindDirection; - } - return MechanicDirectionPathRand(pathDirections); -} + // countof(CoordsDirectionDelta) + assert(DirectionValid(newDirection)); -/** - * - * rct2: 0x006BFF2C - */ -bool Staff::DoMechanicPathFinding() -{ - uint8_t validDirections = GetValidPatrolDirections(NextLoc); - Direction newDirection = kInvalidDirection; - if (GetNextIsSurface()) - { - newDirection = MechanicDirectionSurface(); - } - else - { - auto* pathElement = MapGetPathElementAt(TileCoordsXYZ{ NextLoc }); - if (pathElement == nullptr) - return true; + CoordsXY chosenTile = CoordsXY{ NextLoc } + CoordsDirectionDelta[newDirection]; - newDirection = MechanicDirectionPath(validDirections, pathElement); + while (!MapIsLocationValid(chosenTile)) + { + newDirection = MechanicDirectionSurface(); + chosenTile = CoordsXY{ NextLoc } + CoordsDirectionDelta[newDirection]; + } + + PeepDirection = newDirection; + auto tolerance = (ScenarioRand() & 7) + 2; + SetDestination(chosenTile + CoordsXY{ 16, 16 }, tolerance); + + return false; } - // countof(CoordsDirectionDelta) - assert(DirectionValid(newDirection)); - - CoordsXY chosenTile = CoordsXY{ NextLoc } + CoordsDirectionDelta[newDirection]; - - while (!MapIsLocationValid(chosenTile)) + /** + * + * rct2: 0x006C050B + */ + Direction Staff::DirectionPath(uint8_t validDirections, PathElement* pathElement) const { - newDirection = MechanicDirectionSurface(); - chosenTile = CoordsXY{ NextLoc } + CoordsDirectionDelta[newDirection]; - } + uint32_t pathDirections = pathElement->GetEdges(); + if (State != PeepState::answering && State != PeepState::headingToInspection) + { + pathDirections &= validDirections; + } - PeepDirection = newDirection; - auto tolerance = (ScenarioRand() & 7) + 2; - SetDestination(chosenTile + CoordsXY{ 16, 16 }, tolerance); + if (pathDirections == 0) + { + return DirectionSurface(ScenarioRand() & 3); + } - return false; -} + pathDirections &= ~(1u << DirectionReverse(PeepDirection)); + if (pathDirections == 0) + { + pathDirections |= (1u << DirectionReverse(PeepDirection)); + } -/** - * - * rct2: 0x006C050B - */ -Direction Staff::DirectionPath(uint8_t validDirections, PathElement* pathElement) const -{ - uint32_t pathDirections = pathElement->GetEdges(); - if (State != PeepState::answering && State != PeepState::headingToInspection) - { - pathDirections &= validDirections; - } + Direction direction = Numerics::bitScanForward(pathDirections); + // If this is the only direction they can go, then go + if (pathDirections == (1u << direction)) + { + return direction; + } - if (pathDirections == 0) - { - return DirectionSurface(ScenarioRand() & 3); - } + direction = ScenarioRand() & 3; + for (uint8_t i = 0; i < kNumOrthogonalDirections; ++i, direction = DirectionNext(direction)) + { + if (pathDirections & (1u << direction)) + return direction; + } - pathDirections &= ~(1u << DirectionReverse(PeepDirection)); - if (pathDirections == 0) - { - pathDirections |= (1u << DirectionReverse(PeepDirection)); - } - - Direction direction = Numerics::bitScanForward(pathDirections); - // If this is the only direction they can go, then go - if (pathDirections == (1u << direction)) - { + // This will never happen as pathDirections will always have a bit set return direction; } - direction = ScenarioRand() & 3; - for (uint8_t i = 0; i < kNumOrthogonalDirections; ++i, direction = DirectionNext(direction)) + /** + * + * rct2: 0x006C0351 + */ + bool Staff::DoMiscPathFinding() { - if (pathDirections & (1u << direction)) - return direction; - } + uint8_t validDirections = GetValidPatrolDirections(NextLoc); - // This will never happen as pathDirections will always have a bit set - return direction; -} - -/** - * - * rct2: 0x006C0351 - */ -bool Staff::DoMiscPathFinding() -{ - uint8_t validDirections = GetValidPatrolDirections(NextLoc); - - Direction newDirection = kInvalidDirection; - if (GetNextIsSurface()) - { - newDirection = DirectionSurface(ScenarioRand() & 3); - } - else - { - auto* pathElement = MapGetPathElementAt(TileCoordsXYZ{ NextLoc }); - if (pathElement == nullptr) - return true; - - newDirection = DirectionPath(validDirections, pathElement); - } - - CoordsXY chosenTile = CoordsXY{ NextLoc } + CoordsDirectionDelta[newDirection]; - - while (!MapIsLocationValid(chosenTile)) - { - newDirection = DirectionSurface(ScenarioRand() & 3); - chosenTile = CoordsXY{ NextLoc } + CoordsDirectionDelta[newDirection]; - } - - PeepDirection = newDirection; - auto tolerance = (ScenarioRand() & 7) + 2; - SetDestination(chosenTile + CoordsXY{ 16, 16 }, tolerance); - - return false; -} - -bool Staff::IsMechanicHeadingToFixRideBlockingPath() -{ - if (!IsMechanic()) - return false; - - auto tileCoords = TileCoordsXYZ(CoordsXYZ{ GetDestination(), NextLoc.z }); - auto trackElement = MapGetFirstTileElementWithBaseHeightBetween( - { tileCoords, tileCoords.z + kPathHeightStep }); - if (trackElement == nullptr) - return false; - - auto ride = GetRide(trackElement->GetRideIndex()); - if (ride == nullptr) - return false; - - return ride->id == CurrentRide; -} - -/** - * - * rct2: 0x006C086D - */ -void Staff::EntertainerUpdateNearbyPeeps() const -{ - // Iterate over tiles within a 3-tile radius (96 units) - constexpr auto kTileRadius = 3; - constexpr auto kLookupRadius = kCoordsXYStep * kTileRadius; - - for (int32_t tileX = x - kLookupRadius; tileX <= x + kLookupRadius; tileX += kCoordsXYStep) - { - for (int32_t tileY = y - kLookupRadius; tileY <= y + kLookupRadius; tileY += kCoordsXYStep) + Direction newDirection = kInvalidDirection; + if (GetNextIsSurface()) { - for (auto* guest : EntityTileList({ tileX, tileY })) - { - if (guest->x == kLocationNull) - continue; - - int16_t z_dist = std::abs(z - guest->z); - if (z_dist > kTileRadius / 2) - continue; - - int16_t x_dist = std::abs(x - guest->x); - int16_t y_dist = std::abs(y - guest->y); - - if (x_dist > kLookupRadius) - continue; - - if (y_dist > kLookupRadius) - continue; - - if (guest->State == PeepState::walking) - { - guest->HappinessTarget = std::min(guest->HappinessTarget + 4, kPeepMaxHappiness); - } - else if (guest->State == PeepState::queuing) - { - guest->TimeInQueue = std::max(0, guest->TimeInQueue - 200); - guest->HappinessTarget = std::min(guest->HappinessTarget + 3, kPeepMaxHappiness); - } - } + newDirection = DirectionSurface(ScenarioRand() & 3); } - } -} + else + { + auto* pathElement = MapGetPathElementAt(TileCoordsXYZ{ NextLoc }); + if (pathElement == nullptr) + return true; -/** - * - * rct2: 0x006C05AE - */ -bool Staff::DoEntertainerPathFinding() -{ - if (((ScenarioRand() & 0xFFFF) <= 0x4000) && IsActionInterruptableSafely()) - { - Action = (ScenarioRand() & 1) ? PeepActionType::wave2 : PeepActionType::joy; - AnimationFrameNum = 0; - AnimationImageIdOffset = 0; + newDirection = DirectionPath(validDirections, pathElement); + } - UpdateCurrentAnimationType(); - EntertainerUpdateNearbyPeeps(); + CoordsXY chosenTile = CoordsXY{ NextLoc } + CoordsDirectionDelta[newDirection]; + + while (!MapIsLocationValid(chosenTile)) + { + newDirection = DirectionSurface(ScenarioRand() & 3); + chosenTile = CoordsXY{ NextLoc } + CoordsDirectionDelta[newDirection]; + } + + PeepDirection = newDirection; + auto tolerance = (ScenarioRand() & 7) + 2; + SetDestination(chosenTile + CoordsXY{ 16, 16 }, tolerance); + + return false; } - return DoMiscPathFinding(); -} - -/** - * - * rct2: 0x006BF926 - */ -bool Staff::DoPathFinding() -{ - switch (AssignedStaffType) + bool Staff::IsMechanicHeadingToFixRideBlockingPath() { - case StaffType::handyman: - return DoHandymanPathFinding(); - case StaffType::mechanic: - return DoMechanicPathFinding(); - case StaffType::security: - return DoMiscPathFinding(); - case StaffType::entertainer: - return DoEntertainerPathFinding(); - - default: - assert(false); + if (!IsMechanic()) return false; + + auto tileCoords = TileCoordsXYZ(CoordsXYZ{ GetDestination(), NextLoc.z }); + auto trackElement = MapGetFirstTileElementWithBaseHeightBetween( + { tileCoords, tileCoords.z + kPathHeightStep }); + if (trackElement == nullptr) + return false; + + auto ride = GetRide(trackElement->GetRideIndex()); + if (ride == nullptr) + return false; + + return ride->id == CurrentRide; } -} -void Staff::SetHireDate(int32_t hireDate) -{ - HireDate = hireDate; -} - -int32_t Staff::GetHireDate() const -{ - return HireDate; -} - -Drawing::Colour StaffGetColour(StaffType staffType) -{ - const auto& park = getGameState().park; - switch (staffType) + /** + * + * rct2: 0x006C086D + */ + void Staff::EntertainerUpdateNearbyPeeps() const { - case StaffType::handyman: - return park.staffHandymanColour; - case StaffType::mechanic: - return park.staffMechanicColour; - case StaffType::security: - return park.staffSecurityColour; - case StaffType::entertainer: - return Drawing::Colour::black; - default: - assert(false); - return Drawing::Colour::black; - } -} + // Iterate over tiles within a 3-tile radius (96 units) + constexpr auto kTileRadius = 3; + constexpr auto kLookupRadius = kCoordsXYStep * kTileRadius; -GameActions::Result StaffSetColour(StaffType staffType, OpenRCT2::Drawing::Colour value) -{ - auto& park = getGameState().park; - switch (staffType) - { - case StaffType::handyman: - park.staffHandymanColour = value; - break; - case StaffType::mechanic: - park.staffMechanicColour = value; - break; - case StaffType::security: - park.staffSecurityColour = value; - break; - default: - return GameActions::Result( - GameActions::Status::invalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_ACTION_INVALID_FOR_THAT_STAFF_TYPE); - } - return GameActions::Result(); -} - -/** rct2: 0x009929C8 */ -static constexpr CoordsXY kMowingWaypoints[] = { - { 28, 28 }, { 28, 4 }, { 20, 4 }, { 20, 28 }, { 12, 28 }, { 12, 4 }, { 4, 4 }, { 4, 28 }, -}; - -/** - * - * rct2: 0x006BF567 - */ -void Staff::UpdateMowing() -{ - if (!CheckForPath()) - return; - - while (true) - { - if (auto loc = UpdateAction(); loc.has_value()) + for (int32_t tileX = x - kLookupRadius; tileX <= x + kLookupRadius; tileX += kCoordsXYStep) { - int16_t checkZ = TileElementHeight(*loc); - MoveTo({ loc.value(), checkZ }); - return; - } - - Var37++; - - if (Var37 == 1) - { - SwitchToSpecialSprite(2); - } - - if (Var37 == std::size(kMowingWaypoints)) - { - StateReset(); - return; - } - - auto destination = kMowingWaypoints[Var37] + NextLoc; - SetDestination(destination); - - if (Var37 != 7) - continue; - - auto surfaceElement = MapGetSurfaceElementAt(NextLoc); - if (surfaceElement != nullptr && surfaceElement->CanGrassGrow()) - { - surfaceElement->SetGrassLength(GRASS_LENGTH_MOWED); - MapInvalidateTileZoom0({ NextLoc, surfaceElement->GetBaseZ(), surfaceElement->GetBaseZ() + 16 }); - } - StaffLawnsMown = AddClamp(StaffLawnsMown, 1u); - WindowInvalidateFlags |= PEEP_INVALIDATE_STAFF_STATS; - } -} - -/** - * - * rct2: 0x006BF7E6 - */ -void Staff::UpdateWatering() -{ - StaffMowingTimeout = 0; - if (SubState == 0) - { - if (!CheckForPath()) - return; - - const auto [pathingResult, _] = PerformNextAction(); - if (!(pathingResult & PATHING_DESTINATION_REACHED)) - return; - - Orientation = (Var37 & 3) << 3; - Action = PeepActionType::staffWatering; - AnimationFrameNum = 0; - AnimationImageIdOffset = 0; - UpdateCurrentAnimationType(); - - SubState = 1; - } - else if (SubState == 1) - { - if (!IsActionWalking()) - { - UpdateAction(); - Invalidate(); - return; - } - - auto actionLoc = CoordsXY{ NextLoc } + CoordsDirectionDelta[Var37]; - - TileElement* tile_element = MapGetFirstElementAt(actionLoc); - if (tile_element == nullptr) - return; - - do - { - if (tile_element->GetType() != TileElementType::SmallScenery) - continue; - - if (abs(NextLoc.z - tile_element->GetBaseZ()) > 4 * kCoordsZStep) - continue; - - const auto* sceneryEntry = tile_element->AsSmallScenery()->GetEntry(); - - if (sceneryEntry == nullptr || !sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_CAN_BE_WATERED)) - continue; - - tile_element->AsSmallScenery()->SetAge(0); - MapInvalidateTileZoom0({ actionLoc, tile_element->GetBaseZ(), tile_element->GetClearanceZ() }); - StaffGardensWatered = AddClamp(StaffGardensWatered, 1u); - WindowInvalidateFlags |= PEEP_INVALIDATE_STAFF_STATS; - } while (!(tile_element++)->IsLastForTile()); - - StateReset(); - } -} - -/** - * - * rct2: 0x006BF6C9 - */ -void Staff::UpdateEmptyingBin() -{ - StaffMowingTimeout = 0; - - if (SubState == 0) - { - if (!CheckForPath()) - return; - - const auto [pathingResult, _] = PerformNextAction(); - if (!(pathingResult & PATHING_DESTINATION_REACHED)) - return; - - Orientation = (Var37 & 3) << 3; - Action = PeepActionType::staffEmptyBin; - AnimationFrameNum = 0; - AnimationImageIdOffset = 0; - UpdateCurrentAnimationType(); - - SubState = 1; - } - else if (SubState == 1) - { - if (IsActionWalking()) - { - StateReset(); - return; - } - - UpdateAction(); - Invalidate(); - - if (AnimationFrameNum != 11) - return; - - TileElement* tile_element = MapGetFirstElementAt(NextLoc); - if (tile_element == nullptr) - return; - - for (;; tile_element++) - { - if (tile_element->GetType() == TileElementType::Path) + for (int32_t tileY = y - kLookupRadius; tileY <= y + kLookupRadius; tileY += kCoordsXYStep) { - if (NextLoc.z == tile_element->GetBaseZ()) - break; + for (auto* guest : EntityTileList({ tileX, tileY })) + { + if (guest->x == kLocationNull) + continue; + + int16_t z_dist = std::abs(z - guest->z); + if (z_dist > kTileRadius / 2) + continue; + + int16_t x_dist = std::abs(x - guest->x); + int16_t y_dist = std::abs(y - guest->y); + + if (x_dist > kLookupRadius) + continue; + + if (y_dist > kLookupRadius) + continue; + + if (guest->State == PeepState::walking) + { + guest->HappinessTarget = std::min(guest->HappinessTarget + 4, kPeepMaxHappiness); + } + else if (guest->State == PeepState::queuing) + { + guest->TimeInQueue = std::max(0, guest->TimeInQueue - 200); + guest->HappinessTarget = std::min(guest->HappinessTarget + 3, kPeepMaxHappiness); + } + } } - if ((tile_element)->IsLastForTile()) + } + } + + /** + * + * rct2: 0x006C05AE + */ + bool Staff::DoEntertainerPathFinding() + { + if (((ScenarioRand() & 0xFFFF) <= 0x4000) && IsActionInterruptableSafely()) + { + Action = (ScenarioRand() & 1) ? PeepActionType::wave2 : PeepActionType::joy; + AnimationFrameNum = 0; + AnimationImageIdOffset = 0; + + UpdateCurrentAnimationType(); + EntertainerUpdateNearbyPeeps(); + } + + return DoMiscPathFinding(); + } + + /** + * + * rct2: 0x006BF926 + */ + bool Staff::DoPathFinding() + { + switch (AssignedStaffType) + { + case StaffType::handyman: + return DoHandymanPathFinding(); + case StaffType::mechanic: + return DoMechanicPathFinding(); + case StaffType::security: + return DoMiscPathFinding(); + case StaffType::entertainer: + return DoEntertainerPathFinding(); + + default: + assert(false); + return false; + } + } + + void Staff::SetHireDate(int32_t hireDate) + { + HireDate = hireDate; + } + + int32_t Staff::GetHireDate() const + { + return HireDate; + } + + Drawing::Colour StaffGetColour(StaffType staffType) + { + const auto& park = getGameState().park; + switch (staffType) + { + case StaffType::handyman: + return park.staffHandymanColour; + case StaffType::mechanic: + return park.staffMechanicColour; + case StaffType::security: + return park.staffSecurityColour; + case StaffType::entertainer: + return Drawing::Colour::black; + default: + assert(false); + return Drawing::Colour::black; + } + } + + GameActions::Result StaffSetColour(StaffType staffType, OpenRCT2::Drawing::Colour value) + { + auto& park = getGameState().park; + switch (staffType) + { + case StaffType::handyman: + park.staffHandymanColour = value; + break; + case StaffType::mechanic: + park.staffMechanicColour = value; + break; + case StaffType::security: + park.staffSecurityColour = value; + break; + default: + return GameActions::Result( + GameActions::Status::invalidParameters, STR_ERR_INVALID_PARAMETER, + STR_ERR_ACTION_INVALID_FOR_THAT_STAFF_TYPE); + } + return GameActions::Result(); + } + + /** rct2: 0x009929C8 */ + static constexpr CoordsXY kMowingWaypoints[] = { + { 28, 28 }, { 28, 4 }, { 20, 4 }, { 20, 28 }, { 12, 28 }, { 12, 4 }, { 4, 4 }, { 4, 28 }, + }; + + /** + * + * rct2: 0x006BF567 + */ + void Staff::UpdateMowing() + { + if (!CheckForPath()) + return; + + while (true) + { + if (auto loc = UpdateAction(); loc.has_value()) + { + int16_t checkZ = TileElementHeight(*loc); + MoveTo({ loc.value(), checkZ }); + return; + } + + Var37++; + + if (Var37 == 1) + { + SwitchToSpecialSprite(2); + } + + if (Var37 == std::size(kMowingWaypoints)) { StateReset(); return; } - } - if (!tile_element->AsPath()->HasAddition()) - { - StateReset(); - return; - } + auto destination = kMowingWaypoints[Var37] + NextLoc; + SetDestination(destination); - auto* pathAddEntry = tile_element->AsPath()->GetAdditionEntry(); - if (!(pathAddEntry->flags & PATH_ADDITION_FLAG_IS_BIN) || tile_element->AsPath()->IsBroken() - || tile_element->AsPath()->AdditionIsGhost()) - { - StateReset(); - return; - } + if (Var37 != 7) + continue; - uint8_t additionStatus = tile_element->AsPath()->GetAdditionStatus() | ((3 << Var37) << Var37); - tile_element->AsPath()->SetAdditionStatus(additionStatus); - - MapInvalidateTileZoom0({ NextLoc, tile_element->GetBaseZ(), tile_element->GetClearanceZ() }); - StaffBinsEmptied = AddClamp(StaffBinsEmptied, 1u); - WindowInvalidateFlags |= PEEP_INVALIDATE_STAFF_STATS; - } -} - -/** - * - * rct2: 0x6BF641 - */ -void Staff::UpdateSweeping() -{ - StaffMowingTimeout = 0; - if (!CheckForPath()) - return; - - if (Action == PeepActionType::staffSweep && AnimationFrameNum == 8) - { - // Remove sick at this location - Litter::RemoveAt(GetLocation()); - StaffLitterSwept = AddClamp(StaffLitterSwept, 1u); - WindowInvalidateFlags |= PEEP_INVALIDATE_STAFF_STATS; - } - if (auto loc = UpdateAction(); loc.has_value()) - { - int16_t actionZ = GetZOnSlope(loc->x, loc->y); - MoveTo({ loc.value(), actionZ }); - return; - } - - Var37++; - if (Var37 != 2) - { - Action = PeepActionType::staffSweep; - AnimationFrameNum = 0; - AnimationImageIdOffset = 0; - UpdateCurrentAnimationType(); - return; - } - StateReset(); -} - -/** - * - * rct2: 0x006C16D7 - */ -void Staff::UpdateHeadingToInspect() -{ - auto ride = GetRide(CurrentRide); - if (ride == nullptr) - { - SetState(PeepState::falling); - return; - } - - if (ride->getStation(CurrentRideStation).Exit.IsNull()) - { - ride->flags.unset(RideFlag::dueInspection); - SetState(PeepState::falling); - return; - } - - if (ride->mechanicStatus != MechanicStatus::heading || !ride->flags.has(RideFlag::dueInspection)) - { - SetState(PeepState::falling); - return; - } - - if (SubState == 0) - { - MechanicTimeSinceCall = 0; - ResetPathfindGoal(); - SubState = 2; - } - - if (SubState <= 3) - { - MechanicTimeSinceCall++; - if (MechanicTimeSinceCall > 2500) - { - if (ride->flags.has(RideFlag::dueInspection) && ride->mechanicStatus == MechanicStatus::heading) + auto surfaceElement = MapGetSurfaceElementAt(NextLoc); + if (surfaceElement != nullptr && surfaceElement->CanGrassGrow()) { - ride->mechanicStatus = MechanicStatus::calling; + surfaceElement->SetGrassLength(GRASS_LENGTH_MOWED); + MapInvalidateTileZoom0({ NextLoc, surfaceElement->GetBaseZ(), surfaceElement->GetBaseZ() + 16 }); } + StaffLawnsMown = AddClamp(StaffLawnsMown, 1u); + WindowInvalidateFlags |= PEEP_INVALIDATE_STAFF_STATS; + } + } + + /** + * + * rct2: 0x006BF7E6 + */ + void Staff::UpdateWatering() + { + StaffMowingTimeout = 0; + if (SubState == 0) + { + if (!CheckForPath()) + return; + + const auto [pathingResult, _] = PerformNextAction(); + if (!(pathingResult & PATHING_DESTINATION_REACHED)) + return; + + Orientation = (Var37 & 3) << 3; + Action = PeepActionType::staffWatering; + AnimationFrameNum = 0; + AnimationImageIdOffset = 0; + UpdateCurrentAnimationType(); + + SubState = 1; + } + else if (SubState == 1) + { + if (!IsActionWalking()) + { + UpdateAction(); + Invalidate(); + return; + } + + auto actionLoc = CoordsXY{ NextLoc } + CoordsDirectionDelta[Var37]; + + TileElement* tile_element = MapGetFirstElementAt(actionLoc); + if (tile_element == nullptr) + return; + + do + { + if (tile_element->GetType() != TileElementType::SmallScenery) + continue; + + if (abs(NextLoc.z - tile_element->GetBaseZ()) > 4 * kCoordsZStep) + continue; + + const auto* sceneryEntry = tile_element->AsSmallScenery()->GetEntry(); + + if (sceneryEntry == nullptr || !sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_CAN_BE_WATERED)) + continue; + + tile_element->AsSmallScenery()->SetAge(0); + MapInvalidateTileZoom0({ actionLoc, tile_element->GetBaseZ(), tile_element->GetClearanceZ() }); + StaffGardensWatered = AddClamp(StaffGardensWatered, 1u); + WindowInvalidateFlags |= PEEP_INVALIDATE_STAFF_STATS; + } while (!(tile_element++)->IsLastForTile()); + + StateReset(); + } + } + + /** + * + * rct2: 0x006BF6C9 + */ + void Staff::UpdateEmptyingBin() + { + StaffMowingTimeout = 0; + + if (SubState == 0) + { + if (!CheckForPath()) + return; + + const auto [pathingResult, _] = PerformNextAction(); + if (!(pathingResult & PATHING_DESTINATION_REACHED)) + return; + + Orientation = (Var37 & 3) << 3; + Action = PeepActionType::staffEmptyBin; + AnimationFrameNum = 0; + AnimationImageIdOffset = 0; + UpdateCurrentAnimationType(); + + SubState = 1; + } + else if (SubState == 1) + { + if (IsActionWalking()) + { + StateReset(); + return; + } + + UpdateAction(); + Invalidate(); + + if (AnimationFrameNum != 11) + return; + + TileElement* tile_element = MapGetFirstElementAt(NextLoc); + if (tile_element == nullptr) + return; + + for (;; tile_element++) + { + if (tile_element->GetType() == TileElementType::Path) + { + if (NextLoc.z == tile_element->GetBaseZ()) + break; + } + if ((tile_element)->IsLastForTile()) + { + StateReset(); + return; + } + } + + if (!tile_element->AsPath()->HasAddition()) + { + StateReset(); + return; + } + + auto* pathAddEntry = tile_element->AsPath()->GetAdditionEntry(); + if (!(pathAddEntry->flags & PATH_ADDITION_FLAG_IS_BIN) || tile_element->AsPath()->IsBroken() + || tile_element->AsPath()->AdditionIsGhost()) + { + StateReset(); + return; + } + + uint8_t additionStatus = tile_element->AsPath()->GetAdditionStatus() | ((3 << Var37) << Var37); + tile_element->AsPath()->SetAdditionStatus(additionStatus); + + MapInvalidateTileZoom0({ NextLoc, tile_element->GetBaseZ(), tile_element->GetClearanceZ() }); + StaffBinsEmptied = AddClamp(StaffBinsEmptied, 1u); + WindowInvalidateFlags |= PEEP_INVALIDATE_STAFF_STATS; + } + } + + /** + * + * rct2: 0x6BF641 + */ + void Staff::UpdateSweeping() + { + StaffMowingTimeout = 0; + if (!CheckForPath()) + return; + + if (Action == PeepActionType::staffSweep && AnimationFrameNum == 8) + { + // Remove sick at this location + Litter::RemoveAt(GetLocation()); + StaffLitterSwept = AddClamp(StaffLitterSwept, 1u); + WindowInvalidateFlags |= PEEP_INVALIDATE_STAFF_STATS; + } + if (auto loc = UpdateAction(); loc.has_value()) + { + int16_t actionZ = GetZOnSlope(loc->x, loc->y); + MoveTo({ loc.value(), actionZ }); + return; + } + + Var37++; + if (Var37 != 2) + { + Action = PeepActionType::staffSweep; + AnimationFrameNum = 0; + AnimationImageIdOffset = 0; + UpdateCurrentAnimationType(); + return; + } + StateReset(); + } + + /** + * + * rct2: 0x006C16D7 + */ + void Staff::UpdateHeadingToInspect() + { + auto ride = GetRide(CurrentRide); + if (ride == nullptr) + { SetState(PeepState::falling); return; } - if (!CheckForPath()) - return; - - if (ShouldWaitForLevelCrossing() && !IsMechanicHeadingToFixRideBlockingPath()) - return; - - const auto [pathingResult, rideEntranceExitElement] = PerformNextAction(); - if (!(pathingResult & PATHING_RIDE_EXIT) && !(pathingResult & PATHING_RIDE_ENTRANCE)) + if (ride->getStation(CurrentRideStation).Exit.IsNull()) { + ride->flags.unset(RideFlag::dueInspection); + SetState(PeepState::falling); return; } - if (CurrentRide != rideEntranceExitElement->AsEntrance()->GetRideIndex()) - return; - - StationIndex exitIndex = rideEntranceExitElement->AsEntrance()->GetStationIndex(); - if (CurrentRideStation != exitIndex) - return; - - if (pathingResult & PATHING_RIDE_ENTRANCE) + if (ride->mechanicStatus != MechanicStatus::heading || !ride->flags.has(RideFlag::dueInspection)) { - if (!ride->getStation(exitIndex).Exit.IsNull()) - { - return; - } + SetState(PeepState::falling); + return; } - PeepDirection = rideEntranceExitElement->GetDirection(); - - auto newDestination = CoordsXY{ 16, 16 } + NextLoc + (DirectionOffsets[PeepDirection] * 53); - SetDestination(newDestination, 2); - Orientation = PeepDirection << 3; - - z = rideEntranceExitElement->BaseHeight * 4; - SubState = 4; - // Falls through into SubState 4 - } - - int16_t delta_y = abs(GetLocation().y - GetDestination().y); - if (auto loc = UpdateAction(); loc.has_value()) - { - auto newZ = ride->getStation(CurrentRideStation).GetBaseZ(); - if (delta_y < 20) + if (SubState == 0) { - newZ += ride->getRideTypeDescriptor().Heights.PlatformHeight; - } - - MoveTo({ loc.value(), newZ }); - return; - } - - SetState(PeepState::inspecting); - SubState = 0; -} - -/** - * - * rct2: 0x006C0CB8 - */ -void Staff::UpdateAnswering() -{ - auto ride = GetRide(CurrentRide); - if (ride == nullptr || ride->mechanicStatus != MechanicStatus::heading) - { - SetState(PeepState::falling); - return; - } - - if (SubState == 0) - { - Action = PeepActionType::staffAnswerCall; - AnimationFrameNum = 0; - AnimationImageIdOffset = 0; - - UpdateCurrentAnimationType(); - - SubState = 1; - PeepWindowStateUpdate(this); - return; - } - if (SubState == 1) - { - if (IsActionWalking()) - { - SubState = 2; - PeepWindowStateUpdate(this); MechanicTimeSinceCall = 0; ResetPathfindGoal(); - return; - } - UpdateAction(); - Invalidate(); - return; - } - if (SubState <= 3) - { - MechanicTimeSinceCall++; - if (MechanicTimeSinceCall > 2500) - { - ride->mechanicStatus = MechanicStatus::calling; - ride->windowInvalidateFlags.set(RideInvalidateFlag::maintenance); - SetState(PeepState::falling); - return; + SubState = 2; } - if (!CheckForPath()) - return; - - if (ShouldWaitForLevelCrossing() && !IsMechanicHeadingToFixRideBlockingPath()) - return; - - const auto [pathingResult, rideEntranceExitElement] = PerformNextAction(); - if (!(pathingResult & PATHING_RIDE_EXIT) && !(pathingResult & PATHING_RIDE_ENTRANCE)) + if (SubState <= 3) { - return; - } - - if (CurrentRide != rideEntranceExitElement->AsEntrance()->GetRideIndex()) - return; - - StationIndex exitIndex = rideEntranceExitElement->AsEntrance()->GetStationIndex(); - if (CurrentRideStation != exitIndex) - return; - - if (pathingResult & PATHING_RIDE_ENTRANCE) - { - if (!ride->getStation(exitIndex).Exit.IsNull()) + MechanicTimeSinceCall++; + if (MechanicTimeSinceCall > 2500) { - return; - } - } - - PeepDirection = rideEntranceExitElement->GetDirection(); - - int32_t destX = NextLoc.x + 16 + DirectionOffsets[PeepDirection].x * 53; - int32_t destY = NextLoc.y + 16 + DirectionOffsets[PeepDirection].y * 53; - - SetDestination({ destX, destY }, 2); - Orientation = PeepDirection << 3; - - z = rideEntranceExitElement->BaseHeight * 4; - SubState = 4; - // Falls through into SubState 4 - } - - int16_t delta_y = abs(y - GetDestination().y); - if (auto loc = UpdateAction(); loc.has_value()) - { - auto newZ = ride->getStation(CurrentRideStation).GetBaseZ(); - if (delta_y < 20) - { - newZ += ride->getRideTypeDescriptor().Heights.PlatformHeight; - } - - MoveTo({ loc.value(), newZ }); - return; - } - - SetState(PeepState::fixing); - SubState = 0; -} - -/** rct2: 0x00992A5C */ -static constexpr CoordsXY kWateringUseOffsets[] = { - { 3, 16 }, { 16, 29 }, { 29, 16 }, { 16, 3 }, { 3, 29 }, { 29, 29 }, { 29, 3 }, { 3, 3 }, -}; - -/** - * - * rct2: 0x006BF483 - */ -bool Staff::UpdatePatrollingFindWatering() -{ - if (!(StaffOrders & STAFF_ORDERS_WATER_FLOWERS)) - return false; - - uint8_t chosen_position = ScenarioRand() & 7; - for (int32_t i = 0; i < 8; ++i, ++chosen_position) - { - chosen_position &= 7; - - auto chosenLoc = CoordsXY{ NextLoc } + CoordsDirectionDelta[chosen_position]; - - TileElement* tile_element = MapGetFirstElementAt(chosenLoc); - - // This seems to happen in some SV4 files. - if (tile_element == nullptr) - { - continue; - } - - do - { - if (tile_element->GetType() != TileElementType::SmallScenery) - { - continue; - } - - auto z_diff = abs(NextLoc.z - tile_element->GetBaseZ()); - - if (z_diff >= 4 * kCoordsZStep) - { - continue; - } - - auto* sceneryEntry = tile_element->AsSmallScenery()->GetEntry(); - - if (sceneryEntry == nullptr || !sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_CAN_BE_WATERED)) - { - continue; - } - - if (tile_element->AsSmallScenery()->GetAge() < kSceneryWitherAgeThreshold2) - { - if (chosen_position >= 4) + if (ride->flags.has(RideFlag::dueInspection) && ride->mechanicStatus == MechanicStatus::heading) { - continue; + ride->mechanicStatus = MechanicStatus::calling; } - - if (tile_element->AsSmallScenery()->GetAge() < kSceneryWitherAgeThreshold1) - { - continue; - } - } - - SetState(PeepState::watering); - Var37 = chosen_position; - - SubState = 0; - auto destination = kWateringUseOffsets[chosen_position] + GetLocation().ToTileStart(); - SetDestination(destination, 3); - - return true; - } while (!(tile_element++)->IsLastForTile()); - } - return false; -} - -/** - * - * rct2: 0x006BF3A1 - */ -bool Staff::UpdatePatrollingFindBin() -{ - if (!(StaffOrders & STAFF_ORDERS_EMPTY_BINS)) - return false; - - if (GetNextIsSurface()) - return false; - - TileElement* tileElement = MapGetFirstElementAt(NextLoc); - if (tileElement == nullptr) - return false; - - for (;; tileElement++) - { - if (tileElement->GetType() == TileElementType::Path && (tileElement->GetBaseZ() == NextLoc.z)) - break; - - if (tileElement->IsLastForTile()) - return false; - } - - if (!tileElement->AsPath()->HasAddition()) - return false; - auto* pathAddEntry = tileElement->AsPath()->GetAdditionEntry(); - if (pathAddEntry == nullptr) - return false; - - if (!(pathAddEntry->flags & PATH_ADDITION_FLAG_IS_BIN)) - return false; - - if (tileElement->AsPath()->IsBroken()) - return false; - - if (tileElement->AsPath()->AdditionIsGhost()) - return false; - - uint8_t bin_positions = tileElement->AsPath()->GetEdges(); - uint8_t bin_quantity = tileElement->AsPath()->GetAdditionStatus(); - uint8_t chosen_position = 0; - - for (; chosen_position < 4; ++chosen_position) - { - if (!(bin_positions & 1) && !(bin_quantity & 3)) - break; - bin_positions >>= 1; - bin_quantity >>= 2; - } - - if (chosen_position == 4) - return false; - - Var37 = chosen_position; - SetState(PeepState::emptyingBin); - - SubState = 0; - auto destination = BinUseOffsets[chosen_position] + GetLocation().ToTileStart(); - SetDestination(destination, 3); - return true; -} - -/** - * - * rct2: 0x006BF322 - */ -bool Staff::UpdatePatrollingFindGrass() -{ - if (!(StaffOrders & STAFF_ORDERS_MOWING)) - return false; - - if (StaffMowingTimeout < 12) - return false; - - if (!(GetNextIsSurface())) - return false; - - auto surfaceElement = MapGetSurfaceElementAt(NextLoc); - if (surfaceElement != nullptr && surfaceElement->CanGrassGrow()) - { - if ((surfaceElement->GetGrassLength() & 0x7) >= GRASS_LENGTH_CLEAR_1) - { - SetState(PeepState::mowing); - Var37 = 0; - // Original code used .y for both x and y. Changed to .x to make more sense (both x and y are 28) - - auto destination = kMowingWaypoints[0] + NextLoc; - SetDestination(destination, 3); - return true; - } - } - return false; -} - -/** - * - * rct2: 0x006BF295 - */ -bool Staff::UpdatePatrollingFindSweeping() -{ - if (!(StaffOrders & STAFF_ORDERS_SWEEPING)) - return false; - auto quad = EntityTileList({ x, y }); - for (auto litter : quad) - { - uint16_t z_diff = abs(z - litter->z); - - if (z_diff >= 16) - continue; - - SetState(PeepState::sweeping); - - Var37 = 0; - SetDestination(litter->GetLocation(), 5); - return true; - } - - return false; -} - -bool Staff::SecurityGuardPathIsCrowded() const -{ - // Iterate over tiles within a 3-tile radius (96 units) - constexpr auto kTileRadius = 3; - constexpr auto kLookupRadius = kCoordsXYStep * kTileRadius; - constexpr auto kSecurityPathCrowdedThreshold = 20; - - int16_t guestCount = 0; - - for (int32_t tileX = x - kLookupRadius; tileX <= x + kLookupRadius; tileX += kCoordsXYStep) - { - for (int32_t tileY = y - kLookupRadius; tileY <= y + kLookupRadius; tileY += kCoordsXYStep) - { - for (auto* guest : EntityTileList({ tileX, tileY })) - { - if (guest->x == kLocationNull) - continue; - - int16_t zDist = std::abs(z - guest->z); - if (zDist > kTileRadius / 2) - continue; - - int16_t xDist = std::abs(x - guest->x); - if (xDist > kLookupRadius) - continue; - - int16_t yDist = std::abs(y - guest->y); - if (yDist > kLookupRadius) - continue; - - if (!guest->IsActionWalking()) - continue; - - guestCount++; - if (guestCount >= kSecurityPathCrowdedThreshold) - return true; - } - } - } - - return false; -} - -void Staff::Tick128UpdateStaff() -{ - if (AssignedStaffType != StaffType::security) - return; - - // Alternate between walking animations based on crowd size - auto newAnimationGroup = PeepAnimationGroup::normal; - if (State == PeepState::patrolling && SecurityGuardPathIsCrowded()) - newAnimationGroup = PeepAnimationGroup::alternate; - - if (AnimationGroup == newAnimationGroup) - return; - - AnimationGroup = newAnimationGroup; - AnimationImageIdOffset = 0; - WalkingAnimationFrameNum = 0; - if (Action < PeepActionType::idle) - Action = PeepActionType::walking; - - auto& objManager = GetContext()->GetObjectManager(); - auto* animObj = objManager.GetLoadedObject(AnimationObjectIndex); - - // NB: security staff have two animations groups: one regular, and one slow-walking - PeepFlags &= ~PEEP_FLAGS_SLOW_WALK; - if (animObj->IsSlowWalking(newAnimationGroup)) - { - PeepFlags |= PEEP_FLAGS_SLOW_WALK; - } - - AnimationType = PeepAnimationType::invalid; - UpdateCurrentAnimationType(); -} - -bool Staff::IsMechanic() const -{ - return AssignedStaffType == StaffType::mechanic; -} - -bool Staff::isEntertainer() const -{ - return AssignedStaffType == StaffType::entertainer; -} - -void Staff::Update() -{ - if (PeepFlags & PEEP_FLAGS_POSITION_FROZEN) - { - if (!(PeepFlags & PEEP_FLAGS_ANIMATION_FROZEN)) - { - // This is circumventing other logic, so only update every few ticks - if ((getGameState().currentTicks & 3) == 0) - { - if (IsActionWalking()) - UpdateWalkingAnimation(); - else - UpdateActionAnimation(); - Invalidate(); - } - } - return; - } - else if (PeepFlags & PEEP_FLAGS_ANIMATION_FROZEN) - { - // Animation is frozen while position is not. This allows a peep to walk - // around without its sprite being updated, which looks very glitchy. - // We'll just remove the flag and continue as normal, in this case. - PeepFlags &= ~PEEP_FLAGS_ANIMATION_FROZEN; - } - - // Walking speed logic - const auto stepsToTake = GetStepsToTake(); - const auto carryCheck = StepProgress + stepsToTake; - StepProgress = carryCheck; - - if (carryCheck <= 255) - { - // No-op: Keep replay working for now, can be eliminate with a replay update. - } - else - { - // Loc68FD2F - switch (State) - { - case PeepState::falling: - UpdateFalling(); - break; - case PeepState::one: - Update1(); - break; - case PeepState::onRide: - // No action - break; - case PeepState::picked: - UpdatePicked(); - break; - case PeepState::patrolling: - UpdatePatrolling(); - break; - case PeepState::mowing: - UpdateMowing(); - break; - case PeepState::sweeping: - UpdateSweeping(); - break; - case PeepState::answering: - UpdateAnswering(); - break; - case PeepState::fixing: - UpdateFixing(stepsToTake); - break; - case PeepState::inspecting: - UpdateFixing(stepsToTake); - break; - case PeepState::emptyingBin: - UpdateEmptyingBin(); - break; - case PeepState::watering: - UpdateWatering(); - break; - case PeepState::headingToInspection: - UpdateHeadingToInspect(); - break; - default: - // TODO reset to default state - assert(false); - break; - } - } -} - -/** - * - * rct2: 0x006BF1FD - */ -void Staff::UpdatePatrolling() -{ - if (!CheckForPath()) - return; - - if (ShouldWaitForLevelCrossing() && !IsMechanicHeadingToFixRideBlockingPath()) - { - UpdateWaitingAtCrossing(); - return; - } - - const auto [pathingResult, _] = PerformNextAction(); - if (!(pathingResult & PATHING_DESTINATION_REACHED)) - return; - - if (GetNextIsSurface()) - { - auto surfaceElement = MapGetSurfaceElementAt(NextLoc); - - if (surfaceElement != nullptr) - { - int32_t water_height = surfaceElement->GetWaterHeight(); - if (water_height > 0) - { - MoveTo({ x, y, water_height }); SetState(PeepState::falling); return; } + + if (!CheckForPath()) + return; + + if (ShouldWaitForLevelCrossing() && !IsMechanicHeadingToFixRideBlockingPath()) + return; + + const auto [pathingResult, rideEntranceExitElement] = PerformNextAction(); + if (!(pathingResult & PATHING_RIDE_EXIT) && !(pathingResult & PATHING_RIDE_ENTRANCE)) + { + return; + } + + if (CurrentRide != rideEntranceExitElement->AsEntrance()->GetRideIndex()) + return; + + StationIndex exitIndex = rideEntranceExitElement->AsEntrance()->GetStationIndex(); + if (CurrentRideStation != exitIndex) + return; + + if (pathingResult & PATHING_RIDE_ENTRANCE) + { + if (!ride->getStation(exitIndex).Exit.IsNull()) + { + return; + } + } + + PeepDirection = rideEntranceExitElement->GetDirection(); + + auto newDestination = CoordsXY{ 16, 16 } + NextLoc + (DirectionOffsets[PeepDirection] * 53); + SetDestination(newDestination, 2); + Orientation = PeepDirection << 3; + + z = rideEntranceExitElement->BaseHeight * 4; + SubState = 4; + // Falls through into SubState 4 + } + + int16_t delta_y = abs(GetLocation().y - GetDestination().y); + if (auto loc = UpdateAction(); loc.has_value()) + { + auto newZ = ride->getStation(CurrentRideStation).GetBaseZ(); + if (delta_y < 20) + { + newZ += ride->getRideTypeDescriptor().Heights.PlatformHeight; + } + + MoveTo({ loc.value(), newZ }); + return; + } + + SetState(PeepState::inspecting); + SubState = 0; + } + + /** + * + * rct2: 0x006C0CB8 + */ + void Staff::UpdateAnswering() + { + auto ride = GetRide(CurrentRide); + if (ride == nullptr || ride->mechanicStatus != MechanicStatus::heading) + { + SetState(PeepState::falling); + return; + } + + if (SubState == 0) + { + Action = PeepActionType::staffAnswerCall; + AnimationFrameNum = 0; + AnimationImageIdOffset = 0; + + UpdateCurrentAnimationType(); + + SubState = 1; + PeepWindowStateUpdate(this); + return; + } + if (SubState == 1) + { + if (IsActionWalking()) + { + SubState = 2; + PeepWindowStateUpdate(this); + MechanicTimeSinceCall = 0; + ResetPathfindGoal(); + return; + } + UpdateAction(); + Invalidate(); + return; + } + if (SubState <= 3) + { + MechanicTimeSinceCall++; + if (MechanicTimeSinceCall > 2500) + { + ride->mechanicStatus = MechanicStatus::calling; + ride->windowInvalidateFlags.set(RideInvalidateFlag::maintenance); + SetState(PeepState::falling); + return; + } + + if (!CheckForPath()) + return; + + if (ShouldWaitForLevelCrossing() && !IsMechanicHeadingToFixRideBlockingPath()) + return; + + const auto [pathingResult, rideEntranceExitElement] = PerformNextAction(); + if (!(pathingResult & PATHING_RIDE_EXIT) && !(pathingResult & PATHING_RIDE_ENTRANCE)) + { + return; + } + + if (CurrentRide != rideEntranceExitElement->AsEntrance()->GetRideIndex()) + return; + + StationIndex exitIndex = rideEntranceExitElement->AsEntrance()->GetStationIndex(); + if (CurrentRideStation != exitIndex) + return; + + if (pathingResult & PATHING_RIDE_ENTRANCE) + { + if (!ride->getStation(exitIndex).Exit.IsNull()) + { + return; + } + } + + PeepDirection = rideEntranceExitElement->GetDirection(); + + int32_t destX = NextLoc.x + 16 + DirectionOffsets[PeepDirection].x * 53; + int32_t destY = NextLoc.y + 16 + DirectionOffsets[PeepDirection].y * 53; + + SetDestination({ destX, destY }, 2); + Orientation = PeepDirection << 3; + + z = rideEntranceExitElement->BaseHeight * 4; + SubState = 4; + // Falls through into SubState 4 + } + + int16_t delta_y = abs(y - GetDestination().y); + if (auto loc = UpdateAction(); loc.has_value()) + { + auto newZ = ride->getStation(CurrentRideStation).GetBaseZ(); + if (delta_y < 20) + { + newZ += ride->getRideTypeDescriptor().Heights.PlatformHeight; + } + + MoveTo({ loc.value(), newZ }); + return; + } + + SetState(PeepState::fixing); + SubState = 0; + } + + /** rct2: 0x00992A5C */ + static constexpr CoordsXY kWateringUseOffsets[] = { + { 3, 16 }, { 16, 29 }, { 29, 16 }, { 16, 3 }, { 3, 29 }, { 29, 29 }, { 29, 3 }, { 3, 3 }, + }; + + /** + * + * rct2: 0x006BF483 + */ + bool Staff::UpdatePatrollingFindWatering() + { + if (!(StaffOrders & STAFF_ORDERS_WATER_FLOWERS)) + return false; + + uint8_t chosen_position = ScenarioRand() & 7; + for (int32_t i = 0; i < 8; ++i, ++chosen_position) + { + chosen_position &= 7; + + auto chosenLoc = CoordsXY{ NextLoc } + CoordsDirectionDelta[chosen_position]; + + TileElement* tile_element = MapGetFirstElementAt(chosenLoc); + + // This seems to happen in some SV4 files. + if (tile_element == nullptr) + { + continue; + } + + do + { + if (tile_element->GetType() != TileElementType::SmallScenery) + { + continue; + } + + auto z_diff = abs(NextLoc.z - tile_element->GetBaseZ()); + + if (z_diff >= 4 * kCoordsZStep) + { + continue; + } + + auto* sceneryEntry = tile_element->AsSmallScenery()->GetEntry(); + + if (sceneryEntry == nullptr || !sceneryEntry->HasFlag(SMALL_SCENERY_FLAG_CAN_BE_WATERED)) + { + continue; + } + + if (tile_element->AsSmallScenery()->GetAge() < kSceneryWitherAgeThreshold2) + { + if (chosen_position >= 4) + { + continue; + } + + if (tile_element->AsSmallScenery()->GetAge() < kSceneryWitherAgeThreshold1) + { + continue; + } + } + + SetState(PeepState::watering); + Var37 = chosen_position; + + SubState = 0; + auto destination = kWateringUseOffsets[chosen_position] + GetLocation().ToTileStart(); + SetDestination(destination, 3); + + return true; + } while (!(tile_element++)->IsLastForTile()); + } + return false; + } + + /** + * + * rct2: 0x006BF3A1 + */ + bool Staff::UpdatePatrollingFindBin() + { + if (!(StaffOrders & STAFF_ORDERS_EMPTY_BINS)) + return false; + + if (GetNextIsSurface()) + return false; + + TileElement* tileElement = MapGetFirstElementAt(NextLoc); + if (tileElement == nullptr) + return false; + + for (;; tileElement++) + { + if (tileElement->GetType() == TileElementType::Path && (tileElement->GetBaseZ() == NextLoc.z)) + break; + + if (tileElement->IsLastForTile()) + return false; + } + + if (!tileElement->AsPath()->HasAddition()) + return false; + auto* pathAddEntry = tileElement->AsPath()->GetAdditionEntry(); + if (pathAddEntry == nullptr) + return false; + + if (!(pathAddEntry->flags & PATH_ADDITION_FLAG_IS_BIN)) + return false; + + if (tileElement->AsPath()->IsBroken()) + return false; + + if (tileElement->AsPath()->AdditionIsGhost()) + return false; + + uint8_t bin_positions = tileElement->AsPath()->GetEdges(); + uint8_t bin_quantity = tileElement->AsPath()->GetAdditionStatus(); + uint8_t chosen_position = 0; + + for (; chosen_position < 4; ++chosen_position) + { + if (!(bin_positions & 1) && !(bin_quantity & 3)) + break; + bin_positions >>= 1; + bin_quantity >>= 2; + } + + if (chosen_position == 4) + return false; + + Var37 = chosen_position; + SetState(PeepState::emptyingBin); + + SubState = 0; + auto destination = BinUseOffsets[chosen_position] + GetLocation().ToTileStart(); + SetDestination(destination, 3); + return true; + } + + /** + * + * rct2: 0x006BF322 + */ + bool Staff::UpdatePatrollingFindGrass() + { + if (!(StaffOrders & STAFF_ORDERS_MOWING)) + return false; + + if (StaffMowingTimeout < 12) + return false; + + if (!(GetNextIsSurface())) + return false; + + auto surfaceElement = MapGetSurfaceElementAt(NextLoc); + if (surfaceElement != nullptr && surfaceElement->CanGrassGrow()) + { + if ((surfaceElement->GetGrassLength() & 0x7) >= GRASS_LENGTH_CLEAR_1) + { + SetState(PeepState::mowing); + Var37 = 0; + // Original code used .y for both x and y. Changed to .x to make more sense (both x and y are 28) + + auto destination = kMowingWaypoints[0] + NextLoc; + SetDestination(destination, 3); + return true; + } + } + return false; + } + + /** + * + * rct2: 0x006BF295 + */ + bool Staff::UpdatePatrollingFindSweeping() + { + if (!(StaffOrders & STAFF_ORDERS_SWEEPING)) + return false; + auto quad = EntityTileList({ x, y }); + for (auto litter : quad) + { + uint16_t z_diff = abs(z - litter->z); + + if (z_diff >= 16) + continue; + + SetState(PeepState::sweeping); + + Var37 = 0; + SetDestination(litter->GetLocation(), 5); + return true; + } + + return false; + } + + bool Staff::SecurityGuardPathIsCrowded() const + { + // Iterate over tiles within a 3-tile radius (96 units) + constexpr auto kTileRadius = 3; + constexpr auto kLookupRadius = kCoordsXYStep * kTileRadius; + constexpr auto kSecurityPathCrowdedThreshold = 20; + + int16_t guestCount = 0; + + for (int32_t tileX = x - kLookupRadius; tileX <= x + kLookupRadius; tileX += kCoordsXYStep) + { + for (int32_t tileY = y - kLookupRadius; tileY <= y + kLookupRadius; tileY += kCoordsXYStep) + { + for (auto* guest : EntityTileList({ tileX, tileY })) + { + if (guest->x == kLocationNull) + continue; + + int16_t zDist = std::abs(z - guest->z); + if (zDist > kTileRadius / 2) + continue; + + int16_t xDist = std::abs(x - guest->x); + if (xDist > kLookupRadius) + continue; + + int16_t yDist = std::abs(y - guest->y); + if (yDist > kLookupRadius) + continue; + + if (!guest->IsActionWalking()) + continue; + + guestCount++; + if (guestCount >= kSecurityPathCrowdedThreshold) + return true; + } + } + } + + return false; + } + + void Staff::Tick128UpdateStaff() + { + if (AssignedStaffType != StaffType::security) + return; + + // Alternate between walking animations based on crowd size + auto newAnimationGroup = PeepAnimationGroup::normal; + if (State == PeepState::patrolling && SecurityGuardPathIsCrowded()) + newAnimationGroup = PeepAnimationGroup::alternate; + + if (AnimationGroup == newAnimationGroup) + return; + + AnimationGroup = newAnimationGroup; + AnimationImageIdOffset = 0; + WalkingAnimationFrameNum = 0; + if (Action < PeepActionType::idle) + Action = PeepActionType::walking; + + auto& objManager = GetContext()->GetObjectManager(); + auto* animObj = objManager.GetLoadedObject(AnimationObjectIndex); + + // NB: security staff have two animations groups: one regular, and one slow-walking + PeepFlags &= ~PEEP_FLAGS_SLOW_WALK; + if (animObj->IsSlowWalking(newAnimationGroup)) + { + PeepFlags |= PEEP_FLAGS_SLOW_WALK; + } + + AnimationType = PeepAnimationType::invalid; + UpdateCurrentAnimationType(); + } + + bool Staff::IsMechanic() const + { + return AssignedStaffType == StaffType::mechanic; + } + + bool Staff::isEntertainer() const + { + return AssignedStaffType == StaffType::entertainer; + } + + void Staff::Update() + { + if (PeepFlags & PEEP_FLAGS_POSITION_FROZEN) + { + if (!(PeepFlags & PEEP_FLAGS_ANIMATION_FROZEN)) + { + // This is circumventing other logic, so only update every few ticks + if ((getGameState().currentTicks & 3) == 0) + { + if (IsActionWalking()) + UpdateWalkingAnimation(); + else + UpdateActionAnimation(); + Invalidate(); + } + } + return; + } + else if (PeepFlags & PEEP_FLAGS_ANIMATION_FROZEN) + { + // Animation is frozen while position is not. This allows a peep to walk + // around without its sprite being updated, which looks very glitchy. + // We'll just remove the flag and continue as normal, in this case. + PeepFlags &= ~PEEP_FLAGS_ANIMATION_FROZEN; + } + + // Walking speed logic + const auto stepsToTake = GetStepsToTake(); + const auto carryCheck = StepProgress + stepsToTake; + StepProgress = carryCheck; + + if (carryCheck <= 255) + { + // No-op: Keep replay working for now, can be eliminate with a replay update. + } + else + { + // Loc68FD2F + switch (State) + { + case PeepState::falling: + UpdateFalling(); + break; + case PeepState::one: + Update1(); + break; + case PeepState::onRide: + // No action + break; + case PeepState::picked: + UpdatePicked(); + break; + case PeepState::patrolling: + UpdatePatrolling(); + break; + case PeepState::mowing: + UpdateMowing(); + break; + case PeepState::sweeping: + UpdateSweeping(); + break; + case PeepState::answering: + UpdateAnswering(); + break; + case PeepState::fixing: + UpdateFixing(stepsToTake); + break; + case PeepState::inspecting: + UpdateFixing(stepsToTake); + break; + case PeepState::emptyingBin: + UpdateEmptyingBin(); + break; + case PeepState::watering: + UpdateWatering(); + break; + case PeepState::headingToInspection: + UpdateHeadingToInspect(); + break; + default: + // TODO reset to default state + assert(false); + break; + } } } - if (AssignedStaffType != StaffType::handyman) - return; - - if (UpdatePatrollingFindSweeping()) - return; - - if (UpdatePatrollingFindGrass()) - return; - - if (UpdatePatrollingFindBin()) - return; - - UpdatePatrollingFindWatering(); -} - -enum -{ - PEEP_FIXING_ENTER_STATION = 0, - PEEP_FIXING_MOVE_TO_BROKEN_DOWN_VEHICLE = 1, - PEEP_FIXING_FIX_VEHICLE_CLOSED_RESTRAINTS = 2, - PEEP_FIXING_FIX_VEHICLE_CLOSED_DOORS = 3, - PEEP_FIXING_FIX_VEHICLE_OPEN_RESTRAINTS = 4, - PEEP_FIXING_FIX_VEHICLE_OPEN_DOORS = 5, - PEEP_FIXING_FIX_VEHICLE_MALFUNCTION = 6, - PEEP_FIXING_MOVE_TO_STATION_END = 7, - PEEP_FIXING_FIX_STATION_END = 8, - PEEP_FIXING_MOVE_TO_STATION_START = 9, - PEEP_FIXING_FIX_STATION_START = 10, - PEEP_FIXING_FIX_STATION_BRAKES = 11, - PEEP_FIXING_MOVE_TO_STATION_EXIT = 12, - PEEP_FIXING_FINISH_FIX_OR_INSPECT = 13, - PEEP_FIXING_LEAVE_BY_ENTRANCE_EXIT = 14, -}; - -/** - * FixingSubstatesForBreakdown[] defines the applicable peep sub_states for - * mechanics fixing a ride. The array is indexed by breakdownReason: - * - indexes 0-7 are the 8 breakdown reasons (see BREAKDOWN_* in Ride.h) - * when fixing a broken down ride; - * - index 8 is for inspecting a ride. - */ -// clang-format off -static constexpr uint32_t FixingSubstatesForBreakdown[9] = { - ( // Breakdown::safetyCutOut - (1 << PEEP_FIXING_MOVE_TO_STATION_END) | - (1 << PEEP_FIXING_FIX_STATION_END) | - (1 << PEEP_FIXING_MOVE_TO_STATION_START) | - (1 << PEEP_FIXING_FIX_STATION_START) | - (1 << PEEP_FIXING_MOVE_TO_STATION_EXIT) | - (1 << PEEP_FIXING_FINISH_FIX_OR_INSPECT) | - (1 << PEEP_FIXING_LEAVE_BY_ENTRANCE_EXIT) - ), - ( // Breakdown::restraintsStuckClosed - (1 << PEEP_FIXING_MOVE_TO_BROKEN_DOWN_VEHICLE) | - (1 << PEEP_FIXING_FIX_VEHICLE_CLOSED_RESTRAINTS) | - (1 << PEEP_FIXING_MOVE_TO_STATION_EXIT) | - (1 << PEEP_FIXING_FINISH_FIX_OR_INSPECT) | - (1 << PEEP_FIXING_LEAVE_BY_ENTRANCE_EXIT) - ), - ( // Breakdown::restraintsStuckOpen - (1 << PEEP_FIXING_MOVE_TO_BROKEN_DOWN_VEHICLE) | - (1 << PEEP_FIXING_FIX_VEHICLE_OPEN_RESTRAINTS) | - (1 << PEEP_FIXING_MOVE_TO_STATION_EXIT) | - (1 << PEEP_FIXING_FINISH_FIX_OR_INSPECT) | - (1 << PEEP_FIXING_LEAVE_BY_ENTRANCE_EXIT) - ), - ( // Breakdown::doorsStuckClosed - (1 << PEEP_FIXING_MOVE_TO_BROKEN_DOWN_VEHICLE) | - (1 << PEEP_FIXING_FIX_VEHICLE_CLOSED_DOORS) | - (1 << PEEP_FIXING_MOVE_TO_STATION_EXIT) | - (1 << PEEP_FIXING_FINISH_FIX_OR_INSPECT) | - (1 << PEEP_FIXING_LEAVE_BY_ENTRANCE_EXIT) - ), - ( // Breakdown::doorsStuckOpen - (1 << PEEP_FIXING_MOVE_TO_BROKEN_DOWN_VEHICLE) | - (1 << PEEP_FIXING_FIX_VEHICLE_OPEN_DOORS) | - (1 << PEEP_FIXING_MOVE_TO_STATION_EXIT) | - (1 << PEEP_FIXING_FINISH_FIX_OR_INSPECT) | - (1 << PEEP_FIXING_LEAVE_BY_ENTRANCE_EXIT) - ), - ( // Breakdown::vehicleMalfunction - (1 << PEEP_FIXING_MOVE_TO_BROKEN_DOWN_VEHICLE) | - (1 << PEEP_FIXING_FIX_VEHICLE_MALFUNCTION) | - (1 << PEEP_FIXING_MOVE_TO_STATION_EXIT) | - (1 << PEEP_FIXING_FINISH_FIX_OR_INSPECT) | - (1 << PEEP_FIXING_LEAVE_BY_ENTRANCE_EXIT) - ), - ( // Breakdown::brakesFailure - (1 << PEEP_FIXING_MOVE_TO_STATION_START) | - (1 << PEEP_FIXING_FIX_STATION_BRAKES) | - (1 << PEEP_FIXING_MOVE_TO_STATION_EXIT) | - (1 << PEEP_FIXING_FINISH_FIX_OR_INSPECT) | - (1 << PEEP_FIXING_LEAVE_BY_ENTRANCE_EXIT) - ), - ( // Breakdown::controlFailure - (1 << PEEP_FIXING_MOVE_TO_STATION_END) | - (1 << PEEP_FIXING_FIX_STATION_END) | - (1 << PEEP_FIXING_MOVE_TO_STATION_START) | - (1 << PEEP_FIXING_FIX_STATION_START) | - (1 << PEEP_FIXING_MOVE_TO_STATION_EXIT) | - (1 << PEEP_FIXING_FINISH_FIX_OR_INSPECT) | - (1 << PEEP_FIXING_LEAVE_BY_ENTRANCE_EXIT) - ), - ( // INSPECTION - (1 << PEEP_FIXING_MOVE_TO_STATION_END) | - (1 << PEEP_FIXING_FIX_STATION_END) | - (1 << PEEP_FIXING_MOVE_TO_STATION_START) | - (1 << PEEP_FIXING_FIX_STATION_START) | - (1 << PEEP_FIXING_MOVE_TO_STATION_EXIT) | - (1 << PEEP_FIXING_FINISH_FIX_OR_INSPECT) | - (1 << PEEP_FIXING_LEAVE_BY_ENTRANCE_EXIT) - ), -}; -// clang-format on - -/** - * - * rct2: 0x006C0E8B - * Also used by inspecting. - */ -void Staff::UpdateFixing(int32_t steps) -{ - auto ride = GetRide(CurrentRide); - if (ride == nullptr) + /** + * + * rct2: 0x006BF1FD + */ + void Staff::UpdatePatrolling() { - SetState(PeepState::falling); - return; - } + if (!CheckForPath()) + return; - bool progressToNextSubstate = true; - bool firstRun = true; - - if ((State == PeepState::inspecting) && (ride->flags.hasAny(RideFlag::breakdownPending, RideFlag::brokenDown))) - { - // Ride has broken down since Mechanic was called to inspect it. - // Mechanic identifies the breakdown and switches to fixing it. - State = PeepState::fixing; - } - - while (progressToNextSubstate) - { - switch (SubState) + if (ShouldWaitForLevelCrossing() && !IsMechanicHeadingToFixRideBlockingPath()) { - case PEEP_FIXING_ENTER_STATION: - NextFlags &= ~PEEP_NEXT_FLAG_IS_SLOPED; - progressToNextSubstate = UpdateFixingEnterStation(*ride); - break; - - case PEEP_FIXING_MOVE_TO_BROKEN_DOWN_VEHICLE: - progressToNextSubstate = UpdateFixingMoveToBrokenDownVehicle(firstRun, *ride); - break; - - case PEEP_FIXING_FIX_VEHICLE_CLOSED_RESTRAINTS: - case PEEP_FIXING_FIX_VEHICLE_CLOSED_DOORS: - case PEEP_FIXING_FIX_VEHICLE_OPEN_RESTRAINTS: - case PEEP_FIXING_FIX_VEHICLE_OPEN_DOORS: - progressToNextSubstate = UpdateFixingFixVehicle(firstRun, *ride); - break; - - case PEEP_FIXING_FIX_VEHICLE_MALFUNCTION: - progressToNextSubstate = UpdateFixingFixVehicleMalfunction(firstRun, *ride); - break; - - case PEEP_FIXING_MOVE_TO_STATION_END: - progressToNextSubstate = UpdateFixingMoveToStationEnd(firstRun, *ride); - break; - - case PEEP_FIXING_FIX_STATION_END: - progressToNextSubstate = UpdateFixingFixStationEnd(firstRun); - break; - - case PEEP_FIXING_MOVE_TO_STATION_START: - progressToNextSubstate = UpdateFixingMoveToStationStart(firstRun, *ride); - break; - - case PEEP_FIXING_FIX_STATION_START: - progressToNextSubstate = UpdateFixingFixStationStart(firstRun, *ride); - break; - - case PEEP_FIXING_FIX_STATION_BRAKES: - progressToNextSubstate = UpdateFixingFixStationBrakes(firstRun, *ride); - break; - - case PEEP_FIXING_MOVE_TO_STATION_EXIT: - progressToNextSubstate = UpdateFixingMoveToStationExit(firstRun, *ride); - break; - - case PEEP_FIXING_FINISH_FIX_OR_INSPECT: - progressToNextSubstate = UpdateFixingFinishFixOrInspect(firstRun, steps, *ride); - break; - - case PEEP_FIXING_LEAVE_BY_ENTRANCE_EXIT: - progressToNextSubstate = UpdateFixingLeaveByEntranceExit(firstRun, *ride); - break; - - default: - LOG_ERROR("Invalid substate"); - progressToNextSubstate = false; + UpdateWaitingAtCrossing(); + return; } - firstRun = false; + const auto [pathingResult, _] = PerformNextAction(); + if (!(pathingResult & PATHING_DESTINATION_REACHED)) + return; - if (!progressToNextSubstate) + if (GetNextIsSurface()) { - break; + auto surfaceElement = MapGetSurfaceElementAt(NextLoc); + + if (surfaceElement != nullptr) + { + int32_t water_height = surfaceElement->GetWaterHeight(); + if (water_height > 0) + { + MoveTo({ x, y, water_height }); + SetState(PeepState::falling); + return; + } + } } - int32_t subState = SubState; - uint32_t sub_state_sequence_mask = FixingSubstatesForBreakdown[8]; + if (AssignedStaffType != StaffType::handyman) + return; - if (State != PeepState::inspecting) - { - sub_state_sequence_mask = FixingSubstatesForBreakdown[EnumValue(ride->breakdownReasonPending)]; - } + if (UpdatePatrollingFindSweeping()) + return; - do - { - subState++; - } while ((sub_state_sequence_mask & (1 << subState)) == 0); + if (UpdatePatrollingFindGrass()) + return; - SubState = subState & 0xFF; + if (UpdatePatrollingFindBin()) + return; + + UpdatePatrollingFindWatering(); } -} -/** - * rct2: 0x006C0EEC - * fixing SubState: enter_station - applies to fixing all break down reasons and ride inspections. - */ -bool Staff::UpdateFixingEnterStation(Ride& ride) const -{ - ride.mechanicStatus = MechanicStatus::fixing; - ride.windowInvalidateFlags.set(RideInvalidateFlag::maintenance); - - return true; -} - -/** - * rct2: 0x006C0F09 - * fixing SubState: move_to_broken_down_vehicle - applies to fixing all vehicle specific breakdown reasons - * - see FixingSubstatesForBreakdown[] - */ -bool Staff::UpdateFixingMoveToBrokenDownVehicle(bool firstRun, const Ride& ride) -{ - if (!firstRun) + enum { + PEEP_FIXING_ENTER_STATION = 0, + PEEP_FIXING_MOVE_TO_BROKEN_DOWN_VEHICLE = 1, + PEEP_FIXING_FIX_VEHICLE_CLOSED_RESTRAINTS = 2, + PEEP_FIXING_FIX_VEHICLE_CLOSED_DOORS = 3, + PEEP_FIXING_FIX_VEHICLE_OPEN_RESTRAINTS = 4, + PEEP_FIXING_FIX_VEHICLE_OPEN_DOORS = 5, + PEEP_FIXING_FIX_VEHICLE_MALFUNCTION = 6, + PEEP_FIXING_MOVE_TO_STATION_END = 7, + PEEP_FIXING_FIX_STATION_END = 8, + PEEP_FIXING_MOVE_TO_STATION_START = 9, + PEEP_FIXING_FIX_STATION_START = 10, + PEEP_FIXING_FIX_STATION_BRAKES = 11, + PEEP_FIXING_MOVE_TO_STATION_EXIT = 12, + PEEP_FIXING_FINISH_FIX_OR_INSPECT = 13, + PEEP_FIXING_LEAVE_BY_ENTRANCE_EXIT = 14, + }; + + /** + * FixingSubstatesForBreakdown[] defines the applicable peep sub_states for + * mechanics fixing a ride. The array is indexed by breakdownReason: + * - indexes 0-7 are the 8 breakdown reasons (see BREAKDOWN_* in Ride.h) + * when fixing a broken down ride; + * - index 8 is for inspecting a ride. + */ + // clang-format off + static constexpr uint32_t FixingSubstatesForBreakdown[9] = { + ( // Breakdown::safetyCutOut + (1 << PEEP_FIXING_MOVE_TO_STATION_END) | + (1 << PEEP_FIXING_FIX_STATION_END) | + (1 << PEEP_FIXING_MOVE_TO_STATION_START) | + (1 << PEEP_FIXING_FIX_STATION_START) | + (1 << PEEP_FIXING_MOVE_TO_STATION_EXIT) | + (1 << PEEP_FIXING_FINISH_FIX_OR_INSPECT) | + (1 << PEEP_FIXING_LEAVE_BY_ENTRANCE_EXIT) + ), + ( // Breakdown::restraintsStuckClosed + (1 << PEEP_FIXING_MOVE_TO_BROKEN_DOWN_VEHICLE) | + (1 << PEEP_FIXING_FIX_VEHICLE_CLOSED_RESTRAINTS) | + (1 << PEEP_FIXING_MOVE_TO_STATION_EXIT) | + (1 << PEEP_FIXING_FINISH_FIX_OR_INSPECT) | + (1 << PEEP_FIXING_LEAVE_BY_ENTRANCE_EXIT) + ), + ( // Breakdown::restraintsStuckOpen + (1 << PEEP_FIXING_MOVE_TO_BROKEN_DOWN_VEHICLE) | + (1 << PEEP_FIXING_FIX_VEHICLE_OPEN_RESTRAINTS) | + (1 << PEEP_FIXING_MOVE_TO_STATION_EXIT) | + (1 << PEEP_FIXING_FINISH_FIX_OR_INSPECT) | + (1 << PEEP_FIXING_LEAVE_BY_ENTRANCE_EXIT) + ), + ( // Breakdown::doorsStuckClosed + (1 << PEEP_FIXING_MOVE_TO_BROKEN_DOWN_VEHICLE) | + (1 << PEEP_FIXING_FIX_VEHICLE_CLOSED_DOORS) | + (1 << PEEP_FIXING_MOVE_TO_STATION_EXIT) | + (1 << PEEP_FIXING_FINISH_FIX_OR_INSPECT) | + (1 << PEEP_FIXING_LEAVE_BY_ENTRANCE_EXIT) + ), + ( // Breakdown::doorsStuckOpen + (1 << PEEP_FIXING_MOVE_TO_BROKEN_DOWN_VEHICLE) | + (1 << PEEP_FIXING_FIX_VEHICLE_OPEN_DOORS) | + (1 << PEEP_FIXING_MOVE_TO_STATION_EXIT) | + (1 << PEEP_FIXING_FINISH_FIX_OR_INSPECT) | + (1 << PEEP_FIXING_LEAVE_BY_ENTRANCE_EXIT) + ), + ( // Breakdown::vehicleMalfunction + (1 << PEEP_FIXING_MOVE_TO_BROKEN_DOWN_VEHICLE) | + (1 << PEEP_FIXING_FIX_VEHICLE_MALFUNCTION) | + (1 << PEEP_FIXING_MOVE_TO_STATION_EXIT) | + (1 << PEEP_FIXING_FINISH_FIX_OR_INSPECT) | + (1 << PEEP_FIXING_LEAVE_BY_ENTRANCE_EXIT) + ), + ( // Breakdown::brakesFailure + (1 << PEEP_FIXING_MOVE_TO_STATION_START) | + (1 << PEEP_FIXING_FIX_STATION_BRAKES) | + (1 << PEEP_FIXING_MOVE_TO_STATION_EXIT) | + (1 << PEEP_FIXING_FINISH_FIX_OR_INSPECT) | + (1 << PEEP_FIXING_LEAVE_BY_ENTRANCE_EXIT) + ), + ( // Breakdown::controlFailure + (1 << PEEP_FIXING_MOVE_TO_STATION_END) | + (1 << PEEP_FIXING_FIX_STATION_END) | + (1 << PEEP_FIXING_MOVE_TO_STATION_START) | + (1 << PEEP_FIXING_FIX_STATION_START) | + (1 << PEEP_FIXING_MOVE_TO_STATION_EXIT) | + (1 << PEEP_FIXING_FINISH_FIX_OR_INSPECT) | + (1 << PEEP_FIXING_LEAVE_BY_ENTRANCE_EXIT) + ), + ( // INSPECTION + (1 << PEEP_FIXING_MOVE_TO_STATION_END) | + (1 << PEEP_FIXING_FIX_STATION_END) | + (1 << PEEP_FIXING_MOVE_TO_STATION_START) | + (1 << PEEP_FIXING_FIX_STATION_START) | + (1 << PEEP_FIXING_MOVE_TO_STATION_EXIT) | + (1 << PEEP_FIXING_FINISH_FIX_OR_INSPECT) | + (1 << PEEP_FIXING_LEAVE_BY_ENTRANCE_EXIT) + ), + }; + // clang-format on + + /** + * + * rct2: 0x006C0E8B + * Also used by inspecting. + */ + void Staff::UpdateFixing(int32_t steps) + { + auto ride = GetRide(CurrentRide); + if (ride == nullptr) + { + SetState(PeepState::falling); + return; + } + + bool progressToNextSubstate = true; + bool firstRun = true; + + if ((State == PeepState::inspecting) && (ride->flags.hasAny(RideFlag::breakdownPending, RideFlag::brokenDown))) + { + // Ride has broken down since Mechanic was called to inspect it. + // Mechanic identifies the breakdown and switches to fixing it. + State = PeepState::fixing; + } + + while (progressToNextSubstate) + { + switch (SubState) + { + case PEEP_FIXING_ENTER_STATION: + NextFlags &= ~PEEP_NEXT_FLAG_IS_SLOPED; + progressToNextSubstate = UpdateFixingEnterStation(*ride); + break; + + case PEEP_FIXING_MOVE_TO_BROKEN_DOWN_VEHICLE: + progressToNextSubstate = UpdateFixingMoveToBrokenDownVehicle(firstRun, *ride); + break; + + case PEEP_FIXING_FIX_VEHICLE_CLOSED_RESTRAINTS: + case PEEP_FIXING_FIX_VEHICLE_CLOSED_DOORS: + case PEEP_FIXING_FIX_VEHICLE_OPEN_RESTRAINTS: + case PEEP_FIXING_FIX_VEHICLE_OPEN_DOORS: + progressToNextSubstate = UpdateFixingFixVehicle(firstRun, *ride); + break; + + case PEEP_FIXING_FIX_VEHICLE_MALFUNCTION: + progressToNextSubstate = UpdateFixingFixVehicleMalfunction(firstRun, *ride); + break; + + case PEEP_FIXING_MOVE_TO_STATION_END: + progressToNextSubstate = UpdateFixingMoveToStationEnd(firstRun, *ride); + break; + + case PEEP_FIXING_FIX_STATION_END: + progressToNextSubstate = UpdateFixingFixStationEnd(firstRun); + break; + + case PEEP_FIXING_MOVE_TO_STATION_START: + progressToNextSubstate = UpdateFixingMoveToStationStart(firstRun, *ride); + break; + + case PEEP_FIXING_FIX_STATION_START: + progressToNextSubstate = UpdateFixingFixStationStart(firstRun, *ride); + break; + + case PEEP_FIXING_FIX_STATION_BRAKES: + progressToNextSubstate = UpdateFixingFixStationBrakes(firstRun, *ride); + break; + + case PEEP_FIXING_MOVE_TO_STATION_EXIT: + progressToNextSubstate = UpdateFixingMoveToStationExit(firstRun, *ride); + break; + + case PEEP_FIXING_FINISH_FIX_OR_INSPECT: + progressToNextSubstate = UpdateFixingFinishFixOrInspect(firstRun, steps, *ride); + break; + + case PEEP_FIXING_LEAVE_BY_ENTRANCE_EXIT: + progressToNextSubstate = UpdateFixingLeaveByEntranceExit(firstRun, *ride); + break; + + default: + LOG_ERROR("Invalid substate"); + progressToNextSubstate = false; + } + + firstRun = false; + + if (!progressToNextSubstate) + { + break; + } + + int32_t subState = SubState; + uint32_t sub_state_sequence_mask = FixingSubstatesForBreakdown[8]; + + if (State != PeepState::inspecting) + { + sub_state_sequence_mask = FixingSubstatesForBreakdown[EnumValue(ride->breakdownReasonPending)]; + } + + do + { + subState++; + } while ((sub_state_sequence_mask & (1 << subState)) == 0); + + SubState = subState & 0xFF; + } + } + + /** + * rct2: 0x006C0EEC + * fixing SubState: enter_station - applies to fixing all break down reasons and ride inspections. + */ + bool Staff::UpdateFixingEnterStation(Ride& ride) const + { + ride.mechanicStatus = MechanicStatus::fixing; + ride.windowInvalidateFlags.set(RideInvalidateFlag::maintenance); + + return true; + } + + /** + * rct2: 0x006C0F09 + * fixing SubState: move_to_broken_down_vehicle - applies to fixing all vehicle specific breakdown reasons + * - see FixingSubstatesForBreakdown[] + */ + bool Staff::UpdateFixingMoveToBrokenDownVehicle(bool firstRun, const Ride& ride) + { + if (!firstRun) + { + Vehicle* vehicle = RideGetBrokenVehicle(ride); + if (vehicle == nullptr) + { + return true; + } + + while (true) + { + if (vehicle->IsHead()) + { + break; + } + + auto trackType = vehicle->GetTrackType(); + if (TrackTypeIsStation(trackType)) + { + break; + } + + vehicle = getGameState().entities.GetEntity(vehicle->prev_vehicle_on_ride); + if (vehicle == nullptr) + { + return true; + } + } + + CoordsXY offset = DirectionOffsets[PeepDirection]; + auto destination = (offset * -12) + vehicle->GetLocation(); + SetDestination(destination, 2); + } + + if (auto loc = UpdateAction(); loc.has_value()) + { + MoveTo({ loc.value(), z }); + return false; + } + + return true; + } + + /** + * rct2: 0x006C0FD3 + * fixing SubState: fix_vehicle - applies to fixing vehicle with: + * 1. restraints stuck closed, + * 2. doors stuck closed, + * 3. restrains stuck open, + * 4. doors stuck open. + * - see FixingSubstatesForBreakdown[] + */ + bool Staff::UpdateFixingFixVehicle(bool firstRun, const Ride& ride) + { + if (!firstRun) + { + Orientation = PeepDirection << 3; + + Action = (ScenarioRand() & 1) ? PeepActionType::staffFix2 : PeepActionType::staffFix; + AnimationImageIdOffset = 0; + AnimationFrameNum = 0; + UpdateCurrentAnimationType(); + } + + if (IsActionWalking()) + { + return true; + } + + UpdateAction(); + Invalidate(); + + uint8_t actionFrame = (Action == PeepActionType::staffFix) ? 0x25 : 0x50; + if (AnimationFrameNum != actionFrame) + { + return false; + } + Vehicle* vehicle = RideGetBrokenVehicle(ride); if (vehicle == nullptr) { return true; } - while (true) + vehicle->flags.unset(VehicleFlag::carIsBroken); + + return false; + } + + /** + * rct2: 0x006C107B + * fixing SubState: fix_vehicle_malfunction - applies fixing to vehicle malfunction. + * - see FixingSubstatesForBreakdown[] + */ + bool Staff::UpdateFixingFixVehicleMalfunction(bool firstRun, const Ride& ride) + { + if (!firstRun) { - if (vehicle->IsHead()) - { - break; - } + Orientation = PeepDirection << 3; + Action = PeepActionType::staffFix3; + AnimationImageIdOffset = 0; + AnimationFrameNum = 0; - auto trackType = vehicle->GetTrackType(); - if (TrackTypeIsStation(trackType)) - { - break; - } - - vehicle = getGameState().entities.GetEntity(vehicle->prev_vehicle_on_ride); - if (vehicle == nullptr) - { - return true; - } + UpdateCurrentAnimationType(); } - CoordsXY offset = DirectionOffsets[PeepDirection]; - auto destination = (offset * -12) + vehicle->GetLocation(); - SetDestination(destination, 2); - } - - if (auto loc = UpdateAction(); loc.has_value()) - { - MoveTo({ loc.value(), z }); - return false; - } - - return true; -} - -/** - * rct2: 0x006C0FD3 - * fixing SubState: fix_vehicle - applies to fixing vehicle with: - * 1. restraints stuck closed, - * 2. doors stuck closed, - * 3. restrains stuck open, - * 4. doors stuck open. - * - see FixingSubstatesForBreakdown[] - */ -bool Staff::UpdateFixingFixVehicle(bool firstRun, const Ride& ride) -{ - if (!firstRun) - { - Orientation = PeepDirection << 3; - - Action = (ScenarioRand() & 1) ? PeepActionType::staffFix2 : PeepActionType::staffFix; - AnimationImageIdOffset = 0; - AnimationFrameNum = 0; - UpdateCurrentAnimationType(); - } - - if (IsActionWalking()) - { - return true; - } - - UpdateAction(); - Invalidate(); - - uint8_t actionFrame = (Action == PeepActionType::staffFix) ? 0x25 : 0x50; - if (AnimationFrameNum != actionFrame) - { - return false; - } - - Vehicle* vehicle = RideGetBrokenVehicle(ride); - if (vehicle == nullptr) - { - return true; - } - - vehicle->flags.unset(VehicleFlag::carIsBroken); - - return false; -} - -/** - * rct2: 0x006C107B - * fixing SubState: fix_vehicle_malfunction - applies fixing to vehicle malfunction. - * - see FixingSubstatesForBreakdown[] - */ -bool Staff::UpdateFixingFixVehicleMalfunction(bool firstRun, const Ride& ride) -{ - if (!firstRun) - { - Orientation = PeepDirection << 3; - Action = PeepActionType::staffFix3; - AnimationImageIdOffset = 0; - AnimationFrameNum = 0; - - UpdateCurrentAnimationType(); - } - - if (IsActionWalking()) - { - return true; - } - - UpdateAction(); - Invalidate(); - - if (AnimationFrameNum != 0x65) - { - return false; - } - - Vehicle* vehicle = RideGetBrokenVehicle(ride); - if (vehicle == nullptr) - { - return true; - } - - vehicle->flags.unset(VehicleFlag::trainIsBroken); - - return false; -} - -/** rct2: 0x00992A3C */ -static constexpr CoordsXY kStationFixingOffsets[] = { - { -12, 0 }, - { 0, 12 }, - { 12, 0 }, - { 0, -12 }, -}; - -/** - * rct2: 0x006C1114 - * fixing SubState: move_to_station_end - applies to fixing station specific breakdowns: safety cut-out, control failure, - * inspection. - * - see FixingSubstatesForBreakdown[] - */ -bool Staff::UpdateFixingMoveToStationEnd(bool firstRun, const Ride& ride) -{ - if (!firstRun) - { - if (ride.getRideTypeDescriptor().flags.has(RtdFlag::hasSinglePieceStation) - || !ride.getRideTypeDescriptor().flags.has(RtdFlag::hasTrack)) + if (IsActionWalking()) { return true; } - auto stationPos = ride.getStation(CurrentRideStation).GetStart(); - if (stationPos.IsNull()) - { - return true; - } + UpdateAction(); + Invalidate(); - auto tileElement = MapGetTrackElementAt(stationPos); - if (tileElement == nullptr) + if (AnimationFrameNum != 0x65) { - LOG_ERROR("Couldn't find tile_element"); return false; } - int32_t trackDirection = tileElement->GetDirection(); - CoordsXY offset = kStationFixingOffsets[trackDirection]; - - stationPos.x += 16 + offset.x; - if (offset.x == 0) + Vehicle* vehicle = RideGetBrokenVehicle(ride); + if (vehicle == nullptr) { - stationPos.x = GetDestination().x; + return true; } - stationPos.y += 16 + offset.y; - if (offset.y == 0) - { - stationPos.y = GetDestination().y; - } + vehicle->flags.unset(VehicleFlag::trainIsBroken); - SetDestination(stationPos, 2); - } - - if (auto loc = UpdateAction(); loc.has_value()) - { - MoveTo({ loc.value(), z }); return false; } - return true; -} + /** rct2: 0x00992A3C */ + static constexpr CoordsXY kStationFixingOffsets[] = { + { -12, 0 }, + { 0, 12 }, + { 12, 0 }, + { 0, -12 }, + }; -/** - * rct2: 0x006C11F5 - * fixing SubState: fix_station_end - applies to fixing station specific breakdowns: safety cut-out, control failure, - * inspection. - * - see FixingSubstatesForBreakdown[] - */ -bool Staff::UpdateFixingFixStationEnd(bool firstRun) -{ - if (!firstRun) + /** + * rct2: 0x006C1114 + * fixing SubState: move_to_station_end - applies to fixing station specific breakdowns: safety cut-out, control failure, + * inspection. + * - see FixingSubstatesForBreakdown[] + */ + bool Staff::UpdateFixingMoveToStationEnd(bool firstRun, const Ride& ride) { - Orientation = PeepDirection << 3; - Action = PeepActionType::staffCheckBoard; - AnimationFrameNum = 0; - AnimationImageIdOffset = 0; - - UpdateCurrentAnimationType(); - } - - if (IsActionWalking()) - { - return true; - } - - UpdateAction(); - Invalidate(); - - return false; -} - -/** - * rct2: 0x006C1239 - * fixing SubState: move_to_station_start - * 1. applies to fixing station specific breakdowns: safety cut-out, control failure, - * 2. applies to fixing brake failure, - * 3. applies to inspection. - * - see FixingSubstatesForBreakdown[] - */ -bool Staff::UpdateFixingMoveToStationStart(bool firstRun, const Ride& ride) -{ - if (!firstRun) - { - if (ride.getRideTypeDescriptor().flags.has(RtdFlag::hasSinglePieceStation) - || !ride.getRideTypeDescriptor().flags.has(RtdFlag::hasTrack)) + if (!firstRun) { - return true; - } - - auto stationPosition = ride.getStation(CurrentRideStation).GetStart(); - if (stationPosition.IsNull()) - { - return true; - } - - CoordsXYE input; - input.x = stationPosition.x; - input.y = stationPosition.y; - input.element = MapGetTrackElementAtFromRide({ input.x, input.y, stationPosition.z }, CurrentRide); - if (input.element == nullptr) - { - return true; - } - - Direction stationDirection = 0; - TrackBeginEnd trackBeginEnd; - while (trackBlockGetPrevious(input, &trackBeginEnd)) - { - if (trackBeginEnd.begin_element->AsTrack()->IsStation()) + if (ride.getRideTypeDescriptor().flags.has(RtdFlag::hasSinglePieceStation) + || !ride.getRideTypeDescriptor().flags.has(RtdFlag::hasTrack)) { - input.x = trackBeginEnd.begin_x; - input.y = trackBeginEnd.begin_y; - input.element = trackBeginEnd.begin_element; - - stationDirection = trackBeginEnd.begin_element->GetDirection(); - continue; + return true; } - break; + auto stationPos = ride.getStation(CurrentRideStation).GetStart(); + if (stationPos.IsNull()) + { + return true; + } + + auto tileElement = MapGetTrackElementAt(stationPos); + if (tileElement == nullptr) + { + LOG_ERROR("Couldn't find tile_element"); + return false; + } + + int32_t trackDirection = tileElement->GetDirection(); + CoordsXY offset = kStationFixingOffsets[trackDirection]; + + stationPos.x += 16 + offset.x; + if (offset.x == 0) + { + stationPos.x = GetDestination().x; + } + + stationPos.y += 16 + offset.y; + if (offset.y == 0) + { + stationPos.y = GetDestination().y; + } + + SetDestination(stationPos, 2); } - // Loc6C12ED: - auto destination = CoordsXY{ input.x + 16, input.y + 16 }; - auto offset = kStationFixingOffsets[stationDirection]; - - destination.x -= offset.x; - if (offset.x == 0) + if (auto loc = UpdateAction(); loc.has_value()) { - destination.x = GetDestination().x; + MoveTo({ loc.value(), z }); + return false; } - destination.y -= offset.y; - if (offset.y == 0) - { - destination.y = GetDestination().y; - } - - SetDestination(destination, 2); + return true; } - if (auto loc = UpdateAction(); loc.has_value()) + /** + * rct2: 0x006C11F5 + * fixing SubState: fix_station_end - applies to fixing station specific breakdowns: safety cut-out, control failure, + * inspection. + * - see FixingSubstatesForBreakdown[] + */ + bool Staff::UpdateFixingFixStationEnd(bool firstRun) { - MoveTo({ loc.value(), z }); - return false; - } + if (!firstRun) + { + Orientation = PeepDirection << 3; + Action = PeepActionType::staffCheckBoard; + AnimationFrameNum = 0; + AnimationImageIdOffset = 0; - return true; -} + UpdateCurrentAnimationType(); + } -/** - * rct2: 0x006C1368 - * fixing SubState: fix_station_start - * 1. applies to fixing station specific breakdowns: safety cut-out, control failure, - * 2. applies to inspection. - * - see FixingSubstatesForBreakdown[] - */ -bool Staff::UpdateFixingFixStationStart(bool firstRun, const Ride& ride) -{ - if (!firstRun) - { - if (ride.getRideTypeDescriptor().flags.has(RtdFlag::hasSinglePieceStation) - || !ride.getRideTypeDescriptor().flags.has(RtdFlag::hasTrack)) + if (IsActionWalking()) { return true; } - Orientation = PeepDirection << 3; + UpdateAction(); + Invalidate(); - Action = PeepActionType::staffFix; - AnimationFrameNum = 0; - AnimationImageIdOffset = 0; - - UpdateCurrentAnimationType(); + return false; } - if (IsActionWalking()) + /** + * rct2: 0x006C1239 + * fixing SubState: move_to_station_start + * 1. applies to fixing station specific breakdowns: safety cut-out, control failure, + * 2. applies to fixing brake failure, + * 3. applies to inspection. + * - see FixingSubstatesForBreakdown[] + */ + bool Staff::UpdateFixingMoveToStationStart(bool firstRun, const Ride& ride) { - return true; - } - - UpdateAction(); - - return false; -} - -/** - * rct2: 0x006C13CE - * fixing SubState: fix_station_brakes - applies to fixing brake failure - * - see FixingSubstatesForBreakdown[] - */ -bool Staff::UpdateFixingFixStationBrakes(bool firstRun, Ride& ride) -{ - if (!firstRun) - { - Orientation = PeepDirection << 3; - - Action = PeepActionType::staffFixGround; - AnimationFrameNum = 0; - AnimationImageIdOffset = 0; - - UpdateCurrentAnimationType(); - } - - if (IsActionWalking()) - { - return true; - } - - UpdateAction(); - Invalidate(); - - if (AnimationFrameNum == 0x28) - { - ride.mechanicStatus = MechanicStatus::hasFixedStationBrakes; - ride.windowInvalidateFlags.set(RideInvalidateFlag::maintenance); - } - - if (AnimationFrameNum == 0x13 || AnimationFrameNum == 0x19 || AnimationFrameNum == 0x1F || AnimationFrameNum == 0x25 - || AnimationFrameNum == 0x2B) - { - Audio::Play3D(Audio::SoundId::mechanicFix, GetLocation()); - } - - return false; -} - -/** - * rct2: 0x006C1474 - * fixing SubState: move_to_station_exit - applies to fixing all failures & inspections - * - see FixingSubstatesForBreakdown[] - */ -bool Staff::UpdateFixingMoveToStationExit(bool firstRun, const Ride& ride) -{ - if (!firstRun) - { - auto stationPosition = ride.getStation(CurrentRideStation).Exit.ToCoordsXY(); - if (stationPosition.IsNull()) + if (!firstRun) { - stationPosition = ride.getStation(CurrentRideStation).Entrance.ToCoordsXY(); + if (ride.getRideTypeDescriptor().flags.has(RtdFlag::hasSinglePieceStation) + || !ride.getRideTypeDescriptor().flags.has(RtdFlag::hasTrack)) + { + return true; + } + auto stationPosition = ride.getStation(CurrentRideStation).GetStart(); if (stationPosition.IsNull()) { return true; } + + CoordsXYE input; + input.x = stationPosition.x; + input.y = stationPosition.y; + input.element = MapGetTrackElementAtFromRide({ input.x, input.y, stationPosition.z }, CurrentRide); + if (input.element == nullptr) + { + return true; + } + + Direction stationDirection = 0; + TrackBeginEnd trackBeginEnd; + while (trackBlockGetPrevious(input, &trackBeginEnd)) + { + if (trackBeginEnd.begin_element->AsTrack()->IsStation()) + { + input.x = trackBeginEnd.begin_x; + input.y = trackBeginEnd.begin_y; + input.element = trackBeginEnd.begin_element; + + stationDirection = trackBeginEnd.begin_element->GetDirection(); + continue; + } + + break; + } + + // Loc6C12ED: + auto destination = CoordsXY{ input.x + 16, input.y + 16 }; + auto offset = kStationFixingOffsets[stationDirection]; + + destination.x -= offset.x; + if (offset.x == 0) + { + destination.x = GetDestination().x; + } + + destination.y -= offset.y; + if (offset.y == 0) + { + destination.y = GetDestination().y; + } + + SetDestination(destination, 2); } - stationPosition = stationPosition.ToTileCentre(); - - CoordsXY stationPlatformDirection = DirectionOffsets[PeepDirection]; - stationPosition.x += stationPlatformDirection.x * 20; - stationPosition.y += stationPlatformDirection.y * 20; - - SetDestination(stationPosition, 2); - } - - if (auto loc = UpdateAction(); loc.has_value()) - { - MoveTo({ loc.value(), z }); - return false; - } - - return true; -} - -/** - * rct2: 0x006C1504 - * fixing SubState: finish_fix_or_inspect - applies to fixing all failures & inspections - * - see FixingSubstatesForBreakdown[] - */ -bool Staff::UpdateFixingFinishFixOrInspect(bool firstRun, int32_t steps, Ride& ride) -{ - if (!firstRun) - { - if (State == PeepState::inspecting) + if (auto loc = UpdateAction(); loc.has_value()) { - UpdateRideInspected(CurrentRide); + MoveTo({ loc.value(), z }); + return false; + } - StaffRidesInspected = AddClamp(StaffRidesInspected, 1u); - WindowInvalidateFlags |= PEEP_INVALIDATE_STAFF_STATS; - ride.mechanicStatus = MechanicStatus::undefined; + return true; + } + + /** + * rct2: 0x006C1368 + * fixing SubState: fix_station_start + * 1. applies to fixing station specific breakdowns: safety cut-out, control failure, + * 2. applies to inspection. + * - see FixingSubstatesForBreakdown[] + */ + bool Staff::UpdateFixingFixStationStart(bool firstRun, const Ride& ride) + { + if (!firstRun) + { + if (ride.getRideTypeDescriptor().flags.has(RtdFlag::hasSinglePieceStation) + || !ride.getRideTypeDescriptor().flags.has(RtdFlag::hasTrack)) + { + return true; + } + + Orientation = PeepDirection << 3; + + Action = PeepActionType::staffFix; + AnimationFrameNum = 0; + AnimationImageIdOffset = 0; + + UpdateCurrentAnimationType(); + } + + if (IsActionWalking()) + { return true; } - StaffRidesFixed = AddClamp(StaffRidesFixed, 1u); - WindowInvalidateFlags |= PEEP_INVALIDATE_STAFF_STATS; + UpdateAction(); - Orientation = PeepDirection << 3; - Action = PeepActionType::staffAnswerCall2; - AnimationFrameNum = 0; - AnimationImageIdOffset = 0; - - UpdateCurrentAnimationType(); + return false; } - if (!IsActionWalking()) + /** + * rct2: 0x006C13CE + * fixing SubState: fix_station_brakes - applies to fixing brake failure + * - see FixingSubstatesForBreakdown[] + */ + bool Staff::UpdateFixingFixStationBrakes(bool firstRun, Ride& ride) { + if (!firstRun) + { + Orientation = PeepDirection << 3; + + Action = PeepActionType::staffFixGround; + AnimationFrameNum = 0; + AnimationImageIdOffset = 0; + + UpdateCurrentAnimationType(); + } + + if (IsActionWalking()) + { + return true; + } + UpdateAction(); Invalidate(); + + if (AnimationFrameNum == 0x28) + { + ride.mechanicStatus = MechanicStatus::hasFixedStationBrakes; + ride.windowInvalidateFlags.set(RideInvalidateFlag::maintenance); + } + + if (AnimationFrameNum == 0x13 || AnimationFrameNum == 0x19 || AnimationFrameNum == 0x1F || AnimationFrameNum == 0x25 + || AnimationFrameNum == 0x2B) + { + Audio::Play3D(Audio::SoundId::mechanicFix, GetLocation()); + } + return false; } - RideFixBreakdown(ride, steps); - ride.mechanicStatus = MechanicStatus::undefined; - return true; -} - -/** - * rct2: 0x006C157E - * fixing SubState: leave_by_entrance_exit - applies to fixing all failures & inspections - * - see FixingSubstatesForBreakdown[] - */ -bool Staff::UpdateFixingLeaveByEntranceExit(bool firstRun, const Ride& ride) -{ - if (!firstRun) + /** + * rct2: 0x006C1474 + * fixing SubState: move_to_station_exit - applies to fixing all failures & inspections + * - see FixingSubstatesForBreakdown[] + */ + bool Staff::UpdateFixingMoveToStationExit(bool firstRun, const Ride& ride) { - auto exitPosition = ride.getStation(CurrentRideStation).Exit.ToCoordsXY(); - if (exitPosition.IsNull()) + if (!firstRun) { - exitPosition = ride.getStation(CurrentRideStation).Entrance.ToCoordsXY(); + auto stationPosition = ride.getStation(CurrentRideStation).Exit.ToCoordsXY(); + if (stationPosition.IsNull()) + { + stationPosition = ride.getStation(CurrentRideStation).Entrance.ToCoordsXY(); + if (stationPosition.IsNull()) + { + return true; + } + } + + stationPosition = stationPosition.ToTileCentre(); + + CoordsXY stationPlatformDirection = DirectionOffsets[PeepDirection]; + stationPosition.x += stationPlatformDirection.x * 20; + stationPosition.y += stationPlatformDirection.y * 20; + + SetDestination(stationPosition, 2); + } + + if (auto loc = UpdateAction(); loc.has_value()) + { + MoveTo({ loc.value(), z }); + return false; + } + + return true; + } + + /** + * rct2: 0x006C1504 + * fixing SubState: finish_fix_or_inspect - applies to fixing all failures & inspections + * - see FixingSubstatesForBreakdown[] + */ + bool Staff::UpdateFixingFinishFixOrInspect(bool firstRun, int32_t steps, Ride& ride) + { + if (!firstRun) + { + if (State == PeepState::inspecting) + { + UpdateRideInspected(CurrentRide); + + StaffRidesInspected = AddClamp(StaffRidesInspected, 1u); + WindowInvalidateFlags |= PEEP_INVALIDATE_STAFF_STATS; + ride.mechanicStatus = MechanicStatus::undefined; + return true; + } + + StaffRidesFixed = AddClamp(StaffRidesFixed, 1u); + WindowInvalidateFlags |= PEEP_INVALIDATE_STAFF_STATS; + + Orientation = PeepDirection << 3; + Action = PeepActionType::staffAnswerCall2; + AnimationFrameNum = 0; + AnimationImageIdOffset = 0; + + UpdateCurrentAnimationType(); + } + + if (!IsActionWalking()) + { + UpdateAction(); + Invalidate(); + return false; + } + + RideFixBreakdown(ride, steps); + ride.mechanicStatus = MechanicStatus::undefined; + return true; + } + + /** + * rct2: 0x006C157E + * fixing SubState: leave_by_entrance_exit - applies to fixing all failures & inspections + * - see FixingSubstatesForBreakdown[] + */ + bool Staff::UpdateFixingLeaveByEntranceExit(bool firstRun, const Ride& ride) + { + if (!firstRun) + { + auto exitPosition = ride.getStation(CurrentRideStation).Exit.ToCoordsXY(); if (exitPosition.IsNull()) { - SetState(PeepState::falling); - return false; + exitPosition = ride.getStation(CurrentRideStation).Entrance.ToCoordsXY(); + + if (exitPosition.IsNull()) + { + SetState(PeepState::falling); + return false; + } } + + exitPosition = exitPosition.ToTileCentre(); + + CoordsXY ebx_direction = DirectionOffsets[PeepDirection]; + exitPosition.x -= ebx_direction.x * 19; + exitPosition.y -= ebx_direction.y * 19; + + SetDestination(exitPosition, 2); } - exitPosition = exitPosition.ToTileCentre(); - - CoordsXY ebx_direction = DirectionOffsets[PeepDirection]; - exitPosition.x -= ebx_direction.x * 19; - exitPosition.y -= ebx_direction.y * 19; - - SetDestination(exitPosition, 2); - } - - int16_t xy_distance; - if (auto loc = UpdateAction(xy_distance); loc.has_value()) - { - auto stationHeight = ride.getStation(CurrentRideStation).GetBaseZ(); - if (xy_distance >= 16) + int16_t xy_distance; + if (auto loc = UpdateAction(xy_distance); loc.has_value()) { - stationHeight += ride.getRideTypeDescriptor().Heights.PlatformHeight; - } + auto stationHeight = ride.getStation(CurrentRideStation).GetBaseZ(); + if (xy_distance >= 16) + { + stationHeight += ride.getRideTypeDescriptor().Heights.PlatformHeight; + } - MoveTo({ loc.value(), stationHeight }); + MoveTo({ loc.value(), stationHeight }); + return false; + } + SetState(PeepState::falling); return false; } - SetState(PeepState::falling); - return false; -} -/** - * rct2: 0x6B7588 - */ -void Staff::UpdateRideInspected(RideId rideIndex) -{ - auto ride = GetRide(rideIndex); - if (ride != nullptr) + /** + * rct2: 0x6B7588 + */ + void Staff::UpdateRideInspected(RideId rideIndex) { - ride->flags.unset(RideFlag::dueInspection); - ride->reliability += ((100 - ride->reliabilityPercentage) / 4) * (ScenarioRand() & 0xFF); - ride->lastInspection = 0; - ride->windowInvalidateFlags.set(RideInvalidateFlag::maintenance, RideInvalidateFlag::main, RideInvalidateFlag::list); + auto ride = GetRide(rideIndex); + if (ride != nullptr) + { + ride->flags.unset(RideFlag::dueInspection); + ride->reliability += ((100 - ride->reliabilityPercentage) / 4) * (ScenarioRand() & 0xFF); + ride->lastInspection = 0; + ride->windowInvalidateFlags.set( + RideInvalidateFlag::maintenance, RideInvalidateFlag::main, RideInvalidateFlag::list); + } } -} -money64 GetStaffWage(StaffType type) -{ - switch (type) + money64 GetStaffWage(StaffType type) { - default: - case StaffType::handyman: - return 50.00_GBP; - case StaffType::mechanic: - return 80.00_GBP; - case StaffType::security: - return 60.00_GBP; - case StaffType::entertainer: - return 55.00_GBP; + switch (type) + { + default: + case StaffType::handyman: + return 50.00_GBP; + case StaffType::mechanic: + return 80.00_GBP; + case StaffType::security: + return 60.00_GBP; + case StaffType::entertainer: + return 55.00_GBP; + } } -} -void Staff::Serialise(DataSerialiser& stream) -{ - Peep::Serialise(stream); - stream << AssignedStaffType; - stream << MechanicTimeSinceCall; - stream << HireDate; - stream << StaffOrders; - stream << StaffMowingTimeout; - stream << StaffLawnsMown; - stream << StaffGardensWatered; - stream << StaffLitterSwept; - stream << StaffBinsEmptied; -} + void Staff::Serialise(DataSerialiser& stream) + { + Peep::Serialise(stream); + stream << AssignedStaffType; + stream << MechanicTimeSinceCall; + stream << HireDate; + stream << StaffOrders; + stream << StaffMowingTimeout; + stream << StaffLawnsMown; + stream << StaffGardensWatered; + stream << StaffLitterSwept; + stream << StaffBinsEmptied; + } +} // namespace OpenRCT2 diff --git a/src/openrct2/entity/Staff.h b/src/openrct2/entity/Staff.h index 0e7f839c70..b141301eaa 100644 --- a/src/openrct2/entity/Staff.h +++ b/src/openrct2/entity/Staff.h @@ -16,160 +16,161 @@ #include #include -namespace OpenRCT2 -{ - class DataSerialiser; - - struct TileElement; - struct PathElement; -} // namespace OpenRCT2 +struct Ride; namespace OpenRCT2::Drawing { enum class Colour : uint8_t; } -class PatrolArea; -struct Ride; - -enum class StaffType : uint8_t +namespace OpenRCT2 { - handyman, - mechanic, - security, - entertainer, + class DataSerialiser; - count -}; + struct TileElement; + struct PathElement; -struct Staff : Peep -{ - static constexpr auto cEntityType = EntityType::staff; + class PatrolArea; -public: - PatrolArea* PatrolInfo; - StaffType AssignedStaffType; - uint16_t MechanicTimeSinceCall; // time getting to ride to fix - int32_t HireDate; - uint8_t StaffOrders; - uint8_t StaffMowingTimeout; - union + enum class StaffType : uint8_t { - uint32_t StaffLawnsMown; - uint32_t StaffRidesFixed; + handyman, + mechanic, + security, + entertainer, + + count }; - union + + struct Staff : Peep { - uint32_t StaffGardensWatered; - uint32_t StaffRidesInspected; + static constexpr auto cEntityType = EntityType::staff; + + public: + PatrolArea* PatrolInfo; + StaffType AssignedStaffType; + uint16_t MechanicTimeSinceCall; // time getting to ride to fix + int32_t HireDate; + uint8_t StaffOrders; + uint8_t StaffMowingTimeout; + union + { + uint32_t StaffLawnsMown; + uint32_t StaffRidesFixed; + }; + union + { + uint32_t StaffGardensWatered; + uint32_t StaffRidesInspected; + }; + union + { + uint32_t StaffLitterSwept; + uint32_t StaffVandalsStopped; + }; + uint32_t StaffBinsEmptied; + + void Update(); + void Tick128UpdateStaff(); + bool IsMechanic() const; + bool isEntertainer() const; + bool IsPatrolAreaSet(const CoordsXY& coords) const; + bool IsLocationInPatrol(const CoordsXY& loc) const; + bool IsLocationOnPatrolEdge(const CoordsXY& loc) const; + bool DoPathFinding(); + void SetHireDate(int32_t hireDate); + int32_t GetHireDate() const; + + bool CanIgnoreWideFlag(const CoordsXYZ& staffPos, TileElement* path) const; + + static void ResetStats(); + void Serialise(DataSerialiser& stream); + + void ClearPatrolArea(); + void SetPatrolArea(const CoordsXY& coords, bool value); + void SetPatrolArea(const MapRange& range, bool value); + bool HasPatrolArea() const; + + private: + void UpdatePatrolling(); + void UpdateMowing(); + void UpdateSweeping(); + void UpdateEmptyingBin(); + void UpdateWatering(); + void UpdateAnswering(); + void UpdateFixing(int32_t steps); + bool UpdateFixingEnterStation(Ride& ride) const; + bool UpdateFixingMoveToBrokenDownVehicle(bool firstRun, const Ride& ride); + bool UpdateFixingFixVehicle(bool firstRun, const Ride& ride); + bool UpdateFixingFixVehicleMalfunction(bool firstRun, const Ride& ride); + bool UpdateFixingMoveToStationEnd(bool firstRun, const Ride& ride); + bool UpdateFixingFixStationEnd(bool firstRun); + bool UpdateFixingMoveToStationStart(bool firstRun, const Ride& ride); + bool UpdateFixingFixStationStart(bool firstRun, const Ride& ride); + bool UpdateFixingFixStationBrakes(bool firstRun, Ride& ride); + bool UpdateFixingMoveToStationExit(bool firstRun, const Ride& ride); + bool UpdateFixingFinishFixOrInspect(bool firstRun, int32_t steps, Ride& ride); + bool UpdateFixingLeaveByEntranceExit(bool firstRun, const Ride& ride); + void UpdateRideInspected(RideId rideIndex); + void UpdateHeadingToInspect(); + + bool DoHandymanPathFinding(); + bool DoMechanicPathFinding(); + bool DoEntertainerPathFinding(); + bool DoMiscPathFinding(); + bool IsMechanicHeadingToFixRideBlockingPath(); + + Direction HandymanDirectionRandSurface(uint8_t validDirections) const; + + void EntertainerUpdateNearbyPeeps() const; + bool SecurityGuardPathIsCrowded() const; + + uint8_t GetValidPatrolDirections(const CoordsXY& loc) const; + Direction HandymanDirectionToNearestLitter() const; + uint8_t HandymanDirectionToUncutGrass(uint8_t valid_directions) const; + Direction DirectionSurface(Direction initialDirection) const; + Direction DirectionPath(uint8_t validDirections, PathElement* pathElement) const; + Direction MechanicDirectionSurface() const; + Direction MechanicDirectionPathRand(uint8_t pathDirections) const; + Direction MechanicDirectionPath(uint8_t validDirections, PathElement* pathElement); + bool UpdatePatrollingFindWatering(); + bool UpdatePatrollingFindBin(); + bool UpdatePatrollingFindSweeping(); + bool UpdatePatrollingFindGrass(); }; - union + static_assert(sizeof(Staff) <= 512); + + enum STAFF_ORDERS { - uint32_t StaffLitterSwept; - uint32_t StaffVandalsStopped; + STAFF_ORDERS_SWEEPING = (1 << 0), + STAFF_ORDERS_WATER_FLOWERS = (1 << 1), + STAFF_ORDERS_EMPTY_BINS = (1 << 2), + STAFF_ORDERS_MOWING = (1 << 3), + STAFF_ORDERS_INSPECT_RIDES = (1 << 0), + STAFF_ORDERS_FIX_RIDES = (1 << 1) }; - uint32_t StaffBinsEmptied; - void Update(); - void Tick128UpdateStaff(); - bool IsMechanic() const; - bool isEntertainer() const; - bool IsPatrolAreaSet(const CoordsXY& coords) const; - bool IsLocationInPatrol(const CoordsXY& loc) const; - bool IsLocationOnPatrolEdge(const CoordsXY& loc) const; - bool DoPathFinding(); - void SetHireDate(int32_t hireDate); - int32_t GetHireDate() const; + enum class EntertainerCostume : uint8_t + { + Panda, + Tiger, + Elephant, + Roman, + Gorilla, + Snowman, + Knight, + Astronaut, + Bandit, + Sheriff, + Pirate, - bool CanIgnoreWideFlag(const CoordsXYZ& staffPos, OpenRCT2::TileElement* path) const; + Count + }; - static void ResetStats(); - void Serialise(OpenRCT2::DataSerialiser& stream); + Drawing::Colour StaffGetColour(StaffType staffType); + GameActions::Result StaffSetColour(StaffType staffType, Drawing::Colour value); - void ClearPatrolArea(); - void SetPatrolArea(const CoordsXY& coords, bool value); - void SetPatrolArea(const MapRange& range, bool value); - bool HasPatrolArea() const; + money64 GetStaffWage(StaffType type); -private: - void UpdatePatrolling(); - void UpdateMowing(); - void UpdateSweeping(); - void UpdateEmptyingBin(); - void UpdateWatering(); - void UpdateAnswering(); - void UpdateFixing(int32_t steps); - bool UpdateFixingEnterStation(Ride& ride) const; - bool UpdateFixingMoveToBrokenDownVehicle(bool firstRun, const Ride& ride); - bool UpdateFixingFixVehicle(bool firstRun, const Ride& ride); - bool UpdateFixingFixVehicleMalfunction(bool firstRun, const Ride& ride); - bool UpdateFixingMoveToStationEnd(bool firstRun, const Ride& ride); - bool UpdateFixingFixStationEnd(bool firstRun); - bool UpdateFixingMoveToStationStart(bool firstRun, const Ride& ride); - bool UpdateFixingFixStationStart(bool firstRun, const Ride& ride); - bool UpdateFixingFixStationBrakes(bool firstRun, Ride& ride); - bool UpdateFixingMoveToStationExit(bool firstRun, const Ride& ride); - bool UpdateFixingFinishFixOrInspect(bool firstRun, int32_t steps, Ride& ride); - bool UpdateFixingLeaveByEntranceExit(bool firstRun, const Ride& ride); - void UpdateRideInspected(RideId rideIndex); - void UpdateHeadingToInspect(); - - bool DoHandymanPathFinding(); - bool DoMechanicPathFinding(); - bool DoEntertainerPathFinding(); - bool DoMiscPathFinding(); - bool IsMechanicHeadingToFixRideBlockingPath(); - - Direction HandymanDirectionRandSurface(uint8_t validDirections) const; - - void EntertainerUpdateNearbyPeeps() const; - bool SecurityGuardPathIsCrowded() const; - - uint8_t GetValidPatrolDirections(const CoordsXY& loc) const; - Direction HandymanDirectionToNearestLitter() const; - uint8_t HandymanDirectionToUncutGrass(uint8_t valid_directions) const; - Direction DirectionSurface(Direction initialDirection) const; - Direction DirectionPath(uint8_t validDirections, OpenRCT2::PathElement* pathElement) const; - Direction MechanicDirectionSurface() const; - Direction MechanicDirectionPathRand(uint8_t pathDirections) const; - Direction MechanicDirectionPath(uint8_t validDirections, OpenRCT2::PathElement* pathElement); - bool UpdatePatrollingFindWatering(); - bool UpdatePatrollingFindBin(); - bool UpdatePatrollingFindSweeping(); - bool UpdatePatrollingFindGrass(); -}; -static_assert(sizeof(Staff) <= 512); - -enum STAFF_ORDERS -{ - STAFF_ORDERS_SWEEPING = (1 << 0), - STAFF_ORDERS_WATER_FLOWERS = (1 << 1), - STAFF_ORDERS_EMPTY_BINS = (1 << 2), - STAFF_ORDERS_MOWING = (1 << 3), - STAFF_ORDERS_INSPECT_RIDES = (1 << 0), - STAFF_ORDERS_FIX_RIDES = (1 << 1) -}; - -enum class EntertainerCostume : uint8_t -{ - Panda, - Tiger, - Elephant, - Roman, - Gorilla, - Snowman, - Knight, - Astronaut, - Bandit, - Sheriff, - Pirate, - - Count -}; - -OpenRCT2::Drawing::Colour StaffGetColour(StaffType staffType); -OpenRCT2::GameActions::Result StaffSetColour(StaffType staffType, OpenRCT2::Drawing::Colour value); - -money64 GetStaffWage(StaffType type); - -const PatrolArea& GetMergedPatrolArea(StaffType type); + const PatrolArea& GetMergedPatrolArea(StaffType type); +} // namespace OpenRCT2 diff --git a/src/openrct2/interface/Viewport.h b/src/openrct2/interface/Viewport.h index f3c873466d..6b50078be4 100644 --- a/src/openrct2/interface/Viewport.h +++ b/src/openrct2/interface/Viewport.h @@ -19,9 +19,6 @@ struct PaintSession; struct PaintStruct; -struct EntityBase; -struct Guest; -struct Staff; struct PaintEntry; namespace OpenRCT2::Drawing @@ -31,6 +28,9 @@ namespace OpenRCT2::Drawing namespace OpenRCT2 { + struct EntityBase; + struct Guest; + struct Staff; struct TileElement; struct WindowBase; diff --git a/src/openrct2/management/Marketing.h b/src/openrct2/management/Marketing.h index 4cc2af4845..8f6a6d85c8 100644 --- a/src/openrct2/management/Marketing.h +++ b/src/openrct2/management/Marketing.h @@ -15,8 +15,6 @@ #include "../ride/RideTypes.h" #include "../ride/ShopItem.h" -struct Guest; - enum { ADVERTISING_CAMPAIGN_PARK_ENTRY_FREE, @@ -44,6 +42,8 @@ enum namespace OpenRCT2 { + struct Guest; + enum class MarketingCampaignFlag : uint8_t { firstWeek, @@ -69,7 +69,7 @@ extern const StringId kMarketingCampaignNames[ADVERTISING_CAMPAIGN_COUNT][3]; uint16_t MarketingGetCampaignGuestGenerationProbability(int32_t campaign); void MarketingUpdate(); -void MarketingSetGuestCampaign(Guest* peep, int32_t campaign); +void MarketingSetGuestCampaign(OpenRCT2::Guest* peep, int32_t campaign); bool MarketingIsCampaignTypeApplicable(int32_t campaignType); MarketingCampaign* MarketingGetCampaign(int32_t campaignType); void MarketingNewCampaign(const MarketingCampaign& campaign); diff --git a/src/openrct2/network/Network.h b/src/openrct2/network/Network.h index 4496c7f41f..89de24cd7a 100644 --- a/src/openrct2/network/Network.h +++ b/src/openrct2/network/Network.h @@ -20,9 +20,13 @@ #include #include -struct Peep; struct CoordsXYZ; +namespace OpenRCT2 +{ + struct Peep; +} + namespace OpenRCT2::GameActions { class GameAction; diff --git a/src/openrct2/network/NetworkBase.cpp b/src/openrct2/network/NetworkBase.cpp index ce7154ed2f..21c61831dc 100644 --- a/src/openrct2/network/NetworkBase.cpp +++ b/src/openrct2/network/NetworkBase.cpp @@ -52,7 +52,7 @@ constexpr uint8_t kStreamVersion = 2; const std::string kStreamID = std::string(kOpenRCT2Version) + "-" + std::to_string(kStreamVersion); -static Peep* _pickup_peep = nullptr; +static OpenRCT2::Peep* _pickup_peep = nullptr; static int32_t _pickup_peep_old_x = kLocationNull; #ifndef DISABLE_NETWORK diff --git a/src/openrct2/network/NetworkPlayer.h b/src/openrct2/network/NetworkPlayer.h index 7111a4bf35..75c155d92a 100644 --- a/src/openrct2/network/NetworkPlayer.h +++ b/src/openrct2/network/NetworkPlayer.h @@ -17,7 +17,10 @@ #include #include -struct Peep; +namespace OpenRCT2 +{ + struct Peep; +} namespace OpenRCT2::Network { diff --git a/src/openrct2/paint/Paint.h b/src/openrct2/paint/Paint.h index c40a4b13c8..6f8f239734 100644 --- a/src/openrct2/paint/Paint.h +++ b/src/openrct2/paint/Paint.h @@ -25,12 +25,12 @@ #include #include -struct EntityBase; - enum class ViewportInteractionItem : uint8_t; namespace OpenRCT2 { + struct EntityBase; + struct TileElement; struct SurfaceElement; @@ -64,7 +64,7 @@ struct PaintStruct PaintStruct* Children; PaintStruct* NextQuadrantEntry; OpenRCT2::TileElement* Element; - EntityBase* Entity; + OpenRCT2::EntityBase* Entity; ImageId image_id; ScreenCoordsXY ScreenPos; CoordsXY MapPos; @@ -142,7 +142,7 @@ struct PaintSessionCore PaintStringStruct* LastPSString; AttachedPaintStruct* LastAttachedPS; const OpenRCT2::SurfaceElement* Surface; - EntityBase* CurrentlyDrawnEntity; + OpenRCT2::EntityBase* CurrentlyDrawnEntity; OpenRCT2::TileElement* CurrentlyDrawnTileElement; const OpenRCT2::TileElement* PathElementOnSameHeight; const OpenRCT2::TileElement* TrackElementOnSameHeight; diff --git a/src/openrct2/paint/entity/Paint.Guest.h b/src/openrct2/paint/entity/Paint.Guest.h index 45bc104d53..fb6392b01a 100644 --- a/src/openrct2/paint/entity/Paint.Guest.h +++ b/src/openrct2/paint/entity/Paint.Guest.h @@ -11,13 +11,17 @@ #include +namespace OpenRCT2 +{ + struct Guest; + enum class PeepAnimationType : uint8_t; +} // namespace OpenRCT2 + struct BoundBoxXYZ; -struct Guest; struct PaintSession; -enum class PeepAnimationType : uint8_t; using Direction = uint8_t; -void PaintGuest(PaintSession& session, const Guest& guest, int32_t orientation); +void PaintGuest(PaintSession& session, const OpenRCT2::Guest& guest, int32_t orientation); void PaintGuestAccesories( - PaintSession& session, const Guest& guest, uint8_t imageOffset, PeepAnimationType actionAnimationGroup, + PaintSession& session, const OpenRCT2::Guest& guest, uint8_t imageOffset, OpenRCT2::PeepAnimationType actionAnimationGroup, Direction direction); diff --git a/src/openrct2/paint/entity/Paint.Peep.h b/src/openrct2/paint/entity/Paint.Peep.h index ded61a261c..1a93902ffe 100644 --- a/src/openrct2/paint/entity/Paint.Peep.h +++ b/src/openrct2/paint/entity/Paint.Peep.h @@ -14,9 +14,13 @@ #include -struct Peep; +namespace OpenRCT2 +{ + struct Peep; + enum class PeepAnimationType : uint8_t; +} // namespace OpenRCT2 + using Direction = uint8_t; -enum class PeepAnimationType : uint8_t; constexpr BoundBoxXYZ kPaintPeepBoundBox(int32_t z) { @@ -33,7 +37,7 @@ struct BaseImageAndOffset { ImageIndex baseImageId; uint8_t offset; - PeepAnimationType actionAnimationGroup; + OpenRCT2::PeepAnimationType actionAnimationGroup; }; -BaseImageAndOffset PaintPeepGetBaseImageAndOffset(const Peep& peep, Direction direction); +BaseImageAndOffset PaintPeepGetBaseImageAndOffset(const OpenRCT2::Peep& peep, Direction direction); diff --git a/src/openrct2/paint/entity/Paint.Staff.cpp b/src/openrct2/paint/entity/Paint.Staff.cpp index 408480fb36..29bdfd86a1 100644 --- a/src/openrct2/paint/entity/Paint.Staff.cpp +++ b/src/openrct2/paint/entity/Paint.Staff.cpp @@ -16,6 +16,8 @@ #include "../Paint.h" #include "Paint.Peep.h" +using namespace OpenRCT2; + namespace LightFx = OpenRCT2::Drawing::LightFx; void PaintStaff(PaintSession& session, const Staff& staff, int32_t orientation) diff --git a/src/openrct2/paint/entity/Paint.Staff.h b/src/openrct2/paint/entity/Paint.Staff.h index b1efdb99ee..2397131188 100644 --- a/src/openrct2/paint/entity/Paint.Staff.h +++ b/src/openrct2/paint/entity/Paint.Staff.h @@ -11,8 +11,12 @@ #include -struct PaintSession; -struct Staff; +namespace OpenRCT2 +{ + struct Staff; +} -void PaintStaff(PaintSession& session, const Staff& staff, int32_t orientation); -void PaintStaffLightingEffects(const Staff& staff); +struct PaintSession; + +void PaintStaff(PaintSession& session, const OpenRCT2::Staff& staff, int32_t orientation); +void PaintStaffLightingEffects(const OpenRCT2::Staff& staff); diff --git a/src/openrct2/peep/GuestPathfinding.h b/src/openrct2/peep/GuestPathfinding.h index 781ecaf3db..bffd5819e6 100644 --- a/src/openrct2/peep/GuestPathfinding.h +++ b/src/openrct2/peep/GuestPathfinding.h @@ -14,13 +14,12 @@ #include -struct Peep; -struct Guest; - namespace OpenRCT2 { + struct Guest; + struct Peep; struct TileElement; -} +} // namespace OpenRCT2 namespace OpenRCT2::PathFinding { diff --git a/src/openrct2/peep/PeepAnimations.h b/src/openrct2/peep/PeepAnimations.h index 466f3d14b5..2cf37c8150 100644 --- a/src/openrct2/peep/PeepAnimations.h +++ b/src/openrct2/peep/PeepAnimations.h @@ -18,12 +18,13 @@ #include enum class RCT12PeepAnimationGroup : uint8_t; -enum class StaffType : uint8_t; namespace OpenRCT2 { class PeepAnimationsObject; + enum class StaffType : uint8_t; + enum class AnimationPeepType : uint8_t { guest, diff --git a/src/openrct2/ride/Ride.h b/src/openrct2/ride/Ride.h index 444a92b276..1c06c5a211 100644 --- a/src/openrct2/ride/Ride.h +++ b/src/openrct2/ride/Ride.h @@ -31,14 +31,15 @@ struct IObjectManager; struct Ride; struct RideTypeDescriptor; -struct Guest; -struct Staff; struct Vehicle; struct RideObjectEntry; struct ResultWithMessage; namespace OpenRCT2 { + struct Guest; + struct Staff; + class Formatter; class MusicObject; class StationObject; @@ -483,8 +484,8 @@ public: int32_t getTotalQueueLength() const; int32_t getMaxQueueTime() const; - void queueInsertGuestAtFront(StationIndex stationIndex, Guest* peep); - Guest* getQueueHeadGuest(StationIndex stationIndex) const; + void queueInsertGuestAtFront(StationIndex stationIndex, OpenRCT2::Guest* peep); + OpenRCT2::Guest* getQueueHeadGuest(StationIndex stationIndex) const; void setNameToDefault(); std::string getName() const; @@ -820,14 +821,14 @@ void RideCheckAllReachable(); bool RideTryGetOriginElement(const Ride& ride, CoordsXYE* output); void RideClearBlockedTiles(const Ride& ride); -Staff* RideGetMechanic(const Ride& ride); -Staff* RideGetAssignedMechanic(const Ride& ride); +OpenRCT2::Staff* RideGetMechanic(const Ride& ride); +OpenRCT2::Staff* RideGetAssignedMechanic(const Ride& ride); VehicleColour RideGetVehicleColour(const Ride& ride, int32_t vehicleIndex); int32_t RideGetUnusedPresetVehicleColour(OpenRCT2::ObjectEntryIndex subType); void RideSetVehicleColoursToRandomPreset(Ride& ride, uint8_t preset_index); void RideMeasurementsUpdate(); void RideBreakdownAddNewsItem(const Ride& ride); -Staff* RideFindClosestMechanic(const Ride& ride, int32_t forInspection); +OpenRCT2::Staff* RideFindClosestMechanic(const Ride& ride, int32_t forInspection); int32_t RideInitialiseConstructionWindow(Ride& ride); void RideSetMapTooltip(const OpenRCT2::TileElement& tileElement); void RidePrepareBreakdown(Ride& ride, Breakdown breakdownReason); diff --git a/src/openrct2/ride/RideData.h b/src/openrct2/ride/RideData.h index a36bf46bed..cef3b338d1 100644 --- a/src/openrct2/ride/RideData.h +++ b/src/openrct2/ride/RideData.h @@ -275,9 +275,9 @@ struct UpkeepCostsDescriptor }; using RideTrackGroups = OpenRCT2::BitSet; -using UpdateRideApproachVehicleWaypointsFunction = void (*)(Guest&, const CoordsXY&, int16_t&); +using UpdateRideApproachVehicleWaypointsFunction = void (*)(OpenRCT2::Guest&, const CoordsXY&, int16_t&); using RideMusicUpdateFunction = void (*)(Ride&); -using PeepUpdateRideLeaveEntranceFunc = void (*)(Guest&, Ride&, CoordsXYZD&); +using PeepUpdateRideLeaveEntranceFunc = void (*)(OpenRCT2::Guest&, Ride&, CoordsXYZD&); using StartRideMusicFunction = void (*)(const OpenRCT2::RideAudio::ViewportRideMusicInstance&); using LightFXAddLightsMagicVehicleFunction = void (*)(const Vehicle* vehicle); using RideLocationFunction = CoordsXY (*)(const Vehicle& vehicle, const Ride& ride, const StationIndex& CurrentRideStation); @@ -546,10 +546,10 @@ struct RideTypeDescriptor RideMusicUpdateFunction MusicUpdateFunction = DefaultMusicUpdate; RideClassification Classification = RideClassification::ride; - PeepUpdateRideLeaveEntranceFunc UpdateLeaveEntrance = PeepUpdateRideLeaveEntranceDefault; + PeepUpdateRideLeaveEntranceFunc UpdateLeaveEntrance = OpenRCT2::PeepUpdateRideLeaveEntranceDefault; SpecialElementRatingAdjustmentFunc SpecialElementRatingAdjustment = SpecialTrackElementRatingsAjustment_Default; - RideLocationFunction GetGuestWaypointLocation = GetGuestWaypointLocationDefault; + RideLocationFunction GetGuestWaypointLocation = OpenRCT2::GetGuestWaypointLocationDefault; RideConstructionWindowContext ConstructionWindowContext = RideConstructionWindowContext::Default; RideUpdateFunction RideUpdate = nullptr; @@ -558,7 +558,8 @@ struct RideTypeDescriptor MusicTrackOffsetLengthFunc MusicTrackOffsetLength = OpenRCT2::RideAudio::RideMusicGetTrackOffsetLength_Default; - UpdateRideApproachVehicleWaypointsFunction UpdateRideApproachVehicleWaypoints = UpdateRideApproachVehicleWaypointsDefault; + UpdateRideApproachVehicleWaypointsFunction UpdateRideApproachVehicleWaypoints = OpenRCT2:: + UpdateRideApproachVehicleWaypointsDefault; RtdSpecialType specialType = RtdSpecialType::none; /** @deprecated */ @@ -679,7 +680,7 @@ constexpr RideTypeDescriptor kDummyRTD = .DesignCreateMode = TrackDesignCreateMode::Default, .MusicUpdateFunction = DefaultMusicUpdate, .Classification = RideClassification::ride, - .UpdateLeaveEntrance = PeepUpdateRideLeaveEntranceDefault, + .UpdateLeaveEntrance = OpenRCT2::PeepUpdateRideLeaveEntranceDefault, }; // clang-format on diff --git a/src/openrct2/ride/ShopItem.h b/src/openrct2/ride/ShopItem.h index 581c97b944..b5a0b55920 100644 --- a/src/openrct2/ride/ShopItem.h +++ b/src/openrct2/ride/ShopItem.h @@ -14,7 +14,10 @@ struct Ride; -enum class PeepThoughtType : uint8_t; +namespace OpenRCT2 +{ + enum class PeepThoughtType : uint8_t; +} enum class ShopItem : uint8_t { @@ -96,11 +99,11 @@ struct ShopItemDescriptor uint32_t Image; ShopItemStrings Naming; uint16_t Flags; - Litter::Type Type; + OpenRCT2::Litter::Type Type; uint8_t ConsumptionTime; ShopItem DiscardContainer; - PeepThoughtType TooMuchThought; - PeepThoughtType GoodValueThought; + OpenRCT2::PeepThoughtType TooMuchThought; + OpenRCT2::PeepThoughtType GoodValueThought; constexpr bool HasFlag(const uint16_t flag) const { diff --git a/src/openrct2/ride/Vehicle.h b/src/openrct2/ride/Vehicle.h index 03e2e8d74a..eaa73267d9 100644 --- a/src/openrct2/ride/Vehicle.h +++ b/src/openrct2/ride/Vehicle.h @@ -110,9 +110,9 @@ enum class MiniGolfFlag : uint8_t using MiniGolfFlags = FlagHolder; -struct Vehicle : EntityBase +struct Vehicle : OpenRCT2::EntityBase { - static constexpr auto cEntityType = EntityType::vehicle; + static constexpr auto cEntityType = OpenRCT2::EntityType::vehicle; enum class Type : uint8_t { diff --git a/src/openrct2/scripting/bindings/entity/ScBalloon.hpp b/src/openrct2/scripting/bindings/entity/ScBalloon.hpp index 346237e8f3..aba264aa48 100644 --- a/src/openrct2/scripting/bindings/entity/ScBalloon.hpp +++ b/src/openrct2/scripting/bindings/entity/ScBalloon.hpp @@ -13,7 +13,10 @@ #include "ScEntity.hpp" -struct Balloon; +namespace OpenRCT2 +{ + struct Balloon; +} namespace OpenRCT2::Scripting { diff --git a/src/openrct2/scripting/bindings/entity/ScGuest.hpp b/src/openrct2/scripting/bindings/entity/ScGuest.hpp index 03a7ff0525..810110e9a6 100644 --- a/src/openrct2/scripting/bindings/entity/ScGuest.hpp +++ b/src/openrct2/scripting/bindings/entity/ScGuest.hpp @@ -15,7 +15,10 @@ #include "../../../management/Marketing.h" #include "ScPeep.hpp" -enum class PeepAnimationType : uint8_t; +namespace OpenRCT2 +{ + enum class PeepAnimationType : uint8_t; +} namespace OpenRCT2::Scripting { diff --git a/src/openrct2/scripting/bindings/entity/ScLitter.hpp b/src/openrct2/scripting/bindings/entity/ScLitter.hpp index 70c3dd39ef..732edafbea 100644 --- a/src/openrct2/scripting/bindings/entity/ScLitter.hpp +++ b/src/openrct2/scripting/bindings/entity/ScLitter.hpp @@ -13,7 +13,10 @@ #include "ScEntity.hpp" -struct Litter; +namespace OpenRCT2 +{ + struct Litter; +} namespace OpenRCT2::Scripting { diff --git a/src/openrct2/scripting/bindings/entity/ScMoneyEffect.hpp b/src/openrct2/scripting/bindings/entity/ScMoneyEffect.hpp index 8935b73227..4a37138750 100644 --- a/src/openrct2/scripting/bindings/entity/ScMoneyEffect.hpp +++ b/src/openrct2/scripting/bindings/entity/ScMoneyEffect.hpp @@ -13,7 +13,10 @@ #include "ScEntity.hpp" -struct MoneyEffect; +namespace OpenRCT2 +{ + struct MoneyEffect; +} namespace OpenRCT2::Scripting { diff --git a/src/openrct2/scripting/bindings/entity/ScStaff.hpp b/src/openrct2/scripting/bindings/entity/ScStaff.hpp index 5c86c1b570..26dd1373c5 100644 --- a/src/openrct2/scripting/bindings/entity/ScStaff.hpp +++ b/src/openrct2/scripting/bindings/entity/ScStaff.hpp @@ -15,8 +15,11 @@ #include -enum class PeepAnimationType : uint8_t; -enum class StaffType : uint8_t; +namespace OpenRCT2 +{ + enum class PeepAnimationType : uint8_t; + enum class StaffType : uint8_t; +} // namespace OpenRCT2 namespace OpenRCT2::Scripting { diff --git a/src/openrct2/world/Park.h b/src/openrct2/world/Park.h index fc8062d69a..9d3b71b0f3 100644 --- a/src/openrct2/world/Park.h +++ b/src/openrct2/world/Park.h @@ -12,11 +12,10 @@ #include "../core/Money.hpp" #include "Location.hpp" -struct Guest; - namespace OpenRCT2 { struct GameState_t; + struct Guest; } // namespace OpenRCT2 namespace OpenRCT2::Park