From 55ec676391ffb154f05e7c9736d610153d87cf61 Mon Sep 17 00:00:00 2001 From: SamuXarick <43006711+SamuXarick@users.noreply.github.com> Date: Fri, 16 May 2025 18:04:10 +0100 Subject: [PATCH] Codechange: Iterate with VehiclesOnTile when connecting free wagon chains --- src/train_cmd.cpp | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/src/train_cmd.cpp b/src/train_cmd.cpp index cacc922ddf..31982124fa 100644 --- a/src/train_cmd.cpp +++ b/src/train_cmd.cpp @@ -672,15 +672,22 @@ static CommandCost CmdBuildRailWagon(DoCommandFlags flags, TileIndex tile, const CheckConsistencyOfArticulatedVehicle(v); /* Try to connect the vehicle to one of free chains of wagons. */ - for (Train *w : Train::Iterate()) { - if (w->tile == tile && ///< Same depot - w->IsFreeWagon() && ///< A free wagon chain + std::vector freewagons; + for (Vehicle *u : VehiclesOnTile(tile)) { + if (u->type != VEH_TRAIN) continue; + + Train *w = Train::From(u); + if (w->IsFreeWagon() && ///< A free wagon chain w->engine_type == e->index && ///< Same type w->First() != v && ///< Don't connect to ourself !w->vehstatus.Test(VehState::Crashed)) { ///< Not crashed/flooded - if (Command::Do(DoCommandFlag::Execute, v->index, w->Last()->index, true).Succeeded()) { - break; - } + freewagons.push_back(w->Last()->index); + } + } + std::ranges::sort(freewagons); + for (VehicleID veh_id : freewagons) { + if (Command::Do(DoCommandFlag::Execute, v->index, veh_id, true).Succeeded()) { + break; } } }