From 4cb3b10f5577b16c7f39a339c2b194c848efc532 Mon Sep 17 00:00:00 2001 From: Jonathan G Rennison Date: Thu, 27 Jun 2024 22:00:27 +0100 Subject: [PATCH] Add vehicle function to get first vehicle in tile hash for tile --- src/vehicle.cpp | 19 +++++++++++++++++++ src/vehicle_base.h | 12 ++++++++++++ src/vehicle_func.h | 2 ++ 3 files changed, 33 insertions(+) diff --git a/src/vehicle.cpp b/src/vehicle.cpp index b64687022b..008687b121 100644 --- a/src/vehicle.cpp +++ b/src/vehicle.cpp @@ -581,6 +581,25 @@ Vehicle *VehicleFromPos(TileIndex tile, VehicleType type, void *data, VehicleFro return nullptr; } +/** + * Returns the first vehicle on a specific location, this should be iterated using Vehicle::HashTileNext. + * @note Use #GetFirstVehicleOnPos when you have the intention that all vehicles should be iterated over using Vehicle::HashTileNext. The iteration order is non-deterministic. + * @param tile The location on the map + * @param type The vehicle type + * @return First vehicle or nullptr. + */ +Vehicle *GetFirstVehicleOnPos(TileIndex tile, VehicleType type) +{ + VehicleTypeTileHash &vhash = _vehicle_tile_hashes[type]; + + auto iter = vhash.find(tile); + if (iter != vhash.end()) { + return Vehicle::Get(iter->second); + } else { + return nullptr; + } +} + /** * Callback that returns 'real' vehicles lower or at height \c *(int*)data . * @param v Vehicle to examine. diff --git a/src/vehicle_base.h b/src/vehicle_base.h index 9c3b3a69ea..b0fe4bfb46 100644 --- a/src/vehicle_base.h +++ b/src/vehicle_base.h @@ -793,6 +793,12 @@ public: return v; } + /** + * Get the next vehicle in the tile hash chain. + * @return the next vehicle in the tile hash chain or nullptr when there isn't a next vehicle. + */ + inline Vehicle *HashTileNext() const { return this->hash_tile_next; } + /** * Get the vehicle at offset \a n of this vehicle chain. * @param n Offset from the current vehicle. @@ -1495,6 +1501,12 @@ struct SpecializedVehicle : public Vehicle { */ inline T *GetPrevVehicle() const { return (T *)this->Vehicle::GetPrevVehicle(); } + /** + * Get the next vehicle in the tile hash chain. + * @return the next vehicle in the tile hash chain or nullptr when there isn't a next vehicle. + */ + inline T *HashTileNext() const { return (T *)this->Vehicle::HashTileNext(); } + /** * Tests whether given index is a valid index for vehicle of this type * @param index tested index diff --git a/src/vehicle_func.h b/src/vehicle_func.h index a4d2262ec2..c85300555e 100644 --- a/src/vehicle_func.h +++ b/src/vehicle_func.h @@ -82,6 +82,8 @@ inline bool HasVehicleOnPos(TileIndex tile, VehicleType type, void *data, Vehicl return VehicleFromPos(tile, type, data, proc, true) != nullptr; } +Vehicle *GetFirstVehicleOnPos(TileIndex tile, VehicleType type); + /** * Find a vehicle from a specific location. It will call proc for ALL vehicles * on the tile and YOU must make SURE that the "best one" is stored in the