autoreplace_cmd.cpp

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

Generated on Fri Nov 21 19:01:31 2008 for openttd by  doxygen 1.5.6