# autoreplace_cmd.cpp

Go to the documentation of this file.

    00001 /* $Id: autoreplace_cmd.cpp 15434 2009-02-09 21:20:05Z rubidium $ */
    00002
    00005 #include "stdafx.h"
    00006 #include "company_func.h"
    00007 #include "vehicle_gui.h"
    00008 #include "train.h"
    00009 #include "rail.h"
    00010 #include "command_func.h"
    00011 #include "engine_base.h"
    00012 #include "engine_func.h"
    00013 #include "vehicle_func.h"
    00014 #include "functions.h"
    00015 #include "autoreplace_func.h"
    00016 #include "articulated_vehicles.h"
    00017 #include "core/alloc_func.hpp"
    00018
    00019 #include "table/strings.h"
    00020
    00027 static bool EnginesGotCargoInCommon(EngineID engine_a, EngineID engine_b, VehicleType type)
    00028 {
    00029   uint32 available_cargos_a = GetUnionOfArticulatedRefitMasks(engine_a, type, true);
    00030   uint32 available_cargos_b = GetUnionOfArticulatedRefitMasks(engine_b, type, true);
    00031   return (available_cargos_a == 0 || available_cargos_b == 0 || (available_cargos_a & available_cargos_b) != 0);
    00032 }
    00033
    00041 bool CheckAutoreplaceValidity(EngineID from, EngineID to, CompanyID company)
    00042 {
    00043   /* First we make sure that it's a valid type the user requested
    00044    * check that it's an engine that is in the engine array */
    00045   if (!IsEngineIndex(from) || !IsEngineIndex(to)) return false;
    00046
    00047   /* we can't replace an engine into itself (that would be autorenew) */
    00048   if (from == to) return false;
    00049
    00050   VehicleType type = GetEngine(from)->type;
    00051
    00052   /* check that the new vehicle type is available to the company and its type is the same as the original one */
    00053   if (!IsEngineBuildable(to, type, company)) return false;
    00054
    00055   switch (type) {
    00056     case VEH_TRAIN: {
    00057       const RailVehicleInfo *rvi_from = RailVehInfo(from);
    00058       const RailVehicleInfo *rvi_to   = RailVehInfo(to);
    00059
    00060       /* make sure the railtypes are compatible */
    00061       if ((GetRailTypeInfo(rvi_from->railtype)->compatible_railtypes & GetRailTypeInfo(rvi_to->railtype)->compatible_railtypes) == 0) return false;
    00062
    00063       /* make sure we do not replace wagons with engines or vise versa */
    00064       if ((rvi_from->railveh_type == RAILVEH_WAGON) != (rvi_to->railveh_type == RAILVEH_WAGON)) return false;
    00065       break;
    00066     }
    00067
    00068     case VEH_ROAD:
    00069       /* make sure that we do not replace a tram with a normal road vehicles or vise versa */
    00070       if (HasBit(EngInfo(from)->misc_flags, EF_ROAD_TRAM) != HasBit(EngInfo(to)->misc_flags, EF_ROAD_TRAM)) return false;
    00071       break;
    00072
    00073     case VEH_AIRCRAFT:
    00074       /* make sure that we do not replace a plane with a helicopter or vise versa */
    00075       if ((AircraftVehInfo(from)->subtype & AIR_CTOL) != (AircraftVehInfo(to)->subtype & AIR_CTOL)) return false;
    00076       break;
    00077
    00078     default: break;
    00079   }
    00080
    00081   /* the engines needs to be able to carry the same cargo */
    00082   return EnginesGotCargoInCommon(from, to, type);
    00083 }
    00084
    00090 static void TransferCargo(Vehicle *old_veh, Vehicle *new_head, bool part_of_chain)
    00091 {
    00092   assert(!part_of_chain || new_head->IsPrimaryVehicle());
    00093   /* Loop through source parts */
    00094   for (Vehicle *src = old_veh; src != NULL; src = src->Next()) {
    00095     if (!part_of_chain && src->type == VEH_TRAIN && src != old_veh && src != old_veh->u.rail.other_multiheaded_part && !IsArticulatedPart(src)) {
    00096       /* Skip vehicles, which do not belong to old_veh */
    00097       src = GetLastEnginePart(src);
    00098       continue;
    00099     }
    00100     if (src->cargo_type >= NUM_CARGO || src->cargo.Count() == 0) continue;
    00101
    00102     /* Find free space in the new chain */
    00103     for (Vehicle *dest = new_head; dest != NULL && src->cargo.Count() > 0; dest = dest->Next()) {
    00104       if (!part_of_chain && dest->type == VEH_TRAIN && dest != new_head && dest != new_head->u.rail.other_multiheaded_part && !IsArticulatedPart(dest)) {
    00105         /* Skip vehicles, which do not belong to new_head */
    00106         dest = GetLastEnginePart(dest);
    00107         continue;
    00108       }
    00109       if (dest->cargo_type != src->cargo_type) continue;
    00110
    00111       uint amount = min(src->cargo.Count(), dest->cargo_cap - dest->cargo.Count());
    00112       if (amount <= 0) continue;
    00113
    00114       src->cargo.MoveTo(&dest->cargo, amount);
    00115     }
    00116   }
    00117
    00118   /* Update train weight etc., the old vehicle will be sold anyway */
    00119   if (part_of_chain && new_head->type == VEH_TRAIN) TrainConsistChanged(new_head, true);
    00120 }
    00121
    00128 static bool VerifyAutoreplaceRefitForOrders(const Vehicle *v, EngineID engine_type)
    00129 {
    00130   const Order *o;
    00131   const Vehicle *u;
    00132
    00133   uint32 union_refit_mask_a = GetUnionOfArticulatedRefitMasks(v->engine_type, v->type, false);
    00134   uint32 union_refit_mask_b = GetUnionOfArticulatedRefitMasks(engine_type, v->type, false);
    00135
    00136   if (v->type == VEH_TRAIN) {
    00137     u = v->First();
    00138   } else {
    00139     u = v;
    00140   }
    00141
    00142   FOR_VEHICLE_ORDERS(u, o) {
    00143     if (!o->IsRefit()) continue;
    00144     CargoID cargo_type = o->GetRefitCargo();
    00145
    00146     if (!HasBit(union_refit_mask_a, cargo_type)) continue;
    00147     if (!HasBit(union_refit_mask_b, cargo_type)) return false;
    00148   }
    00149
    00150   return true;
    00151 }
    00152
    00162 static CargoID GetNewCargoTypeForReplace(Vehicle *v, EngineID engine_type, bool part_of_chain)
    00163 {
    00164   CargoID cargo_type;
    00165
    00166   if (GetUnionOfArticulatedRefitMasks(engine_type, v->type, true) == 0) return CT_NO_REFIT; // Don't try to refit an engine with no cargo capacity
    00167
    00168   if (IsArticulatedVehicleCarryingDifferentCargos(v, &cargo_type)) return CT_INVALID; // We cannot refit to mixed cargos in an automated way
    00169
    00170   uint32 available_cargo_types = GetIntersectionOfArticulatedRefitMasks(engine_type, v->type, true);
    00171
    00172   if (cargo_type == CT_INVALID) {
    00173     if (v->type != VEH_TRAIN) return CT_NO_REFIT; // If the vehicle does not carry anything at all, every replacement is fine.
    00174
    00175     if (!part_of_chain) return CT_NO_REFIT;
    00176
    00177     /* the old engine didn't have cargo capacity, but the new one does
    00178      * now we will figure out what cargo the train is carrying and refit to fit this */
    00179
    00180     for (v = v->First(); v != NULL; v = v->Next()) {
    00181       if (v->cargo_cap == 0) continue;
    00182       /* Now we found a cargo type being carried on the train and we will see if it is possible to carry to this one */
    00183       if (HasBit(available_cargo_types, v->cargo_type)) {
    00184         /* Do we have to refit the vehicle, or is it already carrying the right cargo? */
    00185         uint16 *default_capacity = GetCapacityOfArticulatedParts(engine_type, v->type);
    00186         for (CargoID cid = 0; cid < NUM_CARGO; cid++) {
    00187           if (cid != v->cargo_type && default_capacity[cid] > 0) return v->cargo_type;
    00188         }
    00189
    00190         return CT_NO_REFIT;
    00191       }
    00192     }
    00193
    00194     return CT_NO_REFIT; // We failed to find a cargo type on the old vehicle and we will not refit the new one
    00195   } else {
    00196     if (!HasBit(available_cargo_types, cargo_type)) return CT_INVALID; // We can't refit the vehicle to carry the cargo we want
    00197
    00198     if (part_of_chain && !VerifyAutoreplaceRefitForOrders(v, engine_type)) return CT_INVALID; // Some refit orders lose their effect
    00199
    00200     /* Do we have to refit the vehicle, or is it already carrying the right cargo? */
    00201     uint16 *default_capacity = GetCapacityOfArticulatedParts(engine_type, v->type);
    00202     for (CargoID cid = 0; cid < NUM_CARGO; cid++) {
    00203       if (cid != cargo_type && default_capacity[cid] > 0) return cargo_type;
    00204     }
    00205
    00206     return CT_NO_REFIT;
    00207   }
    00208 }
    00209
    00215 static EngineID GetNewEngineType(const Vehicle *v, const Company *c)
    00216 {
    00217   assert(v->type != VEH_TRAIN || !IsArticulatedPart(v));
    00218
    00219   if (v->type == VEH_TRAIN && IsRearDualheaded(v)) {
    00220     /* we build the rear ends of multiheaded trains with the front ones */
    00221     return INVALID_ENGINE;
    00222   }
    00223
    00224   EngineID e = EngineReplacementForCompany(c, v->engine_type, v->group_id);
    00225
    00226   if (e != INVALID_ENGINE && IsEngineBuildable(e, v->type, _current_company)) {
    00227     return e;
    00228   }
    00229
    00230   if (v->NeedsAutorenewing(c) && // replace if engine is too old
    00231       IsEngineBuildable(v->engine_type, v->type, _current_company)) { // engine can still be build
    00232     return v->engine_type;
    00233   }
    00234
    00235   return INVALID_ENGINE;
    00236 }
    00237
    00245 static CommandCost BuildReplacementVehicle(Vehicle *old_veh, Vehicle **new_vehicle, bool part_of_chain)
    00246 {
    00247   *new_vehicle = NULL;
    00248
    00249   /* Shall the vehicle be replaced? */
    00250   const Company *c = GetCompany(_current_company);
    00251   EngineID e = GetNewEngineType(old_veh, c);
    00252   if (e == INVALID_ENGINE) return CommandCost(); // neither autoreplace is set, nor autorenew is triggered
    00253
    00254   /* Does it need to be refitted */
    00255   CargoID refit_cargo = GetNewCargoTypeForReplace(old_veh, e, part_of_chain);
    00256   if (refit_cargo == CT_INVALID) return CommandCost(); // incompatible cargos
    00257
    00258   /* Build the new vehicle */
    00259   CommandCost cost = DoCommand(old_veh->tile, e, 0, DC_EXEC | DC_AUTOREPLACE, GetCmdBuildVeh(old_veh));
    00260   if (cost.Failed()) return cost;
    00261
    00262   Vehicle *new_veh = GetVehicle(_new_vehicle_id);
    00263   *new_vehicle = new_veh;
    00264
    00265   /* Refit the vehicle if needed */
    00266   if (refit_cargo != CT_NO_REFIT) {
    00267     cost.AddCost(DoCommand(0, new_veh->index, refit_cargo, DC_EXEC, GetCmdRefitVeh(new_veh)));
    00268     assert(cost.Succeeded()); // This should be ensured by GetNewCargoTypeForReplace()
    00269   }
    00270
    00271   /* Try to reverse the vehicle, but do not care if it fails as the new type might not be reversible */
    00272   if (new_veh->type == VEH_TRAIN && HasBit(old_veh->u.rail.flags, VRF_REVERSE_DIRECTION)) {
    00273     DoCommand(0, new_veh->index, true, DC_EXEC, CMD_REVERSE_TRAIN_DIRECTION);
    00274   }
    00275
    00276   return cost;
    00277 }
    00278
    00284 static inline CommandCost StartStopVehicle(const Vehicle *v, bool evaluate_callback)
    00285 {
    00286   return DoCommand(0, v->index, evaluate_callback ? 1 : 0, DC_EXEC | DC_AUTOREPLACE, CMD_START_STOP_VEHICLE);
    00287 }
    00288
    00295 static inline CommandCost MoveVehicle(const Vehicle *v, const Vehicle *after, DoCommandFlag flags, bool whole_chain)
    00296 {
    00297   return DoCommand(0, v->index | (after != NULL ? after->index : INVALID_VEHICLE) << 16, whole_chain ? 1 : 0, flags, CMD_MOVE_RAIL_VEHICLE);
    00298 }
    00299
    00305 static CommandCost CopyHeadSpecificThings(Vehicle *old_head, Vehicle *new_head, DoCommandFlag flags)
    00306 {
    00307   CommandCost cost = CommandCost();
    00308
    00309   /* Share orders */
    00310   if (cost.Succeeded() && old_head != new_head) cost.AddCost(DoCommand(0, (old_head->index << 16) | new_head->index, CO_SHARE, DC_EXEC, CMD_CLONE_ORDER));
    00311
    00312   /* Copy group membership */
    00313   if (cost.Succeeded() && old_head != new_head) cost.AddCost(DoCommand(0, old_head->group_id, new_head->index, DC_EXEC, CMD_ADD_VEHICLE_GROUP));
    00314
    00315   /* Perform start/stop check whether the new vehicle suits newgrf restrictions etc. */
    00316   if (cost.Succeeded()) {
    00317     /* Start the vehicle, might be denied by certain things */
    00318     assert((new_head->vehstatus & VS_STOPPED) != 0);
    00319     cost.AddCost(StartStopVehicle(new_head, true));
    00320
    00321     /* Stop the vehicle again, but do not care about evil newgrfs allowing starting but not stopping :p */
    00322     if (cost.Succeeded()) cost.AddCost(StartStopVehicle(new_head, false));
    00323   }
    00324
    00325   /* Last do those things which do never fail (resp. we do not care about), but which are not undo-able */
    00326   if (cost.Succeeded() && old_head != new_head && (flags & DC_EXEC) != 0) {
    00327     /* Copy vehicle name */
    00328     if (old_head->name != NULL) {
    00329       DoCommand(0, new_head->index, 0, DC_EXEC | DC_AUTOREPLACE, CMD_RENAME_VEHICLE, old_head->name);
    00330     }
    00331
    00332     /* Copy other things which cannot be copied by a command and which shall not stay resetted from the build vehicle command */
    00333     new_head->CopyVehicleConfigAndStatistics(old_head);
    00334
    00335     /* Switch vehicle windows to the new vehicle, so they are not closed when the old vehicle is sold */
    00336     ChangeVehicleViewWindow(old_head->index, new_head->index);
    00337   }
    00338
    00339   return cost;
    00340 }
    00341
    00349 static CommandCost ReplaceFreeUnit(Vehicle **single_unit, DoCommandFlag flags, bool *nothing_to_do)
    00350 {
    00351   Vehicle *old_v = *single_unit;
    00352   assert(old_v->type == VEH_TRAIN && !IsArticulatedPart(old_v) && !IsRearDualheaded(old_v));
    00353
    00354   CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES, 0);
    00355
    00356   /* Build and refit replacement vehicle */
    00357   Vehicle *new_v = NULL;
    00358   cost.AddCost(BuildReplacementVehicle(old_v, &new_v, false));
    00359
    00360   /* Was a new vehicle constructed? */
    00361   if (cost.Succeeded() && new_v != NULL) {
    00362     *nothing_to_do = false;
    00363
    00364     if ((flags & DC_EXEC) != 0) {
    00365       /* Move the new vehicle behind the old */
    00366       MoveVehicle(new_v, old_v, DC_EXEC, false);
    00367
    00368       /* Take over cargo
    00369        * Note: We do only transfer cargo from the old to the new vehicle.
    00370        *       I.e. we do not transfer remaining cargo to other vehicles.
    00371        *       Else you would also need to consider moving cargo to other free chains,
    00372        *       or doing the same in ReplaceChain(), which would be quite troublesome.
    00373        */
    00374       TransferCargo(old_v, new_v, false);
    00375
    00376       *single_unit = new_v;
    00377     }
    00378
    00379     /* Sell the old vehicle */
    00380     cost.AddCost(DoCommand(0, old_v->index, 0, flags, GetCmdSellVeh(old_v)));
    00381
    00382     /* If we are not in DC_EXEC undo everything */
    00383     if ((flags & DC_EXEC) == 0) {
    00384       DoCommand(0, new_v->index, 0, DC_EXEC, GetCmdSellVeh(new_v));
    00385     }
    00386   }
    00387
    00388   return cost;
    00389 }
    00390
    00398 static CommandCost ReplaceChain(Vehicle **chain, DoCommandFlag flags, bool wagon_removal, bool *nothing_to_do)
    00399 {
    00400   Vehicle *old_head = *chain;
    00401   assert(old_head->IsPrimaryVehicle());
    00402
    00403   CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES, 0);
    00404
    00405   if (old_head->type == VEH_TRAIN) {
    00406     /* Store the length of the old vehicle chain, rounded up to whole tiles */
    00407     uint16 old_total_length = (old_head->u.rail.cached_total_length + TILE_SIZE - 1) / TILE_SIZE * TILE_SIZE;
    00408
    00409     int num_units = 0;
    00410     for (Vehicle *w = old_head; w != NULL; w = GetNextUnit(w)) num_units++;
    00411
    00412     Vehicle **old_vehs = CallocT<Vehicle *>(num_units);
    00413     Vehicle **new_vehs = CallocT<Vehicle *>(num_units);
    00414     Money *new_costs = MallocT<Money>(num_units);
    00415
    00416     /* Collect vehicles and build replacements
    00417      * Note: The replacement vehicles can only successfully build as long as the old vehicles are still in their chain */
    00418     int i;
    00419     Vehicle *w;
    00420     for (w = old_head, i = 0; w != NULL; w = GetNextUnit(w), i++) {
    00421       assert(i < num_units);
    00422       old_vehs[i] = w;
    00423
    00424       CommandCost ret = BuildReplacementVehicle(old_vehs[i], &new_vehs[i], true);
    00425       cost.AddCost(ret);
    00426       if (cost.Failed()) break;
    00427
    00428       new_costs[i] = ret.GetCost();
    00429       if (new_vehs[i] != NULL) *nothing_to_do = false;
    00430     }
    00431     Vehicle *new_head = (new_vehs[0] != NULL ? new_vehs[0] : old_vehs[0]);
    00432
    00433     /* Note: When autoreplace has already failed here, old_vehs[] is not completely initialized. But it is also not needed. */
    00434     if (cost.Succeeded()) {
    00435       /* Separate the head, so we can start constructing the new chain */
    00436       Vehicle *second = GetNextUnit(old_head);
    00437       if (second != NULL) cost.AddCost(MoveVehicle(second, NULL, DC_EXEC | DC_AUTOREPLACE, true));
    00438
    00439       assert(GetNextUnit(new_head) == NULL);
    00440
    00441       /* Append engines to the new chain
    00442        * We do this from back to front, so that the head of the temporary vehicle chain does not change all the time.
    00443        * OTOH the vehicle attach callback is more expensive this way :s */
    00444       Vehicle *last_engine = NULL;
    00445       if (cost.Succeeded()) {
    00446         for (int i = num_units - 1; i > 0; i--) {
    00447           Vehicle *append = (new_vehs[i] != NULL ? new_vehs[i] : old_vehs[i]);
    00448
    00449           if (RailVehInfo(append->engine_type)->railveh_type == RAILVEH_WAGON) continue;
    00450
    00451           if (last_engine == NULL) last_engine = append;
    00452           cost.AddCost(MoveVehicle(append, new_head, DC_EXEC, false));
    00453           if (cost.Failed()) break;
    00454         }
    00455         if (last_engine == NULL) last_engine = new_head;
    00456       }
    00457
    00458       /* When wagon removal is enabled and the new engines without any wagons are already longer than the old, we have to fail */
    00459       if (cost.Succeeded() && wagon_removal && new_head->u.rail.cached_total_length > old_total_length) cost = CommandCost(STR_TRAIN_TOO_LONG_AFTER_REPLACEMENT);
    00460
    00461       /* Append/insert wagons into the new vehicle chain
    00462        * We do this from back to front, so we can stop when wagon removal or maximum train length (i.e. from mammoth-train setting) is triggered.
    00463        */
    00464       if (cost.Succeeded()) {
    00465         for (int i = num_units - 1; i > 0; i--) {
    00466           assert(last_engine != NULL);
    00467           Vehicle *append = (new_vehs[i] != NULL ? new_vehs[i] : old_vehs[i]);
    00468
    00469           if (RailVehInfo(append->engine_type)->railveh_type == RAILVEH_WAGON) {
    00470             /* Insert wagon after 'last_engine' */
    00471             CommandCost res = MoveVehicle(append, last_engine, DC_EXEC, false);
    00472
    00473             if (res.Succeeded() && wagon_removal && new_head->u.rail.cached_total_length > old_total_length) {
    00474               MoveVehicle(append, NULL, DC_EXEC | DC_AUTOREPLACE, false);
    00475               break;
    00476             }
    00477
    00478             cost.AddCost(res);
    00479             if (cost.Failed()) break;
    00480           } else {
    00481             /* We have reached 'last_engine', continue with the next engine towards the front */
    00482             assert(append == last_engine);
    00483             last_engine = GetPrevUnit(last_engine);
    00484           }
    00485         }
    00486       }
    00487
    00488       /* Sell superfluous new vehicles that could not be inserted. */
    00489       if (cost.Succeeded() && wagon_removal) {
    00490         for (int i = 1; i < num_units; i++) {
    00491           Vehicle *wagon = new_vehs[i];
    00492           if (wagon == NULL) continue;
    00493           if (wagon->First() == new_head) break;
    00494
    00495           assert(RailVehInfo(wagon->engine_type)->railveh_type == RAILVEH_WAGON);
    00496
    00497           /* Sell wagon */
    00498           CommandCost ret = DoCommand(0, wagon->index, 0, DC_EXEC, GetCmdSellVeh(wagon));
    00499           assert(ret.Succeeded());
    00500           new_vehs[i] = NULL;
    00501
    00502           /* Revert the money subtraction when the vehicle was built.
    00503            * This value is different from the sell value, esp. because of refitting */
    00504           cost.AddCost(-new_costs[i]);
    00505         }
    00506       }
    00507
    00508       /* The new vehicle chain is constructed, now take over orders and everything... */
    00509       if (cost.Succeeded()) cost.AddCost(CopyHeadSpecificThings(old_head, new_head, flags));
    00510
    00511       if (cost.Succeeded()) {
    00512         /* Success ! */
    00513         if ((flags & DC_EXEC) != 0 && new_head != old_head) {
    00514           *chain = new_head;
    00515         }
    00516
    00517         /* Transfer cargo of old vehicles and sell them*/
    00518         for (int i = 0; i < num_units; i++) {
    00519           Vehicle *w = old_vehs[i];
    00520           /* Is the vehicle again part of the new chain?
    00521            * Note: We cannot test 'new_vehs[i] != NULL' as wagon removal might cause to remove both */
    00522           if (w->First() == new_head) continue;
    00523
    00524           if ((flags & DC_EXEC) != 0) TransferCargo(w, new_head, true);
    00525
    00526           cost.AddCost(DoCommand(0, w->index, 0, flags, GetCmdSellVeh(w)));
    00527           if ((flags & DC_EXEC) != 0) {
    00528             old_vehs[i] = NULL;
    00529             if (i == 0) old_head = NULL;
    00530           }
    00531         }
    00532       }
    00533
    00534       /* If we are not in DC_EXEC undo everything, i.e. rearrange old vehicles.
    00535        * We do this from back to front, so that the head of the temporary vehicle chain does not change all the time.
    00536        * Note: The vehicle attach callback is disabled here :) */
    00537       if ((flags & DC_EXEC) == 0) {
    00538         /* Separate the head, so we can reattach the old vehicles */
    00539         Vehicle *second = GetNextUnit(old_head);
    00540         if (second != NULL) MoveVehicle(second, NULL, DC_EXEC | DC_AUTOREPLACE, true);
    00541
    00542         assert(GetNextUnit(old_head) == NULL);
    00543
    00544         for (int i = num_units - 1; i > 0; i--) {
    00545           CommandCost ret = MoveVehicle(old_vehs[i], old_head, DC_EXEC | DC_AUTOREPLACE, false);
    00546           assert(ret.Succeeded());
    00547         }
    00548       }
    00549     }
    00550
    00551     /* Finally undo buying of new vehicles */
    00552     if ((flags & DC_EXEC) == 0) {
    00553       for (int i = num_units - 1; i >= 0; i--) {
    00554         if (new_vehs[i] != NULL) {
    00555           DoCommand(0, new_vehs[i]->index, 0, DC_EXEC, GetCmdSellVeh(new_vehs[i]));
    00556           new_vehs[i] = NULL;
    00557         }
    00558       }
    00559     }
    00560
    00561     free(old_vehs);
    00562     free(new_vehs);
    00563     free(new_costs);
    00564   } else {
    00565     /* Build and refit replacement vehicle */
    00566     Vehicle *new_head = NULL;
    00567     cost.AddCost(BuildReplacementVehicle(old_head, &new_head, true));
    00568
    00569     /* Was a new vehicle constructed? */
    00570     if (cost.Succeeded() && new_head != NULL) {
    00571       *nothing_to_do = false;
    00572
    00573       /* The new vehicle is constructed, now take over orders and everything... */
    00574       cost.AddCost(CopyHeadSpecificThings(old_head, new_head, flags));
    00575
    00576       if (cost.Succeeded()) {
    00577         /* The new vehicle is constructed, now take over cargo */
    00578         if ((flags & DC_EXEC) != 0) {
    00579           TransferCargo(old_head, new_head, true);
    00580           *chain = new_head;
    00581         }
    00582
    00583         /* Sell the old vehicle */
    00584         cost.AddCost(DoCommand(0, old_head->index, 0, flags, GetCmdSellVeh(old_head)));
    00585       }
    00586
    00587       /* If we are not in DC_EXEC undo everything */
    00588       if ((flags & DC_EXEC) == 0) {
    00589         DoCommand(0, new_head->index, 0, DC_EXEC, GetCmdSellVeh(new_head));
    00590       }
    00591     }
    00592   }
    00593
    00594   return cost;
    00595 }
    00596
    00604 CommandCost CmdAutoreplaceVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00605 {
    00606   CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES, 0);
    00607   bool nothing_to_do = true;
    00608
    00609   if (!IsValidVehicleID(p1)) return CMD_ERROR;
    00610   Vehicle *v = GetVehicle(p1);
    00611   if (!CheckOwnership(v->owner)) return CMD_ERROR;
    00612   if (!v->IsInDepot()) return CMD_ERROR;
    00613   if (HASBITS(v->vehstatus, VS_CRASHED)) return CMD_ERROR;
    00614
    00615   bool free_wagon = false;
    00616   if (v->type == VEH_TRAIN) {
    00617     if (IsArticulatedPart(v) || IsRearDualheaded(v)) return CMD_ERROR;
    00618     free_wagon = !IsFrontEngine(v);
    00619     if (free_wagon && IsFrontEngine(v->First())) return CMD_ERROR;
    00620   } else {
    00621     if (!v->IsPrimaryVehicle()) return CMD_ERROR;
    00622   }
    00623
    00624   const Company *c = GetCompany(_current_company);
    00625   bool wagon_removal = c->renew_keep_length;
    00626
    00627   /* Test whether any replacement is set, before issuing a whole lot of commands that would end in nothing changed */
    00628   Vehicle *w = v;
    00629   bool any_replacements = false;
    00630   while (w != NULL && !any_replacements) {
    00631     any_replacements = (GetNewEngineType(w, c) != INVALID_ENGINE);
    00632     w = (!free_wagon && w->type == VEH_TRAIN ? GetNextUnit(w) : NULL);
    00633   }
    00634
    00635   if (any_replacements) {
    00636     bool was_stopped = free_wagon || ((v->vehstatus & VS_STOPPED) != 0);
    00637
    00638     /* Stop the vehicle */
    00639     if (!was_stopped) cost.AddCost(StartStopVehicle(v, true));
    00640     if (cost.Failed()) return cost;
    00641
    00642     assert(v->IsStoppedInDepot());
    00643
    00644     /* We have to construct the new vehicle chain to test whether it is valid.
    00645      * Vehicle construction needs random bits, so we have to save the random seeds
    00646      * to prevent desyncs and to replay newgrf callbacks during DC_EXEC */
    00647     SavedRandomSeeds saved_seeds;
    00648     SaveRandomSeeds(&saved_seeds);
    00649     if (free_wagon) {
    00650       cost.AddCost(ReplaceFreeUnit(&v, flags & ~DC_EXEC, &nothing_to_do));
    00651     } else {
    00652       cost.AddCost(ReplaceChain(&v, flags & ~DC_EXEC, wagon_removal, &nothing_to_do));
    00653     }
    00654     RestoreRandomSeeds(saved_seeds);
    00655
    00656     if (cost.Succeeded() && (flags & DC_EXEC) != 0) {
    00657       CommandCost ret;
    00658       if (free_wagon) {
    00659         ret = ReplaceFreeUnit(&v, flags, &nothing_to_do);
    00660       } else {
    00661         ret = ReplaceChain(&v, flags, wagon_removal, &nothing_to_do);
    00662       }
    00663       assert(ret.Succeeded() && ret.GetCost() == cost.GetCost());
    00664     }
    00665
    00666     /* Restart the vehicle */
    00667     if (!was_stopped) cost.AddCost(StartStopVehicle(v, false));
    00668   }
    00669
    00670   if (cost.Succeeded() && nothing_to_do) cost = CommandCost(STR_AUTOREPLACE_NOTHING_TO_DO);
    00671   return cost;
    00672 }